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, UserIdentifiedItem, 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::UserIdentifiedItem::*;
23 pub use self::PpSourceMode::*;
24 pub use self::PpMode::*;
25 use crate::abort_on_err;
27 use crate::source_name;
31 // This slightly awkward construction is to allow for each PpMode to
32 // choose whether it needs to do analyses (which can consume the
33 // Session) and then pass through the session (now attached to the
34 // analysis results) on to the chosen pretty-printer, along with the
37 // Note that since the `&PrinterSupport` is freshly constructed on each
38 // call, it would not make sense to try to attach the lifetime of `self`
39 // to the lifetime of the `&PrinterObject`.
41 // (The `use_once_payload` is working around the current lack of once
42 // functions in the compiler.)
44 /// Constructs a `PrinterSupport` object and passes it to `f`.
45 fn call_with_pp_support<'tcx, A, F>(
46 ppmode: &PpSourceMode,
48 tcx: Option<TyCtxt<'tcx>>,
52 F: FnOnce(&dyn PrinterSupport) -> A,
55 PpmNormal | PpmEveryBodyLoops | PpmExpanded => {
56 let annotation = NoAnn {
63 PpmIdentified | PpmExpandedIdentified => {
64 let annotation = IdentifiedAnnotation {
70 PpmExpandedHygiene => {
71 let annotation = HygieneAnnotation {
76 _ => panic!("Should use call_with_pp_support_hir"),
79 fn call_with_pp_support_hir<A, F>(ppmode: &PpSourceMode, tcx: TyCtxt<'_>, f: F) -> A
81 F: FnOnce(&dyn HirPrinterSupport<'_>, &hir::Crate) -> A,
85 let annotation = NoAnn {
89 f(&annotation, tcx.hir().forest.krate())
93 let annotation = IdentifiedAnnotation {
97 f(&annotation, tcx.hir().forest.krate())
100 abort_on_err(tcx.analysis(LOCAL_CRATE), tcx.sess);
102 let empty_tables = ty::TypeckTables::empty(None);
103 let annotation = TypedAnnotation {
105 tables: Cell::new(&empty_tables)
107 tcx.dep_graph.with_ignore(|| {
108 f(&annotation, tcx.hir().forest.krate())
111 _ => panic!("Should use call_with_pp_support"),
115 trait PrinterSupport: pprust::PpAnn {
116 /// Provides a uniform interface for re-extracting a reference to a
117 /// `Session` from a value that now owns it.
118 fn sess(&self) -> &Session;
120 /// Produces the pretty-print annotation object.
122 /// (Rust does not yet support upcasting from a trait object to
123 /// an object for one of its super-traits.)
124 fn pp_ann<'a>(&'a self) -> &'a dyn pprust::PpAnn;
127 trait HirPrinterSupport<'hir>: pprust_hir::PpAnn {
128 /// Provides a uniform interface for re-extracting a reference to a
129 /// `Session` from a value that now owns it.
130 fn sess(&self) -> &Session;
132 /// Provides a uniform interface for re-extracting a reference to an
133 /// `hir_map::Map` from a value that now owns it.
134 fn hir_map<'a>(&'a self) -> Option<&'a hir_map::Map<'hir>>;
136 /// Produces the pretty-print annotation object.
138 /// (Rust does not yet support upcasting from a trait object to
139 /// an object for one of its super-traits.)
140 fn pp_ann<'a>(&'a self) -> &'a dyn pprust_hir::PpAnn;
142 /// Computes an user-readable representation of a path, if possible.
143 fn node_path(&self, id: hir::HirId) -> Option<String> {
144 self.hir_map().and_then(|map| {
145 map.def_path_from_hir_id(id)
149 .map(|elem| elem.data.to_string())
158 tcx: Option<TyCtxt<'hir>>,
161 impl<'hir> PrinterSupport for NoAnn<'hir> {
162 fn sess(&self) -> &Session {
166 fn pp_ann<'a>(&'a self) -> &'a dyn pprust::PpAnn {
171 impl<'hir> HirPrinterSupport<'hir> for NoAnn<'hir> {
172 fn sess(&self) -> &Session {
176 fn hir_map<'a>(&'a self) -> Option<&'a hir_map::Map<'hir>> {
177 self.tcx.map(|tcx| tcx.hir())
180 fn pp_ann<'a>(&'a self) -> &'a dyn pprust_hir::PpAnn {
185 impl<'hir> pprust::PpAnn for NoAnn<'hir> {}
186 impl<'hir> pprust_hir::PpAnn for NoAnn<'hir> {
187 fn nested(&self, state: &mut pprust_hir::State<'_>, nested: pprust_hir::Nested) {
188 if let Some(tcx) = self.tcx {
189 pprust_hir::PpAnn::nested(tcx.hir(), state, nested)
194 struct IdentifiedAnnotation<'hir> {
196 tcx: Option<TyCtxt<'hir>>,
199 impl<'hir> PrinterSupport for IdentifiedAnnotation<'hir> {
200 fn sess(&self) -> &Session {
204 fn pp_ann<'a>(&'a self) -> &'a dyn pprust::PpAnn {
209 impl<'hir> pprust::PpAnn for IdentifiedAnnotation<'hir> {
210 fn pre(&self, s: &mut pprust::State<'_>, node: pprust::AnnNode<'_>) {
212 pprust::AnnNode::Expr(_) => s.popen(),
216 fn post(&self, s: &mut pprust::State<'_>, node: pprust::AnnNode<'_>) {
218 pprust::AnnNode::Crate(_) |
219 pprust::AnnNode::Ident(_) |
220 pprust::AnnNode::Name(_) => {},
222 pprust::AnnNode::Item(item) => {
224 s.synth_comment(item.id.to_string())
226 pprust::AnnNode::SubItem(id) => {
228 s.synth_comment(id.to_string())
230 pprust::AnnNode::Block(blk) => {
232 s.synth_comment(format!("block {}", blk.id))
234 pprust::AnnNode::Expr(expr) => {
236 s.synth_comment(expr.id.to_string());
239 pprust::AnnNode::Pat(pat) => {
241 s.synth_comment(format!("pat {}", pat.id));
247 impl<'hir> HirPrinterSupport<'hir> for IdentifiedAnnotation<'hir> {
248 fn sess(&self) -> &Session {
252 fn hir_map<'a>(&'a self) -> Option<&'a hir_map::Map<'hir>> {
253 self.tcx.map(|tcx| tcx.hir())
256 fn pp_ann<'a>(&'a self) -> &'a dyn pprust_hir::PpAnn {
261 impl<'hir> pprust_hir::PpAnn for IdentifiedAnnotation<'hir> {
262 fn nested(&self, state: &mut pprust_hir::State<'_>, nested: pprust_hir::Nested) {
263 if let Some(ref tcx) = self.tcx {
264 pprust_hir::PpAnn::nested(tcx.hir(), state, nested)
267 fn pre(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) {
269 pprust_hir::AnnNode::Expr(_) => s.popen(),
273 fn post(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) {
275 pprust_hir::AnnNode::Name(_) => {},
276 pprust_hir::AnnNode::Item(item) => {
278 s.synth_comment(format!("hir_id: {}", item.hir_id));
280 pprust_hir::AnnNode::SubItem(id) => {
282 s.synth_comment(id.to_string());
284 pprust_hir::AnnNode::Block(blk) => {
286 s.synth_comment(format!("block hir_id: {}", blk.hir_id));
288 pprust_hir::AnnNode::Expr(expr) => {
290 s.synth_comment(format!("expr hir_id: {}", expr.hir_id));
293 pprust_hir::AnnNode::Pat(pat) => {
295 s.synth_comment(format!("pat hir_id: {}", pat.hir_id));
297 pprust_hir::AnnNode::Arm(arm) => {
299 s.synth_comment(format!("arm hir_id: {}", arm.hir_id));
305 struct HygieneAnnotation<'a> {
309 impl<'a> PrinterSupport for HygieneAnnotation<'a> {
310 fn sess(&self) -> &Session {
314 fn pp_ann(&self) -> &dyn pprust::PpAnn {
319 impl<'a> pprust::PpAnn for HygieneAnnotation<'a> {
320 fn post(&self, s: &mut pprust::State<'_>, node: pprust::AnnNode<'_>) {
322 pprust::AnnNode::Ident(&ast::Ident { name, span }) => {
324 s.synth_comment(format!("{}{:?}", name.as_u32(), span.ctxt()))
326 pprust::AnnNode::Name(&name) => {
328 s.synth_comment(name.as_u32().to_string())
330 pprust::AnnNode::Crate(_) => {
332 let verbose = self.sess.verbose();
333 s.synth_comment(syntax_pos::hygiene::debug_hygiene_data(verbose));
334 s.s.hardbreak_if_not_bol();
341 struct TypedAnnotation<'a, 'tcx> {
343 tables: Cell<&'a ty::TypeckTables<'tcx>>,
346 impl<'b, 'tcx> HirPrinterSupport<'tcx> for TypedAnnotation<'b, 'tcx> {
347 fn sess(&self) -> &Session {
351 fn hir_map<'a>(&'a self) -> Option<&'a hir_map::Map<'tcx>> {
352 Some(&self.tcx.hir())
355 fn pp_ann<'a>(&'a self) -> &'a dyn pprust_hir::PpAnn {
359 fn node_path(&self, id: hir::HirId) -> Option<String> {
360 Some(self.tcx.def_path_str(self.tcx.hir().local_def_id(id)))
364 impl<'a, 'tcx> pprust_hir::PpAnn for TypedAnnotation<'a, 'tcx> {
365 fn nested(&self, state: &mut pprust_hir::State<'_>, nested: pprust_hir::Nested) {
366 let old_tables = self.tables.get();
367 if let pprust_hir::Nested::Body(id) = nested {
368 self.tables.set(self.tcx.body_tables(id));
370 pprust_hir::PpAnn::nested(self.tcx.hir(), state, nested);
371 self.tables.set(old_tables);
373 fn pre(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) {
375 pprust_hir::AnnNode::Expr(_) => s.popen(),
379 fn post(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) {
381 pprust_hir::AnnNode::Expr(expr) => {
385 s.s.word(self.tables.get().expr_ty(expr).to_string());
393 fn get_source(input: &Input, sess: &Session) -> (String, FileName) {
394 let src_name = source_name(input);
395 let src = String::clone(&sess.source_map()
396 .get_source_file(&src_name)
404 fn write_output(out: Vec<u8>, ofile: Option<&Path>) {
406 None => print!("{}", String::from_utf8(out).unwrap()),
408 match File::create(p) {
409 Ok(mut w) => w.write_all(&out).unwrap(),
410 Err(e) => panic!("print-print failed to open {} due to {}", p.display(), e),
416 pub fn print_after_parsing(sess: &Session,
420 ofile: Option<&Path>) {
421 let (src, src_name) = get_source(input, sess);
423 let mut out = String::new();
425 if let PpmSource(s) = ppm {
426 // Silently ignores an identified node.
428 call_with_pp_support(&s, sess, None, move |annotation| {
429 debug!("pretty printing source code {:?}", s);
430 let sess = annotation.sess();
431 *out = pprust::print_crate(sess.source_map(),
443 write_output(out.into_bytes(), ofile);
446 pub fn print_after_hir_lowering<'tcx>(
451 opt_uii: Option<UserIdentifiedItem>,
452 ofile: Option<&Path>,
454 if ppm.needs_analysis() {
455 abort_on_err(print_with_analysis(
464 let (src, src_name) = get_source(input, tcx.sess);
466 let mut out = String::new();
468 match (ppm, opt_uii) {
469 (PpmSource(s), _) => {
470 // Silently ignores an identified node.
472 let src = src.clone();
473 call_with_pp_support(&s, tcx.sess, Some(tcx), move |annotation| {
474 debug!("pretty printing source code {:?}", s);
475 let sess = annotation.sess();
476 *out = pprust::print_crate(sess.source_map(),
486 (PpmHir(s), None) => {
488 let src = src.clone();
489 call_with_pp_support_hir(&s, tcx, move |annotation, krate| {
490 debug!("pretty printing source code {:?}", s);
491 let sess = annotation.sess();
492 *out = pprust_hir::print_crate(sess.source_map(),
501 (PpmHirTree(s), None) => {
503 call_with_pp_support_hir(&s, tcx, move |_annotation, krate| {
504 debug!("pretty printing source code {:?}", s);
505 *out = format!("{:#?}", krate);
509 (PpmHir(s), Some(uii)) => {
511 let src = src.clone();
512 call_with_pp_support_hir(&s, tcx, move |annotation, _| {
513 debug!("pretty printing source code {:?}", s);
514 let sess = annotation.sess();
515 let hir_map = annotation.hir_map().expect("-Z unpretty missing HIR map");
516 let mut pp_state = pprust_hir::State::new_from_input(sess.source_map(),
520 annotation.pp_ann());
521 for node_id in uii.all_matching_node_ids(hir_map) {
522 let hir_id = tcx.hir().node_to_hir_id(node_id);
523 let node = hir_map.get(hir_id);
524 pp_state.print_node(node);
526 let path = annotation.node_path(hir_id)
527 .expect("-Z unpretty missing node paths");
528 pp_state.synth_comment(path);
529 pp_state.s.hardbreak();
531 *out = pp_state.s.eof();
535 (PpmHirTree(s), Some(uii)) => {
537 call_with_pp_support_hir(&s, tcx, move |_annotation, _krate| {
538 debug!("pretty printing source code {:?}", s);
539 for node_id in uii.all_matching_node_ids(tcx.hir()) {
540 let hir_id = tcx.hir().node_to_hir_id(node_id);
541 let node = tcx.hir().get(hir_id);
542 out.push_str(&format!("{:#?}", node));
550 write_output(out.into_bytes(), ofile);
553 // In an ideal world, this would be a public function called by the driver after
554 // analysis is performed. However, we want to call `phase_3_run_analysis_passes`
555 // with a different callback than the standard driver, so that isn't easy.
556 // Instead, we call that function ourselves.
557 fn print_with_analysis(
560 uii: Option<UserIdentifiedItem>,
561 ofile: Option<&Path>,
562 ) -> Result<(), ErrorReported> {
563 let nodeid = if let Some(uii) = uii {
564 debug!("pretty printing for {:?}", uii);
565 Some(uii.to_one_node_id("-Z unpretty", tcx.sess, tcx.hir()))
567 debug!("pretty printing for whole crate");
571 let mut out = Vec::new();
573 tcx.analysis(LOCAL_CRATE)?;
576 PpmMir | PpmMirCFG => {
577 let def_id = nodeid.map(|nid| tcx.hir().local_def_id_from_node_id(nid));
579 PpmMir => write_mir_pretty(tcx, def_id, &mut out),
580 PpmMirCFG => write_mir_graphviz(tcx, def_id, &mut out),
587 write_output(out, ofile);