]> git.lizzy.rs Git - rust.git/blob - src/librustc_driver/pretty.rs
Rollup merge of #73957 - RalfJung:btree-min-max, r=shepmaster
[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_tables: 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_tables: Cell<Option<&'tcx ty::TypeckTables<'tcx>>>,
309 }
310
311 impl<'tcx> TypedAnnotation<'tcx> {
312     /// Gets the type-checking side-tables 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 tables(&self) -> &'tcx ty::TypeckTables<'tcx> {
317         self.maybe_typeck_tables.get().expect("`TypedAnnotation::tables` called outside of body")
318     }
319 }
320
321 impl<'tcx> HirPrinterSupport<'tcx> for TypedAnnotation<'tcx> {
322     fn sess(&self) -> &Session {
323         &self.tcx.sess
324     }
325
326     fn hir_map(&self) -> Option<hir_map::Map<'tcx>> {
327         Some(self.tcx.hir())
328     }
329
330     fn pp_ann(&self) -> &dyn pprust_hir::PpAnn {
331         self
332     }
333
334     fn node_path(&self, id: hir::HirId) -> Option<String> {
335         Some(self.tcx.def_path_str(self.tcx.hir().local_def_id(id).to_def_id()))
336     }
337 }
338
339 impl<'tcx> pprust_hir::PpAnn for TypedAnnotation<'tcx> {
340     fn nested(&self, state: &mut pprust_hir::State<'_>, nested: pprust_hir::Nested) {
341         let old_maybe_typeck_tables = self.maybe_typeck_tables.get();
342         if let pprust_hir::Nested::Body(id) = nested {
343             self.maybe_typeck_tables.set(Some(self.tcx.body_tables(id)));
344         }
345         let pp_ann = &(&self.tcx.hir() as &dyn hir::intravisit::Map<'_>);
346         pprust_hir::PpAnn::nested(pp_ann, state, nested);
347         self.maybe_typeck_tables.set(old_maybe_typeck_tables);
348     }
349     fn pre(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) {
350         if let pprust_hir::AnnNode::Expr(_) = node {
351             s.popen();
352         }
353     }
354     fn post(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) {
355         if let pprust_hir::AnnNode::Expr(expr) = node {
356             s.s.space();
357             s.s.word("as");
358             s.s.space();
359             s.s.word(self.tables().expr_ty(expr).to_string());
360             s.pclose();
361         }
362     }
363 }
364
365 fn get_source(input: &Input, sess: &Session) -> (String, FileName) {
366     let src_name = input.source_name();
367     let src =
368         String::clone(&sess.source_map().get_source_file(&src_name).unwrap().src.as_ref().unwrap());
369     (src, src_name)
370 }
371
372 fn write_output(out: Vec<u8>, ofile: Option<&Path>) {
373     match ofile {
374         None => print!("{}", String::from_utf8(out).unwrap()),
375         Some(p) => match File::create(p) {
376             Ok(mut w) => w.write_all(&out).unwrap(),
377             Err(e) => panic!("print-print failed to open {} due to {}", p.display(), e),
378         },
379     }
380 }
381
382 pub fn print_after_parsing(
383     sess: &Session,
384     input: &Input,
385     krate: &ast::Crate,
386     ppm: PpMode,
387     ofile: Option<&Path>,
388 ) {
389     let (src, src_name) = get_source(input, sess);
390
391     let mut out = String::new();
392
393     if let PpmSource(s) = ppm {
394         // Silently ignores an identified node.
395         let out = &mut out;
396         call_with_pp_support(&s, sess, None, move |annotation| {
397             debug!("pretty printing source code {:?}", s);
398             let sess = annotation.sess();
399             let parse = &sess.parse_sess;
400             *out = pprust::print_crate(
401                 sess.source_map(),
402                 krate,
403                 src_name,
404                 src,
405                 annotation.pp_ann(),
406                 false,
407                 parse.edition,
408                 parse.injected_crate_name.get().is_some(),
409             )
410         })
411     } else {
412         unreachable!();
413     };
414
415     write_output(out.into_bytes(), ofile);
416 }
417
418 pub fn print_after_hir_lowering<'tcx>(
419     tcx: TyCtxt<'tcx>,
420     input: &Input,
421     krate: &ast::Crate,
422     ppm: PpMode,
423     ofile: Option<&Path>,
424 ) {
425     if ppm.needs_analysis() {
426         abort_on_err(print_with_analysis(tcx, ppm, ofile), tcx.sess);
427         return;
428     }
429
430     let (src, src_name) = get_source(input, tcx.sess);
431
432     let mut out = String::new();
433
434     match ppm {
435         PpmSource(s) => {
436             // Silently ignores an identified node.
437             let out = &mut out;
438             call_with_pp_support(&s, tcx.sess, Some(tcx), move |annotation| {
439                 debug!("pretty printing source code {:?}", s);
440                 let sess = annotation.sess();
441                 let parse = &sess.parse_sess;
442                 *out = pprust::print_crate(
443                     sess.source_map(),
444                     krate,
445                     src_name,
446                     src,
447                     annotation.pp_ann(),
448                     true,
449                     parse.edition,
450                     parse.injected_crate_name.get().is_some(),
451                 )
452             })
453         }
454
455         PpmHir(s) => {
456             let out = &mut out;
457             call_with_pp_support_hir(&s, tcx, move |annotation, krate| {
458                 debug!("pretty printing source code {:?}", s);
459                 let sess = annotation.sess();
460                 let sm = sess.source_map();
461                 *out = pprust_hir::print_crate(sm, krate, src_name, src, annotation.pp_ann())
462             })
463         }
464
465         PpmHirTree(s) => {
466             let out = &mut out;
467             call_with_pp_support_hir(&s, tcx, move |_annotation, krate| {
468                 debug!("pretty printing source code {:?}", s);
469                 *out = format!("{:#?}", krate);
470             });
471         }
472
473         _ => unreachable!(),
474     }
475
476     write_output(out.into_bytes(), ofile);
477 }
478
479 // In an ideal world, this would be a public function called by the driver after
480 // analysis is performed. However, we want to call `phase_3_run_analysis_passes`
481 // with a different callback than the standard driver, so that isn't easy.
482 // Instead, we call that function ourselves.
483 fn print_with_analysis(
484     tcx: TyCtxt<'_>,
485     ppm: PpMode,
486     ofile: Option<&Path>,
487 ) -> Result<(), ErrorReported> {
488     let mut out = Vec::new();
489
490     tcx.analysis(LOCAL_CRATE)?;
491
492     match ppm {
493         PpmMir | PpmMirCFG => match ppm {
494             PpmMir => write_mir_pretty(tcx, None, &mut out),
495             PpmMirCFG => write_mir_graphviz(tcx, None, &mut out),
496             _ => unreachable!(),
497         },
498         _ => unreachable!(),
499     }
500     .unwrap();
501
502     write_output(out, ofile);
503
504     Ok(())
505 }