1 //! The various pretty-printing routines.
4 use rustc::hir::map as hir_map;
5 use rustc::hir::print as pprust_hir;
6 use rustc::hir::def_id::LOCAL_CRATE;
7 use rustc::session::Session;
8 use rustc::session::config::Input;
9 use rustc::ty::{self, TyCtxt};
10 use rustc::util::common::ErrorReported;
11 use rustc_interface::util::ReplaceBodyWithLoop;
12 use rustc_mir::util::{write_mir_pretty, write_mir_graphviz};
15 use syntax::mut_visit::MutVisitor;
16 use syntax::print::{pprust};
17 use syntax_pos::FileName;
24 use std::str::FromStr;
26 pub use self::UserIdentifiedItem::*;
27 pub use self::PpSourceMode::*;
28 pub use self::PpMode::*;
29 use self::NodesMatchingUII::*;
30 use crate::abort_on_err;
32 use crate::source_name;
34 #[derive(Copy, Clone, PartialEq, Debug)]
35 pub enum PpSourceMode {
40 PpmExpandedIdentified,
45 #[derive(Copy, Clone, PartialEq, Debug)]
47 PpmSource(PpSourceMode),
49 PpmHirTree(PpSourceMode),
55 pub fn needs_ast_map(&self, opt_uii: &Option<UserIdentifiedItem>) -> bool {
57 PpmSource(PpmNormal) |
58 PpmSource(PpmEveryBodyLoops) |
59 PpmSource(PpmIdentified) => opt_uii.is_some(),
61 PpmSource(PpmExpanded) |
62 PpmSource(PpmExpandedIdentified) |
63 PpmSource(PpmExpandedHygiene) |
68 PpmSource(PpmTyped) => panic!("invalid state"),
72 pub fn needs_analysis(&self) -> bool {
74 PpmMir | PpmMirCFG => true,
80 pub fn parse_pretty(sess: &Session,
83 -> (PpMode, Option<UserIdentifiedItem>) {
84 let mut split = name.splitn(2, '=');
85 let first = split.next().unwrap();
86 let opt_second = split.next();
87 let first = match (first, extended) {
88 ("normal", _) => PpmSource(PpmNormal),
89 ("identified", _) => PpmSource(PpmIdentified),
90 ("everybody_loops", true) => PpmSource(PpmEveryBodyLoops),
91 ("expanded", _) => PpmSource(PpmExpanded),
92 ("expanded,identified", _) => PpmSource(PpmExpandedIdentified),
93 ("expanded,hygiene", _) => PpmSource(PpmExpandedHygiene),
94 ("hir", true) => PpmHir(PpmNormal),
95 ("hir,identified", true) => PpmHir(PpmIdentified),
96 ("hir,typed", true) => PpmHir(PpmTyped),
97 ("hir-tree", true) => PpmHirTree(PpmNormal),
98 ("mir", true) => PpmMir,
99 ("mir-cfg", true) => PpmMirCFG,
102 sess.fatal(&format!("argument to `unpretty` must be one of `normal`, \
103 `expanded`, `identified`, `expanded,identified`, \
104 `expanded,hygiene`, `everybody_loops`, \
105 `hir`, `hir,identified`, `hir,typed`, `hir-tree`, \
106 `mir` or `mir-cfg`; got {}",
109 sess.fatal(&format!("argument to `pretty` must be one of `normal`, `expanded`, \
110 `identified`, or `expanded,identified`; got {}",
115 let opt_second = opt_second.and_then(|s| s.parse::<UserIdentifiedItem>().ok());
121 // This slightly awkward construction is to allow for each PpMode to
122 // choose whether it needs to do analyses (which can consume the
123 // Session) and then pass through the session (now attached to the
124 // analysis results) on to the chosen pretty-printer, along with the
127 // Note that since the `&PrinterSupport` is freshly constructed on each
128 // call, it would not make sense to try to attach the lifetime of `self`
129 // to the lifetime of the `&PrinterObject`.
131 // (The `use_once_payload` is working around the current lack of once
132 // functions in the compiler.)
135 /// Constructs a `PrinterSupport` object and passes it to `f`.
136 fn call_with_pp_support<'tcx, A, F>(
139 tcx: Option<TyCtxt<'tcx>>,
143 F: FnOnce(&dyn PrinterSupport) -> A,
146 PpmNormal | PpmEveryBodyLoops | PpmExpanded => {
147 let annotation = NoAnn {
154 PpmIdentified | PpmExpandedIdentified => {
155 let annotation = IdentifiedAnnotation {
161 PpmExpandedHygiene => {
162 let annotation = HygieneAnnotation {
167 _ => panic!("Should use call_with_pp_support_hir"),
170 fn call_with_pp_support_hir<A, F>(&self, tcx: TyCtxt<'_>, f: F) -> A
172 F: FnOnce(&dyn HirPrinterSupport<'_>, &hir::Crate) -> A,
176 let annotation = NoAnn {
180 f(&annotation, tcx.hir().forest.krate())
184 let annotation = IdentifiedAnnotation {
188 f(&annotation, tcx.hir().forest.krate())
191 abort_on_err(tcx.analysis(LOCAL_CRATE), tcx.sess);
193 let empty_tables = ty::TypeckTables::empty(None);
194 let annotation = TypedAnnotation {
196 tables: Cell::new(&empty_tables)
198 tcx.dep_graph.with_ignore(|| {
199 f(&annotation, tcx.hir().forest.krate())
202 _ => panic!("Should use call_with_pp_support"),
207 trait PrinterSupport: pprust::PpAnn {
208 /// Provides a uniform interface for re-extracting a reference to a
209 /// `Session` from a value that now owns it.
210 fn sess(&self) -> &Session;
212 /// Produces the pretty-print annotation object.
214 /// (Rust does not yet support upcasting from a trait object to
215 /// an object for one of its super-traits.)
216 fn pp_ann<'a>(&'a self) -> &'a dyn pprust::PpAnn;
219 trait HirPrinterSupport<'hir>: pprust_hir::PpAnn {
220 /// Provides a uniform interface for re-extracting a reference to a
221 /// `Session` from a value that now owns it.
222 fn sess(&self) -> &Session;
224 /// Provides a uniform interface for re-extracting a reference to an
225 /// `hir_map::Map` from a value that now owns it.
226 fn hir_map<'a>(&'a self) -> Option<&'a hir_map::Map<'hir>>;
228 /// Produces the pretty-print annotation object.
230 /// (Rust does not yet support upcasting from a trait object to
231 /// an object for one of its super-traits.)
232 fn pp_ann<'a>(&'a self) -> &'a dyn pprust_hir::PpAnn;
234 /// Computes an user-readable representation of a path, if possible.
235 fn node_path(&self, id: hir::HirId) -> Option<String> {
236 self.hir_map().and_then(|map| {
237 map.def_path_from_hir_id(id)
241 .map(|elem| elem.data.to_string())
250 tcx: Option<TyCtxt<'hir>>,
253 impl<'hir> PrinterSupport for NoAnn<'hir> {
254 fn sess(&self) -> &Session {
258 fn pp_ann<'a>(&'a self) -> &'a dyn pprust::PpAnn {
263 impl<'hir> HirPrinterSupport<'hir> for NoAnn<'hir> {
264 fn sess(&self) -> &Session {
268 fn hir_map<'a>(&'a self) -> Option<&'a hir_map::Map<'hir>> {
269 self.tcx.map(|tcx| tcx.hir())
272 fn pp_ann<'a>(&'a self) -> &'a dyn pprust_hir::PpAnn {
277 impl<'hir> pprust::PpAnn for NoAnn<'hir> {}
278 impl<'hir> pprust_hir::PpAnn for NoAnn<'hir> {
279 fn nested(&self, state: &mut pprust_hir::State<'_>, nested: pprust_hir::Nested) {
280 if let Some(tcx) = self.tcx {
281 pprust_hir::PpAnn::nested(tcx.hir(), state, nested)
286 struct IdentifiedAnnotation<'hir> {
288 tcx: Option<TyCtxt<'hir>>,
291 impl<'hir> PrinterSupport for IdentifiedAnnotation<'hir> {
292 fn sess(&self) -> &Session {
296 fn pp_ann<'a>(&'a self) -> &'a dyn pprust::PpAnn {
301 impl<'hir> pprust::PpAnn for IdentifiedAnnotation<'hir> {
302 fn pre(&self, s: &mut pprust::State<'_>, node: pprust::AnnNode<'_>) {
304 pprust::AnnNode::Expr(_) => s.popen(),
308 fn post(&self, s: &mut pprust::State<'_>, node: pprust::AnnNode<'_>) {
310 pprust::AnnNode::Crate(_) |
311 pprust::AnnNode::Ident(_) |
312 pprust::AnnNode::Name(_) => {},
314 pprust::AnnNode::Item(item) => {
316 s.synth_comment(item.id.to_string())
318 pprust::AnnNode::SubItem(id) => {
320 s.synth_comment(id.to_string())
322 pprust::AnnNode::Block(blk) => {
324 s.synth_comment(format!("block {}", blk.id))
326 pprust::AnnNode::Expr(expr) => {
328 s.synth_comment(expr.id.to_string());
331 pprust::AnnNode::Pat(pat) => {
333 s.synth_comment(format!("pat {}", pat.id));
339 impl<'hir> HirPrinterSupport<'hir> for IdentifiedAnnotation<'hir> {
340 fn sess(&self) -> &Session {
344 fn hir_map<'a>(&'a self) -> Option<&'a hir_map::Map<'hir>> {
345 self.tcx.map(|tcx| tcx.hir())
348 fn pp_ann<'a>(&'a self) -> &'a dyn pprust_hir::PpAnn {
353 impl<'hir> pprust_hir::PpAnn for IdentifiedAnnotation<'hir> {
354 fn nested(&self, state: &mut pprust_hir::State<'_>, nested: pprust_hir::Nested) {
355 if let Some(ref tcx) = self.tcx {
356 pprust_hir::PpAnn::nested(tcx.hir(), state, nested)
359 fn pre(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) {
361 pprust_hir::AnnNode::Expr(_) => s.popen(),
365 fn post(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) {
367 pprust_hir::AnnNode::Name(_) => {},
368 pprust_hir::AnnNode::Item(item) => {
370 s.synth_comment(format!("hir_id: {}", item.hir_id));
372 pprust_hir::AnnNode::SubItem(id) => {
374 s.synth_comment(id.to_string());
376 pprust_hir::AnnNode::Block(blk) => {
378 s.synth_comment(format!("block hir_id: {}", blk.hir_id));
380 pprust_hir::AnnNode::Expr(expr) => {
382 s.synth_comment(format!("expr hir_id: {}", expr.hir_id));
385 pprust_hir::AnnNode::Pat(pat) => {
387 s.synth_comment(format!("pat hir_id: {}", pat.hir_id));
389 pprust_hir::AnnNode::Arm(arm) => {
391 s.synth_comment(format!("arm hir_id: {}", arm.hir_id));
397 struct HygieneAnnotation<'a> {
401 impl<'a> PrinterSupport for HygieneAnnotation<'a> {
402 fn sess(&self) -> &Session {
406 fn pp_ann(&self) -> &dyn pprust::PpAnn {
411 impl<'a> pprust::PpAnn for HygieneAnnotation<'a> {
412 fn post(&self, s: &mut pprust::State<'_>, node: pprust::AnnNode<'_>) {
414 pprust::AnnNode::Ident(&ast::Ident { name, span }) => {
416 s.synth_comment(format!("{}{:?}", name.as_u32(), span.ctxt()))
418 pprust::AnnNode::Name(&name) => {
420 s.synth_comment(name.as_u32().to_string())
422 pprust::AnnNode::Crate(_) => {
424 let verbose = self.sess.verbose();
425 s.synth_comment(syntax_pos::hygiene::debug_hygiene_data(verbose));
426 s.s.hardbreak_if_not_bol();
433 struct TypedAnnotation<'a, 'tcx> {
435 tables: Cell<&'a ty::TypeckTables<'tcx>>,
438 impl<'b, 'tcx> HirPrinterSupport<'tcx> for TypedAnnotation<'b, 'tcx> {
439 fn sess(&self) -> &Session {
443 fn hir_map<'a>(&'a self) -> Option<&'a hir_map::Map<'tcx>> {
444 Some(&self.tcx.hir())
447 fn pp_ann<'a>(&'a self) -> &'a dyn pprust_hir::PpAnn {
451 fn node_path(&self, id: hir::HirId) -> Option<String> {
452 Some(self.tcx.def_path_str(self.tcx.hir().local_def_id(id)))
456 impl<'a, 'tcx> pprust_hir::PpAnn for TypedAnnotation<'a, 'tcx> {
457 fn nested(&self, state: &mut pprust_hir::State<'_>, nested: pprust_hir::Nested) {
458 let old_tables = self.tables.get();
459 if let pprust_hir::Nested::Body(id) = nested {
460 self.tables.set(self.tcx.body_tables(id));
462 pprust_hir::PpAnn::nested(self.tcx.hir(), state, nested);
463 self.tables.set(old_tables);
465 fn pre(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) {
467 pprust_hir::AnnNode::Expr(_) => s.popen(),
471 fn post(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) {
473 pprust_hir::AnnNode::Expr(expr) => {
477 s.s.word(self.tables.get().expr_ty(expr).to_string());
485 #[derive(Clone, Debug)]
486 pub enum UserIdentifiedItem {
487 ItemViaNode(ast::NodeId),
488 ItemViaPath(Vec<String>),
491 impl FromStr for UserIdentifiedItem {
493 fn from_str(s: &str) -> Result<UserIdentifiedItem, ()> {
495 .map(ast::NodeId::from_u32)
497 .unwrap_or_else(|_| ItemViaPath(s.split("::").map(|s| s.to_string()).collect())))
501 enum NodesMatchingUII<'a> {
502 NodesMatchingDirect(option::IntoIter<ast::NodeId>),
503 NodesMatchingSuffix(Box<dyn Iterator<Item = ast::NodeId> + 'a>),
506 impl<'a> Iterator for NodesMatchingUII<'a> {
507 type Item = ast::NodeId;
509 fn next(&mut self) -> Option<ast::NodeId> {
511 &mut NodesMatchingDirect(ref mut iter) => iter.next(),
512 &mut NodesMatchingSuffix(ref mut iter) => iter.next(),
516 fn size_hint(&self) -> (usize, Option<usize>) {
518 &NodesMatchingDirect(ref iter) => iter.size_hint(),
519 &NodesMatchingSuffix(ref iter) => iter.size_hint(),
524 impl UserIdentifiedItem {
525 fn reconstructed_input(&self) -> String {
527 ItemViaNode(node_id) => node_id.to_string(),
528 ItemViaPath(ref parts) => parts.join("::"),
532 fn all_matching_node_ids<'a, 'hir>(&'a self,
533 map: &'a hir_map::Map<'hir>)
534 -> NodesMatchingUII<'a> {
536 ItemViaNode(node_id) => NodesMatchingDirect(Some(node_id).into_iter()),
537 ItemViaPath(ref parts) => {
538 NodesMatchingSuffix(Box::new(map.nodes_matching_suffix(&parts)))
543 fn to_one_node_id(self,
546 map: &hir_map::Map<'_>)
548 let fail_because = |is_wrong_because| -> ast::NodeId {
549 let message = format!("{} needs NodeId (int) or unique path suffix (b::c::d); got \
552 self.reconstructed_input(),
557 let mut saw_node = ast::DUMMY_NODE_ID;
559 for node in self.all_matching_node_ids(map) {
563 fail_because("does not resolve uniquely");
567 fail_because("does not resolve to any item");
575 pub fn visit_crate(sess: &Session, krate: &mut ast::Crate, ppm: PpMode) {
576 if let PpmSource(PpmEveryBodyLoops) = ppm {
577 ReplaceBodyWithLoop::new(sess).visit_crate(krate);
581 fn get_source(input: &Input, sess: &Session) -> (String, FileName) {
582 let src_name = source_name(input);
583 let src = String::clone(&sess.source_map()
584 .get_source_file(&src_name)
592 fn write_output(out: Vec<u8>, ofile: Option<&Path>) {
594 None => print!("{}", String::from_utf8(out).unwrap()),
596 match File::create(p) {
597 Ok(mut w) => w.write_all(&out).unwrap(),
598 Err(e) => panic!("print-print failed to open {} due to {}", p.display(), e),
604 pub fn print_after_parsing(sess: &Session,
608 ofile: Option<&Path>) {
609 let (src, src_name) = get_source(input, sess);
611 let mut out = String::new();
613 if let PpmSource(s) = ppm {
614 // Silently ignores an identified node.
616 s.call_with_pp_support(sess, None, move |annotation| {
617 debug!("pretty printing source code {:?}", s);
618 let sess = annotation.sess();
619 *out = pprust::print_crate(sess.source_map(),
631 write_output(out.into_bytes(), ofile);
634 pub fn print_after_hir_lowering<'tcx>(
639 opt_uii: Option<UserIdentifiedItem>,
640 ofile: Option<&Path>,
642 if ppm.needs_analysis() {
643 abort_on_err(print_with_analysis(
652 let (src, src_name) = get_source(input, tcx.sess);
654 let mut out = String::new();
656 match (ppm, opt_uii) {
657 (PpmSource(s), _) => {
658 // Silently ignores an identified node.
660 let src = src.clone();
661 s.call_with_pp_support(tcx.sess, Some(tcx), move |annotation| {
662 debug!("pretty printing source code {:?}", s);
663 let sess = annotation.sess();
664 *out = pprust::print_crate(sess.source_map(),
674 (PpmHir(s), None) => {
676 let src = src.clone();
677 s.call_with_pp_support_hir(tcx, move |annotation, krate| {
678 debug!("pretty printing source code {:?}", s);
679 let sess = annotation.sess();
680 *out = pprust_hir::print_crate(sess.source_map(),
689 (PpmHirTree(s), None) => {
691 s.call_with_pp_support_hir(tcx, move |_annotation, krate| {
692 debug!("pretty printing source code {:?}", s);
693 *out = format!("{:#?}", krate);
697 (PpmHir(s), Some(uii)) => {
699 let src = src.clone();
700 s.call_with_pp_support_hir(tcx, move |annotation, _| {
701 debug!("pretty printing source code {:?}", s);
702 let sess = annotation.sess();
703 let hir_map = annotation.hir_map().expect("-Z unpretty missing HIR map");
704 let mut pp_state = pprust_hir::State::new_from_input(sess.source_map(),
708 annotation.pp_ann());
709 for node_id in uii.all_matching_node_ids(hir_map) {
710 let hir_id = tcx.hir().node_to_hir_id(node_id);
711 let node = hir_map.get(hir_id);
712 pp_state.print_node(node);
714 let path = annotation.node_path(hir_id)
715 .expect("-Z unpretty missing node paths");
716 pp_state.synth_comment(path);
717 pp_state.s.hardbreak();
719 *out = pp_state.s.eof();
723 (PpmHirTree(s), Some(uii)) => {
725 s.call_with_pp_support_hir(tcx, move |_annotation, _krate| {
726 debug!("pretty printing source code {:?}", s);
727 for node_id in uii.all_matching_node_ids(tcx.hir()) {
728 let hir_id = tcx.hir().node_to_hir_id(node_id);
729 let node = tcx.hir().get(hir_id);
730 out.push_str(&format!("{:#?}", node));
738 write_output(out.into_bytes(), ofile);
741 // In an ideal world, this would be a public function called by the driver after
742 // analysis is performed. However, we want to call `phase_3_run_analysis_passes`
743 // with a different callback than the standard driver, so that isn't easy.
744 // Instead, we call that function ourselves.
745 fn print_with_analysis(
748 uii: Option<UserIdentifiedItem>,
749 ofile: Option<&Path>,
750 ) -> Result<(), ErrorReported> {
751 let nodeid = if let Some(uii) = uii {
752 debug!("pretty printing for {:?}", uii);
753 Some(uii.to_one_node_id("-Z unpretty", tcx.sess, tcx.hir()))
755 debug!("pretty printing for whole crate");
759 let mut out = Vec::new();
761 tcx.analysis(LOCAL_CRATE)?;
764 PpmMir | PpmMirCFG => {
765 let def_id = nodeid.map(|nid| tcx.hir().local_def_id_from_node_id(nid));
767 PpmMir => write_mir_pretty(tcx, def_id, &mut out),
768 PpmMirCFG => write_mir_graphviz(tcx, def_id, &mut out),
775 write_output(out, ofile);