]> git.lizzy.rs Git - rust.git/blob - src/librustc_driver/pretty.rs
Move the `krate` method to Hir and remove the Krate dep node
[rust.git] / src / librustc_driver / pretty.rs
1 //! The various pretty-printing routines.
2
3 use rustc::hir::map as hir_map;
4 use rustc::session::config::{Input, PpMode, PpSourceMode};
5 use rustc::session::Session;
6 use rustc::ty::{self, TyCtxt};
7 use rustc::util::common::ErrorReported;
8 use rustc_ast_pretty::pprust;
9 use rustc_hir as hir;
10 use rustc_hir::def_id::LOCAL_CRATE;
11 use rustc_hir::print as pprust_hir;
12 use rustc_mir::util::{write_mir_graphviz, write_mir_pretty};
13 use rustc_span::FileName;
14 use syntax::ast;
15
16 use std::cell::Cell;
17 use std::fs::File;
18 use std::io::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 // (The `use_once_payload` is working around the current lack of once
36 // functions in the compiler.)
37
38 /// Constructs a `PrinterSupport` object and passes it to `f`.
39 fn call_with_pp_support<'tcx, A, F>(
40     ppmode: &PpSourceMode,
41     sess: &'tcx Session,
42     tcx: Option<TyCtxt<'tcx>>,
43     f: F,
44 ) -> A
45 where
46     F: FnOnce(&dyn PrinterSupport) -> A,
47 {
48     match *ppmode {
49         PpmNormal | PpmEveryBodyLoops | PpmExpanded => {
50             let annotation = NoAnn { sess, tcx };
51             f(&annotation)
52         }
53
54         PpmIdentified | PpmExpandedIdentified => {
55             let annotation = IdentifiedAnnotation { sess, tcx };
56             f(&annotation)
57         }
58         PpmExpandedHygiene => {
59             let annotation = HygieneAnnotation { sess };
60             f(&annotation)
61         }
62         _ => panic!("Should use call_with_pp_support_hir"),
63     }
64 }
65 fn call_with_pp_support_hir<A, F>(ppmode: &PpSourceMode, tcx: TyCtxt<'_>, f: F) -> A
66 where
67     F: FnOnce(&dyn HirPrinterSupport<'_>, &hir::Crate<'_>) -> A,
68 {
69     match *ppmode {
70         PpmNormal => {
71             let annotation = NoAnn { sess: tcx.sess, tcx: Some(tcx) };
72             f(&annotation, tcx.hir().krate())
73         }
74
75         PpmIdentified => {
76             let annotation = IdentifiedAnnotation { sess: tcx.sess, tcx: Some(tcx) };
77             f(&annotation, tcx.hir().krate())
78         }
79         PpmTyped => {
80             abort_on_err(tcx.analysis(LOCAL_CRATE), tcx.sess);
81
82             let empty_tables = ty::TypeckTables::empty(None);
83             let annotation = TypedAnnotation { tcx, tables: Cell::new(&empty_tables) };
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<'a>(&'a self) -> &'a 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<'a>(&'a self) -> Option<&'a 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<'a>(&'a self) -> &'a 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<'a>(&'a self) -> &'a 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<'a>(&'a self) -> Option<&'a hir_map::Map<'hir>> {
146         self.tcx.map(|tcx| *tcx.hir())
147     }
148
149     fn pp_ann<'a>(&'a self) -> &'a 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(), 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<'a>(&'a self) -> &'a 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         match node {
181             pprust::AnnNode::Expr(_) => s.popen(),
182             _ => {}
183         }
184     }
185     fn post(&self, s: &mut pprust::State<'_>, node: pprust::AnnNode<'_>) {
186         match node {
187             pprust::AnnNode::Crate(_) | pprust::AnnNode::Ident(_) | pprust::AnnNode::Name(_) => {}
188
189             pprust::AnnNode::Item(item) => {
190                 s.s.space();
191                 s.synth_comment(item.id.to_string())
192             }
193             pprust::AnnNode::SubItem(id) => {
194                 s.s.space();
195                 s.synth_comment(id.to_string())
196             }
197             pprust::AnnNode::Block(blk) => {
198                 s.s.space();
199                 s.synth_comment(format!("block {}", blk.id))
200             }
201             pprust::AnnNode::Expr(expr) => {
202                 s.s.space();
203                 s.synth_comment(expr.id.to_string());
204                 s.pclose()
205             }
206             pprust::AnnNode::Pat(pat) => {
207                 s.s.space();
208                 s.synth_comment(format!("pat {}", pat.id));
209             }
210         }
211     }
212 }
213
214 impl<'hir> HirPrinterSupport<'hir> for IdentifiedAnnotation<'hir> {
215     fn sess(&self) -> &Session {
216         self.sess
217     }
218
219     fn hir_map<'a>(&'a self) -> Option<&'a hir_map::Map<'hir>> {
220         self.tcx.map(|tcx| *tcx.hir())
221     }
222
223     fn pp_ann<'a>(&'a self) -> &'a dyn pprust_hir::PpAnn {
224         self
225     }
226 }
227
228 impl<'hir> pprust_hir::PpAnn for IdentifiedAnnotation<'hir> {
229     fn nested(&self, state: &mut pprust_hir::State<'_>, nested: pprust_hir::Nested) {
230         if let Some(ref tcx) = self.tcx {
231             pprust_hir::PpAnn::nested(*tcx.hir(), state, nested)
232         }
233     }
234     fn pre(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) {
235         match node {
236             pprust_hir::AnnNode::Expr(_) => s.popen(),
237             _ => {}
238         }
239     }
240     fn post(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) {
241         match node {
242             pprust_hir::AnnNode::Name(_) => {}
243             pprust_hir::AnnNode::Item(item) => {
244                 s.s.space();
245                 s.synth_comment(format!("hir_id: {}", item.hir_id));
246             }
247             pprust_hir::AnnNode::SubItem(id) => {
248                 s.s.space();
249                 s.synth_comment(id.to_string());
250             }
251             pprust_hir::AnnNode::Block(blk) => {
252                 s.s.space();
253                 s.synth_comment(format!("block hir_id: {}", blk.hir_id));
254             }
255             pprust_hir::AnnNode::Expr(expr) => {
256                 s.s.space();
257                 s.synth_comment(format!("expr hir_id: {}", expr.hir_id));
258                 s.pclose();
259             }
260             pprust_hir::AnnNode::Pat(pat) => {
261                 s.s.space();
262                 s.synth_comment(format!("pat hir_id: {}", pat.hir_id));
263             }
264             pprust_hir::AnnNode::Arm(arm) => {
265                 s.s.space();
266                 s.synth_comment(format!("arm hir_id: {}", arm.hir_id));
267             }
268         }
269     }
270 }
271
272 struct HygieneAnnotation<'a> {
273     sess: &'a Session,
274 }
275
276 impl<'a> PrinterSupport for HygieneAnnotation<'a> {
277     fn sess(&self) -> &Session {
278         self.sess
279     }
280
281     fn pp_ann(&self) -> &dyn pprust::PpAnn {
282         self
283     }
284 }
285
286 impl<'a> pprust::PpAnn for HygieneAnnotation<'a> {
287     fn post(&self, s: &mut pprust::State<'_>, node: pprust::AnnNode<'_>) {
288         match node {
289             pprust::AnnNode::Ident(&ast::Ident { name, span }) => {
290                 s.s.space();
291                 s.synth_comment(format!("{}{:?}", name.as_u32(), span.ctxt()))
292             }
293             pprust::AnnNode::Name(&name) => {
294                 s.s.space();
295                 s.synth_comment(name.as_u32().to_string())
296             }
297             pprust::AnnNode::Crate(_) => {
298                 s.s.hardbreak();
299                 let verbose = self.sess.verbose();
300                 s.synth_comment(rustc_span::hygiene::debug_hygiene_data(verbose));
301                 s.s.hardbreak_if_not_bol();
302             }
303             _ => {}
304         }
305     }
306 }
307
308 struct TypedAnnotation<'a, 'tcx> {
309     tcx: TyCtxt<'tcx>,
310     tables: Cell<&'a ty::TypeckTables<'tcx>>,
311 }
312
313 impl<'b, 'tcx> HirPrinterSupport<'tcx> for TypedAnnotation<'b, 'tcx> {
314     fn sess(&self) -> &Session {
315         &self.tcx.sess
316     }
317
318     fn hir_map<'a>(&'a self) -> Option<&'a hir_map::Map<'tcx>> {
319         Some(&self.tcx.hir())
320     }
321
322     fn pp_ann<'a>(&'a self) -> &'a dyn pprust_hir::PpAnn {
323         self
324     }
325
326     fn node_path(&self, id: hir::HirId) -> Option<String> {
327         Some(self.tcx.def_path_str(self.tcx.hir().local_def_id(id)))
328     }
329 }
330
331 impl<'a, 'tcx> pprust_hir::PpAnn for TypedAnnotation<'a, 'tcx> {
332     fn nested(&self, state: &mut pprust_hir::State<'_>, nested: pprust_hir::Nested) {
333         let old_tables = self.tables.get();
334         if let pprust_hir::Nested::Body(id) = nested {
335             self.tables.set(self.tcx.body_tables(id));
336         }
337         pprust_hir::PpAnn::nested(*self.tcx.hir(), state, nested);
338         self.tables.set(old_tables);
339     }
340     fn pre(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) {
341         match node {
342             pprust_hir::AnnNode::Expr(_) => s.popen(),
343             _ => {}
344         }
345     }
346     fn post(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) {
347         match node {
348             pprust_hir::AnnNode::Expr(expr) => {
349                 s.s.space();
350                 s.s.word("as");
351                 s.s.space();
352                 s.s.word(self.tables.get().expr_ty(expr).to_string());
353                 s.pclose();
354             }
355             _ => {}
356         }
357     }
358 }
359
360 fn get_source(input: &Input, sess: &Session) -> (String, FileName) {
361     let src_name = input.source_name();
362     let src =
363         String::clone(&sess.source_map().get_source_file(&src_name).unwrap().src.as_ref().unwrap());
364     (src, src_name)
365 }
366
367 fn write_output(out: Vec<u8>, ofile: Option<&Path>) {
368     match ofile {
369         None => print!("{}", String::from_utf8(out).unwrap()),
370         Some(p) => match File::create(p) {
371             Ok(mut w) => w.write_all(&out).unwrap(),
372             Err(e) => panic!("print-print failed to open {} due to {}", p.display(), e),
373         },
374     }
375 }
376
377 pub fn print_after_parsing(
378     sess: &Session,
379     input: &Input,
380     krate: &ast::Crate,
381     ppm: PpMode,
382     ofile: Option<&Path>,
383 ) {
384     let (src, src_name) = get_source(input, sess);
385
386     let mut out = String::new();
387
388     if let PpmSource(s) = ppm {
389         // Silently ignores an identified node.
390         let out = &mut out;
391         call_with_pp_support(&s, sess, None, move |annotation| {
392             debug!("pretty printing source code {:?}", s);
393             let sess = annotation.sess();
394             let parse = &sess.parse_sess;
395             *out = pprust::print_crate(
396                 sess.source_map(),
397                 krate,
398                 src_name,
399                 src,
400                 annotation.pp_ann(),
401                 false,
402                 parse.edition,
403                 parse.injected_crate_name.try_get().is_some(),
404             )
405         })
406     } else {
407         unreachable!();
408     };
409
410     write_output(out.into_bytes(), ofile);
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 mut out = String::new();
428
429     match ppm {
430         PpmSource(s) => {
431             // Silently ignores an identified node.
432             let out = &mut out;
433             call_with_pp_support(&s, tcx.sess, Some(tcx), move |annotation| {
434                 debug!("pretty printing source code {:?}", s);
435                 let sess = annotation.sess();
436                 let parse = &sess.parse_sess;
437                 *out = pprust::print_crate(
438                     sess.source_map(),
439                     krate,
440                     src_name,
441                     src,
442                     annotation.pp_ann(),
443                     true,
444                     parse.edition,
445                     parse.injected_crate_name.try_get().is_some(),
446                 )
447             })
448         }
449
450         PpmHir(s) => {
451             let out = &mut out;
452             call_with_pp_support_hir(&s, tcx, move |annotation, krate| {
453                 debug!("pretty printing source code {:?}", s);
454                 let sess = annotation.sess();
455                 let cm = sess.source_map();
456                 *out = pprust_hir::print_crate(cm, krate, src_name, src, annotation.pp_ann())
457             })
458         }
459
460         PpmHirTree(s) => {
461             let out = &mut out;
462             call_with_pp_support_hir(&s, tcx, move |_annotation, krate| {
463                 debug!("pretty printing source code {:?}", s);
464                 *out = format!("{:#?}", krate);
465             });
466         }
467
468         _ => unreachable!(),
469     }
470
471     write_output(out.into_bytes(), ofile);
472 }
473
474 // In an ideal world, this would be a public function called by the driver after
475 // analysis is performed. However, we want to call `phase_3_run_analysis_passes`
476 // with a different callback than the standard driver, so that isn't easy.
477 // Instead, we call that function ourselves.
478 fn print_with_analysis(
479     tcx: TyCtxt<'_>,
480     ppm: PpMode,
481     ofile: Option<&Path>,
482 ) -> Result<(), ErrorReported> {
483     let mut out = Vec::new();
484
485     tcx.analysis(LOCAL_CRATE)?;
486
487     match ppm {
488         PpmMir | PpmMirCFG => match ppm {
489             PpmMir => write_mir_pretty(tcx, None, &mut out),
490             PpmMirCFG => write_mir_graphviz(tcx, None, &mut out),
491             _ => unreachable!(),
492         },
493         _ => unreachable!(),
494     }
495     .unwrap();
496
497     write_output(out, ofile);
498
499     Ok(())
500 }