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