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