]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_driver/src/pretty.rs
New upstream version 1.61.0+dfsg1
[rustc.git] / compiler / rustc_driver / src / pretty.rs
CommitLineData
0731742a 1//! The various pretty-printing routines.
1a4d82fc 2
3dfed10e 3use rustc_ast as ast;
74b04a01 4use rustc_ast_pretty::pprust;
5e7ed085 5use rustc_errors::ErrorGuaranteed;
dfeec247 6use rustc_hir as hir;
ba9703b0
XL
7use rustc_hir_pretty as pprust_hir;
8use rustc_middle::hir::map as hir_map;
c295e0f8 9use rustc_middle::mir::{write_mir_graphviz, write_mir_pretty};
ba9703b0 10use rustc_middle::ty::{self, TyCtxt};
6a06907d 11use rustc_session::config::{Input, PpAstTreeMode, PpHirMode, PpMode, PpSourceMode};
ba9703b0 12use rustc_session::Session;
f9f354fc 13use rustc_span::symbol::Ident;
dfeec247 14use rustc_span::FileName;
1a4d82fc 15
32a655c1 16use std::cell::Cell;
94222f64 17use std::fmt::Write;
a7813a04 18use std::path::Path;
1a4d82fc 19
0731742a 20pub use self::PpMode::*;
dfeec247 21pub use self::PpSourceMode::*;
532ac7d7
XL
22use crate::abort_on_err;
23
1a4d82fc
JJ
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`.
1a4d82fc 33
60c5eb7d
XL
34/// Constructs a `PrinterSupport` object and passes it to `f`.
35fn call_with_pp_support<'tcx, A, F>(
36 ppmode: &PpSourceMode,
37 sess: &'tcx Session,
38 tcx: Option<TyCtxt<'tcx>>,
39 f: F,
40) -> A
41where
42 F: FnOnce(&dyn PrinterSupport) -> A,
43{
44 match *ppmode {
5e7ed085 45 Normal | Expanded => {
dfeec247 46 let annotation = NoAnn { sess, tcx };
60c5eb7d
XL
47 f(&annotation)
48 }
1a4d82fc 49
6a06907d 50 Identified | ExpandedIdentified => {
dfeec247 51 let annotation = IdentifiedAnnotation { sess, tcx };
60c5eb7d
XL
52 f(&annotation)
53 }
6a06907d 54 ExpandedHygiene => {
dfeec247 55 let annotation = HygieneAnnotation { sess };
60c5eb7d
XL
56 f(&annotation)
57 }
60c5eb7d
XL
58 }
59}
6a06907d 60fn call_with_pp_support_hir<A, F>(ppmode: &PpHirMode, tcx: TyCtxt<'_>, f: F) -> A
60c5eb7d 61where
3c0e092e 62 F: FnOnce(&dyn HirPrinterSupport<'_>, hir_map::Map<'_>) -> A,
60c5eb7d
XL
63{
64 match *ppmode {
6a06907d 65 PpHirMode::Normal => {
dfeec247 66 let annotation = NoAnn { sess: tcx.sess, tcx: Some(tcx) };
3c0e092e 67 f(&annotation, tcx.hir())
e9174d1e 68 }
e9174d1e 69
6a06907d 70 PpHirMode::Identified => {
dfeec247 71 let annotation = IdentifiedAnnotation { sess: tcx.sess, tcx: Some(tcx) };
3c0e092e 72 f(&annotation, tcx.hir())
60c5eb7d 73 }
6a06907d 74 PpHirMode::Typed => {
17df50a5 75 abort_on_err(tcx.analysis(()), tcx.sess);
60c5eb7d 76
3dfed10e 77 let annotation = TypedAnnotation { tcx, maybe_typeck_results: Cell::new(None) };
3c0e092e 78 tcx.dep_graph.with_ignore(|| f(&annotation, tcx.hir()))
1a4d82fc
JJ
79 }
80 }
81}
82
32a655c1 83trait PrinterSupport: pprust::PpAnn {
1a4d82fc
JJ
84 /// Provides a uniform interface for re-extracting a reference to a
85 /// `Session` from a value that now owns it.
416331ca 86 fn sess(&self) -> &Session;
1a4d82fc 87
1a4d82fc
JJ
88 /// Produces the pretty-print annotation object.
89 ///
90 /// (Rust does not yet support upcasting from a trait object to
c295e0f8 91 /// an object for one of its supertraits.)
ba9703b0 92 fn pp_ann(&self) -> &dyn pprust::PpAnn;
1a4d82fc
JJ
93}
94
32a655c1 95trait HirPrinterSupport<'hir>: pprust_hir::PpAnn {
e9174d1e
SL
96 /// Provides a uniform interface for re-extracting a reference to a
97 /// `Session` from a value that now owns it.
416331ca 98 fn sess(&self) -> &Session;
e9174d1e
SL
99
100 /// Provides a uniform interface for re-extracting a reference to an
101 /// `hir_map::Map` from a value that now owns it.
ba9703b0 102 fn hir_map(&self) -> Option<hir_map::Map<'hir>>;
e9174d1e
SL
103
104 /// Produces the pretty-print annotation object.
105 ///
106 /// (Rust does not yet support upcasting from a trait object to
c295e0f8 107 /// an object for one of its supertraits.)
ba9703b0 108 fn pp_ann(&self) -> &dyn pprust_hir::PpAnn;
e9174d1e
SL
109}
110
32a655c1
SL
111struct NoAnn<'hir> {
112 sess: &'hir Session,
dc9dc135 113 tcx: Option<TyCtxt<'hir>>,
1a4d82fc
JJ
114}
115
32a655c1 116impl<'hir> PrinterSupport for NoAnn<'hir> {
416331ca 117 fn sess(&self) -> &Session {
92a42be0
SL
118 self.sess
119 }
1a4d82fc 120
ba9703b0 121 fn pp_ann(&self) -> &dyn pprust::PpAnn {
92a42be0
SL
122 self
123 }
1a4d82fc
JJ
124}
125
32a655c1 126impl<'hir> HirPrinterSupport<'hir> for NoAnn<'hir> {
416331ca 127 fn sess(&self) -> &Session {
92a42be0
SL
128 self.sess
129 }
e9174d1e 130
ba9703b0
XL
131 fn hir_map(&self) -> Option<hir_map::Map<'hir>> {
132 self.tcx.map(|tcx| tcx.hir())
e9174d1e
SL
133 }
134
ba9703b0 135 fn pp_ann(&self) -> &dyn pprust_hir::PpAnn {
92a42be0
SL
136 self
137 }
e9174d1e
SL
138}
139
32a655c1
SL
140impl<'hir> pprust::PpAnn for NoAnn<'hir> {}
141impl<'hir> pprust_hir::PpAnn for NoAnn<'hir> {
416331ca 142 fn nested(&self, state: &mut pprust_hir::State<'_>, nested: pprust_hir::Nested) {
532ac7d7 143 if let Some(tcx) = self.tcx {
ba9703b0 144 pprust_hir::PpAnn::nested(&(&tcx.hir() as &dyn hir::intravisit::Map<'_>), state, nested)
32a655c1
SL
145 }
146 }
147}
1a4d82fc 148
32a655c1
SL
149struct IdentifiedAnnotation<'hir> {
150 sess: &'hir Session,
dc9dc135 151 tcx: Option<TyCtxt<'hir>>,
1a4d82fc
JJ
152}
153
32a655c1 154impl<'hir> PrinterSupport for IdentifiedAnnotation<'hir> {
416331ca 155 fn sess(&self) -> &Session {
92a42be0
SL
156 self.sess
157 }
1a4d82fc 158
ba9703b0 159 fn pp_ann(&self) -> &dyn pprust::PpAnn {
92a42be0
SL
160 self
161 }
1a4d82fc
JJ
162}
163
32a655c1 164impl<'hir> pprust::PpAnn for IdentifiedAnnotation<'hir> {
416331ca 165 fn pre(&self, s: &mut pprust::State<'_>, node: pprust::AnnNode<'_>) {
ba9703b0
XL
166 if let pprust::AnnNode::Expr(_) = node {
167 s.popen();
1a4d82fc
JJ
168 }
169 }
416331ca 170 fn post(&self, s: &mut pprust::State<'_>, node: pprust::AnnNode<'_>) {
1a4d82fc 171 match node {
dfeec247 172 pprust::AnnNode::Crate(_) | pprust::AnnNode::Ident(_) | pprust::AnnNode::Name(_) => {}
1a4d82fc 173
b7449926 174 pprust::AnnNode::Item(item) => {
416331ca 175 s.s.space();
1a4d82fc
JJ
176 s.synth_comment(item.id.to_string())
177 }
b7449926 178 pprust::AnnNode::SubItem(id) => {
416331ca 179 s.s.space();
c34b1796
AL
180 s.synth_comment(id.to_string())
181 }
b7449926 182 pprust::AnnNode::Block(blk) => {
416331ca 183 s.s.space();
1a4d82fc
JJ
184 s.synth_comment(format!("block {}", blk.id))
185 }
b7449926 186 pprust::AnnNode::Expr(expr) => {
416331ca
XL
187 s.s.space();
188 s.synth_comment(expr.id.to_string());
1a4d82fc
JJ
189 s.pclose()
190 }
b7449926 191 pprust::AnnNode::Pat(pat) => {
416331ca
XL
192 s.s.space();
193 s.synth_comment(format!("pat {}", pat.id));
1a4d82fc
JJ
194 }
195 }
196 }
197}
198
32a655c1 199impl<'hir> HirPrinterSupport<'hir> for IdentifiedAnnotation<'hir> {
416331ca 200 fn sess(&self) -> &Session {
92a42be0
SL
201 self.sess
202 }
e9174d1e 203
ba9703b0
XL
204 fn hir_map(&self) -> Option<hir_map::Map<'hir>> {
205 self.tcx.map(|tcx| tcx.hir())
e9174d1e
SL
206 }
207
ba9703b0 208 fn pp_ann(&self) -> &dyn pprust_hir::PpAnn {
92a42be0
SL
209 self
210 }
e9174d1e
SL
211}
212
32a655c1 213impl<'hir> pprust_hir::PpAnn for IdentifiedAnnotation<'hir> {
416331ca 214 fn nested(&self, state: &mut pprust_hir::State<'_>, nested: pprust_hir::Nested) {
532ac7d7 215 if let Some(ref tcx) = self.tcx {
ba9703b0 216 pprust_hir::PpAnn::nested(&(&tcx.hir() as &dyn hir::intravisit::Map<'_>), state, nested)
32a655c1
SL
217 }
218 }
416331ca 219 fn pre(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) {
ba9703b0
XL
220 if let pprust_hir::AnnNode::Expr(_) = node {
221 s.popen();
e9174d1e
SL
222 }
223 }
416331ca 224 fn post(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) {
e9174d1e 225 match node {
dfeec247 226 pprust_hir::AnnNode::Name(_) => {}
b7449926 227 pprust_hir::AnnNode::Item(item) => {
416331ca 228 s.s.space();
6a06907d 229 s.synth_comment(format!("hir_id: {}", item.hir_id()));
e9174d1e 230 }
b7449926 231 pprust_hir::AnnNode::SubItem(id) => {
416331ca
XL
232 s.s.space();
233 s.synth_comment(id.to_string());
e9174d1e 234 }
b7449926 235 pprust_hir::AnnNode::Block(blk) => {
416331ca
XL
236 s.s.space();
237 s.synth_comment(format!("block hir_id: {}", blk.hir_id));
e9174d1e 238 }
b7449926 239 pprust_hir::AnnNode::Expr(expr) => {
416331ca
XL
240 s.s.space();
241 s.synth_comment(format!("expr hir_id: {}", expr.hir_id));
242 s.pclose();
e9174d1e 243 }
b7449926 244 pprust_hir::AnnNode::Pat(pat) => {
416331ca
XL
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));
e9174d1e
SL
251 }
252 }
253 }
254}
255
32a655c1 256struct HygieneAnnotation<'a> {
dfeec247 257 sess: &'a Session,
1a4d82fc
JJ
258}
259
32a655c1
SL
260impl<'a> PrinterSupport for HygieneAnnotation<'a> {
261 fn sess(&self) -> &Session {
92a42be0
SL
262 self.sess
263 }
1a4d82fc 264
8faf50e0 265 fn pp_ann(&self) -> &dyn pprust::PpAnn {
92a42be0
SL
266 self
267 }
1a4d82fc
JJ
268}
269
32a655c1 270impl<'a> pprust::PpAnn for HygieneAnnotation<'a> {
416331ca 271 fn post(&self, s: &mut pprust::State<'_>, node: pprust::AnnNode<'_>) {
1a4d82fc 272 match node {
f9f354fc 273 pprust::AnnNode::Ident(&Ident { name, span }) => {
416331ca 274 s.s.space();
83c7162d 275 s.synth_comment(format!("{}{:?}", name.as_u32(), span.ctxt()))
1a4d82fc 276 }
b7449926 277 pprust::AnnNode::Name(&name) => {
416331ca 278 s.s.space();
476ff2be 279 s.synth_comment(name.as_u32().to_string())
1a4d82fc 280 }
e1599b0c
XL
281 pprust::AnnNode::Crate(_) => {
282 s.s.hardbreak();
283 let verbose = self.sess.verbose();
dfeec247 284 s.synth_comment(rustc_span::hygiene::debug_hygiene_data(verbose));
e1599b0c
XL
285 s.s.hardbreak_if_not_bol();
286 }
416331ca 287 _ => {}
1a4d82fc
JJ
288 }
289 }
290}
291
f035d41b 292struct TypedAnnotation<'tcx> {
dc9dc135 293 tcx: TyCtxt<'tcx>,
3dfed10e 294 maybe_typeck_results: Cell<Option<&'tcx ty::TypeckResults<'tcx>>>,
1a4d82fc
JJ
295}
296
f035d41b 297impl<'tcx> HirPrinterSupport<'tcx> for TypedAnnotation<'tcx> {
416331ca 298 fn sess(&self) -> &Session {
c295e0f8 299 self.tcx.sess
92a42be0 300 }
1a4d82fc 301
ba9703b0
XL
302 fn hir_map(&self) -> Option<hir_map::Map<'tcx>> {
303 Some(self.tcx.hir())
1a4d82fc
JJ
304 }
305
ba9703b0 306 fn pp_ann(&self) -> &dyn pprust_hir::PpAnn {
92a42be0
SL
307 self
308 }
1a4d82fc
JJ
309}
310
f035d41b 311impl<'tcx> pprust_hir::PpAnn for TypedAnnotation<'tcx> {
416331ca 312 fn nested(&self, state: &mut pprust_hir::State<'_>, nested: pprust_hir::Nested) {
3dfed10e 313 let old_maybe_typeck_results = self.maybe_typeck_results.get();
32a655c1 314 if let pprust_hir::Nested::Body(id) = nested {
3dfed10e 315 self.maybe_typeck_results.set(Some(self.tcx.typeck_body(id)));
32a655c1 316 }
ba9703b0
XL
317 let pp_ann = &(&self.tcx.hir() as &dyn hir::intravisit::Map<'_>);
318 pprust_hir::PpAnn::nested(pp_ann, state, nested);
3dfed10e 319 self.maybe_typeck_results.set(old_maybe_typeck_results);
32a655c1 320 }
416331ca 321 fn pre(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) {
ba9703b0
XL
322 if let pprust_hir::AnnNode::Expr(_) = node {
323 s.popen();
1a4d82fc
JJ
324 }
325 }
416331ca 326 fn post(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) {
ba9703b0 327 if let pprust_hir::AnnNode::Expr(expr) = node {
136023e0
XL
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
ba9703b0 342 s.pclose();
1a4d82fc
JJ
343 }
344 }
345}
346
416331ca 347fn get_source(input: &Input, sess: &Session) -> (String, FileName) {
60c5eb7d 348 let src_name = input.source_name();
5869c6ff 349 let src = String::clone(
c295e0f8 350 sess.source_map()
5869c6ff
XL
351 .get_source_file(&src_name)
352 .expect("get_source_file")
353 .src
354 .as_ref()
355 .expect("src"),
356 );
a7813a04
XL
357 (src, src_name)
358}
359
6a06907d 360fn write_or_print(out: &str, ofile: Option<&Path>) {
a7813a04 361 match ofile {
6a06907d
XL
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 }
a7813a04
XL
368 }
369}
1a4d82fc 370
dfeec247
XL
371pub fn print_after_parsing(
372 sess: &Session,
373 input: &Input,
374 krate: &ast::Crate,
375 ppm: PpMode,
376 ofile: Option<&Path>,
377) {
a7813a04
XL
378 let (src, src_name) = get_source(input, sess);
379
6a06907d
XL
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!(),
a7813a04
XL
403 };
404
6a06907d 405 write_or_print(&out, ofile);
a7813a04
XL
406}
407
532ac7d7 408pub fn print_after_hir_lowering<'tcx>(
dc9dc135 409 tcx: TyCtxt<'tcx>,
532ac7d7
XL
410 input: &Input,
411 krate: &ast::Crate,
412 ppm: PpMode,
dc9dc135
XL
413 ofile: Option<&Path>,
414) {
a7813a04 415 if ppm.needs_analysis() {
dfeec247 416 abort_on_err(print_with_analysis(tcx, ppm, ofile), tcx.sess);
a7813a04
XL
417 return;
418 }
419
532ac7d7 420 let (src, src_name) = get_source(input, tcx.sess);
a7813a04 421
6a06907d
XL
422 let out = match ppm {
423 Source(s) => {
dfeec247 424 // Silently ignores an identified node.
dfeec247
XL
425 call_with_pp_support(&s, tcx.sess, Some(tcx), move |annotation| {
426 debug!("pretty printing source code {:?}", s);
427 let sess = annotation.sess();
74b04a01 428 let parse = &sess.parse_sess;
6a06907d 429 pprust::print_crate(
dfeec247 430 sess.source_map(),
dfeec247
XL
431 krate,
432 src_name,
433 src,
434 annotation.pp_ann(),
435 true,
74b04a01 436 parse.edition,
dfeec247
XL
437 )
438 })
439 }
e9174d1e 440
6a06907d
XL
441 AstTree(PpAstTreeMode::Expanded) => {
442 debug!("pretty-printing expanded AST");
443 format!("{:#?}", krate)
dfeec247 444 }
ff7c6d11 445
3c0e092e 446 Hir(s) => call_with_pp_support_hir(&s, tcx, move |annotation, hir_map| {
6a06907d
XL
447 debug!("pretty printing HIR {:?}", s);
448 let sess = annotation.sess();
449 let sm = sess.source_map();
3c0e092e
XL
450 let attrs = |id| hir_map.attrs(id);
451 pprust_hir::print_crate(
452 sm,
453 hir_map.root_module(),
454 src_name,
455 src,
456 &attrs,
457 annotation.pp_ann(),
458 )
6a06907d
XL
459 }),
460
3c0e092e
XL
461 HirTree => {
462 call_with_pp_support_hir(&PpHirMode::Normal, tcx, move |_annotation, hir_map| {
463 debug!("pretty printing HIR tree");
464 format!("{:#?}", hir_map.krate())
465 })
466 }
6a06907d 467
dfeec247 468 _ => unreachable!(),
6a06907d 469 };
dfeec247 470
6a06907d 471 write_or_print(&out, ofile);
a7813a04
XL
472}
473
474// In an ideal world, this would be a public function called by the driver after
9fa01778 475// analysis is performed. However, we want to call `phase_3_run_analysis_passes`
a7813a04
XL
476// with a different callback than the standard driver, so that isn't easy.
477// Instead, we call that function ourselves.
416331ca
XL
478fn print_with_analysis(
479 tcx: TyCtxt<'_>,
532ac7d7 480 ppm: PpMode,
dc9dc135 481 ofile: Option<&Path>,
5e7ed085 482) -> Result<(), ErrorGuaranteed> {
17df50a5 483 tcx.analysis(())?;
cdc7bbd5
XL
484 let out = match ppm {
485 Mir => {
486 let mut out = Vec::new();
487 write_mir_pretty(tcx, None, &mut out).unwrap();
488 String::from_utf8(out).unwrap()
489 }
490
491 MirCFG => {
492 let mut out = Vec::new();
493 write_mir_graphviz(tcx, None, &mut out).unwrap();
494 String::from_utf8(out).unwrap()
495 }
496
497 ThirTree => {
94222f64
XL
498 let mut out = String::new();
499 abort_on_err(rustc_typeck::check_crate(tcx), tcx.sess);
500 debug!("pretty printing THIR tree");
c295e0f8 501 for did in tcx.hir().body_owners() {
94222f64
XL
502 let _ = writeln!(
503 out,
504 "{:?}:\n{}\n",
505 did,
506 tcx.thir_tree(ty::WithOptConstParam::unknown(did))
507 );
508 }
509 out
cdc7bbd5
XL
510 }
511
532ac7d7 512 _ => unreachable!(),
cdc7bbd5 513 };
c34b1796 514
cdc7bbd5 515 write_or_print(&out, ofile);
532ac7d7
XL
516
517 Ok(())
1a4d82fc 518}