]> git.lizzy.rs Git - rust.git/blob - src/librustc_driver/pretty.rs
Auto merge of #22517 - brson:relnotes, r=Gankro
[rust.git] / src / librustc_driver / pretty.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 //! The various pretty print routines.
12
13 pub use self::UserIdentifiedItem::*;
14 pub use self::PpSourceMode::*;
15 pub use self::PpMode::*;
16 use self::NodesMatchingUII::*;
17
18 use rustc_trans::back::link;
19
20 use driver;
21
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::util::ppaux;
28 use rustc_borrowck as borrowck;
29 use rustc_borrowck::graphviz as borrowck_dot;
30 use rustc_resolve as resolve;
31
32 use syntax::ast;
33 use syntax::ast_map::{self, blocks, NodePrinter};
34 use syntax::codemap;
35 use syntax::fold::{self, Folder};
36 use syntax::print::{pp, pprust};
37 use syntax::ptr::P;
38
39 use graphviz as dot;
40
41 use std::old_io::{self, MemReader};
42 use std::option;
43 use std::str::FromStr;
44
45 #[derive(Copy, PartialEq, Debug)]
46 pub enum PpSourceMode {
47     PpmNormal,
48     PpmEveryBodyLoops,
49     PpmExpanded,
50     PpmTyped,
51     PpmIdentified,
52     PpmExpandedIdentified,
53     PpmExpandedHygiene,
54 }
55
56
57 #[derive(Copy, PartialEq, Debug)]
58 pub enum PpFlowGraphMode {
59     Default,
60     /// Drops the labels from the edges in the flowgraph output. This
61     /// is mostly for use in the --xpretty flowgraph run-make tests,
62     /// since the labels are largely uninteresting in those cases and
63     /// have become a pain to maintain.
64     UnlabelledEdges,
65 }
66 #[derive(Copy, PartialEq, Debug)]
67 pub enum PpMode {
68     PpmSource(PpSourceMode),
69     PpmFlowGraph(PpFlowGraphMode),
70 }
71
72 pub fn parse_pretty(sess: &Session,
73                     name: &str,
74                     extended: bool) -> (PpMode, Option<UserIdentifiedItem>) {
75     let mut split = name.splitn(1, '=');
76     let first = split.next().unwrap();
77     let opt_second = split.next();
78     let first = match (first, extended) {
79         ("normal", _)       => PpmSource(PpmNormal),
80         ("everybody_loops", true) => PpmSource(PpmEveryBodyLoops),
81         ("expanded", _)     => PpmSource(PpmExpanded),
82         ("typed", _)        => PpmSource(PpmTyped),
83         ("expanded,identified", _) => PpmSource(PpmExpandedIdentified),
84         ("expanded,hygiene", _) => PpmSource(PpmExpandedHygiene),
85         ("identified", _)   => PpmSource(PpmIdentified),
86         ("flowgraph", true)    => PpmFlowGraph(PpFlowGraphMode::Default),
87         ("flowgraph,unlabelled", true)    => PpmFlowGraph(PpFlowGraphMode::UnlabelledEdges),
88         _ => {
89             if extended {
90                 sess.fatal(&format!(
91                     "argument to `xpretty` must be one of `normal`, \
92                      `expanded`, `flowgraph[,unlabelled]=<nodeid>`, `typed`, `identified`, \
93                      `expanded,identified`, or `everybody_loops`; got {}", name));
94             } else {
95                 sess.fatal(&format!(
96                     "argument to `pretty` must be one of `normal`, \
97                      `expanded`, `typed`, `identified`, \
98                      or `expanded,identified`; got {}", name));
99             }
100         }
101     };
102     let opt_second = opt_second.and_then(|s| s.parse::<UserIdentifiedItem>().ok());
103     (first, opt_second)
104 }
105
106
107
108 // This slightly awkward construction is to allow for each PpMode to
109 // choose whether it needs to do analyses (which can consume the
110 // Session) and then pass through the session (now attached to the
111 // analysis results) on to the chosen pretty-printer, along with the
112 // `&PpAnn` object.
113 //
114 // Note that since the `&PrinterSupport` is freshly constructed on each
115 // call, it would not make sense to try to attach the lifetime of `self`
116 // to the lifetime of the `&PrinterObject`.
117 //
118 // (The `use_once_payload` is working around the current lack of once
119 // functions in the compiler.)
120
121 impl PpSourceMode {
122     /// Constructs a `PrinterSupport` object and passes it to `f`.
123     fn call_with_pp_support<'tcx, A, B, F>(&self,
124                                            sess: Session,
125                                            ast_map: Option<ast_map::Map<'tcx>>,
126                                            arenas: &'tcx ty::CtxtArenas<'tcx>,
127                                            id: String,
128                                            payload: B,
129                                            f: F) -> A where
130         F: FnOnce(&PrinterSupport, B) -> A,
131     {
132         match *self {
133             PpmNormal | PpmEveryBodyLoops | PpmExpanded => {
134                 let annotation = NoAnn { sess: sess, ast_map: ast_map };
135                 f(&annotation, payload)
136             }
137
138             PpmIdentified | PpmExpandedIdentified => {
139                 let annotation = IdentifiedAnnotation { sess: sess, ast_map: ast_map };
140                 f(&annotation, payload)
141             }
142             PpmExpandedHygiene => {
143                 let annotation = HygieneAnnotation { sess: sess, ast_map: ast_map };
144                 f(&annotation, payload)
145             }
146             PpmTyped => {
147                 let ast_map = ast_map.expect("--pretty=typed missing ast_map");
148                 let analysis = driver::phase_3_run_analysis_passes(sess,
149                                                                    ast_map,
150                                                                    arenas,
151                                                                    id,
152                                                                    resolve::MakeGlobMap::No);
153                 let annotation = TypedAnnotation { analysis: analysis };
154                 f(&annotation, payload)
155             }
156         }
157     }
158 }
159
160 trait PrinterSupport<'ast>: pprust::PpAnn {
161     /// Provides a uniform interface for re-extracting a reference to a
162     /// `Session` from a value that now owns it.
163     fn sess<'a>(&'a self) -> &'a Session;
164
165     /// Provides a uniform interface for re-extracting a reference to an
166     /// `ast_map::Map` from a value that now owns it.
167     fn ast_map<'a>(&'a self) -> Option<&'a ast_map::Map<'ast>>;
168
169     /// Produces the pretty-print annotation object.
170     ///
171     /// (Rust does not yet support upcasting from a trait object to
172     /// an object for one of its super-traits.)
173     fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn;
174 }
175
176 struct NoAnn<'ast> {
177     sess: Session,
178     ast_map: Option<ast_map::Map<'ast>>
179 }
180
181 impl<'ast> PrinterSupport<'ast> for NoAnn<'ast> {
182     fn sess<'a>(&'a self) -> &'a Session { &self.sess }
183
184     fn ast_map<'a>(&'a self) -> Option<&'a ast_map::Map<'ast>> {
185         self.ast_map.as_ref()
186     }
187
188     fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn { self }
189 }
190
191 impl<'ast> pprust::PpAnn for NoAnn<'ast> {}
192
193 struct IdentifiedAnnotation<'ast> {
194     sess: Session,
195     ast_map: Option<ast_map::Map<'ast>>,
196 }
197
198 impl<'ast> PrinterSupport<'ast> for IdentifiedAnnotation<'ast> {
199     fn sess<'a>(&'a self) -> &'a Session { &self.sess }
200
201     fn ast_map<'a>(&'a self) -> Option<&'a ast_map::Map<'ast>> {
202         self.ast_map.as_ref()
203     }
204
205     fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn { self }
206 }
207
208 impl<'ast> pprust::PpAnn for IdentifiedAnnotation<'ast> {
209     fn pre(&self,
210            s: &mut pprust::State,
211            node: pprust::AnnNode) -> old_io::IoResult<()> {
212         match node {
213             pprust::NodeExpr(_) => s.popen(),
214             _ => Ok(())
215         }
216     }
217     fn post(&self,
218             s: &mut pprust::State,
219             node: pprust::AnnNode) -> old_io::IoResult<()> {
220         match node {
221             pprust::NodeIdent(_) | pprust::NodeName(_) => Ok(()),
222
223             pprust::NodeItem(item) => {
224                 try!(pp::space(&mut s.s));
225                 s.synth_comment(item.id.to_string())
226             }
227             pprust::NodeBlock(blk) => {
228                 try!(pp::space(&mut s.s));
229                 s.synth_comment(format!("block {}", blk.id))
230             }
231             pprust::NodeExpr(expr) => {
232                 try!(pp::space(&mut s.s));
233                 try!(s.synth_comment(expr.id.to_string()));
234                 s.pclose()
235             }
236             pprust::NodePat(pat) => {
237                 try!(pp::space(&mut s.s));
238                 s.synth_comment(format!("pat {}", pat.id))
239             }
240         }
241     }
242 }
243
244 struct HygieneAnnotation<'ast> {
245     sess: Session,
246     ast_map: Option<ast_map::Map<'ast>>,
247 }
248
249 impl<'ast> PrinterSupport<'ast> for HygieneAnnotation<'ast> {
250     fn sess<'a>(&'a self) -> &'a Session { &self.sess }
251
252     fn ast_map<'a>(&'a self) -> Option<&'a ast_map::Map<'ast>> {
253         self.ast_map.as_ref()
254     }
255
256     fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn { self }
257 }
258
259 impl<'ast> pprust::PpAnn for HygieneAnnotation<'ast> {
260     fn post(&self,
261             s: &mut pprust::State,
262             node: pprust::AnnNode) -> old_io::IoResult<()> {
263         match node {
264             pprust::NodeIdent(&ast::Ident { name: ast::Name(nm), ctxt }) => {
265                 try!(pp::space(&mut s.s));
266                 // FIXME #16420: this doesn't display the connections
267                 // between syntax contexts
268                 s.synth_comment(format!("{}#{}", nm, ctxt))
269             }
270             pprust::NodeName(&ast::Name(nm)) => {
271                 try!(pp::space(&mut s.s));
272                 s.synth_comment(nm.to_string())
273             }
274             _ => Ok(())
275         }
276     }
277 }
278
279
280 struct TypedAnnotation<'tcx> {
281     analysis: ty::CrateAnalysis<'tcx>,
282 }
283
284 impl<'tcx> PrinterSupport<'tcx> for TypedAnnotation<'tcx> {
285     fn sess<'a>(&'a self) -> &'a Session { &self.analysis.ty_cx.sess }
286
287     fn ast_map<'a>(&'a self) -> Option<&'a ast_map::Map<'tcx>> {
288         Some(&self.analysis.ty_cx.map)
289     }
290
291     fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn { self }
292 }
293
294 impl<'tcx> pprust::PpAnn for TypedAnnotation<'tcx> {
295     fn pre(&self,
296            s: &mut pprust::State,
297            node: pprust::AnnNode) -> old_io::IoResult<()> {
298         match node {
299             pprust::NodeExpr(_) => s.popen(),
300             _ => Ok(())
301         }
302     }
303     fn post(&self,
304             s: &mut pprust::State,
305             node: pprust::AnnNode) -> old_io::IoResult<()> {
306         let tcx = &self.analysis.ty_cx;
307         match node {
308             pprust::NodeExpr(expr) => {
309                 try!(pp::space(&mut s.s));
310                 try!(pp::word(&mut s.s, "as"));
311                 try!(pp::space(&mut s.s));
312                 try!(pp::word(&mut s.s,
313                               &ppaux::ty_to_string(
314                                   tcx,
315                                   ty::expr_ty(tcx, expr))[]));
316                 s.pclose()
317             }
318             _ => Ok(())
319         }
320     }
321 }
322
323 fn gather_flowgraph_variants(sess: &Session) -> Vec<borrowck_dot::Variant> {
324     let print_loans = sess.opts.debugging_opts.flowgraph_print_loans;
325     let print_moves = sess.opts.debugging_opts.flowgraph_print_moves;
326     let print_assigns = sess.opts.debugging_opts.flowgraph_print_assigns;
327     let print_all = sess.opts.debugging_opts.flowgraph_print_all;
328     let mut variants = Vec::new();
329     if print_all || print_loans {
330         variants.push(borrowck_dot::Loans);
331     }
332     if print_all || print_moves {
333         variants.push(borrowck_dot::Moves);
334     }
335     if print_all || print_assigns {
336         variants.push(borrowck_dot::Assigns);
337     }
338     variants
339 }
340
341 #[derive(Clone, Debug)]
342 pub enum UserIdentifiedItem {
343     ItemViaNode(ast::NodeId),
344     ItemViaPath(Vec<String>),
345 }
346
347 impl FromStr for UserIdentifiedItem {
348     type Err = ();
349     fn from_str(s: &str) -> Result<UserIdentifiedItem, ()> {
350         Ok(s.parse().map(ItemViaNode).unwrap_or_else(|_| {
351             ItemViaPath(s.split_str("::").map(|s| s.to_string()).collect())
352         }))
353     }
354 }
355
356 enum NodesMatchingUII<'a, 'ast: 'a> {
357     NodesMatchingDirect(option::IntoIter<ast::NodeId>),
358     NodesMatchingSuffix(ast_map::NodesMatchingSuffix<'a, 'ast>),
359 }
360
361 impl<'a, 'ast> Iterator for NodesMatchingUII<'a, 'ast> {
362     type Item = ast::NodeId;
363
364     fn next(&mut self) -> Option<ast::NodeId> {
365         match self {
366             &mut NodesMatchingDirect(ref mut iter) => iter.next(),
367             &mut NodesMatchingSuffix(ref mut iter) => iter.next(),
368         }
369     }
370 }
371
372 impl UserIdentifiedItem {
373     fn reconstructed_input(&self) -> String {
374         match *self {
375             ItemViaNode(node_id) => node_id.to_string(),
376             ItemViaPath(ref parts) => parts.connect("::"),
377         }
378     }
379
380     fn all_matching_node_ids<'a, 'ast>(&'a self, map: &'a ast_map::Map<'ast>)
381                                        -> NodesMatchingUII<'a, 'ast> {
382         match *self {
383             ItemViaNode(node_id) =>
384                 NodesMatchingDirect(Some(node_id).into_iter()),
385             ItemViaPath(ref parts) =>
386                 NodesMatchingSuffix(map.nodes_matching_suffix(&parts[])),
387         }
388     }
389
390     fn to_one_node_id(self, user_option: &str, sess: &Session, map: &ast_map::Map) -> ast::NodeId {
391         let fail_because = |is_wrong_because| -> ast::NodeId {
392             let message =
393                 format!("{} needs NodeId (int) or unique \
394                          path suffix (b::c::d); got {}, which {}",
395                         user_option,
396                         self.reconstructed_input(),
397                         is_wrong_because);
398             sess.fatal(&message[])
399         };
400
401         let mut saw_node = ast::DUMMY_NODE_ID;
402         let mut seen = 0;
403         for node in self.all_matching_node_ids(map) {
404             saw_node = node;
405             seen += 1;
406             if seen > 1 {
407                 fail_because("does not resolve uniquely");
408             }
409         }
410         if seen == 0 {
411             fail_because("does not resolve to any item");
412         }
413
414         assert!(seen == 1);
415         return saw_node;
416     }
417 }
418
419 fn needs_ast_map(ppm: &PpMode, opt_uii: &Option<UserIdentifiedItem>) -> bool {
420     match *ppm {
421         PpmSource(PpmNormal) |
422         PpmSource(PpmEveryBodyLoops) |
423         PpmSource(PpmIdentified) => opt_uii.is_some(),
424
425         PpmSource(PpmExpanded) |
426         PpmSource(PpmExpandedIdentified) |
427         PpmSource(PpmExpandedHygiene) |
428         PpmSource(PpmTyped) |
429         PpmFlowGraph(_) => true
430     }
431 }
432
433 fn needs_expansion(ppm: &PpMode) -> bool {
434     match *ppm {
435         PpmSource(PpmNormal) |
436         PpmSource(PpmEveryBodyLoops) |
437         PpmSource(PpmIdentified) => false,
438
439         PpmSource(PpmExpanded) |
440         PpmSource(PpmExpandedIdentified) |
441         PpmSource(PpmExpandedHygiene) |
442         PpmSource(PpmTyped) |
443         PpmFlowGraph(_) => true
444     }
445 }
446
447 struct ReplaceBodyWithLoop {
448     within_static_or_const: bool,
449 }
450
451 impl ReplaceBodyWithLoop {
452     fn new() -> ReplaceBodyWithLoop {
453         ReplaceBodyWithLoop { within_static_or_const: false }
454     }
455 }
456
457 impl fold::Folder for ReplaceBodyWithLoop {
458     fn fold_item_underscore(&mut self, i: ast::Item_) -> ast::Item_ {
459         match i {
460             ast::ItemStatic(..) | ast::ItemConst(..) => {
461                 self.within_static_or_const = true;
462                 let ret = fold::noop_fold_item_underscore(i, self);
463                 self.within_static_or_const = false;
464                 return ret;
465             }
466             _ => {
467                 fold::noop_fold_item_underscore(i, self)
468             }
469         }
470     }
471
472
473     fn fold_block(&mut self, b: P<ast::Block>) -> P<ast::Block> {
474         fn expr_to_block(rules: ast::BlockCheckMode,
475                          e: Option<P<ast::Expr>>) -> P<ast::Block> {
476             P(ast::Block {
477                 expr: e,
478                 stmts: vec![], rules: rules,
479                 id: ast::DUMMY_NODE_ID, span: codemap::DUMMY_SP,
480             })
481         }
482
483         if !self.within_static_or_const {
484
485             let empty_block = expr_to_block(ast::DefaultBlock, None);
486             let loop_expr = P(ast::Expr {
487                 node: ast::ExprLoop(empty_block, None),
488                 id: ast::DUMMY_NODE_ID, span: codemap::DUMMY_SP
489             });
490
491             expr_to_block(b.rules, Some(loop_expr))
492
493         } else {
494             fold::noop_fold_block(b, self)
495         }
496     }
497
498     // in general the pretty printer processes unexpanded code, so
499     // we override the default `fold_mac` method which panics.
500     fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac {
501         fold::noop_fold_mac(mac, self)
502     }
503 }
504
505 pub fn pretty_print_input(sess: Session,
506                           cfg: ast::CrateConfig,
507                           input: &Input,
508                           ppm: PpMode,
509                           opt_uii: Option<UserIdentifiedItem>,
510                           ofile: Option<Path>) {
511     let krate = driver::phase_1_parse_input(&sess, cfg, input);
512
513     let krate = if let PpmSource(PpmEveryBodyLoops) = ppm {
514         let mut fold = ReplaceBodyWithLoop::new();
515         fold.fold_crate(krate)
516     } else {
517         krate
518     };
519
520     let id = link::find_crate_name(Some(&sess), &krate.attrs, input);
521
522     let is_expanded = needs_expansion(&ppm);
523     let compute_ast_map = needs_ast_map(&ppm, &opt_uii);
524     let krate = if compute_ast_map {
525         match driver::phase_2_configure_and_expand(&sess, krate, &id[], None) {
526             None => return,
527             Some(k) => k
528         }
529     } else {
530         krate
531     };
532
533     let mut forest = ast_map::Forest::new(krate);
534     let arenas = ty::CtxtArenas::new();
535
536     let (krate, ast_map) = if compute_ast_map {
537         let map = driver::assign_node_ids_and_map(&sess, &mut forest);
538         (map.krate(), Some(map))
539     } else {
540         (forest.krate(), None)
541     };
542
543     let src_name = driver::source_name(input);
544     let src = sess.codemap().get_filemap(&src_name[])
545                             .src.as_bytes().to_vec();
546     let mut rdr = MemReader::new(src);
547
548     let out = match ofile {
549         None => box old_io::stdout() as Box<Writer+'static>,
550         Some(p) => {
551             let r = old_io::File::create(&p);
552             match r {
553                 Ok(w) => box w as Box<Writer+'static>,
554                 Err(e) => panic!("print-print failed to open {} due to {}",
555                                 p.display(), e),
556             }
557         }
558     };
559
560     match (ppm, opt_uii) {
561         (PpmSource(s), None) =>
562             s.call_with_pp_support(
563                 sess, ast_map, &arenas, id, out, |annotation, out| {
564                     debug!("pretty printing source code {:?}", s);
565                     let sess = annotation.sess();
566                     pprust::print_crate(sess.codemap(),
567                                         sess.diagnostic(),
568                                         krate,
569                                         src_name.to_string(),
570                                         &mut rdr,
571                                         out,
572                                         annotation.pp_ann(),
573                                         is_expanded)
574                 }),
575
576         (PpmSource(s), Some(uii)) =>
577             s.call_with_pp_support(
578                 sess, ast_map, &arenas, id, (out,uii), |annotation, (out,uii)| {
579                     debug!("pretty printing source code {:?}", s);
580                     let sess = annotation.sess();
581                     let ast_map = annotation.ast_map()
582                         .expect("--pretty missing ast_map");
583                     let mut pp_state =
584                         pprust::State::new_from_input(sess.codemap(),
585                                                       sess.diagnostic(),
586                                                       src_name.to_string(),
587                                                       &mut rdr,
588                                                       out,
589                                                       annotation.pp_ann(),
590                                                       is_expanded);
591                     for node_id in uii.all_matching_node_ids(ast_map) {
592                         let node = ast_map.get(node_id);
593                         try!(pp_state.print_node(&node));
594                         try!(pp::space(&mut pp_state.s));
595                         try!(pp_state.synth_comment(ast_map.path_to_string(node_id)));
596                         try!(pp::hardbreak(&mut pp_state.s));
597                     }
598                     pp::eof(&mut pp_state.s)
599                 }),
600
601         (PpmFlowGraph(mode), opt_uii) => {
602             debug!("pretty printing flow graph for {:?}", opt_uii);
603             let uii = opt_uii.unwrap_or_else(|| {
604                 sess.fatal(&format!("`pretty flowgraph=..` needs NodeId (int) or
605                                      unique path suffix (b::c::d)")[])
606
607             });
608             let ast_map = ast_map.expect("--pretty flowgraph missing ast_map");
609             let nodeid = uii.to_one_node_id("--pretty", &sess, &ast_map);
610
611             let node = ast_map.find(nodeid).unwrap_or_else(|| {
612                 sess.fatal(&format!("--pretty flowgraph couldn't find id: {}",
613                                    nodeid)[])
614             });
615
616             let code = blocks::Code::from_node(node);
617             match code {
618                 Some(code) => {
619                     let variants = gather_flowgraph_variants(&sess);
620                     let analysis = driver::phase_3_run_analysis_passes(sess,
621                                                                        ast_map,
622                                                                        &arenas,
623                                                                        id,
624                                                                        resolve::MakeGlobMap::No);
625                     print_flowgraph(variants, analysis, code, mode, out)
626                 }
627                 None => {
628                     let message = format!("--pretty=flowgraph needs \
629                                            block, fn, or method; got {:?}",
630                                           node);
631
632                     // point to what was found, if there's an
633                     // accessible span.
634                     match ast_map.opt_span(nodeid) {
635                         Some(sp) => sess.span_fatal(sp, &message[]),
636                         None => sess.fatal(&message[])
637                     }
638                 }
639             }
640         }
641     }.unwrap()
642 }
643
644 fn print_flowgraph<W:old_io::Writer>(variants: Vec<borrowck_dot::Variant>,
645                                  analysis: ty::CrateAnalysis,
646                                  code: blocks::Code,
647                                  mode: PpFlowGraphMode,
648                                  mut out: W) -> old_io::IoResult<()> {
649     let ty_cx = &analysis.ty_cx;
650     let cfg = match code {
651         blocks::BlockCode(block) => cfg::CFG::new(ty_cx, &*block),
652         blocks::FnLikeCode(fn_like) => cfg::CFG::new(ty_cx, &*fn_like.body()),
653     };
654     let labelled_edges = mode != PpFlowGraphMode::UnlabelledEdges;
655     let lcfg = LabelledCFG {
656         ast_map: &ty_cx.map,
657         cfg: &cfg,
658         name: format!("node_{}", code.id()),
659         labelled_edges: labelled_edges,
660     };
661
662     match code {
663         _ if variants.len() == 0 => {
664             let r = dot::render(&lcfg, &mut out);
665             return expand_err_details(r);
666         }
667         blocks::BlockCode(_) => {
668             ty_cx.sess.err("--pretty flowgraph with -Z flowgraph-print \
669                             annotations requires fn-like node id.");
670             return Ok(())
671         }
672         blocks::FnLikeCode(fn_like) => {
673             let fn_parts = borrowck::FnPartsWithCFG::from_fn_like(&fn_like, &cfg);
674             let (bccx, analysis_data) =
675                 borrowck::build_borrowck_dataflow_data_for_fn(ty_cx, fn_parts);
676
677             let lcfg = borrowck_dot::DataflowLabeller {
678                 inner: lcfg,
679                 variants: variants,
680                 borrowck_ctxt: &bccx,
681                 analysis_data: &analysis_data,
682             };
683             let r = dot::render(&lcfg, &mut out);
684             return expand_err_details(r);
685         }
686     }
687
688     fn expand_err_details(r: old_io::IoResult<()>) -> old_io::IoResult<()> {
689         r.map_err(|ioerr| {
690             let orig_detail = ioerr.detail.clone();
691             let m = "graphviz::render failed";
692             old_io::IoError {
693                 detail: Some(match orig_detail {
694                     None => m.to_string(),
695                     Some(d) => format!("{}: {}", m, d)
696                 }),
697                 ..ioerr
698             }
699         })
700     }
701 }