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::{pprust};
34 use syntax::print::pprust::PrintState;
36 use syntax::util::small_vector::SmallVector;
43 use std::io::{self, Write};
46 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, F>(&self,
169 hir_map: Option<&hir_map::Map<'tcx>>,
172 where F: FnOnce(&PrinterSupport) -> A
175 PpmNormal | PpmEveryBodyLoops | PpmExpanded => {
176 let annotation = NoAnn {
178 hir_map: hir_map.map(|m| m.clone()),
183 PpmIdentified | PpmExpandedIdentified => {
184 let annotation = IdentifiedAnnotation {
186 hir_map: hir_map.map(|m| m.clone()),
190 PpmExpandedHygiene => {
191 let annotation = HygieneAnnotation {
196 _ => panic!("Should use call_with_pp_support_hir"),
199 fn call_with_pp_support_hir<'tcx, A, F>(&self,
201 hir_map: &hir_map::Map<'tcx>,
202 analysis: &ty::CrateAnalysis,
203 resolutions: &Resolutions,
204 arena: &'tcx DroplessArena,
205 arenas: &'tcx GlobalArenas<'tcx>,
209 where F: FnOnce(&HirPrinterSupport, &hir::Crate) -> A
213 let annotation = NoAnn {
215 hir_map: Some(hir_map.clone()),
217 f(&annotation, hir_map.forest.krate())
221 let annotation = IdentifiedAnnotation {
223 hir_map: Some(hir_map.clone()),
225 f(&annotation, hir_map.forest.krate())
228 abort_on_err(driver::phase_3_run_analysis_passes(sess,
236 let empty_tables = ty::TypeckTables::empty(None);
237 let annotation = TypedAnnotation {
239 tables: Cell::new(&empty_tables)
241 let _ignore = tcx.dep_graph.in_ignore();
242 f(&annotation, hir_map.forest.krate())
246 _ => panic!("Should use call_with_pp_support"),
251 trait PrinterSupport: pprust::PpAnn {
252 /// Provides a uniform interface for re-extracting a reference to a
253 /// `Session` from a value that now owns it.
254 fn sess<'a>(&'a self) -> &'a Session;
256 /// Produces the pretty-print annotation object.
258 /// (Rust does not yet support upcasting from a trait object to
259 /// an object for one of its super-traits.)
260 fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn;
263 trait HirPrinterSupport<'hir>: pprust_hir::PpAnn {
264 /// Provides a uniform interface for re-extracting a reference to a
265 /// `Session` from a value that now owns it.
266 fn sess<'a>(&'a self) -> &'a Session;
268 /// Provides a uniform interface for re-extracting a reference to an
269 /// `hir_map::Map` from a value that now owns it.
270 fn hir_map<'a>(&'a self) -> Option<&'a hir_map::Map<'hir>>;
272 /// Produces the pretty-print annotation object.
274 /// (Rust does not yet support upcasting from a trait object to
275 /// an object for one of its super-traits.)
276 fn pp_ann<'a>(&'a self) -> &'a pprust_hir::PpAnn;
278 /// Computes an user-readable representation of a path, if possible.
279 fn node_path(&self, id: ast::NodeId) -> Option<String> {
280 self.hir_map().and_then(|map| map.def_path_from_id(id)).map(|path| {
283 .map(|elem| elem.data.to_string())
292 hir_map: Option<hir_map::Map<'hir>>,
295 impl<'hir> PrinterSupport for NoAnn<'hir> {
296 fn sess<'a>(&'a self) -> &'a Session {
300 fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn {
305 impl<'hir> HirPrinterSupport<'hir> for NoAnn<'hir> {
306 fn sess<'a>(&'a self) -> &'a Session {
310 fn hir_map<'a>(&'a self) -> Option<&'a hir_map::Map<'hir>> {
311 self.hir_map.as_ref()
314 fn pp_ann<'a>(&'a self) -> &'a pprust_hir::PpAnn {
319 impl<'hir> pprust::PpAnn for NoAnn<'hir> {}
320 impl<'hir> pprust_hir::PpAnn for NoAnn<'hir> {
321 fn nested(&self, state: &mut pprust_hir::State, nested: pprust_hir::Nested)
323 if let Some(ref map) = self.hir_map {
324 pprust_hir::PpAnn::nested(map, state, nested)
331 struct IdentifiedAnnotation<'hir> {
333 hir_map: Option<hir_map::Map<'hir>>,
336 impl<'hir> PrinterSupport for IdentifiedAnnotation<'hir> {
337 fn sess<'a>(&'a self) -> &'a Session {
341 fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn {
346 impl<'hir> pprust::PpAnn for IdentifiedAnnotation<'hir> {
347 fn pre(&self, s: &mut pprust::State, node: pprust::AnnNode) -> io::Result<()> {
349 pprust::NodeExpr(_) => s.popen(),
353 fn post(&self, s: &mut pprust::State, node: pprust::AnnNode) -> io::Result<()> {
355 pprust::NodeIdent(_) |
356 pprust::NodeName(_) => Ok(()),
358 pprust::NodeItem(item) => {
360 s.synth_comment(item.id.to_string())
362 pprust::NodeSubItem(id) => {
364 s.synth_comment(id.to_string())
366 pprust::NodeBlock(blk) => {
368 s.synth_comment(format!("block {}", blk.id))
370 pprust::NodeExpr(expr) => {
372 s.synth_comment(expr.id.to_string())?;
375 pprust::NodePat(pat) => {
377 s.synth_comment(format!("pat {}", pat.id))
383 impl<'hir> HirPrinterSupport<'hir> for IdentifiedAnnotation<'hir> {
384 fn sess<'a>(&'a self) -> &'a Session {
388 fn hir_map<'a>(&'a self) -> Option<&'a hir_map::Map<'hir>> {
389 self.hir_map.as_ref()
392 fn pp_ann<'a>(&'a self) -> &'a pprust_hir::PpAnn {
397 impl<'hir> pprust_hir::PpAnn for IdentifiedAnnotation<'hir> {
398 fn nested(&self, state: &mut pprust_hir::State, nested: pprust_hir::Nested)
400 if let Some(ref map) = self.hir_map {
401 pprust_hir::PpAnn::nested(map, state, nested)
406 fn pre(&self, s: &mut pprust_hir::State, node: pprust_hir::AnnNode) -> io::Result<()> {
408 pprust_hir::NodeExpr(_) => s.popen(),
412 fn post(&self, s: &mut pprust_hir::State, node: pprust_hir::AnnNode) -> io::Result<()> {
414 pprust_hir::NodeName(_) => Ok(()),
415 pprust_hir::NodeItem(item) => {
417 s.synth_comment(item.id.to_string())
419 pprust_hir::NodeSubItem(id) => {
421 s.synth_comment(id.to_string())
423 pprust_hir::NodeBlock(blk) => {
425 s.synth_comment(format!("block {}", blk.id))
427 pprust_hir::NodeExpr(expr) => {
429 s.synth_comment(expr.id.to_string())?;
432 pprust_hir::NodePat(pat) => {
434 s.synth_comment(format!("pat {}", pat.id))
440 struct HygieneAnnotation<'a> {
444 impl<'a> PrinterSupport for HygieneAnnotation<'a> {
445 fn sess(&self) -> &Session {
449 fn pp_ann(&self) -> &pprust::PpAnn {
454 impl<'a> pprust::PpAnn for HygieneAnnotation<'a> {
455 fn post(&self, s: &mut pprust::State, node: pprust::AnnNode) -> io::Result<()> {
457 pprust::NodeIdent(&ast::Ident { name, ctxt }) => {
459 // FIXME #16420: this doesn't display the connections
460 // between syntax contexts
461 s.synth_comment(format!("{}{:?}", name.as_u32(), ctxt))
463 pprust::NodeName(&name) => {
465 s.synth_comment(name.as_u32().to_string())
473 struct TypedAnnotation<'a, 'tcx: 'a> {
474 tcx: TyCtxt<'a, 'tcx, 'tcx>,
475 tables: Cell<&'a ty::TypeckTables<'tcx>>,
478 impl<'b, 'tcx> HirPrinterSupport<'tcx> for TypedAnnotation<'b, 'tcx> {
479 fn sess<'a>(&'a self) -> &'a Session {
483 fn hir_map<'a>(&'a self) -> Option<&'a hir_map::Map<'tcx>> {
487 fn pp_ann<'a>(&'a self) -> &'a pprust_hir::PpAnn {
491 fn node_path(&self, id: ast::NodeId) -> Option<String> {
492 Some(self.tcx.node_path_str(id))
496 impl<'a, 'tcx> pprust_hir::PpAnn for TypedAnnotation<'a, 'tcx> {
497 fn nested(&self, state: &mut pprust_hir::State, nested: pprust_hir::Nested)
499 let old_tables = self.tables.get();
500 if let pprust_hir::Nested::Body(id) = nested {
501 self.tables.set(self.tcx.body_tables(id));
503 pprust_hir::PpAnn::nested(&self.tcx.hir, state, nested)?;
504 self.tables.set(old_tables);
507 fn pre(&self, s: &mut pprust_hir::State, node: pprust_hir::AnnNode) -> io::Result<()> {
509 pprust_hir::NodeExpr(_) => s.popen(),
513 fn post(&self, s: &mut pprust_hir::State, node: pprust_hir::AnnNode) -> io::Result<()> {
515 pprust_hir::NodeExpr(expr) => {
519 s.s.word(&self.tables.get().expr_ty(expr).to_string())?;
527 fn gather_flowgraph_variants(sess: &Session) -> Vec<borrowck_dot::Variant> {
528 let print_loans = sess.opts.debugging_opts.flowgraph_print_loans;
529 let print_moves = sess.opts.debugging_opts.flowgraph_print_moves;
530 let print_assigns = sess.opts.debugging_opts.flowgraph_print_assigns;
531 let print_all = sess.opts.debugging_opts.flowgraph_print_all;
532 let mut variants = Vec::new();
533 if print_all || print_loans {
534 variants.push(borrowck_dot::Loans);
536 if print_all || print_moves {
537 variants.push(borrowck_dot::Moves);
539 if print_all || print_assigns {
540 variants.push(borrowck_dot::Assigns);
545 #[derive(Clone, Debug)]
546 pub enum UserIdentifiedItem {
547 ItemViaNode(ast::NodeId),
548 ItemViaPath(Vec<String>),
551 impl FromStr for UserIdentifiedItem {
553 fn from_str(s: &str) -> Result<UserIdentifiedItem, ()> {
555 .map(ast::NodeId::new)
557 .unwrap_or_else(|_| ItemViaPath(s.split("::").map(|s| s.to_string()).collect())))
561 enum NodesMatchingUII<'a, 'hir: 'a> {
562 NodesMatchingDirect(option::IntoIter<ast::NodeId>),
563 NodesMatchingSuffix(hir_map::NodesMatchingSuffix<'a, 'hir>),
566 impl<'a, 'hir> Iterator for NodesMatchingUII<'a, 'hir> {
567 type Item = ast::NodeId;
569 fn next(&mut self) -> Option<ast::NodeId> {
571 &mut NodesMatchingDirect(ref mut iter) => iter.next(),
572 &mut NodesMatchingSuffix(ref mut iter) => iter.next(),
577 impl UserIdentifiedItem {
578 fn reconstructed_input(&self) -> String {
580 ItemViaNode(node_id) => node_id.to_string(),
581 ItemViaPath(ref parts) => parts.join("::"),
585 fn all_matching_node_ids<'a, 'hir>(&'a self,
586 map: &'a hir_map::Map<'hir>)
587 -> NodesMatchingUII<'a, 'hir> {
589 ItemViaNode(node_id) => NodesMatchingDirect(Some(node_id).into_iter()),
590 ItemViaPath(ref parts) => NodesMatchingSuffix(map.nodes_matching_suffix(&parts)),
594 fn to_one_node_id(self, user_option: &str, sess: &Session, map: &hir_map::Map) -> ast::NodeId {
595 let fail_because = |is_wrong_because| -> ast::NodeId {
596 let message = format!("{} needs NodeId (int) or unique path suffix (b::c::d); got \
599 self.reconstructed_input(),
604 let mut saw_node = ast::DUMMY_NODE_ID;
606 for node in self.all_matching_node_ids(map) {
610 fail_because("does not resolve uniquely");
614 fail_because("does not resolve to any item");
622 // Note: Also used by librustdoc, see PR #43348. Consider moving this struct elsewhere.
624 // FIXME: Currently the `everybody_loops` transformation is not applied to:
625 // * `const fn`, due to issue #43636 that `loop` is not supported for const evaluation. We are
626 // waiting for miri to fix that.
627 // * `impl Trait`, due to issue #43869 that functions returning impl Trait cannot be diverging.
628 // Solving this may require `!` to implement every trait, which relies on the an even more
629 // ambitious form of the closed RFC #1637. See also [#34511].
631 // [#34511]: https://github.com/rust-lang/rust/issues/34511#issuecomment-322340401
632 pub struct ReplaceBodyWithLoop {
633 within_static_or_const: bool,
636 impl ReplaceBodyWithLoop {
637 pub fn new() -> ReplaceBodyWithLoop {
638 ReplaceBodyWithLoop { within_static_or_const: false }
641 fn run<R, F: FnOnce(&mut Self) -> R>(&mut self, is_const: bool, action: F) -> R {
642 let old_const = mem::replace(&mut self.within_static_or_const, is_const);
643 let ret = action(self);
644 self.within_static_or_const = old_const;
648 fn should_ignore_fn(ret_ty: &ast::FnDecl) -> bool {
649 if let ast::FunctionRetTy::Ty(ref ty) = ret_ty.output {
650 fn involves_impl_trait(ty: &ast::Ty) -> bool {
652 ast::TyKind::ImplTrait(_) => true,
653 ast::TyKind::Slice(ref subty) |
654 ast::TyKind::Array(ref subty, _) |
655 ast::TyKind::Ptr(ast::MutTy { ty: ref subty, .. }) |
656 ast::TyKind::Rptr(_, ast::MutTy { ty: ref subty, .. }) |
657 ast::TyKind::Paren(ref subty) => involves_impl_trait(subty),
658 ast::TyKind::Tup(ref tys) => tys.iter().any(|subty| involves_impl_trait(subty)),
662 involves_impl_trait(ty)
669 impl fold::Folder for ReplaceBodyWithLoop {
670 fn fold_item_kind(&mut self, i: ast::ItemKind) -> ast::ItemKind {
671 let is_const = match i {
672 ast::ItemKind::Static(..) | ast::ItemKind::Const(..) => true,
673 ast::ItemKind::Fn(ref decl, _, ref constness, _, _, _) =>
674 constness.node == ast::Constness::Const || Self::should_ignore_fn(decl),
677 self.run(is_const, |s| fold::noop_fold_item_kind(i, s))
680 fn fold_trait_item(&mut self, i: ast::TraitItem) -> SmallVector<ast::TraitItem> {
681 let is_const = match i.node {
682 ast::TraitItemKind::Const(..) => true,
683 ast::TraitItemKind::Method(ast::MethodSig { ref decl, ref constness, .. }, _) =>
684 constness.node == ast::Constness::Const || Self::should_ignore_fn(decl),
687 self.run(is_const, |s| fold::noop_fold_trait_item(i, s))
690 fn fold_impl_item(&mut self, i: ast::ImplItem) -> SmallVector<ast::ImplItem> {
691 let is_const = match i.node {
692 ast::ImplItemKind::Const(..) => true,
693 ast::ImplItemKind::Method(ast::MethodSig { ref decl, ref constness, .. }, _) =>
694 constness.node == ast::Constness::Const || Self::should_ignore_fn(decl),
697 self.run(is_const, |s| fold::noop_fold_impl_item(i, s))
700 fn fold_block(&mut self, b: P<ast::Block>) -> P<ast::Block> {
701 fn expr_to_block(rules: ast::BlockCheckMode, e: Option<P<ast::Expr>>) -> P<ast::Block> {
705 id: ast::DUMMY_NODE_ID,
707 node: ast::StmtKind::Expr(e),
713 id: ast::DUMMY_NODE_ID,
714 span: syntax_pos::DUMMY_SP,
718 if !self.within_static_or_const {
720 let empty_block = expr_to_block(BlockCheckMode::Default, None);
721 let loop_expr = P(ast::Expr {
722 node: ast::ExprKind::Loop(empty_block, None),
723 id: ast::DUMMY_NODE_ID,
724 span: syntax_pos::DUMMY_SP,
725 attrs: ast::ThinVec::new(),
728 expr_to_block(b.rules, Some(loop_expr))
731 fold::noop_fold_block(b, self)
735 // in general the pretty printer processes unexpanded code, so
736 // we override the default `fold_mac` method which panics.
737 fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac {
738 fold::noop_fold_mac(mac, self)
742 fn print_flowgraph<'a, 'tcx, W: Write>(variants: Vec<borrowck_dot::Variant>,
743 tcx: TyCtxt<'a, 'tcx, 'tcx>,
744 code: blocks::Code<'tcx>,
745 mode: PpFlowGraphMode,
748 let body_id = match code {
749 blocks::Code::Expr(expr) => {
750 // Find the function this expression is from.
751 let mut node_id = expr.id;
753 let node = tcx.hir.get(node_id);
754 if let Some(n) = hir::map::blocks::FnLikeNode::from_node(node) {
757 let parent = tcx.hir.get_parent_node(node_id);
758 assert!(node_id != parent);
762 blocks::Code::FnLike(fn_like) => fn_like.body(),
764 let body = tcx.hir.body(body_id);
765 let cfg = cfg::CFG::new(tcx, &body);
766 let labelled_edges = mode != PpFlowGraphMode::UnlabelledEdges;
767 let lcfg = LabelledCFG {
770 name: format!("node_{}", code.id()),
775 _ if variants.is_empty() => {
776 let r = dot::render(&lcfg, &mut out);
777 return expand_err_details(r);
779 blocks::Code::Expr(_) => {
780 tcx.sess.err("--pretty flowgraph with -Z flowgraph-print annotations requires \
784 blocks::Code::FnLike(fn_like) => {
785 let (bccx, analysis_data) =
786 borrowck::build_borrowck_dataflow_data_for_fn(tcx, fn_like.body(), &cfg);
788 let lcfg = borrowck_dot::DataflowLabeller {
791 borrowck_ctxt: &bccx,
792 analysis_data: &analysis_data,
794 let r = dot::render(&lcfg, &mut out);
795 return expand_err_details(r);
799 fn expand_err_details(r: io::Result<()>) -> io::Result<()> {
801 io::Error::new(io::ErrorKind::Other,
802 format!("graphviz::render failed: {}", ioerr))
807 pub fn fold_crate(krate: ast::Crate, ppm: PpMode) -> ast::Crate {
808 if let PpmSource(PpmEveryBodyLoops) = ppm {
809 let mut fold = ReplaceBodyWithLoop::new();
810 fold.fold_crate(krate)
816 fn get_source(input: &Input, sess: &Session) -> (Vec<u8>, String) {
817 let src_name = driver::source_name(input);
818 let src = sess.codemap()
819 .get_filemap(&src_name)
829 fn write_output(out: Vec<u8>, ofile: Option<&Path>) {
831 None => print!("{}", String::from_utf8(out).unwrap()),
833 match File::create(p) {
834 Ok(mut w) => w.write_all(&out).unwrap(),
835 Err(e) => panic!("print-print failed to open {} due to {}", p.display(), e),
841 pub fn print_after_parsing(sess: &Session,
845 ofile: Option<&Path>) {
846 let dep_graph = DepGraph::new(false);
847 let _ignore = dep_graph.in_ignore();
849 let (src, src_name) = get_source(input, sess);
852 let mut out = Vec::new();
854 if let PpmSource(s) = ppm {
855 // Silently ignores an identified node.
856 let out: &mut Write = &mut out;
857 s.call_with_pp_support(sess, None, move |annotation| {
858 debug!("pretty printing source code {:?}", s);
859 let sess = annotation.sess();
860 pprust::print_crate(sess.codemap(),
863 src_name.to_string(),
874 write_output(out, ofile);
877 pub fn print_after_hir_lowering<'tcx, 'a: 'tcx>(sess: &'a Session,
878 hir_map: &hir_map::Map<'tcx>,
879 analysis: &ty::CrateAnalysis,
880 resolutions: &Resolutions,
885 arena: &'tcx DroplessArena,
886 arenas: &'tcx GlobalArenas<'tcx>,
887 opt_uii: Option<UserIdentifiedItem>,
888 ofile: Option<&Path>) {
889 let dep_graph = DepGraph::new(false);
890 let _ignore = dep_graph.in_ignore();
892 if ppm.needs_analysis() {
893 print_with_analysis(sess,
906 let (src, src_name) = get_source(input, sess);
908 let mut rdr = &src[..];
909 let mut out = Vec::new();
911 match (ppm, opt_uii) {
912 (PpmSource(s), _) => {
913 // Silently ignores an identified node.
914 let out: &mut Write = &mut out;
915 s.call_with_pp_support(sess, Some(hir_map), move |annotation| {
916 debug!("pretty printing source code {:?}", s);
917 let sess = annotation.sess();
918 pprust::print_crate(sess.codemap(),
921 src_name.to_string(),
929 (PpmHir(s), None) => {
930 let out: &mut Write = &mut out;
931 s.call_with_pp_support_hir(sess,
938 move |annotation, krate| {
939 debug!("pretty printing source code {:?}", s);
940 let sess = annotation.sess();
941 pprust_hir::print_crate(sess.codemap(),
944 src_name.to_string(),
952 (PpmHir(s), Some(uii)) => {
953 let out: &mut Write = &mut out;
954 s.call_with_pp_support_hir(sess,
961 move |annotation, _| {
962 debug!("pretty printing source code {:?}", s);
963 let sess = annotation.sess();
964 let hir_map = annotation.hir_map().expect("--unpretty missing HIR map");
965 let mut pp_state = pprust_hir::State::new_from_input(sess.codemap(),
967 src_name.to_string(),
972 for node_id in uii.all_matching_node_ids(hir_map) {
973 let node = hir_map.get(node_id);
974 pp_state.print_node(node)?;
976 let path = annotation.node_path(node_id)
977 .expect("--unpretty missing node paths");
978 pp_state.synth_comment(path)?;
979 pp_state.s.hardbreak()?;
988 write_output(out, ofile);
991 // In an ideal world, this would be a public function called by the driver after
992 // analsysis is performed. However, we want to call `phase_3_run_analysis_passes`
993 // with a different callback than the standard driver, so that isn't easy.
994 // Instead, we call that function ourselves.
995 fn print_with_analysis<'tcx, 'a: 'tcx>(sess: &'a Session,
996 hir_map: &hir_map::Map<'tcx>,
997 analysis: &ty::CrateAnalysis,
998 resolutions: &Resolutions,
1000 arena: &'tcx DroplessArena,
1001 arenas: &'tcx GlobalArenas<'tcx>,
1003 uii: Option<UserIdentifiedItem>,
1004 ofile: Option<&Path>) {
1005 let nodeid = if let Some(uii) = uii {
1006 debug!("pretty printing for {:?}", uii);
1007 Some(uii.to_one_node_id("--unpretty", sess, &hir_map))
1009 debug!("pretty printing for whole crate");
1013 let mut out = Vec::new();
1015 abort_on_err(driver::phase_3_run_analysis_passes(sess,
1018 resolutions.clone(),
1024 PpmMir | PpmMirCFG => {
1025 if let Some(nodeid) = nodeid {
1026 let def_id = tcx.hir.local_def_id(nodeid);
1028 PpmMir => write_mir_pretty(tcx, Some(def_id), &mut out),
1029 PpmMirCFG => write_mir_graphviz(tcx, Some(def_id), &mut out),
1030 _ => unreachable!(),
1034 PpmMir => write_mir_pretty(tcx, None, &mut out),
1035 PpmMirCFG => write_mir_graphviz(tcx, None, &mut out),
1036 _ => unreachable!(),
1041 PpmFlowGraph(mode) => {
1043 nodeid.expect("`pretty flowgraph=..` needs NodeId (int) or unique path \
1045 let node = tcx.hir.find(nodeid).unwrap_or_else(|| {
1046 tcx.sess.fatal(&format!("--pretty flowgraph couldn't find id: {}", nodeid))
1049 match blocks::Code::from_node(&tcx.hir, nodeid) {
1051 let variants = gather_flowgraph_variants(tcx.sess);
1053 let out: &mut Write = &mut out;
1055 print_flowgraph(variants, tcx, code, mode, out)
1058 let message = format!("--pretty=flowgraph needs block, fn, or method; \
1062 tcx.sess.span_fatal(tcx.hir.span(nodeid), &message)
1066 _ => unreachable!(),
1072 write_output(out, ofile);