1 //! The various pretty-printing routines.
3 use crate::session_diagnostics::UnprettyDumpFail;
5 use rustc_ast_pretty::pprust;
6 use rustc_errors::ErrorGuaranteed;
8 use rustc_hir_pretty as pprust_hir;
9 use rustc_middle::hir::map as hir_map;
10 use rustc_middle::mir::{write_mir_graphviz, write_mir_pretty};
11 use rustc_middle::ty::{self, TyCtxt};
12 use rustc_session::config::{Input, PpAstTreeMode, PpHirMode, PpMode, PpSourceMode};
13 use rustc_session::Session;
14 use rustc_span::symbol::Ident;
15 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 /// Constructs a `PrinterSupport` object and passes it to `f`.
36 fn call_with_pp_support<'tcx, A, F>(
37 ppmode: &PpSourceMode,
39 tcx: Option<TyCtxt<'tcx>>,
43 F: FnOnce(&dyn PrinterSupport) -> A,
46 Normal | Expanded => {
47 let annotation = NoAnn { sess, tcx };
51 Identified | ExpandedIdentified => {
52 let annotation = IdentifiedAnnotation { sess, tcx };
56 let annotation = HygieneAnnotation { sess };
61 fn call_with_pp_support_hir<A, F>(ppmode: &PpHirMode, tcx: TyCtxt<'_>, f: F) -> A
63 F: FnOnce(&dyn HirPrinterSupport<'_>, hir_map::Map<'_>) -> A,
66 PpHirMode::Normal => {
67 let annotation = NoAnn { sess: tcx.sess, tcx: Some(tcx) };
68 f(&annotation, tcx.hir())
71 PpHirMode::Identified => {
72 let annotation = IdentifiedAnnotation { sess: tcx.sess, tcx: Some(tcx) };
73 f(&annotation, tcx.hir())
76 abort_on_err(tcx.analysis(()), tcx.sess);
78 let annotation = TypedAnnotation { tcx, maybe_typeck_results: Cell::new(None) };
79 tcx.dep_graph.with_ignore(|| f(&annotation, tcx.hir()))
84 trait PrinterSupport: pprust::PpAnn {
85 /// Provides a uniform interface for re-extracting a reference to a
86 /// `Session` from a value that now owns it.
87 fn sess(&self) -> &Session;
89 /// Produces the pretty-print annotation object.
91 /// (Rust does not yet support upcasting from a trait object to
92 /// an object for one of its supertraits.)
93 fn pp_ann(&self) -> &dyn pprust::PpAnn;
96 trait HirPrinterSupport<'hir>: pprust_hir::PpAnn {
97 /// Provides a uniform interface for re-extracting a reference to a
98 /// `Session` from a value that now owns it.
99 fn sess(&self) -> &Session;
101 /// Provides a uniform interface for re-extracting a reference to an
102 /// `hir_map::Map` from a value that now owns it.
103 fn hir_map(&self) -> Option<hir_map::Map<'hir>>;
105 /// Produces the pretty-print annotation object.
107 /// (Rust does not yet support upcasting from a trait object to
108 /// an object for one of its supertraits.)
109 fn pp_ann(&self) -> &dyn pprust_hir::PpAnn;
114 tcx: Option<TyCtxt<'hir>>,
117 impl<'hir> PrinterSupport for NoAnn<'hir> {
118 fn sess(&self) -> &Session {
122 fn pp_ann(&self) -> &dyn pprust::PpAnn {
127 impl<'hir> HirPrinterSupport<'hir> for NoAnn<'hir> {
128 fn sess(&self) -> &Session {
132 fn hir_map(&self) -> Option<hir_map::Map<'hir>> {
133 self.tcx.map(|tcx| tcx.hir())
136 fn pp_ann(&self) -> &dyn pprust_hir::PpAnn {
141 impl<'hir> pprust::PpAnn for NoAnn<'hir> {}
142 impl<'hir> pprust_hir::PpAnn for NoAnn<'hir> {
143 fn nested(&self, state: &mut pprust_hir::State<'_>, nested: pprust_hir::Nested) {
144 if let Some(tcx) = self.tcx {
145 pprust_hir::PpAnn::nested(&(&tcx.hir() as &dyn hir::intravisit::Map<'_>), state, nested)
150 struct IdentifiedAnnotation<'hir> {
152 tcx: Option<TyCtxt<'hir>>,
155 impl<'hir> PrinterSupport for IdentifiedAnnotation<'hir> {
156 fn sess(&self) -> &Session {
160 fn pp_ann(&self) -> &dyn pprust::PpAnn {
165 impl<'hir> pprust::PpAnn for IdentifiedAnnotation<'hir> {
166 fn pre(&self, s: &mut pprust::State<'_>, node: pprust::AnnNode<'_>) {
167 if let pprust::AnnNode::Expr(_) = node {
171 fn post(&self, s: &mut pprust::State<'_>, node: pprust::AnnNode<'_>) {
173 pprust::AnnNode::Crate(_) | pprust::AnnNode::Ident(_) | pprust::AnnNode::Name(_) => {}
175 pprust::AnnNode::Item(item) => {
177 s.synth_comment(item.id.to_string())
179 pprust::AnnNode::SubItem(id) => {
181 s.synth_comment(id.to_string())
183 pprust::AnnNode::Block(blk) => {
185 s.synth_comment(format!("block {}", blk.id))
187 pprust::AnnNode::Expr(expr) => {
189 s.synth_comment(expr.id.to_string());
192 pprust::AnnNode::Pat(pat) => {
194 s.synth_comment(format!("pat {}", pat.id));
200 impl<'hir> HirPrinterSupport<'hir> for IdentifiedAnnotation<'hir> {
201 fn sess(&self) -> &Session {
205 fn hir_map(&self) -> Option<hir_map::Map<'hir>> {
206 self.tcx.map(|tcx| tcx.hir())
209 fn pp_ann(&self) -> &dyn pprust_hir::PpAnn {
214 impl<'hir> pprust_hir::PpAnn for IdentifiedAnnotation<'hir> {
215 fn nested(&self, state: &mut pprust_hir::State<'_>, nested: pprust_hir::Nested) {
216 if let Some(ref tcx) = self.tcx {
217 pprust_hir::PpAnn::nested(&(&tcx.hir() as &dyn hir::intravisit::Map<'_>), state, nested)
220 fn pre(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) {
221 if let pprust_hir::AnnNode::Expr(_) = node {
225 fn post(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) {
227 pprust_hir::AnnNode::Name(_) => {}
228 pprust_hir::AnnNode::Item(item) => {
230 s.synth_comment(format!("hir_id: {}", item.hir_id()));
232 pprust_hir::AnnNode::SubItem(id) => {
234 s.synth_comment(id.to_string());
236 pprust_hir::AnnNode::Block(blk) => {
238 s.synth_comment(format!("block hir_id: {}", blk.hir_id));
240 pprust_hir::AnnNode::Expr(expr) => {
242 s.synth_comment(format!("expr hir_id: {}", expr.hir_id));
245 pprust_hir::AnnNode::Pat(pat) => {
247 s.synth_comment(format!("pat hir_id: {}", pat.hir_id));
249 pprust_hir::AnnNode::Arm(arm) => {
251 s.synth_comment(format!("arm hir_id: {}", arm.hir_id));
257 struct HygieneAnnotation<'a> {
261 impl<'a> PrinterSupport for HygieneAnnotation<'a> {
262 fn sess(&self) -> &Session {
266 fn pp_ann(&self) -> &dyn pprust::PpAnn {
271 impl<'a> pprust::PpAnn for HygieneAnnotation<'a> {
272 fn post(&self, s: &mut pprust::State<'_>, node: pprust::AnnNode<'_>) {
274 pprust::AnnNode::Ident(&Ident { name, span }) => {
276 s.synth_comment(format!("{}{:?}", name.as_u32(), span.ctxt()))
278 pprust::AnnNode::Name(&name) => {
280 s.synth_comment(name.as_u32().to_string())
282 pprust::AnnNode::Crate(_) => {
284 let verbose = self.sess.verbose();
285 s.synth_comment(rustc_span::hygiene::debug_hygiene_data(verbose));
286 s.s.hardbreak_if_not_bol();
293 struct TypedAnnotation<'tcx> {
295 maybe_typeck_results: Cell<Option<&'tcx ty::TypeckResults<'tcx>>>,
298 impl<'tcx> HirPrinterSupport<'tcx> for TypedAnnotation<'tcx> {
299 fn sess(&self) -> &Session {
303 fn hir_map(&self) -> Option<hir_map::Map<'tcx>> {
307 fn pp_ann(&self) -> &dyn pprust_hir::PpAnn {
312 impl<'tcx> pprust_hir::PpAnn for TypedAnnotation<'tcx> {
313 fn nested(&self, state: &mut pprust_hir::State<'_>, nested: pprust_hir::Nested) {
314 let old_maybe_typeck_results = self.maybe_typeck_results.get();
315 if let pprust_hir::Nested::Body(id) = nested {
316 self.maybe_typeck_results.set(Some(self.tcx.typeck_body(id)));
318 let pp_ann = &(&self.tcx.hir() as &dyn hir::intravisit::Map<'_>);
319 pprust_hir::PpAnn::nested(pp_ann, state, nested);
320 self.maybe_typeck_results.set(old_maybe_typeck_results);
322 fn pre(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) {
323 if let pprust_hir::AnnNode::Expr(_) = node {
327 fn post(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) {
328 if let pprust_hir::AnnNode::Expr(expr) = node {
329 let typeck_results = self.maybe_typeck_results.get().or_else(|| {
332 .maybe_body_owned_by(expr.hir_id.owner)
333 .map(|body_id| self.tcx.typeck_body(body_id))
336 if let Some(typeck_results) = typeck_results {
340 s.s.word(typeck_results.expr_ty(expr).to_string());
348 fn get_source(input: &Input, sess: &Session) -> (String, FileName) {
349 let src_name = input.source_name();
350 let src = String::clone(
352 .get_source_file(&src_name)
353 .expect("get_source_file")
361 fn write_or_print(out: &str, ofile: Option<&Path>, sess: &Session) {
363 None => print!("{}", out),
365 if let Err(e) = std::fs::write(p, out) {
366 sess.emit_fatal(UnprettyDumpFail {
367 path: p.display().to_string(),
375 pub fn print_after_parsing(
380 ofile: Option<&Path>,
382 let (src, src_name) = get_source(input, sess);
384 let out = match ppm {
386 // Silently ignores an identified node.
387 call_with_pp_support(&s, sess, None, move |annotation| {
388 debug!("pretty printing source code {:?}", s);
389 let sess = annotation.sess();
390 let parse = &sess.parse_sess;
399 &sess.parse_sess.attr_id_generator,
403 AstTree(PpAstTreeMode::Normal) => {
404 debug!("pretty printing AST tree");
405 format!("{:#?}", krate)
410 write_or_print(&out, ofile, sess);
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 out = match ppm {
429 // Silently ignores an identified node.
430 call_with_pp_support(&s, tcx.sess, Some(tcx), move |annotation| {
431 debug!("pretty printing source code {:?}", s);
432 let sess = annotation.sess();
433 let parse = &sess.parse_sess;
442 &sess.parse_sess.attr_id_generator,
447 AstTree(PpAstTreeMode::Expanded) => {
448 debug!("pretty-printing expanded AST");
449 format!("{:#?}", krate)
452 Hir(s) => call_with_pp_support_hir(&s, tcx, move |annotation, hir_map| {
453 debug!("pretty printing HIR {:?}", s);
454 let sess = annotation.sess();
455 let sm = sess.source_map();
456 let attrs = |id| hir_map.attrs(id);
457 pprust_hir::print_crate(
459 hir_map.root_module(),
468 call_with_pp_support_hir(&PpHirMode::Normal, tcx, move |_annotation, hir_map| {
469 debug!("pretty printing HIR tree");
470 format!("{:#?}", hir_map.krate())
477 write_or_print(&out, ofile, tcx.sess);
480 // In an ideal world, this would be a public function called by the driver after
481 // analysis is performed. However, we want to call `phase_3_run_analysis_passes`
482 // with a different callback than the standard driver, so that isn't easy.
483 // Instead, we call that function ourselves.
484 fn print_with_analysis(
487 ofile: Option<&Path>,
488 ) -> Result<(), ErrorGuaranteed> {
490 let out = match ppm {
492 let mut out = Vec::new();
493 write_mir_pretty(tcx, None, &mut out).unwrap();
494 String::from_utf8(out).unwrap()
498 let mut out = Vec::new();
499 write_mir_graphviz(tcx, None, &mut out).unwrap();
500 String::from_utf8(out).unwrap()
504 let mut out = String::new();
505 abort_on_err(rustc_typeck::check_crate(tcx), tcx.sess);
506 debug!("pretty printing THIR tree");
507 for did in tcx.hir().body_owners() {
512 tcx.thir_tree(ty::WithOptConstParam::unknown(did))
521 write_or_print(&out, ofile, tcx.sess);