1 //! The various pretty-printing routines.
3 use rustc::hir::map as hir_map;
4 use rustc::session::config::{Input, PpMode, PpSourceMode};
5 use rustc::session::Session;
6 use rustc::ty::{self, TyCtxt};
7 use rustc::util::common::ErrorReported;
8 use rustc_ast_pretty::pprust;
10 use rustc_hir::def_id::LOCAL_CRATE;
11 use rustc_hir::print as pprust_hir;
12 use rustc_mir::util::{write_mir_graphviz, write_mir_pretty};
13 use rustc_span::FileName;
21 pub use self::PpMode::*;
22 pub use self::PpSourceMode::*;
23 use crate::abort_on_err;
25 // This slightly awkward construction is to allow for each PpMode to
26 // choose whether it needs to do analyses (which can consume the
27 // Session) and then pass through the session (now attached to the
28 // analysis results) on to the chosen pretty-printer, along with the
31 // Note that since the `&PrinterSupport` is freshly constructed on each
32 // call, it would not make sense to try to attach the lifetime of `self`
33 // to the lifetime of the `&PrinterObject`.
35 // (The `use_once_payload` is working around the current lack of once
36 // functions in the compiler.)
38 /// Constructs a `PrinterSupport` object and passes it to `f`.
39 fn call_with_pp_support<'tcx, A, F>(
40 ppmode: &PpSourceMode,
42 tcx: Option<TyCtxt<'tcx>>,
46 F: FnOnce(&dyn PrinterSupport) -> A,
49 PpmNormal | PpmEveryBodyLoops | PpmExpanded => {
50 let annotation = NoAnn { sess, tcx };
54 PpmIdentified | PpmExpandedIdentified => {
55 let annotation = IdentifiedAnnotation { sess, tcx };
58 PpmExpandedHygiene => {
59 let annotation = HygieneAnnotation { sess };
62 _ => panic!("Should use call_with_pp_support_hir"),
65 fn call_with_pp_support_hir<A, F>(ppmode: &PpSourceMode, tcx: TyCtxt<'_>, f: F) -> A
67 F: FnOnce(&dyn HirPrinterSupport<'_>, &hir::Crate<'_>) -> A,
71 let annotation = NoAnn { sess: tcx.sess, tcx: Some(tcx) };
72 f(&annotation, tcx.hir().krate())
76 let annotation = IdentifiedAnnotation { sess: tcx.sess, tcx: Some(tcx) };
77 f(&annotation, tcx.hir().krate())
80 abort_on_err(tcx.analysis(LOCAL_CRATE), tcx.sess);
82 let empty_tables = ty::TypeckTables::empty(None);
83 let annotation = TypedAnnotation { tcx, tables: Cell::new(&empty_tables) };
84 tcx.dep_graph.with_ignore(|| f(&annotation, tcx.hir().krate()))
86 _ => panic!("Should use call_with_pp_support"),
90 trait PrinterSupport: pprust::PpAnn {
91 /// Provides a uniform interface for re-extracting a reference to a
92 /// `Session` from a value that now owns it.
93 fn sess(&self) -> &Session;
95 /// Produces the pretty-print annotation object.
97 /// (Rust does not yet support upcasting from a trait object to
98 /// an object for one of its super-traits.)
99 fn pp_ann<'a>(&'a self) -> &'a dyn pprust::PpAnn;
102 trait HirPrinterSupport<'hir>: pprust_hir::PpAnn {
103 /// Provides a uniform interface for re-extracting a reference to a
104 /// `Session` from a value that now owns it.
105 fn sess(&self) -> &Session;
107 /// Provides a uniform interface for re-extracting a reference to an
108 /// `hir_map::Map` from a value that now owns it.
109 fn hir_map<'a>(&'a self) -> Option<&'a hir_map::Map<'hir>>;
111 /// Produces the pretty-print annotation object.
113 /// (Rust does not yet support upcasting from a trait object to
114 /// an object for one of its super-traits.)
115 fn pp_ann<'a>(&'a self) -> &'a dyn pprust_hir::PpAnn;
117 /// Computes an user-readable representation of a path, if possible.
118 fn node_path(&self, id: hir::HirId) -> Option<String> {
119 self.hir_map().and_then(|map| map.def_path_from_hir_id(id)).map(|path| {
120 path.data.into_iter().map(|elem| elem.data.to_string()).collect::<Vec<_>>().join("::")
127 tcx: Option<TyCtxt<'hir>>,
130 impl<'hir> PrinterSupport for NoAnn<'hir> {
131 fn sess(&self) -> &Session {
135 fn pp_ann<'a>(&'a self) -> &'a dyn pprust::PpAnn {
140 impl<'hir> HirPrinterSupport<'hir> for NoAnn<'hir> {
141 fn sess(&self) -> &Session {
145 fn hir_map<'a>(&'a self) -> Option<&'a hir_map::Map<'hir>> {
146 self.tcx.map(|tcx| *tcx.hir())
149 fn pp_ann<'a>(&'a self) -> &'a dyn pprust_hir::PpAnn {
154 impl<'hir> pprust::PpAnn for NoAnn<'hir> {}
155 impl<'hir> pprust_hir::PpAnn for NoAnn<'hir> {
156 fn nested(&self, state: &mut pprust_hir::State<'_>, nested: pprust_hir::Nested) {
157 if let Some(tcx) = self.tcx {
158 pprust_hir::PpAnn::nested(*tcx.hir(), state, nested)
163 struct IdentifiedAnnotation<'hir> {
165 tcx: Option<TyCtxt<'hir>>,
168 impl<'hir> PrinterSupport for IdentifiedAnnotation<'hir> {
169 fn sess(&self) -> &Session {
173 fn pp_ann<'a>(&'a self) -> &'a dyn pprust::PpAnn {
178 impl<'hir> pprust::PpAnn for IdentifiedAnnotation<'hir> {
179 fn pre(&self, s: &mut pprust::State<'_>, node: pprust::AnnNode<'_>) {
181 pprust::AnnNode::Expr(_) => s.popen(),
185 fn post(&self, s: &mut pprust::State<'_>, node: pprust::AnnNode<'_>) {
187 pprust::AnnNode::Crate(_) | pprust::AnnNode::Ident(_) | pprust::AnnNode::Name(_) => {}
189 pprust::AnnNode::Item(item) => {
191 s.synth_comment(item.id.to_string())
193 pprust::AnnNode::SubItem(id) => {
195 s.synth_comment(id.to_string())
197 pprust::AnnNode::Block(blk) => {
199 s.synth_comment(format!("block {}", blk.id))
201 pprust::AnnNode::Expr(expr) => {
203 s.synth_comment(expr.id.to_string());
206 pprust::AnnNode::Pat(pat) => {
208 s.synth_comment(format!("pat {}", pat.id));
214 impl<'hir> HirPrinterSupport<'hir> for IdentifiedAnnotation<'hir> {
215 fn sess(&self) -> &Session {
219 fn hir_map<'a>(&'a self) -> Option<&'a hir_map::Map<'hir>> {
220 self.tcx.map(|tcx| *tcx.hir())
223 fn pp_ann<'a>(&'a self) -> &'a dyn pprust_hir::PpAnn {
228 impl<'hir> pprust_hir::PpAnn for IdentifiedAnnotation<'hir> {
229 fn nested(&self, state: &mut pprust_hir::State<'_>, nested: pprust_hir::Nested) {
230 if let Some(ref tcx) = self.tcx {
231 pprust_hir::PpAnn::nested(*tcx.hir(), state, nested)
234 fn pre(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) {
236 pprust_hir::AnnNode::Expr(_) => s.popen(),
240 fn post(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) {
242 pprust_hir::AnnNode::Name(_) => {}
243 pprust_hir::AnnNode::Item(item) => {
245 s.synth_comment(format!("hir_id: {}", item.hir_id));
247 pprust_hir::AnnNode::SubItem(id) => {
249 s.synth_comment(id.to_string());
251 pprust_hir::AnnNode::Block(blk) => {
253 s.synth_comment(format!("block hir_id: {}", blk.hir_id));
255 pprust_hir::AnnNode::Expr(expr) => {
257 s.synth_comment(format!("expr hir_id: {}", expr.hir_id));
260 pprust_hir::AnnNode::Pat(pat) => {
262 s.synth_comment(format!("pat hir_id: {}", pat.hir_id));
264 pprust_hir::AnnNode::Arm(arm) => {
266 s.synth_comment(format!("arm hir_id: {}", arm.hir_id));
272 struct HygieneAnnotation<'a> {
276 impl<'a> PrinterSupport for HygieneAnnotation<'a> {
277 fn sess(&self) -> &Session {
281 fn pp_ann(&self) -> &dyn pprust::PpAnn {
286 impl<'a> pprust::PpAnn for HygieneAnnotation<'a> {
287 fn post(&self, s: &mut pprust::State<'_>, node: pprust::AnnNode<'_>) {
289 pprust::AnnNode::Ident(&ast::Ident { name, span }) => {
291 s.synth_comment(format!("{}{:?}", name.as_u32(), span.ctxt()))
293 pprust::AnnNode::Name(&name) => {
295 s.synth_comment(name.as_u32().to_string())
297 pprust::AnnNode::Crate(_) => {
299 let verbose = self.sess.verbose();
300 s.synth_comment(rustc_span::hygiene::debug_hygiene_data(verbose));
301 s.s.hardbreak_if_not_bol();
308 struct TypedAnnotation<'a, 'tcx> {
310 tables: Cell<&'a ty::TypeckTables<'tcx>>,
313 impl<'b, 'tcx> HirPrinterSupport<'tcx> for TypedAnnotation<'b, 'tcx> {
314 fn sess(&self) -> &Session {
318 fn hir_map<'a>(&'a self) -> Option<&'a hir_map::Map<'tcx>> {
319 Some(&self.tcx.hir())
322 fn pp_ann<'a>(&'a self) -> &'a dyn pprust_hir::PpAnn {
326 fn node_path(&self, id: hir::HirId) -> Option<String> {
327 Some(self.tcx.def_path_str(self.tcx.hir().local_def_id(id)))
331 impl<'a, 'tcx> pprust_hir::PpAnn for TypedAnnotation<'a, 'tcx> {
332 fn nested(&self, state: &mut pprust_hir::State<'_>, nested: pprust_hir::Nested) {
333 let old_tables = self.tables.get();
334 if let pprust_hir::Nested::Body(id) = nested {
335 self.tables.set(self.tcx.body_tables(id));
337 pprust_hir::PpAnn::nested(*self.tcx.hir(), state, nested);
338 self.tables.set(old_tables);
340 fn pre(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) {
342 pprust_hir::AnnNode::Expr(_) => s.popen(),
346 fn post(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) {
348 pprust_hir::AnnNode::Expr(expr) => {
352 s.s.word(self.tables.get().expr_ty(expr).to_string());
360 fn get_source(input: &Input, sess: &Session) -> (String, FileName) {
361 let src_name = input.source_name();
363 String::clone(&sess.source_map().get_source_file(&src_name).unwrap().src.as_ref().unwrap());
367 fn write_output(out: Vec<u8>, ofile: Option<&Path>) {
369 None => print!("{}", String::from_utf8(out).unwrap()),
370 Some(p) => match File::create(p) {
371 Ok(mut w) => w.write_all(&out).unwrap(),
372 Err(e) => panic!("print-print failed to open {} due to {}", p.display(), e),
377 pub fn print_after_parsing(
382 ofile: Option<&Path>,
384 let (src, src_name) = get_source(input, sess);
386 let mut out = String::new();
388 if let PpmSource(s) = ppm {
389 // Silently ignores an identified node.
391 call_with_pp_support(&s, sess, None, move |annotation| {
392 debug!("pretty printing source code {:?}", s);
393 let sess = annotation.sess();
394 let parse = &sess.parse_sess;
395 *out = pprust::print_crate(
403 parse.injected_crate_name.try_get().is_some(),
410 write_output(out.into_bytes(), ofile);
413 pub fn print_after_hir_lowering<'tcx>(
418 ofile: Option<&Path>,
420 if ppm.needs_analysis() {
421 abort_on_err(print_with_analysis(tcx, ppm, ofile), tcx.sess);
425 let (src, src_name) = get_source(input, tcx.sess);
427 let mut out = String::new();
431 // Silently ignores an identified node.
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 let parse = &sess.parse_sess;
437 *out = pprust::print_crate(
445 parse.injected_crate_name.try_get().is_some(),
452 call_with_pp_support_hir(&s, tcx, move |annotation, krate| {
453 debug!("pretty printing source code {:?}", s);
454 let sess = annotation.sess();
455 let cm = sess.source_map();
456 *out = pprust_hir::print_crate(cm, krate, src_name, src, annotation.pp_ann())
462 call_with_pp_support_hir(&s, tcx, move |_annotation, krate| {
463 debug!("pretty printing source code {:?}", s);
464 *out = format!("{:#?}", krate);
471 write_output(out.into_bytes(), ofile);
474 // In an ideal world, this would be a public function called by the driver after
475 // analysis is performed. However, we want to call `phase_3_run_analysis_passes`
476 // with a different callback than the standard driver, so that isn't easy.
477 // Instead, we call that function ourselves.
478 fn print_with_analysis(
481 ofile: Option<&Path>,
482 ) -> Result<(), ErrorReported> {
483 let mut out = Vec::new();
485 tcx.analysis(LOCAL_CRATE)?;
488 PpmMir | PpmMirCFG => match ppm {
489 PpmMir => write_mir_pretty(tcx, None, &mut out),
490 PpmMirCFG => write_mir_graphviz(tcx, None, &mut out),
497 write_output(out, ofile);