]> git.lizzy.rs Git - rust.git/blob - src/librustc_driver/pretty.rs
Fallout of std::old_io deprecation
[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::fs::File;
42 use std::io::{self, Write};
43 use std::option;
44 use std::path::PathBuf;
45 use std::str::FromStr;
46
47 #[derive(Copy, PartialEq, Debug)]
48 pub enum PpSourceMode {
49     PpmNormal,
50     PpmEveryBodyLoops,
51     PpmExpanded,
52     PpmTyped,
53     PpmIdentified,
54     PpmExpandedIdentified,
55     PpmExpandedHygiene,
56 }
57
58
59 #[derive(Copy, PartialEq, Debug)]
60 pub enum PpFlowGraphMode {
61     Default,
62     /// Drops the labels from the edges in the flowgraph output. This
63     /// is mostly for use in the --xpretty flowgraph run-make tests,
64     /// since the labels are largely uninteresting in those cases and
65     /// have become a pain to maintain.
66     UnlabelledEdges,
67 }
68 #[derive(Copy, PartialEq, Debug)]
69 pub enum PpMode {
70     PpmSource(PpSourceMode),
71     PpmFlowGraph(PpFlowGraphMode),
72 }
73
74 pub fn parse_pretty(sess: &Session,
75                     name: &str,
76                     extended: bool) -> (PpMode, Option<UserIdentifiedItem>) {
77     let mut split = name.splitn(1, '=');
78     let first = split.next().unwrap();
79     let opt_second = split.next();
80     let first = match (first, extended) {
81         ("normal", _)       => PpmSource(PpmNormal),
82         ("everybody_loops", true) => PpmSource(PpmEveryBodyLoops),
83         ("expanded", _)     => PpmSource(PpmExpanded),
84         ("typed", _)        => PpmSource(PpmTyped),
85         ("expanded,identified", _) => PpmSource(PpmExpandedIdentified),
86         ("expanded,hygiene", _) => PpmSource(PpmExpandedHygiene),
87         ("identified", _)   => PpmSource(PpmIdentified),
88         ("flowgraph", true)    => PpmFlowGraph(PpFlowGraphMode::Default),
89         ("flowgraph,unlabelled", true)    => PpmFlowGraph(PpFlowGraphMode::UnlabelledEdges),
90         _ => {
91             if extended {
92                 sess.fatal(&format!(
93                     "argument to `xpretty` must be one of `normal`, \
94                      `expanded`, `flowgraph[,unlabelled]=<nodeid>`, `typed`, `identified`, \
95                      `expanded,identified`, or `everybody_loops`; got {}", name));
96             } else {
97                 sess.fatal(&format!(
98                     "argument to `pretty` must be one of `normal`, \
99                      `expanded`, `typed`, `identified`, \
100                      or `expanded,identified`; got {}", name));
101             }
102         }
103     };
104     let opt_second = opt_second.and_then(|s| s.parse::<UserIdentifiedItem>().ok());
105     (first, opt_second)
106 }
107
108
109
110 // This slightly awkward construction is to allow for each PpMode to
111 // choose whether it needs to do analyses (which can consume the
112 // Session) and then pass through the session (now attached to the
113 // analysis results) on to the chosen pretty-printer, along with the
114 // `&PpAnn` object.
115 //
116 // Note that since the `&PrinterSupport` is freshly constructed on each
117 // call, it would not make sense to try to attach the lifetime of `self`
118 // to the lifetime of the `&PrinterObject`.
119 //
120 // (The `use_once_payload` is working around the current lack of once
121 // functions in the compiler.)
122
123 impl PpSourceMode {
124     /// Constructs a `PrinterSupport` object and passes it to `f`.
125     fn call_with_pp_support<'tcx, A, B, F>(&self,
126                                            sess: Session,
127                                            ast_map: Option<ast_map::Map<'tcx>>,
128                                            arenas: &'tcx ty::CtxtArenas<'tcx>,
129                                            id: String,
130                                            payload: B,
131                                            f: F) -> A where
132         F: FnOnce(&PrinterSupport, B) -> A,
133     {
134         match *self {
135             PpmNormal | PpmEveryBodyLoops | PpmExpanded => {
136                 let annotation = NoAnn { sess: sess, ast_map: ast_map };
137                 f(&annotation, payload)
138             }
139
140             PpmIdentified | PpmExpandedIdentified => {
141                 let annotation = IdentifiedAnnotation { sess: sess, ast_map: ast_map };
142                 f(&annotation, payload)
143             }
144             PpmExpandedHygiene => {
145                 let annotation = HygieneAnnotation { sess: sess, ast_map: ast_map };
146                 f(&annotation, payload)
147             }
148             PpmTyped => {
149                 let ast_map = ast_map.expect("--pretty=typed missing ast_map");
150                 let analysis = driver::phase_3_run_analysis_passes(sess,
151                                                                    ast_map,
152                                                                    arenas,
153                                                                    id,
154                                                                    resolve::MakeGlobMap::No);
155                 let annotation = TypedAnnotation { analysis: analysis };
156                 f(&annotation, payload)
157             }
158         }
159     }
160 }
161
162 trait PrinterSupport<'ast>: pprust::PpAnn {
163     /// Provides a uniform interface for re-extracting a reference to a
164     /// `Session` from a value that now owns it.
165     fn sess<'a>(&'a self) -> &'a Session;
166
167     /// Provides a uniform interface for re-extracting a reference to an
168     /// `ast_map::Map` from a value that now owns it.
169     fn ast_map<'a>(&'a self) -> Option<&'a ast_map::Map<'ast>>;
170
171     /// Produces the pretty-print annotation object.
172     ///
173     /// (Rust does not yet support upcasting from a trait object to
174     /// an object for one of its super-traits.)
175     fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn;
176 }
177
178 struct NoAnn<'ast> {
179     sess: Session,
180     ast_map: Option<ast_map::Map<'ast>>
181 }
182
183 impl<'ast> PrinterSupport<'ast> for NoAnn<'ast> {
184     fn sess<'a>(&'a self) -> &'a Session { &self.sess }
185
186     fn ast_map<'a>(&'a self) -> Option<&'a ast_map::Map<'ast>> {
187         self.ast_map.as_ref()
188     }
189
190     fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn { self }
191 }
192
193 impl<'ast> pprust::PpAnn for NoAnn<'ast> {}
194
195 struct IdentifiedAnnotation<'ast> {
196     sess: Session,
197     ast_map: Option<ast_map::Map<'ast>>,
198 }
199
200 impl<'ast> PrinterSupport<'ast> for IdentifiedAnnotation<'ast> {
201     fn sess<'a>(&'a self) -> &'a Session { &self.sess }
202
203     fn ast_map<'a>(&'a self) -> Option<&'a ast_map::Map<'ast>> {
204         self.ast_map.as_ref()
205     }
206
207     fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn { self }
208 }
209
210 impl<'ast> pprust::PpAnn for IdentifiedAnnotation<'ast> {
211     fn pre(&self,
212            s: &mut pprust::State,
213            node: pprust::AnnNode) -> io::Result<()> {
214         match node {
215             pprust::NodeExpr(_) => s.popen(),
216             _ => Ok(())
217         }
218     }
219     fn post(&self,
220             s: &mut pprust::State,
221             node: pprust::AnnNode) -> io::Result<()> {
222         match node {
223             pprust::NodeIdent(_) | pprust::NodeName(_) => Ok(()),
224
225             pprust::NodeItem(item) => {
226                 try!(pp::space(&mut s.s));
227                 s.synth_comment(item.id.to_string())
228             }
229             pprust::NodeBlock(blk) => {
230                 try!(pp::space(&mut s.s));
231                 s.synth_comment(format!("block {}", blk.id))
232             }
233             pprust::NodeExpr(expr) => {
234                 try!(pp::space(&mut s.s));
235                 try!(s.synth_comment(expr.id.to_string()));
236                 s.pclose()
237             }
238             pprust::NodePat(pat) => {
239                 try!(pp::space(&mut s.s));
240                 s.synth_comment(format!("pat {}", pat.id))
241             }
242         }
243     }
244 }
245
246 struct HygieneAnnotation<'ast> {
247     sess: Session,
248     ast_map: Option<ast_map::Map<'ast>>,
249 }
250
251 impl<'ast> PrinterSupport<'ast> for HygieneAnnotation<'ast> {
252     fn sess<'a>(&'a self) -> &'a Session { &self.sess }
253
254     fn ast_map<'a>(&'a self) -> Option<&'a ast_map::Map<'ast>> {
255         self.ast_map.as_ref()
256     }
257
258     fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn { self }
259 }
260
261 impl<'ast> pprust::PpAnn for HygieneAnnotation<'ast> {
262     fn post(&self,
263             s: &mut pprust::State,
264             node: pprust::AnnNode) -> io::Result<()> {
265         match node {
266             pprust::NodeIdent(&ast::Ident { name: ast::Name(nm), ctxt }) => {
267                 try!(pp::space(&mut s.s));
268                 // FIXME #16420: this doesn't display the connections
269                 // between syntax contexts
270                 s.synth_comment(format!("{}#{}", nm, ctxt))
271             }
272             pprust::NodeName(&ast::Name(nm)) => {
273                 try!(pp::space(&mut s.s));
274                 s.synth_comment(nm.to_string())
275             }
276             _ => Ok(())
277         }
278     }
279 }
280
281
282 struct TypedAnnotation<'tcx> {
283     analysis: ty::CrateAnalysis<'tcx>,
284 }
285
286 impl<'tcx> PrinterSupport<'tcx> for TypedAnnotation<'tcx> {
287     fn sess<'a>(&'a self) -> &'a Session { &self.analysis.ty_cx.sess }
288
289     fn ast_map<'a>(&'a self) -> Option<&'a ast_map::Map<'tcx>> {
290         Some(&self.analysis.ty_cx.map)
291     }
292
293     fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn { self }
294 }
295
296 impl<'tcx> pprust::PpAnn for TypedAnnotation<'tcx> {
297     fn pre(&self,
298            s: &mut pprust::State,
299            node: pprust::AnnNode) -> io::Result<()> {
300         match node {
301             pprust::NodeExpr(_) => s.popen(),
302             _ => Ok(())
303         }
304     }
305     fn post(&self,
306             s: &mut pprust::State,
307             node: pprust::AnnNode) -> io::Result<()> {
308         let tcx = &self.analysis.ty_cx;
309         match node {
310             pprust::NodeExpr(expr) => {
311                 try!(pp::space(&mut s.s));
312                 try!(pp::word(&mut s.s, "as"));
313                 try!(pp::space(&mut s.s));
314                 try!(pp::word(&mut s.s,
315                               &ppaux::ty_to_string(
316                                   tcx,
317                                   ty::expr_ty(tcx, expr))));
318                 s.pclose()
319             }
320             _ => Ok(())
321         }
322     }
323 }
324
325 fn gather_flowgraph_variants(sess: &Session) -> Vec<borrowck_dot::Variant> {
326     let print_loans = sess.opts.debugging_opts.flowgraph_print_loans;
327     let print_moves = sess.opts.debugging_opts.flowgraph_print_moves;
328     let print_assigns = sess.opts.debugging_opts.flowgraph_print_assigns;
329     let print_all = sess.opts.debugging_opts.flowgraph_print_all;
330     let mut variants = Vec::new();
331     if print_all || print_loans {
332         variants.push(borrowck_dot::Loans);
333     }
334     if print_all || print_moves {
335         variants.push(borrowck_dot::Moves);
336     }
337     if print_all || print_assigns {
338         variants.push(borrowck_dot::Assigns);
339     }
340     variants
341 }
342
343 #[derive(Clone, Debug)]
344 pub enum UserIdentifiedItem {
345     ItemViaNode(ast::NodeId),
346     ItemViaPath(Vec<String>),
347 }
348
349 impl FromStr for UserIdentifiedItem {
350     type Err = ();
351     fn from_str(s: &str) -> Result<UserIdentifiedItem, ()> {
352         Ok(s.parse().map(ItemViaNode).unwrap_or_else(|_| {
353             ItemViaPath(s.split("::").map(|s| s.to_string()).collect())
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 = 0;
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                 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<PathBuf>) {
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, 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
548                             .as_ref()
549                             .unwrap()
550                             .as_bytes()
551                             .to_vec();
552     let mut rdr = &src[..];
553
554     let mut out = Vec::new();
555
556     match (ppm, opt_uii) {
557         (PpmSource(s), None) => {
558             let out: &mut Write = &mut out;
559             s.call_with_pp_support(
560                 sess, ast_map, &arenas, id, box out, |annotation, out| {
561                     debug!("pretty printing source code {:?}", s);
562                     let sess = annotation.sess();
563                     pprust::print_crate(sess.codemap(),
564                                         sess.diagnostic(),
565                                         krate,
566                                         src_name.to_string(),
567                                         &mut rdr,
568                                         out,
569                                         annotation.pp_ann(),
570                                         is_expanded)
571             })
572         }
573
574         (PpmSource(s), Some(uii)) => {
575             let out: &mut Write = &mut out;
576             s.call_with_pp_support(
577                 sess, ast_map, &arenas, id, (out,uii), |annotation, (out,uii)| {
578                     debug!("pretty printing source code {:?}", s);
579                     let sess = annotation.sess();
580                     let ast_map = annotation.ast_map()
581                         .expect("--pretty missing ast_map");
582                     let mut pp_state =
583                         pprust::State::new_from_input(sess.codemap(),
584                                                       sess.diagnostic(),
585                                                       src_name.to_string(),
586                                                       &mut rdr,
587                                                       box out,
588                                                       annotation.pp_ann(),
589                                                       is_expanded);
590                     for node_id in uii.all_matching_node_ids(ast_map) {
591                         let node = ast_map.get(node_id);
592                         try!(pp_state.print_node(&node));
593                         try!(pp::space(&mut pp_state.s));
594                         try!(pp_state.synth_comment(ast_map.path_to_string(node_id)));
595                         try!(pp::hardbreak(&mut pp_state.s));
596                     }
597                     pp::eof(&mut pp_state.s)
598                 })
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             let out: &mut Write = &mut out;
618             match code {
619                 Some(code) => {
620                     let variants = gather_flowgraph_variants(&sess);
621                     let analysis = driver::phase_3_run_analysis_passes(sess,
622                                                                        ast_map,
623                                                                        &arenas,
624                                                                        id,
625                                                                        resolve::MakeGlobMap::No);
626                     print_flowgraph(variants, analysis, code, mode, out)
627                 }
628                 None => {
629                     let message = format!("--pretty=flowgraph needs \
630                                            block, fn, or method; got {:?}",
631                                           node);
632
633                     // point to what was found, if there's an
634                     // accessible span.
635                     match ast_map.opt_span(nodeid) {
636                         Some(sp) => sess.span_fatal(sp, &message[..]),
637                         None => sess.fatal(&message[..])
638                     }
639                 }
640             }
641         }
642     }.unwrap();
643
644     match ofile {
645         None => print!("{}", String::from_utf8(out).unwrap()),
646         Some(p) => {
647             match File::create(&p) {
648                 Ok(mut w) => w.write_all(&out).unwrap(),
649                 Err(e) => panic!("print-print failed to open {} due to {}",
650                                 p.display(), e),
651             }
652         }
653     }
654 }
655
656 fn print_flowgraph<W: Write>(variants: Vec<borrowck_dot::Variant>,
657                              analysis: ty::CrateAnalysis,
658                              code: blocks::Code,
659                              mode: PpFlowGraphMode,
660                              mut out: W) -> io::Result<()> {
661     let ty_cx = &analysis.ty_cx;
662     let cfg = match code {
663         blocks::BlockCode(block) => cfg::CFG::new(ty_cx, &*block),
664         blocks::FnLikeCode(fn_like) => cfg::CFG::new(ty_cx, &*fn_like.body()),
665     };
666     let labelled_edges = mode != PpFlowGraphMode::UnlabelledEdges;
667     let lcfg = LabelledCFG {
668         ast_map: &ty_cx.map,
669         cfg: &cfg,
670         name: format!("node_{}", code.id()),
671         labelled_edges: labelled_edges,
672     };
673
674     match code {
675         _ if variants.len() == 0 => {
676             let r = dot::render(&lcfg, &mut out);
677             return expand_err_details(r);
678         }
679         blocks::BlockCode(_) => {
680             ty_cx.sess.err("--pretty flowgraph with -Z flowgraph-print \
681                             annotations requires fn-like node id.");
682             return Ok(())
683         }
684         blocks::FnLikeCode(fn_like) => {
685             let fn_parts = borrowck::FnPartsWithCFG::from_fn_like(&fn_like, &cfg);
686             let (bccx, analysis_data) =
687                 borrowck::build_borrowck_dataflow_data_for_fn(ty_cx, fn_parts);
688
689             let lcfg = borrowck_dot::DataflowLabeller {
690                 inner: lcfg,
691                 variants: variants,
692                 borrowck_ctxt: &bccx,
693                 analysis_data: &analysis_data,
694             };
695             let r = dot::render(&lcfg, &mut out);
696             return expand_err_details(r);
697         }
698     }
699
700     fn expand_err_details(r: io::Result<()>) -> io::Result<()> {
701         r.map_err(|ioerr| {
702             io::Error::new(io::ErrorKind::Other, "graphviz::render failed",
703                            Some(ioerr.to_string()))
704         })
705     }
706 }