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::fold::{self, Folder};
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};
33 use std::str::FromStr;
36 pub use self::UserIdentifiedItem::*;
37 pub use self::PpSourceMode::*;
38 pub use self::PpMode::*;
39 use self::NodesMatchingUII::*;
40 use {abort_on_err, driver};
42 #[derive(Copy, Clone, PartialEq, Debug)]
43 pub enum PpSourceMode {
48 PpmExpandedIdentified,
53 #[derive(Copy, Clone, PartialEq, Debug)]
54 pub enum PpFlowGraphMode {
56 /// Drops the labels from the edges in the flowgraph output. This
57 /// is mostly for use in the -Z unpretty flowgraph run-make tests,
58 /// since the labels are largely uninteresting in those cases and
59 /// have become a pain to maintain.
62 #[derive(Copy, Clone, PartialEq, Debug)]
64 PpmSource(PpSourceMode),
66 PpmHirTree(PpSourceMode),
67 PpmFlowGraph(PpFlowGraphMode),
73 pub fn needs_ast_map(&self, opt_uii: &Option<UserIdentifiedItem>) -> bool {
75 PpmSource(PpmNormal) |
76 PpmSource(PpmEveryBodyLoops) |
77 PpmSource(PpmIdentified) => opt_uii.is_some(),
79 PpmSource(PpmExpanded) |
80 PpmSource(PpmExpandedIdentified) |
81 PpmSource(PpmExpandedHygiene) |
86 PpmFlowGraph(_) => true,
87 PpmSource(PpmTyped) => panic!("invalid state"),
91 pub fn needs_analysis(&self) -> bool {
93 PpmMir | PpmMirCFG | PpmFlowGraph(_) => true,
99 pub fn parse_pretty(sess: &Session,
102 -> (PpMode, Option<UserIdentifiedItem>) {
103 let mut split = name.splitn(2, '=');
104 let first = split.next().unwrap();
105 let opt_second = split.next();
106 let first = match (first, extended) {
107 ("normal", _) => PpmSource(PpmNormal),
108 ("identified", _) => PpmSource(PpmIdentified),
109 ("everybody_loops", true) => PpmSource(PpmEveryBodyLoops),
110 ("expanded", _) => PpmSource(PpmExpanded),
111 ("expanded,identified", _) => PpmSource(PpmExpandedIdentified),
112 ("expanded,hygiene", _) => PpmSource(PpmExpandedHygiene),
113 ("hir", true) => PpmHir(PpmNormal),
114 ("hir,identified", true) => PpmHir(PpmIdentified),
115 ("hir,typed", true) => PpmHir(PpmTyped),
116 ("hir-tree", true) => PpmHirTree(PpmNormal),
117 ("mir", true) => PpmMir,
118 ("mir-cfg", true) => PpmMirCFG,
119 ("flowgraph", true) => PpmFlowGraph(PpFlowGraphMode::Default),
120 ("flowgraph,unlabelled", true) => PpmFlowGraph(PpFlowGraphMode::UnlabelledEdges),
123 sess.fatal(&format!("argument to `unpretty` must be one of `normal`, \
124 `expanded`, `flowgraph[,unlabelled]=<nodeid>`, \
125 `identified`, `expanded,identified`, `everybody_loops`, \
126 `hir`, `hir,identified`, `hir,typed`, `hir-tree`, \
127 `mir` or `mir-cfg`; got {}",
130 sess.fatal(&format!("argument to `pretty` must be one of `normal`, `expanded`, \
131 `identified`, or `expanded,identified`; got {}",
136 let opt_second = opt_second.and_then(|s| s.parse::<UserIdentifiedItem>().ok());
142 // This slightly awkward construction is to allow for each PpMode to
143 // choose whether it needs to do analyses (which can consume the
144 // Session) and then pass through the session (now attached to the
145 // analysis results) on to the chosen pretty-printer, along with the
148 // Note that since the `&PrinterSupport` is freshly constructed on each
149 // call, it would not make sense to try to attach the lifetime of `self`
150 // to the lifetime of the `&PrinterObject`.
152 // (The `use_once_payload` is working around the current lack of once
153 // functions in the compiler.)
156 /// Constructs a `PrinterSupport` object and passes it to `f`.
157 fn call_with_pp_support<'tcx, A, F>(&self,
159 hir_map: Option<&hir_map::Map<'tcx>>,
162 where F: FnOnce(&dyn PrinterSupport) -> A
165 PpmNormal | PpmEveryBodyLoops | PpmExpanded => {
166 let annotation = NoAnn {
168 hir_map: hir_map.map(|m| m.clone()),
173 PpmIdentified | PpmExpandedIdentified => {
174 let annotation = IdentifiedAnnotation {
176 hir_map: hir_map.map(|m| m.clone()),
180 PpmExpandedHygiene => {
181 let annotation = HygieneAnnotation {
186 _ => panic!("Should use call_with_pp_support_hir"),
189 fn call_with_pp_support_hir<'tcx, A, F>(
192 cstore: &'tcx CStore,
193 hir_map: &hir_map::Map<'tcx>,
194 resolutions: &Resolutions,
195 output_filenames: &OutputFilenames,
199 where F: FnOnce(&dyn HirPrinterSupport, &hir::Crate) -> A
203 let annotation = NoAnn {
205 hir_map: Some(hir_map.clone()),
207 f(&annotation, hir_map.forest.krate())
211 let annotation = IdentifiedAnnotation {
213 hir_map: Some(hir_map.clone()),
215 f(&annotation, hir_map.forest.krate())
218 let control = &driver::CompileController::basic();
219 let codegen_backend = ::get_codegen_backend(sess);
220 let mut arenas = AllArenas::new();
221 abort_on_err(driver::phase_3_run_analysis_passes(&*codegen_backend,
231 let empty_tables = ty::TypeckTables::empty(None);
232 let annotation = TypedAnnotation {
234 tables: Cell::new(&empty_tables)
236 tcx.dep_graph.with_ignore(|| {
237 f(&annotation, hir_map.forest.krate())
242 _ => panic!("Should use call_with_pp_support"),
247 trait PrinterSupport: pprust::PpAnn {
248 /// Provides a uniform interface for re-extracting a reference to a
249 /// `Session` from a value that now owns it.
250 fn sess<'a>(&'a self) -> &'a Session;
252 /// Produces the pretty-print annotation object.
254 /// (Rust does not yet support upcasting from a trait object to
255 /// an object for one of its super-traits.)
256 fn pp_ann<'a>(&'a self) -> &'a dyn pprust::PpAnn;
259 trait HirPrinterSupport<'hir>: pprust_hir::PpAnn {
260 /// Provides a uniform interface for re-extracting a reference to a
261 /// `Session` from a value that now owns it.
262 fn sess<'a>(&'a self) -> &'a Session;
264 /// Provides a uniform interface for re-extracting a reference to an
265 /// `hir_map::Map` from a value that now owns it.
266 fn hir_map<'a>(&'a self) -> Option<&'a hir_map::Map<'hir>>;
268 /// Produces the pretty-print annotation object.
270 /// (Rust does not yet support upcasting from a trait object to
271 /// an object for one of its super-traits.)
272 fn pp_ann<'a>(&'a self) -> &'a dyn pprust_hir::PpAnn;
274 /// Computes an user-readable representation of a path, if possible.
275 fn node_path(&self, id: ast::NodeId) -> Option<String> {
276 self.hir_map().and_then(|map| map.def_path_from_id(id)).map(|path| {
279 .map(|elem| elem.data.to_string())
288 hir_map: Option<hir_map::Map<'hir>>,
291 impl<'hir> PrinterSupport for NoAnn<'hir> {
292 fn sess<'a>(&'a self) -> &'a Session {
296 fn pp_ann<'a>(&'a self) -> &'a dyn pprust::PpAnn {
301 impl<'hir> HirPrinterSupport<'hir> for NoAnn<'hir> {
302 fn sess<'a>(&'a self) -> &'a Session {
306 fn hir_map<'a>(&'a self) -> Option<&'a hir_map::Map<'hir>> {
307 self.hir_map.as_ref()
310 fn pp_ann<'a>(&'a self) -> &'a dyn pprust_hir::PpAnn {
315 impl<'hir> pprust::PpAnn for NoAnn<'hir> {}
316 impl<'hir> pprust_hir::PpAnn for NoAnn<'hir> {
317 fn nested(&self, state: &mut pprust_hir::State, nested: pprust_hir::Nested)
319 if let Some(ref map) = self.hir_map {
320 pprust_hir::PpAnn::nested(map, state, nested)
327 struct IdentifiedAnnotation<'hir> {
329 hir_map: Option<hir_map::Map<'hir>>,
332 impl<'hir> PrinterSupport for IdentifiedAnnotation<'hir> {
333 fn sess<'a>(&'a self) -> &'a Session {
337 fn pp_ann<'a>(&'a self) -> &'a dyn pprust::PpAnn {
342 impl<'hir> pprust::PpAnn for IdentifiedAnnotation<'hir> {
343 fn pre(&self, s: &mut pprust::State, node: pprust::AnnNode) -> io::Result<()> {
345 pprust::AnnNode::Expr(_) => s.popen(),
349 fn post(&self, s: &mut pprust::State, node: pprust::AnnNode) -> io::Result<()> {
351 pprust::AnnNode::Ident(_) |
352 pprust::AnnNode::Name(_) => Ok(()),
354 pprust::AnnNode::Item(item) => {
356 s.synth_comment(item.id.to_string())
358 pprust::AnnNode::SubItem(id) => {
360 s.synth_comment(id.to_string())
362 pprust::AnnNode::Block(blk) => {
364 s.synth_comment(format!("block {}", blk.id))
366 pprust::AnnNode::Expr(expr) => {
368 s.synth_comment(expr.id.to_string())?;
371 pprust::AnnNode::Pat(pat) => {
373 s.synth_comment(format!("pat {}", pat.id))
379 impl<'hir> HirPrinterSupport<'hir> for IdentifiedAnnotation<'hir> {
380 fn sess<'a>(&'a self) -> &'a Session {
384 fn hir_map<'a>(&'a self) -> Option<&'a hir_map::Map<'hir>> {
385 self.hir_map.as_ref()
388 fn pp_ann<'a>(&'a self) -> &'a dyn pprust_hir::PpAnn {
393 impl<'hir> pprust_hir::PpAnn for IdentifiedAnnotation<'hir> {
394 fn nested(&self, state: &mut pprust_hir::State, nested: pprust_hir::Nested)
396 if let Some(ref map) = self.hir_map {
397 pprust_hir::PpAnn::nested(map, state, nested)
402 fn pre(&self, s: &mut pprust_hir::State, node: pprust_hir::AnnNode) -> io::Result<()> {
404 pprust_hir::AnnNode::Expr(_) => s.popen(),
408 fn post(&self, s: &mut pprust_hir::State, node: pprust_hir::AnnNode) -> io::Result<()> {
410 pprust_hir::AnnNode::Name(_) => Ok(()),
411 pprust_hir::AnnNode::Item(item) => {
413 s.synth_comment(format!("node_id: {} hir local_id: {}",
414 item.id, item.hir_id.local_id.as_u32()))
416 pprust_hir::AnnNode::SubItem(id) => {
418 s.synth_comment(id.to_string())
420 pprust_hir::AnnNode::Block(blk) => {
422 s.synth_comment(format!("block node_id: {} hir local_id: {}",
423 blk.id, blk.hir_id.local_id.as_u32()))
425 pprust_hir::AnnNode::Expr(expr) => {
427 s.synth_comment(format!("node_id: {} hir local_id: {}",
428 expr.id, expr.hir_id.local_id.as_u32()))?;
431 pprust_hir::AnnNode::Pat(pat) => {
433 s.synth_comment(format!("pat node_id: {} hir local_id: {}",
434 pat.id, pat.hir_id.local_id.as_u32()))
440 struct HygieneAnnotation<'a> {
444 impl<'a> PrinterSupport for HygieneAnnotation<'a> {
445 fn sess(&self) -> &Session {
449 fn pp_ann(&self) -> &dyn 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::AnnNode::Ident(&ast::Ident { name, span }) => {
459 // FIXME #16420: this doesn't display the connections
460 // between syntax contexts
461 s.synth_comment(format!("{}{:?}", name.as_u32(), span.ctxt()))
463 pprust::AnnNode::Name(&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>> {
484 Some(&self.tcx.hir())
487 fn pp_ann<'a>(&'a self) -> &'a dyn 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::AnnNode::Expr(_) => s.popen(),
513 fn post(&self, s: &mut pprust_hir::State, node: pprust_hir::AnnNode) -> io::Result<()> {
515 pprust_hir::AnnNode::Expr(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::from_u32)
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(),
576 fn size_hint(&self) -> (usize, Option<usize>) {
578 &NodesMatchingDirect(ref iter) => iter.size_hint(),
579 &NodesMatchingSuffix(ref iter) => iter.size_hint(),
584 impl UserIdentifiedItem {
585 fn reconstructed_input(&self) -> String {
587 ItemViaNode(node_id) => node_id.to_string(),
588 ItemViaPath(ref parts) => parts.join("::"),
592 fn all_matching_node_ids<'a, 'hir>(&'a self,
593 map: &'a hir_map::Map<'hir>)
594 -> NodesMatchingUII<'a, 'hir> {
596 ItemViaNode(node_id) => NodesMatchingDirect(Some(node_id).into_iter()),
597 ItemViaPath(ref parts) => NodesMatchingSuffix(map.nodes_matching_suffix(&parts)),
601 fn to_one_node_id(self, user_option: &str, sess: &Session, map: &hir_map::Map) -> ast::NodeId {
602 let fail_because = |is_wrong_because| -> ast::NodeId {
603 let message = format!("{} needs NodeId (int) or unique path suffix (b::c::d); got \
606 self.reconstructed_input(),
611 let mut saw_node = ast::DUMMY_NODE_ID;
613 for node in self.all_matching_node_ids(map) {
617 fail_because("does not resolve uniquely");
621 fail_because("does not resolve to any item");
629 // Note: Also used by librustdoc, see PR #43348. Consider moving this struct elsewhere.
631 // FIXME: Currently the `everybody_loops` transformation is not applied to:
632 // * `const fn`, due to issue #43636 that `loop` is not supported for const evaluation. We are
633 // waiting for miri to fix that.
634 // * `impl Trait`, due to issue #43869 that functions returning impl Trait cannot be diverging.
635 // Solving this may require `!` to implement every trait, which relies on the an even more
636 // ambitious form of the closed RFC #1637. See also [#34511].
638 // [#34511]: https://github.com/rust-lang/rust/issues/34511#issuecomment-322340401
639 pub struct ReplaceBodyWithLoop<'a> {
640 within_static_or_const: bool,
641 nested_blocks: Option<Vec<ast::Block>>,
645 impl<'a> ReplaceBodyWithLoop<'a> {
646 pub fn new(sess: &'a Session) -> ReplaceBodyWithLoop<'a> {
647 ReplaceBodyWithLoop {
648 within_static_or_const: false,
654 fn run<R, F: FnOnce(&mut Self) -> R>(&mut self, is_const: bool, action: F) -> R {
655 let old_const = mem::replace(&mut self.within_static_or_const, is_const);
656 let old_blocks = self.nested_blocks.take();
657 let ret = action(self);
658 self.within_static_or_const = old_const;
659 self.nested_blocks = old_blocks;
663 fn should_ignore_fn(ret_ty: &ast::FnDecl) -> bool {
664 if let ast::FunctionRetTy::Ty(ref ty) = ret_ty.output {
665 fn involves_impl_trait(ty: &ast::Ty) -> bool {
667 ast::TyKind::ImplTrait(..) => true,
668 ast::TyKind::Slice(ref subty) |
669 ast::TyKind::Array(ref subty, _) |
670 ast::TyKind::Ptr(ast::MutTy { ty: ref subty, .. }) |
671 ast::TyKind::Rptr(_, ast::MutTy { ty: ref subty, .. }) |
672 ast::TyKind::Paren(ref subty) => involves_impl_trait(subty),
673 ast::TyKind::Tup(ref tys) => any_involves_impl_trait(tys.iter()),
674 ast::TyKind::Path(_, ref path) => path.segments.iter().any(|seg| {
675 match seg.args.as_ref().map(|generic_arg| &**generic_arg) {
677 Some(&ast::GenericArgs::AngleBracketed(ref data)) => {
678 let types = data.args.iter().filter_map(|arg| match arg {
679 ast::GenericArg::Type(ty) => Some(ty),
682 any_involves_impl_trait(types.into_iter()) ||
683 any_involves_impl_trait(data.bindings.iter().map(|b| &b.ty))
685 Some(&ast::GenericArgs::Parenthesized(ref data)) => {
686 any_involves_impl_trait(data.inputs.iter()) ||
687 any_involves_impl_trait(data.output.iter())
695 fn any_involves_impl_trait<'a, I: Iterator<Item = &'a P<ast::Ty>>>(mut it: I) -> bool {
696 it.any(|subty| involves_impl_trait(subty))
699 involves_impl_trait(ty)
706 impl<'a> fold::Folder for ReplaceBodyWithLoop<'a> {
707 fn fold_item_kind(&mut self, i: ast::ItemKind) -> ast::ItemKind {
708 let is_const = match i {
709 ast::ItemKind::Static(..) | ast::ItemKind::Const(..) => true,
710 ast::ItemKind::Fn(ref decl, ref header, _, _) =>
711 header.constness.node == ast::Constness::Const || Self::should_ignore_fn(decl),
714 self.run(is_const, |s| fold::noop_fold_item_kind(i, s))
717 fn fold_trait_item(&mut self, i: ast::TraitItem) -> SmallVec<[ast::TraitItem; 1]> {
718 let is_const = match i.node {
719 ast::TraitItemKind::Const(..) => true,
720 ast::TraitItemKind::Method(ast::MethodSig { ref decl, ref header, .. }, _) =>
721 header.constness.node == ast::Constness::Const || Self::should_ignore_fn(decl),
724 self.run(is_const, |s| fold::noop_fold_trait_item(i, s))
727 fn fold_impl_item(&mut self, i: ast::ImplItem) -> SmallVec<[ast::ImplItem; 1]> {
728 let is_const = match i.node {
729 ast::ImplItemKind::Const(..) => true,
730 ast::ImplItemKind::Method(ast::MethodSig { ref decl, ref header, .. }, _) =>
731 header.constness.node == ast::Constness::Const || Self::should_ignore_fn(decl),
734 self.run(is_const, |s| fold::noop_fold_impl_item(i, s))
737 fn fold_anon_const(&mut self, c: ast::AnonConst) -> ast::AnonConst {
738 self.run(true, |s| fold::noop_fold_anon_const(c, s))
741 fn fold_block(&mut self, b: P<ast::Block>) -> P<ast::Block> {
742 fn stmt_to_block(rules: ast::BlockCheckMode,
743 s: Option<ast::Stmt>,
744 sess: &Session) -> ast::Block {
746 stmts: s.into_iter().collect(),
748 id: sess.next_node_id(),
749 span: syntax_pos::DUMMY_SP,
753 fn block_to_stmt(b: ast::Block, sess: &Session) -> ast::Stmt {
754 let expr = P(ast::Expr {
755 id: sess.next_node_id(),
756 node: ast::ExprKind::Block(P(b), None),
757 span: syntax_pos::DUMMY_SP,
758 attrs: ThinVec::new(),
762 id: sess.next_node_id(),
763 node: ast::StmtKind::Expr(expr),
764 span: syntax_pos::DUMMY_SP,
768 let empty_block = stmt_to_block(BlockCheckMode::Default, None, self.sess);
769 let loop_expr = P(ast::Expr {
770 node: ast::ExprKind::Loop(P(empty_block), None),
771 id: self.sess.next_node_id(),
772 span: syntax_pos::DUMMY_SP,
773 attrs: ThinVec::new(),
776 let loop_stmt = ast::Stmt {
777 id: self.sess.next_node_id(),
778 span: syntax_pos::DUMMY_SP,
779 node: ast::StmtKind::Expr(loop_expr),
782 if self.within_static_or_const {
783 fold::noop_fold_block(b, self)
786 let mut stmts = vec![];
788 let old_blocks = self.nested_blocks.replace(vec![]);
790 stmts.extend(self.fold_stmt(s).into_iter().filter(|s| s.is_item()));
792 // we put a Some in there earlier with that replace(), so this is valid
793 let new_blocks = self.nested_blocks.take().unwrap();
794 self.nested_blocks = old_blocks;
795 stmts.extend(new_blocks.into_iter().map(|b| block_to_stmt(b, &self.sess)));
798 let mut new_block = ast::Block {
803 if let Some(old_blocks) = self.nested_blocks.as_mut() {
804 //push our fresh block onto the cache and yield an empty block with `loop {}`
805 if !new_block.stmts.is_empty() {
806 old_blocks.push(new_block);
809 stmt_to_block(b.rules, Some(loop_stmt), self.sess)
811 //push `loop {}` onto the end of our fresh block and yield that
812 new_block.stmts.push(loop_stmt);
820 // in general the pretty printer processes unexpanded code, so
821 // we override the default `fold_mac` method which panics.
822 fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac {
823 fold::noop_fold_mac(mac, self)
827 fn print_flowgraph<'a, 'tcx, W: Write>(variants: Vec<borrowck_dot::Variant>,
828 tcx: TyCtxt<'a, 'tcx, 'tcx>,
829 code: blocks::Code<'tcx>,
830 mode: PpFlowGraphMode,
833 let body_id = match code {
834 blocks::Code::Expr(expr) => {
835 // Find the function this expression is from.
836 let mut node_id = expr.id;
838 let node = tcx.hir().get(node_id);
839 if let Some(n) = hir::map::blocks::FnLikeNode::from_node(node) {
842 let parent = tcx.hir().get_parent_node(node_id);
843 assert_ne!(node_id, parent);
847 blocks::Code::FnLike(fn_like) => fn_like.body(),
849 let body = tcx.hir().body(body_id);
850 let cfg = cfg::CFG::new(tcx, &body);
851 let labelled_edges = mode != PpFlowGraphMode::UnlabelledEdges;
852 let lcfg = LabelledCFG {
855 name: format!("node_{}", code.id()),
860 _ if variants.is_empty() => {
861 let r = dot::render(&lcfg, &mut out);
862 return expand_err_details(r);
864 blocks::Code::Expr(_) => {
865 tcx.sess.err("--pretty flowgraph with -Z flowgraph-print annotations requires \
869 blocks::Code::FnLike(fn_like) => {
870 let (bccx, analysis_data) =
871 borrowck::build_borrowck_dataflow_data_for_fn(tcx, fn_like.body(), &cfg);
873 let lcfg = borrowck_dot::DataflowLabeller {
876 borrowck_ctxt: &bccx,
877 analysis_data: &analysis_data,
879 let r = dot::render(&lcfg, &mut out);
880 return expand_err_details(r);
884 fn expand_err_details(r: io::Result<()>) -> io::Result<()> {
886 io::Error::new(io::ErrorKind::Other,
887 format!("graphviz::render failed: {}", ioerr))
892 pub fn fold_crate(sess: &Session, krate: ast::Crate, ppm: PpMode) -> ast::Crate {
893 if let PpmSource(PpmEveryBodyLoops) = ppm {
894 let mut fold = ReplaceBodyWithLoop::new(sess);
895 fold.fold_crate(krate)
901 fn get_source(input: &Input, sess: &Session) -> (Vec<u8>, FileName) {
902 let src_name = driver::source_name(input);
903 let src = sess.source_map()
904 .get_source_file(&src_name)
914 fn write_output(out: Vec<u8>, ofile: Option<&Path>) {
916 None => print!("{}", String::from_utf8(out).unwrap()),
918 match File::create(p) {
919 Ok(mut w) => w.write_all(&out).unwrap(),
920 Err(e) => panic!("print-print failed to open {} due to {}", p.display(), e),
926 pub fn print_after_parsing(sess: &Session,
930 ofile: Option<&Path>) {
931 let (src, src_name) = get_source(input, sess);
934 let mut out = Vec::new();
936 if let PpmSource(s) = ppm {
937 // Silently ignores an identified node.
938 let out: &mut dyn Write = &mut out;
939 s.call_with_pp_support(sess, None, move |annotation| {
940 debug!("pretty printing source code {:?}", s);
941 let sess = annotation.sess();
942 pprust::print_crate(sess.source_map(),
955 write_output(out, ofile);
958 pub fn print_after_hir_lowering<'tcx, 'a: 'tcx>(sess: &'a Session,
959 cstore: &'tcx CStore,
960 hir_map: &hir_map::Map<'tcx>,
961 resolutions: &Resolutions,
966 output_filenames: &OutputFilenames,
967 opt_uii: Option<UserIdentifiedItem>,
968 ofile: Option<&Path>) {
969 if ppm.needs_analysis() {
970 print_with_analysis(sess,
982 let (src, src_name) = get_source(input, sess);
984 let mut rdr = &src[..];
985 let mut out = Vec::new();
987 match (ppm, opt_uii) {
988 (PpmSource(s), _) => {
989 // Silently ignores an identified node.
990 let out: &mut dyn Write = &mut out;
991 s.call_with_pp_support(sess, Some(hir_map), move |annotation| {
992 debug!("pretty printing source code {:?}", s);
993 let sess = annotation.sess();
994 pprust::print_crate(sess.source_map(),
1000 annotation.pp_ann(),
1005 (PpmHir(s), None) => {
1006 let out: &mut dyn Write = &mut out;
1007 s.call_with_pp_support_hir(sess,
1013 move |annotation, krate| {
1014 debug!("pretty printing source code {:?}", s);
1015 let sess = annotation.sess();
1016 pprust_hir::print_crate(sess.source_map(),
1022 annotation.pp_ann(),
1027 (PpmHirTree(s), None) => {
1028 let out: &mut dyn Write = &mut out;
1029 s.call_with_pp_support_hir(sess,
1035 move |_annotation, krate| {
1036 debug!("pretty printing source code {:?}", s);
1037 write!(out, "{:#?}", krate)
1041 (PpmHir(s), Some(uii)) => {
1042 let out: &mut dyn Write = &mut out;
1043 s.call_with_pp_support_hir(sess,
1049 move |annotation, _| {
1050 debug!("pretty printing source code {:?}", s);
1051 let sess = annotation.sess();
1052 let hir_map = annotation.hir_map().expect("-Z unpretty missing HIR map");
1053 let mut pp_state = pprust_hir::State::new_from_input(sess.source_map(),
1058 annotation.pp_ann(),
1060 for node_id in uii.all_matching_node_ids(hir_map) {
1061 let node = hir_map.get(node_id);
1062 pp_state.print_node(node)?;
1063 pp_state.s.space()?;
1064 let path = annotation.node_path(node_id)
1065 .expect("-Z unpretty missing node paths");
1066 pp_state.synth_comment(path)?;
1067 pp_state.s.hardbreak()?;
1073 (PpmHirTree(s), Some(uii)) => {
1074 let out: &mut dyn Write = &mut out;
1075 s.call_with_pp_support_hir(sess,
1081 move |_annotation, _krate| {
1082 debug!("pretty printing source code {:?}", s);
1083 for node_id in uii.all_matching_node_ids(hir_map) {
1084 let node = hir_map.get(node_id);
1085 write!(out, "{:#?}", node)?;
1091 _ => unreachable!(),
1095 write_output(out, ofile);
1098 // In an ideal world, this would be a public function called by the driver after
1099 // analysis is performed. However, we want to call `phase_3_run_analysis_passes`
1100 // with a different callback than the standard driver, so that isn't easy.
1101 // Instead, we call that function ourselves.
1102 fn print_with_analysis<'tcx, 'a: 'tcx>(sess: &'a Session,
1104 hir_map: &hir_map::Map<'tcx>,
1105 resolutions: &Resolutions,
1107 output_filenames: &OutputFilenames,
1109 uii: Option<UserIdentifiedItem>,
1110 ofile: Option<&Path>) {
1111 let nodeid = if let Some(uii) = uii {
1112 debug!("pretty printing for {:?}", uii);
1113 Some(uii.to_one_node_id("-Z unpretty", sess, &hir_map))
1115 debug!("pretty printing for whole crate");
1119 let mut out = Vec::new();
1121 let control = &driver::CompileController::basic();
1122 let codegen_backend = ::get_codegen_backend(sess);
1123 let mut arenas = AllArenas::new();
1124 abort_on_err(driver::phase_3_run_analysis_passes(&*codegen_backend,
1129 resolutions.clone(),
1135 PpmMir | PpmMirCFG => {
1136 if let Some(nodeid) = nodeid {
1137 let def_id = tcx.hir().local_def_id(nodeid);
1139 PpmMir => write_mir_pretty(tcx, Some(def_id), &mut out),
1140 PpmMirCFG => write_mir_graphviz(tcx, Some(def_id), &mut out),
1141 _ => unreachable!(),
1145 PpmMir => write_mir_pretty(tcx, None, &mut out),
1146 PpmMirCFG => write_mir_graphviz(tcx, None, &mut out),
1147 _ => unreachable!(),
1152 PpmFlowGraph(mode) => {
1154 nodeid.expect("`pretty flowgraph=..` needs NodeId (int) or unique path \
1156 let node = tcx.hir().find(nodeid).unwrap_or_else(|| {
1157 tcx.sess.fatal(&format!("--pretty flowgraph couldn't find id: {}", nodeid))
1160 match blocks::Code::from_node(&tcx.hir(), nodeid) {
1162 let variants = gather_flowgraph_variants(tcx.sess);
1164 let out: &mut dyn Write = &mut out;
1166 print_flowgraph(variants, tcx, code, mode, out)
1169 let message = format!("--pretty=flowgraph needs block, fn, or method; \
1173 tcx.sess.span_fatal(tcx.hir().span(nodeid), &message)
1177 _ => unreachable!(),
1183 write_output(out, ofile);