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.
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.
11 //! The various pretty print routines.
13 pub use self::UserIdentifiedItem::*;
14 pub use self::PpSourceMode::*;
15 pub use self::PpMode::*;
16 use self::NodesMatchingUII::*;
18 use rustc_trans::back::link;
22 use rustc::middle::ty;
23 use rustc::middle::cfg;
24 use rustc::middle::cfg::graphviz::LabelledCFG;
25 use rustc::session::Session;
26 use rustc::session::config::{mod, Input};
27 use rustc::util::ppaux;
28 use rustc_borrowck as borrowck;
29 use rustc_borrowck::graphviz as borrowck_dot;
32 use syntax::ast_map::{mod, blocks, NodePrinter};
34 use syntax::fold::{mod, Folder};
35 use syntax::print::{pp, pprust};
40 use std::io::{mod, MemReader};
42 use std::str::FromStr;
44 #[deriving(Copy, PartialEq, Show)]
45 pub enum PpSourceMode {
51 PpmExpandedIdentified,
55 #[deriving(Copy, PartialEq, Show)]
57 PpmSource(PpSourceMode),
61 pub fn parse_pretty(sess: &Session,
63 extended: bool) -> (PpMode, Option<UserIdentifiedItem>) {
64 let mut split = name.splitn(1, '=');
65 let first = split.next().unwrap();
66 let opt_second = split.next();
67 let first = match (first, extended) {
68 ("normal", _) => PpmSource(PpmNormal),
69 ("everybody_loops", true) => PpmSource(PpmEveryBodyLoops),
70 ("expanded", _) => PpmSource(PpmExpanded),
71 ("typed", _) => PpmSource(PpmTyped),
72 ("expanded,identified", _) => PpmSource(PpmExpandedIdentified),
73 ("expanded,hygiene", _) => PpmSource(PpmExpandedHygiene),
74 ("identified", _) => PpmSource(PpmIdentified),
75 ("flowgraph", true) => PpmFlowGraph,
79 "argument to `xpretty` must be one of `normal`, \
80 `expanded`, `flowgraph=<nodeid>`, `typed`, `identified`, \
81 `expanded,identified`, or `everybody_loops`; got {}", name).as_slice());
84 "argument to `pretty` must be one of `normal`, \
85 `expanded`, `typed`, `identified`, \
86 or `expanded,identified`; got {}", name).as_slice());
90 let opt_second = opt_second.and_then(|s| s.parse::<UserIdentifiedItem>());
96 // This slightly awkward construction is to allow for each PpMode to
97 // choose whether it needs to do analyses (which can consume the
98 // Session) and then pass through the session (now attached to the
99 // analysis results) on to the chosen pretty-printer, along with the
102 // Note that since the `&PrinterSupport` is freshly constructed on each
103 // call, it would not make sense to try to attach the lifetime of `self`
104 // to the lifetime of the `&PrinterObject`.
106 // (The `use_once_payload` is working around the current lack of once
107 // functions in the compiler.)
110 /// Constructs a `PrinterSupport` object and passes it to `f`.
111 fn call_with_pp_support<'tcx, A, B, F>(&self,
113 ast_map: Option<ast_map::Map<'tcx>>,
114 arenas: &'tcx ty::CtxtArenas<'tcx>,
118 F: FnOnce(&PrinterSupport, B) -> A,
121 PpmNormal | PpmEveryBodyLoops | PpmExpanded => {
122 let annotation = NoAnn { sess: sess, ast_map: ast_map };
123 f(&annotation, payload)
126 PpmIdentified | PpmExpandedIdentified => {
127 let annotation = IdentifiedAnnotation { sess: sess, ast_map: ast_map };
128 f(&annotation, payload)
130 PpmExpandedHygiene => {
131 let annotation = HygieneAnnotation { sess: sess, ast_map: ast_map };
132 f(&annotation, payload)
135 let ast_map = ast_map.expect("--pretty=typed missing ast_map");
136 let analysis = driver::phase_3_run_analysis_passes(sess, ast_map, arenas, id);
137 let annotation = TypedAnnotation { analysis: analysis };
138 f(&annotation, payload)
144 trait PrinterSupport<'ast>: pprust::PpAnn {
145 /// Provides a uniform interface for re-extracting a reference to a
146 /// `Session` from a value that now owns it.
147 fn sess<'a>(&'a self) -> &'a Session;
149 /// Provides a uniform interface for re-extracting a reference to an
150 /// `ast_map::Map` from a value that now owns it.
151 fn ast_map<'a>(&'a self) -> Option<&'a ast_map::Map<'ast>>;
153 /// Produces the pretty-print annotation object.
155 /// (Rust does not yet support upcasting from a trait object to
156 /// an object for one of its super-traits.)
157 fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn;
162 ast_map: Option<ast_map::Map<'ast>>
165 impl<'ast> PrinterSupport<'ast> for NoAnn<'ast> {
166 fn sess<'a>(&'a self) -> &'a Session { &self.sess }
168 fn ast_map<'a>(&'a self) -> Option<&'a ast_map::Map<'ast>> {
169 self.ast_map.as_ref()
172 fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn { self }
175 impl<'ast> pprust::PpAnn for NoAnn<'ast> {}
177 struct IdentifiedAnnotation<'ast> {
179 ast_map: Option<ast_map::Map<'ast>>,
182 impl<'ast> PrinterSupport<'ast> for IdentifiedAnnotation<'ast> {
183 fn sess<'a>(&'a self) -> &'a Session { &self.sess }
185 fn ast_map<'a>(&'a self) -> Option<&'a ast_map::Map<'ast>> {
186 self.ast_map.as_ref()
189 fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn { self }
192 impl<'ast> pprust::PpAnn for IdentifiedAnnotation<'ast> {
194 s: &mut pprust::State,
195 node: pprust::AnnNode) -> io::IoResult<()> {
197 pprust::NodeExpr(_) => s.popen(),
202 s: &mut pprust::State,
203 node: pprust::AnnNode) -> io::IoResult<()> {
205 pprust::NodeIdent(_) | pprust::NodeName(_) => Ok(()),
207 pprust::NodeItem(item) => {
208 try!(pp::space(&mut s.s));
209 s.synth_comment(item.id.to_string())
211 pprust::NodeBlock(blk) => {
212 try!(pp::space(&mut s.s));
213 s.synth_comment(format!("block {}", blk.id))
215 pprust::NodeExpr(expr) => {
216 try!(pp::space(&mut s.s));
217 try!(s.synth_comment(expr.id.to_string()));
220 pprust::NodePat(pat) => {
221 try!(pp::space(&mut s.s));
222 s.synth_comment(format!("pat {}", pat.id))
228 struct HygieneAnnotation<'ast> {
230 ast_map: Option<ast_map::Map<'ast>>,
233 impl<'ast> PrinterSupport<'ast> for HygieneAnnotation<'ast> {
234 fn sess<'a>(&'a self) -> &'a Session { &self.sess }
236 fn ast_map<'a>(&'a self) -> Option<&'a ast_map::Map<'ast>> {
237 self.ast_map.as_ref()
240 fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn { self }
243 impl<'ast> pprust::PpAnn for HygieneAnnotation<'ast> {
245 s: &mut pprust::State,
246 node: pprust::AnnNode) -> io::IoResult<()> {
248 pprust::NodeIdent(&ast::Ident { name: ast::Name(nm), ctxt }) => {
249 try!(pp::space(&mut s.s));
250 // FIXME #16420: this doesn't display the connections
251 // between syntax contexts
252 s.synth_comment(format!("{}#{}", nm, ctxt))
254 pprust::NodeName(&ast::Name(nm)) => {
255 try!(pp::space(&mut s.s));
256 s.synth_comment(nm.to_string())
264 struct TypedAnnotation<'tcx> {
265 analysis: ty::CrateAnalysis<'tcx>,
268 impl<'tcx> PrinterSupport<'tcx> for TypedAnnotation<'tcx> {
269 fn sess<'a>(&'a self) -> &'a Session { &self.analysis.ty_cx.sess }
271 fn ast_map<'a>(&'a self) -> Option<&'a ast_map::Map<'tcx>> {
272 Some(&self.analysis.ty_cx.map)
275 fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn { self }
278 impl<'tcx> pprust::PpAnn for TypedAnnotation<'tcx> {
280 s: &mut pprust::State,
281 node: pprust::AnnNode) -> io::IoResult<()> {
283 pprust::NodeExpr(_) => s.popen(),
288 s: &mut pprust::State,
289 node: pprust::AnnNode) -> io::IoResult<()> {
290 let tcx = &self.analysis.ty_cx;
292 pprust::NodeExpr(expr) => {
293 try!(pp::space(&mut s.s));
294 try!(pp::word(&mut s.s, "as"));
295 try!(pp::space(&mut s.s));
296 try!(pp::word(&mut s.s,
299 ty::expr_ty(tcx, expr))[]));
307 fn gather_flowgraph_variants(sess: &Session) -> Vec<borrowck_dot::Variant> {
308 let print_loans = config::FLOWGRAPH_PRINT_LOANS;
309 let print_moves = config::FLOWGRAPH_PRINT_MOVES;
310 let print_assigns = config::FLOWGRAPH_PRINT_ASSIGNS;
311 let print_all = config::FLOWGRAPH_PRINT_ALL;
312 let opt = |&: print_which| sess.debugging_opt(print_which);
313 let mut variants = Vec::new();
314 if opt(print_all) || opt(print_loans) {
315 variants.push(borrowck_dot::Loans);
317 if opt(print_all) || opt(print_moves) {
318 variants.push(borrowck_dot::Moves);
320 if opt(print_all) || opt(print_assigns) {
321 variants.push(borrowck_dot::Assigns);
326 #[deriving(Clone, Show)]
327 pub enum UserIdentifiedItem {
328 ItemViaNode(ast::NodeId),
329 ItemViaPath(Vec<String>),
332 impl FromStr for UserIdentifiedItem {
333 fn from_str(s: &str) -> Option<UserIdentifiedItem> {
334 s.parse().map(ItemViaNode).or_else(|| {
335 let v : Vec<_> = s.split_str("::")
336 .map(|x|x.to_string())
343 enum NodesMatchingUII<'a, 'ast: 'a> {
344 NodesMatchingDirect(option::IntoIter<ast::NodeId>),
345 NodesMatchingSuffix(ast_map::NodesMatchingSuffix<'a, 'ast>),
348 impl<'a, 'ast> Iterator for NodesMatchingUII<'a, 'ast> {
349 type Item = ast::NodeId;
351 fn next(&mut self) -> Option<ast::NodeId> {
353 &NodesMatchingDirect(ref mut iter) => iter.next(),
354 &NodesMatchingSuffix(ref mut iter) => iter.next(),
359 impl UserIdentifiedItem {
360 fn reconstructed_input(&self) -> String {
362 ItemViaNode(node_id) => node_id.to_string(),
363 ItemViaPath(ref parts) => parts.connect("::"),
367 fn all_matching_node_ids<'a, 'ast>(&'a self, map: &'a ast_map::Map<'ast>)
368 -> NodesMatchingUII<'a, 'ast> {
370 ItemViaNode(node_id) =>
371 NodesMatchingDirect(Some(node_id).into_iter()),
372 ItemViaPath(ref parts) =>
373 NodesMatchingSuffix(map.nodes_matching_suffix(parts[])),
377 fn to_one_node_id(self, user_option: &str, sess: &Session, map: &ast_map::Map) -> ast::NodeId {
378 let fail_because = |&: is_wrong_because| -> ast::NodeId {
380 format!("{} needs NodeId (int) or unique \
381 path suffix (b::c::d); got {}, which {}",
383 self.reconstructed_input(),
385 sess.fatal(message[])
388 let mut saw_node = ast::DUMMY_NODE_ID;
390 for node in self.all_matching_node_ids(map) {
394 fail_because("does not resolve uniquely");
398 fail_because("does not resolve to any item");
406 fn needs_ast_map(ppm: &PpMode, opt_uii: &Option<UserIdentifiedItem>) -> bool {
408 PpmSource(PpmNormal) |
409 PpmSource(PpmEveryBodyLoops) |
410 PpmSource(PpmIdentified) => opt_uii.is_some(),
412 PpmSource(PpmExpanded) |
413 PpmSource(PpmExpandedIdentified) |
414 PpmSource(PpmExpandedHygiene) |
415 PpmSource(PpmTyped) |
420 fn needs_expansion(ppm: &PpMode) -> bool {
422 PpmSource(PpmNormal) |
423 PpmSource(PpmEveryBodyLoops) |
424 PpmSource(PpmIdentified) => false,
426 PpmSource(PpmExpanded) |
427 PpmSource(PpmExpandedIdentified) |
428 PpmSource(PpmExpandedHygiene) |
429 PpmSource(PpmTyped) |
434 struct ReplaceBodyWithLoop {
435 within_static_or_const: bool,
438 impl ReplaceBodyWithLoop {
439 fn new() -> ReplaceBodyWithLoop {
440 ReplaceBodyWithLoop { within_static_or_const: false }
444 impl fold::Folder for ReplaceBodyWithLoop {
445 fn fold_item_underscore(&mut self, i: ast::Item_) -> ast::Item_ {
447 ast::ItemStatic(..) | ast::ItemConst(..) => {
448 self.within_static_or_const = true;
449 let ret = fold::noop_fold_item_underscore(i, self);
450 self.within_static_or_const = false;
454 fold::noop_fold_item_underscore(i, self)
460 fn fold_block(&mut self, b: P<ast::Block>) -> P<ast::Block> {
461 fn expr_to_block(rules: ast::BlockCheckMode,
462 e: Option<P<ast::Expr>>) -> P<ast::Block> {
465 view_items: vec![], stmts: vec![], rules: rules,
466 id: ast::DUMMY_NODE_ID, span: codemap::DUMMY_SP,
470 if !self.within_static_or_const {
472 let empty_block = expr_to_block(ast::DefaultBlock, None);
473 let loop_expr = P(ast::Expr {
474 node: ast::ExprLoop(empty_block, None),
475 id: ast::DUMMY_NODE_ID, span: codemap::DUMMY_SP
478 expr_to_block(b.rules, Some(loop_expr))
481 fold::noop_fold_block(b, self)
485 // in general the pretty printer processes unexpanded code, so
486 // we override the default `fold_mac` method which panics.
487 fn fold_mac(&mut self, _macro: ast::Mac) -> ast::Mac {
488 fold::noop_fold_mac(_macro, self)
492 pub fn pretty_print_input(sess: Session,
493 cfg: ast::CrateConfig,
496 opt_uii: Option<UserIdentifiedItem>,
497 ofile: Option<Path>) {
498 let krate = driver::phase_1_parse_input(&sess, cfg, input);
500 let krate = if let PpmSource(PpmEveryBodyLoops) = ppm {
501 let mut fold = ReplaceBodyWithLoop::new();
502 fold.fold_crate(krate)
507 let id = link::find_crate_name(Some(&sess), krate.attrs.as_slice(), input);
509 let is_expanded = needs_expansion(&ppm);
510 let compute_ast_map = needs_ast_map(&ppm, &opt_uii);
511 let krate = if compute_ast_map {
512 match driver::phase_2_configure_and_expand(&sess, krate, id[], None) {
520 let mut forest = ast_map::Forest::new(krate);
521 let arenas = ty::CtxtArenas::new();
523 let (krate, ast_map) = if compute_ast_map {
524 let map = driver::assign_node_ids_and_map(&sess, &mut forest);
525 (map.krate(), Some(map))
527 (forest.krate(), None)
530 let src_name = driver::source_name(input);
531 let src = sess.codemap().get_filemap(src_name[])
532 .src.as_bytes().to_vec();
533 let mut rdr = MemReader::new(src);
535 let out = match ofile {
536 None => box io::stdout() as Box<Writer+'static>,
538 let r = io::File::create(&p);
540 Ok(w) => box w as Box<Writer+'static>,
541 Err(e) => panic!("print-print failed to open {} due to {}",
547 match (ppm, opt_uii) {
548 (PpmSource(s), None) =>
549 s.call_with_pp_support(
550 sess, ast_map, &arenas, id, out, |annotation, out| {
551 debug!("pretty printing source code {}", s);
552 let sess = annotation.sess();
553 pprust::print_crate(sess.codemap(),
556 src_name.to_string(),
563 (PpmSource(s), Some(uii)) =>
564 s.call_with_pp_support(
565 sess, ast_map, &arenas, id, (out,uii), |annotation, (out,uii)| {
566 debug!("pretty printing source code {}", s);
567 let sess = annotation.sess();
568 let ast_map = annotation.ast_map()
569 .expect("--pretty missing ast_map");
571 pprust::State::new_from_input(sess.codemap(),
573 src_name.to_string(),
578 for node_id in uii.all_matching_node_ids(ast_map) {
579 let node = ast_map.get(node_id);
580 try!(pp_state.print_node(&node));
581 try!(pp::space(&mut pp_state.s));
582 try!(pp_state.synth_comment(ast_map.path_to_string(node_id)));
583 try!(pp::hardbreak(&mut pp_state.s));
585 pp::eof(&mut pp_state.s)
588 (PpmFlowGraph, opt_uii) => {
589 debug!("pretty printing flow graph for {}", opt_uii);
590 let uii = opt_uii.unwrap_or_else(|| {
591 sess.fatal(format!("`pretty flowgraph=..` needs NodeId (int) or
592 unique path suffix (b::c::d)")[])
595 let ast_map = ast_map.expect("--pretty flowgraph missing ast_map");
596 let nodeid = uii.to_one_node_id("--pretty", &sess, &ast_map);
598 let node = ast_map.find(nodeid).unwrap_or_else(|| {
599 sess.fatal(format!("--pretty flowgraph couldn't find id: {}",
603 let code = blocks::Code::from_node(node);
606 let variants = gather_flowgraph_variants(&sess);
607 let analysis = driver::phase_3_run_analysis_passes(sess, ast_map, &arenas, id);
608 print_flowgraph(variants, analysis, code, out)
611 let message = format!("--pretty=flowgraph needs \
612 block, fn, or method; got {}",
615 // point to what was found, if there's an
617 match ast_map.opt_span(nodeid) {
618 Some(sp) => sess.span_fatal(sp, message[]),
619 None => sess.fatal(message[])
627 fn print_flowgraph<W:io::Writer>(variants: Vec<borrowck_dot::Variant>,
628 analysis: ty::CrateAnalysis,
630 mut out: W) -> io::IoResult<()> {
631 let ty_cx = &analysis.ty_cx;
632 let cfg = match code {
633 blocks::BlockCode(block) => cfg::CFG::new(ty_cx, &*block),
634 blocks::FnLikeCode(fn_like) => cfg::CFG::new(ty_cx, &*fn_like.body()),
638 _ if variants.len() == 0 => {
639 let lcfg = LabelledCFG {
642 name: format!("node_{}", code.id()),
644 let r = dot::render(&lcfg, &mut out);
645 return expand_err_details(r);
647 blocks::BlockCode(_) => {
648 ty_cx.sess.err("--pretty flowgraph with -Z flowgraph-print \
649 annotations requires fn-like node id.");
652 blocks::FnLikeCode(fn_like) => {
653 let fn_parts = borrowck::FnPartsWithCFG::from_fn_like(&fn_like, &cfg);
654 let (bccx, analysis_data) =
655 borrowck::build_borrowck_dataflow_data_for_fn(ty_cx, fn_parts);
657 let lcfg = LabelledCFG {
660 name: format!("node_{}", code.id()),
662 let lcfg = borrowck_dot::DataflowLabeller {
665 borrowck_ctxt: &bccx,
666 analysis_data: &analysis_data,
668 let r = dot::render(&lcfg, &mut out);
669 return expand_err_details(r);
673 fn expand_err_details(r: io::IoResult<()>) -> io::IoResult<()> {
675 let orig_detail = ioerr.detail.clone();
676 let m = "graphviz::render failed";
678 detail: Some(match orig_detail {
679 None => m.to_string(),
680 Some(d) => format!("{}: {}", m, d)