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::Input;
27 use rustc::util::ppaux;
28 use rustc_borrowck as borrowck;
29 use rustc_borrowck::graphviz as borrowck_dot;
30 use rustc_resolve as resolve;
33 use syntax::ast_map::{self, blocks, NodePrinter};
35 use syntax::fold::{self, Folder};
36 use syntax::print::{pp, pprust};
41 use std::old_io::{self, MemReader};
43 use std::str::FromStr;
45 #[derive(Copy, PartialEq, Debug)]
46 pub enum PpSourceMode {
52 PpmExpandedIdentified,
57 #[derive(Copy, PartialEq, Debug)]
58 pub enum PpFlowGraphMode {
60 /// Drops the labels from the edges in the flowgraph output. This
61 /// is mostly for use in the --xpretty flowgraph run-make tests,
62 /// since the labels are largely uninteresting in those cases and
63 /// have become a pain to maintain.
66 #[derive(Copy, PartialEq, Debug)]
68 PpmSource(PpSourceMode),
69 PpmFlowGraph(PpFlowGraphMode),
72 pub fn parse_pretty(sess: &Session,
74 extended: bool) -> (PpMode, Option<UserIdentifiedItem>) {
75 let mut split = name.splitn(1, '=');
76 let first = split.next().unwrap();
77 let opt_second = split.next();
78 let first = match (first, extended) {
79 ("normal", _) => PpmSource(PpmNormal),
80 ("everybody_loops", true) => PpmSource(PpmEveryBodyLoops),
81 ("expanded", _) => PpmSource(PpmExpanded),
82 ("typed", _) => PpmSource(PpmTyped),
83 ("expanded,identified", _) => PpmSource(PpmExpandedIdentified),
84 ("expanded,hygiene", _) => PpmSource(PpmExpandedHygiene),
85 ("identified", _) => PpmSource(PpmIdentified),
86 ("flowgraph", true) => PpmFlowGraph(PpFlowGraphMode::Default),
87 ("flowgraph,unlabelled", true) => PpmFlowGraph(PpFlowGraphMode::UnlabelledEdges),
91 "argument to `xpretty` must be one of `normal`, \
92 `expanded`, `flowgraph[,unlabelled]=<nodeid>`, `typed`, `identified`, \
93 `expanded,identified`, or `everybody_loops`; got {}", name));
96 "argument to `pretty` must be one of `normal`, \
97 `expanded`, `typed`, `identified`, \
98 or `expanded,identified`; got {}", name));
102 let opt_second = opt_second.and_then(|s| s.parse::<UserIdentifiedItem>().ok());
108 // This slightly awkward construction is to allow for each PpMode to
109 // choose whether it needs to do analyses (which can consume the
110 // Session) and then pass through the session (now attached to the
111 // analysis results) on to the chosen pretty-printer, along with the
114 // Note that since the `&PrinterSupport` is freshly constructed on each
115 // call, it would not make sense to try to attach the lifetime of `self`
116 // to the lifetime of the `&PrinterObject`.
118 // (The `use_once_payload` is working around the current lack of once
119 // functions in the compiler.)
122 /// Constructs a `PrinterSupport` object and passes it to `f`.
123 fn call_with_pp_support<'tcx, A, B, F>(&self,
125 ast_map: Option<ast_map::Map<'tcx>>,
126 arenas: &'tcx ty::CtxtArenas<'tcx>,
130 F: FnOnce(&PrinterSupport, B) -> A,
133 PpmNormal | PpmEveryBodyLoops | PpmExpanded => {
134 let annotation = NoAnn { sess: sess, ast_map: ast_map };
135 f(&annotation, payload)
138 PpmIdentified | PpmExpandedIdentified => {
139 let annotation = IdentifiedAnnotation { sess: sess, ast_map: ast_map };
140 f(&annotation, payload)
142 PpmExpandedHygiene => {
143 let annotation = HygieneAnnotation { sess: sess, ast_map: ast_map };
144 f(&annotation, payload)
147 let ast_map = ast_map.expect("--pretty=typed missing ast_map");
148 let analysis = driver::phase_3_run_analysis_passes(sess,
152 resolve::MakeGlobMap::No);
153 let annotation = TypedAnnotation { analysis: analysis };
154 f(&annotation, payload)
160 trait PrinterSupport<'ast>: pprust::PpAnn {
161 /// Provides a uniform interface for re-extracting a reference to a
162 /// `Session` from a value that now owns it.
163 fn sess<'a>(&'a self) -> &'a Session;
165 /// Provides a uniform interface for re-extracting a reference to an
166 /// `ast_map::Map` from a value that now owns it.
167 fn ast_map<'a>(&'a self) -> Option<&'a ast_map::Map<'ast>>;
169 /// Produces the pretty-print annotation object.
171 /// (Rust does not yet support upcasting from a trait object to
172 /// an object for one of its super-traits.)
173 fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn;
178 ast_map: Option<ast_map::Map<'ast>>
181 impl<'ast> PrinterSupport<'ast> for NoAnn<'ast> {
182 fn sess<'a>(&'a self) -> &'a Session { &self.sess }
184 fn ast_map<'a>(&'a self) -> Option<&'a ast_map::Map<'ast>> {
185 self.ast_map.as_ref()
188 fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn { self }
191 impl<'ast> pprust::PpAnn for NoAnn<'ast> {}
193 struct IdentifiedAnnotation<'ast> {
195 ast_map: Option<ast_map::Map<'ast>>,
198 impl<'ast> PrinterSupport<'ast> for IdentifiedAnnotation<'ast> {
199 fn sess<'a>(&'a self) -> &'a Session { &self.sess }
201 fn ast_map<'a>(&'a self) -> Option<&'a ast_map::Map<'ast>> {
202 self.ast_map.as_ref()
205 fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn { self }
208 impl<'ast> pprust::PpAnn for IdentifiedAnnotation<'ast> {
210 s: &mut pprust::State,
211 node: pprust::AnnNode) -> old_io::IoResult<()> {
213 pprust::NodeExpr(_) => s.popen(),
218 s: &mut pprust::State,
219 node: pprust::AnnNode) -> old_io::IoResult<()> {
221 pprust::NodeIdent(_) | pprust::NodeName(_) => Ok(()),
223 pprust::NodeItem(item) => {
224 try!(pp::space(&mut s.s));
225 s.synth_comment(item.id.to_string())
227 pprust::NodeBlock(blk) => {
228 try!(pp::space(&mut s.s));
229 s.synth_comment(format!("block {}", blk.id))
231 pprust::NodeExpr(expr) => {
232 try!(pp::space(&mut s.s));
233 try!(s.synth_comment(expr.id.to_string()));
236 pprust::NodePat(pat) => {
237 try!(pp::space(&mut s.s));
238 s.synth_comment(format!("pat {}", pat.id))
244 struct HygieneAnnotation<'ast> {
246 ast_map: Option<ast_map::Map<'ast>>,
249 impl<'ast> PrinterSupport<'ast> for HygieneAnnotation<'ast> {
250 fn sess<'a>(&'a self) -> &'a Session { &self.sess }
252 fn ast_map<'a>(&'a self) -> Option<&'a ast_map::Map<'ast>> {
253 self.ast_map.as_ref()
256 fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn { self }
259 impl<'ast> pprust::PpAnn for HygieneAnnotation<'ast> {
261 s: &mut pprust::State,
262 node: pprust::AnnNode) -> old_io::IoResult<()> {
264 pprust::NodeIdent(&ast::Ident { name: ast::Name(nm), ctxt }) => {
265 try!(pp::space(&mut s.s));
266 // FIXME #16420: this doesn't display the connections
267 // between syntax contexts
268 s.synth_comment(format!("{}#{}", nm, ctxt))
270 pprust::NodeName(&ast::Name(nm)) => {
271 try!(pp::space(&mut s.s));
272 s.synth_comment(nm.to_string())
280 struct TypedAnnotation<'tcx> {
281 analysis: ty::CrateAnalysis<'tcx>,
284 impl<'tcx> PrinterSupport<'tcx> for TypedAnnotation<'tcx> {
285 fn sess<'a>(&'a self) -> &'a Session { &self.analysis.ty_cx.sess }
287 fn ast_map<'a>(&'a self) -> Option<&'a ast_map::Map<'tcx>> {
288 Some(&self.analysis.ty_cx.map)
291 fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn { self }
294 impl<'tcx> pprust::PpAnn for TypedAnnotation<'tcx> {
296 s: &mut pprust::State,
297 node: pprust::AnnNode) -> old_io::IoResult<()> {
299 pprust::NodeExpr(_) => s.popen(),
304 s: &mut pprust::State,
305 node: pprust::AnnNode) -> old_io::IoResult<()> {
306 let tcx = &self.analysis.ty_cx;
308 pprust::NodeExpr(expr) => {
309 try!(pp::space(&mut s.s));
310 try!(pp::word(&mut s.s, "as"));
311 try!(pp::space(&mut s.s));
312 try!(pp::word(&mut s.s,
313 &ppaux::ty_to_string(
315 ty::expr_ty(tcx, expr))[]));
323 fn gather_flowgraph_variants(sess: &Session) -> Vec<borrowck_dot::Variant> {
324 let print_loans = sess.opts.debugging_opts.flowgraph_print_loans;
325 let print_moves = sess.opts.debugging_opts.flowgraph_print_moves;
326 let print_assigns = sess.opts.debugging_opts.flowgraph_print_assigns;
327 let print_all = sess.opts.debugging_opts.flowgraph_print_all;
328 let mut variants = Vec::new();
329 if print_all || print_loans {
330 variants.push(borrowck_dot::Loans);
332 if print_all || print_moves {
333 variants.push(borrowck_dot::Moves);
335 if print_all || print_assigns {
336 variants.push(borrowck_dot::Assigns);
341 #[derive(Clone, Debug)]
342 pub enum UserIdentifiedItem {
343 ItemViaNode(ast::NodeId),
344 ItemViaPath(Vec<String>),
347 impl FromStr for UserIdentifiedItem {
349 fn from_str(s: &str) -> Result<UserIdentifiedItem, ()> {
350 Ok(s.parse().map(ItemViaNode).unwrap_or_else(|_| {
351 ItemViaPath(s.split_str("::").map(|s| s.to_string()).collect())
356 enum NodesMatchingUII<'a, 'ast: 'a> {
357 NodesMatchingDirect(option::IntoIter<ast::NodeId>),
358 NodesMatchingSuffix(ast_map::NodesMatchingSuffix<'a, 'ast>),
361 impl<'a, 'ast> Iterator for NodesMatchingUII<'a, 'ast> {
362 type Item = ast::NodeId;
364 fn next(&mut self) -> Option<ast::NodeId> {
366 &mut NodesMatchingDirect(ref mut iter) => iter.next(),
367 &mut NodesMatchingSuffix(ref mut iter) => iter.next(),
372 impl UserIdentifiedItem {
373 fn reconstructed_input(&self) -> String {
375 ItemViaNode(node_id) => node_id.to_string(),
376 ItemViaPath(ref parts) => parts.connect("::"),
380 fn all_matching_node_ids<'a, 'ast>(&'a self, map: &'a ast_map::Map<'ast>)
381 -> NodesMatchingUII<'a, 'ast> {
383 ItemViaNode(node_id) =>
384 NodesMatchingDirect(Some(node_id).into_iter()),
385 ItemViaPath(ref parts) =>
386 NodesMatchingSuffix(map.nodes_matching_suffix(&parts[])),
390 fn to_one_node_id(self, user_option: &str, sess: &Session, map: &ast_map::Map) -> ast::NodeId {
391 let fail_because = |is_wrong_because| -> ast::NodeId {
393 format!("{} needs NodeId (int) or unique \
394 path suffix (b::c::d); got {}, which {}",
396 self.reconstructed_input(),
398 sess.fatal(&message[])
401 let mut saw_node = ast::DUMMY_NODE_ID;
403 for node in self.all_matching_node_ids(map) {
407 fail_because("does not resolve uniquely");
411 fail_because("does not resolve to any item");
419 fn needs_ast_map(ppm: &PpMode, opt_uii: &Option<UserIdentifiedItem>) -> bool {
421 PpmSource(PpmNormal) |
422 PpmSource(PpmEveryBodyLoops) |
423 PpmSource(PpmIdentified) => opt_uii.is_some(),
425 PpmSource(PpmExpanded) |
426 PpmSource(PpmExpandedIdentified) |
427 PpmSource(PpmExpandedHygiene) |
428 PpmSource(PpmTyped) |
429 PpmFlowGraph(_) => true
433 fn needs_expansion(ppm: &PpMode) -> bool {
435 PpmSource(PpmNormal) |
436 PpmSource(PpmEveryBodyLoops) |
437 PpmSource(PpmIdentified) => false,
439 PpmSource(PpmExpanded) |
440 PpmSource(PpmExpandedIdentified) |
441 PpmSource(PpmExpandedHygiene) |
442 PpmSource(PpmTyped) |
443 PpmFlowGraph(_) => true
447 struct ReplaceBodyWithLoop {
448 within_static_or_const: bool,
451 impl ReplaceBodyWithLoop {
452 fn new() -> ReplaceBodyWithLoop {
453 ReplaceBodyWithLoop { within_static_or_const: false }
457 impl fold::Folder for ReplaceBodyWithLoop {
458 fn fold_item_underscore(&mut self, i: ast::Item_) -> ast::Item_ {
460 ast::ItemStatic(..) | ast::ItemConst(..) => {
461 self.within_static_or_const = true;
462 let ret = fold::noop_fold_item_underscore(i, self);
463 self.within_static_or_const = false;
467 fold::noop_fold_item_underscore(i, self)
473 fn fold_block(&mut self, b: P<ast::Block>) -> P<ast::Block> {
474 fn expr_to_block(rules: ast::BlockCheckMode,
475 e: Option<P<ast::Expr>>) -> P<ast::Block> {
478 stmts: vec![], rules: rules,
479 id: ast::DUMMY_NODE_ID, span: codemap::DUMMY_SP,
483 if !self.within_static_or_const {
485 let empty_block = expr_to_block(ast::DefaultBlock, None);
486 let loop_expr = P(ast::Expr {
487 node: ast::ExprLoop(empty_block, None),
488 id: ast::DUMMY_NODE_ID, span: codemap::DUMMY_SP
491 expr_to_block(b.rules, Some(loop_expr))
494 fold::noop_fold_block(b, self)
498 // in general the pretty printer processes unexpanded code, so
499 // we override the default `fold_mac` method which panics.
500 fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac {
501 fold::noop_fold_mac(mac, self)
505 pub fn pretty_print_input(sess: Session,
506 cfg: ast::CrateConfig,
509 opt_uii: Option<UserIdentifiedItem>,
510 ofile: Option<Path>) {
511 let krate = driver::phase_1_parse_input(&sess, cfg, input);
513 let krate = if let PpmSource(PpmEveryBodyLoops) = ppm {
514 let mut fold = ReplaceBodyWithLoop::new();
515 fold.fold_crate(krate)
520 let id = link::find_crate_name(Some(&sess), &krate.attrs, input);
522 let is_expanded = needs_expansion(&ppm);
523 let compute_ast_map = needs_ast_map(&ppm, &opt_uii);
524 let krate = if compute_ast_map {
525 match driver::phase_2_configure_and_expand(&sess, krate, &id[], None) {
533 let mut forest = ast_map::Forest::new(krate);
534 let arenas = ty::CtxtArenas::new();
536 let (krate, ast_map) = if compute_ast_map {
537 let map = driver::assign_node_ids_and_map(&sess, &mut forest);
538 (map.krate(), Some(map))
540 (forest.krate(), None)
543 let src_name = driver::source_name(input);
544 let src = sess.codemap().get_filemap(&src_name[])
545 .src.as_bytes().to_vec();
546 let mut rdr = MemReader::new(src);
548 let out = match ofile {
549 None => box old_io::stdout() as Box<Writer+'static>,
551 let r = old_io::File::create(&p);
553 Ok(w) => box w as Box<Writer+'static>,
554 Err(e) => panic!("print-print failed to open {} due to {}",
560 match (ppm, opt_uii) {
561 (PpmSource(s), None) =>
562 s.call_with_pp_support(
563 sess, ast_map, &arenas, id, out, |annotation, out| {
564 debug!("pretty printing source code {:?}", s);
565 let sess = annotation.sess();
566 pprust::print_crate(sess.codemap(),
569 src_name.to_string(),
576 (PpmSource(s), Some(uii)) =>
577 s.call_with_pp_support(
578 sess, ast_map, &arenas, id, (out,uii), |annotation, (out,uii)| {
579 debug!("pretty printing source code {:?}", s);
580 let sess = annotation.sess();
581 let ast_map = annotation.ast_map()
582 .expect("--pretty missing ast_map");
584 pprust::State::new_from_input(sess.codemap(),
586 src_name.to_string(),
591 for node_id in uii.all_matching_node_ids(ast_map) {
592 let node = ast_map.get(node_id);
593 try!(pp_state.print_node(&node));
594 try!(pp::space(&mut pp_state.s));
595 try!(pp_state.synth_comment(ast_map.path_to_string(node_id)));
596 try!(pp::hardbreak(&mut pp_state.s));
598 pp::eof(&mut pp_state.s)
601 (PpmFlowGraph(mode), opt_uii) => {
602 debug!("pretty printing flow graph for {:?}", opt_uii);
603 let uii = opt_uii.unwrap_or_else(|| {
604 sess.fatal(&format!("`pretty flowgraph=..` needs NodeId (int) or
605 unique path suffix (b::c::d)")[])
608 let ast_map = ast_map.expect("--pretty flowgraph missing ast_map");
609 let nodeid = uii.to_one_node_id("--pretty", &sess, &ast_map);
611 let node = ast_map.find(nodeid).unwrap_or_else(|| {
612 sess.fatal(&format!("--pretty flowgraph couldn't find id: {}",
616 let code = blocks::Code::from_node(node);
619 let variants = gather_flowgraph_variants(&sess);
620 let analysis = driver::phase_3_run_analysis_passes(sess,
624 resolve::MakeGlobMap::No);
625 print_flowgraph(variants, analysis, code, mode, out)
628 let message = format!("--pretty=flowgraph needs \
629 block, fn, or method; got {:?}",
632 // point to what was found, if there's an
634 match ast_map.opt_span(nodeid) {
635 Some(sp) => sess.span_fatal(sp, &message[]),
636 None => sess.fatal(&message[])
644 fn print_flowgraph<W:old_io::Writer>(variants: Vec<borrowck_dot::Variant>,
645 analysis: ty::CrateAnalysis,
647 mode: PpFlowGraphMode,
648 mut out: W) -> old_io::IoResult<()> {
649 let ty_cx = &analysis.ty_cx;
650 let cfg = match code {
651 blocks::BlockCode(block) => cfg::CFG::new(ty_cx, &*block),
652 blocks::FnLikeCode(fn_like) => cfg::CFG::new(ty_cx, &*fn_like.body()),
654 let labelled_edges = mode != PpFlowGraphMode::UnlabelledEdges;
655 let lcfg = LabelledCFG {
658 name: format!("node_{}", code.id()),
659 labelled_edges: labelled_edges,
663 _ if variants.len() == 0 => {
664 let r = dot::render(&lcfg, &mut out);
665 return expand_err_details(r);
667 blocks::BlockCode(_) => {
668 ty_cx.sess.err("--pretty flowgraph with -Z flowgraph-print \
669 annotations requires fn-like node id.");
672 blocks::FnLikeCode(fn_like) => {
673 let fn_parts = borrowck::FnPartsWithCFG::from_fn_like(&fn_like, &cfg);
674 let (bccx, analysis_data) =
675 borrowck::build_borrowck_dataflow_data_for_fn(ty_cx, fn_parts);
677 let lcfg = borrowck_dot::DataflowLabeller {
680 borrowck_ctxt: &bccx,
681 analysis_data: &analysis_data,
683 let r = dot::render(&lcfg, &mut out);
684 return expand_err_details(r);
688 fn expand_err_details(r: old_io::IoResult<()>) -> old_io::IoResult<()> {
690 let orig_detail = ioerr.detail.clone();
691 let m = "graphviz::render failed";
693 detail: Some(match orig_detail {
694 None => m.to_string(),
695 Some(d) => format!("{}: {}", m, d)