]> git.lizzy.rs Git - rust.git/blob - src/librustc_driver/pretty.rs
rollup merge of #21151: brson/beta
[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::io::{self, MemReader};
42 use std::option;
43 use std::str::FromStr;
44
45 #[derive(Copy, PartialEq, Show)]
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, Show)]
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, Show)]
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).as_slice());
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).as_slice());
99             }
100         }
101     };
102     let opt_second = opt_second.and_then(|s| s.parse::<UserIdentifiedItem>());
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) -> 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) -> 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) -> 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) -> 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) -> 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, Show)]
342 pub enum UserIdentifiedItem {
343     ItemViaNode(ast::NodeId),
344     ItemViaPath(Vec<String>),
345 }
346
347 impl FromStr for UserIdentifiedItem {
348     fn from_str(s: &str) -> Option<UserIdentifiedItem> {
349         s.parse().map(ItemViaNode).or_else(|| {
350             let v : Vec<_> = s.split_str("::")
351                 .map(|x|x.to_string())
352                 .collect();
353             Some(ItemViaPath(v))
354         })
355     }
356 }
357
358 enum NodesMatchingUII<'a, 'ast: 'a> {
359     NodesMatchingDirect(option::IntoIter<ast::NodeId>),
360     NodesMatchingSuffix(ast_map::NodesMatchingSuffix<'a, 'ast>),
361 }
362
363 impl<'a, 'ast> Iterator for NodesMatchingUII<'a, 'ast> {
364     type Item = ast::NodeId;
365
366     fn next(&mut self) -> Option<ast::NodeId> {
367         match self {
368             &mut NodesMatchingDirect(ref mut iter) => iter.next(),
369             &mut NodesMatchingSuffix(ref mut iter) => iter.next(),
370         }
371     }
372 }
373
374 impl UserIdentifiedItem {
375     fn reconstructed_input(&self) -> String {
376         match *self {
377             ItemViaNode(node_id) => node_id.to_string(),
378             ItemViaPath(ref parts) => parts.connect("::"),
379         }
380     }
381
382     fn all_matching_node_ids<'a, 'ast>(&'a self, map: &'a ast_map::Map<'ast>)
383                                        -> NodesMatchingUII<'a, 'ast> {
384         match *self {
385             ItemViaNode(node_id) =>
386                 NodesMatchingDirect(Some(node_id).into_iter()),
387             ItemViaPath(ref parts) =>
388                 NodesMatchingSuffix(map.nodes_matching_suffix(&parts[])),
389         }
390     }
391
392     fn to_one_node_id(self, user_option: &str, sess: &Session, map: &ast_map::Map) -> ast::NodeId {
393         let fail_because = |&: is_wrong_because| -> ast::NodeId {
394             let message =
395                 format!("{} needs NodeId (int) or unique \
396                          path suffix (b::c::d); got {}, which {}",
397                         user_option,
398                         self.reconstructed_input(),
399                         is_wrong_because);
400             sess.fatal(&message[])
401         };
402
403         let mut saw_node = ast::DUMMY_NODE_ID;
404         let mut seen = 0u;
405         for node in self.all_matching_node_ids(map) {
406             saw_node = node;
407             seen += 1;
408             if seen > 1 {
409                 fail_because("does not resolve uniquely");
410             }
411         }
412         if seen == 0 {
413             fail_because("does not resolve to any item");
414         }
415
416         assert!(seen == 1);
417         return saw_node;
418     }
419 }
420
421 fn needs_ast_map(ppm: &PpMode, opt_uii: &Option<UserIdentifiedItem>) -> bool {
422     match *ppm {
423         PpmSource(PpmNormal) |
424         PpmSource(PpmEveryBodyLoops) |
425         PpmSource(PpmIdentified) => opt_uii.is_some(),
426
427         PpmSource(PpmExpanded) |
428         PpmSource(PpmExpandedIdentified) |
429         PpmSource(PpmExpandedHygiene) |
430         PpmSource(PpmTyped) |
431         PpmFlowGraph(_) => true
432     }
433 }
434
435 fn needs_expansion(ppm: &PpMode) -> bool {
436     match *ppm {
437         PpmSource(PpmNormal) |
438         PpmSource(PpmEveryBodyLoops) |
439         PpmSource(PpmIdentified) => false,
440
441         PpmSource(PpmExpanded) |
442         PpmSource(PpmExpandedIdentified) |
443         PpmSource(PpmExpandedHygiene) |
444         PpmSource(PpmTyped) |
445         PpmFlowGraph(_) => true
446     }
447 }
448
449 struct ReplaceBodyWithLoop {
450     within_static_or_const: bool,
451 }
452
453 impl ReplaceBodyWithLoop {
454     fn new() -> ReplaceBodyWithLoop {
455         ReplaceBodyWithLoop { within_static_or_const: false }
456     }
457 }
458
459 impl fold::Folder for ReplaceBodyWithLoop {
460     fn fold_item_underscore(&mut self, i: ast::Item_) -> ast::Item_ {
461         match i {
462             ast::ItemStatic(..) | ast::ItemConst(..) => {
463                 self.within_static_or_const = true;
464                 let ret = fold::noop_fold_item_underscore(i, self);
465                 self.within_static_or_const = false;
466                 return ret;
467             }
468             _ => {
469                 fold::noop_fold_item_underscore(i, self)
470             }
471         }
472     }
473
474
475     fn fold_block(&mut self, b: P<ast::Block>) -> P<ast::Block> {
476         fn expr_to_block(rules: ast::BlockCheckMode,
477                          e: Option<P<ast::Expr>>) -> P<ast::Block> {
478             P(ast::Block {
479                 expr: e,
480                 view_items: vec![], stmts: vec![], rules: rules,
481                 id: ast::DUMMY_NODE_ID, span: codemap::DUMMY_SP,
482             })
483         }
484
485         if !self.within_static_or_const {
486
487             let empty_block = expr_to_block(ast::DefaultBlock, None);
488             let loop_expr = P(ast::Expr {
489                 node: ast::ExprLoop(empty_block, None),
490                 id: ast::DUMMY_NODE_ID, span: codemap::DUMMY_SP
491             });
492
493             expr_to_block(b.rules, Some(loop_expr))
494
495         } else {
496             fold::noop_fold_block(b, self)
497         }
498     }
499
500     // in general the pretty printer processes unexpanded code, so
501     // we override the default `fold_mac` method which panics.
502     fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac {
503         fold::noop_fold_mac(mac, self)
504     }
505 }
506
507 pub fn pretty_print_input(sess: Session,
508                           cfg: ast::CrateConfig,
509                           input: &Input,
510                           ppm: PpMode,
511                           opt_uii: Option<UserIdentifiedItem>,
512                           ofile: Option<Path>) {
513     let krate = driver::phase_1_parse_input(&sess, cfg, input);
514
515     let krate = if let PpmSource(PpmEveryBodyLoops) = ppm {
516         let mut fold = ReplaceBodyWithLoop::new();
517         fold.fold_crate(krate)
518     } else {
519         krate
520     };
521
522     let id = link::find_crate_name(Some(&sess), krate.attrs.as_slice(), input);
523
524     let is_expanded = needs_expansion(&ppm);
525     let compute_ast_map = needs_ast_map(&ppm, &opt_uii);
526     let krate = if compute_ast_map {
527         match driver::phase_2_configure_and_expand(&sess, krate, &id[], None) {
528             None => return,
529             Some(k) => k
530         }
531     } else {
532         krate
533     };
534
535     let mut forest = ast_map::Forest::new(krate);
536     let arenas = ty::CtxtArenas::new();
537
538     let (krate, ast_map) = if compute_ast_map {
539         let map = driver::assign_node_ids_and_map(&sess, &mut forest);
540         (map.krate(), Some(map))
541     } else {
542         (forest.krate(), None)
543     };
544
545     let src_name = driver::source_name(input);
546     let src = sess.codemap().get_filemap(&src_name[])
547                             .src.as_bytes().to_vec();
548     let mut rdr = MemReader::new(src);
549
550     let out = match ofile {
551         None => box io::stdout() as Box<Writer+'static>,
552         Some(p) => {
553             let r = io::File::create(&p);
554             match r {
555                 Ok(w) => box w as Box<Writer+'static>,
556                 Err(e) => panic!("print-print failed to open {} due to {}",
557                                 p.display(), e),
558             }
559         }
560     };
561
562     match (ppm, opt_uii) {
563         (PpmSource(s), None) =>
564             s.call_with_pp_support(
565                 sess, ast_map, &arenas, id, out, |annotation, out| {
566                     debug!("pretty printing source code {:?}", s);
567                     let sess = annotation.sess();
568                     pprust::print_crate(sess.codemap(),
569                                         sess.diagnostic(),
570                                         krate,
571                                         src_name.to_string(),
572                                         &mut rdr,
573                                         out,
574                                         annotation.pp_ann(),
575                                         is_expanded)
576                 }),
577
578         (PpmSource(s), Some(uii)) =>
579             s.call_with_pp_support(
580                 sess, ast_map, &arenas, id, (out,uii), |annotation, (out,uii)| {
581                     debug!("pretty printing source code {:?}", s);
582                     let sess = annotation.sess();
583                     let ast_map = annotation.ast_map()
584                         .expect("--pretty missing ast_map");
585                     let mut pp_state =
586                         pprust::State::new_from_input(sess.codemap(),
587                                                       sess.diagnostic(),
588                                                       src_name.to_string(),
589                                                       &mut rdr,
590                                                       out,
591                                                       annotation.pp_ann(),
592                                                       is_expanded);
593                     for node_id in uii.all_matching_node_ids(ast_map) {
594                         let node = ast_map.get(node_id);
595                         try!(pp_state.print_node(&node));
596                         try!(pp::space(&mut pp_state.s));
597                         try!(pp_state.synth_comment(ast_map.path_to_string(node_id)));
598                         try!(pp::hardbreak(&mut pp_state.s));
599                     }
600                     pp::eof(&mut pp_state.s)
601                 }),
602
603         (PpmFlowGraph(mode), opt_uii) => {
604             debug!("pretty printing flow graph for {:?}", opt_uii);
605             let uii = opt_uii.unwrap_or_else(|| {
606                 sess.fatal(&format!("`pretty flowgraph=..` needs NodeId (int) or
607                                      unique path suffix (b::c::d)")[])
608
609             });
610             let ast_map = ast_map.expect("--pretty flowgraph missing ast_map");
611             let nodeid = uii.to_one_node_id("--pretty", &sess, &ast_map);
612
613             let node = ast_map.find(nodeid).unwrap_or_else(|| {
614                 sess.fatal(&format!("--pretty flowgraph couldn't find id: {}",
615                                    nodeid)[])
616             });
617
618             let code = blocks::Code::from_node(node);
619             match code {
620                 Some(code) => {
621                     let variants = gather_flowgraph_variants(&sess);
622                     let analysis = driver::phase_3_run_analysis_passes(sess,
623                                                                        ast_map,
624                                                                        &arenas,
625                                                                        id,
626                                                                        resolve::MakeGlobMap::No);
627                     print_flowgraph(variants, analysis, code, mode, out)
628                 }
629                 None => {
630                     let message = format!("--pretty=flowgraph needs \
631                                            block, fn, or method; got {:?}",
632                                           node);
633
634                     // point to what was found, if there's an
635                     // accessible span.
636                     match ast_map.opt_span(nodeid) {
637                         Some(sp) => sess.span_fatal(sp, &message[]),
638                         None => sess.fatal(&message[])
639                     }
640                 }
641             }
642         }
643     }.unwrap()
644 }
645
646 fn print_flowgraph<W:io::Writer>(variants: Vec<borrowck_dot::Variant>,
647                                  analysis: ty::CrateAnalysis,
648                                  code: blocks::Code,
649                                  mode: PpFlowGraphMode,
650                                  mut out: W) -> io::IoResult<()> {
651     let ty_cx = &analysis.ty_cx;
652     let cfg = match code {
653         blocks::BlockCode(block) => cfg::CFG::new(ty_cx, &*block),
654         blocks::FnLikeCode(fn_like) => cfg::CFG::new(ty_cx, &*fn_like.body()),
655     };
656     let labelled_edges = mode != PpFlowGraphMode::UnlabelledEdges;
657     let lcfg = LabelledCFG {
658         ast_map: &ty_cx.map,
659         cfg: &cfg,
660         name: format!("node_{}", code.id()),
661         labelled_edges: labelled_edges,
662     };
663
664     match code {
665         _ if variants.len() == 0 => {
666             let r = dot::render(&lcfg, &mut out);
667             return expand_err_details(r);
668         }
669         blocks::BlockCode(_) => {
670             ty_cx.sess.err("--pretty flowgraph with -Z flowgraph-print \
671                             annotations requires fn-like node id.");
672             return Ok(())
673         }
674         blocks::FnLikeCode(fn_like) => {
675             let fn_parts = borrowck::FnPartsWithCFG::from_fn_like(&fn_like, &cfg);
676             let (bccx, analysis_data) =
677                 borrowck::build_borrowck_dataflow_data_for_fn(ty_cx, fn_parts);
678
679             let lcfg = borrowck_dot::DataflowLabeller {
680                 inner: lcfg,
681                 variants: variants,
682                 borrowck_ctxt: &bccx,
683                 analysis_data: &analysis_data,
684             };
685             let r = dot::render(&lcfg, &mut out);
686             return expand_err_details(r);
687         }
688     }
689
690     fn expand_err_details(r: io::IoResult<()>) -> io::IoResult<()> {
691         r.map_err(|ioerr| {
692             let orig_detail = ioerr.detail.clone();
693             let m = "graphviz::render failed";
694             io::IoError {
695                 detail: Some(match orig_detail {
696                     None => m.to_string(),
697                     Some(d) => format!("{}: {}", m, d)
698                 }),
699                 ..ioerr
700             }
701         })
702     }
703 }