]> git.proxmox.com Git - rustc.git/blob - src/librustc_driver/pretty.rs
Imported Upstream version 1.9.0+dfsg1
[rustc.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 rustc_trans::back::link;
19
20 use {driver, abort_on_err};
21
22 use rustc::dep_graph::DepGraph;
23 use rustc::ty::{self, TyCtxt};
24 use rustc::cfg;
25 use rustc::cfg::graphviz::LabelledCFG;
26 use rustc::session::Session;
27 use rustc::session::config::Input;
28 use rustc_borrowck as borrowck;
29 use rustc_borrowck::graphviz as borrowck_dot;
30 use rustc_resolve as resolve;
31 use rustc_metadata::cstore::CStore;
32
33 use rustc_mir::pretty::write_mir_pretty;
34 use rustc_mir::graphviz::write_mir_graphviz;
35
36 use syntax::ast::{self, BlockCheckMode};
37 use syntax::codemap;
38 use syntax::fold::{self, Folder};
39 use syntax::print::{pp, pprust};
40 use syntax::print::pprust::PrintState;
41 use syntax::ptr::P;
42 use syntax::util::small_vector::SmallVector;
43
44 use graphviz as dot;
45
46 use std::fs::File;
47 use std::io::{self, Write};
48 use std::iter;
49 use std::option;
50 use std::path::PathBuf;
51 use std::str::FromStr;
52
53 use rustc::hir::map as hir_map;
54 use rustc::hir::map::{blocks, NodePrinter};
55 use rustc::hir;
56 use rustc::hir::lowering::{lower_crate, LoweringContext};
57 use rustc::hir::print as pprust_hir;
58
59 use rustc::mir::mir_map::MirMap;
60
61 #[derive(Copy, Clone, PartialEq, Debug)]
62 pub enum PpSourceMode {
63 PpmNormal,
64 PpmEveryBodyLoops,
65 PpmExpanded,
66 PpmIdentified,
67 PpmExpandedIdentified,
68 PpmExpandedHygiene,
69 PpmTyped,
70 }
71
72 #[derive(Copy, Clone, PartialEq, Debug)]
73 pub enum PpFlowGraphMode {
74 Default,
75 /// Drops the labels from the edges in the flowgraph output. This
76 /// is mostly for use in the --unpretty flowgraph run-make tests,
77 /// since the labels are largely uninteresting in those cases and
78 /// have become a pain to maintain.
79 UnlabelledEdges,
80 }
81 #[derive(Copy, Clone, PartialEq, Debug)]
82 pub enum PpMode {
83 PpmSource(PpSourceMode),
84 PpmHir(PpSourceMode),
85 PpmFlowGraph(PpFlowGraphMode),
86 PpmMir,
87 PpmMirCFG,
88 }
89
90 pub fn parse_pretty(sess: &Session,
91 name: &str,
92 extended: bool)
93 -> (PpMode, Option<UserIdentifiedItem>) {
94 let mut split = name.splitn(2, '=');
95 let first = split.next().unwrap();
96 let opt_second = split.next();
97 let first = match (first, extended) {
98 ("normal", _) => PpmSource(PpmNormal),
99 ("identified", _) => PpmSource(PpmIdentified),
100 ("everybody_loops", true) => PpmSource(PpmEveryBodyLoops),
101 ("expanded", _) => PpmSource(PpmExpanded),
102 ("expanded,identified", _) => PpmSource(PpmExpandedIdentified),
103 ("expanded,hygiene", _) => PpmSource(PpmExpandedHygiene),
104 ("hir", true) => PpmHir(PpmNormal),
105 ("hir,identified", true) => PpmHir(PpmIdentified),
106 ("hir,typed", true) => PpmHir(PpmTyped),
107 ("mir", true) => PpmMir,
108 ("mir-cfg", true) => PpmMirCFG,
109 ("flowgraph", true) => PpmFlowGraph(PpFlowGraphMode::Default),
110 ("flowgraph,unlabelled", true) => PpmFlowGraph(PpFlowGraphMode::UnlabelledEdges),
111 _ => {
112 if extended {
113 sess.fatal(&format!("argument to `unpretty` must be one of `normal`, \
114 `expanded`, `flowgraph[,unlabelled]=<nodeid>`, \
115 `identified`, `expanded,identified`, `everybody_loops`, \
116 `hir`, `hir,identified`, `hir,typed`, or `mir`; got {}",
117 name));
118 } else {
119 sess.fatal(&format!("argument to `pretty` must be one of `normal`, `expanded`, \
120 `identified`, or `expanded,identified`; got {}",
121 name));
122 }
123 }
124 };
125 let opt_second = opt_second.and_then(|s| s.parse::<UserIdentifiedItem>().ok());
126 (first, opt_second)
127 }
128
129
130
131 // This slightly awkward construction is to allow for each PpMode to
132 // choose whether it needs to do analyses (which can consume the
133 // Session) and then pass through the session (now attached to the
134 // analysis results) on to the chosen pretty-printer, along with the
135 // `&PpAnn` object.
136 //
137 // Note that since the `&PrinterSupport` is freshly constructed on each
138 // call, it would not make sense to try to attach the lifetime of `self`
139 // to the lifetime of the `&PrinterObject`.
140 //
141 // (The `use_once_payload` is working around the current lack of once
142 // functions in the compiler.)
143
144 impl PpSourceMode {
145 /// Constructs a `PrinterSupport` object and passes it to `f`.
146 fn call_with_pp_support<'tcx, A, B, F>(&self,
147 sess: &'tcx Session,
148 ast_map: Option<hir_map::Map<'tcx>>,
149 payload: B,
150 f: F)
151 -> A
152 where F: FnOnce(&PrinterSupport, B) -> A
153 {
154 match *self {
155 PpmNormal | PpmEveryBodyLoops | PpmExpanded => {
156 let annotation = NoAnn {
157 sess: sess,
158 ast_map: ast_map,
159 };
160 f(&annotation, payload)
161 }
162
163 PpmIdentified | PpmExpandedIdentified => {
164 let annotation = IdentifiedAnnotation {
165 sess: sess,
166 ast_map: ast_map,
167 };
168 f(&annotation, payload)
169 }
170 PpmExpandedHygiene => {
171 let annotation = HygieneAnnotation {
172 sess: sess,
173 ast_map: ast_map,
174 };
175 f(&annotation, payload)
176 }
177 _ => panic!("Should use call_with_pp_support_hir"),
178 }
179 }
180 fn call_with_pp_support_hir<'tcx, A, B, F>(&self,
181 sess: &'tcx Session,
182 cstore: &CStore,
183 ast_map: &hir_map::Map<'tcx>,
184 arenas: &'tcx ty::CtxtArenas<'tcx>,
185 id: &str,
186 payload: B,
187 f: F)
188 -> A
189 where F: FnOnce(&HirPrinterSupport, B, &hir::Crate) -> A
190 {
191 match *self {
192 PpmNormal => {
193 let annotation = NoAnn {
194 sess: sess,
195 ast_map: Some(ast_map.clone()),
196 };
197 f(&annotation, payload, ast_map.forest.krate())
198 }
199
200 PpmIdentified => {
201 let annotation = IdentifiedAnnotation {
202 sess: sess,
203 ast_map: Some(ast_map.clone()),
204 };
205 f(&annotation, payload, ast_map.forest.krate())
206 }
207 PpmTyped => {
208 abort_on_err(driver::phase_3_run_analysis_passes(sess,
209 cstore,
210 ast_map.clone(),
211 arenas,
212 id,
213 resolve::MakeGlobMap::No,
214 |tcx, _, _, _| {
215 let annotation = TypedAnnotation {
216 tcx: tcx,
217 };
218 let _ignore = tcx.dep_graph.in_ignore();
219 f(&annotation,
220 payload,
221 ast_map.forest.krate())
222 }), sess)
223 }
224 _ => panic!("Should use call_with_pp_support"),
225 }
226 }
227 }
228
229 trait PrinterSupport<'ast>: pprust::PpAnn {
230 /// Provides a uniform interface for re-extracting a reference to a
231 /// `Session` from a value that now owns it.
232 fn sess<'a>(&'a self) -> &'a Session;
233
234 /// Provides a uniform interface for re-extracting a reference to an
235 /// `hir_map::Map` from a value that now owns it.
236 fn ast_map<'a>(&'a self) -> Option<&'a hir_map::Map<'ast>>;
237
238 /// Produces the pretty-print annotation object.
239 ///
240 /// (Rust does not yet support upcasting from a trait object to
241 /// an object for one of its super-traits.)
242 fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn;
243 }
244
245 trait HirPrinterSupport<'ast>: pprust_hir::PpAnn {
246 /// Provides a uniform interface for re-extracting a reference to a
247 /// `Session` from a value that now owns it.
248 fn sess<'a>(&'a self) -> &'a Session;
249
250 /// Provides a uniform interface for re-extracting a reference to an
251 /// `hir_map::Map` from a value that now owns it.
252 fn ast_map<'a>(&'a self) -> Option<&'a hir_map::Map<'ast>>;
253
254 /// Produces the pretty-print annotation object.
255 ///
256 /// (Rust does not yet support upcasting from a trait object to
257 /// an object for one of its super-traits.)
258 fn pp_ann<'a>(&'a self) -> &'a pprust_hir::PpAnn;
259
260 /// Computes an user-readable representation of a path, if possible.
261 fn node_path(&self, id: ast::NodeId) -> Option<String> {
262 self.ast_map().and_then(|map| map.def_path_from_id(id)).map(|path| {
263 path.data.into_iter().map(|elem| {
264 elem.data.to_string()
265 }).collect::<Vec<_>>().join("::")
266 })
267 }
268 }
269
270 struct NoAnn<'ast> {
271 sess: &'ast Session,
272 ast_map: Option<hir_map::Map<'ast>>,
273 }
274
275 impl<'ast> PrinterSupport<'ast> for NoAnn<'ast> {
276 fn sess<'a>(&'a self) -> &'a Session {
277 self.sess
278 }
279
280 fn ast_map<'a>(&'a self) -> Option<&'a hir_map::Map<'ast>> {
281 self.ast_map.as_ref()
282 }
283
284 fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn {
285 self
286 }
287 }
288
289 impl<'ast> HirPrinterSupport<'ast> for NoAnn<'ast> {
290 fn sess<'a>(&'a self) -> &'a Session {
291 self.sess
292 }
293
294 fn ast_map<'a>(&'a self) -> Option<&'a hir_map::Map<'ast>> {
295 self.ast_map.as_ref()
296 }
297
298 fn pp_ann<'a>(&'a self) -> &'a pprust_hir::PpAnn {
299 self
300 }
301 }
302
303 impl<'ast> pprust::PpAnn for NoAnn<'ast> {}
304 impl<'ast> pprust_hir::PpAnn for NoAnn<'ast> {}
305
306 struct IdentifiedAnnotation<'ast> {
307 sess: &'ast Session,
308 ast_map: Option<hir_map::Map<'ast>>,
309 }
310
311 impl<'ast> PrinterSupport<'ast> for IdentifiedAnnotation<'ast> {
312 fn sess<'a>(&'a self) -> &'a Session {
313 self.sess
314 }
315
316 fn ast_map<'a>(&'a self) -> Option<&'a hir_map::Map<'ast>> {
317 self.ast_map.as_ref()
318 }
319
320 fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn {
321 self
322 }
323 }
324
325 impl<'ast> pprust::PpAnn for IdentifiedAnnotation<'ast> {
326 fn pre(&self, s: &mut pprust::State, node: pprust::AnnNode) -> io::Result<()> {
327 match node {
328 pprust::NodeExpr(_) => s.popen(),
329 _ => Ok(()),
330 }
331 }
332 fn post(&self, s: &mut pprust::State, node: pprust::AnnNode) -> io::Result<()> {
333 match node {
334 pprust::NodeIdent(_) | pprust::NodeName(_) => Ok(()),
335
336 pprust::NodeItem(item) => {
337 pp::space(&mut s.s)?;
338 s.synth_comment(item.id.to_string())
339 }
340 pprust::NodeSubItem(id) => {
341 pp::space(&mut s.s)?;
342 s.synth_comment(id.to_string())
343 }
344 pprust::NodeBlock(blk) => {
345 pp::space(&mut s.s)?;
346 s.synth_comment(format!("block {}", blk.id))
347 }
348 pprust::NodeExpr(expr) => {
349 pp::space(&mut s.s)?;
350 s.synth_comment(expr.id.to_string())?;
351 s.pclose()
352 }
353 pprust::NodePat(pat) => {
354 pp::space(&mut s.s)?;
355 s.synth_comment(format!("pat {}", pat.id))
356 }
357 }
358 }
359 }
360
361 impl<'ast> HirPrinterSupport<'ast> for IdentifiedAnnotation<'ast> {
362 fn sess<'a>(&'a self) -> &'a Session {
363 self.sess
364 }
365
366 fn ast_map<'a>(&'a self) -> Option<&'a hir_map::Map<'ast>> {
367 self.ast_map.as_ref()
368 }
369
370 fn pp_ann<'a>(&'a self) -> &'a pprust_hir::PpAnn {
371 self
372 }
373 }
374
375 impl<'ast> pprust_hir::PpAnn for IdentifiedAnnotation<'ast> {
376 fn pre(&self, s: &mut pprust_hir::State, node: pprust_hir::AnnNode) -> io::Result<()> {
377 match node {
378 pprust_hir::NodeExpr(_) => s.popen(),
379 _ => Ok(()),
380 }
381 }
382 fn post(&self, s: &mut pprust_hir::State, node: pprust_hir::AnnNode) -> io::Result<()> {
383 match node {
384 pprust_hir::NodeName(_) => Ok(()),
385 pprust_hir::NodeItem(item) => {
386 pp::space(&mut s.s)?;
387 s.synth_comment(item.id.to_string())
388 }
389 pprust_hir::NodeSubItem(id) => {
390 pp::space(&mut s.s)?;
391 s.synth_comment(id.to_string())
392 }
393 pprust_hir::NodeBlock(blk) => {
394 pp::space(&mut s.s)?;
395 s.synth_comment(format!("block {}", blk.id))
396 }
397 pprust_hir::NodeExpr(expr) => {
398 pp::space(&mut s.s)?;
399 s.synth_comment(expr.id.to_string())?;
400 s.pclose()
401 }
402 pprust_hir::NodePat(pat) => {
403 pp::space(&mut s.s)?;
404 s.synth_comment(format!("pat {}", pat.id))
405 }
406 }
407 }
408 }
409
410 struct HygieneAnnotation<'ast> {
411 sess: &'ast Session,
412 ast_map: Option<hir_map::Map<'ast>>,
413 }
414
415 impl<'ast> PrinterSupport<'ast> for HygieneAnnotation<'ast> {
416 fn sess<'a>(&'a self) -> &'a Session {
417 self.sess
418 }
419
420 fn ast_map<'a>(&'a self) -> Option<&'a hir_map::Map<'ast>> {
421 self.ast_map.as_ref()
422 }
423
424 fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn {
425 self
426 }
427 }
428
429 impl<'ast> pprust::PpAnn for HygieneAnnotation<'ast> {
430 fn post(&self, s: &mut pprust::State, node: pprust::AnnNode) -> io::Result<()> {
431 match node {
432 pprust::NodeIdent(&ast::Ident { name: ast::Name(nm), ctxt }) => {
433 pp::space(&mut s.s)?;
434 // FIXME #16420: this doesn't display the connections
435 // between syntax contexts
436 s.synth_comment(format!("{}#{}", nm, ctxt.0))
437 }
438 pprust::NodeName(&ast::Name(nm)) => {
439 pp::space(&mut s.s)?;
440 s.synth_comment(nm.to_string())
441 }
442 _ => Ok(()),
443 }
444 }
445 }
446
447
448 struct TypedAnnotation<'a, 'tcx: 'a> {
449 tcx: &'a TyCtxt<'tcx>,
450 }
451
452 impl<'b, 'tcx> HirPrinterSupport<'tcx> for TypedAnnotation<'b, 'tcx> {
453 fn sess<'a>(&'a self) -> &'a Session {
454 &self.tcx.sess
455 }
456
457 fn ast_map<'a>(&'a self) -> Option<&'a hir_map::Map<'tcx>> {
458 Some(&self.tcx.map)
459 }
460
461 fn pp_ann<'a>(&'a self) -> &'a pprust_hir::PpAnn {
462 self
463 }
464
465 fn node_path(&self, id: ast::NodeId) -> Option<String> {
466 Some(self.tcx.node_path_str(id))
467 }
468 }
469
470 impl<'a, 'tcx> pprust_hir::PpAnn for TypedAnnotation<'a, 'tcx> {
471 fn pre(&self, s: &mut pprust_hir::State, node: pprust_hir::AnnNode) -> io::Result<()> {
472 match node {
473 pprust_hir::NodeExpr(_) => s.popen(),
474 _ => Ok(()),
475 }
476 }
477 fn post(&self, s: &mut pprust_hir::State, node: pprust_hir::AnnNode) -> io::Result<()> {
478 match node {
479 pprust_hir::NodeExpr(expr) => {
480 pp::space(&mut s.s)?;
481 pp::word(&mut s.s, "as")?;
482 pp::space(&mut s.s)?;
483 pp::word(&mut s.s, &self.tcx.expr_ty(expr).to_string())?;
484 s.pclose()
485 }
486 _ => Ok(()),
487 }
488 }
489 }
490
491 fn gather_flowgraph_variants(sess: &Session) -> Vec<borrowck_dot::Variant> {
492 let print_loans = sess.opts.debugging_opts.flowgraph_print_loans;
493 let print_moves = sess.opts.debugging_opts.flowgraph_print_moves;
494 let print_assigns = sess.opts.debugging_opts.flowgraph_print_assigns;
495 let print_all = sess.opts.debugging_opts.flowgraph_print_all;
496 let mut variants = Vec::new();
497 if print_all || print_loans {
498 variants.push(borrowck_dot::Loans);
499 }
500 if print_all || print_moves {
501 variants.push(borrowck_dot::Moves);
502 }
503 if print_all || print_assigns {
504 variants.push(borrowck_dot::Assigns);
505 }
506 variants
507 }
508
509 #[derive(Clone, Debug)]
510 pub enum UserIdentifiedItem {
511 ItemViaNode(ast::NodeId),
512 ItemViaPath(Vec<String>),
513 }
514
515 impl FromStr for UserIdentifiedItem {
516 type Err = ();
517 fn from_str(s: &str) -> Result<UserIdentifiedItem, ()> {
518 Ok(s.parse()
519 .map(ItemViaNode)
520 .unwrap_or_else(|_| ItemViaPath(s.split("::").map(|s| s.to_string()).collect())))
521 }
522 }
523
524 enum NodesMatchingUII<'a, 'ast: 'a> {
525 NodesMatchingDirect(option::IntoIter<ast::NodeId>),
526 NodesMatchingSuffix(hir_map::NodesMatchingSuffix<'a, 'ast>),
527 }
528
529 impl<'a, 'ast> Iterator for NodesMatchingUII<'a, 'ast> {
530 type Item = ast::NodeId;
531
532 fn next(&mut self) -> Option<ast::NodeId> {
533 match self {
534 &mut NodesMatchingDirect(ref mut iter) => iter.next(),
535 &mut NodesMatchingSuffix(ref mut iter) => iter.next(),
536 }
537 }
538 }
539
540 impl UserIdentifiedItem {
541 fn reconstructed_input(&self) -> String {
542 match *self {
543 ItemViaNode(node_id) => node_id.to_string(),
544 ItemViaPath(ref parts) => parts.join("::"),
545 }
546 }
547
548 fn all_matching_node_ids<'a, 'ast>(&'a self,
549 map: &'a hir_map::Map<'ast>)
550 -> NodesMatchingUII<'a, 'ast> {
551 match *self {
552 ItemViaNode(node_id) => NodesMatchingDirect(Some(node_id).into_iter()),
553 ItemViaPath(ref parts) => NodesMatchingSuffix(map.nodes_matching_suffix(&parts[..])),
554 }
555 }
556
557 fn to_one_node_id(self, user_option: &str, sess: &Session, map: &hir_map::Map) -> ast::NodeId {
558 let fail_because = |is_wrong_because| -> ast::NodeId {
559 let message = format!("{} needs NodeId (int) or unique path suffix (b::c::d); got \
560 {}, which {}",
561 user_option,
562 self.reconstructed_input(),
563 is_wrong_because);
564 sess.fatal(&message[..])
565 };
566
567 let mut saw_node = ast::DUMMY_NODE_ID;
568 let mut seen = 0;
569 for node in self.all_matching_node_ids(map) {
570 saw_node = node;
571 seen += 1;
572 if seen > 1 {
573 fail_because("does not resolve uniquely");
574 }
575 }
576 if seen == 0 {
577 fail_because("does not resolve to any item");
578 }
579
580 assert!(seen == 1);
581 return saw_node;
582 }
583 }
584
585 fn needs_ast_map(ppm: &PpMode, opt_uii: &Option<UserIdentifiedItem>) -> bool {
586 match *ppm {
587 PpmSource(PpmNormal) |
588 PpmSource(PpmEveryBodyLoops) |
589 PpmSource(PpmIdentified) => opt_uii.is_some(),
590
591 PpmSource(PpmExpanded) |
592 PpmSource(PpmExpandedIdentified) |
593 PpmSource(PpmExpandedHygiene) |
594 PpmHir(_) |
595 PpmMir |
596 PpmMirCFG |
597 PpmFlowGraph(_) => true,
598 PpmSource(PpmTyped) => panic!("invalid state"),
599 }
600 }
601
602 fn needs_expansion(ppm: &PpMode) -> bool {
603 match *ppm {
604 PpmSource(PpmNormal) |
605 PpmSource(PpmEveryBodyLoops) |
606 PpmSource(PpmIdentified) => false,
607
608 PpmSource(PpmExpanded) |
609 PpmSource(PpmExpandedIdentified) |
610 PpmSource(PpmExpandedHygiene) |
611 PpmHir(_) |
612 PpmMir |
613 PpmMirCFG |
614 PpmFlowGraph(_) => true,
615 PpmSource(PpmTyped) => panic!("invalid state"),
616 }
617 }
618
619 struct ReplaceBodyWithLoop {
620 within_static_or_const: bool,
621 }
622
623 impl ReplaceBodyWithLoop {
624 fn new() -> ReplaceBodyWithLoop {
625 ReplaceBodyWithLoop { within_static_or_const: false }
626 }
627 }
628
629 impl fold::Folder for ReplaceBodyWithLoop {
630 fn fold_item_kind(&mut self, i: ast::ItemKind) -> ast::ItemKind {
631 match i {
632 ast::ItemKind::Static(..) | ast::ItemKind::Const(..) => {
633 self.within_static_or_const = true;
634 let ret = fold::noop_fold_item_kind(i, self);
635 self.within_static_or_const = false;
636 return ret;
637 }
638 _ => {
639 fold::noop_fold_item_kind(i, self)
640 }
641 }
642 }
643
644 fn fold_trait_item(&mut self, i: ast::TraitItem) -> SmallVector<ast::TraitItem> {
645 match i.node {
646 ast::TraitItemKind::Const(..) => {
647 self.within_static_or_const = true;
648 let ret = fold::noop_fold_trait_item(i, self);
649 self.within_static_or_const = false;
650 return ret;
651 }
652 _ => fold::noop_fold_trait_item(i, self),
653 }
654 }
655
656 fn fold_impl_item(&mut self, i: ast::ImplItem) -> SmallVector<ast::ImplItem> {
657 match i.node {
658 ast::ImplItemKind::Const(..) => {
659 self.within_static_or_const = true;
660 let ret = fold::noop_fold_impl_item(i, self);
661 self.within_static_or_const = false;
662 return ret;
663 }
664 _ => fold::noop_fold_impl_item(i, self),
665 }
666 }
667
668 fn fold_block(&mut self, b: P<ast::Block>) -> P<ast::Block> {
669 fn expr_to_block(rules: ast::BlockCheckMode, e: Option<P<ast::Expr>>) -> P<ast::Block> {
670 P(ast::Block {
671 expr: e,
672 stmts: vec![],
673 rules: rules,
674 id: ast::DUMMY_NODE_ID,
675 span: codemap::DUMMY_SP,
676 })
677 }
678
679 if !self.within_static_or_const {
680
681 let empty_block = expr_to_block(BlockCheckMode::Default, None);
682 let loop_expr = P(ast::Expr {
683 node: ast::ExprKind::Loop(empty_block, None),
684 id: ast::DUMMY_NODE_ID,
685 span: codemap::DUMMY_SP,
686 attrs: None,
687 });
688
689 expr_to_block(b.rules, Some(loop_expr))
690
691 } else {
692 fold::noop_fold_block(b, self)
693 }
694 }
695
696 // in general the pretty printer processes unexpanded code, so
697 // we override the default `fold_mac` method which panics.
698 fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac {
699 fold::noop_fold_mac(mac, self)
700 }
701 }
702
703 pub fn pretty_print_input(sess: Session,
704 cstore: &CStore,
705 cfg: ast::CrateConfig,
706 input: &Input,
707 ppm: PpMode,
708 opt_uii: Option<UserIdentifiedItem>,
709 ofile: Option<PathBuf>) {
710 let krate = panictry!(driver::phase_1_parse_input(&sess, cfg, input));
711
712 let krate = if let PpmSource(PpmEveryBodyLoops) = ppm {
713 let mut fold = ReplaceBodyWithLoop::new();
714 fold.fold_crate(krate)
715 } else {
716 krate
717 };
718
719 let id = link::find_crate_name(Some(&sess), &krate.attrs, input);
720
721 let is_expanded = needs_expansion(&ppm);
722 let compute_ast_map = needs_ast_map(&ppm, &opt_uii);
723 let krate = if compute_ast_map {
724 match driver::phase_2_configure_and_expand(&sess, &cstore, krate, &id[..], None) {
725 Err(_) => return,
726 Ok(k) => driver::assign_node_ids(&sess, k),
727 }
728 } else {
729 krate
730 };
731
732 // There is some twisted, god-forsaken tangle of lifetimes here which makes
733 // the ordering of stuff super-finicky.
734 let mut hir_forest;
735 let lcx = LoweringContext::new(&sess, Some(&krate));
736 let arenas = ty::CtxtArenas::new();
737 let dep_graph = DepGraph::new(false);
738 let _ignore = dep_graph.in_ignore();
739 let ast_map = if compute_ast_map {
740 hir_forest = hir_map::Forest::new(lower_crate(&lcx, &krate), dep_graph.clone());
741 let map = driver::make_map(&sess, &mut hir_forest);
742 Some(map)
743 } else {
744 None
745 };
746
747 let src_name = driver::source_name(input);
748 let src = sess.codemap()
749 .get_filemap(&src_name[..])
750 .src
751 .as_ref()
752 .unwrap()
753 .as_bytes()
754 .to_vec();
755 let mut rdr = &src[..];
756
757 let mut out = Vec::new();
758
759 match (ppm, opt_uii) {
760 (PpmSource(s), _) => {
761 // Silently ignores an identified node.
762 let out: &mut Write = &mut out;
763 s.call_with_pp_support(&sess, ast_map, box out, |annotation, out| {
764 debug!("pretty printing source code {:?}", s);
765 let sess = annotation.sess();
766 pprust::print_crate(sess.codemap(),
767 sess.diagnostic(),
768 &krate,
769 src_name.to_string(),
770 &mut rdr,
771 out,
772 annotation.pp_ann(),
773 is_expanded)
774 })
775 }
776
777 (PpmHir(s), None) => {
778 let out: &mut Write = &mut out;
779 s.call_with_pp_support_hir(&sess,
780 cstore,
781 &ast_map.unwrap(),
782 &arenas,
783 &id,
784 box out,
785 |annotation, out, krate| {
786 debug!("pretty printing source code {:?}", s);
787 let sess = annotation.sess();
788 pprust_hir::print_crate(sess.codemap(),
789 sess.diagnostic(),
790 krate,
791 src_name.to_string(),
792 &mut rdr,
793 out,
794 annotation.pp_ann(),
795 is_expanded)
796 })
797 }
798
799 (PpmHir(s), Some(uii)) => {
800 let out: &mut Write = &mut out;
801 s.call_with_pp_support_hir(&sess,
802 cstore,
803 &ast_map.unwrap(),
804 &arenas,
805 &id,
806 (out,uii),
807 |annotation, (out,uii), _| {
808 debug!("pretty printing source code {:?}", s);
809 let sess = annotation.sess();
810 let ast_map = annotation.ast_map().expect("--unpretty missing HIR map");
811 let mut pp_state =
812 pprust_hir::State::new_from_input(sess.codemap(),
813 sess.diagnostic(),
814 src_name.to_string(),
815 &mut rdr,
816 box out,
817 annotation.pp_ann(),
818 true,
819 Some(ast_map.krate()));
820 for node_id in uii.all_matching_node_ids(ast_map) {
821 let node = ast_map.get(node_id);
822 pp_state.print_node(&node)?;
823 pp::space(&mut pp_state.s)?;
824 let path = annotation.node_path(node_id)
825 .expect("--unpretty missing node paths");
826 pp_state.synth_comment(path)?;
827 pp::hardbreak(&mut pp_state.s)?;
828 }
829 pp::eof(&mut pp_state.s)
830 })
831 }
832
833 (pp_type@PpmMir, uii) | (pp_type@PpmMirCFG, uii) => {
834 let ast_map = ast_map.expect("--unpretty missing ast_map");
835 let nodeid = if let Some(uii) = uii {
836 debug!("pretty printing MIR for {:?}", uii);
837 Some(uii.to_one_node_id("--unpretty", &sess, &ast_map))
838 } else {
839 debug!("pretty printing MIR for whole crate");
840 None
841 };
842 abort_on_err(driver::phase_3_run_analysis_passes(&sess,
843 &cstore,
844 ast_map,
845 &arenas,
846 &id,
847 resolve::MakeGlobMap::No,
848 |tcx, mir_map, _, _| {
849 if let Some(mir_map) = mir_map {
850 if let Some(nodeid) = nodeid {
851 let mir = mir_map.map.get(&nodeid).unwrap_or_else(|| {
852 sess.fatal(&format!("no MIR map entry for node {}", nodeid))
853 });
854 match pp_type {
855 PpmMir => write_mir_pretty(tcx, iter::once((&nodeid, mir)), &mut out),
856 _ => write_mir_graphviz(tcx, iter::once((&nodeid, mir)), &mut out)
857 }?;
858 } else {
859 match pp_type {
860 PpmMir => write_mir_pretty(tcx, mir_map.map.iter(), &mut out),
861 _ => write_mir_graphviz(tcx, mir_map.map.iter(), &mut out)
862 }?;
863 }
864 }
865 Ok(())
866 }), &sess)
867 }
868
869 (PpmFlowGraph(mode), opt_uii) => {
870 debug!("pretty printing flow graph for {:?}", opt_uii);
871 let uii = opt_uii.unwrap_or_else(|| {
872 sess.fatal(&format!("`pretty flowgraph=..` needs NodeId (int) or
873 \
874 unique path suffix (b::c::d)"))
875
876 });
877 let ast_map = ast_map.expect("--pretty flowgraph missing ast_map");
878 let nodeid = uii.to_one_node_id("--pretty", &sess, &ast_map);
879
880 let node = ast_map.find(nodeid).unwrap_or_else(|| {
881 sess.fatal(&format!("--pretty flowgraph couldn't find id: {}", nodeid))
882 });
883
884 let code = blocks::Code::from_node(node);
885 let out: &mut Write = &mut out;
886 match code {
887 Some(code) => {
888 let variants = gather_flowgraph_variants(&sess);
889 abort_on_err(driver::phase_3_run_analysis_passes(&sess,
890 &cstore,
891 ast_map,
892 &arenas,
893 &id,
894 resolve::MakeGlobMap::No,
895 |tcx, mir_map, _, _| {
896 print_flowgraph(variants,
897 tcx,
898 mir_map.as_ref(),
899 code,
900 mode,
901 out)
902 }), &sess)
903 }
904 None => {
905 let message = format!("--pretty=flowgraph needs block, fn, or method; got \
906 {:?}",
907 node);
908
909 // point to what was found, if there's an
910 // accessible span.
911 match ast_map.opt_span(nodeid) {
912 Some(sp) => sess.span_fatal(sp, &message[..]),
913 None => sess.fatal(&message[..]),
914 }
915 }
916 }
917 }
918 }
919 .unwrap();
920
921 match ofile {
922 None => print!("{}", String::from_utf8(out).unwrap()),
923 Some(p) => {
924 match File::create(&p) {
925 Ok(mut w) => w.write_all(&out).unwrap(),
926 Err(e) => panic!("print-print failed to open {} due to {}", p.display(), e),
927 }
928 }
929 }
930 }
931
932 fn print_flowgraph<'tcx, W: Write>(variants: Vec<borrowck_dot::Variant>,
933 tcx: &TyCtxt<'tcx>,
934 mir_map: Option<&MirMap<'tcx>>,
935 code: blocks::Code,
936 mode: PpFlowGraphMode,
937 mut out: W)
938 -> io::Result<()> {
939 let cfg = match code {
940 blocks::BlockCode(block) => cfg::CFG::new(tcx, &block),
941 blocks::FnLikeCode(fn_like) => cfg::CFG::new(tcx, &fn_like.body()),
942 };
943 let labelled_edges = mode != PpFlowGraphMode::UnlabelledEdges;
944 let lcfg = LabelledCFG {
945 ast_map: &tcx.map,
946 cfg: &cfg,
947 name: format!("node_{}", code.id()),
948 labelled_edges: labelled_edges,
949 };
950
951 match code {
952 _ if variants.is_empty() => {
953 let r = dot::render(&lcfg, &mut out);
954 return expand_err_details(r);
955 }
956 blocks::BlockCode(_) => {
957 tcx.sess.err("--pretty flowgraph with -Z flowgraph-print annotations requires \
958 fn-like node id.");
959 return Ok(());
960 }
961 blocks::FnLikeCode(fn_like) => {
962 let (bccx, analysis_data) =
963 borrowck::build_borrowck_dataflow_data_for_fn(tcx,
964 mir_map,
965 fn_like.to_fn_parts(),
966 &cfg);
967
968 let lcfg = borrowck_dot::DataflowLabeller {
969 inner: lcfg,
970 variants: variants,
971 borrowck_ctxt: &bccx,
972 analysis_data: &analysis_data,
973 };
974 let r = dot::render(&lcfg, &mut out);
975 return expand_err_details(r);
976 }
977 }
978
979 fn expand_err_details(r: io::Result<()>) -> io::Result<()> {
980 r.map_err(|ioerr| {
981 io::Error::new(io::ErrorKind::Other,
982 &format!("graphviz::render failed: {}", ioerr)[..])
983 })
984 }
985 }