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