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.
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.
11 //! The various pretty print routines.
13 pub use self::UserIdentifiedItem::*;
14 pub use self::PpSourceMode::*;
15 pub use self::PpMode::*;
16 use self::NodesMatchingUII::*;
18 use rustc_trans::back::link;
22 use rustc::middle::ty;
23 use rustc::middle::cfg;
24 use rustc::middle::cfg::graphviz::LabelledCFG;
25 use rustc::session::Session;
26 use rustc::session::config::Input;
27 use rustc_borrowck as borrowck;
28 use rustc_borrowck::graphviz as borrowck_dot;
29 use rustc_resolve as resolve;
33 use syntax::fold::{self, Folder};
34 use syntax::print::{pp, pprust};
36 use syntax::util::small_vector::SmallVector;
41 use std::io::{self, Write};
43 use std::path::PathBuf;
44 use std::str::FromStr;
46 use rustc::front::map as hir_map;
47 use rustc::front::map::{blocks, NodePrinter};
49 use rustc_front::lowering::lower_crate;
50 use rustc_front::print::pprust as pprust_hir;
52 #[derive(Copy, Clone, PartialEq, Debug)]
53 pub enum PpSourceMode {
58 PpmExpandedIdentified,
63 #[derive(Copy, Clone, PartialEq, Debug)]
64 pub enum PpFlowGraphMode {
66 /// Drops the labels from the edges in the flowgraph output. This
67 /// is mostly for use in the --unpretty flowgraph run-make tests,
68 /// since the labels are largely uninteresting in those cases and
69 /// have become a pain to maintain.
72 #[derive(Copy, Clone, PartialEq, Debug)]
74 PpmSource(PpSourceMode),
76 PpmFlowGraph(PpFlowGraphMode),
79 pub fn parse_pretty(sess: &Session,
81 extended: bool) -> (PpMode, Option<UserIdentifiedItem>) {
82 let mut split = name.splitn(2, '=');
83 let first = split.next().unwrap();
84 let opt_second = split.next();
85 let first = match (first, extended) {
86 ("normal", _) => PpmSource(PpmNormal),
87 ("identified", _) => PpmSource(PpmIdentified),
88 ("everybody_loops", true) => PpmSource(PpmEveryBodyLoops),
89 ("expanded", _) => PpmSource(PpmExpanded),
90 ("expanded,identified", _) => PpmSource(PpmExpandedIdentified),
91 ("expanded,hygiene", _) => PpmSource(PpmExpandedHygiene),
92 ("hir", true) => PpmHir(PpmNormal),
93 ("hir,identified", true) => PpmHir(PpmExpandedIdentified),
94 ("hir,typed", true) => PpmHir(PpmTyped),
95 ("flowgraph", true) => PpmFlowGraph(PpFlowGraphMode::Default),
96 ("flowgraph,unlabelled", true) => PpmFlowGraph(PpFlowGraphMode::UnlabelledEdges),
100 "argument to `unpretty` must be one of `normal`, \
101 `expanded`, `flowgraph[,unlabelled]=<nodeid>`, `identified`, \
102 `expanded,identified`, `everybody_loops`, `hir`, \
103 `hir,identified`, or `hir,typed`; got {}", name));
106 "argument to `pretty` must be one of `normal`, `expanded`, \
107 `identified`, or `expanded,identified`; got {}", name));
111 let opt_second = opt_second.and_then(|s| s.parse::<UserIdentifiedItem>().ok());
117 // This slightly awkward construction is to allow for each PpMode to
118 // choose whether it needs to do analyses (which can consume the
119 // Session) and then pass through the session (now attached to the
120 // analysis results) on to the chosen pretty-printer, along with the
123 // Note that since the `&PrinterSupport` is freshly constructed on each
124 // call, it would not make sense to try to attach the lifetime of `self`
125 // to the lifetime of the `&PrinterObject`.
127 // (The `use_once_payload` is working around the current lack of once
128 // functions in the compiler.)
131 /// Constructs a `PrinterSupport` object and passes it to `f`.
132 fn call_with_pp_support<'tcx, A, B, F>(&self,
134 ast_map: Option<hir_map::Map<'tcx>>,
137 F: FnOnce(&PrinterSupport, B) -> A,
140 PpmNormal | PpmEveryBodyLoops | PpmExpanded => {
141 let annotation = NoAnn { sess: sess, ast_map: ast_map };
142 f(&annotation, payload)
145 PpmIdentified | PpmExpandedIdentified => {
146 let annotation = IdentifiedAnnotation { sess: sess, ast_map: ast_map };
147 f(&annotation, payload)
149 PpmExpandedHygiene => {
150 let annotation = HygieneAnnotation { sess: sess, ast_map: ast_map };
151 f(&annotation, payload)
153 _ => panic!("Should use call_with_pp_support_hir"),
156 fn call_with_pp_support_hir<'tcx, A, B, F>(&self,
158 ast_map: &hir_map::Map<'tcx>,
159 ast_crate: &ast::Crate,
160 arenas: &'tcx ty::CtxtArenas<'tcx>,
164 F: FnOnce(&HirPrinterSupport, B, &hir::Crate) -> A,
168 let annotation = NoAnn { sess: sess, ast_map: Some(ast_map.clone()) };
169 f(&annotation, payload, &ast_map.forest.krate)
173 let annotation = IdentifiedAnnotation {
175 ast_map: Some(ast_map.clone())
177 f(&annotation, payload, &ast_map.forest.krate)
180 driver::phase_3_run_analysis_passes(sess,
185 resolve::MakeGlobMap::No,
187 let annotation = TypedAnnotation { tcx: tcx };
188 f(&annotation, payload, &ast_map.forest.krate)
191 _ => panic!("Should use call_with_pp_support"),
196 trait PrinterSupport<'ast>: pprust::PpAnn {
197 /// Provides a uniform interface for re-extracting a reference to a
198 /// `Session` from a value that now owns it.
199 fn sess<'a>(&'a self) -> &'a Session;
201 /// Provides a uniform interface for re-extracting a reference to an
202 /// `hir_map::Map` from a value that now owns it.
203 fn ast_map<'a>(&'a self) -> Option<&'a hir_map::Map<'ast>>;
205 /// Produces the pretty-print annotation object.
207 /// (Rust does not yet support upcasting from a trait object to
208 /// an object for one of its super-traits.)
209 fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn;
212 trait HirPrinterSupport<'ast>: pprust_hir::PpAnn {
213 /// Provides a uniform interface for re-extracting a reference to a
214 /// `Session` from a value that now owns it.
215 fn sess<'a>(&'a self) -> &'a Session;
217 /// Provides a uniform interface for re-extracting a reference to an
218 /// `hir_map::Map` from a value that now owns it.
219 fn ast_map<'a>(&'a self) -> Option<&'a hir_map::Map<'ast>>;
221 /// Produces the pretty-print annotation object.
223 /// (Rust does not yet support upcasting from a trait object to
224 /// an object for one of its super-traits.)
225 fn pp_ann<'a>(&'a self) -> &'a pprust_hir::PpAnn;
230 ast_map: Option<hir_map::Map<'ast>>
233 impl<'ast> PrinterSupport<'ast> for NoAnn<'ast> {
234 fn sess<'a>(&'a self) -> &'a Session { &self.sess }
236 fn ast_map<'a>(&'a self) -> Option<&'a hir_map::Map<'ast>> {
237 self.ast_map.as_ref()
240 fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn { self }
243 impl<'ast> HirPrinterSupport<'ast> for NoAnn<'ast> {
244 fn sess<'a>(&'a self) -> &'a Session { &self.sess }
246 fn ast_map<'a>(&'a self) -> Option<&'a hir_map::Map<'ast>> {
247 self.ast_map.as_ref()
250 fn pp_ann<'a>(&'a self) -> &'a pprust_hir::PpAnn { self }
253 impl<'ast> pprust::PpAnn for NoAnn<'ast> {}
254 impl<'ast> pprust_hir::PpAnn for NoAnn<'ast> {}
256 struct IdentifiedAnnotation<'ast> {
258 ast_map: Option<hir_map::Map<'ast>>,
261 impl<'ast> PrinterSupport<'ast> for IdentifiedAnnotation<'ast> {
262 fn sess<'a>(&'a self) -> &'a Session { &self.sess }
264 fn ast_map<'a>(&'a self) -> Option<&'a hir_map::Map<'ast>> {
265 self.ast_map.as_ref()
268 fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn { self }
271 impl<'ast> pprust::PpAnn for IdentifiedAnnotation<'ast> {
273 s: &mut pprust::State,
274 node: pprust::AnnNode) -> io::Result<()> {
276 pprust::NodeExpr(_) => s.popen(),
281 s: &mut pprust::State,
282 node: pprust::AnnNode) -> io::Result<()> {
284 pprust::NodeIdent(_) | pprust::NodeName(_) => Ok(()),
286 pprust::NodeItem(item) => {
287 try!(pp::space(&mut s.s));
288 s.synth_comment(item.id.to_string())
290 pprust::NodeSubItem(id) => {
291 try!(pp::space(&mut s.s));
292 s.synth_comment(id.to_string())
294 pprust::NodeBlock(blk) => {
295 try!(pp::space(&mut s.s));
296 s.synth_comment(format!("block {}", blk.id))
298 pprust::NodeExpr(expr) => {
299 try!(pp::space(&mut s.s));
300 try!(s.synth_comment(expr.id.to_string()));
303 pprust::NodePat(pat) => {
304 try!(pp::space(&mut s.s));
305 s.synth_comment(format!("pat {}", pat.id))
311 impl<'ast> HirPrinterSupport<'ast> for IdentifiedAnnotation<'ast> {
312 fn sess<'a>(&'a self) -> &'a Session { &self.sess }
314 fn ast_map<'a>(&'a self) -> Option<&'a hir_map::Map<'ast>> {
315 self.ast_map.as_ref()
318 fn pp_ann<'a>(&'a self) -> &'a pprust_hir::PpAnn { self }
321 impl<'ast> pprust_hir::PpAnn for IdentifiedAnnotation<'ast> {
323 s: &mut pprust_hir::State,
324 node: pprust_hir::AnnNode) -> io::Result<()> {
326 pprust_hir::NodeExpr(_) => s.popen(),
331 s: &mut pprust_hir::State,
332 node: pprust_hir::AnnNode) -> io::Result<()> {
334 pprust_hir::NodeIdent(_) | pprust_hir::NodeName(_) => Ok(()),
336 pprust_hir::NodeItem(item) => {
337 try!(pp::space(&mut s.s));
338 s.synth_comment(item.id.to_string())
340 pprust_hir::NodeSubItem(id) => {
341 try!(pp::space(&mut s.s));
342 s.synth_comment(id.to_string())
344 pprust_hir::NodeBlock(blk) => {
345 try!(pp::space(&mut s.s));
346 s.synth_comment(format!("block {}", blk.id))
348 pprust_hir::NodeExpr(expr) => {
349 try!(pp::space(&mut s.s));
350 try!(s.synth_comment(expr.id.to_string()));
353 pprust_hir::NodePat(pat) => {
354 try!(pp::space(&mut s.s));
355 s.synth_comment(format!("pat {}", pat.id))
361 struct HygieneAnnotation<'ast> {
363 ast_map: Option<hir_map::Map<'ast>>,
366 impl<'ast> PrinterSupport<'ast> for HygieneAnnotation<'ast> {
367 fn sess<'a>(&'a self) -> &'a Session { &self.sess }
369 fn ast_map<'a>(&'a self) -> Option<&'a hir_map::Map<'ast>> {
370 self.ast_map.as_ref()
373 fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn { self }
376 impl<'ast> pprust::PpAnn for HygieneAnnotation<'ast> {
378 s: &mut pprust::State,
379 node: pprust::AnnNode) -> io::Result<()> {
381 pprust::NodeIdent(&ast::Ident { name: ast::Name(nm), ctxt }) => {
382 try!(pp::space(&mut s.s));
383 // FIXME #16420: this doesn't display the connections
384 // between syntax contexts
385 s.synth_comment(format!("{}#{}", nm, ctxt))
387 pprust::NodeName(&ast::Name(nm)) => {
388 try!(pp::space(&mut s.s));
389 s.synth_comment(nm.to_string())
397 struct TypedAnnotation<'a, 'tcx: 'a> {
398 tcx: &'a ty::ctxt<'tcx>,
401 impl<'b, 'tcx> HirPrinterSupport<'tcx> for TypedAnnotation<'b, 'tcx> {
402 fn sess<'a>(&'a self) -> &'a Session { &self.tcx.sess }
404 fn ast_map<'a>(&'a self) -> Option<&'a hir_map::Map<'tcx>> {
408 fn pp_ann<'a>(&'a self) -> &'a pprust_hir::PpAnn { self }
411 impl<'a, 'tcx> pprust_hir::PpAnn for TypedAnnotation<'a, 'tcx> {
413 s: &mut pprust_hir::State,
414 node: pprust_hir::AnnNode) -> io::Result<()> {
416 pprust_hir::NodeExpr(_) => s.popen(),
421 s: &mut pprust_hir::State,
422 node: pprust_hir::AnnNode) -> io::Result<()> {
424 pprust_hir::NodeExpr(expr) => {
425 try!(pp::space(&mut s.s));
426 try!(pp::word(&mut s.s, "as"));
427 try!(pp::space(&mut s.s));
428 try!(pp::word(&mut s.s,
429 &self.tcx.expr_ty(expr).to_string()));
437 fn gather_flowgraph_variants(sess: &Session) -> Vec<borrowck_dot::Variant> {
438 let print_loans = sess.opts.debugging_opts.flowgraph_print_loans;
439 let print_moves = sess.opts.debugging_opts.flowgraph_print_moves;
440 let print_assigns = sess.opts.debugging_opts.flowgraph_print_assigns;
441 let print_all = sess.opts.debugging_opts.flowgraph_print_all;
442 let mut variants = Vec::new();
443 if print_all || print_loans {
444 variants.push(borrowck_dot::Loans);
446 if print_all || print_moves {
447 variants.push(borrowck_dot::Moves);
449 if print_all || print_assigns {
450 variants.push(borrowck_dot::Assigns);
455 #[derive(Clone, Debug)]
456 pub enum UserIdentifiedItem {
457 ItemViaNode(ast::NodeId),
458 ItemViaPath(Vec<String>),
461 impl FromStr for UserIdentifiedItem {
463 fn from_str(s: &str) -> Result<UserIdentifiedItem, ()> {
464 Ok(s.parse().map(ItemViaNode).unwrap_or_else(|_| {
465 ItemViaPath(s.split("::").map(|s| s.to_string()).collect())
470 enum NodesMatchingUII<'a, 'ast: 'a> {
471 NodesMatchingDirect(option::IntoIter<ast::NodeId>),
472 NodesMatchingSuffix(hir_map::NodesMatchingSuffix<'a, 'ast>),
475 impl<'a, 'ast> Iterator for NodesMatchingUII<'a, 'ast> {
476 type Item = ast::NodeId;
478 fn next(&mut self) -> Option<ast::NodeId> {
480 &mut NodesMatchingDirect(ref mut iter) => iter.next(),
481 &mut NodesMatchingSuffix(ref mut iter) => iter.next(),
486 impl UserIdentifiedItem {
487 fn reconstructed_input(&self) -> String {
489 ItemViaNode(node_id) => node_id.to_string(),
490 ItemViaPath(ref parts) => parts.join("::"),
494 fn all_matching_node_ids<'a, 'ast>(&'a self, map: &'a hir_map::Map<'ast>)
495 -> NodesMatchingUII<'a, 'ast> {
497 ItemViaNode(node_id) =>
498 NodesMatchingDirect(Some(node_id).into_iter()),
499 ItemViaPath(ref parts) =>
500 NodesMatchingSuffix(map.nodes_matching_suffix(&parts[..])),
504 fn to_one_node_id(self, user_option: &str, sess: &Session, map: &hir_map::Map) -> ast::NodeId {
505 let fail_because = |is_wrong_because| -> ast::NodeId {
507 format!("{} needs NodeId (int) or unique \
508 path suffix (b::c::d); got {}, which {}",
510 self.reconstructed_input(),
512 sess.fatal(&message[..])
515 let mut saw_node = ast::DUMMY_NODE_ID;
517 for node in self.all_matching_node_ids(map) {
521 fail_because("does not resolve uniquely");
525 fail_because("does not resolve to any item");
533 fn needs_ast_map(ppm: &PpMode, opt_uii: &Option<UserIdentifiedItem>) -> bool {
535 PpmSource(PpmNormal) |
536 PpmSource(PpmEveryBodyLoops) |
537 PpmSource(PpmIdentified) => opt_uii.is_some(),
539 PpmSource(PpmExpanded) |
540 PpmSource(PpmExpandedIdentified) |
541 PpmSource(PpmExpandedHygiene) |
543 PpmFlowGraph(_) => true,
544 PpmSource(PpmTyped) => panic!("invalid state"),
548 fn needs_expansion(ppm: &PpMode) -> bool {
550 PpmSource(PpmNormal) |
551 PpmSource(PpmEveryBodyLoops) |
552 PpmSource(PpmIdentified) => false,
554 PpmSource(PpmExpanded) |
555 PpmSource(PpmExpandedIdentified) |
556 PpmSource(PpmExpandedHygiene) |
558 PpmFlowGraph(_) => true,
559 PpmSource(PpmTyped) => panic!("invalid state"),
563 struct ReplaceBodyWithLoop {
564 within_static_or_const: bool,
567 impl ReplaceBodyWithLoop {
568 fn new() -> ReplaceBodyWithLoop {
569 ReplaceBodyWithLoop { within_static_or_const: false }
573 impl fold::Folder for ReplaceBodyWithLoop {
574 fn fold_item_underscore(&mut self, i: ast::Item_) -> ast::Item_ {
576 ast::ItemStatic(..) | ast::ItemConst(..) => {
577 self.within_static_or_const = true;
578 let ret = fold::noop_fold_item_underscore(i, self);
579 self.within_static_or_const = false;
583 fold::noop_fold_item_underscore(i, self)
588 fn fold_trait_item(&mut self, i: P<ast::TraitItem>) -> SmallVector<P<ast::TraitItem>> {
590 ast::ConstTraitItem(..) => {
591 self.within_static_or_const = true;
592 let ret = fold::noop_fold_trait_item(i, self);
593 self.within_static_or_const = false;
596 _ => fold::noop_fold_trait_item(i, self),
600 fn fold_impl_item(&mut self, i: P<ast::ImplItem>) -> SmallVector<P<ast::ImplItem>> {
602 ast::ConstImplItem(..) => {
603 self.within_static_or_const = true;
604 let ret = fold::noop_fold_impl_item(i, self);
605 self.within_static_or_const = false;
608 _ => fold::noop_fold_impl_item(i, self),
612 fn fold_block(&mut self, b: P<ast::Block>) -> P<ast::Block> {
613 fn expr_to_block(rules: ast::BlockCheckMode,
614 e: Option<P<ast::Expr>>) -> P<ast::Block> {
617 stmts: vec![], rules: rules,
618 id: ast::DUMMY_NODE_ID, span: codemap::DUMMY_SP,
622 if !self.within_static_or_const {
624 let empty_block = expr_to_block(ast::DefaultBlock, None);
625 let loop_expr = P(ast::Expr {
626 node: ast::ExprLoop(empty_block, None),
627 id: ast::DUMMY_NODE_ID, span: codemap::DUMMY_SP
630 expr_to_block(b.rules, Some(loop_expr))
633 fold::noop_fold_block(b, self)
637 // in general the pretty printer processes unexpanded code, so
638 // we override the default `fold_mac` method which panics.
639 fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac {
640 fold::noop_fold_mac(mac, self)
644 pub fn pretty_print_input(sess: Session,
645 cfg: ast::CrateConfig,
648 opt_uii: Option<UserIdentifiedItem>,
649 ofile: Option<PathBuf>) {
650 let krate = driver::phase_1_parse_input(&sess, cfg, input);
652 let krate = if let PpmSource(PpmEveryBodyLoops) = ppm {
653 let mut fold = ReplaceBodyWithLoop::new();
654 fold.fold_crate(krate)
659 let id = link::find_crate_name(Some(&sess), &krate.attrs, input);
661 let is_expanded = needs_expansion(&ppm);
662 let compute_ast_map = needs_ast_map(&ppm, &opt_uii);
663 let krate = if compute_ast_map {
664 match driver::phase_2_configure_and_expand(&sess, krate, &id[..], None) {
666 Some(k) => driver::assign_node_ids(&sess, k)
672 // There is some twisted, god-forsaken tangle of lifetimes here which makes
673 // the ordering of stuff super-finicky.
675 let arenas = ty::CtxtArenas::new();
676 let ast_map = if compute_ast_map {
677 hir_forest = hir_map::Forest::new(lower_crate(&krate));
678 let map = driver::make_map(&sess, &mut hir_forest);
684 let src_name = driver::source_name(input);
685 let src = sess.codemap().get_filemap(&src_name[..])
691 let mut rdr = &src[..];
693 let mut out = Vec::new();
695 match (ppm, opt_uii) {
696 (PpmSource(s), _) => {
697 // Silently ignores an identified node.
698 let out: &mut Write = &mut out;
699 s.call_with_pp_support(
700 sess, ast_map, box out, |annotation, out| {
701 debug!("pretty printing source code {:?}", s);
702 let sess = annotation.sess();
703 pprust::print_crate(sess.codemap(),
706 src_name.to_string(),
714 (PpmHir(s), None) => {
715 let out: &mut Write = &mut out;
716 s.call_with_pp_support_hir(
717 sess, &ast_map.unwrap(), &krate, &arenas, id, box out, |annotation, out, krate| {
718 debug!("pretty printing source code {:?}", s);
719 let sess = annotation.sess();
720 pprust_hir::print_crate(sess.codemap(),
723 src_name.to_string(),
731 (PpmHir(s), Some(uii)) => {
732 let out: &mut Write = &mut out;
733 s.call_with_pp_support_hir(sess,
739 |annotation, (out,uii), _| {
740 debug!("pretty printing source code {:?}", s);
741 let sess = annotation.sess();
742 let ast_map = annotation.ast_map().expect("--pretty missing ast_map");
744 pprust_hir::State::new_from_input(sess.codemap(),
746 src_name.to_string(),
751 for node_id in uii.all_matching_node_ids(ast_map) {
752 let node = ast_map.get(node_id);
753 try!(pp_state.print_node(&node));
754 try!(pp::space(&mut pp_state.s));
755 try!(pp_state.synth_comment(ast_map.path_to_string(node_id)));
756 try!(pp::hardbreak(&mut pp_state.s));
758 pp::eof(&mut pp_state.s)
762 (PpmFlowGraph(mode), opt_uii) => {
763 debug!("pretty printing flow graph for {:?}", opt_uii);
764 let uii = opt_uii.unwrap_or_else(|| {
765 sess.fatal(&format!("`pretty flowgraph=..` needs NodeId (int) or
766 unique path suffix (b::c::d)"))
769 let ast_map = ast_map.expect("--pretty flowgraph missing ast_map");
770 let nodeid = uii.to_one_node_id("--pretty", &sess, &ast_map);
772 let node = ast_map.find(nodeid).unwrap_or_else(|| {
773 sess.fatal(&format!("--pretty flowgraph couldn't find id: {}",
777 let code = blocks::Code::from_node(node);
778 let out: &mut Write = &mut out;
781 let variants = gather_flowgraph_variants(&sess);
782 driver::phase_3_run_analysis_passes(sess,
787 resolve::MakeGlobMap::No,
789 print_flowgraph(variants, tcx, code, mode, out)
793 let message = format!("--pretty=flowgraph needs \
794 block, fn, or method; got {:?}",
797 // point to what was found, if there's an
799 match ast_map.opt_span(nodeid) {
800 Some(sp) => sess.span_fatal(sp, &message[..]),
801 None => sess.fatal(&message[..])
809 None => print!("{}", String::from_utf8(out).unwrap()),
811 match File::create(&p) {
812 Ok(mut w) => w.write_all(&out).unwrap(),
813 Err(e) => panic!("print-print failed to open {} due to {}",
820 fn print_flowgraph<W: Write>(variants: Vec<borrowck_dot::Variant>,
823 mode: PpFlowGraphMode,
824 mut out: W) -> io::Result<()> {
825 let cfg = match code {
826 blocks::BlockCode(block) => cfg::CFG::new(tcx, &*block),
827 blocks::FnLikeCode(fn_like) => cfg::CFG::new(tcx, &*fn_like.body()),
829 let labelled_edges = mode != PpFlowGraphMode::UnlabelledEdges;
830 let lcfg = LabelledCFG {
833 name: format!("node_{}", code.id()),
834 labelled_edges: labelled_edges,
838 _ if variants.is_empty() => {
839 let r = dot::render(&lcfg, &mut out);
840 return expand_err_details(r);
842 blocks::BlockCode(_) => {
843 tcx.sess.err("--pretty flowgraph with -Z flowgraph-print \
844 annotations requires fn-like node id.");
847 blocks::FnLikeCode(fn_like) => {
848 let fn_parts = borrowck::FnPartsWithCFG::from_fn_like(&fn_like, &cfg);
849 let (bccx, analysis_data) =
850 borrowck::build_borrowck_dataflow_data_for_fn(tcx, fn_parts);
852 let lcfg = borrowck_dot::DataflowLabeller {
855 borrowck_ctxt: &bccx,
856 analysis_data: &analysis_data,
858 let r = dot::render(&lcfg, &mut out);
859 return expand_err_details(r);
863 fn expand_err_details(r: io::Result<()>) -> io::Result<()> {
865 io::Error::new(io::ErrorKind::Other,
866 &format!("graphviz::render failed: {}", ioerr)[..])