]> git.lizzy.rs Git - rust.git/blob - src/librustc_driver/pretty.rs
Rollup merge of #27374 - dhuseby:fixing_configure_bsd, r=alexcrichton
[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::ast_map::{self, blocks, NodePrinter};
23 use rustc::middle::ty;
24 use rustc::middle::cfg;
25 use rustc::middle::cfg::graphviz::LabelledCFG;
26 use rustc::session::Session;
27 use rustc::session::config::Input;
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::codemap;
34 use syntax::fold::{self, Folder};
35 use syntax::print::{pp, pprust};
36 use syntax::ptr::P;
37 use syntax::util::small_vector::SmallVector;
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, Clone, 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, Clone, 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, Clone, 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(2, '=');
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                 driver::phase_3_run_analysis_passes(sess,
151                                                     ast_map,
152                                                     arenas,
153                                                     id,
154                                                     resolve::MakeGlobMap::No,
155                                                     |tcx, _| {
156                     let annotation = TypedAnnotation { tcx: tcx };
157                     f(&annotation, payload)
158                 }).1
159             }
160         }
161     }
162 }
163
164 trait PrinterSupport<'ast>: pprust::PpAnn {
165     /// Provides a uniform interface for re-extracting a reference to a
166     /// `Session` from a value that now owns it.
167     fn sess<'a>(&'a self) -> &'a Session;
168
169     /// Provides a uniform interface for re-extracting a reference to an
170     /// `ast_map::Map` from a value that now owns it.
171     fn ast_map<'a>(&'a self) -> Option<&'a ast_map::Map<'ast>>;
172
173     /// Produces the pretty-print annotation object.
174     ///
175     /// (Rust does not yet support upcasting from a trait object to
176     /// an object for one of its super-traits.)
177     fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn;
178 }
179
180 struct NoAnn<'ast> {
181     sess: Session,
182     ast_map: Option<ast_map::Map<'ast>>
183 }
184
185 impl<'ast> PrinterSupport<'ast> for NoAnn<'ast> {
186     fn sess<'a>(&'a self) -> &'a Session { &self.sess }
187
188     fn ast_map<'a>(&'a self) -> Option<&'a ast_map::Map<'ast>> {
189         self.ast_map.as_ref()
190     }
191
192     fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn { self }
193 }
194
195 impl<'ast> pprust::PpAnn for NoAnn<'ast> {}
196
197 struct IdentifiedAnnotation<'ast> {
198     sess: Session,
199     ast_map: Option<ast_map::Map<'ast>>,
200 }
201
202 impl<'ast> PrinterSupport<'ast> for IdentifiedAnnotation<'ast> {
203     fn sess<'a>(&'a self) -> &'a Session { &self.sess }
204
205     fn ast_map<'a>(&'a self) -> Option<&'a ast_map::Map<'ast>> {
206         self.ast_map.as_ref()
207     }
208
209     fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn { self }
210 }
211
212 impl<'ast> pprust::PpAnn for IdentifiedAnnotation<'ast> {
213     fn pre(&self,
214            s: &mut pprust::State,
215            node: pprust::AnnNode) -> io::Result<()> {
216         match node {
217             pprust::NodeExpr(_) => s.popen(),
218             _ => Ok(())
219         }
220     }
221     fn post(&self,
222             s: &mut pprust::State,
223             node: pprust::AnnNode) -> io::Result<()> {
224         match node {
225             pprust::NodeIdent(_) | pprust::NodeName(_) => Ok(()),
226
227             pprust::NodeItem(item) => {
228                 try!(pp::space(&mut s.s));
229                 s.synth_comment(item.id.to_string())
230             }
231             pprust::NodeSubItem(id) => {
232                 try!(pp::space(&mut s.s));
233                 s.synth_comment(id.to_string())
234             }
235             pprust::NodeBlock(blk) => {
236                 try!(pp::space(&mut s.s));
237                 s.synth_comment(format!("block {}", blk.id))
238             }
239             pprust::NodeExpr(expr) => {
240                 try!(pp::space(&mut s.s));
241                 try!(s.synth_comment(expr.id.to_string()));
242                 s.pclose()
243             }
244             pprust::NodePat(pat) => {
245                 try!(pp::space(&mut s.s));
246                 s.synth_comment(format!("pat {}", pat.id))
247             }
248         }
249     }
250 }
251
252 struct HygieneAnnotation<'ast> {
253     sess: Session,
254     ast_map: Option<ast_map::Map<'ast>>,
255 }
256
257 impl<'ast> PrinterSupport<'ast> for HygieneAnnotation<'ast> {
258     fn sess<'a>(&'a self) -> &'a Session { &self.sess }
259
260     fn ast_map<'a>(&'a self) -> Option<&'a ast_map::Map<'ast>> {
261         self.ast_map.as_ref()
262     }
263
264     fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn { self }
265 }
266
267 impl<'ast> pprust::PpAnn for HygieneAnnotation<'ast> {
268     fn post(&self,
269             s: &mut pprust::State,
270             node: pprust::AnnNode) -> io::Result<()> {
271         match node {
272             pprust::NodeIdent(&ast::Ident { name: ast::Name(nm), ctxt }) => {
273                 try!(pp::space(&mut s.s));
274                 // FIXME #16420: this doesn't display the connections
275                 // between syntax contexts
276                 s.synth_comment(format!("{}#{}", nm, ctxt))
277             }
278             pprust::NodeName(&ast::Name(nm)) => {
279                 try!(pp::space(&mut s.s));
280                 s.synth_comment(nm.to_string())
281             }
282             _ => Ok(())
283         }
284     }
285 }
286
287
288 struct TypedAnnotation<'a, 'tcx: 'a> {
289     tcx: &'a ty::ctxt<'tcx>,
290 }
291
292 impl<'b, 'tcx> PrinterSupport<'tcx> for TypedAnnotation<'b, 'tcx> {
293     fn sess<'a>(&'a self) -> &'a Session { &self.tcx.sess }
294
295     fn ast_map<'a>(&'a self) -> Option<&'a ast_map::Map<'tcx>> {
296         Some(&self.tcx.map)
297     }
298
299     fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn { self }
300 }
301
302 impl<'a, 'tcx> pprust::PpAnn for TypedAnnotation<'a, 'tcx> {
303     fn pre(&self,
304            s: &mut pprust::State,
305            node: pprust::AnnNode) -> io::Result<()> {
306         match node {
307             pprust::NodeExpr(_) => s.popen(),
308             _ => Ok(())
309         }
310     }
311     fn post(&self,
312             s: &mut pprust::State,
313             node: pprust::AnnNode) -> io::Result<()> {
314         match node {
315             pprust::NodeExpr(expr) => {
316                 try!(pp::space(&mut s.s));
317                 try!(pp::word(&mut s.s, "as"));
318                 try!(pp::space(&mut s.s));
319                 try!(pp::word(&mut s.s,
320                               &self.tcx.expr_ty(expr).to_string()));
321                 s.pclose()
322             }
323             _ => Ok(())
324         }
325     }
326 }
327
328 fn gather_flowgraph_variants(sess: &Session) -> Vec<borrowck_dot::Variant> {
329     let print_loans = sess.opts.debugging_opts.flowgraph_print_loans;
330     let print_moves = sess.opts.debugging_opts.flowgraph_print_moves;
331     let print_assigns = sess.opts.debugging_opts.flowgraph_print_assigns;
332     let print_all = sess.opts.debugging_opts.flowgraph_print_all;
333     let mut variants = Vec::new();
334     if print_all || print_loans {
335         variants.push(borrowck_dot::Loans);
336     }
337     if print_all || print_moves {
338         variants.push(borrowck_dot::Moves);
339     }
340     if print_all || print_assigns {
341         variants.push(borrowck_dot::Assigns);
342     }
343     variants
344 }
345
346 #[derive(Clone, Debug)]
347 pub enum UserIdentifiedItem {
348     ItemViaNode(ast::NodeId),
349     ItemViaPath(Vec<String>),
350 }
351
352 impl FromStr for UserIdentifiedItem {
353     type Err = ();
354     fn from_str(s: &str) -> Result<UserIdentifiedItem, ()> {
355         Ok(s.parse().map(ItemViaNode).unwrap_or_else(|_| {
356             ItemViaPath(s.split("::").map(|s| s.to_string()).collect())
357         }))
358     }
359 }
360
361 enum NodesMatchingUII<'a, 'ast: 'a> {
362     NodesMatchingDirect(option::IntoIter<ast::NodeId>),
363     NodesMatchingSuffix(ast_map::NodesMatchingSuffix<'a, 'ast>),
364 }
365
366 impl<'a, 'ast> Iterator for NodesMatchingUII<'a, 'ast> {
367     type Item = ast::NodeId;
368
369     fn next(&mut self) -> Option<ast::NodeId> {
370         match self {
371             &mut NodesMatchingDirect(ref mut iter) => iter.next(),
372             &mut NodesMatchingSuffix(ref mut iter) => iter.next(),
373         }
374     }
375 }
376
377 impl UserIdentifiedItem {
378     fn reconstructed_input(&self) -> String {
379         match *self {
380             ItemViaNode(node_id) => node_id.to_string(),
381             ItemViaPath(ref parts) => parts.join("::"),
382         }
383     }
384
385     fn all_matching_node_ids<'a, 'ast>(&'a self, map: &'a ast_map::Map<'ast>)
386                                        -> NodesMatchingUII<'a, 'ast> {
387         match *self {
388             ItemViaNode(node_id) =>
389                 NodesMatchingDirect(Some(node_id).into_iter()),
390             ItemViaPath(ref parts) =>
391                 NodesMatchingSuffix(map.nodes_matching_suffix(&parts[..])),
392         }
393     }
394
395     fn to_one_node_id(self, user_option: &str, sess: &Session, map: &ast_map::Map) -> ast::NodeId {
396         let fail_because = |is_wrong_because| -> ast::NodeId {
397             let message =
398                 format!("{} needs NodeId (int) or unique \
399                          path suffix (b::c::d); got {}, which {}",
400                         user_option,
401                         self.reconstructed_input(),
402                         is_wrong_because);
403             sess.fatal(&message[..])
404         };
405
406         let mut saw_node = ast::DUMMY_NODE_ID;
407         let mut seen = 0;
408         for node in self.all_matching_node_ids(map) {
409             saw_node = node;
410             seen += 1;
411             if seen > 1 {
412                 fail_because("does not resolve uniquely");
413             }
414         }
415         if seen == 0 {
416             fail_because("does not resolve to any item");
417         }
418
419         assert!(seen == 1);
420         return saw_node;
421     }
422 }
423
424 fn needs_ast_map(ppm: &PpMode, opt_uii: &Option<UserIdentifiedItem>) -> bool {
425     match *ppm {
426         PpmSource(PpmNormal) |
427         PpmSource(PpmEveryBodyLoops) |
428         PpmSource(PpmIdentified) => opt_uii.is_some(),
429
430         PpmSource(PpmExpanded) |
431         PpmSource(PpmExpandedIdentified) |
432         PpmSource(PpmExpandedHygiene) |
433         PpmSource(PpmTyped) |
434         PpmFlowGraph(_) => true
435     }
436 }
437
438 fn needs_expansion(ppm: &PpMode) -> bool {
439     match *ppm {
440         PpmSource(PpmNormal) |
441         PpmSource(PpmEveryBodyLoops) |
442         PpmSource(PpmIdentified) => false,
443
444         PpmSource(PpmExpanded) |
445         PpmSource(PpmExpandedIdentified) |
446         PpmSource(PpmExpandedHygiene) |
447         PpmSource(PpmTyped) |
448         PpmFlowGraph(_) => true
449     }
450 }
451
452 struct ReplaceBodyWithLoop {
453     within_static_or_const: bool,
454 }
455
456 impl ReplaceBodyWithLoop {
457     fn new() -> ReplaceBodyWithLoop {
458         ReplaceBodyWithLoop { within_static_or_const: false }
459     }
460 }
461
462 impl fold::Folder for ReplaceBodyWithLoop {
463     fn fold_item_underscore(&mut self, i: ast::Item_) -> ast::Item_ {
464         match i {
465             ast::ItemStatic(..) | ast::ItemConst(..) => {
466                 self.within_static_or_const = true;
467                 let ret = fold::noop_fold_item_underscore(i, self);
468                 self.within_static_or_const = false;
469                 return ret;
470             }
471             _ => {
472                 fold::noop_fold_item_underscore(i, self)
473             }
474         }
475     }
476
477     fn fold_trait_item(&mut self, i: P<ast::TraitItem>) -> SmallVector<P<ast::TraitItem>> {
478         match i.node {
479             ast::ConstTraitItem(..) => {
480                 self.within_static_or_const = true;
481                 let ret = fold::noop_fold_trait_item(i, self);
482                 self.within_static_or_const = false;
483                 return ret;
484             }
485             _ => fold::noop_fold_trait_item(i, self),
486         }
487     }
488
489     fn fold_impl_item(&mut self, i: P<ast::ImplItem>) -> SmallVector<P<ast::ImplItem>> {
490         match i.node {
491             ast::ConstImplItem(..) => {
492                 self.within_static_or_const = true;
493                 let ret = fold::noop_fold_impl_item(i, self);
494                 self.within_static_or_const = false;
495                 return ret;
496             }
497             _ => fold::noop_fold_impl_item(i, self),
498         }
499     }
500
501     fn fold_block(&mut self, b: P<ast::Block>) -> P<ast::Block> {
502         fn expr_to_block(rules: ast::BlockCheckMode,
503                          e: Option<P<ast::Expr>>) -> P<ast::Block> {
504             P(ast::Block {
505                 expr: e,
506                 stmts: vec![], rules: rules,
507                 id: ast::DUMMY_NODE_ID, span: codemap::DUMMY_SP,
508             })
509         }
510
511         if !self.within_static_or_const {
512
513             let empty_block = expr_to_block(ast::DefaultBlock, None);
514             let loop_expr = P(ast::Expr {
515                 node: ast::ExprLoop(empty_block, None),
516                 id: ast::DUMMY_NODE_ID, span: codemap::DUMMY_SP
517             });
518
519             expr_to_block(b.rules, Some(loop_expr))
520
521         } else {
522             fold::noop_fold_block(b, self)
523         }
524     }
525
526     // in general the pretty printer processes unexpanded code, so
527     // we override the default `fold_mac` method which panics.
528     fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac {
529         fold::noop_fold_mac(mac, self)
530     }
531 }
532
533 pub fn pretty_print_input(sess: Session,
534                           cfg: ast::CrateConfig,
535                           input: &Input,
536                           ppm: PpMode,
537                           opt_uii: Option<UserIdentifiedItem>,
538                           ofile: Option<PathBuf>) {
539     let krate = driver::phase_1_parse_input(&sess, cfg, input);
540
541     let krate = if let PpmSource(PpmEveryBodyLoops) = ppm {
542         let mut fold = ReplaceBodyWithLoop::new();
543         fold.fold_crate(krate)
544     } else {
545         krate
546     };
547
548     let id = link::find_crate_name(Some(&sess), &krate.attrs, input);
549
550     let is_expanded = needs_expansion(&ppm);
551     let compute_ast_map = needs_ast_map(&ppm, &opt_uii);
552     let krate = if compute_ast_map {
553         match driver::phase_2_configure_and_expand(&sess, krate, &id[..], None) {
554             None => return,
555             Some(k) => k
556         }
557     } else {
558         krate
559     };
560
561     let mut forest = ast_map::Forest::new(krate);
562     let arenas = ty::CtxtArenas::new();
563
564     let (krate, ast_map) = if compute_ast_map {
565         let map = driver::assign_node_ids_and_map(&sess, &mut forest);
566         (map.krate(), Some(map))
567     } else {
568         (forest.krate(), None)
569     };
570
571     let src_name = driver::source_name(input);
572     let src = sess.codemap().get_filemap(&src_name[..])
573                             .src
574                             .as_ref()
575                             .unwrap()
576                             .as_bytes()
577                             .to_vec();
578     let mut rdr = &src[..];
579
580     let mut out = Vec::new();
581
582     match (ppm, opt_uii) {
583         (PpmSource(s), None) => {
584             let out: &mut Write = &mut out;
585             s.call_with_pp_support(
586                 sess, ast_map, &arenas, id, box out, |annotation, out| {
587                     debug!("pretty printing source code {:?}", s);
588                     let sess = annotation.sess();
589                     pprust::print_crate(sess.codemap(),
590                                         sess.diagnostic(),
591                                         krate,
592                                         src_name.to_string(),
593                                         &mut rdr,
594                                         out,
595                                         annotation.pp_ann(),
596                                         is_expanded)
597             })
598         }
599
600         (PpmSource(s), Some(uii)) => {
601             let out: &mut Write = &mut out;
602             s.call_with_pp_support(
603                 sess, ast_map, &arenas, id, (out,uii), |annotation, (out,uii)| {
604                     debug!("pretty printing source code {:?}", s);
605                     let sess = annotation.sess();
606                     let ast_map = annotation.ast_map()
607                         .expect("--pretty missing ast_map");
608                     let mut pp_state =
609                         pprust::State::new_from_input(sess.codemap(),
610                                                       sess.diagnostic(),
611                                                       src_name.to_string(),
612                                                       &mut rdr,
613                                                       box out,
614                                                       annotation.pp_ann(),
615                                                       is_expanded);
616                     for node_id in uii.all_matching_node_ids(ast_map) {
617                         let node = ast_map.get(node_id);
618                         try!(pp_state.print_node(&node));
619                         try!(pp::space(&mut pp_state.s));
620                         try!(pp_state.synth_comment(ast_map.path_to_string(node_id)));
621                         try!(pp::hardbreak(&mut pp_state.s));
622                     }
623                     pp::eof(&mut pp_state.s)
624                 })
625         }
626
627         (PpmFlowGraph(mode), opt_uii) => {
628             debug!("pretty printing flow graph for {:?}", opt_uii);
629             let uii = opt_uii.unwrap_or_else(|| {
630                 sess.fatal(&format!("`pretty flowgraph=..` needs NodeId (int) or
631                                      unique path suffix (b::c::d)"))
632
633             });
634             let ast_map = ast_map.expect("--pretty flowgraph missing ast_map");
635             let nodeid = uii.to_one_node_id("--pretty", &sess, &ast_map);
636
637             let node = ast_map.find(nodeid).unwrap_or_else(|| {
638                 sess.fatal(&format!("--pretty flowgraph couldn't find id: {}",
639                                    nodeid))
640             });
641
642             let code = blocks::Code::from_node(node);
643             let out: &mut Write = &mut out;
644             match code {
645                 Some(code) => {
646                     let variants = gather_flowgraph_variants(&sess);
647                     driver::phase_3_run_analysis_passes(sess,
648                                                         ast_map,
649                                                         &arenas,
650                                                         id,
651                                                         resolve::MakeGlobMap::No,
652                                                         |tcx, _| {
653                         print_flowgraph(variants, tcx, code, mode, out)
654                     }).1
655                 }
656                 None => {
657                     let message = format!("--pretty=flowgraph needs \
658                                            block, fn, or method; got {:?}",
659                                           node);
660
661                     // point to what was found, if there's an
662                     // accessible span.
663                     match ast_map.opt_span(nodeid) {
664                         Some(sp) => sess.span_fatal(sp, &message[..]),
665                         None => sess.fatal(&message[..])
666                     }
667                 }
668             }
669         }
670     }.unwrap();
671
672     match ofile {
673         None => print!("{}", String::from_utf8(out).unwrap()),
674         Some(p) => {
675             match File::create(&p) {
676                 Ok(mut w) => w.write_all(&out).unwrap(),
677                 Err(e) => panic!("print-print failed to open {} due to {}",
678                                 p.display(), e),
679             }
680         }
681     }
682 }
683
684 fn print_flowgraph<W: Write>(variants: Vec<borrowck_dot::Variant>,
685                              tcx: &ty::ctxt,
686                              code: blocks::Code,
687                              mode: PpFlowGraphMode,
688                              mut out: W) -> io::Result<()> {
689     let cfg = match code {
690         blocks::BlockCode(block) => cfg::CFG::new(tcx, &*block),
691         blocks::FnLikeCode(fn_like) => cfg::CFG::new(tcx, &*fn_like.body()),
692     };
693     let labelled_edges = mode != PpFlowGraphMode::UnlabelledEdges;
694     let lcfg = LabelledCFG {
695         ast_map: &tcx.map,
696         cfg: &cfg,
697         name: format!("node_{}", code.id()),
698         labelled_edges: labelled_edges,
699     };
700
701     match code {
702         _ if variants.is_empty() => {
703             let r = dot::render(&lcfg, &mut out);
704             return expand_err_details(r);
705         }
706         blocks::BlockCode(_) => {
707             tcx.sess.err("--pretty flowgraph with -Z flowgraph-print \
708                           annotations requires fn-like node id.");
709             return Ok(())
710         }
711         blocks::FnLikeCode(fn_like) => {
712             let fn_parts = borrowck::FnPartsWithCFG::from_fn_like(&fn_like, &cfg);
713             let (bccx, analysis_data) =
714                 borrowck::build_borrowck_dataflow_data_for_fn(tcx, fn_parts);
715
716             let lcfg = borrowck_dot::DataflowLabeller {
717                 inner: lcfg,
718                 variants: variants,
719                 borrowck_ctxt: &bccx,
720                 analysis_data: &analysis_data,
721             };
722             let r = dot::render(&lcfg, &mut out);
723             return expand_err_details(r);
724         }
725     }
726
727     fn expand_err_details(r: io::Result<()>) -> io::Result<()> {
728         r.map_err(|ioerr| {
729             io::Error::new(io::ErrorKind::Other,
730                            &format!("graphviz::render failed: {}", ioerr)[..])
731         })
732     }
733 }