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::{PpMode, PpSourceMode, UserIdentifiedItem, Input};
9 use rustc::ty::{self, TyCtxt};
10 use rustc::util::common::ErrorReported;
11 use rustc_mir::util::{write_mir_pretty, write_mir_graphviz};
14 use syntax::print::{pprust};
15 use syntax_pos::FileName;
22 pub use self::UserIdentifiedItem::*;
23 pub use self::PpSourceMode::*;
24 pub use self::PpMode::*;
25 use crate::abort_on_err;
27 // This slightly awkward construction is to allow for each PpMode to
28 // choose whether it needs to do analyses (which can consume the
29 // Session) and then pass through the session (now attached to the
30 // analysis results) on to the chosen pretty-printer, along with the
33 // Note that since the `&PrinterSupport` is freshly constructed on each
34 // call, it would not make sense to try to attach the lifetime of `self`
35 // to the lifetime of the `&PrinterObject`.
37 // (The `use_once_payload` is working around the current lack of once
38 // functions in the compiler.)
40 /// Constructs a `PrinterSupport` object and passes it to `f`.
41 fn call_with_pp_support<'tcx, A, F>(
42 ppmode: &PpSourceMode,
44 tcx: Option<TyCtxt<'tcx>>,
48 F: FnOnce(&dyn PrinterSupport) -> A,
51 PpmNormal | PpmEveryBodyLoops | PpmExpanded => {
52 let annotation = NoAnn {
59 PpmIdentified | PpmExpandedIdentified => {
60 let annotation = IdentifiedAnnotation {
66 PpmExpandedHygiene => {
67 let annotation = HygieneAnnotation {
72 _ => panic!("Should use call_with_pp_support_hir"),
75 fn call_with_pp_support_hir<A, F>(ppmode: &PpSourceMode, tcx: TyCtxt<'_>, f: F) -> A
77 F: FnOnce(&dyn HirPrinterSupport<'_>, &hir::Crate) -> A,
81 let annotation = NoAnn {
85 f(&annotation, tcx.hir().forest.krate())
89 let annotation = IdentifiedAnnotation {
93 f(&annotation, tcx.hir().forest.krate())
96 abort_on_err(tcx.analysis(LOCAL_CRATE), tcx.sess);
98 let empty_tables = ty::TypeckTables::empty(None);
99 let annotation = TypedAnnotation {
101 tables: Cell::new(&empty_tables)
103 tcx.dep_graph.with_ignore(|| {
104 f(&annotation, tcx.hir().forest.krate())
107 _ => panic!("Should use call_with_pp_support"),
111 trait PrinterSupport: pprust::PpAnn {
112 /// Provides a uniform interface for re-extracting a reference to a
113 /// `Session` from a value that now owns it.
114 fn sess(&self) -> &Session;
116 /// Produces the pretty-print annotation object.
118 /// (Rust does not yet support upcasting from a trait object to
119 /// an object for one of its super-traits.)
120 fn pp_ann<'a>(&'a self) -> &'a dyn pprust::PpAnn;
123 trait HirPrinterSupport<'hir>: pprust_hir::PpAnn {
124 /// Provides a uniform interface for re-extracting a reference to a
125 /// `Session` from a value that now owns it.
126 fn sess(&self) -> &Session;
128 /// Provides a uniform interface for re-extracting a reference to an
129 /// `hir_map::Map` from a value that now owns it.
130 fn hir_map<'a>(&'a self) -> Option<&'a hir_map::Map<'hir>>;
132 /// Produces the pretty-print annotation object.
134 /// (Rust does not yet support upcasting from a trait object to
135 /// an object for one of its super-traits.)
136 fn pp_ann<'a>(&'a self) -> &'a dyn pprust_hir::PpAnn;
138 /// Computes an user-readable representation of a path, if possible.
139 fn node_path(&self, id: hir::HirId) -> Option<String> {
140 self.hir_map().and_then(|map| {
141 map.def_path_from_hir_id(id)
145 .map(|elem| elem.data.to_string())
154 tcx: Option<TyCtxt<'hir>>,
157 impl<'hir> PrinterSupport for NoAnn<'hir> {
158 fn sess(&self) -> &Session {
162 fn pp_ann<'a>(&'a self) -> &'a dyn pprust::PpAnn {
167 impl<'hir> HirPrinterSupport<'hir> for NoAnn<'hir> {
168 fn sess(&self) -> &Session {
172 fn hir_map<'a>(&'a self) -> Option<&'a hir_map::Map<'hir>> {
173 self.tcx.map(|tcx| tcx.hir())
176 fn pp_ann<'a>(&'a self) -> &'a dyn pprust_hir::PpAnn {
181 impl<'hir> pprust::PpAnn for NoAnn<'hir> {}
182 impl<'hir> pprust_hir::PpAnn for NoAnn<'hir> {
183 fn nested(&self, state: &mut pprust_hir::State<'_>, nested: pprust_hir::Nested) {
184 if let Some(tcx) = self.tcx {
185 pprust_hir::PpAnn::nested(tcx.hir(), state, nested)
190 struct IdentifiedAnnotation<'hir> {
192 tcx: Option<TyCtxt<'hir>>,
195 impl<'hir> PrinterSupport for IdentifiedAnnotation<'hir> {
196 fn sess(&self) -> &Session {
200 fn pp_ann<'a>(&'a self) -> &'a dyn pprust::PpAnn {
205 impl<'hir> pprust::PpAnn for IdentifiedAnnotation<'hir> {
206 fn pre(&self, s: &mut pprust::State<'_>, node: pprust::AnnNode<'_>) {
208 pprust::AnnNode::Expr(_) => s.popen(),
212 fn post(&self, s: &mut pprust::State<'_>, node: pprust::AnnNode<'_>) {
214 pprust::AnnNode::Crate(_) |
215 pprust::AnnNode::Ident(_) |
216 pprust::AnnNode::Name(_) => {},
218 pprust::AnnNode::Item(item) => {
220 s.synth_comment(item.id.to_string())
222 pprust::AnnNode::SubItem(id) => {
224 s.synth_comment(id.to_string())
226 pprust::AnnNode::Block(blk) => {
228 s.synth_comment(format!("block {}", blk.id))
230 pprust::AnnNode::Expr(expr) => {
232 s.synth_comment(expr.id.to_string());
235 pprust::AnnNode::Pat(pat) => {
237 s.synth_comment(format!("pat {}", pat.id));
243 impl<'hir> HirPrinterSupport<'hir> for IdentifiedAnnotation<'hir> {
244 fn sess(&self) -> &Session {
248 fn hir_map<'a>(&'a self) -> Option<&'a hir_map::Map<'hir>> {
249 self.tcx.map(|tcx| tcx.hir())
252 fn pp_ann<'a>(&'a self) -> &'a dyn pprust_hir::PpAnn {
257 impl<'hir> pprust_hir::PpAnn for IdentifiedAnnotation<'hir> {
258 fn nested(&self, state: &mut pprust_hir::State<'_>, nested: pprust_hir::Nested) {
259 if let Some(ref tcx) = self.tcx {
260 pprust_hir::PpAnn::nested(tcx.hir(), state, nested)
263 fn pre(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) {
265 pprust_hir::AnnNode::Expr(_) => s.popen(),
269 fn post(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) {
271 pprust_hir::AnnNode::Name(_) => {},
272 pprust_hir::AnnNode::Item(item) => {
274 s.synth_comment(format!("hir_id: {}", item.hir_id));
276 pprust_hir::AnnNode::SubItem(id) => {
278 s.synth_comment(id.to_string());
280 pprust_hir::AnnNode::Block(blk) => {
282 s.synth_comment(format!("block hir_id: {}", blk.hir_id));
284 pprust_hir::AnnNode::Expr(expr) => {
286 s.synth_comment(format!("expr hir_id: {}", expr.hir_id));
289 pprust_hir::AnnNode::Pat(pat) => {
291 s.synth_comment(format!("pat hir_id: {}", pat.hir_id));
293 pprust_hir::AnnNode::Arm(arm) => {
295 s.synth_comment(format!("arm hir_id: {}", arm.hir_id));
301 struct HygieneAnnotation<'a> {
305 impl<'a> PrinterSupport for HygieneAnnotation<'a> {
306 fn sess(&self) -> &Session {
310 fn pp_ann(&self) -> &dyn pprust::PpAnn {
315 impl<'a> pprust::PpAnn for HygieneAnnotation<'a> {
316 fn post(&self, s: &mut pprust::State<'_>, node: pprust::AnnNode<'_>) {
318 pprust::AnnNode::Ident(&ast::Ident { name, span }) => {
320 s.synth_comment(format!("{}{:?}", name.as_u32(), span.ctxt()))
322 pprust::AnnNode::Name(&name) => {
324 s.synth_comment(name.as_u32().to_string())
326 pprust::AnnNode::Crate(_) => {
328 let verbose = self.sess.verbose();
329 s.synth_comment(syntax_pos::hygiene::debug_hygiene_data(verbose));
330 s.s.hardbreak_if_not_bol();
337 struct TypedAnnotation<'a, 'tcx> {
339 tables: Cell<&'a ty::TypeckTables<'tcx>>,
342 impl<'b, 'tcx> HirPrinterSupport<'tcx> for TypedAnnotation<'b, 'tcx> {
343 fn sess(&self) -> &Session {
347 fn hir_map<'a>(&'a self) -> Option<&'a hir_map::Map<'tcx>> {
348 Some(&self.tcx.hir())
351 fn pp_ann<'a>(&'a self) -> &'a dyn pprust_hir::PpAnn {
355 fn node_path(&self, id: hir::HirId) -> Option<String> {
356 Some(self.tcx.def_path_str(self.tcx.hir().local_def_id(id)))
360 impl<'a, 'tcx> pprust_hir::PpAnn for TypedAnnotation<'a, 'tcx> {
361 fn nested(&self, state: &mut pprust_hir::State<'_>, nested: pprust_hir::Nested) {
362 let old_tables = self.tables.get();
363 if let pprust_hir::Nested::Body(id) = nested {
364 self.tables.set(self.tcx.body_tables(id));
366 pprust_hir::PpAnn::nested(self.tcx.hir(), state, nested);
367 self.tables.set(old_tables);
369 fn pre(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) {
371 pprust_hir::AnnNode::Expr(_) => s.popen(),
375 fn post(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) {
377 pprust_hir::AnnNode::Expr(expr) => {
381 s.s.word(self.tables.get().expr_ty(expr).to_string());
389 fn get_source(input: &Input, sess: &Session) -> (String, FileName) {
390 let src_name = input.source_name();
391 let src = String::clone(&sess.source_map()
392 .get_source_file(&src_name)
400 fn write_output(out: Vec<u8>, ofile: Option<&Path>) {
402 None => print!("{}", String::from_utf8(out).unwrap()),
404 match File::create(p) {
405 Ok(mut w) => w.write_all(&out).unwrap(),
406 Err(e) => panic!("print-print failed to open {} due to {}", p.display(), e),
412 pub fn print_after_parsing(sess: &Session,
416 ofile: Option<&Path>) {
417 let (src, src_name) = get_source(input, sess);
419 let mut out = String::new();
421 if let PpmSource(s) = ppm {
422 // Silently ignores an identified node.
424 call_with_pp_support(&s, sess, None, move |annotation| {
425 debug!("pretty printing source code {:?}", s);
426 let sess = annotation.sess();
427 *out = pprust::print_crate(sess.source_map(),
439 write_output(out.into_bytes(), ofile);
442 pub fn print_after_hir_lowering<'tcx>(
447 opt_uii: Option<UserIdentifiedItem>,
448 ofile: Option<&Path>,
450 if ppm.needs_analysis() {
451 abort_on_err(print_with_analysis(
460 let (src, src_name) = get_source(input, tcx.sess);
462 let mut out = String::new();
464 match (ppm, opt_uii) {
465 (PpmSource(s), _) => {
466 // Silently ignores an identified node.
468 let src = src.clone();
469 call_with_pp_support(&s, tcx.sess, Some(tcx), move |annotation| {
470 debug!("pretty printing source code {:?}", s);
471 let sess = annotation.sess();
472 *out = pprust::print_crate(sess.source_map(),
482 (PpmHir(s), None) => {
484 let src = src.clone();
485 call_with_pp_support_hir(&s, tcx, move |annotation, krate| {
486 debug!("pretty printing source code {:?}", s);
487 let sess = annotation.sess();
488 *out = pprust_hir::print_crate(sess.source_map(),
497 (PpmHirTree(s), None) => {
499 call_with_pp_support_hir(&s, tcx, move |_annotation, krate| {
500 debug!("pretty printing source code {:?}", s);
501 *out = format!("{:#?}", krate);
505 (PpmHir(s), Some(uii)) => {
507 let src = src.clone();
508 call_with_pp_support_hir(&s, tcx, move |annotation, _| {
509 debug!("pretty printing source code {:?}", s);
510 let sess = annotation.sess();
511 let hir_map = annotation.hir_map().expect("-Z unpretty missing HIR map");
512 let mut pp_state = pprust_hir::State::new_from_input(sess.source_map(),
516 annotation.pp_ann());
517 for node_id in uii.all_matching_node_ids(hir_map) {
518 let hir_id = tcx.hir().node_to_hir_id(node_id);
519 let node = hir_map.get(hir_id);
520 pp_state.print_node(node);
522 let path = annotation.node_path(hir_id)
523 .expect("-Z unpretty missing node paths");
524 pp_state.synth_comment(path);
525 pp_state.s.hardbreak();
527 *out = pp_state.s.eof();
531 (PpmHirTree(s), Some(uii)) => {
533 call_with_pp_support_hir(&s, tcx, move |_annotation, _krate| {
534 debug!("pretty printing source code {:?}", s);
535 for node_id in uii.all_matching_node_ids(tcx.hir()) {
536 let hir_id = tcx.hir().node_to_hir_id(node_id);
537 let node = tcx.hir().get(hir_id);
538 out.push_str(&format!("{:#?}", node));
546 write_output(out.into_bytes(), ofile);
549 // In an ideal world, this would be a public function called by the driver after
550 // analysis is performed. However, we want to call `phase_3_run_analysis_passes`
551 // with a different callback than the standard driver, so that isn't easy.
552 // Instead, we call that function ourselves.
553 fn print_with_analysis(
556 uii: Option<UserIdentifiedItem>,
557 ofile: Option<&Path>,
558 ) -> Result<(), ErrorReported> {
559 let nodeid = if let Some(uii) = uii {
560 debug!("pretty printing for {:?}", uii);
561 Some(uii.to_one_node_id("-Z unpretty", tcx.sess, tcx.hir()))
563 debug!("pretty printing for whole crate");
567 let mut out = Vec::new();
569 tcx.analysis(LOCAL_CRATE)?;
572 PpmMir | PpmMirCFG => {
573 let def_id = nodeid.map(|nid| tcx.hir().local_def_id_from_node_id(nid));
575 PpmMir => write_mir_pretty(tcx, def_id, &mut out),
576 PpmMirCFG => write_mir_graphviz(tcx, def_id, &mut out),
583 write_output(out, ofile);