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 // 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 {
58 PpmIdentified | PpmExpandedIdentified => {
59 let annotation = IdentifiedAnnotation {
65 PpmExpandedHygiene => {
66 let annotation = HygieneAnnotation {
71 _ => panic!("Should use call_with_pp_support_hir"),
74 fn call_with_pp_support_hir<A, F>(ppmode: &PpSourceMode, tcx: TyCtxt<'_>, f: F) -> A
76 F: FnOnce(&dyn HirPrinterSupport<'_>, &hir::Crate) -> A,
80 let annotation = NoAnn {
84 f(&annotation, tcx.hir().forest.krate())
88 let annotation = IdentifiedAnnotation {
92 f(&annotation, tcx.hir().forest.krate())
95 abort_on_err(tcx.analysis(LOCAL_CRATE), tcx.sess);
97 let empty_tables = ty::TypeckTables::empty(None);
98 let annotation = TypedAnnotation {
100 tables: Cell::new(&empty_tables)
102 tcx.dep_graph.with_ignore(|| {
103 f(&annotation, tcx.hir().forest.krate())
106 _ => panic!("Should use call_with_pp_support"),
110 trait PrinterSupport: pprust::PpAnn {
111 /// Provides a uniform interface for re-extracting a reference to a
112 /// `Session` from a value that now owns it.
113 fn sess(&self) -> &Session;
115 /// Produces the pretty-print annotation object.
117 /// (Rust does not yet support upcasting from a trait object to
118 /// an object for one of its super-traits.)
119 fn pp_ann<'a>(&'a self) -> &'a dyn pprust::PpAnn;
122 trait HirPrinterSupport<'hir>: pprust_hir::PpAnn {
123 /// Provides a uniform interface for re-extracting a reference to a
124 /// `Session` from a value that now owns it.
125 fn sess(&self) -> &Session;
127 /// Provides a uniform interface for re-extracting a reference to an
128 /// `hir_map::Map` from a value that now owns it.
129 fn hir_map<'a>(&'a self) -> Option<&'a hir_map::Map<'hir>>;
131 /// Produces the pretty-print annotation object.
133 /// (Rust does not yet support upcasting from a trait object to
134 /// an object for one of its super-traits.)
135 fn pp_ann<'a>(&'a self) -> &'a dyn pprust_hir::PpAnn;
137 /// Computes an user-readable representation of a path, if possible.
138 fn node_path(&self, id: hir::HirId) -> Option<String> {
139 self.hir_map().and_then(|map| {
140 map.def_path_from_hir_id(id)
144 .map(|elem| elem.data.to_string())
153 tcx: Option<TyCtxt<'hir>>,
156 impl<'hir> PrinterSupport for NoAnn<'hir> {
157 fn sess(&self) -> &Session {
161 fn pp_ann<'a>(&'a self) -> &'a dyn pprust::PpAnn {
166 impl<'hir> HirPrinterSupport<'hir> for NoAnn<'hir> {
167 fn sess(&self) -> &Session {
171 fn hir_map<'a>(&'a self) -> Option<&'a hir_map::Map<'hir>> {
172 self.tcx.map(|tcx| tcx.hir())
175 fn pp_ann<'a>(&'a self) -> &'a dyn pprust_hir::PpAnn {
180 impl<'hir> pprust::PpAnn for NoAnn<'hir> {}
181 impl<'hir> pprust_hir::PpAnn for NoAnn<'hir> {
182 fn nested(&self, state: &mut pprust_hir::State<'_>, nested: pprust_hir::Nested) {
183 if let Some(tcx) = self.tcx {
184 pprust_hir::PpAnn::nested(tcx.hir(), state, nested)
189 struct IdentifiedAnnotation<'hir> {
191 tcx: Option<TyCtxt<'hir>>,
194 impl<'hir> PrinterSupport for IdentifiedAnnotation<'hir> {
195 fn sess(&self) -> &Session {
199 fn pp_ann<'a>(&'a self) -> &'a dyn pprust::PpAnn {
204 impl<'hir> pprust::PpAnn for IdentifiedAnnotation<'hir> {
205 fn pre(&self, s: &mut pprust::State<'_>, node: pprust::AnnNode<'_>) {
207 pprust::AnnNode::Expr(_) => s.popen(),
211 fn post(&self, s: &mut pprust::State<'_>, node: pprust::AnnNode<'_>) {
213 pprust::AnnNode::Crate(_) |
214 pprust::AnnNode::Ident(_) |
215 pprust::AnnNode::Name(_) => {},
217 pprust::AnnNode::Item(item) => {
219 s.synth_comment(item.id.to_string())
221 pprust::AnnNode::SubItem(id) => {
223 s.synth_comment(id.to_string())
225 pprust::AnnNode::Block(blk) => {
227 s.synth_comment(format!("block {}", blk.id))
229 pprust::AnnNode::Expr(expr) => {
231 s.synth_comment(expr.id.to_string());
234 pprust::AnnNode::Pat(pat) => {
236 s.synth_comment(format!("pat {}", pat.id));
242 impl<'hir> HirPrinterSupport<'hir> for IdentifiedAnnotation<'hir> {
243 fn sess(&self) -> &Session {
247 fn hir_map<'a>(&'a self) -> Option<&'a hir_map::Map<'hir>> {
248 self.tcx.map(|tcx| tcx.hir())
251 fn pp_ann<'a>(&'a self) -> &'a dyn pprust_hir::PpAnn {
256 impl<'hir> pprust_hir::PpAnn for IdentifiedAnnotation<'hir> {
257 fn nested(&self, state: &mut pprust_hir::State<'_>, nested: pprust_hir::Nested) {
258 if let Some(ref tcx) = self.tcx {
259 pprust_hir::PpAnn::nested(tcx.hir(), state, nested)
262 fn pre(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) {
264 pprust_hir::AnnNode::Expr(_) => s.popen(),
268 fn post(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) {
270 pprust_hir::AnnNode::Name(_) => {},
271 pprust_hir::AnnNode::Item(item) => {
273 s.synth_comment(format!("hir_id: {}", item.hir_id));
275 pprust_hir::AnnNode::SubItem(id) => {
277 s.synth_comment(id.to_string());
279 pprust_hir::AnnNode::Block(blk) => {
281 s.synth_comment(format!("block hir_id: {}", blk.hir_id));
283 pprust_hir::AnnNode::Expr(expr) => {
285 s.synth_comment(format!("expr hir_id: {}", expr.hir_id));
288 pprust_hir::AnnNode::Pat(pat) => {
290 s.synth_comment(format!("pat hir_id: {}", pat.hir_id));
292 pprust_hir::AnnNode::Arm(arm) => {
294 s.synth_comment(format!("arm hir_id: {}", arm.hir_id));
300 struct HygieneAnnotation<'a> {
304 impl<'a> PrinterSupport for HygieneAnnotation<'a> {
305 fn sess(&self) -> &Session {
309 fn pp_ann(&self) -> &dyn pprust::PpAnn {
314 impl<'a> pprust::PpAnn for HygieneAnnotation<'a> {
315 fn post(&self, s: &mut pprust::State<'_>, node: pprust::AnnNode<'_>) {
317 pprust::AnnNode::Ident(&ast::Ident { name, span }) => {
319 s.synth_comment(format!("{}{:?}", name.as_u32(), span.ctxt()))
321 pprust::AnnNode::Name(&name) => {
323 s.synth_comment(name.as_u32().to_string())
325 pprust::AnnNode::Crate(_) => {
327 let verbose = self.sess.verbose();
328 s.synth_comment(syntax_pos::hygiene::debug_hygiene_data(verbose));
329 s.s.hardbreak_if_not_bol();
336 struct TypedAnnotation<'a, 'tcx> {
338 tables: Cell<&'a ty::TypeckTables<'tcx>>,
341 impl<'b, 'tcx> HirPrinterSupport<'tcx> for TypedAnnotation<'b, 'tcx> {
342 fn sess(&self) -> &Session {
346 fn hir_map<'a>(&'a self) -> Option<&'a hir_map::Map<'tcx>> {
347 Some(&self.tcx.hir())
350 fn pp_ann<'a>(&'a self) -> &'a dyn pprust_hir::PpAnn {
354 fn node_path(&self, id: hir::HirId) -> Option<String> {
355 Some(self.tcx.def_path_str(self.tcx.hir().local_def_id(id)))
359 impl<'a, 'tcx> pprust_hir::PpAnn for TypedAnnotation<'a, 'tcx> {
360 fn nested(&self, state: &mut pprust_hir::State<'_>, nested: pprust_hir::Nested) {
361 let old_tables = self.tables.get();
362 if let pprust_hir::Nested::Body(id) = nested {
363 self.tables.set(self.tcx.body_tables(id));
365 pprust_hir::PpAnn::nested(self.tcx.hir(), state, nested);
366 self.tables.set(old_tables);
368 fn pre(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) {
370 pprust_hir::AnnNode::Expr(_) => s.popen(),
374 fn post(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) {
376 pprust_hir::AnnNode::Expr(expr) => {
380 s.s.word(self.tables.get().expr_ty(expr).to_string());
388 fn get_source(input: &Input, sess: &Session) -> (String, FileName) {
389 let src_name = input.source_name();
390 let src = String::clone(&sess.source_map()
391 .get_source_file(&src_name)
399 fn write_output(out: Vec<u8>, ofile: Option<&Path>) {
401 None => print!("{}", String::from_utf8(out).unwrap()),
403 match File::create(p) {
404 Ok(mut w) => w.write_all(&out).unwrap(),
405 Err(e) => panic!("print-print failed to open {} due to {}", p.display(), e),
411 pub fn print_after_parsing(sess: &Session,
415 ofile: Option<&Path>) {
416 let (src, src_name) = get_source(input, sess);
418 let mut out = String::new();
420 if let PpmSource(s) = ppm {
421 // Silently ignores an identified node.
423 call_with_pp_support(&s, sess, None, move |annotation| {
424 debug!("pretty printing source code {:?}", s);
425 let sess = annotation.sess();
426 *out = pprust::print_crate(sess.source_map(),
438 write_output(out.into_bytes(), ofile);
441 pub fn print_after_hir_lowering<'tcx>(
446 ofile: Option<&Path>,
448 if ppm.needs_analysis() {
449 abort_on_err(print_with_analysis(
457 let (src, src_name) = get_source(input, tcx.sess);
459 let mut out = String::new();
463 // Silently ignores an identified node.
465 let src = src.clone();
466 call_with_pp_support(&s, tcx.sess, Some(tcx), move |annotation| {
467 debug!("pretty printing source code {:?}", s);
468 let sess = annotation.sess();
469 *out = pprust::print_crate(sess.source_map(),
481 let src = src.clone();
482 call_with_pp_support_hir(&s, tcx, move |annotation, krate| {
483 debug!("pretty printing source code {:?}", s);
484 let sess = annotation.sess();
485 *out = pprust_hir::print_crate(sess.source_map(),
496 call_with_pp_support_hir(&s, tcx, move |_annotation, krate| {
497 debug!("pretty printing source code {:?}", s);
498 *out = format!("{:#?}", krate);
505 write_output(out.into_bytes(), ofile);
508 // In an ideal world, this would be a public function called by the driver after
509 // analysis is performed. However, we want to call `phase_3_run_analysis_passes`
510 // with a different callback than the standard driver, so that isn't easy.
511 // Instead, we call that function ourselves.
512 fn print_with_analysis(
515 ofile: Option<&Path>,
516 ) -> Result<(), ErrorReported> {
517 let mut out = Vec::new();
519 tcx.analysis(LOCAL_CRATE)?;
522 PpmMir | PpmMirCFG => {
524 PpmMir => write_mir_pretty(tcx, None, &mut out),
525 PpmMirCFG => write_mir_graphviz(tcx, None, &mut out),
532 write_output(out, ofile);