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