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