]> git.lizzy.rs Git - rust.git/blob - src/librustc_driver/pretty.rs
Auto merge of #61722 - eddyb:vowel-exclusion-zone, r=oli-obk
[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>(
158         &self,
159         sess: &'tcx Session,
160         tcx: Option<TyCtxt<'tcx, 'tcx>>,
161         f: F,
162     ) -> A
163     where
164         F: FnOnce(&dyn PrinterSupport) -> A,
165     {
166         match *self {
167             PpmNormal | PpmEveryBodyLoops | PpmExpanded => {
168                 let annotation = NoAnn {
169                     sess,
170                     tcx,
171                 };
172                 f(&annotation)
173             }
174
175             PpmIdentified | PpmExpandedIdentified => {
176                 let annotation = IdentifiedAnnotation {
177                     sess,
178                     tcx,
179                 };
180                 f(&annotation)
181             }
182             PpmExpandedHygiene => {
183                 let annotation = HygieneAnnotation {
184                     sess,
185                 };
186                 f(&annotation)
187             }
188             _ => panic!("Should use call_with_pp_support_hir"),
189         }
190     }
191     fn call_with_pp_support_hir<'tcx, A, F>(&self, tcx: TyCtxt<'tcx, 'tcx>, f: F) -> A
192     where
193         F: FnOnce(&dyn HirPrinterSupport<'_>, &hir::Crate) -> A,
194     {
195         match *self {
196             PpmNormal => {
197                 let annotation = NoAnn {
198                     sess: tcx.sess,
199                     tcx: Some(tcx),
200                 };
201                 f(&annotation, tcx.hir().forest.krate())
202             }
203
204             PpmIdentified => {
205                 let annotation = IdentifiedAnnotation {
206                     sess: tcx.sess,
207                     tcx: Some(tcx),
208                 };
209                 f(&annotation, tcx.hir().forest.krate())
210             }
211             PpmTyped => {
212                 abort_on_err(tcx.analysis(LOCAL_CRATE), tcx.sess);
213
214                 let empty_tables = ty::TypeckTables::empty(None);
215                 let annotation = TypedAnnotation {
216                     tcx,
217                     tables: Cell::new(&empty_tables)
218                 };
219                 tcx.dep_graph.with_ignore(|| {
220                     f(&annotation, tcx.hir().forest.krate())
221                 })
222             }
223             _ => panic!("Should use call_with_pp_support"),
224         }
225     }
226 }
227
228 trait PrinterSupport: pprust::PpAnn {
229     /// Provides a uniform interface for re-extracting a reference to a
230     /// `Session` from a value that now owns it.
231     fn sess<'a>(&'a self) -> &'a Session;
232
233     /// Produces the pretty-print annotation object.
234     ///
235     /// (Rust does not yet support upcasting from a trait object to
236     /// an object for one of its super-traits.)
237     fn pp_ann<'a>(&'a self) -> &'a dyn pprust::PpAnn;
238 }
239
240 trait HirPrinterSupport<'hir>: pprust_hir::PpAnn {
241     /// Provides a uniform interface for re-extracting a reference to a
242     /// `Session` from a value that now owns it.
243     fn sess<'a>(&'a self) -> &'a Session;
244
245     /// Provides a uniform interface for re-extracting a reference to an
246     /// `hir_map::Map` from a value that now owns it.
247     fn hir_map<'a>(&'a self) -> Option<&'a hir_map::Map<'hir>>;
248
249     /// Produces the pretty-print annotation object.
250     ///
251     /// (Rust does not yet support upcasting from a trait object to
252     /// an object for one of its super-traits.)
253     fn pp_ann<'a>(&'a self) -> &'a dyn pprust_hir::PpAnn;
254
255     /// Computes an user-readable representation of a path, if possible.
256     fn node_path(&self, id: ast::NodeId) -> Option<String> {
257         self.hir_map().and_then(|map| {
258             let hir_id = map.node_to_hir_id(id);
259             map.def_path_from_hir_id(hir_id)
260         }).map(|path| {
261             path.data
262                 .into_iter()
263                 .map(|elem| elem.data.to_string())
264                 .collect::<Vec<_>>()
265                 .join("::")
266         })
267     }
268 }
269
270 struct NoAnn<'hir> {
271     sess: &'hir Session,
272     tcx: Option<TyCtxt<'hir, 'hir>>,
273 }
274
275 impl<'hir> PrinterSupport for NoAnn<'hir> {
276     fn sess<'a>(&'a self) -> &'a Session {
277         self.sess
278     }
279
280     fn pp_ann<'a>(&'a self) -> &'a dyn pprust::PpAnn {
281         self
282     }
283 }
284
285 impl<'hir> HirPrinterSupport<'hir> for NoAnn<'hir> {
286     fn sess<'a>(&'a self) -> &'a Session {
287         self.sess
288     }
289
290     fn hir_map<'a>(&'a self) -> Option<&'a hir_map::Map<'hir>> {
291         self.tcx.map(|tcx| tcx.hir())
292     }
293
294     fn pp_ann<'a>(&'a self) -> &'a dyn pprust_hir::PpAnn {
295         self
296     }
297 }
298
299 impl<'hir> pprust::PpAnn for NoAnn<'hir> {}
300 impl<'hir> pprust_hir::PpAnn for NoAnn<'hir> {
301     fn nested(&self, state: &mut pprust_hir::State<'_>, nested: pprust_hir::Nested)
302               -> io::Result<()> {
303         if let Some(tcx) = self.tcx {
304             pprust_hir::PpAnn::nested(tcx.hir(), state, nested)
305         } else {
306             Ok(())
307         }
308     }
309 }
310
311 struct IdentifiedAnnotation<'hir> {
312     sess: &'hir Session,
313     tcx: Option<TyCtxt<'hir, 'hir>>,
314 }
315
316 impl<'hir> PrinterSupport for IdentifiedAnnotation<'hir> {
317     fn sess<'a>(&'a self) -> &'a Session {
318         self.sess
319     }
320
321     fn pp_ann<'a>(&'a self) -> &'a dyn pprust::PpAnn {
322         self
323     }
324 }
325
326 impl<'hir> pprust::PpAnn for IdentifiedAnnotation<'hir> {
327     fn pre(&self, s: &mut pprust::State<'_>, node: pprust::AnnNode<'_>) -> io::Result<()> {
328         match node {
329             pprust::AnnNode::Expr(_) => s.popen(),
330             _ => Ok(()),
331         }
332     }
333     fn post(&self, s: &mut pprust::State<'_>, node: pprust::AnnNode<'_>) -> io::Result<()> {
334         match node {
335             pprust::AnnNode::Ident(_) |
336             pprust::AnnNode::Name(_) => Ok(()),
337
338             pprust::AnnNode::Item(item) => {
339                 s.s.space()?;
340                 s.synth_comment(item.id.to_string())
341             }
342             pprust::AnnNode::SubItem(id) => {
343                 s.s.space()?;
344                 s.synth_comment(id.to_string())
345             }
346             pprust::AnnNode::Block(blk) => {
347                 s.s.space()?;
348                 s.synth_comment(format!("block {}", blk.id))
349             }
350             pprust::AnnNode::Expr(expr) => {
351                 s.s.space()?;
352                 s.synth_comment(expr.id.to_string())?;
353                 s.pclose()
354             }
355             pprust::AnnNode::Pat(pat) => {
356                 s.s.space()?;
357                 s.synth_comment(format!("pat {}", pat.id))
358             }
359         }
360     }
361 }
362
363 impl<'hir> HirPrinterSupport<'hir> for IdentifiedAnnotation<'hir> {
364     fn sess<'a>(&'a self) -> &'a Session {
365         self.sess
366     }
367
368     fn hir_map<'a>(&'a self) -> Option<&'a hir_map::Map<'hir>> {
369         self.tcx.map(|tcx| tcx.hir())
370     }
371
372     fn pp_ann<'a>(&'a self) -> &'a dyn pprust_hir::PpAnn {
373         self
374     }
375 }
376
377 impl<'hir> pprust_hir::PpAnn for IdentifiedAnnotation<'hir> {
378     fn nested(&self, state: &mut pprust_hir::State<'_>, nested: pprust_hir::Nested)
379               -> io::Result<()> {
380         if let Some(ref tcx) = self.tcx {
381             pprust_hir::PpAnn::nested(tcx.hir(), state, nested)
382         } else {
383             Ok(())
384         }
385     }
386     fn pre(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) -> io::Result<()> {
387         match node {
388             pprust_hir::AnnNode::Expr(_) => s.popen(),
389             _ => Ok(()),
390         }
391     }
392     fn post(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) -> io::Result<()> {
393         match node {
394             pprust_hir::AnnNode::Name(_) => Ok(()),
395             pprust_hir::AnnNode::Item(item) => {
396                 s.s.space()?;
397                 s.synth_comment(format!("hir_id: {} hir local_id: {}",
398                                         item.hir_id, item.hir_id.local_id.as_u32()))
399             }
400             pprust_hir::AnnNode::SubItem(id) => {
401                 s.s.space()?;
402                 s.synth_comment(id.to_string())
403             }
404             pprust_hir::AnnNode::Block(blk) => {
405                 s.s.space()?;
406                 s.synth_comment(format!("block hir_id: {} hir local_id: {}",
407                                         blk.hir_id, blk.hir_id.local_id.as_u32()))
408             }
409             pprust_hir::AnnNode::Expr(expr) => {
410                 s.s.space()?;
411                 s.synth_comment(format!("expr hir_id: {} hir local_id: {}",
412                                         expr.hir_id, expr.hir_id.local_id.as_u32()))?;
413                 s.pclose()
414             }
415             pprust_hir::AnnNode::Pat(pat) => {
416                 s.s.space()?;
417                 s.synth_comment(format!("pat hir_id: {} hir local_id: {}",
418                                         pat.hir_id, pat.hir_id.local_id.as_u32()))
419             }
420         }
421     }
422 }
423
424 struct HygieneAnnotation<'a> {
425     sess: &'a Session
426 }
427
428 impl<'a> PrinterSupport for HygieneAnnotation<'a> {
429     fn sess(&self) -> &Session {
430         self.sess
431     }
432
433     fn pp_ann(&self) -> &dyn pprust::PpAnn {
434         self
435     }
436 }
437
438 impl<'a> pprust::PpAnn for HygieneAnnotation<'a> {
439     fn post(&self, s: &mut pprust::State<'_>, node: pprust::AnnNode<'_>) -> io::Result<()> {
440         match node {
441             pprust::AnnNode::Ident(&ast::Ident { name, span }) => {
442                 s.s.space()?;
443                 // FIXME #16420: this doesn't display the connections
444                 // between syntax contexts
445                 s.synth_comment(format!("{}{:?}", name.as_u32(), span.ctxt()))
446             }
447             pprust::AnnNode::Name(&name) => {
448                 s.s.space()?;
449                 s.synth_comment(name.as_u32().to_string())
450             }
451             _ => Ok(()),
452         }
453     }
454 }
455
456 struct TypedAnnotation<'a, 'tcx: 'a> {
457     tcx: TyCtxt<'tcx, 'tcx>,
458     tables: Cell<&'a ty::TypeckTables<'tcx>>,
459 }
460
461 impl<'b, 'tcx> HirPrinterSupport<'tcx> for TypedAnnotation<'b, 'tcx> {
462     fn sess<'a>(&'a self) -> &'a Session {
463         &self.tcx.sess
464     }
465
466     fn hir_map<'a>(&'a self) -> Option<&'a hir_map::Map<'tcx>> {
467         Some(&self.tcx.hir())
468     }
469
470     fn pp_ann<'a>(&'a self) -> &'a dyn pprust_hir::PpAnn {
471         self
472     }
473
474     fn node_path(&self, id: ast::NodeId) -> Option<String> {
475         Some(self.tcx.def_path_str(self.tcx.hir().local_def_id(id)))
476     }
477 }
478
479 impl<'a, 'tcx> pprust_hir::PpAnn for TypedAnnotation<'a, 'tcx> {
480     fn nested(&self, state: &mut pprust_hir::State<'_>, nested: pprust_hir::Nested)
481               -> io::Result<()> {
482         let old_tables = self.tables.get();
483         if let pprust_hir::Nested::Body(id) = nested {
484             self.tables.set(self.tcx.body_tables(id));
485         }
486         pprust_hir::PpAnn::nested(self.tcx.hir(), state, nested)?;
487         self.tables.set(old_tables);
488         Ok(())
489     }
490     fn pre(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) -> io::Result<()> {
491         match node {
492             pprust_hir::AnnNode::Expr(_) => s.popen(),
493             _ => Ok(()),
494         }
495     }
496     fn post(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) -> io::Result<()> {
497         match node {
498             pprust_hir::AnnNode::Expr(expr) => {
499                 s.s.space()?;
500                 s.s.word("as")?;
501                 s.s.space()?;
502                 s.s.word(self.tables.get().expr_ty(expr).to_string())?;
503                 s.pclose()
504             }
505             _ => Ok(()),
506         }
507     }
508 }
509
510 fn gather_flowgraph_variants(sess: &Session) -> Vec<borrowck_dot::Variant> {
511     let print_loans = sess.opts.debugging_opts.flowgraph_print_loans;
512     let print_moves = sess.opts.debugging_opts.flowgraph_print_moves;
513     let print_assigns = sess.opts.debugging_opts.flowgraph_print_assigns;
514     let print_all = sess.opts.debugging_opts.flowgraph_print_all;
515     let mut variants = Vec::new();
516     if print_all || print_loans {
517         variants.push(borrowck_dot::Loans);
518     }
519     if print_all || print_moves {
520         variants.push(borrowck_dot::Moves);
521     }
522     if print_all || print_assigns {
523         variants.push(borrowck_dot::Assigns);
524     }
525     variants
526 }
527
528 #[derive(Clone, Debug)]
529 pub enum UserIdentifiedItem {
530     ItemViaNode(ast::NodeId),
531     ItemViaPath(Vec<String>),
532 }
533
534 impl FromStr for UserIdentifiedItem {
535     type Err = ();
536     fn from_str(s: &str) -> Result<UserIdentifiedItem, ()> {
537         Ok(s.parse()
538             .map(ast::NodeId::from_u32)
539             .map(ItemViaNode)
540             .unwrap_or_else(|_| ItemViaPath(s.split("::").map(|s| s.to_string()).collect())))
541     }
542 }
543
544 enum NodesMatchingUII<'a> {
545     NodesMatchingDirect(option::IntoIter<ast::NodeId>),
546     NodesMatchingSuffix(Box<dyn Iterator<Item = ast::NodeId> + 'a>),
547 }
548
549 impl<'a> Iterator for NodesMatchingUII<'a> {
550     type Item = ast::NodeId;
551
552     fn next(&mut self) -> Option<ast::NodeId> {
553         match self {
554             &mut NodesMatchingDirect(ref mut iter) => iter.next(),
555             &mut NodesMatchingSuffix(ref mut iter) => iter.next(),
556         }
557     }
558
559     fn size_hint(&self) -> (usize, Option<usize>) {
560         match self {
561             &NodesMatchingDirect(ref iter) => iter.size_hint(),
562             &NodesMatchingSuffix(ref iter) => iter.size_hint(),
563         }
564     }
565 }
566
567 impl UserIdentifiedItem {
568     fn reconstructed_input(&self) -> String {
569         match *self {
570             ItemViaNode(node_id) => node_id.to_string(),
571             ItemViaPath(ref parts) => parts.join("::"),
572         }
573     }
574
575     fn all_matching_node_ids<'a, 'hir>(&'a self,
576                                        map: &'a hir_map::Map<'hir>)
577                                        -> NodesMatchingUII<'a> {
578         match *self {
579             ItemViaNode(node_id) => NodesMatchingDirect(Some(node_id).into_iter()),
580             ItemViaPath(ref parts) => {
581                 NodesMatchingSuffix(Box::new(map.nodes_matching_suffix(&parts)))
582             }
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<'tcx, W: Write>(
619     variants: Vec<borrowck_dot::Variant>,
620     tcx: TyCtxt<'tcx, 'tcx>,
621     code: blocks::Code<'tcx>,
622     mode: PpFlowGraphMode,
623     mut out: W,
624 ) -> io::Result<()> {
625     let body_id = match code {
626         blocks::Code::Expr(expr) => {
627             // Find the function this expression is from.
628             let mut hir_id = expr.hir_id;
629             loop {
630                 let node = tcx.hir().get_by_hir_id(hir_id);
631                 if let Some(n) = hir::map::blocks::FnLikeNode::from_node(node) {
632                     break n.body();
633                 }
634                 let parent = tcx.hir().get_parent_node_by_hir_id(hir_id);
635                 assert_ne!(hir_id, parent);
636                 hir_id = parent;
637             }
638         }
639         blocks::Code::FnLike(fn_like) => fn_like.body(),
640     };
641     let body = tcx.hir().body(body_id);
642     let cfg = cfg::CFG::new(tcx, &body);
643     let labelled_edges = mode != PpFlowGraphMode::UnlabelledEdges;
644     let hir_id = code.id();
645     // We have to disassemble the hir_id because name must be ASCII
646     // alphanumeric. This does not appear in the rendered graph, so it does not
647     // have to be user friendly.
648     let name = format!(
649         "hir_id_{}_{}",
650         hir_id.owner.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>,
758     input: &Input,
759     krate: &ast::Crate,
760     ppm: PpMode,
761     opt_uii: Option<UserIdentifiedItem>,
762     ofile: Option<&Path>,
763 ) {
764     if ppm.needs_analysis() {
765         abort_on_err(print_with_analysis(
766             tcx,
767             ppm,
768             opt_uii,
769             ofile
770         ), tcx.sess);
771         return;
772     }
773
774     let (src, src_name) = get_source(input, tcx.sess);
775
776     let mut rdr = &src[..];
777     let mut out = Vec::new();
778
779     match (ppm, opt_uii) {
780             (PpmSource(s), _) => {
781                 // Silently ignores an identified node.
782                 let out: &mut dyn Write = &mut out;
783                 s.call_with_pp_support(tcx.sess, Some(tcx), move |annotation| {
784                     debug!("pretty printing source code {:?}", s);
785                     let sess = annotation.sess();
786                     pprust::print_crate(sess.source_map(),
787                                         &sess.parse_sess,
788                                         krate,
789                                         src_name,
790                                         &mut rdr,
791                                         box out,
792                                         annotation.pp_ann(),
793                                         true)
794                 })
795             }
796
797             (PpmHir(s), None) => {
798                 let out: &mut dyn Write = &mut out;
799                 s.call_with_pp_support_hir(tcx, move |annotation, krate| {
800                     debug!("pretty printing source code {:?}", s);
801                     let sess = annotation.sess();
802                     pprust_hir::print_crate(sess.source_map(),
803                                             &sess.parse_sess,
804                                             krate,
805                                             src_name,
806                                             &mut rdr,
807                                             box out,
808                                             annotation.pp_ann())
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                     for node_id in uii.all_matching_node_ids(hir_map) {
833                         let node = hir_map.get(node_id);
834                         pp_state.print_node(node)?;
835                         pp_state.s.space()?;
836                         let path = annotation.node_path(node_id)
837                             .expect("-Z unpretty missing node paths");
838                         pp_state.synth_comment(path)?;
839                         pp_state.s.hardbreak()?;
840                     }
841                     pp_state.s.eof()
842                 })
843             }
844
845             (PpmHirTree(s), Some(uii)) => {
846                 let out: &mut dyn Write = &mut out;
847                 s.call_with_pp_support_hir(tcx, move |_annotation, _krate| {
848                     debug!("pretty printing source code {:?}", s);
849                     for node_id in uii.all_matching_node_ids(tcx.hir()) {
850                         let node = tcx.hir().get(node_id);
851                         write!(out, "{:#?}", node)?;
852                     }
853                     Ok(())
854                 })
855             }
856
857             _ => unreachable!(),
858         }
859         .unwrap();
860
861     write_output(out, ofile);
862 }
863
864 // In an ideal world, this would be a public function called by the driver after
865 // analysis is performed. However, we want to call `phase_3_run_analysis_passes`
866 // with a different callback than the standard driver, so that isn't easy.
867 // Instead, we call that function ourselves.
868 fn print_with_analysis<'tcx>(
869     tcx: TyCtxt<'tcx, 'tcx>,
870     ppm: PpMode,
871     uii: Option<UserIdentifiedItem>,
872     ofile: Option<&Path>,
873 ) -> Result<(), ErrorReported> {
874     let nodeid = if let Some(uii) = uii {
875         debug!("pretty printing for {:?}", uii);
876         Some(uii.to_one_node_id("-Z unpretty", tcx.sess, tcx.hir()))
877     } else {
878         debug!("pretty printing for whole crate");
879         None
880     };
881
882     let mut out = Vec::new();
883
884     tcx.analysis(LOCAL_CRATE)?;
885
886     let mut print = || match ppm {
887         PpmMir | PpmMirCFG => {
888             if let Some(nodeid) = nodeid {
889                 let def_id = tcx.hir().local_def_id(nodeid);
890                 match ppm {
891                     PpmMir => write_mir_pretty(tcx, Some(def_id), &mut out),
892                     PpmMirCFG => write_mir_graphviz(tcx, Some(def_id), &mut out),
893                     _ => unreachable!(),
894                 }?;
895             } else {
896                 match ppm {
897                     PpmMir => write_mir_pretty(tcx, None, &mut out),
898                     PpmMirCFG => write_mir_graphviz(tcx, None, &mut out),
899                     _ => unreachable!(),
900                 }?;
901             }
902             Ok(())
903         }
904         PpmFlowGraph(mode) => {
905             let nodeid =
906                 nodeid.expect("`pretty flowgraph=..` needs NodeId (int) or unique path \
907                                 suffix (b::c::d)");
908             let node = tcx.hir().find(nodeid).unwrap_or_else(|| {
909                 tcx.sess.fatal(&format!("--pretty flowgraph couldn't find id: {}", nodeid))
910             });
911
912             match blocks::Code::from_node(&tcx.hir(), nodeid) {
913                 Some(code) => {
914                     let variants = gather_flowgraph_variants(tcx.sess);
915
916                     let out: &mut dyn Write = &mut out;
917
918                     print_flowgraph(variants, tcx, code, mode, out)
919                 }
920                 None => {
921                     let message = format!("--pretty=flowgraph needs block, fn, or method; \
922                                             got {:?}",
923                                             node);
924
925                     tcx.sess.span_fatal(tcx.hir().span(nodeid), &message)
926                 }
927             }
928         }
929         _ => unreachable!(),
930     };
931
932     print().unwrap();
933
934     write_output(out, ofile);
935
936     Ok(())
937 }