1 //! The various pretty-printing routines.
4 use rustc::hir::def_id::LOCAL_CRATE;
5 use rustc::hir::map as hir_map;
6 use rustc::hir::print as pprust_hir;
7 use rustc::session::config::{Input, PpMode, PpSourceMode};
8 use rustc::session::Session;
9 use rustc::ty::{self, TyCtxt};
10 use rustc::util::common::ErrorReported;
11 use rustc_mir::util::{write_mir_graphviz, write_mir_pretty};
13 use rustc_span::FileName;
15 use syntax::print::pprust;
22 pub use self::PpMode::*;
23 pub use self::PpSourceMode::*;
24 use crate::abort_on_err;
26 // This slightly awkward construction is to allow for each PpMode to
27 // choose whether it needs to do analyses (which can consume the
28 // Session) and then pass through the session (now attached to the
29 // analysis results) on to the chosen pretty-printer, along with the
32 // Note that since the `&PrinterSupport` is freshly constructed on each
33 // call, it would not make sense to try to attach the lifetime of `self`
34 // to the lifetime of the `&PrinterObject`.
36 // (The `use_once_payload` is working around the current lack of once
37 // functions in the compiler.)
39 /// Constructs a `PrinterSupport` object and passes it to `f`.
40 fn call_with_pp_support<'tcx, A, F>(
41 ppmode: &PpSourceMode,
43 tcx: Option<TyCtxt<'tcx>>,
47 F: FnOnce(&dyn PrinterSupport) -> A,
50 PpmNormal | PpmEveryBodyLoops | PpmExpanded => {
51 let annotation = NoAnn { sess, tcx };
55 PpmIdentified | PpmExpandedIdentified => {
56 let annotation = IdentifiedAnnotation { sess, tcx };
59 PpmExpandedHygiene => {
60 let annotation = HygieneAnnotation { sess };
63 _ => panic!("Should use call_with_pp_support_hir"),
66 fn call_with_pp_support_hir<A, F>(ppmode: &PpSourceMode, tcx: TyCtxt<'_>, f: F) -> A
68 F: FnOnce(&dyn HirPrinterSupport<'_>, &hir::Crate<'_>) -> A,
72 let annotation = NoAnn { sess: tcx.sess, tcx: Some(tcx) };
73 f(&annotation, tcx.hir().forest.krate())
77 let annotation = IdentifiedAnnotation { sess: tcx.sess, tcx: Some(tcx) };
78 f(&annotation, tcx.hir().forest.krate())
81 abort_on_err(tcx.analysis(LOCAL_CRATE), tcx.sess);
83 let empty_tables = ty::TypeckTables::empty(None);
84 let annotation = TypedAnnotation { tcx, tables: Cell::new(&empty_tables) };
85 tcx.dep_graph.with_ignore(|| f(&annotation, tcx.hir().forest.krate()))
87 _ => panic!("Should use call_with_pp_support"),
91 trait PrinterSupport: pprust::PpAnn {
92 /// Provides a uniform interface for re-extracting a reference to a
93 /// `Session` from a value that now owns it.
94 fn sess(&self) -> &Session;
96 /// Produces the pretty-print annotation object.
98 /// (Rust does not yet support upcasting from a trait object to
99 /// an object for one of its super-traits.)
100 fn pp_ann<'a>(&'a self) -> &'a dyn pprust::PpAnn;
103 trait HirPrinterSupport<'hir>: pprust_hir::PpAnn {
104 /// Provides a uniform interface for re-extracting a reference to a
105 /// `Session` from a value that now owns it.
106 fn sess(&self) -> &Session;
108 /// Provides a uniform interface for re-extracting a reference to an
109 /// `hir_map::Map` from a value that now owns it.
110 fn hir_map<'a>(&'a self) -> Option<&'a hir_map::Map<'hir>>;
112 /// Produces the pretty-print annotation object.
114 /// (Rust does not yet support upcasting from a trait object to
115 /// an object for one of its super-traits.)
116 fn pp_ann<'a>(&'a self) -> &'a dyn pprust_hir::PpAnn;
118 /// Computes an user-readable representation of a path, if possible.
119 fn node_path(&self, id: hir::HirId) -> Option<String> {
120 self.hir_map().and_then(|map| map.def_path_from_hir_id(id)).map(|path| {
121 path.data.into_iter().map(|elem| elem.data.to_string()).collect::<Vec<_>>().join("::")
128 tcx: Option<TyCtxt<'hir>>,
131 impl<'hir> PrinterSupport for NoAnn<'hir> {
132 fn sess(&self) -> &Session {
136 fn pp_ann<'a>(&'a self) -> &'a dyn pprust::PpAnn {
141 impl<'hir> HirPrinterSupport<'hir> for NoAnn<'hir> {
142 fn sess(&self) -> &Session {
146 fn hir_map<'a>(&'a self) -> Option<&'a hir_map::Map<'hir>> {
147 self.tcx.map(|tcx| tcx.hir())
150 fn pp_ann<'a>(&'a self) -> &'a dyn pprust_hir::PpAnn {
155 impl<'hir> pprust::PpAnn for NoAnn<'hir> {}
156 impl<'hir> pprust_hir::PpAnn for NoAnn<'hir> {
157 fn nested(&self, state: &mut pprust_hir::State<'_>, nested: pprust_hir::Nested) {
158 if let Some(tcx) = self.tcx {
159 pprust_hir::PpAnn::nested(tcx.hir(), state, nested)
164 struct IdentifiedAnnotation<'hir> {
166 tcx: Option<TyCtxt<'hir>>,
169 impl<'hir> PrinterSupport for IdentifiedAnnotation<'hir> {
170 fn sess(&self) -> &Session {
174 fn pp_ann<'a>(&'a self) -> &'a dyn pprust::PpAnn {
179 impl<'hir> pprust::PpAnn for IdentifiedAnnotation<'hir> {
180 fn pre(&self, s: &mut pprust::State<'_>, node: pprust::AnnNode<'_>) {
182 pprust::AnnNode::Expr(_) => s.popen(),
186 fn post(&self, s: &mut pprust::State<'_>, node: pprust::AnnNode<'_>) {
188 pprust::AnnNode::Crate(_) | pprust::AnnNode::Ident(_) | pprust::AnnNode::Name(_) => {}
190 pprust::AnnNode::Item(item) => {
192 s.synth_comment(item.id.to_string())
194 pprust::AnnNode::SubItem(id) => {
196 s.synth_comment(id.to_string())
198 pprust::AnnNode::Block(blk) => {
200 s.synth_comment(format!("block {}", blk.id))
202 pprust::AnnNode::Expr(expr) => {
204 s.synth_comment(expr.id.to_string());
207 pprust::AnnNode::Pat(pat) => {
209 s.synth_comment(format!("pat {}", pat.id));
215 impl<'hir> HirPrinterSupport<'hir> for IdentifiedAnnotation<'hir> {
216 fn sess(&self) -> &Session {
220 fn hir_map<'a>(&'a self) -> Option<&'a hir_map::Map<'hir>> {
221 self.tcx.map(|tcx| tcx.hir())
224 fn pp_ann<'a>(&'a self) -> &'a dyn pprust_hir::PpAnn {
229 impl<'hir> pprust_hir::PpAnn for IdentifiedAnnotation<'hir> {
230 fn nested(&self, state: &mut pprust_hir::State<'_>, nested: pprust_hir::Nested) {
231 if let Some(ref tcx) = self.tcx {
232 pprust_hir::PpAnn::nested(tcx.hir(), state, nested)
235 fn pre(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) {
237 pprust_hir::AnnNode::Expr(_) => s.popen(),
241 fn post(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) {
243 pprust_hir::AnnNode::Name(_) => {}
244 pprust_hir::AnnNode::Item(item) => {
246 s.synth_comment(format!("hir_id: {}", item.hir_id));
248 pprust_hir::AnnNode::SubItem(id) => {
250 s.synth_comment(id.to_string());
252 pprust_hir::AnnNode::Block(blk) => {
254 s.synth_comment(format!("block hir_id: {}", blk.hir_id));
256 pprust_hir::AnnNode::Expr(expr) => {
258 s.synth_comment(format!("expr hir_id: {}", expr.hir_id));
261 pprust_hir::AnnNode::Pat(pat) => {
263 s.synth_comment(format!("pat hir_id: {}", pat.hir_id));
265 pprust_hir::AnnNode::Arm(arm) => {
267 s.synth_comment(format!("arm hir_id: {}", arm.hir_id));
273 struct HygieneAnnotation<'a> {
277 impl<'a> PrinterSupport for HygieneAnnotation<'a> {
278 fn sess(&self) -> &Session {
282 fn pp_ann(&self) -> &dyn pprust::PpAnn {
287 impl<'a> pprust::PpAnn for HygieneAnnotation<'a> {
288 fn post(&self, s: &mut pprust::State<'_>, node: pprust::AnnNode<'_>) {
290 pprust::AnnNode::Ident(&ast::Ident { name, span }) => {
292 s.synth_comment(format!("{}{:?}", name.as_u32(), span.ctxt()))
294 pprust::AnnNode::Name(&name) => {
296 s.synth_comment(name.as_u32().to_string())
298 pprust::AnnNode::Crate(_) => {
300 let verbose = self.sess.verbose();
301 s.synth_comment(rustc_span::hygiene::debug_hygiene_data(verbose));
302 s.s.hardbreak_if_not_bol();
309 struct TypedAnnotation<'a, 'tcx> {
311 tables: Cell<&'a ty::TypeckTables<'tcx>>,
314 impl<'b, 'tcx> HirPrinterSupport<'tcx> for TypedAnnotation<'b, 'tcx> {
315 fn sess(&self) -> &Session {
319 fn hir_map<'a>(&'a self) -> Option<&'a hir_map::Map<'tcx>> {
320 Some(&self.tcx.hir())
323 fn pp_ann<'a>(&'a self) -> &'a dyn pprust_hir::PpAnn {
327 fn node_path(&self, id: hir::HirId) -> Option<String> {
328 Some(self.tcx.def_path_str(self.tcx.hir().local_def_id(id)))
332 impl<'a, 'tcx> pprust_hir::PpAnn for TypedAnnotation<'a, 'tcx> {
333 fn nested(&self, state: &mut pprust_hir::State<'_>, nested: pprust_hir::Nested) {
334 let old_tables = self.tables.get();
335 if let pprust_hir::Nested::Body(id) = nested {
336 self.tables.set(self.tcx.body_tables(id));
338 pprust_hir::PpAnn::nested(self.tcx.hir(), state, nested);
339 self.tables.set(old_tables);
341 fn pre(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) {
343 pprust_hir::AnnNode::Expr(_) => s.popen(),
347 fn post(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) {
349 pprust_hir::AnnNode::Expr(expr) => {
353 s.s.word(self.tables.get().expr_ty(expr).to_string());
361 fn get_source(input: &Input, sess: &Session) -> (String, FileName) {
362 let src_name = input.source_name();
364 String::clone(&sess.source_map().get_source_file(&src_name).unwrap().src.as_ref().unwrap());
368 fn write_output(out: Vec<u8>, ofile: Option<&Path>) {
370 None => print!("{}", String::from_utf8(out).unwrap()),
371 Some(p) => match File::create(p) {
372 Ok(mut w) => w.write_all(&out).unwrap(),
373 Err(e) => panic!("print-print failed to open {} due to {}", p.display(), e),
378 pub fn print_after_parsing(
383 ofile: Option<&Path>,
385 let (src, src_name) = get_source(input, sess);
387 let mut out = String::new();
389 if let PpmSource(s) = ppm {
390 // Silently ignores an identified node.
392 call_with_pp_support(&s, sess, None, move |annotation| {
393 debug!("pretty printing source code {:?}", s);
394 let sess = annotation.sess();
395 *out = pprust::print_crate(
409 write_output(out.into_bytes(), ofile);
412 pub fn print_after_hir_lowering<'tcx>(
417 ofile: Option<&Path>,
419 if ppm.needs_analysis() {
420 abort_on_err(print_with_analysis(tcx, ppm, ofile), tcx.sess);
424 let (src, src_name) = get_source(input, tcx.sess);
426 let mut out = String::new();
430 // Silently ignores an identified node.
432 let src = src.clone();
433 call_with_pp_support(&s, tcx.sess, Some(tcx), move |annotation| {
434 debug!("pretty printing source code {:?}", s);
435 let sess = annotation.sess();
436 *out = pprust::print_crate(
450 let src = src.clone();
451 call_with_pp_support_hir(&s, tcx, move |annotation, krate| {
452 debug!("pretty printing source code {:?}", s);
453 let sess = annotation.sess();
454 *out = pprust_hir::print_crate(
467 call_with_pp_support_hir(&s, tcx, move |_annotation, krate| {
468 debug!("pretty printing source code {:?}", s);
469 *out = format!("{:#?}", krate);
476 write_output(out.into_bytes(), ofile);
479 // In an ideal world, this would be a public function called by the driver after
480 // analysis is performed. However, we want to call `phase_3_run_analysis_passes`
481 // with a different callback than the standard driver, so that isn't easy.
482 // Instead, we call that function ourselves.
483 fn print_with_analysis(
486 ofile: Option<&Path>,
487 ) -> Result<(), ErrorReported> {
488 let mut out = Vec::new();
490 tcx.analysis(LOCAL_CRATE)?;
493 PpmMir | PpmMirCFG => match ppm {
494 PpmMir => write_mir_pretty(tcx, None, &mut out),
495 PpmMirCFG => write_mir_graphviz(tcx, None, &mut out),
502 write_output(out, ofile);