1 //! The various pretty-printing routines.
4 use rustc_ast_pretty::pprust;
5 use rustc_errors::ErrorReported;
7 use rustc_hir::def_id::LOCAL_CRATE;
8 use rustc_hir_pretty as pprust_hir;
9 use rustc_middle::hir::map as hir_map;
10 use rustc_middle::ty::{self, TyCtxt};
11 use rustc_mir::util::{write_mir_graphviz, write_mir_pretty};
12 use rustc_session::config::{Input, PpMode, PpSourceMode};
13 use rustc_session::Session;
14 use rustc_span::symbol::Ident;
15 use rustc_span::FileName;
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 PpmNormal | PpmEveryBodyLoops | PpmExpanded => {
48 let annotation = NoAnn { sess, tcx };
52 PpmIdentified | PpmExpandedIdentified => {
53 let annotation = IdentifiedAnnotation { sess, tcx };
56 PpmExpandedHygiene => {
57 let annotation = HygieneAnnotation { sess };
60 _ => panic!("Should use call_with_pp_support_hir"),
63 fn call_with_pp_support_hir<A, F>(ppmode: &PpSourceMode, tcx: TyCtxt<'_>, f: F) -> A
65 F: FnOnce(&dyn HirPrinterSupport<'_>, &hir::Crate<'_>) -> A,
69 let annotation = NoAnn { sess: tcx.sess, tcx: Some(tcx) };
70 f(&annotation, tcx.hir().krate())
74 let annotation = IdentifiedAnnotation { sess: tcx.sess, tcx: Some(tcx) };
75 f(&annotation, tcx.hir().krate())
78 abort_on_err(tcx.analysis(LOCAL_CRATE), tcx.sess);
80 let annotation = TypedAnnotation { tcx, maybe_typeck_results: Cell::new(None) };
81 tcx.dep_graph.with_ignore(|| f(&annotation, tcx.hir().krate()))
83 _ => panic!("Should use call_with_pp_support"),
87 trait PrinterSupport: pprust::PpAnn {
88 /// Provides a uniform interface for re-extracting a reference to a
89 /// `Session` from a value that now owns it.
90 fn sess(&self) -> &Session;
92 /// Produces the pretty-print annotation object.
94 /// (Rust does not yet support upcasting from a trait object to
95 /// an object for one of its super-traits.)
96 fn pp_ann(&self) -> &dyn pprust::PpAnn;
99 trait HirPrinterSupport<'hir>: pprust_hir::PpAnn {
100 /// Provides a uniform interface for re-extracting a reference to a
101 /// `Session` from a value that now owns it.
102 fn sess(&self) -> &Session;
104 /// Provides a uniform interface for re-extracting a reference to an
105 /// `hir_map::Map` from a value that now owns it.
106 fn hir_map(&self) -> Option<hir_map::Map<'hir>>;
108 /// Produces the pretty-print annotation object.
110 /// (Rust does not yet support upcasting from a trait object to
111 /// an object for one of its super-traits.)
112 fn pp_ann(&self) -> &dyn pprust_hir::PpAnn;
114 /// Computes an user-readable representation of a path, if possible.
115 fn node_path(&self, id: hir::HirId) -> Option<String> {
116 self.hir_map().and_then(|map| map.def_path_from_hir_id(id)).map(|path| {
117 path.data.into_iter().map(|elem| elem.data.to_string()).collect::<Vec<_>>().join("::")
124 tcx: Option<TyCtxt<'hir>>,
127 impl<'hir> PrinterSupport for NoAnn<'hir> {
128 fn sess(&self) -> &Session {
132 fn pp_ann(&self) -> &dyn pprust::PpAnn {
137 impl<'hir> HirPrinterSupport<'hir> for NoAnn<'hir> {
138 fn sess(&self) -> &Session {
142 fn hir_map(&self) -> Option<hir_map::Map<'hir>> {
143 self.tcx.map(|tcx| tcx.hir())
146 fn pp_ann(&self) -> &dyn pprust_hir::PpAnn {
151 impl<'hir> pprust::PpAnn for NoAnn<'hir> {}
152 impl<'hir> pprust_hir::PpAnn for NoAnn<'hir> {
153 fn nested(&self, state: &mut pprust_hir::State<'_>, nested: pprust_hir::Nested) {
154 if let Some(tcx) = self.tcx {
155 pprust_hir::PpAnn::nested(&(&tcx.hir() as &dyn hir::intravisit::Map<'_>), state, nested)
160 struct IdentifiedAnnotation<'hir> {
162 tcx: Option<TyCtxt<'hir>>,
165 impl<'hir> PrinterSupport for IdentifiedAnnotation<'hir> {
166 fn sess(&self) -> &Session {
170 fn pp_ann(&self) -> &dyn pprust::PpAnn {
175 impl<'hir> pprust::PpAnn for IdentifiedAnnotation<'hir> {
176 fn pre(&self, s: &mut pprust::State<'_>, node: pprust::AnnNode<'_>) {
177 if let pprust::AnnNode::Expr(_) = node {
181 fn post(&self, s: &mut pprust::State<'_>, node: pprust::AnnNode<'_>) {
183 pprust::AnnNode::Crate(_) | pprust::AnnNode::Ident(_) | pprust::AnnNode::Name(_) => {}
185 pprust::AnnNode::Item(item) => {
187 s.synth_comment(item.id.to_string())
189 pprust::AnnNode::SubItem(id) => {
191 s.synth_comment(id.to_string())
193 pprust::AnnNode::Block(blk) => {
195 s.synth_comment(format!("block {}", blk.id))
197 pprust::AnnNode::Expr(expr) => {
199 s.synth_comment(expr.id.to_string());
202 pprust::AnnNode::Pat(pat) => {
204 s.synth_comment(format!("pat {}", pat.id));
210 impl<'hir> HirPrinterSupport<'hir> for IdentifiedAnnotation<'hir> {
211 fn sess(&self) -> &Session {
215 fn hir_map(&self) -> Option<hir_map::Map<'hir>> {
216 self.tcx.map(|tcx| tcx.hir())
219 fn pp_ann(&self) -> &dyn pprust_hir::PpAnn {
224 impl<'hir> pprust_hir::PpAnn for IdentifiedAnnotation<'hir> {
225 fn nested(&self, state: &mut pprust_hir::State<'_>, nested: pprust_hir::Nested) {
226 if let Some(ref tcx) = self.tcx {
227 pprust_hir::PpAnn::nested(&(&tcx.hir() as &dyn hir::intravisit::Map<'_>), state, nested)
230 fn pre(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) {
231 if let pprust_hir::AnnNode::Expr(_) = node {
235 fn post(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) {
237 pprust_hir::AnnNode::Name(_) => {}
238 pprust_hir::AnnNode::Item(item) => {
240 s.synth_comment(format!("hir_id: {}", item.hir_id));
242 pprust_hir::AnnNode::SubItem(id) => {
244 s.synth_comment(id.to_string());
246 pprust_hir::AnnNode::Block(blk) => {
248 s.synth_comment(format!("block hir_id: {}", blk.hir_id));
250 pprust_hir::AnnNode::Expr(expr) => {
252 s.synth_comment(format!("expr hir_id: {}", expr.hir_id));
255 pprust_hir::AnnNode::Pat(pat) => {
257 s.synth_comment(format!("pat hir_id: {}", pat.hir_id));
259 pprust_hir::AnnNode::Arm(arm) => {
261 s.synth_comment(format!("arm hir_id: {}", arm.hir_id));
267 struct HygieneAnnotation<'a> {
271 impl<'a> PrinterSupport for HygieneAnnotation<'a> {
272 fn sess(&self) -> &Session {
276 fn pp_ann(&self) -> &dyn pprust::PpAnn {
281 impl<'a> pprust::PpAnn for HygieneAnnotation<'a> {
282 fn post(&self, s: &mut pprust::State<'_>, node: pprust::AnnNode<'_>) {
284 pprust::AnnNode::Ident(&Ident { name, span }) => {
286 s.synth_comment(format!("{}{:?}", name.as_u32(), span.ctxt()))
288 pprust::AnnNode::Name(&name) => {
290 s.synth_comment(name.as_u32().to_string())
292 pprust::AnnNode::Crate(_) => {
294 let verbose = self.sess.verbose();
295 s.synth_comment(rustc_span::hygiene::debug_hygiene_data(verbose));
296 s.s.hardbreak_if_not_bol();
303 struct TypedAnnotation<'tcx> {
305 maybe_typeck_results: Cell<Option<&'tcx ty::TypeckResults<'tcx>>>,
308 impl<'tcx> TypedAnnotation<'tcx> {
309 /// Gets the type-checking results for the current body.
310 /// As this will ICE if called outside bodies, only call when working with
311 /// `Expr` or `Pat` nodes (they are guaranteed to be found only in bodies).
313 fn typeck_results(&self) -> &'tcx ty::TypeckResults<'tcx> {
314 self.maybe_typeck_results
316 .expect("`TypedAnnotation::typeck_results` called outside of body")
320 impl<'tcx> HirPrinterSupport<'tcx> for TypedAnnotation<'tcx> {
321 fn sess(&self) -> &Session {
325 fn hir_map(&self) -> Option<hir_map::Map<'tcx>> {
329 fn pp_ann(&self) -> &dyn pprust_hir::PpAnn {
333 fn node_path(&self, id: hir::HirId) -> Option<String> {
334 Some(self.tcx.def_path_str(self.tcx.hir().local_def_id(id).to_def_id()))
338 impl<'tcx> pprust_hir::PpAnn for TypedAnnotation<'tcx> {
339 fn nested(&self, state: &mut pprust_hir::State<'_>, nested: pprust_hir::Nested) {
340 let old_maybe_typeck_results = self.maybe_typeck_results.get();
341 if let pprust_hir::Nested::Body(id) = nested {
342 self.maybe_typeck_results.set(Some(self.tcx.typeck_body(id)));
344 let pp_ann = &(&self.tcx.hir() as &dyn hir::intravisit::Map<'_>);
345 pprust_hir::PpAnn::nested(pp_ann, state, nested);
346 self.maybe_typeck_results.set(old_maybe_typeck_results);
348 fn pre(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) {
349 if let pprust_hir::AnnNode::Expr(_) = node {
353 fn post(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) {
354 if let pprust_hir::AnnNode::Expr(expr) = node {
358 s.s.word(self.typeck_results().expr_ty(expr).to_string());
364 fn get_source(input: &Input, sess: &Session) -> (String, FileName) {
365 let src_name = input.source_name();
367 String::clone(&sess.source_map().get_source_file(&src_name).unwrap().src.as_ref().unwrap());
371 fn write_output(out: Vec<u8>, ofile: Option<&Path>) {
373 None => print!("{}", String::from_utf8(out).unwrap()),
374 Some(p) => match File::create(p) {
375 Ok(mut w) => w.write_all(&out).unwrap(),
376 Err(e) => panic!("print-print failed to open {} due to {}", p.display(), e),
381 pub fn print_after_parsing(
386 ofile: Option<&Path>,
388 let (src, src_name) = get_source(input, sess);
390 let mut out = String::new();
392 if let PpmSource(s) = ppm {
393 // Silently ignores an identified node.
395 call_with_pp_support(&s, sess, None, move |annotation| {
396 debug!("pretty printing source code {:?}", s);
397 let sess = annotation.sess();
398 let parse = &sess.parse_sess;
399 *out = pprust::print_crate(
407 parse.injected_crate_name.get().is_some(),
414 write_output(out.into_bytes(), ofile);
417 pub fn print_after_hir_lowering<'tcx>(
422 ofile: Option<&Path>,
424 if ppm.needs_analysis() {
425 abort_on_err(print_with_analysis(tcx, ppm, ofile), tcx.sess);
429 let (src, src_name) = get_source(input, tcx.sess);
431 let mut out = String::new();
435 // Silently ignores an identified node.
437 call_with_pp_support(&s, tcx.sess, Some(tcx), move |annotation| {
438 debug!("pretty printing source code {:?}", s);
439 let sess = annotation.sess();
440 let parse = &sess.parse_sess;
441 *out = pprust::print_crate(
449 parse.injected_crate_name.get().is_some(),
456 call_with_pp_support_hir(&s, tcx, move |annotation, krate| {
457 debug!("pretty printing source code {:?}", s);
458 let sess = annotation.sess();
459 let sm = sess.source_map();
460 *out = pprust_hir::print_crate(sm, krate, src_name, src, annotation.pp_ann())
466 call_with_pp_support_hir(&s, tcx, move |_annotation, krate| {
467 debug!("pretty printing source code {:?}", s);
468 *out = format!("{:#?}", krate);
475 write_output(out.into_bytes(), ofile);
478 // In an ideal world, this would be a public function called by the driver after
479 // analysis is performed. However, we want to call `phase_3_run_analysis_passes`
480 // with a different callback than the standard driver, so that isn't easy.
481 // Instead, we call that function ourselves.
482 fn print_with_analysis(
485 ofile: Option<&Path>,
486 ) -> Result<(), ErrorReported> {
487 let mut out = Vec::new();
489 tcx.analysis(LOCAL_CRATE)?;
492 PpmMir | PpmMirCFG => match ppm {
493 PpmMir => write_mir_pretty(tcx, None, &mut out),
494 PpmMirCFG => write_mir_graphviz(tcx, None, &mut out),
501 write_output(out, ofile);