]> git.lizzy.rs Git - rust.git/blob - src/librustc_driver/pretty.rs
test for #50518
[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 crate::abort_on_err;
39
40 use crate::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| {
259             let hir_id = map.node_to_hir_id(id);
260             map.def_path_from_hir_id(hir_id)
261         }).map(|path| {
262             path.data
263                 .into_iter()
264                 .map(|elem| elem.data.to_string())
265                 .collect::<Vec<_>>()
266                 .join("::")
267         })
268     }
269 }
270
271 struct NoAnn<'hir> {
272     sess: &'hir Session,
273     tcx: Option<TyCtxt<'hir, 'hir, 'hir>>,
274 }
275
276 impl<'hir> PrinterSupport for NoAnn<'hir> {
277     fn sess<'a>(&'a self) -> &'a Session {
278         self.sess
279     }
280
281     fn pp_ann<'a>(&'a self) -> &'a dyn pprust::PpAnn {
282         self
283     }
284 }
285
286 impl<'hir> HirPrinterSupport<'hir> for NoAnn<'hir> {
287     fn sess<'a>(&'a self) -> &'a Session {
288         self.sess
289     }
290
291     fn hir_map<'a>(&'a self) -> Option<&'a hir_map::Map<'hir>> {
292         self.tcx.map(|tcx| tcx.hir())
293     }
294
295     fn pp_ann<'a>(&'a self) -> &'a dyn pprust_hir::PpAnn {
296         self
297     }
298 }
299
300 impl<'hir> pprust::PpAnn for NoAnn<'hir> {}
301 impl<'hir> pprust_hir::PpAnn for NoAnn<'hir> {
302     fn nested(&self, state: &mut pprust_hir::State<'_>, nested: pprust_hir::Nested)
303               -> io::Result<()> {
304         if let Some(tcx) = self.tcx {
305             pprust_hir::PpAnn::nested(tcx.hir(), state, nested)
306         } else {
307             Ok(())
308         }
309     }
310 }
311
312 struct IdentifiedAnnotation<'hir> {
313     sess: &'hir Session,
314     tcx: Option<TyCtxt<'hir, 'hir, 'hir>>,
315 }
316
317 impl<'hir> PrinterSupport for IdentifiedAnnotation<'hir> {
318     fn sess<'a>(&'a self) -> &'a Session {
319         self.sess
320     }
321
322     fn pp_ann<'a>(&'a self) -> &'a dyn pprust::PpAnn {
323         self
324     }
325 }
326
327 impl<'hir> pprust::PpAnn for IdentifiedAnnotation<'hir> {
328     fn pre(&self, s: &mut pprust::State<'_>, node: pprust::AnnNode<'_>) -> io::Result<()> {
329         match node {
330             pprust::AnnNode::Expr(_) => s.popen(),
331             _ => Ok(()),
332         }
333     }
334     fn post(&self, s: &mut pprust::State<'_>, node: pprust::AnnNode<'_>) -> io::Result<()> {
335         match node {
336             pprust::AnnNode::Ident(_) |
337             pprust::AnnNode::Name(_) => Ok(()),
338
339             pprust::AnnNode::Item(item) => {
340                 s.s.space()?;
341                 s.synth_comment(item.id.to_string())
342             }
343             pprust::AnnNode::SubItem(id) => {
344                 s.s.space()?;
345                 s.synth_comment(id.to_string())
346             }
347             pprust::AnnNode::Block(blk) => {
348                 s.s.space()?;
349                 s.synth_comment(format!("block {}", blk.id))
350             }
351             pprust::AnnNode::Expr(expr) => {
352                 s.s.space()?;
353                 s.synth_comment(expr.id.to_string())?;
354                 s.pclose()
355             }
356             pprust::AnnNode::Pat(pat) => {
357                 s.s.space()?;
358                 s.synth_comment(format!("pat {}", pat.id))
359             }
360         }
361     }
362 }
363
364 impl<'hir> HirPrinterSupport<'hir> for IdentifiedAnnotation<'hir> {
365     fn sess<'a>(&'a self) -> &'a Session {
366         self.sess
367     }
368
369     fn hir_map<'a>(&'a self) -> Option<&'a hir_map::Map<'hir>> {
370         self.tcx.map(|tcx| tcx.hir())
371     }
372
373     fn pp_ann<'a>(&'a self) -> &'a dyn pprust_hir::PpAnn {
374         self
375     }
376 }
377
378 impl<'hir> pprust_hir::PpAnn for IdentifiedAnnotation<'hir> {
379     fn nested(&self, state: &mut pprust_hir::State<'_>, nested: pprust_hir::Nested)
380               -> io::Result<()> {
381         if let Some(ref tcx) = self.tcx {
382             pprust_hir::PpAnn::nested(tcx.hir(), state, nested)
383         } else {
384             Ok(())
385         }
386     }
387     fn pre(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) -> io::Result<()> {
388         match node {
389             pprust_hir::AnnNode::Expr(_) => s.popen(),
390             _ => Ok(()),
391         }
392     }
393     fn post(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) -> io::Result<()> {
394         match node {
395             pprust_hir::AnnNode::Name(_) => Ok(()),
396             pprust_hir::AnnNode::Item(item) => {
397                 s.s.space()?;
398                 s.synth_comment(format!("hir_id: {} hir local_id: {}",
399                                         item.hir_id, item.hir_id.local_id.as_u32()))
400             }
401             pprust_hir::AnnNode::SubItem(id) => {
402                 s.s.space()?;
403                 s.synth_comment(id.to_string())
404             }
405             pprust_hir::AnnNode::Block(blk) => {
406                 s.s.space()?;
407                 s.synth_comment(format!("block hir_id: {} hir local_id: {}",
408                                         blk.hir_id, blk.hir_id.local_id.as_u32()))
409             }
410             pprust_hir::AnnNode::Expr(expr) => {
411                 s.s.space()?;
412                 s.synth_comment(format!("expr hir_id: {} hir local_id: {}",
413                                         expr.hir_id, expr.hir_id.local_id.as_u32()))?;
414                 s.pclose()
415             }
416             pprust_hir::AnnNode::Pat(pat) => {
417                 s.s.space()?;
418                 s.synth_comment(format!("pat hir_id: {} hir local_id: {}",
419                                         pat.hir_id, pat.hir_id.local_id.as_u32()))
420             }
421         }
422     }
423 }
424
425 struct HygieneAnnotation<'a> {
426     sess: &'a Session
427 }
428
429 impl<'a> PrinterSupport for HygieneAnnotation<'a> {
430     fn sess(&self) -> &Session {
431         self.sess
432     }
433
434     fn pp_ann(&self) -> &dyn pprust::PpAnn {
435         self
436     }
437 }
438
439 impl<'a> pprust::PpAnn for HygieneAnnotation<'a> {
440     fn post(&self, s: &mut pprust::State<'_>, node: pprust::AnnNode<'_>) -> io::Result<()> {
441         match node {
442             pprust::AnnNode::Ident(&ast::Ident { name, span }) => {
443                 s.s.space()?;
444                 // FIXME #16420: this doesn't display the connections
445                 // between syntax contexts
446                 s.synth_comment(format!("{}{:?}", name.as_u32(), span.ctxt()))
447             }
448             pprust::AnnNode::Name(&name) => {
449                 s.s.space()?;
450                 s.synth_comment(name.as_u32().to_string())
451             }
452             _ => Ok(()),
453         }
454     }
455 }
456
457
458 struct TypedAnnotation<'a, 'tcx: 'a> {
459     tcx: TyCtxt<'a, 'tcx, 'tcx>,
460     tables: Cell<&'a ty::TypeckTables<'tcx>>,
461 }
462
463 impl<'b, 'tcx> HirPrinterSupport<'tcx> for TypedAnnotation<'b, 'tcx> {
464     fn sess<'a>(&'a self) -> &'a Session {
465         &self.tcx.sess
466     }
467
468     fn hir_map<'a>(&'a self) -> Option<&'a hir_map::Map<'tcx>> {
469         Some(&self.tcx.hir())
470     }
471
472     fn pp_ann<'a>(&'a self) -> &'a dyn pprust_hir::PpAnn {
473         self
474     }
475
476     fn node_path(&self, id: ast::NodeId) -> Option<String> {
477         Some(self.tcx.def_path_str(self.tcx.hir().local_def_id(id)))
478     }
479 }
480
481 impl<'a, 'tcx> pprust_hir::PpAnn for TypedAnnotation<'a, 'tcx> {
482     fn nested(&self, state: &mut pprust_hir::State<'_>, nested: pprust_hir::Nested)
483               -> io::Result<()> {
484         let old_tables = self.tables.get();
485         if let pprust_hir::Nested::Body(id) = nested {
486             self.tables.set(self.tcx.body_tables(id));
487         }
488         pprust_hir::PpAnn::nested(self.tcx.hir(), state, nested)?;
489         self.tables.set(old_tables);
490         Ok(())
491     }
492     fn pre(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) -> io::Result<()> {
493         match node {
494             pprust_hir::AnnNode::Expr(_) => s.popen(),
495             _ => Ok(()),
496         }
497     }
498     fn post(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) -> io::Result<()> {
499         match node {
500             pprust_hir::AnnNode::Expr(expr) => {
501                 s.s.space()?;
502                 s.s.word("as")?;
503                 s.s.space()?;
504                 s.s.word(self.tables.get().expr_ty(expr).to_string())?;
505                 s.pclose()
506             }
507             _ => Ok(()),
508         }
509     }
510 }
511
512 fn gather_flowgraph_variants(sess: &Session) -> Vec<borrowck_dot::Variant> {
513     let print_loans = sess.opts.debugging_opts.flowgraph_print_loans;
514     let print_moves = sess.opts.debugging_opts.flowgraph_print_moves;
515     let print_assigns = sess.opts.debugging_opts.flowgraph_print_assigns;
516     let print_all = sess.opts.debugging_opts.flowgraph_print_all;
517     let mut variants = Vec::new();
518     if print_all || print_loans {
519         variants.push(borrowck_dot::Loans);
520     }
521     if print_all || print_moves {
522         variants.push(borrowck_dot::Moves);
523     }
524     if print_all || print_assigns {
525         variants.push(borrowck_dot::Assigns);
526     }
527     variants
528 }
529
530 #[derive(Clone, Debug)]
531 pub enum UserIdentifiedItem {
532     ItemViaNode(ast::NodeId),
533     ItemViaPath(Vec<String>),
534 }
535
536 impl FromStr for UserIdentifiedItem {
537     type Err = ();
538     fn from_str(s: &str) -> Result<UserIdentifiedItem, ()> {
539         Ok(s.parse()
540             .map(ast::NodeId::from_u32)
541             .map(ItemViaNode)
542             .unwrap_or_else(|_| ItemViaPath(s.split("::").map(|s| s.to_string()).collect())))
543     }
544 }
545
546 enum NodesMatchingUII<'a, 'hir: 'a> {
547     NodesMatchingDirect(option::IntoIter<ast::NodeId>),
548     NodesMatchingSuffix(hir_map::NodesMatchingSuffix<'a, 'hir>),
549 }
550
551 impl<'a, 'hir> Iterator for NodesMatchingUII<'a, 'hir> {
552     type Item = ast::NodeId;
553
554     fn next(&mut self) -> Option<ast::NodeId> {
555         match self {
556             &mut NodesMatchingDirect(ref mut iter) => iter.next(),
557             &mut NodesMatchingSuffix(ref mut iter) => iter.next(),
558         }
559     }
560
561     fn size_hint(&self) -> (usize, Option<usize>) {
562         match self {
563             &NodesMatchingDirect(ref iter) => iter.size_hint(),
564             &NodesMatchingSuffix(ref iter) => iter.size_hint(),
565         }
566     }
567 }
568
569 impl UserIdentifiedItem {
570     fn reconstructed_input(&self) -> String {
571         match *self {
572             ItemViaNode(node_id) => node_id.to_string(),
573             ItemViaPath(ref parts) => parts.join("::"),
574         }
575     }
576
577     fn all_matching_node_ids<'a, 'hir>(&'a self,
578                                        map: &'a hir_map::Map<'hir>)
579                                        -> NodesMatchingUII<'a, 'hir> {
580         match *self {
581             ItemViaNode(node_id) => NodesMatchingDirect(Some(node_id).into_iter()),
582             ItemViaPath(ref parts) => NodesMatchingSuffix(map.nodes_matching_suffix(&parts)),
583         }
584     }
585
586     fn to_one_node_id(self,
587                       user_option: &str,
588                       sess: &Session,
589                       map: &hir_map::Map<'_>)
590                       -> ast::NodeId {
591         let fail_because = |is_wrong_because| -> ast::NodeId {
592             let message = format!("{} needs NodeId (int) or unique path suffix (b::c::d); got \
593                                    {}, which {}",
594                                   user_option,
595                                   self.reconstructed_input(),
596                                   is_wrong_because);
597             sess.fatal(&message)
598         };
599
600         let mut saw_node = ast::DUMMY_NODE_ID;
601         let mut seen = 0;
602         for node in self.all_matching_node_ids(map) {
603             saw_node = node;
604             seen += 1;
605             if seen > 1 {
606                 fail_because("does not resolve uniquely");
607             }
608         }
609         if seen == 0 {
610             fail_because("does not resolve to any item");
611         }
612
613         assert!(seen == 1);
614         return saw_node;
615     }
616 }
617
618 fn print_flowgraph<'a, 'tcx, W: Write>(variants: Vec<borrowck_dot::Variant>,
619                                        tcx: TyCtxt<'a, 'tcx, 'tcx>,
620                                        code: blocks::Code<'tcx>,
621                                        mode: PpFlowGraphMode,
622                                        mut out: W)
623                                        -> io::Result<()> {
624     let body_id = match code {
625         blocks::Code::Expr(expr) => {
626             // Find the function this expression is from.
627             let mut hir_id = expr.hir_id;
628             loop {
629                 let node = tcx.hir().get_by_hir_id(hir_id);
630                 if let Some(n) = hir::map::blocks::FnLikeNode::from_node(node) {
631                     break n.body();
632                 }
633                 let parent = tcx.hir().get_parent_node_by_hir_id(hir_id);
634                 assert_ne!(hir_id, parent);
635                 hir_id = parent;
636             }
637         }
638         blocks::Code::FnLike(fn_like) => fn_like.body(),
639     };
640     let body = tcx.hir().body(body_id);
641     let cfg = cfg::CFG::new(tcx, &body);
642     let labelled_edges = mode != PpFlowGraphMode::UnlabelledEdges;
643     let hir_id = code.id();
644     // We have to disassemble the hir_id because name must be ASCII
645     // alphanumeric. This does not appear in the rendered graph, so it does not
646     // have to be user friendly.
647     let name = format!(
648         "hir_id_{}_{}_{}",
649         hir_id.owner.address_space().index(),
650         hir_id.owner.as_array_index(),
651         hir_id.local_id.index(),
652     );
653     let lcfg = LabelledCFG {
654         tcx,
655         cfg: &cfg,
656         name,
657         labelled_edges,
658     };
659
660     match code {
661         _ if variants.is_empty() => {
662             let r = dot::render(&lcfg, &mut out);
663             return expand_err_details(r);
664         }
665         blocks::Code::Expr(_) => {
666             tcx.sess.err("--pretty flowgraph with -Z flowgraph-print annotations requires \
667                           fn-like node id.");
668             return Ok(());
669         }
670         blocks::Code::FnLike(fn_like) => {
671             let (bccx, analysis_data) =
672                 borrowck::build_borrowck_dataflow_data_for_fn(tcx, fn_like.body(), &cfg);
673
674             let lcfg = borrowck_dot::DataflowLabeller {
675                 inner: lcfg,
676                 variants,
677                 borrowck_ctxt: &bccx,
678                 analysis_data: &analysis_data,
679             };
680             let r = dot::render(&lcfg, &mut out);
681             return expand_err_details(r);
682         }
683     }
684
685     fn expand_err_details(r: io::Result<()>) -> io::Result<()> {
686         r.map_err(|ioerr| {
687             io::Error::new(io::ErrorKind::Other,
688                            format!("graphviz::render failed: {}", ioerr))
689         })
690     }
691 }
692
693 pub fn visit_crate(sess: &Session, krate: &mut ast::Crate, ppm: PpMode) {
694     if let PpmSource(PpmEveryBodyLoops) = ppm {
695         ReplaceBodyWithLoop::new(sess).visit_crate(krate);
696     }
697 }
698
699 fn get_source(input: &Input, sess: &Session) -> (Vec<u8>, FileName) {
700     let src_name = source_name(input);
701     let src = sess.source_map()
702         .get_source_file(&src_name)
703         .unwrap()
704         .src
705         .as_ref()
706         .unwrap()
707         .as_bytes()
708         .to_vec();
709     (src, src_name)
710 }
711
712 fn write_output(out: Vec<u8>, ofile: Option<&Path>) {
713     match ofile {
714         None => print!("{}", String::from_utf8(out).unwrap()),
715         Some(p) => {
716             match File::create(p) {
717                 Ok(mut w) => w.write_all(&out).unwrap(),
718                 Err(e) => panic!("print-print failed to open {} due to {}", p.display(), e),
719             }
720         }
721     }
722 }
723
724 pub fn print_after_parsing(sess: &Session,
725                            input: &Input,
726                            krate: &ast::Crate,
727                            ppm: PpMode,
728                            ofile: Option<&Path>) {
729     let (src, src_name) = get_source(input, sess);
730
731     let mut rdr = &*src;
732     let mut out = Vec::new();
733
734     if let PpmSource(s) = ppm {
735         // Silently ignores an identified node.
736         let out: &mut dyn Write = &mut out;
737         s.call_with_pp_support(sess, None, move |annotation| {
738             debug!("pretty printing source code {:?}", s);
739             let sess = annotation.sess();
740             pprust::print_crate(sess.source_map(),
741                                 &sess.parse_sess,
742                                 krate,
743                                 src_name,
744                                 &mut rdr,
745                                 box out,
746                                 annotation.pp_ann(),
747                                 false)
748         }).unwrap()
749     } else {
750         unreachable!();
751     };
752
753     write_output(out, ofile);
754 }
755
756 pub fn print_after_hir_lowering<'tcx>(
757     tcx: TyCtxt<'tcx, 'tcx, 'tcx>,
758     input: &Input,
759     krate: &ast::Crate,
760     ppm: PpMode,
761     opt_uii: Option<UserIdentifiedItem>,
762     ofile: Option<&Path>) {
763     if ppm.needs_analysis() {
764         abort_on_err(print_with_analysis(
765             tcx,
766             ppm,
767             opt_uii,
768             ofile
769         ), tcx.sess);
770         return;
771     }
772
773     let (src, src_name) = get_source(input, tcx.sess);
774
775     let mut rdr = &src[..];
776     let mut out = Vec::new();
777
778     match (ppm, opt_uii) {
779             (PpmSource(s), _) => {
780                 // Silently ignores an identified node.
781                 let out: &mut dyn Write = &mut out;
782                 s.call_with_pp_support(tcx.sess, Some(tcx), move |annotation| {
783                     debug!("pretty printing source code {:?}", s);
784                     let sess = annotation.sess();
785                     pprust::print_crate(sess.source_map(),
786                                         &sess.parse_sess,
787                                         krate,
788                                         src_name,
789                                         &mut rdr,
790                                         box out,
791                                         annotation.pp_ann(),
792                                         true)
793                 })
794             }
795
796             (PpmHir(s), None) => {
797                 let out: &mut dyn Write = &mut out;
798                 s.call_with_pp_support_hir(tcx, move |annotation, krate| {
799                     debug!("pretty printing source code {:?}", s);
800                     let sess = annotation.sess();
801                     pprust_hir::print_crate(sess.source_map(),
802                                             &sess.parse_sess,
803                                             krate,
804                                             src_name,
805                                             &mut rdr,
806                                             box out,
807                                             annotation.pp_ann(),
808                                             true)
809                 })
810             }
811
812             (PpmHirTree(s), None) => {
813                 let out: &mut dyn Write = &mut out;
814                 s.call_with_pp_support_hir(tcx, move |_annotation, krate| {
815                     debug!("pretty printing source code {:?}", s);
816                     write!(out, "{:#?}", krate)
817                 })
818             }
819
820             (PpmHir(s), Some(uii)) => {
821                 let out: &mut dyn Write = &mut out;
822                 s.call_with_pp_support_hir(tcx, move |annotation, _| {
823                     debug!("pretty printing source code {:?}", s);
824                     let sess = annotation.sess();
825                     let hir_map = annotation.hir_map().expect("-Z unpretty missing HIR map");
826                     let mut pp_state = pprust_hir::State::new_from_input(sess.source_map(),
827                                                                          &sess.parse_sess,
828                                                                          src_name,
829                                                                          &mut rdr,
830                                                                          box out,
831                                                                          annotation.pp_ann(),
832                                                                          true);
833                     for node_id in uii.all_matching_node_ids(hir_map) {
834                         let node = hir_map.get(node_id);
835                         pp_state.print_node(node)?;
836                         pp_state.s.space()?;
837                         let path = annotation.node_path(node_id)
838                             .expect("-Z unpretty missing node paths");
839                         pp_state.synth_comment(path)?;
840                         pp_state.s.hardbreak()?;
841                     }
842                     pp_state.s.eof()
843                 })
844             }
845
846             (PpmHirTree(s), Some(uii)) => {
847                 let out: &mut dyn Write = &mut out;
848                 s.call_with_pp_support_hir(tcx, move |_annotation, _krate| {
849                     debug!("pretty printing source code {:?}", s);
850                     for node_id in uii.all_matching_node_ids(tcx.hir()) {
851                         let node = tcx.hir().get(node_id);
852                         write!(out, "{:#?}", node)?;
853                     }
854                     Ok(())
855                 })
856             }
857
858             _ => unreachable!(),
859         }
860         .unwrap();
861
862     write_output(out, ofile);
863 }
864
865 // In an ideal world, this would be a public function called by the driver after
866 // analysis is performed. However, we want to call `phase_3_run_analysis_passes`
867 // with a different callback than the standard driver, so that isn't easy.
868 // Instead, we call that function ourselves.
869 fn print_with_analysis<'tcx>(
870     tcx: TyCtxt<'_, 'tcx, 'tcx>,
871     ppm: PpMode,
872     uii: Option<UserIdentifiedItem>,
873     ofile: Option<&Path>
874 ) -> Result<(), ErrorReported> {
875     let nodeid = if let Some(uii) = uii {
876         debug!("pretty printing for {:?}", uii);
877         Some(uii.to_one_node_id("-Z unpretty", tcx.sess, tcx.hir()))
878     } else {
879         debug!("pretty printing for whole crate");
880         None
881     };
882
883     let mut out = Vec::new();
884
885     tcx.analysis(LOCAL_CRATE)?;
886
887     let mut print = || match ppm {
888         PpmMir | PpmMirCFG => {
889             if let Some(nodeid) = nodeid {
890                 let def_id = tcx.hir().local_def_id(nodeid);
891                 match ppm {
892                     PpmMir => write_mir_pretty(tcx, Some(def_id), &mut out),
893                     PpmMirCFG => write_mir_graphviz(tcx, Some(def_id), &mut out),
894                     _ => unreachable!(),
895                 }?;
896             } else {
897                 match ppm {
898                     PpmMir => write_mir_pretty(tcx, None, &mut out),
899                     PpmMirCFG => write_mir_graphviz(tcx, None, &mut out),
900                     _ => unreachable!(),
901                 }?;
902             }
903             Ok(())
904         }
905         PpmFlowGraph(mode) => {
906             let nodeid =
907                 nodeid.expect("`pretty flowgraph=..` needs NodeId (int) or unique path \
908                                 suffix (b::c::d)");
909             let node = tcx.hir().find(nodeid).unwrap_or_else(|| {
910                 tcx.sess.fatal(&format!("--pretty flowgraph couldn't find id: {}", nodeid))
911             });
912
913             match blocks::Code::from_node(&tcx.hir(), nodeid) {
914                 Some(code) => {
915                     let variants = gather_flowgraph_variants(tcx.sess);
916
917                     let out: &mut dyn Write = &mut out;
918
919                     print_flowgraph(variants, tcx, code, mode, out)
920                 }
921                 None => {
922                     let message = format!("--pretty=flowgraph needs block, fn, or method; \
923                                             got {:?}",
924                                             node);
925
926                     tcx.sess.span_fatal(tcx.hir().span(nodeid), &message)
927                 }
928             }
929         }
930         _ => unreachable!(),
931     };
932
933     print().unwrap();
934
935     write_output(out, ofile);
936
937     Ok(())
938 }