]> git.lizzy.rs Git - rust.git/blob - src/librustc_driver/pretty.rs
Rollup merge of #58138 - ishitatsuyuki:stability-delay, r=estebank
[rust.git] / src / librustc_driver / pretty.rs
1 //! The various pretty-printing routines.
2
3 use rustc::cfg;
4 use rustc::cfg::graphviz::LabelledCFG;
5 use rustc::hir;
6 use rustc::hir::map as hir_map;
7 use rustc::hir::map::blocks;
8 use rustc::hir::print as pprust_hir;
9 use rustc::session::Session;
10 use rustc::session::config::{Input, OutputFilenames};
11 use rustc::ty::{self, TyCtxt, Resolutions, AllArenas};
12 use rustc_borrowck as borrowck;
13 use rustc_borrowck::graphviz as borrowck_dot;
14 use rustc_data_structures::thin_vec::ThinVec;
15 use rustc_metadata::cstore::CStore;
16 use rustc_mir::util::{write_mir_pretty, write_mir_graphviz};
17
18 use syntax::ast::{self, BlockCheckMode};
19 use syntax::fold::{self, Folder};
20 use syntax::print::{pprust};
21 use syntax::print::pprust::PrintState;
22 use syntax::ptr::P;
23 use syntax_pos::{self, FileName};
24
25 use graphviz as dot;
26 use smallvec::SmallVec;
27
28 use std::cell::Cell;
29 use std::fs::File;
30 use std::io::{self, Write};
31 use std::option;
32 use std::path::Path;
33 use std::str::FromStr;
34 use std::mem;
35
36 pub use self::UserIdentifiedItem::*;
37 pub use self::PpSourceMode::*;
38 pub use self::PpMode::*;
39 use self::NodesMatchingUII::*;
40 use {abort_on_err, driver};
41
42 #[derive(Copy, Clone, PartialEq, Debug)]
43 pub enum PpSourceMode {
44     PpmNormal,
45     PpmEveryBodyLoops,
46     PpmExpanded,
47     PpmIdentified,
48     PpmExpandedIdentified,
49     PpmExpandedHygiene,
50     PpmTyped,
51 }
52
53 #[derive(Copy, Clone, PartialEq, Debug)]
54 pub enum PpFlowGraphMode {
55     Default,
56     /// Drops the labels from the edges in the flowgraph output. This
57     /// is mostly for use in the -Z unpretty flowgraph run-make tests,
58     /// since the labels are largely uninteresting in those cases and
59     /// have become a pain to maintain.
60     UnlabelledEdges,
61 }
62 #[derive(Copy, Clone, PartialEq, Debug)]
63 pub enum PpMode {
64     PpmSource(PpSourceMode),
65     PpmHir(PpSourceMode),
66     PpmHirTree(PpSourceMode),
67     PpmFlowGraph(PpFlowGraphMode),
68     PpmMir,
69     PpmMirCFG,
70 }
71
72 impl PpMode {
73     pub fn needs_ast_map(&self, opt_uii: &Option<UserIdentifiedItem>) -> bool {
74         match *self {
75             PpmSource(PpmNormal) |
76             PpmSource(PpmEveryBodyLoops) |
77             PpmSource(PpmIdentified) => opt_uii.is_some(),
78
79             PpmSource(PpmExpanded) |
80             PpmSource(PpmExpandedIdentified) |
81             PpmSource(PpmExpandedHygiene) |
82             PpmHir(_) |
83             PpmHirTree(_) |
84             PpmMir |
85             PpmMirCFG |
86             PpmFlowGraph(_) => true,
87             PpmSource(PpmTyped) => panic!("invalid state"),
88         }
89     }
90
91     pub fn needs_analysis(&self) -> bool {
92         match *self {
93             PpmMir | PpmMirCFG | PpmFlowGraph(_) => true,
94             _ => false,
95         }
96     }
97 }
98
99 pub fn parse_pretty(sess: &Session,
100                     name: &str,
101                     extended: bool)
102                     -> (PpMode, Option<UserIdentifiedItem>) {
103     let mut split = name.splitn(2, '=');
104     let first = split.next().unwrap();
105     let opt_second = split.next();
106     let first = match (first, extended) {
107         ("normal", _) => PpmSource(PpmNormal),
108         ("identified", _) => PpmSource(PpmIdentified),
109         ("everybody_loops", true) => PpmSource(PpmEveryBodyLoops),
110         ("expanded", _) => PpmSource(PpmExpanded),
111         ("expanded,identified", _) => PpmSource(PpmExpandedIdentified),
112         ("expanded,hygiene", _) => PpmSource(PpmExpandedHygiene),
113         ("hir", true) => PpmHir(PpmNormal),
114         ("hir,identified", true) => PpmHir(PpmIdentified),
115         ("hir,typed", true) => PpmHir(PpmTyped),
116         ("hir-tree", true) => PpmHirTree(PpmNormal),
117         ("mir", true) => PpmMir,
118         ("mir-cfg", true) => PpmMirCFG,
119         ("flowgraph", true) => PpmFlowGraph(PpFlowGraphMode::Default),
120         ("flowgraph,unlabelled", true) => PpmFlowGraph(PpFlowGraphMode::UnlabelledEdges),
121         _ => {
122             if extended {
123                 sess.fatal(&format!("argument to `unpretty` must be one of `normal`, \
124                                      `expanded`, `flowgraph[,unlabelled]=<nodeid>`, \
125                                      `identified`, `expanded,identified`, `everybody_loops`, \
126                                      `hir`, `hir,identified`, `hir,typed`, `hir-tree`, \
127                                      `mir` or `mir-cfg`; got {}",
128                                     name));
129             } else {
130                 sess.fatal(&format!("argument to `pretty` must be one of `normal`, `expanded`, \
131                                      `identified`, or `expanded,identified`; got {}",
132                                     name));
133             }
134         }
135     };
136     let opt_second = opt_second.and_then(|s| s.parse::<UserIdentifiedItem>().ok());
137     (first, opt_second)
138 }
139
140
141
142 // This slightly awkward construction is to allow for each PpMode to
143 // choose whether it needs to do analyses (which can consume the
144 // Session) and then pass through the session (now attached to the
145 // analysis results) on to the chosen pretty-printer, along with the
146 // `&PpAnn` object.
147 //
148 // Note that since the `&PrinterSupport` is freshly constructed on each
149 // call, it would not make sense to try to attach the lifetime of `self`
150 // to the lifetime of the `&PrinterObject`.
151 //
152 // (The `use_once_payload` is working around the current lack of once
153 // functions in the compiler.)
154
155 impl PpSourceMode {
156     /// Constructs a `PrinterSupport` object and passes it to `f`.
157     fn call_with_pp_support<'tcx, A, F>(&self,
158                                         sess: &'tcx Session,
159                                         hir_map: Option<&hir_map::Map<'tcx>>,
160                                         f: F)
161                                         -> A
162         where F: FnOnce(&dyn PrinterSupport) -> A
163     {
164         match *self {
165             PpmNormal | PpmEveryBodyLoops | PpmExpanded => {
166                 let annotation = NoAnn {
167                     sess,
168                     hir_map: hir_map.map(|m| m.clone()),
169                 };
170                 f(&annotation)
171             }
172
173             PpmIdentified | PpmExpandedIdentified => {
174                 let annotation = IdentifiedAnnotation {
175                     sess,
176                     hir_map: hir_map.map(|m| m.clone()),
177                 };
178                 f(&annotation)
179             }
180             PpmExpandedHygiene => {
181                 let annotation = HygieneAnnotation {
182                     sess,
183                 };
184                 f(&annotation)
185             }
186             _ => panic!("Should use call_with_pp_support_hir"),
187         }
188     }
189     fn call_with_pp_support_hir<'tcx, A, F>(
190         &self,
191         sess: &'tcx Session,
192         cstore: &'tcx CStore,
193         hir_map: &hir_map::Map<'tcx>,
194         resolutions: &Resolutions,
195         output_filenames: &OutputFilenames,
196         id: &str,
197         f: F
198     ) -> A
199         where F: FnOnce(&dyn HirPrinterSupport, &hir::Crate) -> A
200     {
201         match *self {
202             PpmNormal => {
203                 let annotation = NoAnn {
204                     sess,
205                     hir_map: Some(hir_map.clone()),
206                 };
207                 f(&annotation, hir_map.forest.krate())
208             }
209
210             PpmIdentified => {
211                 let annotation = IdentifiedAnnotation {
212                     sess,
213                     hir_map: Some(hir_map.clone()),
214                 };
215                 f(&annotation, hir_map.forest.krate())
216             }
217             PpmTyped => {
218                 let control = &driver::CompileController::basic();
219                 let codegen_backend = ::get_codegen_backend(sess);
220                 let mut arenas = AllArenas::new();
221                 abort_on_err(driver::phase_3_run_analysis_passes(&*codegen_backend,
222                                                                  control,
223                                                                  sess,
224                                                                  cstore,
225                                                                  hir_map.clone(),
226                                                                  resolutions.clone(),
227                                                                  &mut arenas,
228                                                                  id,
229                                                                  output_filenames,
230                                                                  |tcx, _, _| {
231                     let empty_tables = ty::TypeckTables::empty(None);
232                     let annotation = TypedAnnotation {
233                         tcx,
234                         tables: Cell::new(&empty_tables)
235                     };
236                     tcx.dep_graph.with_ignore(|| {
237                         f(&annotation, hir_map.forest.krate())
238                     })
239                 }),
240                              sess)
241             }
242             _ => panic!("Should use call_with_pp_support"),
243         }
244     }
245 }
246
247 trait PrinterSupport: pprust::PpAnn {
248     /// Provides a uniform interface for re-extracting a reference to a
249     /// `Session` from a value that now owns it.
250     fn sess<'a>(&'a self) -> &'a Session;
251
252     /// Produces the pretty-print annotation object.
253     ///
254     /// (Rust does not yet support upcasting from a trait object to
255     /// an object for one of its super-traits.)
256     fn pp_ann<'a>(&'a self) -> &'a dyn pprust::PpAnn;
257 }
258
259 trait HirPrinterSupport<'hir>: pprust_hir::PpAnn {
260     /// Provides a uniform interface for re-extracting a reference to a
261     /// `Session` from a value that now owns it.
262     fn sess<'a>(&'a self) -> &'a Session;
263
264     /// Provides a uniform interface for re-extracting a reference to an
265     /// `hir_map::Map` from a value that now owns it.
266     fn hir_map<'a>(&'a self) -> Option<&'a hir_map::Map<'hir>>;
267
268     /// Produces the pretty-print annotation object.
269     ///
270     /// (Rust does not yet support upcasting from a trait object to
271     /// an object for one of its super-traits.)
272     fn pp_ann<'a>(&'a self) -> &'a dyn pprust_hir::PpAnn;
273
274     /// Computes an user-readable representation of a path, if possible.
275     fn node_path(&self, id: ast::NodeId) -> Option<String> {
276         self.hir_map().and_then(|map| map.def_path_from_id(id)).map(|path| {
277             path.data
278                 .into_iter()
279                 .map(|elem| elem.data.to_string())
280                 .collect::<Vec<_>>()
281                 .join("::")
282         })
283     }
284 }
285
286 struct NoAnn<'hir> {
287     sess: &'hir Session,
288     hir_map: Option<hir_map::Map<'hir>>,
289 }
290
291 impl<'hir> PrinterSupport for NoAnn<'hir> {
292     fn sess<'a>(&'a self) -> &'a Session {
293         self.sess
294     }
295
296     fn pp_ann<'a>(&'a self) -> &'a dyn pprust::PpAnn {
297         self
298     }
299 }
300
301 impl<'hir> HirPrinterSupport<'hir> for NoAnn<'hir> {
302     fn sess<'a>(&'a self) -> &'a Session {
303         self.sess
304     }
305
306     fn hir_map<'a>(&'a self) -> Option<&'a hir_map::Map<'hir>> {
307         self.hir_map.as_ref()
308     }
309
310     fn pp_ann<'a>(&'a self) -> &'a dyn pprust_hir::PpAnn {
311         self
312     }
313 }
314
315 impl<'hir> pprust::PpAnn for NoAnn<'hir> {}
316 impl<'hir> pprust_hir::PpAnn for NoAnn<'hir> {
317     fn nested(&self, state: &mut pprust_hir::State, nested: pprust_hir::Nested)
318               -> io::Result<()> {
319         if let Some(ref map) = self.hir_map {
320             pprust_hir::PpAnn::nested(map, state, nested)
321         } else {
322             Ok(())
323         }
324     }
325 }
326
327 struct IdentifiedAnnotation<'hir> {
328     sess: &'hir Session,
329     hir_map: Option<hir_map::Map<'hir>>,
330 }
331
332 impl<'hir> PrinterSupport for IdentifiedAnnotation<'hir> {
333     fn sess<'a>(&'a self) -> &'a Session {
334         self.sess
335     }
336
337     fn pp_ann<'a>(&'a self) -> &'a dyn pprust::PpAnn {
338         self
339     }
340 }
341
342 impl<'hir> pprust::PpAnn for IdentifiedAnnotation<'hir> {
343     fn pre(&self, s: &mut pprust::State, node: pprust::AnnNode) -> io::Result<()> {
344         match node {
345             pprust::AnnNode::Expr(_) => s.popen(),
346             _ => Ok(()),
347         }
348     }
349     fn post(&self, s: &mut pprust::State, node: pprust::AnnNode) -> io::Result<()> {
350         match node {
351             pprust::AnnNode::Ident(_) |
352             pprust::AnnNode::Name(_) => Ok(()),
353
354             pprust::AnnNode::Item(item) => {
355                 s.s.space()?;
356                 s.synth_comment(item.id.to_string())
357             }
358             pprust::AnnNode::SubItem(id) => {
359                 s.s.space()?;
360                 s.synth_comment(id.to_string())
361             }
362             pprust::AnnNode::Block(blk) => {
363                 s.s.space()?;
364                 s.synth_comment(format!("block {}", blk.id))
365             }
366             pprust::AnnNode::Expr(expr) => {
367                 s.s.space()?;
368                 s.synth_comment(expr.id.to_string())?;
369                 s.pclose()
370             }
371             pprust::AnnNode::Pat(pat) => {
372                 s.s.space()?;
373                 s.synth_comment(format!("pat {}", pat.id))
374             }
375         }
376     }
377 }
378
379 impl<'hir> HirPrinterSupport<'hir> for IdentifiedAnnotation<'hir> {
380     fn sess<'a>(&'a self) -> &'a Session {
381         self.sess
382     }
383
384     fn hir_map<'a>(&'a self) -> Option<&'a hir_map::Map<'hir>> {
385         self.hir_map.as_ref()
386     }
387
388     fn pp_ann<'a>(&'a self) -> &'a dyn pprust_hir::PpAnn {
389         self
390     }
391 }
392
393 impl<'hir> pprust_hir::PpAnn for IdentifiedAnnotation<'hir> {
394     fn nested(&self, state: &mut pprust_hir::State, nested: pprust_hir::Nested)
395               -> io::Result<()> {
396         if let Some(ref map) = self.hir_map {
397             pprust_hir::PpAnn::nested(map, state, nested)
398         } else {
399             Ok(())
400         }
401     }
402     fn pre(&self, s: &mut pprust_hir::State, node: pprust_hir::AnnNode) -> io::Result<()> {
403         match node {
404             pprust_hir::AnnNode::Expr(_) => s.popen(),
405             _ => Ok(()),
406         }
407     }
408     fn post(&self, s: &mut pprust_hir::State, node: pprust_hir::AnnNode) -> io::Result<()> {
409         match node {
410             pprust_hir::AnnNode::Name(_) => Ok(()),
411             pprust_hir::AnnNode::Item(item) => {
412                 s.s.space()?;
413                 s.synth_comment(format!("node_id: {} hir local_id: {}",
414                                         item.id, item.hir_id.local_id.as_u32()))
415             }
416             pprust_hir::AnnNode::SubItem(id) => {
417                 s.s.space()?;
418                 s.synth_comment(id.to_string())
419             }
420             pprust_hir::AnnNode::Block(blk) => {
421                 s.s.space()?;
422                 s.synth_comment(format!("block node_id: {} hir local_id: {}",
423                                         blk.id, blk.hir_id.local_id.as_u32()))
424             }
425             pprust_hir::AnnNode::Expr(expr) => {
426                 s.s.space()?;
427                 s.synth_comment(format!("node_id: {} hir local_id: {}",
428                                         expr.id, expr.hir_id.local_id.as_u32()))?;
429                 s.pclose()
430             }
431             pprust_hir::AnnNode::Pat(pat) => {
432                 s.s.space()?;
433                 s.synth_comment(format!("pat node_id: {} hir local_id: {}",
434                                         pat.id, pat.hir_id.local_id.as_u32()))
435             }
436         }
437     }
438 }
439
440 struct HygieneAnnotation<'a> {
441     sess: &'a Session
442 }
443
444 impl<'a> PrinterSupport for HygieneAnnotation<'a> {
445     fn sess(&self) -> &Session {
446         self.sess
447     }
448
449     fn pp_ann(&self) -> &dyn pprust::PpAnn {
450         self
451     }
452 }
453
454 impl<'a> pprust::PpAnn for HygieneAnnotation<'a> {
455     fn post(&self, s: &mut pprust::State, node: pprust::AnnNode) -> io::Result<()> {
456         match node {
457             pprust::AnnNode::Ident(&ast::Ident { name, span }) => {
458                 s.s.space()?;
459                 // FIXME #16420: this doesn't display the connections
460                 // between syntax contexts
461                 s.synth_comment(format!("{}{:?}", name.as_u32(), span.ctxt()))
462             }
463             pprust::AnnNode::Name(&name) => {
464                 s.s.space()?;
465                 s.synth_comment(name.as_u32().to_string())
466             }
467             _ => Ok(()),
468         }
469     }
470 }
471
472
473 struct TypedAnnotation<'a, 'tcx: 'a> {
474     tcx: TyCtxt<'a, 'tcx, 'tcx>,
475     tables: Cell<&'a ty::TypeckTables<'tcx>>,
476 }
477
478 impl<'b, 'tcx> HirPrinterSupport<'tcx> for TypedAnnotation<'b, 'tcx> {
479     fn sess<'a>(&'a self) -> &'a Session {
480         &self.tcx.sess
481     }
482
483     fn hir_map<'a>(&'a self) -> Option<&'a hir_map::Map<'tcx>> {
484         Some(&self.tcx.hir())
485     }
486
487     fn pp_ann<'a>(&'a self) -> &'a dyn pprust_hir::PpAnn {
488         self
489     }
490
491     fn node_path(&self, id: ast::NodeId) -> Option<String> {
492         Some(self.tcx.node_path_str(id))
493     }
494 }
495
496 impl<'a, 'tcx> pprust_hir::PpAnn for TypedAnnotation<'a, 'tcx> {
497     fn nested(&self, state: &mut pprust_hir::State, nested: pprust_hir::Nested)
498               -> io::Result<()> {
499         let old_tables = self.tables.get();
500         if let pprust_hir::Nested::Body(id) = nested {
501             self.tables.set(self.tcx.body_tables(id));
502         }
503         pprust_hir::PpAnn::nested(self.tcx.hir(), state, nested)?;
504         self.tables.set(old_tables);
505         Ok(())
506     }
507     fn pre(&self, s: &mut pprust_hir::State, node: pprust_hir::AnnNode) -> io::Result<()> {
508         match node {
509             pprust_hir::AnnNode::Expr(_) => s.popen(),
510             _ => Ok(()),
511         }
512     }
513     fn post(&self, s: &mut pprust_hir::State, node: pprust_hir::AnnNode) -> io::Result<()> {
514         match node {
515             pprust_hir::AnnNode::Expr(expr) => {
516                 s.s.space()?;
517                 s.s.word("as")?;
518                 s.s.space()?;
519                 s.s.word(self.tables.get().expr_ty(expr).to_string())?;
520                 s.pclose()
521             }
522             _ => Ok(()),
523         }
524     }
525 }
526
527 fn gather_flowgraph_variants(sess: &Session) -> Vec<borrowck_dot::Variant> {
528     let print_loans = sess.opts.debugging_opts.flowgraph_print_loans;
529     let print_moves = sess.opts.debugging_opts.flowgraph_print_moves;
530     let print_assigns = sess.opts.debugging_opts.flowgraph_print_assigns;
531     let print_all = sess.opts.debugging_opts.flowgraph_print_all;
532     let mut variants = Vec::new();
533     if print_all || print_loans {
534         variants.push(borrowck_dot::Loans);
535     }
536     if print_all || print_moves {
537         variants.push(borrowck_dot::Moves);
538     }
539     if print_all || print_assigns {
540         variants.push(borrowck_dot::Assigns);
541     }
542     variants
543 }
544
545 #[derive(Clone, Debug)]
546 pub enum UserIdentifiedItem {
547     ItemViaNode(ast::NodeId),
548     ItemViaPath(Vec<String>),
549 }
550
551 impl FromStr for UserIdentifiedItem {
552     type Err = ();
553     fn from_str(s: &str) -> Result<UserIdentifiedItem, ()> {
554         Ok(s.parse()
555             .map(ast::NodeId::from_u32)
556             .map(ItemViaNode)
557             .unwrap_or_else(|_| ItemViaPath(s.split("::").map(|s| s.to_string()).collect())))
558     }
559 }
560
561 enum NodesMatchingUII<'a, 'hir: 'a> {
562     NodesMatchingDirect(option::IntoIter<ast::NodeId>),
563     NodesMatchingSuffix(hir_map::NodesMatchingSuffix<'a, 'hir>),
564 }
565
566 impl<'a, 'hir> Iterator for NodesMatchingUII<'a, 'hir> {
567     type Item = ast::NodeId;
568
569     fn next(&mut self) -> Option<ast::NodeId> {
570         match self {
571             &mut NodesMatchingDirect(ref mut iter) => iter.next(),
572             &mut NodesMatchingSuffix(ref mut iter) => iter.next(),
573         }
574     }
575
576     fn size_hint(&self) -> (usize, Option<usize>) {
577         match self {
578             &NodesMatchingDirect(ref iter) => iter.size_hint(),
579             &NodesMatchingSuffix(ref iter) => iter.size_hint(),
580         }
581     }
582 }
583
584 impl UserIdentifiedItem {
585     fn reconstructed_input(&self) -> String {
586         match *self {
587             ItemViaNode(node_id) => node_id.to_string(),
588             ItemViaPath(ref parts) => parts.join("::"),
589         }
590     }
591
592     fn all_matching_node_ids<'a, 'hir>(&'a self,
593                                        map: &'a hir_map::Map<'hir>)
594                                        -> NodesMatchingUII<'a, 'hir> {
595         match *self {
596             ItemViaNode(node_id) => NodesMatchingDirect(Some(node_id).into_iter()),
597             ItemViaPath(ref parts) => NodesMatchingSuffix(map.nodes_matching_suffix(&parts)),
598         }
599     }
600
601     fn to_one_node_id(self, user_option: &str, sess: &Session, map: &hir_map::Map) -> ast::NodeId {
602         let fail_because = |is_wrong_because| -> ast::NodeId {
603             let message = format!("{} needs NodeId (int) or unique path suffix (b::c::d); got \
604                                    {}, which {}",
605                                   user_option,
606                                   self.reconstructed_input(),
607                                   is_wrong_because);
608             sess.fatal(&message)
609         };
610
611         let mut saw_node = ast::DUMMY_NODE_ID;
612         let mut seen = 0;
613         for node in self.all_matching_node_ids(map) {
614             saw_node = node;
615             seen += 1;
616             if seen > 1 {
617                 fail_because("does not resolve uniquely");
618             }
619         }
620         if seen == 0 {
621             fail_because("does not resolve to any item");
622         }
623
624         assert!(seen == 1);
625         return saw_node;
626     }
627 }
628
629 // Note: Also used by librustdoc, see PR #43348. Consider moving this struct elsewhere.
630 //
631 // FIXME: Currently the `everybody_loops` transformation is not applied to:
632 //  * `const fn`, due to issue #43636 that `loop` is not supported for const evaluation. We are
633 //    waiting for miri to fix that.
634 //  * `impl Trait`, due to issue #43869 that functions returning impl Trait cannot be diverging.
635 //    Solving this may require `!` to implement every trait, which relies on the an even more
636 //    ambitious form of the closed RFC #1637. See also [#34511].
637 //
638 // [#34511]: https://github.com/rust-lang/rust/issues/34511#issuecomment-322340401
639 pub struct ReplaceBodyWithLoop<'a> {
640     within_static_or_const: bool,
641     nested_blocks: Option<Vec<ast::Block>>,
642     sess: &'a Session,
643 }
644
645 impl<'a> ReplaceBodyWithLoop<'a> {
646     pub fn new(sess: &'a Session) -> ReplaceBodyWithLoop<'a> {
647         ReplaceBodyWithLoop {
648             within_static_or_const: false,
649             nested_blocks: None,
650             sess
651         }
652     }
653
654     fn run<R, F: FnOnce(&mut Self) -> R>(&mut self, is_const: bool, action: F) -> R {
655         let old_const = mem::replace(&mut self.within_static_or_const, is_const);
656         let old_blocks = self.nested_blocks.take();
657         let ret = action(self);
658         self.within_static_or_const = old_const;
659         self.nested_blocks = old_blocks;
660         ret
661     }
662
663     fn should_ignore_fn(ret_ty: &ast::FnDecl) -> bool {
664         if let ast::FunctionRetTy::Ty(ref ty) = ret_ty.output {
665             fn involves_impl_trait(ty: &ast::Ty) -> bool {
666                 match ty.node {
667                     ast::TyKind::ImplTrait(..) => true,
668                     ast::TyKind::Slice(ref subty) |
669                     ast::TyKind::Array(ref subty, _) |
670                     ast::TyKind::Ptr(ast::MutTy { ty: ref subty, .. }) |
671                     ast::TyKind::Rptr(_, ast::MutTy { ty: ref subty, .. }) |
672                     ast::TyKind::Paren(ref subty) => involves_impl_trait(subty),
673                     ast::TyKind::Tup(ref tys) => any_involves_impl_trait(tys.iter()),
674                     ast::TyKind::Path(_, ref path) => path.segments.iter().any(|seg| {
675                         match seg.args.as_ref().map(|generic_arg| &**generic_arg) {
676                             None => false,
677                             Some(&ast::GenericArgs::AngleBracketed(ref data)) => {
678                                 let types = data.args.iter().filter_map(|arg| match arg {
679                                     ast::GenericArg::Type(ty) => Some(ty),
680                                     _ => None,
681                                 });
682                                 any_involves_impl_trait(types.into_iter()) ||
683                                 any_involves_impl_trait(data.bindings.iter().map(|b| &b.ty))
684                             },
685                             Some(&ast::GenericArgs::Parenthesized(ref data)) => {
686                                 any_involves_impl_trait(data.inputs.iter()) ||
687                                 any_involves_impl_trait(data.output.iter())
688                             }
689                         }
690                     }),
691                     _ => false,
692                 }
693             }
694
695             fn any_involves_impl_trait<'a, I: Iterator<Item = &'a P<ast::Ty>>>(mut it: I) -> bool {
696                 it.any(|subty| involves_impl_trait(subty))
697             }
698
699             involves_impl_trait(ty)
700         } else {
701             false
702         }
703     }
704 }
705
706 impl<'a> fold::Folder for ReplaceBodyWithLoop<'a> {
707     fn fold_item_kind(&mut self, i: ast::ItemKind) -> ast::ItemKind {
708         let is_const = match i {
709             ast::ItemKind::Static(..) | ast::ItemKind::Const(..) => true,
710             ast::ItemKind::Fn(ref decl, ref header, _, _) =>
711                 header.constness.node == ast::Constness::Const || Self::should_ignore_fn(decl),
712             _ => false,
713         };
714         self.run(is_const, |s| fold::noop_fold_item_kind(i, s))
715     }
716
717     fn fold_trait_item(&mut self, i: ast::TraitItem) -> SmallVec<[ast::TraitItem; 1]> {
718         let is_const = match i.node {
719             ast::TraitItemKind::Const(..) => true,
720             ast::TraitItemKind::Method(ast::MethodSig { ref decl, ref header, .. }, _) =>
721                 header.constness.node == ast::Constness::Const || Self::should_ignore_fn(decl),
722             _ => false,
723         };
724         self.run(is_const, |s| fold::noop_fold_trait_item(i, s))
725     }
726
727     fn fold_impl_item(&mut self, i: ast::ImplItem) -> SmallVec<[ast::ImplItem; 1]> {
728         let is_const = match i.node {
729             ast::ImplItemKind::Const(..) => true,
730             ast::ImplItemKind::Method(ast::MethodSig { ref decl, ref header, .. }, _) =>
731                 header.constness.node == ast::Constness::Const || Self::should_ignore_fn(decl),
732             _ => false,
733         };
734         self.run(is_const, |s| fold::noop_fold_impl_item(i, s))
735     }
736
737     fn fold_anon_const(&mut self, c: ast::AnonConst) -> ast::AnonConst {
738         self.run(true, |s| fold::noop_fold_anon_const(c, s))
739     }
740
741     fn fold_block(&mut self, b: P<ast::Block>) -> P<ast::Block> {
742         fn stmt_to_block(rules: ast::BlockCheckMode,
743                          s: Option<ast::Stmt>,
744                          sess: &Session) -> ast::Block {
745             ast::Block {
746                 stmts: s.into_iter().collect(),
747                 rules,
748                 id: sess.next_node_id(),
749                 span: syntax_pos::DUMMY_SP,
750             }
751         }
752
753         fn block_to_stmt(b: ast::Block, sess: &Session) -> ast::Stmt {
754             let expr = P(ast::Expr {
755                 id: sess.next_node_id(),
756                 node: ast::ExprKind::Block(P(b), None),
757                 span: syntax_pos::DUMMY_SP,
758                 attrs: ThinVec::new(),
759             });
760
761             ast::Stmt {
762                 id: sess.next_node_id(),
763                 node: ast::StmtKind::Expr(expr),
764                 span: syntax_pos::DUMMY_SP,
765             }
766         }
767
768         let empty_block = stmt_to_block(BlockCheckMode::Default, None, self.sess);
769         let loop_expr = P(ast::Expr {
770             node: ast::ExprKind::Loop(P(empty_block), None),
771             id: self.sess.next_node_id(),
772             span: syntax_pos::DUMMY_SP,
773                 attrs: ThinVec::new(),
774         });
775
776         let loop_stmt = ast::Stmt {
777             id: self.sess.next_node_id(),
778             span: syntax_pos::DUMMY_SP,
779             node: ast::StmtKind::Expr(loop_expr),
780         };
781
782         if self.within_static_or_const {
783             fold::noop_fold_block(b, self)
784         } else {
785             b.map(|b| {
786                 let mut stmts = vec![];
787                 for s in b.stmts {
788                     let old_blocks = self.nested_blocks.replace(vec![]);
789
790                     stmts.extend(self.fold_stmt(s).into_iter().filter(|s| s.is_item()));
791
792                     // we put a Some in there earlier with that replace(), so this is valid
793                     let new_blocks = self.nested_blocks.take().unwrap();
794                     self.nested_blocks = old_blocks;
795                     stmts.extend(new_blocks.into_iter().map(|b| block_to_stmt(b, &self.sess)));
796                 }
797
798                 let mut new_block = ast::Block {
799                     stmts,
800                     ..b
801                 };
802
803                 if let Some(old_blocks) = self.nested_blocks.as_mut() {
804                     //push our fresh block onto the cache and yield an empty block with `loop {}`
805                     if !new_block.stmts.is_empty() {
806                         old_blocks.push(new_block);
807                     }
808
809                     stmt_to_block(b.rules, Some(loop_stmt), self.sess)
810                 } else {
811                     //push `loop {}` onto the end of our fresh block and yield that
812                     new_block.stmts.push(loop_stmt);
813
814                     new_block
815                 }
816             })
817         }
818     }
819
820     // in general the pretty printer processes unexpanded code, so
821     // we override the default `fold_mac` method which panics.
822     fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac {
823         fold::noop_fold_mac(mac, self)
824     }
825 }
826
827 fn print_flowgraph<'a, 'tcx, W: Write>(variants: Vec<borrowck_dot::Variant>,
828                                        tcx: TyCtxt<'a, 'tcx, 'tcx>,
829                                        code: blocks::Code<'tcx>,
830                                        mode: PpFlowGraphMode,
831                                        mut out: W)
832                                        -> io::Result<()> {
833     let body_id = match code {
834         blocks::Code::Expr(expr) => {
835             // Find the function this expression is from.
836             let mut node_id = expr.id;
837             loop {
838                 let node = tcx.hir().get(node_id);
839                 if let Some(n) = hir::map::blocks::FnLikeNode::from_node(node) {
840                     break n.body();
841                 }
842                 let parent = tcx.hir().get_parent_node(node_id);
843                 assert_ne!(node_id, parent);
844                 node_id = parent;
845             }
846         }
847         blocks::Code::FnLike(fn_like) => fn_like.body(),
848     };
849     let body = tcx.hir().body(body_id);
850     let cfg = cfg::CFG::new(tcx, &body);
851     let labelled_edges = mode != PpFlowGraphMode::UnlabelledEdges;
852     let lcfg = LabelledCFG {
853         tcx,
854         cfg: &cfg,
855         name: format!("node_{}", code.id()),
856         labelled_edges,
857     };
858
859     match code {
860         _ if variants.is_empty() => {
861             let r = dot::render(&lcfg, &mut out);
862             return expand_err_details(r);
863         }
864         blocks::Code::Expr(_) => {
865             tcx.sess.err("--pretty flowgraph with -Z flowgraph-print annotations requires \
866                           fn-like node id.");
867             return Ok(());
868         }
869         blocks::Code::FnLike(fn_like) => {
870             let (bccx, analysis_data) =
871                 borrowck::build_borrowck_dataflow_data_for_fn(tcx, fn_like.body(), &cfg);
872
873             let lcfg = borrowck_dot::DataflowLabeller {
874                 inner: lcfg,
875                 variants,
876                 borrowck_ctxt: &bccx,
877                 analysis_data: &analysis_data,
878             };
879             let r = dot::render(&lcfg, &mut out);
880             return expand_err_details(r);
881         }
882     }
883
884     fn expand_err_details(r: io::Result<()>) -> io::Result<()> {
885         r.map_err(|ioerr| {
886             io::Error::new(io::ErrorKind::Other,
887                            format!("graphviz::render failed: {}", ioerr))
888         })
889     }
890 }
891
892 pub fn fold_crate(sess: &Session, krate: ast::Crate, ppm: PpMode) -> ast::Crate {
893     if let PpmSource(PpmEveryBodyLoops) = ppm {
894         let mut fold = ReplaceBodyWithLoop::new(sess);
895         fold.fold_crate(krate)
896     } else {
897         krate
898     }
899 }
900
901 fn get_source(input: &Input, sess: &Session) -> (Vec<u8>, FileName) {
902     let src_name = driver::source_name(input);
903     let src = sess.source_map()
904         .get_source_file(&src_name)
905         .unwrap()
906         .src
907         .as_ref()
908         .unwrap()
909         .as_bytes()
910         .to_vec();
911     (src, src_name)
912 }
913
914 fn write_output(out: Vec<u8>, ofile: Option<&Path>) {
915     match ofile {
916         None => print!("{}", String::from_utf8(out).unwrap()),
917         Some(p) => {
918             match File::create(p) {
919                 Ok(mut w) => w.write_all(&out).unwrap(),
920                 Err(e) => panic!("print-print failed to open {} due to {}", p.display(), e),
921             }
922         }
923     }
924 }
925
926 pub fn print_after_parsing(sess: &Session,
927                            input: &Input,
928                            krate: &ast::Crate,
929                            ppm: PpMode,
930                            ofile: Option<&Path>) {
931     let (src, src_name) = get_source(input, sess);
932
933     let mut rdr = &*src;
934     let mut out = Vec::new();
935
936     if let PpmSource(s) = ppm {
937         // Silently ignores an identified node.
938         let out: &mut dyn Write = &mut out;
939         s.call_with_pp_support(sess, None, move |annotation| {
940             debug!("pretty printing source code {:?}", s);
941             let sess = annotation.sess();
942             pprust::print_crate(sess.source_map(),
943                                 &sess.parse_sess,
944                                 krate,
945                                 src_name,
946                                 &mut rdr,
947                                 box out,
948                                 annotation.pp_ann(),
949                                 false)
950         }).unwrap()
951     } else {
952         unreachable!();
953     };
954
955     write_output(out, ofile);
956 }
957
958 pub fn print_after_hir_lowering<'tcx, 'a: 'tcx>(sess: &'a Session,
959                                                 cstore: &'tcx CStore,
960                                                 hir_map: &hir_map::Map<'tcx>,
961                                                 resolutions: &Resolutions,
962                                                 input: &Input,
963                                                 krate: &ast::Crate,
964                                                 crate_name: &str,
965                                                 ppm: PpMode,
966                                                 output_filenames: &OutputFilenames,
967                                                 opt_uii: Option<UserIdentifiedItem>,
968                                                 ofile: Option<&Path>) {
969     if ppm.needs_analysis() {
970         print_with_analysis(sess,
971                             cstore,
972                             hir_map,
973                             resolutions,
974                             crate_name,
975                             output_filenames,
976                             ppm,
977                             opt_uii,
978                             ofile);
979         return;
980     }
981
982     let (src, src_name) = get_source(input, sess);
983
984     let mut rdr = &src[..];
985     let mut out = Vec::new();
986
987     match (ppm, opt_uii) {
988             (PpmSource(s), _) => {
989                 // Silently ignores an identified node.
990                 let out: &mut dyn Write = &mut out;
991                 s.call_with_pp_support(sess, Some(hir_map), move |annotation| {
992                     debug!("pretty printing source code {:?}", s);
993                     let sess = annotation.sess();
994                     pprust::print_crate(sess.source_map(),
995                                         &sess.parse_sess,
996                                         krate,
997                                         src_name,
998                                         &mut rdr,
999                                         box out,
1000                                         annotation.pp_ann(),
1001                                         true)
1002                 })
1003             }
1004
1005             (PpmHir(s), None) => {
1006                 let out: &mut dyn Write = &mut out;
1007                 s.call_with_pp_support_hir(sess,
1008                                            cstore,
1009                                            hir_map,
1010                                            resolutions,
1011                                            output_filenames,
1012                                            crate_name,
1013                                            move |annotation, krate| {
1014                     debug!("pretty printing source code {:?}", s);
1015                     let sess = annotation.sess();
1016                     pprust_hir::print_crate(sess.source_map(),
1017                                             &sess.parse_sess,
1018                                             krate,
1019                                             src_name,
1020                                             &mut rdr,
1021                                             box out,
1022                                             annotation.pp_ann(),
1023                                             true)
1024                 })
1025             }
1026
1027             (PpmHirTree(s), None) => {
1028                 let out: &mut dyn Write = &mut out;
1029                 s.call_with_pp_support_hir(sess,
1030                                            cstore,
1031                                            hir_map,
1032                                            resolutions,
1033                                            output_filenames,
1034                                            crate_name,
1035                                            move |_annotation, krate| {
1036                     debug!("pretty printing source code {:?}", s);
1037                     write!(out, "{:#?}", krate)
1038                 })
1039             }
1040
1041             (PpmHir(s), Some(uii)) => {
1042                 let out: &mut dyn Write = &mut out;
1043                 s.call_with_pp_support_hir(sess,
1044                                            cstore,
1045                                            hir_map,
1046                                            resolutions,
1047                                            output_filenames,
1048                                            crate_name,
1049                                            move |annotation, _| {
1050                     debug!("pretty printing source code {:?}", s);
1051                     let sess = annotation.sess();
1052                     let hir_map = annotation.hir_map().expect("-Z unpretty missing HIR map");
1053                     let mut pp_state = pprust_hir::State::new_from_input(sess.source_map(),
1054                                                                          &sess.parse_sess,
1055                                                                          src_name,
1056                                                                          &mut rdr,
1057                                                                          box out,
1058                                                                          annotation.pp_ann(),
1059                                                                          true);
1060                     for node_id in uii.all_matching_node_ids(hir_map) {
1061                         let node = hir_map.get(node_id);
1062                         pp_state.print_node(node)?;
1063                         pp_state.s.space()?;
1064                         let path = annotation.node_path(node_id)
1065                             .expect("-Z unpretty missing node paths");
1066                         pp_state.synth_comment(path)?;
1067                         pp_state.s.hardbreak()?;
1068                     }
1069                     pp_state.s.eof()
1070                 })
1071             }
1072
1073             (PpmHirTree(s), Some(uii)) => {
1074                 let out: &mut dyn Write = &mut out;
1075                 s.call_with_pp_support_hir(sess,
1076                                            cstore,
1077                                            hir_map,
1078                                            resolutions,
1079                                            output_filenames,
1080                                            crate_name,
1081                                            move |_annotation, _krate| {
1082                     debug!("pretty printing source code {:?}", s);
1083                     for node_id in uii.all_matching_node_ids(hir_map) {
1084                         let node = hir_map.get(node_id);
1085                         write!(out, "{:#?}", node)?;
1086                     }
1087                     Ok(())
1088                 })
1089             }
1090
1091             _ => unreachable!(),
1092         }
1093         .unwrap();
1094
1095     write_output(out, ofile);
1096 }
1097
1098 // In an ideal world, this would be a public function called by the driver after
1099 // analysis is performed. However, we want to call `phase_3_run_analysis_passes`
1100 // with a different callback than the standard driver, so that isn't easy.
1101 // Instead, we call that function ourselves.
1102 fn print_with_analysis<'tcx, 'a: 'tcx>(sess: &'a Session,
1103                                        cstore: &'a CStore,
1104                                        hir_map: &hir_map::Map<'tcx>,
1105                                        resolutions: &Resolutions,
1106                                        crate_name: &str,
1107                                        output_filenames: &OutputFilenames,
1108                                        ppm: PpMode,
1109                                        uii: Option<UserIdentifiedItem>,
1110                                        ofile: Option<&Path>) {
1111     let nodeid = if let Some(uii) = uii {
1112         debug!("pretty printing for {:?}", uii);
1113         Some(uii.to_one_node_id("-Z unpretty", sess, &hir_map))
1114     } else {
1115         debug!("pretty printing for whole crate");
1116         None
1117     };
1118
1119     let mut out = Vec::new();
1120
1121     let control = &driver::CompileController::basic();
1122     let codegen_backend = ::get_codegen_backend(sess);
1123     let mut arenas = AllArenas::new();
1124     abort_on_err(driver::phase_3_run_analysis_passes(&*codegen_backend,
1125                                                      control,
1126                                                      sess,
1127                                                      cstore,
1128                                                      hir_map.clone(),
1129                                                      resolutions.clone(),
1130                                                      &mut arenas,
1131                                                      crate_name,
1132                                                      output_filenames,
1133                                                      |tcx, _, _| {
1134         match ppm {
1135             PpmMir | PpmMirCFG => {
1136                 if let Some(nodeid) = nodeid {
1137                     let def_id = tcx.hir().local_def_id(nodeid);
1138                     match ppm {
1139                         PpmMir => write_mir_pretty(tcx, Some(def_id), &mut out),
1140                         PpmMirCFG => write_mir_graphviz(tcx, Some(def_id), &mut out),
1141                         _ => unreachable!(),
1142                     }?;
1143                 } else {
1144                     match ppm {
1145                         PpmMir => write_mir_pretty(tcx, None, &mut out),
1146                         PpmMirCFG => write_mir_graphviz(tcx, None, &mut out),
1147                         _ => unreachable!(),
1148                     }?;
1149                 }
1150                 Ok(())
1151             }
1152             PpmFlowGraph(mode) => {
1153                 let nodeid =
1154                     nodeid.expect("`pretty flowgraph=..` needs NodeId (int) or unique path \
1155                                    suffix (b::c::d)");
1156                 let node = tcx.hir().find(nodeid).unwrap_or_else(|| {
1157                     tcx.sess.fatal(&format!("--pretty flowgraph couldn't find id: {}", nodeid))
1158                 });
1159
1160                 match blocks::Code::from_node(&tcx.hir(), nodeid) {
1161                     Some(code) => {
1162                         let variants = gather_flowgraph_variants(tcx.sess);
1163
1164                         let out: &mut dyn Write = &mut out;
1165
1166                         print_flowgraph(variants, tcx, code, mode, out)
1167                     }
1168                     None => {
1169                         let message = format!("--pretty=flowgraph needs block, fn, or method; \
1170                                                got {:?}",
1171                                               node);
1172
1173                         tcx.sess.span_fatal(tcx.hir().span(nodeid), &message)
1174                     }
1175                 }
1176             }
1177             _ => unreachable!(),
1178         }
1179     }),
1180                  sess)
1181         .unwrap();
1182
1183     write_output(out, ofile);
1184 }