]> git.lizzy.rs Git - rust.git/blob - src/librustc_driver/pretty.rs
Auto merge of #43648 - RalfJung:jemalloc-debug, r=alexcrichton
[rust.git] / src / librustc_driver / pretty.rs
1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! The various pretty print routines.
12
13 pub use self::UserIdentifiedItem::*;
14 pub use self::PpSourceMode::*;
15 pub use self::PpMode::*;
16 use self::NodesMatchingUII::*;
17
18 use {abort_on_err, driver};
19
20 use rustc::ty::{self, TyCtxt, GlobalArenas, Resolutions};
21 use rustc::cfg;
22 use rustc::cfg::graphviz::LabelledCFG;
23 use rustc::dep_graph::DepGraph;
24 use rustc::session::Session;
25 use rustc::session::config::Input;
26 use rustc_borrowck as borrowck;
27 use rustc_borrowck::graphviz as borrowck_dot;
28
29 use rustc_mir::util::{write_mir_pretty, write_mir_graphviz};
30
31 use syntax::ast::{self, BlockCheckMode};
32 use syntax::fold::{self, Folder};
33 use syntax::print::{pprust};
34 use syntax::print::pprust::PrintState;
35 use syntax::ptr::P;
36 use syntax::util::small_vector::SmallVector;
37 use syntax_pos;
38
39 use graphviz as dot;
40
41 use std::cell::Cell;
42 use std::fs::File;
43 use std::io::{self, Write};
44 use std::option;
45 use std::path::Path;
46 use std::str::FromStr;
47 use std::mem;
48
49 use rustc::hir::map as hir_map;
50 use rustc::hir::map::blocks;
51 use rustc::hir;
52 use rustc::hir::print as pprust_hir;
53
54 use arena::DroplessArena;
55
56 #[derive(Copy, Clone, PartialEq, Debug)]
57 pub enum PpSourceMode {
58     PpmNormal,
59     PpmEveryBodyLoops,
60     PpmExpanded,
61     PpmIdentified,
62     PpmExpandedIdentified,
63     PpmExpandedHygiene,
64     PpmTyped,
65 }
66
67 #[derive(Copy, Clone, PartialEq, Debug)]
68 pub enum PpFlowGraphMode {
69     Default,
70     /// Drops the labels from the edges in the flowgraph output. This
71     /// is mostly for use in the --unpretty flowgraph run-make tests,
72     /// since the labels are largely uninteresting in those cases and
73     /// have become a pain to maintain.
74     UnlabelledEdges,
75 }
76 #[derive(Copy, Clone, PartialEq, Debug)]
77 pub enum PpMode {
78     PpmSource(PpSourceMode),
79     PpmHir(PpSourceMode),
80     PpmFlowGraph(PpFlowGraphMode),
81     PpmMir,
82     PpmMirCFG,
83 }
84
85 impl PpMode {
86     pub fn needs_ast_map(&self, opt_uii: &Option<UserIdentifiedItem>) -> bool {
87         match *self {
88             PpmSource(PpmNormal) |
89             PpmSource(PpmEveryBodyLoops) |
90             PpmSource(PpmIdentified) => opt_uii.is_some(),
91
92             PpmSource(PpmExpanded) |
93             PpmSource(PpmExpandedIdentified) |
94             PpmSource(PpmExpandedHygiene) |
95             PpmHir(_) |
96             PpmMir |
97             PpmMirCFG |
98             PpmFlowGraph(_) => true,
99             PpmSource(PpmTyped) => panic!("invalid state"),
100         }
101     }
102
103     pub fn needs_analysis(&self) -> bool {
104         match *self {
105             PpmMir | PpmMirCFG | PpmFlowGraph(_) => true,
106             _ => false,
107         }
108     }
109 }
110
111 pub fn parse_pretty(sess: &Session,
112                     name: &str,
113                     extended: bool)
114                     -> (PpMode, Option<UserIdentifiedItem>) {
115     let mut split = name.splitn(2, '=');
116     let first = split.next().unwrap();
117     let opt_second = split.next();
118     let first = match (first, extended) {
119         ("normal", _) => PpmSource(PpmNormal),
120         ("identified", _) => PpmSource(PpmIdentified),
121         ("everybody_loops", true) => PpmSource(PpmEveryBodyLoops),
122         ("expanded", _) => PpmSource(PpmExpanded),
123         ("expanded,identified", _) => PpmSource(PpmExpandedIdentified),
124         ("expanded,hygiene", _) => PpmSource(PpmExpandedHygiene),
125         ("hir", true) => PpmHir(PpmNormal),
126         ("hir,identified", true) => PpmHir(PpmIdentified),
127         ("hir,typed", true) => PpmHir(PpmTyped),
128         ("mir", true) => PpmMir,
129         ("mir-cfg", true) => PpmMirCFG,
130         ("flowgraph", true) => PpmFlowGraph(PpFlowGraphMode::Default),
131         ("flowgraph,unlabelled", true) => PpmFlowGraph(PpFlowGraphMode::UnlabelledEdges),
132         _ => {
133             if extended {
134                 sess.fatal(&format!("argument to `unpretty` must be one of `normal`, \
135                                      `expanded`, `flowgraph[,unlabelled]=<nodeid>`, \
136                                      `identified`, `expanded,identified`, `everybody_loops`, \
137                                      `hir`, `hir,identified`, `hir,typed`, or `mir`; got {}",
138                                     name));
139             } else {
140                 sess.fatal(&format!("argument to `pretty` must be one of `normal`, `expanded`, \
141                                      `identified`, or `expanded,identified`; got {}",
142                                     name));
143             }
144         }
145     };
146     let opt_second = opt_second.and_then(|s| s.parse::<UserIdentifiedItem>().ok());
147     (first, opt_second)
148 }
149
150
151
152 // This slightly awkward construction is to allow for each PpMode to
153 // choose whether it needs to do analyses (which can consume the
154 // Session) and then pass through the session (now attached to the
155 // analysis results) on to the chosen pretty-printer, along with the
156 // `&PpAnn` object.
157 //
158 // Note that since the `&PrinterSupport` is freshly constructed on each
159 // call, it would not make sense to try to attach the lifetime of `self`
160 // to the lifetime of the `&PrinterObject`.
161 //
162 // (The `use_once_payload` is working around the current lack of once
163 // functions in the compiler.)
164
165 impl PpSourceMode {
166     /// Constructs a `PrinterSupport` object and passes it to `f`.
167     fn call_with_pp_support<'tcx, A, F>(&self,
168                                            sess: &'tcx Session,
169                                            hir_map: Option<&hir_map::Map<'tcx>>,
170                                            f: F)
171                                            -> A
172         where F: FnOnce(&PrinterSupport) -> A
173     {
174         match *self {
175             PpmNormal | PpmEveryBodyLoops | PpmExpanded => {
176                 let annotation = NoAnn {
177                     sess,
178                     hir_map: hir_map.map(|m| m.clone()),
179                 };
180                 f(&annotation)
181             }
182
183             PpmIdentified | PpmExpandedIdentified => {
184                 let annotation = IdentifiedAnnotation {
185                     sess,
186                     hir_map: hir_map.map(|m| m.clone()),
187                 };
188                 f(&annotation)
189             }
190             PpmExpandedHygiene => {
191                 let annotation = HygieneAnnotation {
192                     sess,
193                 };
194                 f(&annotation)
195             }
196             _ => panic!("Should use call_with_pp_support_hir"),
197         }
198     }
199     fn call_with_pp_support_hir<'tcx, A, F>(&self,
200                                                sess: &'tcx Session,
201                                                hir_map: &hir_map::Map<'tcx>,
202                                                analysis: &ty::CrateAnalysis,
203                                                resolutions: &Resolutions,
204                                                arena: &'tcx DroplessArena,
205                                                arenas: &'tcx GlobalArenas<'tcx>,
206                                                id: &str,
207                                                f: F)
208                                                -> A
209         where F: FnOnce(&HirPrinterSupport, &hir::Crate) -> A
210     {
211         match *self {
212             PpmNormal => {
213                 let annotation = NoAnn {
214                     sess,
215                     hir_map: Some(hir_map.clone()),
216                 };
217                 f(&annotation, hir_map.forest.krate())
218             }
219
220             PpmIdentified => {
221                 let annotation = IdentifiedAnnotation {
222                     sess,
223                     hir_map: Some(hir_map.clone()),
224                 };
225                 f(&annotation, hir_map.forest.krate())
226             }
227             PpmTyped => {
228                 abort_on_err(driver::phase_3_run_analysis_passes(sess,
229                                                                  hir_map.clone(),
230                                                                  analysis.clone(),
231                                                                  resolutions.clone(),
232                                                                  arena,
233                                                                  arenas,
234                                                                  id,
235                                                                  |tcx, _, _, _| {
236                     let empty_tables = ty::TypeckTables::empty(None);
237                     let annotation = TypedAnnotation {
238                         tcx,
239                         tables: Cell::new(&empty_tables)
240                     };
241                     let _ignore = tcx.dep_graph.in_ignore();
242                     f(&annotation, hir_map.forest.krate())
243                 }),
244                              sess)
245             }
246             _ => panic!("Should use call_with_pp_support"),
247         }
248     }
249 }
250
251 trait PrinterSupport: pprust::PpAnn {
252     /// Provides a uniform interface for re-extracting a reference to a
253     /// `Session` from a value that now owns it.
254     fn sess<'a>(&'a self) -> &'a Session;
255
256     /// Produces the pretty-print annotation object.
257     ///
258     /// (Rust does not yet support upcasting from a trait object to
259     /// an object for one of its super-traits.)
260     fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn;
261 }
262
263 trait HirPrinterSupport<'hir>: pprust_hir::PpAnn {
264     /// Provides a uniform interface for re-extracting a reference to a
265     /// `Session` from a value that now owns it.
266     fn sess<'a>(&'a self) -> &'a Session;
267
268     /// Provides a uniform interface for re-extracting a reference to an
269     /// `hir_map::Map` from a value that now owns it.
270     fn hir_map<'a>(&'a self) -> Option<&'a hir_map::Map<'hir>>;
271
272     /// Produces the pretty-print annotation object.
273     ///
274     /// (Rust does not yet support upcasting from a trait object to
275     /// an object for one of its super-traits.)
276     fn pp_ann<'a>(&'a self) -> &'a pprust_hir::PpAnn;
277
278     /// Computes an user-readable representation of a path, if possible.
279     fn node_path(&self, id: ast::NodeId) -> Option<String> {
280         self.hir_map().and_then(|map| map.def_path_from_id(id)).map(|path| {
281             path.data
282                 .into_iter()
283                 .map(|elem| elem.data.to_string())
284                 .collect::<Vec<_>>()
285                 .join("::")
286         })
287     }
288 }
289
290 struct NoAnn<'hir> {
291     sess: &'hir Session,
292     hir_map: Option<hir_map::Map<'hir>>,
293 }
294
295 impl<'hir> PrinterSupport for NoAnn<'hir> {
296     fn sess<'a>(&'a self) -> &'a Session {
297         self.sess
298     }
299
300     fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn {
301         self
302     }
303 }
304
305 impl<'hir> HirPrinterSupport<'hir> for NoAnn<'hir> {
306     fn sess<'a>(&'a self) -> &'a Session {
307         self.sess
308     }
309
310     fn hir_map<'a>(&'a self) -> Option<&'a hir_map::Map<'hir>> {
311         self.hir_map.as_ref()
312     }
313
314     fn pp_ann<'a>(&'a self) -> &'a pprust_hir::PpAnn {
315         self
316     }
317 }
318
319 impl<'hir> pprust::PpAnn for NoAnn<'hir> {}
320 impl<'hir> pprust_hir::PpAnn for NoAnn<'hir> {
321     fn nested(&self, state: &mut pprust_hir::State, nested: pprust_hir::Nested)
322               -> io::Result<()> {
323         if let Some(ref map) = self.hir_map {
324             pprust_hir::PpAnn::nested(map, state, nested)
325         } else {
326             Ok(())
327         }
328     }
329 }
330
331 struct IdentifiedAnnotation<'hir> {
332     sess: &'hir Session,
333     hir_map: Option<hir_map::Map<'hir>>,
334 }
335
336 impl<'hir> PrinterSupport for IdentifiedAnnotation<'hir> {
337     fn sess<'a>(&'a self) -> &'a Session {
338         self.sess
339     }
340
341     fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn {
342         self
343     }
344 }
345
346 impl<'hir> pprust::PpAnn for IdentifiedAnnotation<'hir> {
347     fn pre(&self, s: &mut pprust::State, node: pprust::AnnNode) -> io::Result<()> {
348         match node {
349             pprust::NodeExpr(_) => s.popen(),
350             _ => Ok(()),
351         }
352     }
353     fn post(&self, s: &mut pprust::State, node: pprust::AnnNode) -> io::Result<()> {
354         match node {
355             pprust::NodeIdent(_) |
356             pprust::NodeName(_) => Ok(()),
357
358             pprust::NodeItem(item) => {
359                 s.s.space()?;
360                 s.synth_comment(item.id.to_string())
361             }
362             pprust::NodeSubItem(id) => {
363                 s.s.space()?;
364                 s.synth_comment(id.to_string())
365             }
366             pprust::NodeBlock(blk) => {
367                 s.s.space()?;
368                 s.synth_comment(format!("block {}", blk.id))
369             }
370             pprust::NodeExpr(expr) => {
371                 s.s.space()?;
372                 s.synth_comment(expr.id.to_string())?;
373                 s.pclose()
374             }
375             pprust::NodePat(pat) => {
376                 s.s.space()?;
377                 s.synth_comment(format!("pat {}", pat.id))
378             }
379         }
380     }
381 }
382
383 impl<'hir> HirPrinterSupport<'hir> for IdentifiedAnnotation<'hir> {
384     fn sess<'a>(&'a self) -> &'a Session {
385         self.sess
386     }
387
388     fn hir_map<'a>(&'a self) -> Option<&'a hir_map::Map<'hir>> {
389         self.hir_map.as_ref()
390     }
391
392     fn pp_ann<'a>(&'a self) -> &'a pprust_hir::PpAnn {
393         self
394     }
395 }
396
397 impl<'hir> pprust_hir::PpAnn for IdentifiedAnnotation<'hir> {
398     fn nested(&self, state: &mut pprust_hir::State, nested: pprust_hir::Nested)
399               -> io::Result<()> {
400         if let Some(ref map) = self.hir_map {
401             pprust_hir::PpAnn::nested(map, state, nested)
402         } else {
403             Ok(())
404         }
405     }
406     fn pre(&self, s: &mut pprust_hir::State, node: pprust_hir::AnnNode) -> io::Result<()> {
407         match node {
408             pprust_hir::NodeExpr(_) => s.popen(),
409             _ => Ok(()),
410         }
411     }
412     fn post(&self, s: &mut pprust_hir::State, node: pprust_hir::AnnNode) -> io::Result<()> {
413         match node {
414             pprust_hir::NodeName(_) => Ok(()),
415             pprust_hir::NodeItem(item) => {
416                 s.s.space()?;
417                 s.synth_comment(item.id.to_string())
418             }
419             pprust_hir::NodeSubItem(id) => {
420                 s.s.space()?;
421                 s.synth_comment(id.to_string())
422             }
423             pprust_hir::NodeBlock(blk) => {
424                 s.s.space()?;
425                 s.synth_comment(format!("block {}", blk.id))
426             }
427             pprust_hir::NodeExpr(expr) => {
428                 s.s.space()?;
429                 s.synth_comment(expr.id.to_string())?;
430                 s.pclose()
431             }
432             pprust_hir::NodePat(pat) => {
433                 s.s.space()?;
434                 s.synth_comment(format!("pat {}", pat.id))
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) -> &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::NodeIdent(&ast::Ident { name, ctxt }) => {
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(), ctxt))
462             }
463             pprust::NodeName(&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 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::NodeExpr(_) => 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::NodeExpr(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::new)
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
577 impl UserIdentifiedItem {
578     fn reconstructed_input(&self) -> String {
579         match *self {
580             ItemViaNode(node_id) => node_id.to_string(),
581             ItemViaPath(ref parts) => parts.join("::"),
582         }
583     }
584
585     fn all_matching_node_ids<'a, 'hir>(&'a self,
586                                        map: &'a hir_map::Map<'hir>)
587                                        -> NodesMatchingUII<'a, 'hir> {
588         match *self {
589             ItemViaNode(node_id) => NodesMatchingDirect(Some(node_id).into_iter()),
590             ItemViaPath(ref parts) => NodesMatchingSuffix(map.nodes_matching_suffix(&parts)),
591         }
592     }
593
594     fn to_one_node_id(self, user_option: &str, sess: &Session, map: &hir_map::Map) -> ast::NodeId {
595         let fail_because = |is_wrong_because| -> ast::NodeId {
596             let message = format!("{} needs NodeId (int) or unique path suffix (b::c::d); got \
597                                    {}, which {}",
598                                   user_option,
599                                   self.reconstructed_input(),
600                                   is_wrong_because);
601             sess.fatal(&message)
602         };
603
604         let mut saw_node = ast::DUMMY_NODE_ID;
605         let mut seen = 0;
606         for node in self.all_matching_node_ids(map) {
607             saw_node = node;
608             seen += 1;
609             if seen > 1 {
610                 fail_because("does not resolve uniquely");
611             }
612         }
613         if seen == 0 {
614             fail_because("does not resolve to any item");
615         }
616
617         assert!(seen == 1);
618         return saw_node;
619     }
620 }
621
622 // Note: Also used by librustdoc, see PR #43348. Consider moving this struct elsewhere.
623 //
624 // FIXME: Currently the `everybody_loops` transformation is not applied to:
625 //  * `const fn`, due to issue #43636 that `loop` is not supported for const evaluation. We are
626 //    waiting for miri to fix that.
627 //  * `impl Trait`, due to issue #43869 that functions returning impl Trait cannot be diverging.
628 //    Solving this may require `!` to implement every trait, which relies on the an even more
629 //    ambitious form of the closed RFC #1637. See also [#34511].
630 //
631 // [#34511]: https://github.com/rust-lang/rust/issues/34511#issuecomment-322340401
632 pub struct ReplaceBodyWithLoop {
633     within_static_or_const: bool,
634 }
635
636 impl ReplaceBodyWithLoop {
637     pub fn new() -> ReplaceBodyWithLoop {
638         ReplaceBodyWithLoop { within_static_or_const: false }
639     }
640
641     fn run<R, F: FnOnce(&mut Self) -> R>(&mut self, is_const: bool, action: F) -> R {
642         let old_const = mem::replace(&mut self.within_static_or_const, is_const);
643         let ret = action(self);
644         self.within_static_or_const = old_const;
645         ret
646     }
647
648     fn should_ignore_fn(ret_ty: &ast::FnDecl) -> bool {
649         if let ast::FunctionRetTy::Ty(ref ty) = ret_ty.output {
650             fn involves_impl_trait(ty: &ast::Ty) -> bool {
651                 match ty.node {
652                     ast::TyKind::ImplTrait(_) => true,
653                     ast::TyKind::Slice(ref subty) |
654                     ast::TyKind::Array(ref subty, _) |
655                     ast::TyKind::Ptr(ast::MutTy { ty: ref subty, .. }) |
656                     ast::TyKind::Rptr(_, ast::MutTy { ty: ref subty, .. }) |
657                     ast::TyKind::Paren(ref subty) => involves_impl_trait(subty),
658                     ast::TyKind::Tup(ref tys) => tys.iter().any(|subty| involves_impl_trait(subty)),
659                     _ => false,
660                 }
661             }
662             involves_impl_trait(ty)
663         } else {
664             false
665         }
666     }
667 }
668
669 impl fold::Folder for ReplaceBodyWithLoop {
670     fn fold_item_kind(&mut self, i: ast::ItemKind) -> ast::ItemKind {
671         let is_const = match i {
672             ast::ItemKind::Static(..) | ast::ItemKind::Const(..) => true,
673             ast::ItemKind::Fn(ref decl, _, ref constness, _, _, _) =>
674                 constness.node == ast::Constness::Const || Self::should_ignore_fn(decl),
675             _ => false,
676         };
677         self.run(is_const, |s| fold::noop_fold_item_kind(i, s))
678     }
679
680     fn fold_trait_item(&mut self, i: ast::TraitItem) -> SmallVector<ast::TraitItem> {
681         let is_const = match i.node {
682             ast::TraitItemKind::Const(..) => true,
683             ast::TraitItemKind::Method(ast::MethodSig { ref decl, ref constness, .. }, _) =>
684                 constness.node == ast::Constness::Const || Self::should_ignore_fn(decl),
685             _ => false,
686         };
687         self.run(is_const, |s| fold::noop_fold_trait_item(i, s))
688     }
689
690     fn fold_impl_item(&mut self, i: ast::ImplItem) -> SmallVector<ast::ImplItem> {
691         let is_const = match i.node {
692             ast::ImplItemKind::Const(..) => true,
693             ast::ImplItemKind::Method(ast::MethodSig { ref decl, ref constness, .. }, _) =>
694                 constness.node == ast::Constness::Const || Self::should_ignore_fn(decl),
695             _ => false,
696         };
697         self.run(is_const, |s| fold::noop_fold_impl_item(i, s))
698     }
699
700     fn fold_block(&mut self, b: P<ast::Block>) -> P<ast::Block> {
701         fn expr_to_block(rules: ast::BlockCheckMode, e: Option<P<ast::Expr>>) -> P<ast::Block> {
702             P(ast::Block {
703                 stmts: e.map(|e| {
704                         ast::Stmt {
705                             id: ast::DUMMY_NODE_ID,
706                             span: e.span,
707                             node: ast::StmtKind::Expr(e),
708                         }
709                     })
710                     .into_iter()
711                     .collect(),
712                 rules,
713                 id: ast::DUMMY_NODE_ID,
714                 span: syntax_pos::DUMMY_SP,
715             })
716         }
717
718         if !self.within_static_or_const {
719
720             let empty_block = expr_to_block(BlockCheckMode::Default, None);
721             let loop_expr = P(ast::Expr {
722                 node: ast::ExprKind::Loop(empty_block, None),
723                 id: ast::DUMMY_NODE_ID,
724                 span: syntax_pos::DUMMY_SP,
725                 attrs: ast::ThinVec::new(),
726             });
727
728             expr_to_block(b.rules, Some(loop_expr))
729
730         } else {
731             fold::noop_fold_block(b, self)
732         }
733     }
734
735     // in general the pretty printer processes unexpanded code, so
736     // we override the default `fold_mac` method which panics.
737     fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac {
738         fold::noop_fold_mac(mac, self)
739     }
740 }
741
742 fn print_flowgraph<'a, 'tcx, W: Write>(variants: Vec<borrowck_dot::Variant>,
743                                        tcx: TyCtxt<'a, 'tcx, 'tcx>,
744                                        code: blocks::Code<'tcx>,
745                                        mode: PpFlowGraphMode,
746                                        mut out: W)
747                                        -> io::Result<()> {
748     let body_id = match code {
749         blocks::Code::Expr(expr) => {
750             // Find the function this expression is from.
751             let mut node_id = expr.id;
752             loop {
753                 let node = tcx.hir.get(node_id);
754                 if let Some(n) = hir::map::blocks::FnLikeNode::from_node(node) {
755                     break n.body();
756                 }
757                 let parent = tcx.hir.get_parent_node(node_id);
758                 assert!(node_id != parent);
759                 node_id = parent;
760             }
761         }
762         blocks::Code::FnLike(fn_like) => fn_like.body(),
763     };
764     let body = tcx.hir.body(body_id);
765     let cfg = cfg::CFG::new(tcx, &body);
766     let labelled_edges = mode != PpFlowGraphMode::UnlabelledEdges;
767     let lcfg = LabelledCFG {
768         hir_map: &tcx.hir,
769         cfg: &cfg,
770         name: format!("node_{}", code.id()),
771         labelled_edges,
772     };
773
774     match code {
775         _ if variants.is_empty() => {
776             let r = dot::render(&lcfg, &mut out);
777             return expand_err_details(r);
778         }
779         blocks::Code::Expr(_) => {
780             tcx.sess.err("--pretty flowgraph with -Z flowgraph-print annotations requires \
781                           fn-like node id.");
782             return Ok(());
783         }
784         blocks::Code::FnLike(fn_like) => {
785             let (bccx, analysis_data) =
786                 borrowck::build_borrowck_dataflow_data_for_fn(tcx, fn_like.body(), &cfg);
787
788             let lcfg = borrowck_dot::DataflowLabeller {
789                 inner: lcfg,
790                 variants,
791                 borrowck_ctxt: &bccx,
792                 analysis_data: &analysis_data,
793             };
794             let r = dot::render(&lcfg, &mut out);
795             return expand_err_details(r);
796         }
797     }
798
799     fn expand_err_details(r: io::Result<()>) -> io::Result<()> {
800         r.map_err(|ioerr| {
801             io::Error::new(io::ErrorKind::Other,
802                            format!("graphviz::render failed: {}", ioerr))
803         })
804     }
805 }
806
807 pub fn fold_crate(krate: ast::Crate, ppm: PpMode) -> ast::Crate {
808     if let PpmSource(PpmEveryBodyLoops) = ppm {
809         let mut fold = ReplaceBodyWithLoop::new();
810         fold.fold_crate(krate)
811     } else {
812         krate
813     }
814 }
815
816 fn get_source(input: &Input, sess: &Session) -> (Vec<u8>, String) {
817     let src_name = driver::source_name(input);
818     let src = sess.codemap()
819         .get_filemap(&src_name)
820         .unwrap()
821         .src
822         .as_ref()
823         .unwrap()
824         .as_bytes()
825         .to_vec();
826     (src, src_name)
827 }
828
829 fn write_output(out: Vec<u8>, ofile: Option<&Path>) {
830     match ofile {
831         None => print!("{}", String::from_utf8(out).unwrap()),
832         Some(p) => {
833             match File::create(p) {
834                 Ok(mut w) => w.write_all(&out).unwrap(),
835                 Err(e) => panic!("print-print failed to open {} due to {}", p.display(), e),
836             }
837         }
838     }
839 }
840
841 pub fn print_after_parsing(sess: &Session,
842                            input: &Input,
843                            krate: &ast::Crate,
844                            ppm: PpMode,
845                            ofile: Option<&Path>) {
846     let dep_graph = DepGraph::new(false);
847     let _ignore = dep_graph.in_ignore();
848
849     let (src, src_name) = get_source(input, sess);
850
851     let mut rdr = &*src;
852     let mut out = Vec::new();
853
854     if let PpmSource(s) = ppm {
855         // Silently ignores an identified node.
856         let out: &mut Write = &mut out;
857         s.call_with_pp_support(sess, None, move |annotation| {
858                 debug!("pretty printing source code {:?}", s);
859                 let sess = annotation.sess();
860                 pprust::print_crate(sess.codemap(),
861                                     &sess.parse_sess,
862                                     krate,
863                                     src_name.to_string(),
864                                     &mut rdr,
865                                     box out,
866                                     annotation.pp_ann(),
867                                     false)
868             })
869             .unwrap()
870     } else {
871         unreachable!();
872     };
873
874     write_output(out, ofile);
875 }
876
877 pub fn print_after_hir_lowering<'tcx, 'a: 'tcx>(sess: &'a Session,
878                                                 hir_map: &hir_map::Map<'tcx>,
879                                                 analysis: &ty::CrateAnalysis,
880                                                 resolutions: &Resolutions,
881                                                 input: &Input,
882                                                 krate: &ast::Crate,
883                                                 crate_name: &str,
884                                                 ppm: PpMode,
885                                                 arena: &'tcx DroplessArena,
886                                                 arenas: &'tcx GlobalArenas<'tcx>,
887                                                 opt_uii: Option<UserIdentifiedItem>,
888                                                 ofile: Option<&Path>) {
889     let dep_graph = DepGraph::new(false);
890     let _ignore = dep_graph.in_ignore();
891
892     if ppm.needs_analysis() {
893         print_with_analysis(sess,
894                             hir_map,
895                             analysis,
896                             resolutions,
897                             crate_name,
898                             arena,
899                             arenas,
900                             ppm,
901                             opt_uii,
902                             ofile);
903         return;
904     }
905
906     let (src, src_name) = get_source(input, sess);
907
908     let mut rdr = &src[..];
909     let mut out = Vec::new();
910
911     match (ppm, opt_uii) {
912             (PpmSource(s), _) => {
913                 // Silently ignores an identified node.
914                 let out: &mut Write = &mut out;
915                 s.call_with_pp_support(sess, Some(hir_map), move |annotation| {
916                     debug!("pretty printing source code {:?}", s);
917                     let sess = annotation.sess();
918                     pprust::print_crate(sess.codemap(),
919                                         &sess.parse_sess,
920                                         krate,
921                                         src_name.to_string(),
922                                         &mut rdr,
923                                         box out,
924                                         annotation.pp_ann(),
925                                         true)
926                 })
927             }
928
929             (PpmHir(s), None) => {
930                 let out: &mut Write = &mut out;
931                 s.call_with_pp_support_hir(sess,
932                                            hir_map,
933                                            analysis,
934                                            resolutions,
935                                            arena,
936                                            arenas,
937                                            crate_name,
938                                            move |annotation, krate| {
939                     debug!("pretty printing source code {:?}", s);
940                     let sess = annotation.sess();
941                     pprust_hir::print_crate(sess.codemap(),
942                                             &sess.parse_sess,
943                                             krate,
944                                             src_name.to_string(),
945                                             &mut rdr,
946                                             box out,
947                                             annotation.pp_ann(),
948                                             true)
949                 })
950             }
951
952             (PpmHir(s), Some(uii)) => {
953                 let out: &mut Write = &mut out;
954                 s.call_with_pp_support_hir(sess,
955                                            hir_map,
956                                            analysis,
957                                            resolutions,
958                                            arena,
959                                            arenas,
960                                            crate_name,
961                                            move |annotation, _| {
962                     debug!("pretty printing source code {:?}", s);
963                     let sess = annotation.sess();
964                     let hir_map = annotation.hir_map().expect("--unpretty missing HIR map");
965                     let mut pp_state = pprust_hir::State::new_from_input(sess.codemap(),
966                                                                          &sess.parse_sess,
967                                                                          src_name.to_string(),
968                                                                          &mut rdr,
969                                                                          box out,
970                                                                          annotation.pp_ann(),
971                                                                          true);
972                     for node_id in uii.all_matching_node_ids(hir_map) {
973                         let node = hir_map.get(node_id);
974                         pp_state.print_node(node)?;
975                         pp_state.s.space()?;
976                         let path = annotation.node_path(node_id)
977                             .expect("--unpretty missing node paths");
978                         pp_state.synth_comment(path)?;
979                         pp_state.s.hardbreak()?;
980                     }
981                     pp_state.s.eof()
982                 })
983             }
984             _ => unreachable!(),
985         }
986         .unwrap();
987
988     write_output(out, ofile);
989 }
990
991 // In an ideal world, this would be a public function called by the driver after
992 // analsysis is performed. However, we want to call `phase_3_run_analysis_passes`
993 // with a different callback than the standard driver, so that isn't easy.
994 // Instead, we call that function ourselves.
995 fn print_with_analysis<'tcx, 'a: 'tcx>(sess: &'a Session,
996                                        hir_map: &hir_map::Map<'tcx>,
997                                        analysis: &ty::CrateAnalysis,
998                                        resolutions: &Resolutions,
999                                        crate_name: &str,
1000                                        arena: &'tcx DroplessArena,
1001                                        arenas: &'tcx GlobalArenas<'tcx>,
1002                                        ppm: PpMode,
1003                                        uii: Option<UserIdentifiedItem>,
1004                                        ofile: Option<&Path>) {
1005     let nodeid = if let Some(uii) = uii {
1006         debug!("pretty printing for {:?}", uii);
1007         Some(uii.to_one_node_id("--unpretty", sess, &hir_map))
1008     } else {
1009         debug!("pretty printing for whole crate");
1010         None
1011     };
1012
1013     let mut out = Vec::new();
1014
1015     abort_on_err(driver::phase_3_run_analysis_passes(sess,
1016                                                      hir_map.clone(),
1017                                                      analysis.clone(),
1018                                                      resolutions.clone(),
1019                                                      arena,
1020                                                      arenas,
1021                                                      crate_name,
1022                                                      |tcx, _, _, _| {
1023         match ppm {
1024             PpmMir | PpmMirCFG => {
1025                 if let Some(nodeid) = nodeid {
1026                     let def_id = tcx.hir.local_def_id(nodeid);
1027                     match ppm {
1028                         PpmMir => write_mir_pretty(tcx, Some(def_id), &mut out),
1029                         PpmMirCFG => write_mir_graphviz(tcx, Some(def_id), &mut out),
1030                         _ => unreachable!(),
1031                     }?;
1032                 } else {
1033                     match ppm {
1034                         PpmMir => write_mir_pretty(tcx, None, &mut out),
1035                         PpmMirCFG => write_mir_graphviz(tcx, None, &mut out),
1036                         _ => unreachable!(),
1037                     }?;
1038                 }
1039                 Ok(())
1040             }
1041             PpmFlowGraph(mode) => {
1042                 let nodeid =
1043                     nodeid.expect("`pretty flowgraph=..` needs NodeId (int) or unique path \
1044                                    suffix (b::c::d)");
1045                 let node = tcx.hir.find(nodeid).unwrap_or_else(|| {
1046                     tcx.sess.fatal(&format!("--pretty flowgraph couldn't find id: {}", nodeid))
1047                 });
1048
1049                 match blocks::Code::from_node(&tcx.hir, nodeid) {
1050                     Some(code) => {
1051                         let variants = gather_flowgraph_variants(tcx.sess);
1052
1053                         let out: &mut Write = &mut out;
1054
1055                         print_flowgraph(variants, tcx, code, mode, out)
1056                     }
1057                     None => {
1058                         let message = format!("--pretty=flowgraph needs block, fn, or method; \
1059                                                got {:?}",
1060                                               node);
1061
1062                         tcx.sess.span_fatal(tcx.hir.span(nodeid), &message)
1063                     }
1064                 }
1065             }
1066             _ => unreachable!(),
1067         }
1068     }),
1069                  sess)
1070         .unwrap();
1071
1072     write_output(out, ofile);
1073 }