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_interface::interface::CompilerIO;
10 use rustc_middle::hir::map as hir_map;
11 use rustc_middle::mir::{write_mir_graphviz, write_mir_pretty};
12 use rustc_middle::ty::{self, TyCtxt};
13 use rustc_session::config::{Input, PpAstTreeMode, PpHirMode, PpMode, PpSourceMode};
14 use rustc_session::Session;
15 use rustc_span::symbol::Ident;
16 use rustc_span::FileName;
20 use std::path::PathBuf;
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 /// Constructs a `PrinterSupport` object and passes it to `f`.
37 fn call_with_pp_support<'tcx, A, F>(
38 ppmode: &PpSourceMode,
40 tcx: Option<TyCtxt<'tcx>>,
44 F: FnOnce(&dyn PrinterSupport) -> A,
47 Normal | Expanded => {
48 let annotation = NoAnn { sess, tcx };
52 Identified | ExpandedIdentified => {
53 let annotation = IdentifiedAnnotation { sess, tcx };
57 let annotation = HygieneAnnotation { sess };
62 fn call_with_pp_support_hir<A, F>(ppmode: &PpHirMode, tcx: TyCtxt<'_>, f: F) -> A
64 F: FnOnce(&dyn HirPrinterSupport<'_>, hir_map::Map<'_>) -> A,
67 PpHirMode::Normal => {
68 let annotation = NoAnn { sess: tcx.sess, tcx: Some(tcx) };
69 f(&annotation, tcx.hir())
72 PpHirMode::Identified => {
73 let annotation = IdentifiedAnnotation { sess: tcx.sess, tcx: Some(tcx) };
74 f(&annotation, tcx.hir())
77 abort_on_err(tcx.analysis(()), tcx.sess);
79 let annotation = TypedAnnotation { tcx, maybe_typeck_results: Cell::new(None) };
80 tcx.dep_graph.with_ignore(|| f(&annotation, tcx.hir()))
85 trait PrinterSupport: pprust::PpAnn {
86 /// Provides a uniform interface for re-extracting a reference to a
87 /// `Session` from a value that now owns it.
88 fn sess(&self) -> &Session;
90 /// Produces the pretty-print annotation object.
92 /// (Rust does not yet support upcasting from a trait object to
93 /// an object for one of its supertraits.)
94 fn pp_ann(&self) -> &dyn pprust::PpAnn;
97 trait HirPrinterSupport<'hir>: pprust_hir::PpAnn {
98 /// Provides a uniform interface for re-extracting a reference to a
99 /// `Session` from a value that now owns it.
100 fn sess(&self) -> &Session;
102 /// Provides a uniform interface for re-extracting a reference to an
103 /// `hir_map::Map` from a value that now owns it.
104 fn hir_map(&self) -> Option<hir_map::Map<'hir>>;
106 /// Produces the pretty-print annotation object.
108 /// (Rust does not yet support upcasting from a trait object to
109 /// an object for one of its supertraits.)
110 fn pp_ann(&self) -> &dyn pprust_hir::PpAnn;
115 tcx: Option<TyCtxt<'hir>>,
118 impl<'hir> PrinterSupport for NoAnn<'hir> {
119 fn sess(&self) -> &Session {
123 fn pp_ann(&self) -> &dyn pprust::PpAnn {
128 impl<'hir> HirPrinterSupport<'hir> for NoAnn<'hir> {
129 fn sess(&self) -> &Session {
133 fn hir_map(&self) -> Option<hir_map::Map<'hir>> {
134 self.tcx.map(|tcx| tcx.hir())
137 fn pp_ann(&self) -> &dyn pprust_hir::PpAnn {
142 impl<'hir> pprust::PpAnn for NoAnn<'hir> {}
143 impl<'hir> pprust_hir::PpAnn for NoAnn<'hir> {
144 fn nested(&self, state: &mut pprust_hir::State<'_>, nested: pprust_hir::Nested) {
145 if let Some(tcx) = self.tcx {
146 pprust_hir::PpAnn::nested(&(&tcx.hir() as &dyn hir::intravisit::Map<'_>), state, nested)
151 struct IdentifiedAnnotation<'hir> {
153 tcx: Option<TyCtxt<'hir>>,
156 impl<'hir> PrinterSupport for IdentifiedAnnotation<'hir> {
157 fn sess(&self) -> &Session {
161 fn pp_ann(&self) -> &dyn pprust::PpAnn {
166 impl<'hir> pprust::PpAnn for IdentifiedAnnotation<'hir> {
167 fn pre(&self, s: &mut pprust::State<'_>, node: pprust::AnnNode<'_>) {
168 if let pprust::AnnNode::Expr(_) = node {
172 fn post(&self, s: &mut pprust::State<'_>, node: pprust::AnnNode<'_>) {
174 pprust::AnnNode::Crate(_) | pprust::AnnNode::Ident(_) | pprust::AnnNode::Name(_) => {}
176 pprust::AnnNode::Item(item) => {
178 s.synth_comment(item.id.to_string())
180 pprust::AnnNode::SubItem(id) => {
182 s.synth_comment(id.to_string())
184 pprust::AnnNode::Block(blk) => {
186 s.synth_comment(format!("block {}", blk.id))
188 pprust::AnnNode::Expr(expr) => {
190 s.synth_comment(expr.id.to_string());
193 pprust::AnnNode::Pat(pat) => {
195 s.synth_comment(format!("pat {}", pat.id));
201 impl<'hir> HirPrinterSupport<'hir> for IdentifiedAnnotation<'hir> {
202 fn sess(&self) -> &Session {
206 fn hir_map(&self) -> Option<hir_map::Map<'hir>> {
207 self.tcx.map(|tcx| tcx.hir())
210 fn pp_ann(&self) -> &dyn pprust_hir::PpAnn {
215 impl<'hir> pprust_hir::PpAnn for IdentifiedAnnotation<'hir> {
216 fn nested(&self, state: &mut pprust_hir::State<'_>, nested: pprust_hir::Nested) {
217 if let Some(ref tcx) = self.tcx {
218 pprust_hir::PpAnn::nested(&(&tcx.hir() as &dyn hir::intravisit::Map<'_>), state, nested)
221 fn pre(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) {
222 if let pprust_hir::AnnNode::Expr(_) = node {
226 fn post(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) {
228 pprust_hir::AnnNode::Name(_) => {}
229 pprust_hir::AnnNode::Item(item) => {
231 s.synth_comment(format!("hir_id: {}", item.hir_id()));
233 pprust_hir::AnnNode::SubItem(id) => {
235 s.synth_comment(id.to_string());
237 pprust_hir::AnnNode::Block(blk) => {
239 s.synth_comment(format!("block hir_id: {}", blk.hir_id));
241 pprust_hir::AnnNode::Expr(expr) => {
243 s.synth_comment(format!("expr hir_id: {}", expr.hir_id));
246 pprust_hir::AnnNode::Pat(pat) => {
248 s.synth_comment(format!("pat hir_id: {}", pat.hir_id));
250 pprust_hir::AnnNode::Arm(arm) => {
252 s.synth_comment(format!("arm hir_id: {}", arm.hir_id));
258 struct HygieneAnnotation<'a> {
262 impl<'a> PrinterSupport for HygieneAnnotation<'a> {
263 fn sess(&self) -> &Session {
267 fn pp_ann(&self) -> &dyn pprust::PpAnn {
272 impl<'a> pprust::PpAnn for HygieneAnnotation<'a> {
273 fn post(&self, s: &mut pprust::State<'_>, node: pprust::AnnNode<'_>) {
275 pprust::AnnNode::Ident(&Ident { name, span }) => {
277 s.synth_comment(format!("{}{:?}", name.as_u32(), span.ctxt()))
279 pprust::AnnNode::Name(&name) => {
281 s.synth_comment(name.as_u32().to_string())
283 pprust::AnnNode::Crate(_) => {
285 let verbose = self.sess.verbose();
286 s.synth_comment(rustc_span::hygiene::debug_hygiene_data(verbose));
287 s.s.hardbreak_if_not_bol();
294 struct TypedAnnotation<'tcx> {
296 maybe_typeck_results: Cell<Option<&'tcx ty::TypeckResults<'tcx>>>,
299 impl<'tcx> HirPrinterSupport<'tcx> for TypedAnnotation<'tcx> {
300 fn sess(&self) -> &Session {
304 fn hir_map(&self) -> Option<hir_map::Map<'tcx>> {
308 fn pp_ann(&self) -> &dyn pprust_hir::PpAnn {
313 impl<'tcx> pprust_hir::PpAnn for TypedAnnotation<'tcx> {
314 fn nested(&self, state: &mut pprust_hir::State<'_>, nested: pprust_hir::Nested) {
315 let old_maybe_typeck_results = self.maybe_typeck_results.get();
316 if let pprust_hir::Nested::Body(id) = nested {
317 self.maybe_typeck_results.set(Some(self.tcx.typeck_body(id)));
319 let pp_ann = &(&self.tcx.hir() as &dyn hir::intravisit::Map<'_>);
320 pprust_hir::PpAnn::nested(pp_ann, state, nested);
321 self.maybe_typeck_results.set(old_maybe_typeck_results);
323 fn pre(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) {
324 if let pprust_hir::AnnNode::Expr(_) = node {
328 fn post(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) {
329 if let pprust_hir::AnnNode::Expr(expr) = node {
330 let typeck_results = self.maybe_typeck_results.get().or_else(|| {
333 .maybe_body_owned_by(expr.hir_id.owner.def_id)
334 .map(|body_id| self.tcx.typeck_body(body_id))
337 if let Some(typeck_results) = typeck_results {
341 s.s.word(typeck_results.expr_ty(expr).to_string());
349 fn get_source(input: &Input, sess: &Session) -> (String, FileName) {
350 let src_name = input.source_name();
351 let src = String::clone(
353 .get_source_file(&src_name)
354 .expect("get_source_file")
362 fn write_or_print(out: &str, ofile: &Option<PathBuf>, sess: &Session) {
364 None => print!("{out}"),
366 if let Err(e) = std::fs::write(p, out) {
367 sess.emit_fatal(UnprettyDumpFail {
368 path: p.display().to_string(),
376 pub fn print_after_parsing(sess: &Session, io: &CompilerIO, krate: &ast::Crate, ppm: PpMode) {
377 let (src, src_name) = get_source(&io.input, sess);
379 let out = match ppm {
381 // Silently ignores an identified node.
382 call_with_pp_support(&s, sess, None, move |annotation| {
383 debug!("pretty printing source code {:?}", s);
384 let sess = annotation.sess();
385 let parse = &sess.parse_sess;
394 &sess.parse_sess.attr_id_generator,
398 AstTree(PpAstTreeMode::Normal) => {
399 debug!("pretty printing AST tree");
400 format!("{krate:#?}")
405 write_or_print(&out, &io.output_file, sess);
408 pub fn print_after_hir_lowering<'tcx>(
414 if ppm.needs_analysis() {
415 abort_on_err(print_with_analysis(tcx, ppm, &io.output_file), tcx.sess);
419 let (src, src_name) = get_source(&io.input, tcx.sess);
421 let out = match ppm {
423 // Silently ignores an identified node.
424 call_with_pp_support(&s, tcx.sess, Some(tcx), move |annotation| {
425 debug!("pretty printing source code {:?}", s);
426 let sess = annotation.sess();
427 let parse = &sess.parse_sess;
436 &sess.parse_sess.attr_id_generator,
441 AstTree(PpAstTreeMode::Expanded) => {
442 debug!("pretty-printing expanded AST");
443 format!("{krate:#?}")
446 Hir(s) => call_with_pp_support_hir(&s, tcx, move |annotation, hir_map| {
447 debug!("pretty printing HIR {:?}", s);
448 let sess = annotation.sess();
449 let sm = sess.source_map();
450 let attrs = |id| hir_map.attrs(id);
451 pprust_hir::print_crate(
453 hir_map.root_module(),
462 call_with_pp_support_hir(&PpHirMode::Normal, tcx, move |_annotation, hir_map| {
463 debug!("pretty printing HIR tree");
464 format!("{:#?}", hir_map.krate())
471 write_or_print(&out, &io.output_file, tcx.sess);
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<PathBuf>,
482 ) -> Result<(), ErrorGuaranteed> {
484 let out = match ppm {
486 let mut out = Vec::new();
487 write_mir_pretty(tcx, None, &mut out).unwrap();
488 String::from_utf8(out).unwrap()
492 let mut out = Vec::new();
493 write_mir_graphviz(tcx, None, &mut out).unwrap();
494 String::from_utf8(out).unwrap()
498 let mut out = String::new();
499 abort_on_err(rustc_hir_analysis::check_crate(tcx), tcx.sess);
500 debug!("pretty printing THIR tree");
501 for did in tcx.hir().body_owners() {
506 tcx.thir_tree(ty::WithOptConstParam::unknown(did))
515 write_or_print(&out, ofile, tcx.sess);