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