]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_driver/src/pretty.rs
Rollup merge of #79983 - petar-dambovaliev:master, r=Dylan-DPC
[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 = String::clone(
367         &sess
368             .source_map()
369             .get_source_file(&src_name)
370             .expect("get_source_file")
371             .src
372             .as_ref()
373             .expect("src"),
374     );
375     (src, src_name)
376 }
377
378 fn write_output(out: Vec<u8>, ofile: Option<&Path>) {
379     match ofile {
380         None => print!("{}", String::from_utf8(out).unwrap()),
381         Some(p) => match File::create(p) {
382             Ok(mut w) => w.write_all(&out).unwrap(),
383             Err(e) => panic!("print-print failed to open {} due to {}", p.display(), e),
384         },
385     }
386 }
387
388 pub fn print_after_parsing(
389     sess: &Session,
390     input: &Input,
391     krate: &ast::Crate,
392     ppm: PpMode,
393     ofile: Option<&Path>,
394 ) {
395     let (src, src_name) = get_source(input, sess);
396
397     let mut out = String::new();
398
399     if let PpmSource(s) = ppm {
400         // Silently ignores an identified node.
401         let out = &mut out;
402         call_with_pp_support(&s, sess, None, move |annotation| {
403             debug!("pretty printing source code {:?}", s);
404             let sess = annotation.sess();
405             let parse = &sess.parse_sess;
406             *out = pprust::print_crate(
407                 sess.source_map(),
408                 krate,
409                 src_name,
410                 src,
411                 annotation.pp_ann(),
412                 false,
413                 parse.edition,
414             )
415         })
416     } else {
417         unreachable!();
418     };
419
420     write_output(out.into_bytes(), ofile);
421 }
422
423 pub fn print_after_hir_lowering<'tcx>(
424     tcx: TyCtxt<'tcx>,
425     input: &Input,
426     krate: &ast::Crate,
427     ppm: PpMode,
428     ofile: Option<&Path>,
429 ) {
430     if ppm.needs_analysis() {
431         abort_on_err(print_with_analysis(tcx, ppm, ofile), tcx.sess);
432         return;
433     }
434
435     let (src, src_name) = get_source(input, tcx.sess);
436
437     let mut out = String::new();
438
439     match ppm {
440         PpmSource(s) => {
441             // Silently ignores an identified node.
442             let out = &mut out;
443             call_with_pp_support(&s, tcx.sess, Some(tcx), move |annotation| {
444                 debug!("pretty printing source code {:?}", s);
445                 let sess = annotation.sess();
446                 let parse = &sess.parse_sess;
447                 *out = pprust::print_crate(
448                     sess.source_map(),
449                     krate,
450                     src_name,
451                     src,
452                     annotation.pp_ann(),
453                     true,
454                     parse.edition,
455                 )
456             })
457         }
458
459         PpmHir(s) => {
460             let out = &mut out;
461             call_with_pp_support_hir(&s, tcx, move |annotation, krate| {
462                 debug!("pretty printing source code {:?}", s);
463                 let sess = annotation.sess();
464                 let sm = sess.source_map();
465                 *out = pprust_hir::print_crate(sm, krate, src_name, src, annotation.pp_ann())
466             })
467         }
468
469         PpmHirTree(s) => {
470             let out = &mut out;
471             call_with_pp_support_hir(&s, tcx, move |_annotation, krate| {
472                 debug!("pretty printing source code {:?}", s);
473                 *out = format!("{:#?}", krate);
474             });
475         }
476
477         _ => unreachable!(),
478     }
479
480     write_output(out.into_bytes(), ofile);
481 }
482
483 // In an ideal world, this would be a public function called by the driver after
484 // analysis is performed. However, we want to call `phase_3_run_analysis_passes`
485 // with a different callback than the standard driver, so that isn't easy.
486 // Instead, we call that function ourselves.
487 fn print_with_analysis(
488     tcx: TyCtxt<'_>,
489     ppm: PpMode,
490     ofile: Option<&Path>,
491 ) -> Result<(), ErrorReported> {
492     let mut out = Vec::new();
493
494     tcx.analysis(LOCAL_CRATE)?;
495
496     match ppm {
497         PpmMir | PpmMirCFG => match ppm {
498             PpmMir => write_mir_pretty(tcx, None, &mut out),
499             PpmMirCFG => write_mir_graphviz(tcx, None, &mut out),
500             _ => unreachable!(),
501         },
502         _ => unreachable!(),
503     }
504     .unwrap();
505
506     write_output(out, ofile);
507
508     Ok(())
509 }