]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_driver/src/pretty.rs
Rollup merge of #102245 - ink-feather-org:const_cmp_by, r=fee1-dead
[rust.git] / compiler / rustc_driver / src / pretty.rs
1 //! The various pretty-printing routines.
2
3 use crate::session_diagnostics::UnprettyDumpFail;
4 use rustc_ast as ast;
5 use rustc_ast_pretty::pprust;
6 use rustc_errors::ErrorGuaranteed;
7 use rustc_hir as hir;
8 use rustc_hir_pretty as pprust_hir;
9 use rustc_middle::hir::map as hir_map;
10 use rustc_middle::mir::{write_mir_graphviz, write_mir_pretty};
11 use rustc_middle::ty::{self, TyCtxt};
12 use rustc_session::config::{Input, PpAstTreeMode, PpHirMode, 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::fmt::Write;
19 use std::path::Path;
20
21 pub use self::PpMode::*;
22 pub use self::PpSourceMode::*;
23 use crate::abort_on_err;
24
25 // This slightly awkward construction is to allow for each PpMode to
26 // choose whether it needs to do analyses (which can consume the
27 // Session) and then pass through the session (now attached to the
28 // analysis results) on to the chosen pretty-printer, along with the
29 // `&PpAnn` object.
30 //
31 // Note that since the `&PrinterSupport` is freshly constructed on each
32 // call, it would not make sense to try to attach the lifetime of `self`
33 // to the lifetime of the `&PrinterObject`.
34
35 /// Constructs a `PrinterSupport` object and passes it to `f`.
36 fn call_with_pp_support<'tcx, A, F>(
37     ppmode: &PpSourceMode,
38     sess: &'tcx Session,
39     tcx: Option<TyCtxt<'tcx>>,
40     f: F,
41 ) -> A
42 where
43     F: FnOnce(&dyn PrinterSupport) -> A,
44 {
45     match *ppmode {
46         Normal | Expanded => {
47             let annotation = NoAnn { sess, tcx };
48             f(&annotation)
49         }
50
51         Identified | ExpandedIdentified => {
52             let annotation = IdentifiedAnnotation { sess, tcx };
53             f(&annotation)
54         }
55         ExpandedHygiene => {
56             let annotation = HygieneAnnotation { sess };
57             f(&annotation)
58         }
59     }
60 }
61 fn call_with_pp_support_hir<A, F>(ppmode: &PpHirMode, tcx: TyCtxt<'_>, f: F) -> A
62 where
63     F: FnOnce(&dyn HirPrinterSupport<'_>, hir_map::Map<'_>) -> A,
64 {
65     match *ppmode {
66         PpHirMode::Normal => {
67             let annotation = NoAnn { sess: tcx.sess, tcx: Some(tcx) };
68             f(&annotation, tcx.hir())
69         }
70
71         PpHirMode::Identified => {
72             let annotation = IdentifiedAnnotation { sess: tcx.sess, tcx: Some(tcx) };
73             f(&annotation, tcx.hir())
74         }
75         PpHirMode::Typed => {
76             abort_on_err(tcx.analysis(()), tcx.sess);
77
78             let annotation = TypedAnnotation { tcx, maybe_typeck_results: Cell::new(None) };
79             tcx.dep_graph.with_ignore(|| f(&annotation, tcx.hir()))
80         }
81     }
82 }
83
84 trait PrinterSupport: pprust::PpAnn {
85     /// Provides a uniform interface for re-extracting a reference to a
86     /// `Session` from a value that now owns it.
87     fn sess(&self) -> &Session;
88
89     /// Produces the pretty-print annotation object.
90     ///
91     /// (Rust does not yet support upcasting from a trait object to
92     /// an object for one of its supertraits.)
93     fn pp_ann(&self) -> &dyn pprust::PpAnn;
94 }
95
96 trait HirPrinterSupport<'hir>: pprust_hir::PpAnn {
97     /// Provides a uniform interface for re-extracting a reference to a
98     /// `Session` from a value that now owns it.
99     fn sess(&self) -> &Session;
100
101     /// Provides a uniform interface for re-extracting a reference to an
102     /// `hir_map::Map` from a value that now owns it.
103     fn hir_map(&self) -> Option<hir_map::Map<'hir>>;
104
105     /// Produces the pretty-print annotation object.
106     ///
107     /// (Rust does not yet support upcasting from a trait object to
108     /// an object for one of its supertraits.)
109     fn pp_ann(&self) -> &dyn pprust_hir::PpAnn;
110 }
111
112 struct NoAnn<'hir> {
113     sess: &'hir Session,
114     tcx: Option<TyCtxt<'hir>>,
115 }
116
117 impl<'hir> PrinterSupport for NoAnn<'hir> {
118     fn sess(&self) -> &Session {
119         self.sess
120     }
121
122     fn pp_ann(&self) -> &dyn pprust::PpAnn {
123         self
124     }
125 }
126
127 impl<'hir> HirPrinterSupport<'hir> for NoAnn<'hir> {
128     fn sess(&self) -> &Session {
129         self.sess
130     }
131
132     fn hir_map(&self) -> Option<hir_map::Map<'hir>> {
133         self.tcx.map(|tcx| tcx.hir())
134     }
135
136     fn pp_ann(&self) -> &dyn pprust_hir::PpAnn {
137         self
138     }
139 }
140
141 impl<'hir> pprust::PpAnn for NoAnn<'hir> {}
142 impl<'hir> pprust_hir::PpAnn for NoAnn<'hir> {
143     fn nested(&self, state: &mut pprust_hir::State<'_>, nested: pprust_hir::Nested) {
144         if let Some(tcx) = self.tcx {
145             pprust_hir::PpAnn::nested(&(&tcx.hir() as &dyn hir::intravisit::Map<'_>), state, nested)
146         }
147     }
148 }
149
150 struct IdentifiedAnnotation<'hir> {
151     sess: &'hir Session,
152     tcx: Option<TyCtxt<'hir>>,
153 }
154
155 impl<'hir> PrinterSupport for IdentifiedAnnotation<'hir> {
156     fn sess(&self) -> &Session {
157         self.sess
158     }
159
160     fn pp_ann(&self) -> &dyn pprust::PpAnn {
161         self
162     }
163 }
164
165 impl<'hir> pprust::PpAnn for IdentifiedAnnotation<'hir> {
166     fn pre(&self, s: &mut pprust::State<'_>, node: pprust::AnnNode<'_>) {
167         if let pprust::AnnNode::Expr(_) = node {
168             s.popen();
169         }
170     }
171     fn post(&self, s: &mut pprust::State<'_>, node: pprust::AnnNode<'_>) {
172         match node {
173             pprust::AnnNode::Crate(_) | pprust::AnnNode::Ident(_) | pprust::AnnNode::Name(_) => {}
174
175             pprust::AnnNode::Item(item) => {
176                 s.s.space();
177                 s.synth_comment(item.id.to_string())
178             }
179             pprust::AnnNode::SubItem(id) => {
180                 s.s.space();
181                 s.synth_comment(id.to_string())
182             }
183             pprust::AnnNode::Block(blk) => {
184                 s.s.space();
185                 s.synth_comment(format!("block {}", blk.id))
186             }
187             pprust::AnnNode::Expr(expr) => {
188                 s.s.space();
189                 s.synth_comment(expr.id.to_string());
190                 s.pclose()
191             }
192             pprust::AnnNode::Pat(pat) => {
193                 s.s.space();
194                 s.synth_comment(format!("pat {}", pat.id));
195             }
196         }
197     }
198 }
199
200 impl<'hir> HirPrinterSupport<'hir> for IdentifiedAnnotation<'hir> {
201     fn sess(&self) -> &Session {
202         self.sess
203     }
204
205     fn hir_map(&self) -> Option<hir_map::Map<'hir>> {
206         self.tcx.map(|tcx| tcx.hir())
207     }
208
209     fn pp_ann(&self) -> &dyn pprust_hir::PpAnn {
210         self
211     }
212 }
213
214 impl<'hir> pprust_hir::PpAnn for IdentifiedAnnotation<'hir> {
215     fn nested(&self, state: &mut pprust_hir::State<'_>, nested: pprust_hir::Nested) {
216         if let Some(ref tcx) = self.tcx {
217             pprust_hir::PpAnn::nested(&(&tcx.hir() as &dyn hir::intravisit::Map<'_>), state, nested)
218         }
219     }
220     fn pre(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) {
221         if let pprust_hir::AnnNode::Expr(_) = node {
222             s.popen();
223         }
224     }
225     fn post(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) {
226         match node {
227             pprust_hir::AnnNode::Name(_) => {}
228             pprust_hir::AnnNode::Item(item) => {
229                 s.s.space();
230                 s.synth_comment(format!("hir_id: {}", item.hir_id()));
231             }
232             pprust_hir::AnnNode::SubItem(id) => {
233                 s.s.space();
234                 s.synth_comment(id.to_string());
235             }
236             pprust_hir::AnnNode::Block(blk) => {
237                 s.s.space();
238                 s.synth_comment(format!("block hir_id: {}", blk.hir_id));
239             }
240             pprust_hir::AnnNode::Expr(expr) => {
241                 s.s.space();
242                 s.synth_comment(format!("expr hir_id: {}", expr.hir_id));
243                 s.pclose();
244             }
245             pprust_hir::AnnNode::Pat(pat) => {
246                 s.s.space();
247                 s.synth_comment(format!("pat hir_id: {}", pat.hir_id));
248             }
249             pprust_hir::AnnNode::Arm(arm) => {
250                 s.s.space();
251                 s.synth_comment(format!("arm hir_id: {}", arm.hir_id));
252             }
253         }
254     }
255 }
256
257 struct HygieneAnnotation<'a> {
258     sess: &'a Session,
259 }
260
261 impl<'a> PrinterSupport for HygieneAnnotation<'a> {
262     fn sess(&self) -> &Session {
263         self.sess
264     }
265
266     fn pp_ann(&self) -> &dyn pprust::PpAnn {
267         self
268     }
269 }
270
271 impl<'a> pprust::PpAnn for HygieneAnnotation<'a> {
272     fn post(&self, s: &mut pprust::State<'_>, node: pprust::AnnNode<'_>) {
273         match node {
274             pprust::AnnNode::Ident(&Ident { name, span }) => {
275                 s.s.space();
276                 s.synth_comment(format!("{}{:?}", name.as_u32(), span.ctxt()))
277             }
278             pprust::AnnNode::Name(&name) => {
279                 s.s.space();
280                 s.synth_comment(name.as_u32().to_string())
281             }
282             pprust::AnnNode::Crate(_) => {
283                 s.s.hardbreak();
284                 let verbose = self.sess.verbose();
285                 s.synth_comment(rustc_span::hygiene::debug_hygiene_data(verbose));
286                 s.s.hardbreak_if_not_bol();
287             }
288             _ => {}
289         }
290     }
291 }
292
293 struct TypedAnnotation<'tcx> {
294     tcx: TyCtxt<'tcx>,
295     maybe_typeck_results: Cell<Option<&'tcx ty::TypeckResults<'tcx>>>,
296 }
297
298 impl<'tcx> HirPrinterSupport<'tcx> for TypedAnnotation<'tcx> {
299     fn sess(&self) -> &Session {
300         self.tcx.sess
301     }
302
303     fn hir_map(&self) -> Option<hir_map::Map<'tcx>> {
304         Some(self.tcx.hir())
305     }
306
307     fn pp_ann(&self) -> &dyn pprust_hir::PpAnn {
308         self
309     }
310 }
311
312 impl<'tcx> pprust_hir::PpAnn for TypedAnnotation<'tcx> {
313     fn nested(&self, state: &mut pprust_hir::State<'_>, nested: pprust_hir::Nested) {
314         let old_maybe_typeck_results = self.maybe_typeck_results.get();
315         if let pprust_hir::Nested::Body(id) = nested {
316             self.maybe_typeck_results.set(Some(self.tcx.typeck_body(id)));
317         }
318         let pp_ann = &(&self.tcx.hir() as &dyn hir::intravisit::Map<'_>);
319         pprust_hir::PpAnn::nested(pp_ann, state, nested);
320         self.maybe_typeck_results.set(old_maybe_typeck_results);
321     }
322     fn pre(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) {
323         if let pprust_hir::AnnNode::Expr(_) = node {
324             s.popen();
325         }
326     }
327     fn post(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) {
328         if let pprust_hir::AnnNode::Expr(expr) = node {
329             let typeck_results = self.maybe_typeck_results.get().or_else(|| {
330                 self.tcx
331                     .hir()
332                     .maybe_body_owned_by(expr.hir_id.owner.def_id)
333                     .map(|body_id| self.tcx.typeck_body(body_id))
334             });
335
336             if let Some(typeck_results) = typeck_results {
337                 s.s.space();
338                 s.s.word("as");
339                 s.s.space();
340                 s.s.word(typeck_results.expr_ty(expr).to_string());
341             }
342
343             s.pclose();
344         }
345     }
346 }
347
348 fn get_source(input: &Input, sess: &Session) -> (String, FileName) {
349     let src_name = input.source_name();
350     let src = String::clone(
351         sess.source_map()
352             .get_source_file(&src_name)
353             .expect("get_source_file")
354             .src
355             .as_ref()
356             .expect("src"),
357     );
358     (src, src_name)
359 }
360
361 fn write_or_print(out: &str, ofile: Option<&Path>, sess: &Session) {
362     match ofile {
363         None => print!("{}", out),
364         Some(p) => {
365             if let Err(e) = std::fs::write(p, out) {
366                 sess.emit_fatal(UnprettyDumpFail {
367                     path: p.display().to_string(),
368                     err: e.to_string(),
369                 });
370             }
371         }
372     }
373 }
374
375 pub fn print_after_parsing(
376     sess: &Session,
377     input: &Input,
378     krate: &ast::Crate,
379     ppm: PpMode,
380     ofile: Option<&Path>,
381 ) {
382     let (src, src_name) = get_source(input, sess);
383
384     let out = match ppm {
385         Source(s) => {
386             // Silently ignores an identified node.
387             call_with_pp_support(&s, sess, None, move |annotation| {
388                 debug!("pretty printing source code {:?}", s);
389                 let sess = annotation.sess();
390                 let parse = &sess.parse_sess;
391                 pprust::print_crate(
392                     sess.source_map(),
393                     krate,
394                     src_name,
395                     src,
396                     annotation.pp_ann(),
397                     false,
398                     parse.edition,
399                     &sess.parse_sess.attr_id_generator,
400                 )
401             })
402         }
403         AstTree(PpAstTreeMode::Normal) => {
404             debug!("pretty printing AST tree");
405             format!("{:#?}", krate)
406         }
407         _ => unreachable!(),
408     };
409
410     write_or_print(&out, ofile, sess);
411 }
412
413 pub fn print_after_hir_lowering<'tcx>(
414     tcx: TyCtxt<'tcx>,
415     input: &Input,
416     krate: &ast::Crate,
417     ppm: PpMode,
418     ofile: Option<&Path>,
419 ) {
420     if ppm.needs_analysis() {
421         abort_on_err(print_with_analysis(tcx, ppm, ofile), tcx.sess);
422         return;
423     }
424
425     let (src, src_name) = get_source(input, tcx.sess);
426
427     let out = match ppm {
428         Source(s) => {
429             // Silently ignores an identified node.
430             call_with_pp_support(&s, tcx.sess, Some(tcx), move |annotation| {
431                 debug!("pretty printing source code {:?}", s);
432                 let sess = annotation.sess();
433                 let parse = &sess.parse_sess;
434                 pprust::print_crate(
435                     sess.source_map(),
436                     krate,
437                     src_name,
438                     src,
439                     annotation.pp_ann(),
440                     true,
441                     parse.edition,
442                     &sess.parse_sess.attr_id_generator,
443                 )
444             })
445         }
446
447         AstTree(PpAstTreeMode::Expanded) => {
448             debug!("pretty-printing expanded AST");
449             format!("{:#?}", krate)
450         }
451
452         Hir(s) => call_with_pp_support_hir(&s, tcx, move |annotation, hir_map| {
453             debug!("pretty printing HIR {:?}", s);
454             let sess = annotation.sess();
455             let sm = sess.source_map();
456             let attrs = |id| hir_map.attrs(id);
457             pprust_hir::print_crate(
458                 sm,
459                 hir_map.root_module(),
460                 src_name,
461                 src,
462                 &attrs,
463                 annotation.pp_ann(),
464             )
465         }),
466
467         HirTree => {
468             call_with_pp_support_hir(&PpHirMode::Normal, tcx, move |_annotation, hir_map| {
469                 debug!("pretty printing HIR tree");
470                 format!("{:#?}", hir_map.krate())
471             })
472         }
473
474         _ => unreachable!(),
475     };
476
477     write_or_print(&out, ofile, tcx.sess);
478 }
479
480 // In an ideal world, this would be a public function called by the driver after
481 // analysis is performed. However, we want to call `phase_3_run_analysis_passes`
482 // with a different callback than the standard driver, so that isn't easy.
483 // Instead, we call that function ourselves.
484 fn print_with_analysis(
485     tcx: TyCtxt<'_>,
486     ppm: PpMode,
487     ofile: Option<&Path>,
488 ) -> Result<(), ErrorGuaranteed> {
489     tcx.analysis(())?;
490     let out = match ppm {
491         Mir => {
492             let mut out = Vec::new();
493             write_mir_pretty(tcx, None, &mut out).unwrap();
494             String::from_utf8(out).unwrap()
495         }
496
497         MirCFG => {
498             let mut out = Vec::new();
499             write_mir_graphviz(tcx, None, &mut out).unwrap();
500             String::from_utf8(out).unwrap()
501         }
502
503         ThirTree => {
504             let mut out = String::new();
505             abort_on_err(rustc_typeck::check_crate(tcx), tcx.sess);
506             debug!("pretty printing THIR tree");
507             for did in tcx.hir().body_owners() {
508                 let _ = writeln!(
509                     out,
510                     "{:?}:\n{}\n",
511                     did,
512                     tcx.thir_tree(ty::WithOptConstParam::unknown(did))
513                 );
514             }
515             out
516         }
517
518         _ => unreachable!(),
519     };
520
521     write_or_print(&out, ofile, tcx.sess);
522
523     Ok(())
524 }