]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_driver/src/pretty.rs
Clean up outdated `use_once_payload` pretty printer comment
[rust.git] / compiler / rustc_driver / src / pretty.rs
1 //! The various pretty-printing routines.
2
3 use rustc_ast as ast;
4 use rustc_ast_pretty::pprust;
5 use rustc_errors::ErrorReported;
6 use rustc_hir as hir;
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;
16
17 use std::cell::Cell;
18 use std::fs::File;
19 use std::io::Write;
20 use std::path::Path;
21
22 pub use self::PpMode::*;
23 pub use self::PpSourceMode::*;
24 use crate::abort_on_err;
25
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
30 // `&PpAnn` object.
31 //
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`.
35
36 /// Constructs a `PrinterSupport` object and passes it to `f`.
37 fn call_with_pp_support<'tcx, A, F>(
38     ppmode: &PpSourceMode,
39     sess: &'tcx Session,
40     tcx: Option<TyCtxt<'tcx>>,
41     f: F,
42 ) -> A
43 where
44     F: FnOnce(&dyn PrinterSupport) -> A,
45 {
46     match *ppmode {
47         PpmNormal | PpmEveryBodyLoops | PpmExpanded => {
48             let annotation = NoAnn { sess, tcx };
49             f(&annotation)
50         }
51
52         PpmIdentified | PpmExpandedIdentified => {
53             let annotation = IdentifiedAnnotation { sess, tcx };
54             f(&annotation)
55         }
56         PpmExpandedHygiene => {
57             let annotation = HygieneAnnotation { sess };
58             f(&annotation)
59         }
60         _ => panic!("Should use call_with_pp_support_hir"),
61     }
62 }
63 fn call_with_pp_support_hir<A, F>(ppmode: &PpSourceMode, tcx: TyCtxt<'_>, f: F) -> A
64 where
65     F: FnOnce(&dyn HirPrinterSupport<'_>, &hir::Crate<'_>) -> A,
66 {
67     match *ppmode {
68         PpmNormal => {
69             let annotation = NoAnn { sess: tcx.sess, tcx: Some(tcx) };
70             f(&annotation, tcx.hir().krate())
71         }
72
73         PpmIdentified => {
74             let annotation = IdentifiedAnnotation { sess: tcx.sess, tcx: Some(tcx) };
75             f(&annotation, tcx.hir().krate())
76         }
77         PpmTyped => {
78             abort_on_err(tcx.analysis(LOCAL_CRATE), tcx.sess);
79
80             let annotation = TypedAnnotation { tcx, maybe_typeck_results: Cell::new(None) };
81             tcx.dep_graph.with_ignore(|| f(&annotation, tcx.hir().krate()))
82         }
83         _ => panic!("Should use call_with_pp_support"),
84     }
85 }
86
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;
91
92     /// Produces the pretty-print annotation object.
93     ///
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;
97 }
98
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;
103
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>>;
107
108     /// Produces the pretty-print annotation object.
109     ///
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;
113
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("::")
118         })
119     }
120 }
121
122 struct NoAnn<'hir> {
123     sess: &'hir Session,
124     tcx: Option<TyCtxt<'hir>>,
125 }
126
127 impl<'hir> PrinterSupport for NoAnn<'hir> {
128     fn sess(&self) -> &Session {
129         self.sess
130     }
131
132     fn pp_ann(&self) -> &dyn pprust::PpAnn {
133         self
134     }
135 }
136
137 impl<'hir> HirPrinterSupport<'hir> for NoAnn<'hir> {
138     fn sess(&self) -> &Session {
139         self.sess
140     }
141
142     fn hir_map(&self) -> Option<hir_map::Map<'hir>> {
143         self.tcx.map(|tcx| tcx.hir())
144     }
145
146     fn pp_ann(&self) -> &dyn pprust_hir::PpAnn {
147         self
148     }
149 }
150
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)
156         }
157     }
158 }
159
160 struct IdentifiedAnnotation<'hir> {
161     sess: &'hir Session,
162     tcx: Option<TyCtxt<'hir>>,
163 }
164
165 impl<'hir> PrinterSupport for IdentifiedAnnotation<'hir> {
166     fn sess(&self) -> &Session {
167         self.sess
168     }
169
170     fn pp_ann(&self) -> &dyn pprust::PpAnn {
171         self
172     }
173 }
174
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 {
178             s.popen();
179         }
180     }
181     fn post(&self, s: &mut pprust::State<'_>, node: pprust::AnnNode<'_>) {
182         match node {
183             pprust::AnnNode::Crate(_) | pprust::AnnNode::Ident(_) | pprust::AnnNode::Name(_) => {}
184
185             pprust::AnnNode::Item(item) => {
186                 s.s.space();
187                 s.synth_comment(item.id.to_string())
188             }
189             pprust::AnnNode::SubItem(id) => {
190                 s.s.space();
191                 s.synth_comment(id.to_string())
192             }
193             pprust::AnnNode::Block(blk) => {
194                 s.s.space();
195                 s.synth_comment(format!("block {}", blk.id))
196             }
197             pprust::AnnNode::Expr(expr) => {
198                 s.s.space();
199                 s.synth_comment(expr.id.to_string());
200                 s.pclose()
201             }
202             pprust::AnnNode::Pat(pat) => {
203                 s.s.space();
204                 s.synth_comment(format!("pat {}", pat.id));
205             }
206         }
207     }
208 }
209
210 impl<'hir> HirPrinterSupport<'hir> for IdentifiedAnnotation<'hir> {
211     fn sess(&self) -> &Session {
212         self.sess
213     }
214
215     fn hir_map(&self) -> Option<hir_map::Map<'hir>> {
216         self.tcx.map(|tcx| tcx.hir())
217     }
218
219     fn pp_ann(&self) -> &dyn pprust_hir::PpAnn {
220         self
221     }
222 }
223
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)
228         }
229     }
230     fn pre(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) {
231         if let pprust_hir::AnnNode::Expr(_) = node {
232             s.popen();
233         }
234     }
235     fn post(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) {
236         match node {
237             pprust_hir::AnnNode::Name(_) => {}
238             pprust_hir::AnnNode::Item(item) => {
239                 s.s.space();
240                 s.synth_comment(format!("hir_id: {}", item.hir_id));
241             }
242             pprust_hir::AnnNode::SubItem(id) => {
243                 s.s.space();
244                 s.synth_comment(id.to_string());
245             }
246             pprust_hir::AnnNode::Block(blk) => {
247                 s.s.space();
248                 s.synth_comment(format!("block hir_id: {}", blk.hir_id));
249             }
250             pprust_hir::AnnNode::Expr(expr) => {
251                 s.s.space();
252                 s.synth_comment(format!("expr hir_id: {}", expr.hir_id));
253                 s.pclose();
254             }
255             pprust_hir::AnnNode::Pat(pat) => {
256                 s.s.space();
257                 s.synth_comment(format!("pat hir_id: {}", pat.hir_id));
258             }
259             pprust_hir::AnnNode::Arm(arm) => {
260                 s.s.space();
261                 s.synth_comment(format!("arm hir_id: {}", arm.hir_id));
262             }
263         }
264     }
265 }
266
267 struct HygieneAnnotation<'a> {
268     sess: &'a Session,
269 }
270
271 impl<'a> PrinterSupport for HygieneAnnotation<'a> {
272     fn sess(&self) -> &Session {
273         self.sess
274     }
275
276     fn pp_ann(&self) -> &dyn pprust::PpAnn {
277         self
278     }
279 }
280
281 impl<'a> pprust::PpAnn for HygieneAnnotation<'a> {
282     fn post(&self, s: &mut pprust::State<'_>, node: pprust::AnnNode<'_>) {
283         match node {
284             pprust::AnnNode::Ident(&Ident { name, span }) => {
285                 s.s.space();
286                 s.synth_comment(format!("{}{:?}", name.as_u32(), span.ctxt()))
287             }
288             pprust::AnnNode::Name(&name) => {
289                 s.s.space();
290                 s.synth_comment(name.as_u32().to_string())
291             }
292             pprust::AnnNode::Crate(_) => {
293                 s.s.hardbreak();
294                 let verbose = self.sess.verbose();
295                 s.synth_comment(rustc_span::hygiene::debug_hygiene_data(verbose));
296                 s.s.hardbreak_if_not_bol();
297             }
298             _ => {}
299         }
300     }
301 }
302
303 struct TypedAnnotation<'tcx> {
304     tcx: TyCtxt<'tcx>,
305     maybe_typeck_results: Cell<Option<&'tcx ty::TypeckResults<'tcx>>>,
306 }
307
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).
312     #[track_caller]
313     fn typeck_results(&self) -> &'tcx ty::TypeckResults<'tcx> {
314         self.maybe_typeck_results
315             .get()
316             .expect("`TypedAnnotation::typeck_results` called outside of body")
317     }
318 }
319
320 impl<'tcx> HirPrinterSupport<'tcx> for TypedAnnotation<'tcx> {
321     fn sess(&self) -> &Session {
322         &self.tcx.sess
323     }
324
325     fn hir_map(&self) -> Option<hir_map::Map<'tcx>> {
326         Some(self.tcx.hir())
327     }
328
329     fn pp_ann(&self) -> &dyn pprust_hir::PpAnn {
330         self
331     }
332
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()))
335     }
336 }
337
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)));
343         }
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);
347     }
348     fn pre(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) {
349         if let pprust_hir::AnnNode::Expr(_) = node {
350             s.popen();
351         }
352     }
353     fn post(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) {
354         if let pprust_hir::AnnNode::Expr(expr) = node {
355             s.s.space();
356             s.s.word("as");
357             s.s.space();
358             s.s.word(self.typeck_results().expr_ty(expr).to_string());
359             s.pclose();
360         }
361     }
362 }
363
364 fn get_source(input: &Input, sess: &Session) -> (String, FileName) {
365     let src_name = input.source_name();
366     let src =
367         String::clone(&sess.source_map().get_source_file(&src_name).unwrap().src.as_ref().unwrap());
368     (src, src_name)
369 }
370
371 fn write_output(out: Vec<u8>, ofile: Option<&Path>) {
372     match ofile {
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),
377         },
378     }
379 }
380
381 pub fn print_after_parsing(
382     sess: &Session,
383     input: &Input,
384     krate: &ast::Crate,
385     ppm: PpMode,
386     ofile: Option<&Path>,
387 ) {
388     let (src, src_name) = get_source(input, sess);
389
390     let mut out = String::new();
391
392     if let PpmSource(s) = ppm {
393         // Silently ignores an identified node.
394         let out = &mut out;
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(
400                 sess.source_map(),
401                 krate,
402                 src_name,
403                 src,
404                 annotation.pp_ann(),
405                 false,
406                 parse.edition,
407                 parse.injected_crate_name.get().is_some(),
408             )
409         })
410     } else {
411         unreachable!();
412     };
413
414     write_output(out.into_bytes(), ofile);
415 }
416
417 pub fn print_after_hir_lowering<'tcx>(
418     tcx: TyCtxt<'tcx>,
419     input: &Input,
420     krate: &ast::Crate,
421     ppm: PpMode,
422     ofile: Option<&Path>,
423 ) {
424     if ppm.needs_analysis() {
425         abort_on_err(print_with_analysis(tcx, ppm, ofile), tcx.sess);
426         return;
427     }
428
429     let (src, src_name) = get_source(input, tcx.sess);
430
431     let mut out = String::new();
432
433     match ppm {
434         PpmSource(s) => {
435             // Silently ignores an identified node.
436             let out = &mut out;
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(
442                     sess.source_map(),
443                     krate,
444                     src_name,
445                     src,
446                     annotation.pp_ann(),
447                     true,
448                     parse.edition,
449                     parse.injected_crate_name.get().is_some(),
450                 )
451             })
452         }
453
454         PpmHir(s) => {
455             let out = &mut out;
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())
461             })
462         }
463
464         PpmHirTree(s) => {
465             let out = &mut out;
466             call_with_pp_support_hir(&s, tcx, move |_annotation, krate| {
467                 debug!("pretty printing source code {:?}", s);
468                 *out = format!("{:#?}", krate);
469             });
470         }
471
472         _ => unreachable!(),
473     }
474
475     write_output(out.into_bytes(), ofile);
476 }
477
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(
483     tcx: TyCtxt<'_>,
484     ppm: PpMode,
485     ofile: Option<&Path>,
486 ) -> Result<(), ErrorReported> {
487     let mut out = Vec::new();
488
489     tcx.analysis(LOCAL_CRATE)?;
490
491     match ppm {
492         PpmMir | PpmMirCFG => match ppm {
493             PpmMir => write_mir_pretty(tcx, None, &mut out),
494             PpmMirCFG => write_mir_graphviz(tcx, None, &mut out),
495             _ => unreachable!(),
496         },
497         _ => unreachable!(),
498     }
499     .unwrap();
500
501     write_output(out, ofile);
502
503     Ok(())
504 }