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