1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! The various pretty print routines.
13 pub use self::UserIdentifiedItem::*;
14 pub use self::PpSourceMode::*;
15 pub use self::PpMode::*;
16 use self::NodesMatchingUII::*;
18 use {abort_on_err, driver};
20 use rustc::ty::{self, TyCtxt, GlobalArenas, Resolutions};
22 use rustc::cfg::graphviz::LabelledCFG;
23 use rustc::dep_graph::DepGraph;
24 use rustc::session::Session;
25 use rustc::session::config::Input;
26 use rustc_borrowck as borrowck;
27 use rustc_borrowck::graphviz as borrowck_dot;
29 use rustc_mir::util::{write_mir_pretty, write_mir_graphviz};
31 use syntax::ast::{self, BlockCheckMode};
32 use syntax::fold::{self, Folder};
33 use syntax::print::{pp, pprust};
34 use syntax::print::pprust::PrintState;
36 use syntax::util::small_vector::SmallVector;
43 use std::io::{self, Write};
47 use std::str::FromStr;
49 use rustc::hir::map as hir_map;
50 use rustc::hir::map::blocks;
52 use rustc::hir::print as pprust_hir;
54 use arena::DroplessArena;
56 #[derive(Copy, Clone, PartialEq, Debug)]
57 pub enum PpSourceMode {
62 PpmExpandedIdentified,
67 #[derive(Copy, Clone, PartialEq, Debug)]
68 pub enum PpFlowGraphMode {
70 /// Drops the labels from the edges in the flowgraph output. This
71 /// is mostly for use in the --unpretty flowgraph run-make tests,
72 /// since the labels are largely uninteresting in those cases and
73 /// have become a pain to maintain.
76 #[derive(Copy, Clone, PartialEq, Debug)]
78 PpmSource(PpSourceMode),
80 PpmFlowGraph(PpFlowGraphMode),
86 pub fn needs_ast_map(&self, opt_uii: &Option<UserIdentifiedItem>) -> bool {
88 PpmSource(PpmNormal) |
89 PpmSource(PpmEveryBodyLoops) |
90 PpmSource(PpmIdentified) => opt_uii.is_some(),
92 PpmSource(PpmExpanded) |
93 PpmSource(PpmExpandedIdentified) |
94 PpmSource(PpmExpandedHygiene) |
98 PpmFlowGraph(_) => true,
99 PpmSource(PpmTyped) => panic!("invalid state"),
103 pub fn needs_analysis(&self) -> bool {
105 PpmMir | PpmMirCFG | PpmFlowGraph(_) => true,
111 pub fn parse_pretty(sess: &Session,
114 -> (PpMode, Option<UserIdentifiedItem>) {
115 let mut split = name.splitn(2, '=');
116 let first = split.next().unwrap();
117 let opt_second = split.next();
118 let first = match (first, extended) {
119 ("normal", _) => PpmSource(PpmNormal),
120 ("identified", _) => PpmSource(PpmIdentified),
121 ("everybody_loops", true) => PpmSource(PpmEveryBodyLoops),
122 ("expanded", _) => PpmSource(PpmExpanded),
123 ("expanded,identified", _) => PpmSource(PpmExpandedIdentified),
124 ("expanded,hygiene", _) => PpmSource(PpmExpandedHygiene),
125 ("hir", true) => PpmHir(PpmNormal),
126 ("hir,identified", true) => PpmHir(PpmIdentified),
127 ("hir,typed", true) => PpmHir(PpmTyped),
128 ("mir", true) => PpmMir,
129 ("mir-cfg", true) => PpmMirCFG,
130 ("flowgraph", true) => PpmFlowGraph(PpFlowGraphMode::Default),
131 ("flowgraph,unlabelled", true) => PpmFlowGraph(PpFlowGraphMode::UnlabelledEdges),
134 sess.fatal(&format!("argument to `unpretty` must be one of `normal`, \
135 `expanded`, `flowgraph[,unlabelled]=<nodeid>`, \
136 `identified`, `expanded,identified`, `everybody_loops`, \
137 `hir`, `hir,identified`, `hir,typed`, or `mir`; got {}",
140 sess.fatal(&format!("argument to `pretty` must be one of `normal`, `expanded`, \
141 `identified`, or `expanded,identified`; got {}",
146 let opt_second = opt_second.and_then(|s| s.parse::<UserIdentifiedItem>().ok());
152 // This slightly awkward construction is to allow for each PpMode to
153 // choose whether it needs to do analyses (which can consume the
154 // Session) and then pass through the session (now attached to the
155 // analysis results) on to the chosen pretty-printer, along with the
158 // Note that since the `&PrinterSupport` is freshly constructed on each
159 // call, it would not make sense to try to attach the lifetime of `self`
160 // to the lifetime of the `&PrinterObject`.
162 // (The `use_once_payload` is working around the current lack of once
163 // functions in the compiler.)
166 /// Constructs a `PrinterSupport` object and passes it to `f`.
167 fn call_with_pp_support<'tcx, A, B, F>(&self,
169 hir_map: Option<&hir_map::Map<'tcx>>,
173 where F: FnOnce(&PrinterSupport, B) -> A
176 PpmNormal | PpmEveryBodyLoops | PpmExpanded => {
177 let annotation = NoAnn {
179 hir_map: hir_map.map(|m| m.clone()),
181 f(&annotation, payload)
184 PpmIdentified | PpmExpandedIdentified => {
185 let annotation = IdentifiedAnnotation {
187 hir_map: hir_map.map(|m| m.clone()),
189 f(&annotation, payload)
191 PpmExpandedHygiene => {
192 let annotation = HygieneAnnotation {
195 f(&annotation, payload)
197 _ => panic!("Should use call_with_pp_support_hir"),
200 fn call_with_pp_support_hir<'tcx, A, B, F>(&self,
202 hir_map: &hir_map::Map<'tcx>,
203 analysis: &ty::CrateAnalysis,
204 resolutions: &Resolutions,
205 arena: &'tcx DroplessArena,
206 arenas: &'tcx GlobalArenas<'tcx>,
211 where F: FnOnce(&HirPrinterSupport, B, &hir::Crate) -> A
215 let annotation = NoAnn {
217 hir_map: Some(hir_map.clone()),
219 f(&annotation, payload, hir_map.forest.krate())
223 let annotation = IdentifiedAnnotation {
225 hir_map: Some(hir_map.clone()),
227 f(&annotation, payload, hir_map.forest.krate())
230 abort_on_err(driver::phase_3_run_analysis_passes(sess,
238 let empty_tables = ty::TypeckTables::empty();
239 let annotation = TypedAnnotation {
241 tables: Cell::new(&empty_tables)
243 let _ignore = tcx.dep_graph.in_ignore();
244 f(&annotation, payload, hir_map.forest.krate())
248 _ => panic!("Should use call_with_pp_support"),
253 trait PrinterSupport: pprust::PpAnn {
254 /// Provides a uniform interface for re-extracting a reference to a
255 /// `Session` from a value that now owns it.
256 fn sess<'a>(&'a self) -> &'a Session;
258 /// Produces the pretty-print annotation object.
260 /// (Rust does not yet support upcasting from a trait object to
261 /// an object for one of its super-traits.)
262 fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn;
265 trait HirPrinterSupport<'hir>: pprust_hir::PpAnn {
266 /// Provides a uniform interface for re-extracting a reference to a
267 /// `Session` from a value that now owns it.
268 fn sess<'a>(&'a self) -> &'a Session;
270 /// Provides a uniform interface for re-extracting a reference to an
271 /// `hir_map::Map` from a value that now owns it.
272 fn hir_map<'a>(&'a self) -> Option<&'a hir_map::Map<'hir>>;
274 /// Produces the pretty-print annotation object.
276 /// (Rust does not yet support upcasting from a trait object to
277 /// an object for one of its super-traits.)
278 fn pp_ann<'a>(&'a self) -> &'a pprust_hir::PpAnn;
280 /// Computes an user-readable representation of a path, if possible.
281 fn node_path(&self, id: ast::NodeId) -> Option<String> {
282 self.hir_map().and_then(|map| map.def_path_from_id(id)).map(|path| {
285 .map(|elem| elem.data.to_string())
294 hir_map: Option<hir_map::Map<'hir>>,
297 impl<'hir> PrinterSupport for NoAnn<'hir> {
298 fn sess<'a>(&'a self) -> &'a Session {
302 fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn {
307 impl<'hir> HirPrinterSupport<'hir> for NoAnn<'hir> {
308 fn sess<'a>(&'a self) -> &'a Session {
312 fn hir_map<'a>(&'a self) -> Option<&'a hir_map::Map<'hir>> {
313 self.hir_map.as_ref()
316 fn pp_ann<'a>(&'a self) -> &'a pprust_hir::PpAnn {
321 impl<'hir> pprust::PpAnn for NoAnn<'hir> {}
322 impl<'hir> pprust_hir::PpAnn for NoAnn<'hir> {
323 fn nested(&self, state: &mut pprust_hir::State, nested: pprust_hir::Nested)
325 if let Some(ref map) = self.hir_map {
326 pprust_hir::PpAnn::nested(map, state, nested)
333 struct IdentifiedAnnotation<'hir> {
335 hir_map: Option<hir_map::Map<'hir>>,
338 impl<'hir> PrinterSupport for IdentifiedAnnotation<'hir> {
339 fn sess<'a>(&'a self) -> &'a Session {
343 fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn {
348 impl<'hir> pprust::PpAnn for IdentifiedAnnotation<'hir> {
349 fn pre(&self, s: &mut pprust::State, node: pprust::AnnNode) -> io::Result<()> {
351 pprust::NodeExpr(_) => s.popen(),
355 fn post(&self, s: &mut pprust::State, node: pprust::AnnNode) -> io::Result<()> {
357 pprust::NodeIdent(_) |
358 pprust::NodeName(_) => Ok(()),
360 pprust::NodeItem(item) => {
361 pp::space(&mut s.s)?;
362 s.synth_comment(item.id.to_string())
364 pprust::NodeSubItem(id) => {
365 pp::space(&mut s.s)?;
366 s.synth_comment(id.to_string())
368 pprust::NodeBlock(blk) => {
369 pp::space(&mut s.s)?;
370 s.synth_comment(format!("block {}", blk.id))
372 pprust::NodeExpr(expr) => {
373 pp::space(&mut s.s)?;
374 s.synth_comment(expr.id.to_string())?;
377 pprust::NodePat(pat) => {
378 pp::space(&mut s.s)?;
379 s.synth_comment(format!("pat {}", pat.id))
385 impl<'hir> HirPrinterSupport<'hir> for IdentifiedAnnotation<'hir> {
386 fn sess<'a>(&'a self) -> &'a Session {
390 fn hir_map<'a>(&'a self) -> Option<&'a hir_map::Map<'hir>> {
391 self.hir_map.as_ref()
394 fn pp_ann<'a>(&'a self) -> &'a pprust_hir::PpAnn {
399 impl<'hir> pprust_hir::PpAnn for IdentifiedAnnotation<'hir> {
400 fn nested(&self, state: &mut pprust_hir::State, nested: pprust_hir::Nested)
402 if let Some(ref map) = self.hir_map {
403 pprust_hir::PpAnn::nested(map, state, nested)
408 fn pre(&self, s: &mut pprust_hir::State, node: pprust_hir::AnnNode) -> io::Result<()> {
410 pprust_hir::NodeExpr(_) => s.popen(),
414 fn post(&self, s: &mut pprust_hir::State, node: pprust_hir::AnnNode) -> io::Result<()> {
416 pprust_hir::NodeName(_) => Ok(()),
417 pprust_hir::NodeItem(item) => {
418 pp::space(&mut s.s)?;
419 s.synth_comment(item.id.to_string())
421 pprust_hir::NodeSubItem(id) => {
422 pp::space(&mut s.s)?;
423 s.synth_comment(id.to_string())
425 pprust_hir::NodeBlock(blk) => {
426 pp::space(&mut s.s)?;
427 s.synth_comment(format!("block {}", blk.id))
429 pprust_hir::NodeExpr(expr) => {
430 pp::space(&mut s.s)?;
431 s.synth_comment(expr.id.to_string())?;
434 pprust_hir::NodePat(pat) => {
435 pp::space(&mut s.s)?;
436 s.synth_comment(format!("pat {}", pat.id))
442 struct HygieneAnnotation<'a> {
446 impl<'a> PrinterSupport for HygieneAnnotation<'a> {
447 fn sess(&self) -> &Session {
451 fn pp_ann(&self) -> &pprust::PpAnn {
456 impl<'a> pprust::PpAnn for HygieneAnnotation<'a> {
457 fn post(&self, s: &mut pprust::State, node: pprust::AnnNode) -> io::Result<()> {
459 pprust::NodeIdent(&ast::Ident { name, ctxt }) => {
460 pp::space(&mut s.s)?;
461 // FIXME #16420: this doesn't display the connections
462 // between syntax contexts
463 s.synth_comment(format!("{}{:?}", name.as_u32(), ctxt))
465 pprust::NodeName(&name) => {
466 pp::space(&mut s.s)?;
467 s.synth_comment(name.as_u32().to_string())
475 struct TypedAnnotation<'a, 'tcx: 'a> {
476 tcx: TyCtxt<'a, 'tcx, 'tcx>,
477 tables: Cell<&'a ty::TypeckTables<'tcx>>,
480 impl<'b, 'tcx> HirPrinterSupport<'tcx> for TypedAnnotation<'b, 'tcx> {
481 fn sess<'a>(&'a self) -> &'a Session {
485 fn hir_map<'a>(&'a self) -> Option<&'a hir_map::Map<'tcx>> {
489 fn pp_ann<'a>(&'a self) -> &'a pprust_hir::PpAnn {
493 fn node_path(&self, id: ast::NodeId) -> Option<String> {
494 Some(self.tcx.node_path_str(id))
498 impl<'a, 'tcx> pprust_hir::PpAnn for TypedAnnotation<'a, 'tcx> {
499 fn nested(&self, state: &mut pprust_hir::State, nested: pprust_hir::Nested)
501 let old_tables = self.tables.get();
502 if let pprust_hir::Nested::Body(id) = nested {
503 self.tables.set(self.tcx.body_tables(id));
505 pprust_hir::PpAnn::nested(&self.tcx.hir, state, nested)?;
506 self.tables.set(old_tables);
509 fn pre(&self, s: &mut pprust_hir::State, node: pprust_hir::AnnNode) -> io::Result<()> {
511 pprust_hir::NodeExpr(_) => s.popen(),
515 fn post(&self, s: &mut pprust_hir::State, node: pprust_hir::AnnNode) -> io::Result<()> {
517 pprust_hir::NodeExpr(expr) => {
518 pp::space(&mut s.s)?;
519 pp::word(&mut s.s, "as")?;
520 pp::space(&mut s.s)?;
521 pp::word(&mut s.s, &self.tables.get().expr_ty(expr).to_string())?;
529 fn gather_flowgraph_variants(sess: &Session) -> Vec<borrowck_dot::Variant> {
530 let print_loans = sess.opts.debugging_opts.flowgraph_print_loans;
531 let print_moves = sess.opts.debugging_opts.flowgraph_print_moves;
532 let print_assigns = sess.opts.debugging_opts.flowgraph_print_assigns;
533 let print_all = sess.opts.debugging_opts.flowgraph_print_all;
534 let mut variants = Vec::new();
535 if print_all || print_loans {
536 variants.push(borrowck_dot::Loans);
538 if print_all || print_moves {
539 variants.push(borrowck_dot::Moves);
541 if print_all || print_assigns {
542 variants.push(borrowck_dot::Assigns);
547 #[derive(Clone, Debug)]
548 pub enum UserIdentifiedItem {
549 ItemViaNode(ast::NodeId),
550 ItemViaPath(Vec<String>),
553 impl FromStr for UserIdentifiedItem {
555 fn from_str(s: &str) -> Result<UserIdentifiedItem, ()> {
557 .map(ast::NodeId::new)
559 .unwrap_or_else(|_| ItemViaPath(s.split("::").map(|s| s.to_string()).collect())))
563 enum NodesMatchingUII<'a, 'hir: 'a> {
564 NodesMatchingDirect(option::IntoIter<ast::NodeId>),
565 NodesMatchingSuffix(hir_map::NodesMatchingSuffix<'a, 'hir>),
568 impl<'a, 'hir> Iterator for NodesMatchingUII<'a, 'hir> {
569 type Item = ast::NodeId;
571 fn next(&mut self) -> Option<ast::NodeId> {
573 &mut NodesMatchingDirect(ref mut iter) => iter.next(),
574 &mut NodesMatchingSuffix(ref mut iter) => iter.next(),
579 impl UserIdentifiedItem {
580 fn reconstructed_input(&self) -> String {
582 ItemViaNode(node_id) => node_id.to_string(),
583 ItemViaPath(ref parts) => parts.join("::"),
587 fn all_matching_node_ids<'a, 'hir>(&'a self,
588 map: &'a hir_map::Map<'hir>)
589 -> NodesMatchingUII<'a, 'hir> {
591 ItemViaNode(node_id) => NodesMatchingDirect(Some(node_id).into_iter()),
592 ItemViaPath(ref parts) => NodesMatchingSuffix(map.nodes_matching_suffix(&parts[..])),
596 fn to_one_node_id(self, user_option: &str, sess: &Session, map: &hir_map::Map) -> ast::NodeId {
597 let fail_because = |is_wrong_because| -> ast::NodeId {
598 let message = format!("{} needs NodeId (int) or unique path suffix (b::c::d); got \
601 self.reconstructed_input(),
603 sess.fatal(&message[..])
606 let mut saw_node = ast::DUMMY_NODE_ID;
608 for node in self.all_matching_node_ids(map) {
612 fail_because("does not resolve uniquely");
616 fail_because("does not resolve to any item");
624 struct ReplaceBodyWithLoop {
625 within_static_or_const: bool,
628 impl ReplaceBodyWithLoop {
629 fn new() -> ReplaceBodyWithLoop {
630 ReplaceBodyWithLoop { within_static_or_const: false }
634 impl fold::Folder for ReplaceBodyWithLoop {
635 fn fold_item_kind(&mut self, i: ast::ItemKind) -> ast::ItemKind {
637 ast::ItemKind::Static(..) |
638 ast::ItemKind::Const(..) => {
639 self.within_static_or_const = true;
640 let ret = fold::noop_fold_item_kind(i, self);
641 self.within_static_or_const = false;
644 _ => fold::noop_fold_item_kind(i, self),
648 fn fold_trait_item(&mut self, i: ast::TraitItem) -> SmallVector<ast::TraitItem> {
650 ast::TraitItemKind::Const(..) => {
651 self.within_static_or_const = true;
652 let ret = fold::noop_fold_trait_item(i, self);
653 self.within_static_or_const = false;
656 _ => fold::noop_fold_trait_item(i, self),
660 fn fold_impl_item(&mut self, i: ast::ImplItem) -> SmallVector<ast::ImplItem> {
662 ast::ImplItemKind::Const(..) => {
663 self.within_static_or_const = true;
664 let ret = fold::noop_fold_impl_item(i, self);
665 self.within_static_or_const = false;
668 _ => fold::noop_fold_impl_item(i, self),
672 fn fold_block(&mut self, b: P<ast::Block>) -> P<ast::Block> {
673 fn expr_to_block(rules: ast::BlockCheckMode, e: Option<P<ast::Expr>>) -> P<ast::Block> {
677 id: ast::DUMMY_NODE_ID,
679 node: ast::StmtKind::Expr(e),
685 id: ast::DUMMY_NODE_ID,
686 span: syntax_pos::DUMMY_SP,
690 if !self.within_static_or_const {
692 let empty_block = expr_to_block(BlockCheckMode::Default, None);
693 let loop_expr = P(ast::Expr {
694 node: ast::ExprKind::Loop(empty_block, None),
695 id: ast::DUMMY_NODE_ID,
696 span: syntax_pos::DUMMY_SP,
697 attrs: ast::ThinVec::new(),
700 expr_to_block(b.rules, Some(loop_expr))
703 fold::noop_fold_block(b, self)
707 // in general the pretty printer processes unexpanded code, so
708 // we override the default `fold_mac` method which panics.
709 fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac {
710 fold::noop_fold_mac(mac, self)
714 fn print_flowgraph<'a, 'tcx, W: Write>(variants: Vec<borrowck_dot::Variant>,
715 tcx: TyCtxt<'a, 'tcx, 'tcx>,
716 code: blocks::Code<'tcx>,
717 mode: PpFlowGraphMode,
720 let body_id = match code {
721 blocks::Code::Expr(expr) => {
722 // Find the function this expression is from.
723 let mut node_id = expr.id;
725 let node = tcx.hir.get(node_id);
726 if let Some(n) = hir::map::blocks::FnLikeNode::from_node(node) {
729 let parent = tcx.hir.get_parent_node(node_id);
730 assert!(node_id != parent);
734 blocks::Code::FnLike(fn_like) => fn_like.body(),
736 let body = tcx.hir.body(body_id);
737 let cfg = cfg::CFG::new(tcx, &body);
738 let labelled_edges = mode != PpFlowGraphMode::UnlabelledEdges;
739 let lcfg = LabelledCFG {
742 name: format!("node_{}", code.id()),
743 labelled_edges: labelled_edges,
747 _ if variants.is_empty() => {
748 let r = dot::render(&lcfg, &mut out);
749 return expand_err_details(r);
751 blocks::Code::Expr(_) => {
752 tcx.sess.err("--pretty flowgraph with -Z flowgraph-print annotations requires \
756 blocks::Code::FnLike(fn_like) => {
757 let (bccx, analysis_data) =
758 borrowck::build_borrowck_dataflow_data_for_fn(tcx, fn_like.body(), &cfg);
760 let lcfg = borrowck_dot::DataflowLabeller {
763 borrowck_ctxt: &bccx,
764 analysis_data: &analysis_data,
766 let r = dot::render(&lcfg, &mut out);
767 return expand_err_details(r);
771 fn expand_err_details(r: io::Result<()>) -> io::Result<()> {
773 io::Error::new(io::ErrorKind::Other,
774 &format!("graphviz::render failed: {}", ioerr)[..])
779 pub fn fold_crate(krate: ast::Crate, ppm: PpMode) -> ast::Crate {
780 if let PpmSource(PpmEveryBodyLoops) = ppm {
781 let mut fold = ReplaceBodyWithLoop::new();
782 fold.fold_crate(krate)
788 fn get_source(input: &Input, sess: &Session) -> (Vec<u8>, String) {
789 let src_name = driver::source_name(input);
790 let src = sess.codemap()
791 .get_filemap(&src_name)
801 fn write_output(out: Vec<u8>, ofile: Option<&Path>) {
803 None => print!("{}", String::from_utf8(out).unwrap()),
805 match File::create(p) {
806 Ok(mut w) => w.write_all(&out).unwrap(),
807 Err(e) => panic!("print-print failed to open {} due to {}", p.display(), e),
813 pub fn print_after_parsing(sess: &Session,
817 ofile: Option<&Path>) {
818 let dep_graph = DepGraph::new(false);
819 let _ignore = dep_graph.in_ignore();
821 let (src, src_name) = get_source(input, sess);
824 let mut out = Vec::new();
826 if let PpmSource(s) = ppm {
827 // Silently ignores an identified node.
828 let out: &mut Write = &mut out;
829 s.call_with_pp_support(sess, None, box out, |annotation, out| {
830 debug!("pretty printing source code {:?}", s);
831 let sess = annotation.sess();
832 pprust::print_crate(sess.codemap(),
835 src_name.to_string(),
846 write_output(out, ofile);
849 pub fn print_after_hir_lowering<'tcx, 'a: 'tcx>(sess: &'a Session,
850 hir_map: &hir_map::Map<'tcx>,
851 analysis: &ty::CrateAnalysis,
852 resolutions: &Resolutions,
857 arena: &'tcx DroplessArena,
858 arenas: &'tcx GlobalArenas<'tcx>,
859 opt_uii: Option<UserIdentifiedItem>,
860 ofile: Option<&Path>) {
861 let dep_graph = DepGraph::new(false);
862 let _ignore = dep_graph.in_ignore();
864 if ppm.needs_analysis() {
865 print_with_analysis(sess,
878 let (src, src_name) = get_source(input, sess);
880 let mut rdr = &src[..];
881 let mut out = Vec::new();
883 match (ppm, opt_uii) {
884 (PpmSource(s), _) => {
885 // Silently ignores an identified node.
886 let out: &mut Write = &mut out;
887 s.call_with_pp_support(sess, Some(hir_map), box out, |annotation, out| {
888 debug!("pretty printing source code {:?}", s);
889 let sess = annotation.sess();
890 pprust::print_crate(sess.codemap(),
893 src_name.to_string(),
901 (PpmHir(s), None) => {
902 let out: &mut Write = &mut out;
903 s.call_with_pp_support_hir(sess,
911 |annotation, out, krate| {
912 debug!("pretty printing source code {:?}", s);
913 let sess = annotation.sess();
914 pprust_hir::print_crate(sess.codemap(),
917 src_name.to_string(),
925 (PpmHir(s), Some(uii)) => {
926 let out: &mut Write = &mut out;
927 s.call_with_pp_support_hir(sess,
935 |annotation, (out, uii), _| {
936 debug!("pretty printing source code {:?}", s);
937 let sess = annotation.sess();
938 let hir_map = annotation.hir_map().expect("--unpretty missing HIR map");
939 let mut pp_state = pprust_hir::State::new_from_input(sess.codemap(),
941 src_name.to_string(),
946 for node_id in uii.all_matching_node_ids(hir_map) {
947 let node = hir_map.get(node_id);
948 pp_state.print_node(node)?;
949 pp::space(&mut pp_state.s)?;
950 let path = annotation.node_path(node_id)
951 .expect("--unpretty missing node paths");
952 pp_state.synth_comment(path)?;
953 pp::hardbreak(&mut pp_state.s)?;
955 pp::eof(&mut pp_state.s)
962 write_output(out, ofile);
965 // In an ideal world, this would be a public function called by the driver after
966 // analsysis is performed. However, we want to call `phase_3_run_analysis_passes`
967 // with a different callback than the standard driver, so that isn't easy.
968 // Instead, we call that function ourselves.
969 fn print_with_analysis<'tcx, 'a: 'tcx>(sess: &'a Session,
970 hir_map: &hir_map::Map<'tcx>,
971 analysis: &ty::CrateAnalysis,
972 resolutions: &Resolutions,
974 arena: &'tcx DroplessArena,
975 arenas: &'tcx GlobalArenas<'tcx>,
977 uii: Option<UserIdentifiedItem>,
978 ofile: Option<&Path>) {
979 let nodeid = if let Some(uii) = uii {
980 debug!("pretty printing for {:?}", uii);
981 Some(uii.to_one_node_id("--unpretty", sess, &hir_map))
983 debug!("pretty printing for whole crate");
987 let mut out = Vec::new();
989 abort_on_err(driver::phase_3_run_analysis_passes(sess,
998 PpmMir | PpmMirCFG => {
999 if let Some(nodeid) = nodeid {
1000 let def_id = tcx.hir.local_def_id(nodeid);
1002 PpmMir => write_mir_pretty(tcx, iter::once(def_id), &mut out),
1003 PpmMirCFG => write_mir_graphviz(tcx, iter::once(def_id), &mut out),
1004 _ => unreachable!(),
1009 write_mir_pretty(tcx,
1010 tcx.maps.mir.borrow().keys().into_iter(),
1014 write_mir_graphviz(tcx,
1015 tcx.maps.mir.borrow().keys().into_iter(),
1018 _ => unreachable!(),
1023 PpmFlowGraph(mode) => {
1025 nodeid.expect("`pretty flowgraph=..` needs NodeId (int) or unique path \
1027 let node = tcx.hir.find(nodeid).unwrap_or_else(|| {
1028 tcx.sess.fatal(&format!("--pretty flowgraph couldn't find id: {}", nodeid))
1031 match blocks::Code::from_node(&tcx.hir, nodeid) {
1033 let variants = gather_flowgraph_variants(tcx.sess);
1035 let out: &mut Write = &mut out;
1037 print_flowgraph(variants, tcx, code, mode, out)
1040 let message = format!("--pretty=flowgraph needs block, fn, or method; \
1044 tcx.sess.span_fatal(tcx.hir.span(nodeid), &message)
1048 _ => unreachable!(),
1054 write_output(out, ofile);