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