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::*;
19 use driver::{self, Resolutions};
21 use rustc::dep_graph::DepGraph;
22 use rustc::ty::{self, TyCtxt};
24 use rustc::cfg::graphviz::LabelledCFG;
25 use rustc::session::Session;
26 use rustc::session::config::Input;
27 use rustc_borrowck as borrowck;
28 use rustc_borrowck::graphviz as borrowck_dot;
30 use rustc_mir::pretty::write_mir_pretty;
31 use rustc_mir::graphviz::write_mir_graphviz;
33 use syntax::ast::{self, BlockCheckMode};
35 use syntax::fold::{self, Folder};
36 use syntax::print::{pp, pprust};
37 use syntax::print::pprust::PrintState;
39 use syntax::util::small_vector::SmallVector;
44 use std::io::{self, Write};
48 use std::str::FromStr;
50 use rustc::hir::map as hir_map;
51 use rustc::hir::map::{blocks, NodePrinter};
53 use rustc::hir::print as pprust_hir;
55 use rustc::mir::mir_map::MirMap;
57 #[derive(Copy, Clone, PartialEq, Debug)]
58 pub enum PpSourceMode {
63 PpmExpandedIdentified,
68 #[derive(Copy, Clone, PartialEq, Debug)]
69 pub enum PpFlowGraphMode {
71 /// Drops the labels from the edges in the flowgraph output. This
72 /// is mostly for use in the --unpretty flowgraph run-make tests,
73 /// since the labels are largely uninteresting in those cases and
74 /// have become a pain to maintain.
77 #[derive(Copy, Clone, PartialEq, Debug)]
79 PpmSource(PpSourceMode),
81 PpmFlowGraph(PpFlowGraphMode),
87 pub fn needs_ast_map(&self, opt_uii: &Option<UserIdentifiedItem>) -> bool {
89 PpmSource(PpmNormal) |
90 PpmSource(PpmEveryBodyLoops) |
91 PpmSource(PpmIdentified) => opt_uii.is_some(),
93 PpmSource(PpmExpanded) |
94 PpmSource(PpmExpandedIdentified) |
95 PpmSource(PpmExpandedHygiene) |
99 PpmFlowGraph(_) => true,
100 PpmSource(PpmTyped) => panic!("invalid state"),
104 pub fn needs_analysis(&self) -> bool {
106 PpmMir | PpmMirCFG | PpmFlowGraph(_) => true,
112 pub fn parse_pretty(sess: &Session,
115 -> (PpMode, Option<UserIdentifiedItem>) {
116 let mut split = name.splitn(2, '=');
117 let first = split.next().unwrap();
118 let opt_second = split.next();
119 let first = match (first, extended) {
120 ("normal", _) => PpmSource(PpmNormal),
121 ("identified", _) => PpmSource(PpmIdentified),
122 ("everybody_loops", true) => PpmSource(PpmEveryBodyLoops),
123 ("expanded", _) => PpmSource(PpmExpanded),
124 ("expanded,identified", _) => PpmSource(PpmExpandedIdentified),
125 ("expanded,hygiene", _) => PpmSource(PpmExpandedHygiene),
126 ("hir", true) => PpmHir(PpmNormal),
127 ("hir,identified", true) => PpmHir(PpmIdentified),
128 ("hir,typed", true) => PpmHir(PpmTyped),
129 ("mir", true) => PpmMir,
130 ("mir-cfg", true) => PpmMirCFG,
131 ("flowgraph", true) => PpmFlowGraph(PpFlowGraphMode::Default),
132 ("flowgraph,unlabelled", true) => PpmFlowGraph(PpFlowGraphMode::UnlabelledEdges),
135 sess.fatal(&format!("argument to `unpretty` must be one of `normal`, \
136 `expanded`, `flowgraph[,unlabelled]=<nodeid>`, \
137 `identified`, `expanded,identified`, `everybody_loops`, \
138 `hir`, `hir,identified`, `hir,typed`, or `mir`; got {}",
141 sess.fatal(&format!("argument to `pretty` must be one of `normal`, `expanded`, \
142 `identified`, or `expanded,identified`; got {}",
147 let opt_second = opt_second.and_then(|s| s.parse::<UserIdentifiedItem>().ok());
153 // This slightly awkward construction is to allow for each PpMode to
154 // choose whether it needs to do analyses (which can consume the
155 // Session) and then pass through the session (now attached to the
156 // analysis results) on to the chosen pretty-printer, along with the
159 // Note that since the `&PrinterSupport` is freshly constructed on each
160 // call, it would not make sense to try to attach the lifetime of `self`
161 // to the lifetime of the `&PrinterObject`.
163 // (The `use_once_payload` is working around the current lack of once
164 // functions in the compiler.)
167 /// Constructs a `PrinterSupport` object and passes it to `f`.
168 fn call_with_pp_support<'tcx, A, B, F>(&self,
170 ast_map: Option<&hir_map::Map<'tcx>>,
174 where F: FnOnce(&PrinterSupport, B) -> A
177 PpmNormal | PpmEveryBodyLoops | PpmExpanded => {
178 let annotation = NoAnn {
180 ast_map: ast_map.map(|m| m.clone()),
182 f(&annotation, payload)
185 PpmIdentified | PpmExpandedIdentified => {
186 let annotation = IdentifiedAnnotation {
188 ast_map: ast_map.map(|m| m.clone()),
190 f(&annotation, payload)
192 PpmExpandedHygiene => {
193 let annotation = HygieneAnnotation {
195 ast_map: ast_map.map(|m| m.clone()),
197 f(&annotation, payload)
199 _ => panic!("Should use call_with_pp_support_hir"),
202 fn call_with_pp_support_hir<'tcx, A, B, F>(&self,
204 ast_map: &hir_map::Map<'tcx>,
205 analysis: &ty::CrateAnalysis,
206 resolutions: &Resolutions,
207 arenas: &'tcx ty::CtxtArenas<'tcx>,
212 where F: FnOnce(&HirPrinterSupport, B, &hir::Crate) -> A
216 let annotation = NoAnn {
218 ast_map: Some(ast_map.clone()),
220 f(&annotation, payload, ast_map.forest.krate())
224 let annotation = IdentifiedAnnotation {
226 ast_map: Some(ast_map.clone()),
228 f(&annotation, payload, ast_map.forest.krate())
231 abort_on_err(driver::phase_3_run_analysis_passes(sess,
238 let annotation = TypedAnnotation {
241 let _ignore = tcx.dep_graph.in_ignore();
244 ast_map.forest.krate())
247 _ => panic!("Should use call_with_pp_support"),
252 trait PrinterSupport<'ast>: pprust::PpAnn {
253 /// Provides a uniform interface for re-extracting a reference to a
254 /// `Session` from a value that now owns it.
255 fn sess<'a>(&'a self) -> &'a Session;
257 /// Provides a uniform interface for re-extracting a reference to an
258 /// `hir_map::Map` from a value that now owns it.
259 fn ast_map<'a>(&'a self) -> Option<&'a hir_map::Map<'ast>>;
261 /// Produces the pretty-print annotation object.
263 /// (Rust does not yet support upcasting from a trait object to
264 /// an object for one of its super-traits.)
265 fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn;
268 trait HirPrinterSupport<'ast>: pprust_hir::PpAnn {
269 /// Provides a uniform interface for re-extracting a reference to a
270 /// `Session` from a value that now owns it.
271 fn sess<'a>(&'a self) -> &'a Session;
273 /// Provides a uniform interface for re-extracting a reference to an
274 /// `hir_map::Map` from a value that now owns it.
275 fn ast_map<'a>(&'a self) -> Option<&'a hir_map::Map<'ast>>;
277 /// Produces the pretty-print annotation object.
279 /// (Rust does not yet support upcasting from a trait object to
280 /// an object for one of its super-traits.)
281 fn pp_ann<'a>(&'a self) -> &'a pprust_hir::PpAnn;
283 /// Computes an user-readable representation of a path, if possible.
284 fn node_path(&self, id: ast::NodeId) -> Option<String> {
285 self.ast_map().and_then(|map| map.def_path_from_id(id)).map(|path| {
286 path.data.into_iter().map(|elem| {
287 elem.data.to_string()
288 }).collect::<Vec<_>>().join("::")
295 ast_map: Option<hir_map::Map<'ast>>,
298 impl<'ast> PrinterSupport<'ast> for NoAnn<'ast> {
299 fn sess<'a>(&'a self) -> &'a Session {
303 fn ast_map<'a>(&'a self) -> Option<&'a hir_map::Map<'ast>> {
304 self.ast_map.as_ref()
307 fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn {
312 impl<'ast> HirPrinterSupport<'ast> for NoAnn<'ast> {
313 fn sess<'a>(&'a self) -> &'a Session {
317 fn ast_map<'a>(&'a self) -> Option<&'a hir_map::Map<'ast>> {
318 self.ast_map.as_ref()
321 fn pp_ann<'a>(&'a self) -> &'a pprust_hir::PpAnn {
326 impl<'ast> pprust::PpAnn for NoAnn<'ast> {}
327 impl<'ast> pprust_hir::PpAnn for NoAnn<'ast> {}
329 struct IdentifiedAnnotation<'ast> {
331 ast_map: Option<hir_map::Map<'ast>>,
334 impl<'ast> PrinterSupport<'ast> for IdentifiedAnnotation<'ast> {
335 fn sess<'a>(&'a self) -> &'a Session {
339 fn ast_map<'a>(&'a self) -> Option<&'a hir_map::Map<'ast>> {
340 self.ast_map.as_ref()
343 fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn {
348 impl<'ast> pprust::PpAnn for IdentifiedAnnotation<'ast> {
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(_) | pprust::NodeName(_) => Ok(()),
359 pprust::NodeItem(item) => {
360 pp::space(&mut s.s)?;
361 s.synth_comment(item.id.to_string())
363 pprust::NodeSubItem(id) => {
364 pp::space(&mut s.s)?;
365 s.synth_comment(id.to_string())
367 pprust::NodeBlock(blk) => {
368 pp::space(&mut s.s)?;
369 s.synth_comment(format!("block {}", blk.id))
371 pprust::NodeExpr(expr) => {
372 pp::space(&mut s.s)?;
373 s.synth_comment(expr.id.to_string())?;
376 pprust::NodePat(pat) => {
377 pp::space(&mut s.s)?;
378 s.synth_comment(format!("pat {}", pat.id))
384 impl<'ast> HirPrinterSupport<'ast> for IdentifiedAnnotation<'ast> {
385 fn sess<'a>(&'a self) -> &'a Session {
389 fn ast_map<'a>(&'a self) -> Option<&'a hir_map::Map<'ast>> {
390 self.ast_map.as_ref()
393 fn pp_ann<'a>(&'a self) -> &'a pprust_hir::PpAnn {
398 impl<'ast> pprust_hir::PpAnn for IdentifiedAnnotation<'ast> {
399 fn pre(&self, s: &mut pprust_hir::State, node: pprust_hir::AnnNode) -> io::Result<()> {
401 pprust_hir::NodeExpr(_) => s.popen(),
405 fn post(&self, s: &mut pprust_hir::State, node: pprust_hir::AnnNode) -> io::Result<()> {
407 pprust_hir::NodeName(_) => Ok(()),
408 pprust_hir::NodeItem(item) => {
409 pp::space(&mut s.s)?;
410 s.synth_comment(item.id.to_string())
412 pprust_hir::NodeSubItem(id) => {
413 pp::space(&mut s.s)?;
414 s.synth_comment(id.to_string())
416 pprust_hir::NodeBlock(blk) => {
417 pp::space(&mut s.s)?;
418 s.synth_comment(format!("block {}", blk.id))
420 pprust_hir::NodeExpr(expr) => {
421 pp::space(&mut s.s)?;
422 s.synth_comment(expr.id.to_string())?;
425 pprust_hir::NodePat(pat) => {
426 pp::space(&mut s.s)?;
427 s.synth_comment(format!("pat {}", pat.id))
433 struct HygieneAnnotation<'ast> {
435 ast_map: Option<hir_map::Map<'ast>>,
438 impl<'ast> PrinterSupport<'ast> for HygieneAnnotation<'ast> {
439 fn sess<'a>(&'a self) -> &'a Session {
443 fn ast_map<'a>(&'a self) -> Option<&'a hir_map::Map<'ast>> {
444 self.ast_map.as_ref()
447 fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn {
452 impl<'ast> pprust::PpAnn for HygieneAnnotation<'ast> {
453 fn post(&self, s: &mut pprust::State, node: pprust::AnnNode) -> io::Result<()> {
455 pprust::NodeIdent(&ast::Ident { name: ast::Name(nm), ctxt }) => {
456 pp::space(&mut s.s)?;
457 // FIXME #16420: this doesn't display the connections
458 // between syntax contexts
459 s.synth_comment(format!("{}#{}", nm, ctxt.0))
461 pprust::NodeName(&ast::Name(nm)) => {
462 pp::space(&mut s.s)?;
463 s.synth_comment(nm.to_string())
471 struct TypedAnnotation<'a, 'tcx: 'a> {
472 tcx: TyCtxt<'a, 'tcx, 'tcx>,
475 impl<'b, 'tcx> HirPrinterSupport<'tcx> for TypedAnnotation<'b, 'tcx> {
476 fn sess<'a>(&'a self) -> &'a Session {
480 fn ast_map<'a>(&'a self) -> Option<&'a hir_map::Map<'tcx>> {
484 fn pp_ann<'a>(&'a self) -> &'a pprust_hir::PpAnn {
488 fn node_path(&self, id: ast::NodeId) -> Option<String> {
489 Some(self.tcx.node_path_str(id))
493 impl<'a, 'tcx> pprust_hir::PpAnn for TypedAnnotation<'a, 'tcx> {
494 fn pre(&self, s: &mut pprust_hir::State, node: pprust_hir::AnnNode) -> io::Result<()> {
496 pprust_hir::NodeExpr(_) => s.popen(),
500 fn post(&self, s: &mut pprust_hir::State, node: pprust_hir::AnnNode) -> io::Result<()> {
502 pprust_hir::NodeExpr(expr) => {
503 pp::space(&mut s.s)?;
504 pp::word(&mut s.s, "as")?;
505 pp::space(&mut s.s)?;
506 pp::word(&mut s.s, &self.tcx.expr_ty(expr).to_string())?;
514 fn gather_flowgraph_variants(sess: &Session) -> Vec<borrowck_dot::Variant> {
515 let print_loans = sess.opts.debugging_opts.flowgraph_print_loans;
516 let print_moves = sess.opts.debugging_opts.flowgraph_print_moves;
517 let print_assigns = sess.opts.debugging_opts.flowgraph_print_assigns;
518 let print_all = sess.opts.debugging_opts.flowgraph_print_all;
519 let mut variants = Vec::new();
520 if print_all || print_loans {
521 variants.push(borrowck_dot::Loans);
523 if print_all || print_moves {
524 variants.push(borrowck_dot::Moves);
526 if print_all || print_assigns {
527 variants.push(borrowck_dot::Assigns);
532 #[derive(Clone, Debug)]
533 pub enum UserIdentifiedItem {
534 ItemViaNode(ast::NodeId),
535 ItemViaPath(Vec<String>),
538 impl FromStr for UserIdentifiedItem {
540 fn from_str(s: &str) -> Result<UserIdentifiedItem, ()> {
543 .unwrap_or_else(|_| ItemViaPath(s.split("::").map(|s| s.to_string()).collect())))
547 enum NodesMatchingUII<'a, 'ast: 'a> {
548 NodesMatchingDirect(option::IntoIter<ast::NodeId>),
549 NodesMatchingSuffix(hir_map::NodesMatchingSuffix<'a, 'ast>),
552 impl<'a, 'ast> Iterator for NodesMatchingUII<'a, 'ast> {
553 type Item = ast::NodeId;
555 fn next(&mut self) -> Option<ast::NodeId> {
557 &mut NodesMatchingDirect(ref mut iter) => iter.next(),
558 &mut NodesMatchingSuffix(ref mut iter) => iter.next(),
563 impl UserIdentifiedItem {
564 fn reconstructed_input(&self) -> String {
566 ItemViaNode(node_id) => node_id.to_string(),
567 ItemViaPath(ref parts) => parts.join("::"),
571 fn all_matching_node_ids<'a, 'ast>(&'a self,
572 map: &'a hir_map::Map<'ast>)
573 -> NodesMatchingUII<'a, 'ast> {
575 ItemViaNode(node_id) => NodesMatchingDirect(Some(node_id).into_iter()),
576 ItemViaPath(ref parts) => NodesMatchingSuffix(map.nodes_matching_suffix(&parts[..])),
580 fn to_one_node_id(self, user_option: &str, sess: &Session, map: &hir_map::Map) -> ast::NodeId {
581 let fail_because = |is_wrong_because| -> ast::NodeId {
582 let message = format!("{} needs NodeId (int) or unique path suffix (b::c::d); got \
585 self.reconstructed_input(),
587 sess.fatal(&message[..])
590 let mut saw_node = ast::DUMMY_NODE_ID;
592 for node in self.all_matching_node_ids(map) {
596 fail_because("does not resolve uniquely");
600 fail_because("does not resolve to any item");
608 struct ReplaceBodyWithLoop {
609 within_static_or_const: bool,
612 impl ReplaceBodyWithLoop {
613 fn new() -> ReplaceBodyWithLoop {
614 ReplaceBodyWithLoop { within_static_or_const: false }
618 impl fold::Folder for ReplaceBodyWithLoop {
619 fn fold_item_kind(&mut self, i: ast::ItemKind) -> ast::ItemKind {
621 ast::ItemKind::Static(..) | ast::ItemKind::Const(..) => {
622 self.within_static_or_const = true;
623 let ret = fold::noop_fold_item_kind(i, self);
624 self.within_static_or_const = false;
628 fold::noop_fold_item_kind(i, self)
633 fn fold_trait_item(&mut self, i: ast::TraitItem) -> SmallVector<ast::TraitItem> {
635 ast::TraitItemKind::Const(..) => {
636 self.within_static_or_const = true;
637 let ret = fold::noop_fold_trait_item(i, self);
638 self.within_static_or_const = false;
641 _ => fold::noop_fold_trait_item(i, self),
645 fn fold_impl_item(&mut self, i: ast::ImplItem) -> SmallVector<ast::ImplItem> {
647 ast::ImplItemKind::Const(..) => {
648 self.within_static_or_const = true;
649 let ret = fold::noop_fold_impl_item(i, self);
650 self.within_static_or_const = false;
653 _ => fold::noop_fold_impl_item(i, self),
657 fn fold_block(&mut self, b: P<ast::Block>) -> P<ast::Block> {
658 fn expr_to_block(rules: ast::BlockCheckMode, e: Option<P<ast::Expr>>) -> P<ast::Block> {
663 id: ast::DUMMY_NODE_ID,
664 span: codemap::DUMMY_SP,
668 if !self.within_static_or_const {
670 let empty_block = expr_to_block(BlockCheckMode::Default, None);
671 let loop_expr = P(ast::Expr {
672 node: ast::ExprKind::Loop(empty_block, None),
673 id: ast::DUMMY_NODE_ID,
674 span: codemap::DUMMY_SP,
678 expr_to_block(b.rules, Some(loop_expr))
681 fold::noop_fold_block(b, self)
685 // in general the pretty printer processes unexpanded code, so
686 // we override the default `fold_mac` method which panics.
687 fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac {
688 fold::noop_fold_mac(mac, self)
692 fn print_flowgraph<'a, 'tcx, W: Write>(variants: Vec<borrowck_dot::Variant>,
693 tcx: TyCtxt<'a, 'tcx, 'tcx>,
694 mir_map: Option<&MirMap<'tcx>>,
696 mode: PpFlowGraphMode,
699 let cfg = match code {
700 blocks::BlockCode(block) => cfg::CFG::new(tcx, &block),
701 blocks::FnLikeCode(fn_like) => cfg::CFG::new(tcx, &fn_like.body()),
703 let labelled_edges = mode != PpFlowGraphMode::UnlabelledEdges;
704 let lcfg = LabelledCFG {
707 name: format!("node_{}", code.id()),
708 labelled_edges: labelled_edges,
712 _ if variants.is_empty() => {
713 let r = dot::render(&lcfg, &mut out);
714 return expand_err_details(r);
716 blocks::BlockCode(_) => {
717 tcx.sess.err("--pretty flowgraph with -Z flowgraph-print annotations requires \
721 blocks::FnLikeCode(fn_like) => {
722 let (bccx, analysis_data) =
723 borrowck::build_borrowck_dataflow_data_for_fn(tcx,
725 fn_like.to_fn_parts(),
728 let lcfg = borrowck_dot::DataflowLabeller {
731 borrowck_ctxt: &bccx,
732 analysis_data: &analysis_data,
734 let r = dot::render(&lcfg, &mut out);
735 return expand_err_details(r);
739 fn expand_err_details(r: io::Result<()>) -> io::Result<()> {
741 io::Error::new(io::ErrorKind::Other,
742 &format!("graphviz::render failed: {}", ioerr)[..])
747 pub fn fold_crate(krate: ast::Crate, ppm: PpMode) -> ast::Crate {
748 if let PpmSource(PpmEveryBodyLoops) = ppm {
749 let mut fold = ReplaceBodyWithLoop::new();
750 fold.fold_crate(krate)
756 fn get_source(input: &Input, sess: &Session) -> (Vec<u8>, String) {
757 let src_name = driver::source_name(input);
758 let src = sess.codemap()
759 .get_filemap(&src_name)
768 fn write_output(out: Vec<u8>, ofile: Option<&Path>) {
770 None => print!("{}", String::from_utf8(out).unwrap()),
772 match File::create(p) {
773 Ok(mut w) => w.write_all(&out).unwrap(),
774 Err(e) => panic!("print-print failed to open {} due to {}", p.display(), e),
780 pub fn print_after_parsing(sess: &Session,
784 ofile: Option<&Path>) {
785 let dep_graph = DepGraph::new(false);
786 let _ignore = dep_graph.in_ignore();
788 let (src, src_name) = get_source(input, sess);
791 let mut out = Vec::new();
793 if let PpmSource(s) = ppm {
794 // Silently ignores an identified node.
795 let out: &mut Write = &mut out;
796 s.call_with_pp_support(sess, None, box out, |annotation, out| {
797 debug!("pretty printing source code {:?}", s);
798 let sess = annotation.sess();
799 pprust::print_crate(sess.codemap(),
802 src_name.to_string(),
812 write_output(out, ofile);
815 pub fn print_after_hir_lowering<'tcx, 'a: 'tcx>(sess: &'a Session,
816 ast_map: &hir_map::Map<'tcx>,
817 analysis: &ty::CrateAnalysis,
818 resolutions: &Resolutions,
823 arenas: &'tcx ty::CtxtArenas<'tcx>,
824 opt_uii: Option<UserIdentifiedItem>,
825 ofile: Option<&Path>) {
826 let dep_graph = DepGraph::new(false);
827 let _ignore = dep_graph.in_ignore();
829 if ppm.needs_analysis() {
830 print_with_analysis(sess, ast_map, analysis, resolutions,
831 crate_name, arenas, ppm, opt_uii, ofile);
835 let (src, src_name) = get_source(input, sess);
837 let mut rdr = &src[..];
838 let mut out = Vec::new();
840 match (ppm, opt_uii) {
841 (PpmSource(s), _) => {
842 // Silently ignores an identified node.
843 let out: &mut Write = &mut out;
844 s.call_with_pp_support(sess, Some(ast_map), box out, |annotation, out| {
845 debug!("pretty printing source code {:?}", s);
846 let sess = annotation.sess();
847 pprust::print_crate(sess.codemap(),
850 src_name.to_string(),
858 (PpmHir(s), None) => {
859 let out: &mut Write = &mut out;
860 s.call_with_pp_support_hir(sess,
867 |annotation, out, krate| {
868 debug!("pretty printing source code {:?}", s);
869 let sess = annotation.sess();
870 pprust_hir::print_crate(sess.codemap(),
873 src_name.to_string(),
881 (PpmHir(s), Some(uii)) => {
882 let out: &mut Write = &mut out;
883 s.call_with_pp_support_hir(sess,
890 |annotation, (out,uii), _| {
891 debug!("pretty printing source code {:?}", s);
892 let sess = annotation.sess();
893 let ast_map = annotation.ast_map().expect("--unpretty missing HIR map");
895 pprust_hir::State::new_from_input(sess.codemap(),
897 src_name.to_string(),
902 Some(ast_map.krate()));
903 for node_id in uii.all_matching_node_ids(ast_map) {
904 let node = ast_map.get(node_id);
905 pp_state.print_node(&node)?;
906 pp::space(&mut pp_state.s)?;
907 let path = annotation.node_path(node_id)
908 .expect("--unpretty missing node paths");
909 pp_state.synth_comment(path)?;
910 pp::hardbreak(&mut pp_state.s)?;
912 pp::eof(&mut pp_state.s)
918 write_output(out, ofile);
921 // In an ideal world, this would be a public function called by the driver after
922 // analsysis is performed. However, we want to call `phase_3_run_analysis_passes`
923 // with a different callback than the standard driver, so that isn't easy.
924 // Instead, we call that function ourselves.
925 fn print_with_analysis<'tcx, 'a: 'tcx>(sess: &'a Session,
926 ast_map: &hir_map::Map<'tcx>,
927 analysis: &ty::CrateAnalysis,
928 resolutions: &Resolutions,
930 arenas: &'tcx ty::CtxtArenas<'tcx>,
932 uii: Option<UserIdentifiedItem>,
933 ofile: Option<&Path>) {
934 let nodeid = if let Some(uii) = uii {
935 debug!("pretty printing for {:?}", uii);
936 Some(uii.to_one_node_id("--unpretty", sess, &ast_map))
938 debug!("pretty printing for whole crate");
942 let mut out = Vec::new();
944 abort_on_err(driver::phase_3_run_analysis_passes(sess,
950 |tcx, mir_map, _, _| {
952 PpmMir | PpmMirCFG => {
953 if let Some(mir_map) = mir_map {
954 if let Some(nodeid) = nodeid {
955 let mir = mir_map.map.get(&nodeid).unwrap_or_else(|| {
956 sess.fatal(&format!("no MIR map entry for node {}", nodeid))
959 PpmMir => write_mir_pretty(tcx, iter::once((&nodeid, mir)), &mut out),
961 write_mir_graphviz(tcx, iter::once((&nodeid, mir)), &mut out)
967 PpmMir => write_mir_pretty(tcx, mir_map.map.iter(), &mut out),
968 PpmMirCFG => write_mir_graphviz(tcx, mir_map.map.iter(), &mut out),
975 PpmFlowGraph(mode) => {
976 let nodeid = nodeid.expect("`pretty flowgraph=..` needs NodeId (int) or \
977 unique path suffix (b::c::d)");
978 let node = tcx.map.find(nodeid).unwrap_or_else(|| {
979 tcx.sess.fatal(&format!("--pretty flowgraph couldn't find id: {}", nodeid))
982 let code = blocks::Code::from_node(node);
985 let variants = gather_flowgraph_variants(tcx.sess);
987 let out: &mut Write = &mut out;
989 print_flowgraph(variants,
997 let message = format!("--pretty=flowgraph needs block, fn, or method; got \
1001 // Point to what was found, if there's an accessible span.
1002 match tcx.map.opt_span(nodeid) {
1003 Some(sp) => tcx.sess.span_fatal(sp, &message),
1004 None => tcx.sess.fatal(&message),
1009 _ => unreachable!(),
1013 write_output(out, ofile);