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