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