]> git.lizzy.rs Git - rust.git/blob - src/librustc_driver/pretty.rs
Rollup merge of #73762 - poliorcetics:trait-keyword, r=KodrAus
[rust.git] / src / librustc_driver / pretty.rs
1 //! The various pretty-printing routines.
2
3 use rustc_ast::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 // (The `use_once_payload` is working around the current lack of once
37 // functions in the compiler.)
38
39 /// Constructs a `PrinterSupport` object and passes it to `f`.
40 fn call_with_pp_support<'tcx, A, F>(
41     ppmode: &PpSourceMode,
42     sess: &'tcx Session,
43     tcx: Option<TyCtxt<'tcx>>,
44     f: F,
45 ) -> A
46 where
47     F: FnOnce(&dyn PrinterSupport) -> A,
48 {
49     match *ppmode {
50         PpmNormal | PpmEveryBodyLoops | PpmExpanded => {
51             let annotation = NoAnn { sess, tcx };
52             f(&annotation)
53         }
54
55         PpmIdentified | PpmExpandedIdentified => {
56             let annotation = IdentifiedAnnotation { sess, tcx };
57             f(&annotation)
58         }
59         PpmExpandedHygiene => {
60             let annotation = HygieneAnnotation { sess };
61             f(&annotation)
62         }
63         _ => panic!("Should use call_with_pp_support_hir"),
64     }
65 }
66 fn call_with_pp_support_hir<A, F>(ppmode: &PpSourceMode, tcx: TyCtxt<'_>, f: F) -> A
67 where
68     F: FnOnce(&dyn HirPrinterSupport<'_>, &hir::Crate<'_>) -> A,
69 {
70     match *ppmode {
71         PpmNormal => {
72             let annotation = NoAnn { sess: tcx.sess, tcx: Some(tcx) };
73             f(&annotation, tcx.hir().krate())
74         }
75
76         PpmIdentified => {
77             let annotation = IdentifiedAnnotation { sess: tcx.sess, tcx: Some(tcx) };
78             f(&annotation, tcx.hir().krate())
79         }
80         PpmTyped => {
81             abort_on_err(tcx.analysis(LOCAL_CRATE), tcx.sess);
82
83             let annotation = TypedAnnotation { tcx, maybe_typeck_results: Cell::new(None) };
84             tcx.dep_graph.with_ignore(|| f(&annotation, tcx.hir().krate()))
85         }
86         _ => panic!("Should use call_with_pp_support"),
87     }
88 }
89
90 trait PrinterSupport: pprust::PpAnn {
91     /// Provides a uniform interface for re-extracting a reference to a
92     /// `Session` from a value that now owns it.
93     fn sess(&self) -> &Session;
94
95     /// Produces the pretty-print annotation object.
96     ///
97     /// (Rust does not yet support upcasting from a trait object to
98     /// an object for one of its super-traits.)
99     fn pp_ann(&self) -> &dyn pprust::PpAnn;
100 }
101
102 trait HirPrinterSupport<'hir>: pprust_hir::PpAnn {
103     /// Provides a uniform interface for re-extracting a reference to a
104     /// `Session` from a value that now owns it.
105     fn sess(&self) -> &Session;
106
107     /// Provides a uniform interface for re-extracting a reference to an
108     /// `hir_map::Map` from a value that now owns it.
109     fn hir_map(&self) -> Option<hir_map::Map<'hir>>;
110
111     /// Produces the pretty-print annotation object.
112     ///
113     /// (Rust does not yet support upcasting from a trait object to
114     /// an object for one of its super-traits.)
115     fn pp_ann(&self) -> &dyn pprust_hir::PpAnn;
116
117     /// Computes an user-readable representation of a path, if possible.
118     fn node_path(&self, id: hir::HirId) -> Option<String> {
119         self.hir_map().and_then(|map| map.def_path_from_hir_id(id)).map(|path| {
120             path.data.into_iter().map(|elem| elem.data.to_string()).collect::<Vec<_>>().join("::")
121         })
122     }
123 }
124
125 struct NoAnn<'hir> {
126     sess: &'hir Session,
127     tcx: Option<TyCtxt<'hir>>,
128 }
129
130 impl<'hir> PrinterSupport for NoAnn<'hir> {
131     fn sess(&self) -> &Session {
132         self.sess
133     }
134
135     fn pp_ann(&self) -> &dyn pprust::PpAnn {
136         self
137     }
138 }
139
140 impl<'hir> HirPrinterSupport<'hir> for NoAnn<'hir> {
141     fn sess(&self) -> &Session {
142         self.sess
143     }
144
145     fn hir_map(&self) -> Option<hir_map::Map<'hir>> {
146         self.tcx.map(|tcx| tcx.hir())
147     }
148
149     fn pp_ann(&self) -> &dyn pprust_hir::PpAnn {
150         self
151     }
152 }
153
154 impl<'hir> pprust::PpAnn for NoAnn<'hir> {}
155 impl<'hir> pprust_hir::PpAnn for NoAnn<'hir> {
156     fn nested(&self, state: &mut pprust_hir::State<'_>, nested: pprust_hir::Nested) {
157         if let Some(tcx) = self.tcx {
158             pprust_hir::PpAnn::nested(&(&tcx.hir() as &dyn hir::intravisit::Map<'_>), state, nested)
159         }
160     }
161 }
162
163 struct IdentifiedAnnotation<'hir> {
164     sess: &'hir Session,
165     tcx: Option<TyCtxt<'hir>>,
166 }
167
168 impl<'hir> PrinterSupport for IdentifiedAnnotation<'hir> {
169     fn sess(&self) -> &Session {
170         self.sess
171     }
172
173     fn pp_ann(&self) -> &dyn pprust::PpAnn {
174         self
175     }
176 }
177
178 impl<'hir> pprust::PpAnn for IdentifiedAnnotation<'hir> {
179     fn pre(&self, s: &mut pprust::State<'_>, node: pprust::AnnNode<'_>) {
180         if let pprust::AnnNode::Expr(_) = node {
181             s.popen();
182         }
183     }
184     fn post(&self, s: &mut pprust::State<'_>, node: pprust::AnnNode<'_>) {
185         match node {
186             pprust::AnnNode::Crate(_) | pprust::AnnNode::Ident(_) | pprust::AnnNode::Name(_) => {}
187
188             pprust::AnnNode::Item(item) => {
189                 s.s.space();
190                 s.synth_comment(item.id.to_string())
191             }
192             pprust::AnnNode::SubItem(id) => {
193                 s.s.space();
194                 s.synth_comment(id.to_string())
195             }
196             pprust::AnnNode::Block(blk) => {
197                 s.s.space();
198                 s.synth_comment(format!("block {}", blk.id))
199             }
200             pprust::AnnNode::Expr(expr) => {
201                 s.s.space();
202                 s.synth_comment(expr.id.to_string());
203                 s.pclose()
204             }
205             pprust::AnnNode::Pat(pat) => {
206                 s.s.space();
207                 s.synth_comment(format!("pat {}", pat.id));
208             }
209         }
210     }
211 }
212
213 impl<'hir> HirPrinterSupport<'hir> for IdentifiedAnnotation<'hir> {
214     fn sess(&self) -> &Session {
215         self.sess
216     }
217
218     fn hir_map(&self) -> Option<hir_map::Map<'hir>> {
219         self.tcx.map(|tcx| tcx.hir())
220     }
221
222     fn pp_ann(&self) -> &dyn pprust_hir::PpAnn {
223         self
224     }
225 }
226
227 impl<'hir> pprust_hir::PpAnn for IdentifiedAnnotation<'hir> {
228     fn nested(&self, state: &mut pprust_hir::State<'_>, nested: pprust_hir::Nested) {
229         if let Some(ref tcx) = self.tcx {
230             pprust_hir::PpAnn::nested(&(&tcx.hir() as &dyn hir::intravisit::Map<'_>), state, nested)
231         }
232     }
233     fn pre(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) {
234         if let pprust_hir::AnnNode::Expr(_) = node {
235             s.popen();
236         }
237     }
238     fn post(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) {
239         match node {
240             pprust_hir::AnnNode::Name(_) => {}
241             pprust_hir::AnnNode::Item(item) => {
242                 s.s.space();
243                 s.synth_comment(format!("hir_id: {}", item.hir_id));
244             }
245             pprust_hir::AnnNode::SubItem(id) => {
246                 s.s.space();
247                 s.synth_comment(id.to_string());
248             }
249             pprust_hir::AnnNode::Block(blk) => {
250                 s.s.space();
251                 s.synth_comment(format!("block hir_id: {}", blk.hir_id));
252             }
253             pprust_hir::AnnNode::Expr(expr) => {
254                 s.s.space();
255                 s.synth_comment(format!("expr hir_id: {}", expr.hir_id));
256                 s.pclose();
257             }
258             pprust_hir::AnnNode::Pat(pat) => {
259                 s.s.space();
260                 s.synth_comment(format!("pat hir_id: {}", pat.hir_id));
261             }
262             pprust_hir::AnnNode::Arm(arm) => {
263                 s.s.space();
264                 s.synth_comment(format!("arm hir_id: {}", arm.hir_id));
265             }
266         }
267     }
268 }
269
270 struct HygieneAnnotation<'a> {
271     sess: &'a Session,
272 }
273
274 impl<'a> PrinterSupport for HygieneAnnotation<'a> {
275     fn sess(&self) -> &Session {
276         self.sess
277     }
278
279     fn pp_ann(&self) -> &dyn pprust::PpAnn {
280         self
281     }
282 }
283
284 impl<'a> pprust::PpAnn for HygieneAnnotation<'a> {
285     fn post(&self, s: &mut pprust::State<'_>, node: pprust::AnnNode<'_>) {
286         match node {
287             pprust::AnnNode::Ident(&Ident { name, span }) => {
288                 s.s.space();
289                 s.synth_comment(format!("{}{:?}", name.as_u32(), span.ctxt()))
290             }
291             pprust::AnnNode::Name(&name) => {
292                 s.s.space();
293                 s.synth_comment(name.as_u32().to_string())
294             }
295             pprust::AnnNode::Crate(_) => {
296                 s.s.hardbreak();
297                 let verbose = self.sess.verbose();
298                 s.synth_comment(rustc_span::hygiene::debug_hygiene_data(verbose));
299                 s.s.hardbreak_if_not_bol();
300             }
301             _ => {}
302         }
303     }
304 }
305
306 struct TypedAnnotation<'tcx> {
307     tcx: TyCtxt<'tcx>,
308     maybe_typeck_results: Cell<Option<&'tcx ty::TypeckResults<'tcx>>>,
309 }
310
311 impl<'tcx> TypedAnnotation<'tcx> {
312     /// Gets the type-checking results for the current body.
313     /// As this will ICE if called outside bodies, only call when working with
314     /// `Expr` or `Pat` nodes (they are guaranteed to be found only in bodies).
315     #[track_caller]
316     fn typeck_results(&self) -> &'tcx ty::TypeckResults<'tcx> {
317         self.maybe_typeck_results
318             .get()
319             .expect("`TypedAnnotation::typeck_results` called outside of body")
320     }
321 }
322
323 impl<'tcx> HirPrinterSupport<'tcx> for TypedAnnotation<'tcx> {
324     fn sess(&self) -> &Session {
325         &self.tcx.sess
326     }
327
328     fn hir_map(&self) -> Option<hir_map::Map<'tcx>> {
329         Some(self.tcx.hir())
330     }
331
332     fn pp_ann(&self) -> &dyn pprust_hir::PpAnn {
333         self
334     }
335
336     fn node_path(&self, id: hir::HirId) -> Option<String> {
337         Some(self.tcx.def_path_str(self.tcx.hir().local_def_id(id).to_def_id()))
338     }
339 }
340
341 impl<'tcx> pprust_hir::PpAnn for TypedAnnotation<'tcx> {
342     fn nested(&self, state: &mut pprust_hir::State<'_>, nested: pprust_hir::Nested) {
343         let old_maybe_typeck_results = self.maybe_typeck_results.get();
344         if let pprust_hir::Nested::Body(id) = nested {
345             self.maybe_typeck_results.set(Some(self.tcx.typeck_body(id)));
346         }
347         let pp_ann = &(&self.tcx.hir() as &dyn hir::intravisit::Map<'_>);
348         pprust_hir::PpAnn::nested(pp_ann, state, nested);
349         self.maybe_typeck_results.set(old_maybe_typeck_results);
350     }
351     fn pre(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) {
352         if let pprust_hir::AnnNode::Expr(_) = node {
353             s.popen();
354         }
355     }
356     fn post(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) {
357         if let pprust_hir::AnnNode::Expr(expr) = node {
358             s.s.space();
359             s.s.word("as");
360             s.s.space();
361             s.s.word(self.typeck_results().expr_ty(expr).to_string());
362             s.pclose();
363         }
364     }
365 }
366
367 fn get_source(input: &Input, sess: &Session) -> (String, FileName) {
368     let src_name = input.source_name();
369     let src =
370         String::clone(&sess.source_map().get_source_file(&src_name).unwrap().src.as_ref().unwrap());
371     (src, src_name)
372 }
373
374 fn write_output(out: Vec<u8>, ofile: Option<&Path>) {
375     match ofile {
376         None => print!("{}", String::from_utf8(out).unwrap()),
377         Some(p) => match File::create(p) {
378             Ok(mut w) => w.write_all(&out).unwrap(),
379             Err(e) => panic!("print-print failed to open {} due to {}", p.display(), e),
380         },
381     }
382 }
383
384 pub fn print_after_parsing(
385     sess: &Session,
386     input: &Input,
387     krate: &ast::Crate,
388     ppm: PpMode,
389     ofile: Option<&Path>,
390 ) {
391     let (src, src_name) = get_source(input, sess);
392
393     let mut out = String::new();
394
395     if let PpmSource(s) = ppm {
396         // Silently ignores an identified node.
397         let out = &mut out;
398         call_with_pp_support(&s, sess, None, move |annotation| {
399             debug!("pretty printing source code {:?}", s);
400             let sess = annotation.sess();
401             let parse = &sess.parse_sess;
402             *out = pprust::print_crate(
403                 sess.source_map(),
404                 krate,
405                 src_name,
406                 src,
407                 annotation.pp_ann(),
408                 false,
409                 parse.edition,
410                 parse.injected_crate_name.get().is_some(),
411             )
412         })
413     } else {
414         unreachable!();
415     };
416
417     write_output(out.into_bytes(), ofile);
418 }
419
420 pub fn print_after_hir_lowering<'tcx>(
421     tcx: TyCtxt<'tcx>,
422     input: &Input,
423     krate: &ast::Crate,
424     ppm: PpMode,
425     ofile: Option<&Path>,
426 ) {
427     if ppm.needs_analysis() {
428         abort_on_err(print_with_analysis(tcx, ppm, ofile), tcx.sess);
429         return;
430     }
431
432     let (src, src_name) = get_source(input, tcx.sess);
433
434     let mut out = String::new();
435
436     match ppm {
437         PpmSource(s) => {
438             // Silently ignores an identified node.
439             let out = &mut out;
440             call_with_pp_support(&s, tcx.sess, Some(tcx), move |annotation| {
441                 debug!("pretty printing source code {:?}", s);
442                 let sess = annotation.sess();
443                 let parse = &sess.parse_sess;
444                 *out = pprust::print_crate(
445                     sess.source_map(),
446                     krate,
447                     src_name,
448                     src,
449                     annotation.pp_ann(),
450                     true,
451                     parse.edition,
452                     parse.injected_crate_name.get().is_some(),
453                 )
454             })
455         }
456
457         PpmHir(s) => {
458             let out = &mut out;
459             call_with_pp_support_hir(&s, tcx, move |annotation, krate| {
460                 debug!("pretty printing source code {:?}", s);
461                 let sess = annotation.sess();
462                 let sm = sess.source_map();
463                 *out = pprust_hir::print_crate(sm, krate, src_name, src, annotation.pp_ann())
464             })
465         }
466
467         PpmHirTree(s) => {
468             let out = &mut out;
469             call_with_pp_support_hir(&s, tcx, move |_annotation, krate| {
470                 debug!("pretty printing source code {:?}", s);
471                 *out = format!("{:#?}", krate);
472             });
473         }
474
475         _ => unreachable!(),
476     }
477
478     write_output(out.into_bytes(), ofile);
479 }
480
481 // In an ideal world, this would be a public function called by the driver after
482 // analysis is performed. However, we want to call `phase_3_run_analysis_passes`
483 // with a different callback than the standard driver, so that isn't easy.
484 // Instead, we call that function ourselves.
485 fn print_with_analysis(
486     tcx: TyCtxt<'_>,
487     ppm: PpMode,
488     ofile: Option<&Path>,
489 ) -> Result<(), ErrorReported> {
490     let mut out = Vec::new();
491
492     tcx.analysis(LOCAL_CRATE)?;
493
494     match ppm {
495         PpmMir | PpmMirCFG => match ppm {
496             PpmMir => write_mir_pretty(tcx, None, &mut out),
497             PpmMirCFG => write_mir_graphviz(tcx, None, &mut out),
498             _ => unreachable!(),
499         },
500         _ => unreachable!(),
501     }
502     .unwrap();
503
504     write_output(out, ofile);
505
506     Ok(())
507 }