rustc_driver_impl/
pretty.rs

1//! The various pretty-printing routines.
2
3use std::cell::Cell;
4use std::fmt::Write;
5
6use rustc_ast_pretty::pprust as pprust_ast;
7use rustc_middle::bug;
8use rustc_middle::mir::{write_mir_graphviz, write_mir_pretty};
9use rustc_middle::ty::{self, TyCtxt};
10use rustc_mir_build::thir::print::{thir_flat, thir_tree};
11use rustc_session::Session;
12use rustc_session::config::{OutFileName, PpHirMode, PpMode, PpSourceMode};
13use rustc_smir::rustc_internal::pretty::write_smir_pretty;
14use rustc_span::{FileName, Ident};
15use tracing::debug;
16use {rustc_ast as ast, rustc_hir_pretty as pprust_hir};
17
18pub use self::PpMode::*;
19pub use self::PpSourceMode::*;
20
21struct AstNoAnn;
22
23impl pprust_ast::PpAnn for AstNoAnn {}
24
25struct AstIdentifiedAnn;
26
27impl pprust_ast::PpAnn for AstIdentifiedAnn {
28    fn pre(&self, s: &mut pprust_ast::State<'_>, node: pprust_ast::AnnNode<'_>) {
29        if let pprust_ast::AnnNode::Expr(_) = node {
30            s.popen();
31        }
32    }
33
34    fn post(&self, s: &mut pprust_ast::State<'_>, node: pprust_ast::AnnNode<'_>) {
35        match node {
36            pprust_ast::AnnNode::Crate(_)
37            | pprust_ast::AnnNode::Ident(_)
38            | pprust_ast::AnnNode::Name(_) => {}
39
40            pprust_ast::AnnNode::Item(item) => {
41                s.s.space();
42                s.synth_comment(item.id.to_string())
43            }
44            pprust_ast::AnnNode::SubItem(id) => {
45                s.s.space();
46                s.synth_comment(id.to_string())
47            }
48            pprust_ast::AnnNode::Block(blk) => {
49                s.s.space();
50                s.synth_comment(format!("block {}", blk.id))
51            }
52            pprust_ast::AnnNode::Expr(expr) => {
53                s.s.space();
54                s.synth_comment(expr.id.to_string());
55                s.pclose()
56            }
57            pprust_ast::AnnNode::Pat(pat) => {
58                s.s.space();
59                s.synth_comment(format!("pat {}", pat.id));
60            }
61        }
62    }
63}
64
65struct HirIdentifiedAnn<'tcx> {
66    tcx: TyCtxt<'tcx>,
67}
68
69impl<'tcx> pprust_hir::PpAnn for HirIdentifiedAnn<'tcx> {
70    fn nested(&self, state: &mut pprust_hir::State<'_>, nested: pprust_hir::Nested) {
71        self.tcx.nested(state, nested)
72    }
73
74    fn pre(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) {
75        if let pprust_hir::AnnNode::Expr(_) = node {
76            s.popen();
77        }
78    }
79
80    fn post(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) {
81        match node {
82            pprust_hir::AnnNode::Name(_) => {}
83            pprust_hir::AnnNode::Item(item) => {
84                s.s.space();
85                s.synth_comment(format!("hir_id: {}", item.hir_id()));
86            }
87            pprust_hir::AnnNode::SubItem(id) => {
88                s.s.space();
89                s.synth_comment(id.to_string());
90            }
91            pprust_hir::AnnNode::Block(blk) => {
92                s.s.space();
93                s.synth_comment(format!("block hir_id: {}", blk.hir_id));
94            }
95            pprust_hir::AnnNode::Expr(expr) => {
96                s.s.space();
97                s.synth_comment(format!("expr hir_id: {}", expr.hir_id));
98                s.pclose();
99            }
100            pprust_hir::AnnNode::Pat(pat) => {
101                s.s.space();
102                s.synth_comment(format!("pat hir_id: {}", pat.hir_id));
103            }
104            pprust_hir::AnnNode::TyPat(pat) => {
105                s.s.space();
106                s.synth_comment(format!("ty pat hir_id: {}", pat.hir_id));
107            }
108            pprust_hir::AnnNode::Arm(arm) => {
109                s.s.space();
110                s.synth_comment(format!("arm hir_id: {}", arm.hir_id));
111            }
112        }
113    }
114}
115
116struct AstHygieneAnn<'a> {
117    sess: &'a Session,
118}
119
120impl<'a> pprust_ast::PpAnn for AstHygieneAnn<'a> {
121    fn post(&self, s: &mut pprust_ast::State<'_>, node: pprust_ast::AnnNode<'_>) {
122        match node {
123            pprust_ast::AnnNode::Ident(&Ident { name, span }) => {
124                s.s.space();
125                s.synth_comment(format!("{}{:?}", name.as_u32(), span.ctxt()))
126            }
127            pprust_ast::AnnNode::Name(&name) => {
128                s.s.space();
129                s.synth_comment(name.as_u32().to_string())
130            }
131            pprust_ast::AnnNode::Crate(_) => {
132                s.s.hardbreak();
133                let verbose = self.sess.verbose_internals();
134                s.synth_comment(rustc_span::hygiene::debug_hygiene_data(verbose));
135                s.s.hardbreak_if_not_bol();
136            }
137            _ => {}
138        }
139    }
140}
141
142struct HirTypedAnn<'tcx> {
143    tcx: TyCtxt<'tcx>,
144    maybe_typeck_results: Cell<Option<&'tcx ty::TypeckResults<'tcx>>>,
145}
146
147impl<'tcx> pprust_hir::PpAnn for HirTypedAnn<'tcx> {
148    fn nested(&self, state: &mut pprust_hir::State<'_>, nested: pprust_hir::Nested) {
149        let old_maybe_typeck_results = self.maybe_typeck_results.get();
150        if let pprust_hir::Nested::Body(id) = nested {
151            self.maybe_typeck_results.set(Some(self.tcx.typeck_body(id)));
152        }
153        self.tcx.nested(state, nested);
154        self.maybe_typeck_results.set(old_maybe_typeck_results);
155    }
156
157    fn pre(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) {
158        if let pprust_hir::AnnNode::Expr(_) = node {
159            s.popen();
160        }
161    }
162
163    fn post(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) {
164        if let pprust_hir::AnnNode::Expr(expr) = node {
165            let typeck_results = self.maybe_typeck_results.get().or_else(|| {
166                self.tcx
167                    .hir_maybe_body_owned_by(expr.hir_id.owner.def_id)
168                    .map(|body_id| self.tcx.typeck_body(body_id.id()))
169            });
170
171            if let Some(typeck_results) = typeck_results {
172                s.s.space();
173                s.s.word("as");
174                s.s.space();
175                s.s.word(typeck_results.expr_ty(expr).to_string());
176            }
177
178            s.pclose();
179        }
180    }
181}
182
183fn get_source(sess: &Session) -> (String, FileName) {
184    let src_name = sess.io.input.source_name();
185    let src = String::clone(
186        sess.source_map()
187            .get_source_file(&src_name)
188            .expect("get_source_file")
189            .src
190            .as_ref()
191            .expect("src"),
192    );
193    (src, src_name)
194}
195
196fn write_or_print(out: &str, sess: &Session) {
197    sess.io.output_file.as_ref().unwrap_or(&OutFileName::Stdout).overwrite(out, sess);
198}
199
200// Extra data for pretty-printing, the form of which depends on what kind of
201// pretty-printing we are doing.
202pub enum PrintExtra<'tcx> {
203    AfterParsing { krate: &'tcx ast::Crate },
204    NeedsAstMap { tcx: TyCtxt<'tcx> },
205}
206
207impl<'tcx> PrintExtra<'tcx> {
208    fn with_krate<F, R>(&self, f: F) -> R
209    where
210        F: FnOnce(&ast::Crate) -> R,
211    {
212        match self {
213            PrintExtra::AfterParsing { krate, .. } => f(krate),
214            PrintExtra::NeedsAstMap { tcx } => f(&tcx.resolver_for_lowering().borrow().1),
215        }
216    }
217
218    fn tcx(&self) -> TyCtxt<'tcx> {
219        match self {
220            PrintExtra::AfterParsing { .. } => bug!("PrintExtra::tcx"),
221            PrintExtra::NeedsAstMap { tcx } => *tcx,
222        }
223    }
224}
225
226pub fn print<'tcx>(sess: &Session, ppm: PpMode, ex: PrintExtra<'tcx>) {
227    if ppm.needs_analysis() {
228        ex.tcx().ensure_ok().analysis(());
229    }
230
231    let (src, src_name) = get_source(sess);
232
233    let out = match ppm {
234        Source(s) => {
235            debug!("pretty printing source code {:?}", s);
236            let annotation: Box<dyn pprust_ast::PpAnn> = match s {
237                Normal => Box::new(AstNoAnn),
238                Expanded => Box::new(AstNoAnn),
239                Identified => Box::new(AstIdentifiedAnn),
240                ExpandedIdentified => Box::new(AstIdentifiedAnn),
241                ExpandedHygiene => Box::new(AstHygieneAnn { sess }),
242            };
243            let psess = &sess.psess;
244            let is_expanded = ppm.needs_ast_map();
245            ex.with_krate(|krate| {
246                pprust_ast::print_crate(
247                    sess.source_map(),
248                    krate,
249                    src_name,
250                    src,
251                    &*annotation,
252                    is_expanded,
253                    psess.edition,
254                    &sess.psess.attr_id_generator,
255                )
256            })
257        }
258        AstTree => {
259            debug!("pretty printing AST tree");
260            ex.with_krate(|krate| format!("{krate:#?}"))
261        }
262        AstTreeExpanded => {
263            debug!("pretty-printing expanded AST");
264            format!("{:#?}", ex.tcx().resolver_for_lowering().borrow().1)
265        }
266        Hir(s) => {
267            debug!("pretty printing HIR {:?}", s);
268            let tcx = ex.tcx();
269            let f = |annotation: &dyn pprust_hir::PpAnn| {
270                let sm = sess.source_map();
271                let attrs = |id| tcx.hir_attrs(id);
272                pprust_hir::print_crate(
273                    sm,
274                    tcx.hir_root_module(),
275                    src_name,
276                    src,
277                    &attrs,
278                    annotation,
279                )
280            };
281            match s {
282                PpHirMode::Normal => f(&tcx),
283                PpHirMode::Identified => {
284                    let annotation = HirIdentifiedAnn { tcx };
285                    f(&annotation)
286                }
287                PpHirMode::Typed => {
288                    let annotation = HirTypedAnn { tcx, maybe_typeck_results: Cell::new(None) };
289                    tcx.dep_graph.with_ignore(|| f(&annotation))
290                }
291            }
292        }
293        HirTree => {
294            debug!("pretty printing HIR tree");
295            format!("{:#?}", ex.tcx().hir_crate(()))
296        }
297        Mir => {
298            let mut out = Vec::new();
299            write_mir_pretty(ex.tcx(), None, &mut out).unwrap();
300            String::from_utf8(out).unwrap()
301        }
302        MirCFG => {
303            let mut out = Vec::new();
304            write_mir_graphviz(ex.tcx(), None, &mut out).unwrap();
305            String::from_utf8(out).unwrap()
306        }
307        StableMir => {
308            let mut out = Vec::new();
309            write_smir_pretty(ex.tcx(), &mut out).unwrap();
310            String::from_utf8(out).unwrap()
311        }
312        ThirTree => {
313            let tcx = ex.tcx();
314            let mut out = String::new();
315            rustc_hir_analysis::check_crate(tcx);
316            tcx.dcx().abort_if_errors();
317            debug!("pretty printing THIR tree");
318            for did in tcx.hir_body_owners() {
319                let _ = writeln!(out, "{:?}:\n{}\n", did, thir_tree(tcx, did));
320            }
321            out
322        }
323        ThirFlat => {
324            let tcx = ex.tcx();
325            let mut out = String::new();
326            rustc_hir_analysis::check_crate(tcx);
327            tcx.dcx().abort_if_errors();
328            debug!("pretty printing THIR flat");
329            for did in tcx.hir_body_owners() {
330                let _ = writeln!(out, "{:?}:\n{}\n", did, thir_flat(tcx, did));
331            }
332            out
333        }
334    };
335
336    write_or_print(&out, sess);
337}