1 //! The various pretty-printing routines.
4 use rustc::cfg::graphviz::LabelledCFG;
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::session::Session;
10 use rustc::session::config::{Input, OutputFilenames};
11 use rustc::ty::{self, TyCtxt, Resolutions, AllArenas};
12 use rustc_borrowck as borrowck;
13 use rustc_borrowck::graphviz as borrowck_dot;
14 use rustc_data_structures::thin_vec::ThinVec;
15 use rustc_metadata::cstore::CStore;
16 use rustc_mir::util::{write_mir_pretty, write_mir_graphviz};
18 use syntax::ast::{self, BlockCheckMode};
19 use syntax::mut_visit::{*, MutVisitor, visit_clobber};
20 use syntax::print::{pprust};
21 use syntax::print::pprust::PrintState;
23 use syntax_pos::{self, FileName};
26 use smallvec::SmallVec;
30 use std::io::{self, Write};
31 use std::ops::DerefMut;
34 use std::str::FromStr;
37 pub use self::UserIdentifiedItem::*;
38 pub use self::PpSourceMode::*;
39 pub use self::PpMode::*;
40 use self::NodesMatchingUII::*;
41 use {abort_on_err, driver};
43 #[derive(Copy, Clone, PartialEq, Debug)]
44 pub enum PpSourceMode {
49 PpmExpandedIdentified,
54 #[derive(Copy, Clone, PartialEq, Debug)]
55 pub enum PpFlowGraphMode {
57 /// Drops the labels from the edges in the flowgraph output. This
58 /// is mostly for use in the -Z unpretty flowgraph run-make tests,
59 /// since the labels are largely uninteresting in those cases and
60 /// have become a pain to maintain.
63 #[derive(Copy, Clone, PartialEq, Debug)]
65 PpmSource(PpSourceMode),
67 PpmHirTree(PpSourceMode),
68 PpmFlowGraph(PpFlowGraphMode),
74 pub fn needs_ast_map(&self, opt_uii: &Option<UserIdentifiedItem>) -> bool {
76 PpmSource(PpmNormal) |
77 PpmSource(PpmEveryBodyLoops) |
78 PpmSource(PpmIdentified) => opt_uii.is_some(),
80 PpmSource(PpmExpanded) |
81 PpmSource(PpmExpandedIdentified) |
82 PpmSource(PpmExpandedHygiene) |
87 PpmFlowGraph(_) => true,
88 PpmSource(PpmTyped) => panic!("invalid state"),
92 pub fn needs_analysis(&self) -> bool {
94 PpmMir | PpmMirCFG | PpmFlowGraph(_) => true,
100 pub fn parse_pretty(sess: &Session,
103 -> (PpMode, Option<UserIdentifiedItem>) {
104 let mut split = name.splitn(2, '=');
105 let first = split.next().unwrap();
106 let opt_second = split.next();
107 let first = match (first, extended) {
108 ("normal", _) => PpmSource(PpmNormal),
109 ("identified", _) => PpmSource(PpmIdentified),
110 ("everybody_loops", true) => PpmSource(PpmEveryBodyLoops),
111 ("expanded", _) => PpmSource(PpmExpanded),
112 ("expanded,identified", _) => PpmSource(PpmExpandedIdentified),
113 ("expanded,hygiene", _) => PpmSource(PpmExpandedHygiene),
114 ("hir", true) => PpmHir(PpmNormal),
115 ("hir,identified", true) => PpmHir(PpmIdentified),
116 ("hir,typed", true) => PpmHir(PpmTyped),
117 ("hir-tree", true) => PpmHirTree(PpmNormal),
118 ("mir", true) => PpmMir,
119 ("mir-cfg", true) => PpmMirCFG,
120 ("flowgraph", true) => PpmFlowGraph(PpFlowGraphMode::Default),
121 ("flowgraph,unlabelled", true) => PpmFlowGraph(PpFlowGraphMode::UnlabelledEdges),
124 sess.fatal(&format!("argument to `unpretty` must be one of `normal`, \
125 `expanded`, `flowgraph[,unlabelled]=<nodeid>`, \
126 `identified`, `expanded,identified`, `everybody_loops`, \
127 `hir`, `hir,identified`, `hir,typed`, `hir-tree`, \
128 `mir` or `mir-cfg`; got {}",
131 sess.fatal(&format!("argument to `pretty` must be one of `normal`, `expanded`, \
132 `identified`, or `expanded,identified`; got {}",
137 let opt_second = opt_second.and_then(|s| s.parse::<UserIdentifiedItem>().ok());
143 // This slightly awkward construction is to allow for each PpMode to
144 // choose whether it needs to do analyses (which can consume the
145 // Session) and then pass through the session (now attached to the
146 // analysis results) on to the chosen pretty-printer, along with the
149 // Note that since the `&PrinterSupport` is freshly constructed on each
150 // call, it would not make sense to try to attach the lifetime of `self`
151 // to the lifetime of the `&PrinterObject`.
153 // (The `use_once_payload` is working around the current lack of once
154 // functions in the compiler.)
157 /// Constructs a `PrinterSupport` object and passes it to `f`.
158 fn call_with_pp_support<'tcx, A, F>(&self,
160 hir_map: Option<&hir_map::Map<'tcx>>,
163 where F: FnOnce(&dyn PrinterSupport) -> A
166 PpmNormal | PpmEveryBodyLoops | PpmExpanded => {
167 let annotation = NoAnn {
169 hir_map: hir_map.map(|m| m.clone()),
174 PpmIdentified | PpmExpandedIdentified => {
175 let annotation = IdentifiedAnnotation {
177 hir_map: hir_map.map(|m| m.clone()),
181 PpmExpandedHygiene => {
182 let annotation = HygieneAnnotation {
187 _ => panic!("Should use call_with_pp_support_hir"),
190 fn call_with_pp_support_hir<'tcx, A, F>(
193 cstore: &'tcx CStore,
194 hir_map: &hir_map::Map<'tcx>,
195 resolutions: &Resolutions,
196 output_filenames: &OutputFilenames,
200 where F: FnOnce(&dyn HirPrinterSupport, &hir::Crate) -> A
204 let annotation = NoAnn {
206 hir_map: Some(hir_map.clone()),
208 f(&annotation, hir_map.forest.krate())
212 let annotation = IdentifiedAnnotation {
214 hir_map: Some(hir_map.clone()),
216 f(&annotation, hir_map.forest.krate())
219 let control = &driver::CompileController::basic();
220 let codegen_backend = ::get_codegen_backend(sess);
221 let mut arenas = AllArenas::new();
222 abort_on_err(driver::phase_3_run_analysis_passes(&*codegen_backend,
232 let empty_tables = ty::TypeckTables::empty(None);
233 let annotation = TypedAnnotation {
235 tables: Cell::new(&empty_tables)
237 tcx.dep_graph.with_ignore(|| {
238 f(&annotation, hir_map.forest.krate())
243 _ => panic!("Should use call_with_pp_support"),
248 trait PrinterSupport: pprust::PpAnn {
249 /// Provides a uniform interface for re-extracting a reference to a
250 /// `Session` from a value that now owns it.
251 fn sess<'a>(&'a self) -> &'a Session;
253 /// Produces the pretty-print annotation object.
255 /// (Rust does not yet support upcasting from a trait object to
256 /// an object for one of its super-traits.)
257 fn pp_ann<'a>(&'a self) -> &'a dyn pprust::PpAnn;
260 trait HirPrinterSupport<'hir>: pprust_hir::PpAnn {
261 /// Provides a uniform interface for re-extracting a reference to a
262 /// `Session` from a value that now owns it.
263 fn sess<'a>(&'a self) -> &'a Session;
265 /// Provides a uniform interface for re-extracting a reference to an
266 /// `hir_map::Map` from a value that now owns it.
267 fn hir_map<'a>(&'a self) -> Option<&'a hir_map::Map<'hir>>;
269 /// Produces the pretty-print annotation object.
271 /// (Rust does not yet support upcasting from a trait object to
272 /// an object for one of its super-traits.)
273 fn pp_ann<'a>(&'a self) -> &'a dyn pprust_hir::PpAnn;
275 /// Computes an user-readable representation of a path, if possible.
276 fn node_path(&self, id: ast::NodeId) -> Option<String> {
277 self.hir_map().and_then(|map| map.def_path_from_id(id)).map(|path| {
280 .map(|elem| elem.data.to_string())
289 hir_map: Option<hir_map::Map<'hir>>,
292 impl<'hir> PrinterSupport for NoAnn<'hir> {
293 fn sess<'a>(&'a self) -> &'a Session {
297 fn pp_ann<'a>(&'a self) -> &'a dyn pprust::PpAnn {
302 impl<'hir> HirPrinterSupport<'hir> for NoAnn<'hir> {
303 fn sess<'a>(&'a self) -> &'a Session {
307 fn hir_map<'a>(&'a self) -> Option<&'a hir_map::Map<'hir>> {
308 self.hir_map.as_ref()
311 fn pp_ann<'a>(&'a self) -> &'a dyn pprust_hir::PpAnn {
316 impl<'hir> pprust::PpAnn for NoAnn<'hir> {}
317 impl<'hir> pprust_hir::PpAnn for NoAnn<'hir> {
318 fn nested(&self, state: &mut pprust_hir::State, nested: pprust_hir::Nested)
320 if let Some(ref map) = self.hir_map {
321 pprust_hir::PpAnn::nested(map, state, nested)
328 struct IdentifiedAnnotation<'hir> {
330 hir_map: Option<hir_map::Map<'hir>>,
333 impl<'hir> PrinterSupport for IdentifiedAnnotation<'hir> {
334 fn sess<'a>(&'a self) -> &'a Session {
338 fn pp_ann<'a>(&'a self) -> &'a dyn pprust::PpAnn {
343 impl<'hir> pprust::PpAnn for IdentifiedAnnotation<'hir> {
344 fn pre(&self, s: &mut pprust::State, node: pprust::AnnNode) -> io::Result<()> {
346 pprust::AnnNode::Expr(_) => s.popen(),
350 fn post(&self, s: &mut pprust::State, node: pprust::AnnNode) -> io::Result<()> {
352 pprust::AnnNode::Ident(_) |
353 pprust::AnnNode::Name(_) => Ok(()),
355 pprust::AnnNode::Item(item) => {
357 s.synth_comment(item.id.to_string())
359 pprust::AnnNode::SubItem(id) => {
361 s.synth_comment(id.to_string())
363 pprust::AnnNode::Block(blk) => {
365 s.synth_comment(format!("block {}", blk.id))
367 pprust::AnnNode::Expr(expr) => {
369 s.synth_comment(expr.id.to_string())?;
372 pprust::AnnNode::Pat(pat) => {
374 s.synth_comment(format!("pat {}", pat.id))
380 impl<'hir> HirPrinterSupport<'hir> for IdentifiedAnnotation<'hir> {
381 fn sess<'a>(&'a self) -> &'a Session {
385 fn hir_map<'a>(&'a self) -> Option<&'a hir_map::Map<'hir>> {
386 self.hir_map.as_ref()
389 fn pp_ann<'a>(&'a self) -> &'a dyn pprust_hir::PpAnn {
394 impl<'hir> pprust_hir::PpAnn for IdentifiedAnnotation<'hir> {
395 fn nested(&self, state: &mut pprust_hir::State, nested: pprust_hir::Nested)
397 if let Some(ref map) = self.hir_map {
398 pprust_hir::PpAnn::nested(map, state, nested)
403 fn pre(&self, s: &mut pprust_hir::State, node: pprust_hir::AnnNode) -> io::Result<()> {
405 pprust_hir::AnnNode::Expr(_) => s.popen(),
409 fn post(&self, s: &mut pprust_hir::State, node: pprust_hir::AnnNode) -> io::Result<()> {
411 pprust_hir::AnnNode::Name(_) => Ok(()),
412 pprust_hir::AnnNode::Item(item) => {
414 s.synth_comment(format!("node_id: {} hir local_id: {}",
415 item.id, item.hir_id.local_id.as_u32()))
417 pprust_hir::AnnNode::SubItem(id) => {
419 s.synth_comment(id.to_string())
421 pprust_hir::AnnNode::Block(blk) => {
423 s.synth_comment(format!("block hir_id: {} hir local_id: {}",
424 blk.hir_id, blk.hir_id.local_id.as_u32()))
426 pprust_hir::AnnNode::Expr(expr) => {
428 s.synth_comment(format!("node_id: {} hir local_id: {}",
429 expr.id, expr.hir_id.local_id.as_u32()))?;
432 pprust_hir::AnnNode::Pat(pat) => {
434 s.synth_comment(format!("pat node_id: {} hir local_id: {}",
435 pat.id, pat.hir_id.local_id.as_u32()))
441 struct HygieneAnnotation<'a> {
445 impl<'a> PrinterSupport for HygieneAnnotation<'a> {
446 fn sess(&self) -> &Session {
450 fn pp_ann(&self) -> &dyn pprust::PpAnn {
455 impl<'a> pprust::PpAnn for HygieneAnnotation<'a> {
456 fn post(&self, s: &mut pprust::State, node: pprust::AnnNode) -> io::Result<()> {
458 pprust::AnnNode::Ident(&ast::Ident { name, span }) => {
460 // FIXME #16420: this doesn't display the connections
461 // between syntax contexts
462 s.synth_comment(format!("{}{:?}", name.as_u32(), span.ctxt()))
464 pprust::AnnNode::Name(&name) => {
466 s.synth_comment(name.as_u32().to_string())
474 struct TypedAnnotation<'a, 'tcx: 'a> {
475 tcx: TyCtxt<'a, 'tcx, 'tcx>,
476 tables: Cell<&'a ty::TypeckTables<'tcx>>,
479 impl<'b, 'tcx> HirPrinterSupport<'tcx> for TypedAnnotation<'b, 'tcx> {
480 fn sess<'a>(&'a self) -> &'a Session {
484 fn hir_map<'a>(&'a self) -> Option<&'a hir_map::Map<'tcx>> {
485 Some(&self.tcx.hir())
488 fn pp_ann<'a>(&'a self) -> &'a dyn pprust_hir::PpAnn {
492 fn node_path(&self, id: ast::NodeId) -> Option<String> {
493 Some(self.tcx.node_path_str(id))
497 impl<'a, 'tcx> pprust_hir::PpAnn for TypedAnnotation<'a, 'tcx> {
498 fn nested(&self, state: &mut pprust_hir::State, nested: pprust_hir::Nested)
500 let old_tables = self.tables.get();
501 if let pprust_hir::Nested::Body(id) = nested {
502 self.tables.set(self.tcx.body_tables(id));
504 pprust_hir::PpAnn::nested(self.tcx.hir(), state, nested)?;
505 self.tables.set(old_tables);
508 fn pre(&self, s: &mut pprust_hir::State, node: pprust_hir::AnnNode) -> io::Result<()> {
510 pprust_hir::AnnNode::Expr(_) => s.popen(),
514 fn post(&self, s: &mut pprust_hir::State, node: pprust_hir::AnnNode) -> io::Result<()> {
516 pprust_hir::AnnNode::Expr(expr) => {
520 s.s.word(self.tables.get().expr_ty(expr).to_string())?;
528 fn gather_flowgraph_variants(sess: &Session) -> Vec<borrowck_dot::Variant> {
529 let print_loans = sess.opts.debugging_opts.flowgraph_print_loans;
530 let print_moves = sess.opts.debugging_opts.flowgraph_print_moves;
531 let print_assigns = sess.opts.debugging_opts.flowgraph_print_assigns;
532 let print_all = sess.opts.debugging_opts.flowgraph_print_all;
533 let mut variants = Vec::new();
534 if print_all || print_loans {
535 variants.push(borrowck_dot::Loans);
537 if print_all || print_moves {
538 variants.push(borrowck_dot::Moves);
540 if print_all || print_assigns {
541 variants.push(borrowck_dot::Assigns);
546 #[derive(Clone, Debug)]
547 pub enum UserIdentifiedItem {
548 ItemViaNode(ast::NodeId),
549 ItemViaPath(Vec<String>),
552 impl FromStr for UserIdentifiedItem {
554 fn from_str(s: &str) -> Result<UserIdentifiedItem, ()> {
556 .map(ast::NodeId::from_u32)
558 .unwrap_or_else(|_| ItemViaPath(s.split("::").map(|s| s.to_string()).collect())))
562 enum NodesMatchingUII<'a, 'hir: 'a> {
563 NodesMatchingDirect(option::IntoIter<ast::NodeId>),
564 NodesMatchingSuffix(hir_map::NodesMatchingSuffix<'a, 'hir>),
567 impl<'a, 'hir> Iterator for NodesMatchingUII<'a, 'hir> {
568 type Item = ast::NodeId;
570 fn next(&mut self) -> Option<ast::NodeId> {
572 &mut NodesMatchingDirect(ref mut iter) => iter.next(),
573 &mut NodesMatchingSuffix(ref mut iter) => iter.next(),
577 fn size_hint(&self) -> (usize, Option<usize>) {
579 &NodesMatchingDirect(ref iter) => iter.size_hint(),
580 &NodesMatchingSuffix(ref iter) => iter.size_hint(),
585 impl UserIdentifiedItem {
586 fn reconstructed_input(&self) -> String {
588 ItemViaNode(node_id) => node_id.to_string(),
589 ItemViaPath(ref parts) => parts.join("::"),
593 fn all_matching_node_ids<'a, 'hir>(&'a self,
594 map: &'a hir_map::Map<'hir>)
595 -> NodesMatchingUII<'a, 'hir> {
597 ItemViaNode(node_id) => NodesMatchingDirect(Some(node_id).into_iter()),
598 ItemViaPath(ref parts) => NodesMatchingSuffix(map.nodes_matching_suffix(&parts)),
602 fn to_one_node_id(self, user_option: &str, sess: &Session, map: &hir_map::Map) -> ast::NodeId {
603 let fail_because = |is_wrong_because| -> ast::NodeId {
604 let message = format!("{} needs NodeId (int) or unique path suffix (b::c::d); got \
607 self.reconstructed_input(),
612 let mut saw_node = ast::DUMMY_NODE_ID;
614 for node in self.all_matching_node_ids(map) {
618 fail_because("does not resolve uniquely");
622 fail_because("does not resolve to any item");
630 // Note: Also used by librustdoc, see PR #43348. Consider moving this struct elsewhere.
632 // FIXME: Currently the `everybody_loops` transformation is not applied to:
633 // * `const fn`, due to issue #43636 that `loop` is not supported for const evaluation. We are
634 // waiting for miri to fix that.
635 // * `impl Trait`, due to issue #43869 that functions returning impl Trait cannot be diverging.
636 // Solving this may require `!` to implement every trait, which relies on the an even more
637 // ambitious form of the closed RFC #1637. See also [#34511].
639 // [#34511]: https://github.com/rust-lang/rust/issues/34511#issuecomment-322340401
640 pub struct ReplaceBodyWithLoop<'a> {
641 within_static_or_const: bool,
642 nested_blocks: Option<Vec<ast::Block>>,
646 impl<'a> ReplaceBodyWithLoop<'a> {
647 pub fn new(sess: &'a Session) -> ReplaceBodyWithLoop<'a> {
648 ReplaceBodyWithLoop {
649 within_static_or_const: false,
655 fn run<R, F: FnOnce(&mut Self) -> R>(&mut self, is_const: bool, action: F) -> R {
656 let old_const = mem::replace(&mut self.within_static_or_const, is_const);
657 let old_blocks = self.nested_blocks.take();
658 let ret = action(self);
659 self.within_static_or_const = old_const;
660 self.nested_blocks = old_blocks;
664 fn should_ignore_fn(ret_ty: &ast::FnDecl) -> bool {
665 if let ast::FunctionRetTy::Ty(ref ty) = ret_ty.output {
666 fn involves_impl_trait(ty: &ast::Ty) -> bool {
668 ast::TyKind::ImplTrait(..) => true,
669 ast::TyKind::Slice(ref subty) |
670 ast::TyKind::Array(ref subty, _) |
671 ast::TyKind::Ptr(ast::MutTy { ty: ref subty, .. }) |
672 ast::TyKind::Rptr(_, ast::MutTy { ty: ref subty, .. }) |
673 ast::TyKind::Paren(ref subty) => involves_impl_trait(subty),
674 ast::TyKind::Tup(ref tys) => any_involves_impl_trait(tys.iter()),
675 ast::TyKind::Path(_, ref path) => path.segments.iter().any(|seg| {
676 match seg.args.as_ref().map(|generic_arg| &**generic_arg) {
678 Some(&ast::GenericArgs::AngleBracketed(ref data)) => {
679 let types = data.args.iter().filter_map(|arg| match arg {
680 ast::GenericArg::Type(ty) => Some(ty),
683 any_involves_impl_trait(types.into_iter()) ||
684 any_involves_impl_trait(data.bindings.iter().map(|b| &b.ty))
686 Some(&ast::GenericArgs::Parenthesized(ref data)) => {
687 any_involves_impl_trait(data.inputs.iter()) ||
688 any_involves_impl_trait(data.output.iter())
696 fn any_involves_impl_trait<'a, I: Iterator<Item = &'a P<ast::Ty>>>(mut it: I) -> bool {
697 it.any(|subty| involves_impl_trait(subty))
700 involves_impl_trait(ty)
707 impl<'a> MutVisitor for ReplaceBodyWithLoop<'a> {
708 fn visit_item_kind(&mut self, i: &mut ast::ItemKind) {
709 let is_const = match i {
710 ast::ItemKind::Static(..) | ast::ItemKind::Const(..) => true,
711 ast::ItemKind::Fn(ref decl, ref header, _, _) =>
712 header.constness.node == ast::Constness::Const || Self::should_ignore_fn(decl),
715 self.run(is_const, |s| noop_visit_item_kind(i, s))
718 fn flat_map_trait_item(&mut self, i: ast::TraitItem) -> SmallVec<[ast::TraitItem; 1]> {
719 let is_const = match i.node {
720 ast::TraitItemKind::Const(..) => true,
721 ast::TraitItemKind::Method(ast::MethodSig { ref decl, ref header, .. }, _) =>
722 header.constness.node == ast::Constness::Const || Self::should_ignore_fn(decl),
725 self.run(is_const, |s| noop_flat_map_trait_item(i, s))
728 fn flat_map_impl_item(&mut self, i: ast::ImplItem) -> SmallVec<[ast::ImplItem; 1]> {
729 let is_const = match i.node {
730 ast::ImplItemKind::Const(..) => true,
731 ast::ImplItemKind::Method(ast::MethodSig { ref decl, ref header, .. }, _) =>
732 header.constness.node == ast::Constness::Const || Self::should_ignore_fn(decl),
735 self.run(is_const, |s| noop_flat_map_impl_item(i, s))
738 fn visit_anon_const(&mut self, c: &mut ast::AnonConst) {
739 self.run(true, |s| noop_visit_anon_const(c, s))
742 fn visit_block(&mut self, b: &mut P<ast::Block>) {
743 fn stmt_to_block(rules: ast::BlockCheckMode,
744 s: Option<ast::Stmt>,
745 sess: &Session) -> ast::Block {
747 stmts: s.into_iter().collect(),
749 id: sess.next_node_id(),
750 span: syntax_pos::DUMMY_SP,
754 fn block_to_stmt(b: ast::Block, sess: &Session) -> ast::Stmt {
755 let expr = P(ast::Expr {
756 id: sess.next_node_id(),
757 node: ast::ExprKind::Block(P(b), None),
758 span: syntax_pos::DUMMY_SP,
759 attrs: ThinVec::new(),
763 id: sess.next_node_id(),
764 node: ast::StmtKind::Expr(expr),
765 span: syntax_pos::DUMMY_SP,
769 let empty_block = stmt_to_block(BlockCheckMode::Default, None, self.sess);
770 let loop_expr = P(ast::Expr {
771 node: ast::ExprKind::Loop(P(empty_block), None),
772 id: self.sess.next_node_id(),
773 span: syntax_pos::DUMMY_SP,
774 attrs: ThinVec::new(),
777 let loop_stmt = ast::Stmt {
778 id: self.sess.next_node_id(),
779 span: syntax_pos::DUMMY_SP,
780 node: ast::StmtKind::Expr(loop_expr),
783 if self.within_static_or_const {
784 noop_visit_block(b, self)
786 visit_clobber(b.deref_mut(), |b| {
787 let mut stmts = vec![];
789 let old_blocks = self.nested_blocks.replace(vec![]);
791 stmts.extend(self.flat_map_stmt(s).into_iter().filter(|s| s.is_item()));
793 // we put a Some in there earlier with that replace(), so this is valid
794 let new_blocks = self.nested_blocks.take().unwrap();
795 self.nested_blocks = old_blocks;
796 stmts.extend(new_blocks.into_iter().map(|b| block_to_stmt(b, &self.sess)));
799 let mut new_block = ast::Block {
804 if let Some(old_blocks) = self.nested_blocks.as_mut() {
805 //push our fresh block onto the cache and yield an empty block with `loop {}`
806 if !new_block.stmts.is_empty() {
807 old_blocks.push(new_block);
810 stmt_to_block(b.rules, Some(loop_stmt), self.sess)
812 //push `loop {}` onto the end of our fresh block and yield that
813 new_block.stmts.push(loop_stmt);
821 // in general the pretty printer processes unexpanded code, so
822 // we override the default `visit_mac` method which panics.
823 fn visit_mac(&mut self, mac: &mut ast::Mac) {
824 noop_visit_mac(mac, self)
828 fn print_flowgraph<'a, 'tcx, W: Write>(variants: Vec<borrowck_dot::Variant>,
829 tcx: TyCtxt<'a, 'tcx, 'tcx>,
830 code: blocks::Code<'tcx>,
831 mode: PpFlowGraphMode,
834 let body_id = match code {
835 blocks::Code::Expr(expr) => {
836 // Find the function this expression is from.
837 let mut node_id = expr.id;
839 let node = tcx.hir().get(node_id);
840 if let Some(n) = hir::map::blocks::FnLikeNode::from_node(node) {
843 let parent = tcx.hir().get_parent_node(node_id);
844 assert_ne!(node_id, parent);
848 blocks::Code::FnLike(fn_like) => fn_like.body(),
850 let body = tcx.hir().body(body_id);
851 let cfg = cfg::CFG::new(tcx, &body);
852 let labelled_edges = mode != PpFlowGraphMode::UnlabelledEdges;
853 let lcfg = LabelledCFG {
856 name: format!("node_{}", code.id()),
861 _ if variants.is_empty() => {
862 let r = dot::render(&lcfg, &mut out);
863 return expand_err_details(r);
865 blocks::Code::Expr(_) => {
866 tcx.sess.err("--pretty flowgraph with -Z flowgraph-print annotations requires \
870 blocks::Code::FnLike(fn_like) => {
871 let (bccx, analysis_data) =
872 borrowck::build_borrowck_dataflow_data_for_fn(tcx, fn_like.body(), &cfg);
874 let lcfg = borrowck_dot::DataflowLabeller {
877 borrowck_ctxt: &bccx,
878 analysis_data: &analysis_data,
880 let r = dot::render(&lcfg, &mut out);
881 return expand_err_details(r);
885 fn expand_err_details(r: io::Result<()>) -> io::Result<()> {
887 io::Error::new(io::ErrorKind::Other,
888 format!("graphviz::render failed: {}", ioerr))
893 pub fn visit_crate(sess: &Session, krate: &mut ast::Crate, ppm: PpMode) {
894 if let PpmSource(PpmEveryBodyLoops) = ppm {
895 ReplaceBodyWithLoop::new(sess).visit_crate(krate);
899 fn get_source(input: &Input, sess: &Session) -> (Vec<u8>, FileName) {
900 let src_name = driver::source_name(input);
901 let src = sess.source_map()
902 .get_source_file(&src_name)
912 fn write_output(out: Vec<u8>, ofile: Option<&Path>) {
914 None => print!("{}", String::from_utf8(out).unwrap()),
916 match File::create(p) {
917 Ok(mut w) => w.write_all(&out).unwrap(),
918 Err(e) => panic!("print-print failed to open {} due to {}", p.display(), e),
924 pub fn print_after_parsing(sess: &Session,
928 ofile: Option<&Path>) {
929 let (src, src_name) = get_source(input, sess);
932 let mut out = Vec::new();
934 if let PpmSource(s) = ppm {
935 // Silently ignores an identified node.
936 let out: &mut dyn Write = &mut out;
937 s.call_with_pp_support(sess, None, move |annotation| {
938 debug!("pretty printing source code {:?}", s);
939 let sess = annotation.sess();
940 pprust::print_crate(sess.source_map(),
953 write_output(out, ofile);
956 pub fn print_after_hir_lowering<'tcx, 'a: 'tcx>(sess: &'a Session,
957 cstore: &'tcx CStore,
958 hir_map: &hir_map::Map<'tcx>,
959 resolutions: &Resolutions,
964 output_filenames: &OutputFilenames,
965 opt_uii: Option<UserIdentifiedItem>,
966 ofile: Option<&Path>) {
967 if ppm.needs_analysis() {
968 print_with_analysis(sess,
980 let (src, src_name) = get_source(input, sess);
982 let mut rdr = &src[..];
983 let mut out = Vec::new();
985 match (ppm, opt_uii) {
986 (PpmSource(s), _) => {
987 // Silently ignores an identified node.
988 let out: &mut dyn Write = &mut out;
989 s.call_with_pp_support(sess, Some(hir_map), move |annotation| {
990 debug!("pretty printing source code {:?}", s);
991 let sess = annotation.sess();
992 pprust::print_crate(sess.source_map(),
1003 (PpmHir(s), None) => {
1004 let out: &mut dyn Write = &mut out;
1005 s.call_with_pp_support_hir(sess,
1011 move |annotation, krate| {
1012 debug!("pretty printing source code {:?}", s);
1013 let sess = annotation.sess();
1014 pprust_hir::print_crate(sess.source_map(),
1020 annotation.pp_ann(),
1025 (PpmHirTree(s), None) => {
1026 let out: &mut dyn Write = &mut out;
1027 s.call_with_pp_support_hir(sess,
1033 move |_annotation, krate| {
1034 debug!("pretty printing source code {:?}", s);
1035 write!(out, "{:#?}", krate)
1039 (PpmHir(s), Some(uii)) => {
1040 let out: &mut dyn Write = &mut out;
1041 s.call_with_pp_support_hir(sess,
1047 move |annotation, _| {
1048 debug!("pretty printing source code {:?}", s);
1049 let sess = annotation.sess();
1050 let hir_map = annotation.hir_map().expect("-Z unpretty missing HIR map");
1051 let mut pp_state = pprust_hir::State::new_from_input(sess.source_map(),
1056 annotation.pp_ann(),
1058 for node_id in uii.all_matching_node_ids(hir_map) {
1059 let node = hir_map.get(node_id);
1060 pp_state.print_node(node)?;
1061 pp_state.s.space()?;
1062 let path = annotation.node_path(node_id)
1063 .expect("-Z unpretty missing node paths");
1064 pp_state.synth_comment(path)?;
1065 pp_state.s.hardbreak()?;
1071 (PpmHirTree(s), Some(uii)) => {
1072 let out: &mut dyn Write = &mut out;
1073 s.call_with_pp_support_hir(sess,
1079 move |_annotation, _krate| {
1080 debug!("pretty printing source code {:?}", s);
1081 for node_id in uii.all_matching_node_ids(hir_map) {
1082 let node = hir_map.get(node_id);
1083 write!(out, "{:#?}", node)?;
1089 _ => unreachable!(),
1093 write_output(out, ofile);
1096 // In an ideal world, this would be a public function called by the driver after
1097 // analysis is performed. However, we want to call `phase_3_run_analysis_passes`
1098 // with a different callback than the standard driver, so that isn't easy.
1099 // Instead, we call that function ourselves.
1100 fn print_with_analysis<'tcx, 'a: 'tcx>(sess: &'a Session,
1102 hir_map: &hir_map::Map<'tcx>,
1103 resolutions: &Resolutions,
1105 output_filenames: &OutputFilenames,
1107 uii: Option<UserIdentifiedItem>,
1108 ofile: Option<&Path>) {
1109 let nodeid = if let Some(uii) = uii {
1110 debug!("pretty printing for {:?}", uii);
1111 Some(uii.to_one_node_id("-Z unpretty", sess, &hir_map))
1113 debug!("pretty printing for whole crate");
1117 let mut out = Vec::new();
1119 let control = &driver::CompileController::basic();
1120 let codegen_backend = ::get_codegen_backend(sess);
1121 let mut arenas = AllArenas::new();
1122 abort_on_err(driver::phase_3_run_analysis_passes(&*codegen_backend,
1127 resolutions.clone(),
1133 PpmMir | PpmMirCFG => {
1134 if let Some(nodeid) = nodeid {
1135 let def_id = tcx.hir().local_def_id(nodeid);
1137 PpmMir => write_mir_pretty(tcx, Some(def_id), &mut out),
1138 PpmMirCFG => write_mir_graphviz(tcx, Some(def_id), &mut out),
1139 _ => unreachable!(),
1143 PpmMir => write_mir_pretty(tcx, None, &mut out),
1144 PpmMirCFG => write_mir_graphviz(tcx, None, &mut out),
1145 _ => unreachable!(),
1150 PpmFlowGraph(mode) => {
1152 nodeid.expect("`pretty flowgraph=..` needs NodeId (int) or unique path \
1154 let node = tcx.hir().find(nodeid).unwrap_or_else(|| {
1155 tcx.sess.fatal(&format!("--pretty flowgraph couldn't find id: {}", nodeid))
1158 match blocks::Code::from_node(&tcx.hir(), nodeid) {
1160 let variants = gather_flowgraph_variants(tcx.sess);
1162 let out: &mut dyn Write = &mut out;
1164 print_flowgraph(variants, tcx, code, mode, out)
1167 let message = format!("--pretty=flowgraph needs block, fn, or method; \
1171 tcx.sess.span_fatal(tcx.hir().span(nodeid), &message)
1175 _ => unreachable!(),
1181 write_output(out, ofile);