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, 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::PpSourceMode::*;
23 pub use self::PpMode::*;
24 use crate::abort_on_err;
26 use crate::source_name;
30 // This slightly awkward construction is to allow for each PpMode to
31 // choose whether it needs to do analyses (which can consume the
32 // Session) and then pass through the session (now attached to the
33 // analysis results) on to the chosen pretty-printer, along with the
36 // Note that since the `&PrinterSupport` is freshly constructed on each
37 // call, it would not make sense to try to attach the lifetime of `self`
38 // to the lifetime of the `&PrinterObject`.
40 // (The `use_once_payload` is working around the current lack of once
41 // functions in the compiler.)
43 /// Constructs a `PrinterSupport` object and passes it to `f`.
44 fn call_with_pp_support<'tcx, A, F>(
45 ppmode: &PpSourceMode,
47 tcx: Option<TyCtxt<'tcx>>,
51 F: FnOnce(&dyn PrinterSupport) -> A,
54 PpmNormal | PpmEveryBodyLoops | PpmExpanded => {
55 let annotation = NoAnn {
62 PpmIdentified | PpmExpandedIdentified => {
63 let annotation = IdentifiedAnnotation {
69 PpmExpandedHygiene => {
70 let annotation = HygieneAnnotation {
75 _ => panic!("Should use call_with_pp_support_hir"),
78 fn call_with_pp_support_hir<A, F>(ppmode: &PpSourceMode, tcx: TyCtxt<'_>, f: F) -> A
80 F: FnOnce(&dyn HirPrinterSupport<'_>, &hir::Crate) -> A,
84 let annotation = NoAnn {
88 f(&annotation, tcx.hir().forest.krate())
92 let annotation = IdentifiedAnnotation {
96 f(&annotation, tcx.hir().forest.krate())
99 abort_on_err(tcx.analysis(LOCAL_CRATE), tcx.sess);
101 let empty_tables = ty::TypeckTables::empty(None);
102 let annotation = TypedAnnotation {
104 tables: Cell::new(&empty_tables)
106 tcx.dep_graph.with_ignore(|| {
107 f(&annotation, tcx.hir().forest.krate())
110 _ => panic!("Should use call_with_pp_support"),
114 trait PrinterSupport: pprust::PpAnn {
115 /// Provides a uniform interface for re-extracting a reference to a
116 /// `Session` from a value that now owns it.
117 fn sess(&self) -> &Session;
119 /// Produces the pretty-print annotation object.
121 /// (Rust does not yet support upcasting from a trait object to
122 /// an object for one of its super-traits.)
123 fn pp_ann<'a>(&'a self) -> &'a dyn pprust::PpAnn;
126 trait HirPrinterSupport<'hir>: pprust_hir::PpAnn {
127 /// Provides a uniform interface for re-extracting a reference to a
128 /// `Session` from a value that now owns it.
129 fn sess(&self) -> &Session;
131 /// Provides a uniform interface for re-extracting a reference to an
132 /// `hir_map::Map` from a value that now owns it.
133 fn hir_map<'a>(&'a self) -> Option<&'a hir_map::Map<'hir>>;
135 /// Produces the pretty-print annotation object.
137 /// (Rust does not yet support upcasting from a trait object to
138 /// an object for one of its super-traits.)
139 fn pp_ann<'a>(&'a self) -> &'a dyn pprust_hir::PpAnn;
141 /// Computes an user-readable representation of a path, if possible.
142 fn node_path(&self, id: hir::HirId) -> Option<String> {
143 self.hir_map().and_then(|map| {
144 map.def_path_from_hir_id(id)
148 .map(|elem| elem.data.to_string())
157 tcx: Option<TyCtxt<'hir>>,
160 impl<'hir> PrinterSupport for NoAnn<'hir> {
161 fn sess(&self) -> &Session {
165 fn pp_ann<'a>(&'a self) -> &'a dyn pprust::PpAnn {
170 impl<'hir> HirPrinterSupport<'hir> for NoAnn<'hir> {
171 fn sess(&self) -> &Session {
175 fn hir_map<'a>(&'a self) -> Option<&'a hir_map::Map<'hir>> {
176 self.tcx.map(|tcx| tcx.hir())
179 fn pp_ann<'a>(&'a self) -> &'a dyn pprust_hir::PpAnn {
184 impl<'hir> pprust::PpAnn for NoAnn<'hir> {}
185 impl<'hir> pprust_hir::PpAnn for NoAnn<'hir> {
186 fn nested(&self, state: &mut pprust_hir::State<'_>, nested: pprust_hir::Nested) {
187 if let Some(tcx) = self.tcx {
188 pprust_hir::PpAnn::nested(tcx.hir(), state, nested)
193 struct IdentifiedAnnotation<'hir> {
195 tcx: Option<TyCtxt<'hir>>,
198 impl<'hir> PrinterSupport for IdentifiedAnnotation<'hir> {
199 fn sess(&self) -> &Session {
203 fn pp_ann<'a>(&'a self) -> &'a dyn pprust::PpAnn {
208 impl<'hir> pprust::PpAnn for IdentifiedAnnotation<'hir> {
209 fn pre(&self, s: &mut pprust::State<'_>, node: pprust::AnnNode<'_>) {
211 pprust::AnnNode::Expr(_) => s.popen(),
215 fn post(&self, s: &mut pprust::State<'_>, node: pprust::AnnNode<'_>) {
217 pprust::AnnNode::Crate(_) |
218 pprust::AnnNode::Ident(_) |
219 pprust::AnnNode::Name(_) => {},
221 pprust::AnnNode::Item(item) => {
223 s.synth_comment(item.id.to_string())
225 pprust::AnnNode::SubItem(id) => {
227 s.synth_comment(id.to_string())
229 pprust::AnnNode::Block(blk) => {
231 s.synth_comment(format!("block {}", blk.id))
233 pprust::AnnNode::Expr(expr) => {
235 s.synth_comment(expr.id.to_string());
238 pprust::AnnNode::Pat(pat) => {
240 s.synth_comment(format!("pat {}", pat.id));
246 impl<'hir> HirPrinterSupport<'hir> for IdentifiedAnnotation<'hir> {
247 fn sess(&self) -> &Session {
251 fn hir_map<'a>(&'a self) -> Option<&'a hir_map::Map<'hir>> {
252 self.tcx.map(|tcx| tcx.hir())
255 fn pp_ann<'a>(&'a self) -> &'a dyn pprust_hir::PpAnn {
260 impl<'hir> pprust_hir::PpAnn for IdentifiedAnnotation<'hir> {
261 fn nested(&self, state: &mut pprust_hir::State<'_>, nested: pprust_hir::Nested) {
262 if let Some(ref tcx) = self.tcx {
263 pprust_hir::PpAnn::nested(tcx.hir(), state, nested)
266 fn pre(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) {
268 pprust_hir::AnnNode::Expr(_) => s.popen(),
272 fn post(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) {
274 pprust_hir::AnnNode::Name(_) => {},
275 pprust_hir::AnnNode::Item(item) => {
277 s.synth_comment(format!("hir_id: {}", item.hir_id));
279 pprust_hir::AnnNode::SubItem(id) => {
281 s.synth_comment(id.to_string());
283 pprust_hir::AnnNode::Block(blk) => {
285 s.synth_comment(format!("block hir_id: {}", blk.hir_id));
287 pprust_hir::AnnNode::Expr(expr) => {
289 s.synth_comment(format!("expr hir_id: {}", expr.hir_id));
292 pprust_hir::AnnNode::Pat(pat) => {
294 s.synth_comment(format!("pat hir_id: {}", pat.hir_id));
296 pprust_hir::AnnNode::Arm(arm) => {
298 s.synth_comment(format!("arm hir_id: {}", arm.hir_id));
304 struct HygieneAnnotation<'a> {
308 impl<'a> PrinterSupport for HygieneAnnotation<'a> {
309 fn sess(&self) -> &Session {
313 fn pp_ann(&self) -> &dyn pprust::PpAnn {
318 impl<'a> pprust::PpAnn for HygieneAnnotation<'a> {
319 fn post(&self, s: &mut pprust::State<'_>, node: pprust::AnnNode<'_>) {
321 pprust::AnnNode::Ident(&ast::Ident { name, span }) => {
323 s.synth_comment(format!("{}{:?}", name.as_u32(), span.ctxt()))
325 pprust::AnnNode::Name(&name) => {
327 s.synth_comment(name.as_u32().to_string())
329 pprust::AnnNode::Crate(_) => {
331 let verbose = self.sess.verbose();
332 s.synth_comment(syntax_pos::hygiene::debug_hygiene_data(verbose));
333 s.s.hardbreak_if_not_bol();
340 struct TypedAnnotation<'a, 'tcx> {
342 tables: Cell<&'a ty::TypeckTables<'tcx>>,
345 impl<'b, 'tcx> HirPrinterSupport<'tcx> for TypedAnnotation<'b, 'tcx> {
346 fn sess(&self) -> &Session {
350 fn hir_map<'a>(&'a self) -> Option<&'a hir_map::Map<'tcx>> {
351 Some(&self.tcx.hir())
354 fn pp_ann<'a>(&'a self) -> &'a dyn pprust_hir::PpAnn {
358 fn node_path(&self, id: hir::HirId) -> Option<String> {
359 Some(self.tcx.def_path_str(self.tcx.hir().local_def_id(id)))
363 impl<'a, 'tcx> pprust_hir::PpAnn for TypedAnnotation<'a, 'tcx> {
364 fn nested(&self, state: &mut pprust_hir::State<'_>, nested: pprust_hir::Nested) {
365 let old_tables = self.tables.get();
366 if let pprust_hir::Nested::Body(id) = nested {
367 self.tables.set(self.tcx.body_tables(id));
369 pprust_hir::PpAnn::nested(self.tcx.hir(), state, nested);
370 self.tables.set(old_tables);
372 fn pre(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) {
374 pprust_hir::AnnNode::Expr(_) => s.popen(),
378 fn post(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) {
380 pprust_hir::AnnNode::Expr(expr) => {
384 s.s.word(self.tables.get().expr_ty(expr).to_string());
392 fn get_source(input: &Input, sess: &Session) -> (String, FileName) {
393 let src_name = source_name(input);
394 let src = String::clone(&sess.source_map()
395 .get_source_file(&src_name)
403 fn write_output(out: Vec<u8>, ofile: Option<&Path>) {
405 None => print!("{}", String::from_utf8(out).unwrap()),
407 match File::create(p) {
408 Ok(mut w) => w.write_all(&out).unwrap(),
409 Err(e) => panic!("print-print failed to open {} due to {}", p.display(), e),
415 pub fn print_after_parsing(sess: &Session,
419 ofile: Option<&Path>) {
420 let (src, src_name) = get_source(input, sess);
422 let mut out = String::new();
424 if let PpmSource(s) = ppm {
425 // Silently ignores an identified node.
427 call_with_pp_support(&s, sess, None, move |annotation| {
428 debug!("pretty printing source code {:?}", s);
429 let sess = annotation.sess();
430 *out = pprust::print_crate(sess.source_map(),
442 write_output(out.into_bytes(), ofile);
445 pub fn print_after_hir_lowering<'tcx>(
450 ofile: Option<&Path>,
452 if ppm.needs_analysis() {
453 abort_on_err(print_with_analysis(
461 let (src, src_name) = get_source(input, tcx.sess);
463 let mut out = String::new();
467 // Silently ignores an identified node.
469 let src = src.clone();
470 call_with_pp_support(&s, tcx.sess, Some(tcx), move |annotation| {
471 debug!("pretty printing source code {:?}", s);
472 let sess = annotation.sess();
473 *out = pprust::print_crate(sess.source_map(),
485 let src = src.clone();
486 call_with_pp_support_hir(&s, tcx, move |annotation, krate| {
487 debug!("pretty printing source code {:?}", s);
488 let sess = annotation.sess();
489 *out = pprust_hir::print_crate(sess.source_map(),
500 call_with_pp_support_hir(&s, tcx, move |_annotation, krate| {
501 debug!("pretty printing source code {:?}", s);
502 *out = format!("{:#?}", krate);
509 write_output(out.into_bytes(), ofile);
512 // In an ideal world, this would be a public function called by the driver after
513 // analysis is performed. However, we want to call `phase_3_run_analysis_passes`
514 // with a different callback than the standard driver, so that isn't easy.
515 // Instead, we call that function ourselves.
516 fn print_with_analysis(
519 ofile: Option<&Path>,
520 ) -> Result<(), ErrorReported> {
521 let mut out = Vec::new();
523 tcx.analysis(LOCAL_CRATE)?;
526 PpmMir | PpmMirCFG => {
528 PpmMir => write_mir_pretty(tcx, None, &mut out),
529 PpmMirCFG => write_mir_graphviz(tcx, None, &mut out),
536 write_output(out, ofile);