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::io::{self, MemReader};
43 use std::str::FromStr;
45 #[derive(Copy, PartialEq, Show)]
46 pub enum PpSourceMode {
52 PpmExpandedIdentified,
57 #[derive(Copy, PartialEq, Show)]
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, Show)]
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).as_slice());
96 "argument to `pretty` must be one of `normal`, \
97 `expanded`, `typed`, `identified`, \
98 or `expanded,identified`; got {}", name).as_slice());
102 let opt_second = opt_second.and_then(|s| s.parse::<UserIdentifiedItem>());
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) -> io::IoResult<()> {
213 pprust::NodeExpr(_) => s.popen(),
218 s: &mut pprust::State,
219 node: pprust::AnnNode) -> 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) -> 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) -> io::IoResult<()> {
299 pprust::NodeExpr(_) => s.popen(),
304 s: &mut pprust::State,
305 node: pprust::AnnNode) -> 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, Show)]
342 pub enum UserIdentifiedItem {
343 ItemViaNode(ast::NodeId),
344 ItemViaPath(Vec<String>),
347 impl FromStr for UserIdentifiedItem {
348 fn from_str(s: &str) -> Option<UserIdentifiedItem> {
349 s.parse().map(ItemViaNode).or_else(|| {
350 let v : Vec<_> = s.split_str("::")
351 .map(|x|x.to_string())
358 enum NodesMatchingUII<'a, 'ast: 'a> {
359 NodesMatchingDirect(option::IntoIter<ast::NodeId>),
360 NodesMatchingSuffix(ast_map::NodesMatchingSuffix<'a, 'ast>),
363 impl<'a, 'ast> Iterator for NodesMatchingUII<'a, 'ast> {
364 type Item = ast::NodeId;
366 fn next(&mut self) -> Option<ast::NodeId> {
368 &mut NodesMatchingDirect(ref mut iter) => iter.next(),
369 &mut NodesMatchingSuffix(ref mut iter) => iter.next(),
374 impl UserIdentifiedItem {
375 fn reconstructed_input(&self) -> String {
377 ItemViaNode(node_id) => node_id.to_string(),
378 ItemViaPath(ref parts) => parts.connect("::"),
382 fn all_matching_node_ids<'a, 'ast>(&'a self, map: &'a ast_map::Map<'ast>)
383 -> NodesMatchingUII<'a, 'ast> {
385 ItemViaNode(node_id) =>
386 NodesMatchingDirect(Some(node_id).into_iter()),
387 ItemViaPath(ref parts) =>
388 NodesMatchingSuffix(map.nodes_matching_suffix(&parts[])),
392 fn to_one_node_id(self, user_option: &str, sess: &Session, map: &ast_map::Map) -> ast::NodeId {
393 let fail_because = |&: is_wrong_because| -> ast::NodeId {
395 format!("{} needs NodeId (int) or unique \
396 path suffix (b::c::d); got {}, which {}",
398 self.reconstructed_input(),
400 sess.fatal(&message[])
403 let mut saw_node = ast::DUMMY_NODE_ID;
405 for node in self.all_matching_node_ids(map) {
409 fail_because("does not resolve uniquely");
413 fail_because("does not resolve to any item");
421 fn needs_ast_map(ppm: &PpMode, opt_uii: &Option<UserIdentifiedItem>) -> bool {
423 PpmSource(PpmNormal) |
424 PpmSource(PpmEveryBodyLoops) |
425 PpmSource(PpmIdentified) => opt_uii.is_some(),
427 PpmSource(PpmExpanded) |
428 PpmSource(PpmExpandedIdentified) |
429 PpmSource(PpmExpandedHygiene) |
430 PpmSource(PpmTyped) |
431 PpmFlowGraph(_) => true
435 fn needs_expansion(ppm: &PpMode) -> bool {
437 PpmSource(PpmNormal) |
438 PpmSource(PpmEveryBodyLoops) |
439 PpmSource(PpmIdentified) => false,
441 PpmSource(PpmExpanded) |
442 PpmSource(PpmExpandedIdentified) |
443 PpmSource(PpmExpandedHygiene) |
444 PpmSource(PpmTyped) |
445 PpmFlowGraph(_) => true
449 struct ReplaceBodyWithLoop {
450 within_static_or_const: bool,
453 impl ReplaceBodyWithLoop {
454 fn new() -> ReplaceBodyWithLoop {
455 ReplaceBodyWithLoop { within_static_or_const: false }
459 impl fold::Folder for ReplaceBodyWithLoop {
460 fn fold_item_underscore(&mut self, i: ast::Item_) -> ast::Item_ {
462 ast::ItemStatic(..) | ast::ItemConst(..) => {
463 self.within_static_or_const = true;
464 let ret = fold::noop_fold_item_underscore(i, self);
465 self.within_static_or_const = false;
469 fold::noop_fold_item_underscore(i, self)
475 fn fold_block(&mut self, b: P<ast::Block>) -> P<ast::Block> {
476 fn expr_to_block(rules: ast::BlockCheckMode,
477 e: Option<P<ast::Expr>>) -> P<ast::Block> {
480 view_items: vec![], stmts: vec![], rules: rules,
481 id: ast::DUMMY_NODE_ID, span: codemap::DUMMY_SP,
485 if !self.within_static_or_const {
487 let empty_block = expr_to_block(ast::DefaultBlock, None);
488 let loop_expr = P(ast::Expr {
489 node: ast::ExprLoop(empty_block, None),
490 id: ast::DUMMY_NODE_ID, span: codemap::DUMMY_SP
493 expr_to_block(b.rules, Some(loop_expr))
496 fold::noop_fold_block(b, self)
500 // in general the pretty printer processes unexpanded code, so
501 // we override the default `fold_mac` method which panics.
502 fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac {
503 fold::noop_fold_mac(mac, self)
507 pub fn pretty_print_input(sess: Session,
508 cfg: ast::CrateConfig,
511 opt_uii: Option<UserIdentifiedItem>,
512 ofile: Option<Path>) {
513 let krate = driver::phase_1_parse_input(&sess, cfg, input);
515 let krate = if let PpmSource(PpmEveryBodyLoops) = ppm {
516 let mut fold = ReplaceBodyWithLoop::new();
517 fold.fold_crate(krate)
522 let id = link::find_crate_name(Some(&sess), krate.attrs.as_slice(), input);
524 let is_expanded = needs_expansion(&ppm);
525 let compute_ast_map = needs_ast_map(&ppm, &opt_uii);
526 let krate = if compute_ast_map {
527 match driver::phase_2_configure_and_expand(&sess, krate, &id[], None) {
535 let mut forest = ast_map::Forest::new(krate);
536 let arenas = ty::CtxtArenas::new();
538 let (krate, ast_map) = if compute_ast_map {
539 let map = driver::assign_node_ids_and_map(&sess, &mut forest);
540 (map.krate(), Some(map))
542 (forest.krate(), None)
545 let src_name = driver::source_name(input);
546 let src = sess.codemap().get_filemap(&src_name[])
547 .src.as_bytes().to_vec();
548 let mut rdr = MemReader::new(src);
550 let out = match ofile {
551 None => box io::stdout() as Box<Writer+'static>,
553 let r = io::File::create(&p);
555 Ok(w) => box w as Box<Writer+'static>,
556 Err(e) => panic!("print-print failed to open {} due to {}",
562 match (ppm, opt_uii) {
563 (PpmSource(s), None) =>
564 s.call_with_pp_support(
565 sess, ast_map, &arenas, id, out, |annotation, out| {
566 debug!("pretty printing source code {:?}", s);
567 let sess = annotation.sess();
568 pprust::print_crate(sess.codemap(),
571 src_name.to_string(),
578 (PpmSource(s), Some(uii)) =>
579 s.call_with_pp_support(
580 sess, ast_map, &arenas, id, (out,uii), |annotation, (out,uii)| {
581 debug!("pretty printing source code {:?}", s);
582 let sess = annotation.sess();
583 let ast_map = annotation.ast_map()
584 .expect("--pretty missing ast_map");
586 pprust::State::new_from_input(sess.codemap(),
588 src_name.to_string(),
593 for node_id in uii.all_matching_node_ids(ast_map) {
594 let node = ast_map.get(node_id);
595 try!(pp_state.print_node(&node));
596 try!(pp::space(&mut pp_state.s));
597 try!(pp_state.synth_comment(ast_map.path_to_string(node_id)));
598 try!(pp::hardbreak(&mut pp_state.s));
600 pp::eof(&mut pp_state.s)
603 (PpmFlowGraph(mode), opt_uii) => {
604 debug!("pretty printing flow graph for {:?}", opt_uii);
605 let uii = opt_uii.unwrap_or_else(|| {
606 sess.fatal(&format!("`pretty flowgraph=..` needs NodeId (int) or
607 unique path suffix (b::c::d)")[])
610 let ast_map = ast_map.expect("--pretty flowgraph missing ast_map");
611 let nodeid = uii.to_one_node_id("--pretty", &sess, &ast_map);
613 let node = ast_map.find(nodeid).unwrap_or_else(|| {
614 sess.fatal(&format!("--pretty flowgraph couldn't find id: {}",
618 let code = blocks::Code::from_node(node);
621 let variants = gather_flowgraph_variants(&sess);
622 let analysis = driver::phase_3_run_analysis_passes(sess,
626 resolve::MakeGlobMap::No);
627 print_flowgraph(variants, analysis, code, mode, out)
630 let message = format!("--pretty=flowgraph needs \
631 block, fn, or method; got {:?}",
634 // point to what was found, if there's an
636 match ast_map.opt_span(nodeid) {
637 Some(sp) => sess.span_fatal(sp, &message[]),
638 None => sess.fatal(&message[])
646 fn print_flowgraph<W:io::Writer>(variants: Vec<borrowck_dot::Variant>,
647 analysis: ty::CrateAnalysis,
649 mode: PpFlowGraphMode,
650 mut out: W) -> io::IoResult<()> {
651 let ty_cx = &analysis.ty_cx;
652 let cfg = match code {
653 blocks::BlockCode(block) => cfg::CFG::new(ty_cx, &*block),
654 blocks::FnLikeCode(fn_like) => cfg::CFG::new(ty_cx, &*fn_like.body()),
656 let labelled_edges = mode != PpFlowGraphMode::UnlabelledEdges;
657 let lcfg = LabelledCFG {
660 name: format!("node_{}", code.id()),
661 labelled_edges: labelled_edges,
665 _ if variants.len() == 0 => {
666 let r = dot::render(&lcfg, &mut out);
667 return expand_err_details(r);
669 blocks::BlockCode(_) => {
670 ty_cx.sess.err("--pretty flowgraph with -Z flowgraph-print \
671 annotations requires fn-like node id.");
674 blocks::FnLikeCode(fn_like) => {
675 let fn_parts = borrowck::FnPartsWithCFG::from_fn_like(&fn_like, &cfg);
676 let (bccx, analysis_data) =
677 borrowck::build_borrowck_dataflow_data_for_fn(ty_cx, fn_parts);
679 let lcfg = borrowck_dot::DataflowLabeller {
682 borrowck_ctxt: &bccx,
683 analysis_data: &analysis_data,
685 let r = dot::render(&lcfg, &mut out);
686 return expand_err_details(r);
690 fn expand_err_details(r: io::IoResult<()>) -> io::IoResult<()> {
692 let orig_detail = ioerr.detail.clone();
693 let m = "graphviz::render failed";
695 detail: Some(match orig_detail {
696 None => m.to_string(),
697 Some(d) => format!("{}: {}", m, d)