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};
42 use std::io::{self, Write};
44 use std::path::PathBuf;
45 use std::str::FromStr;
47 #[derive(Copy, PartialEq, Debug)]
48 pub enum PpSourceMode {
54 PpmExpandedIdentified,
59 #[derive(Copy, PartialEq, Debug)]
60 pub enum PpFlowGraphMode {
62 /// Drops the labels from the edges in the flowgraph output. This
63 /// is mostly for use in the --xpretty flowgraph run-make tests,
64 /// since the labels are largely uninteresting in those cases and
65 /// have become a pain to maintain.
68 #[derive(Copy, PartialEq, Debug)]
70 PpmSource(PpSourceMode),
71 PpmFlowGraph(PpFlowGraphMode),
74 pub fn parse_pretty(sess: &Session,
76 extended: bool) -> (PpMode, Option<UserIdentifiedItem>) {
77 let mut split = name.splitn(1, '=');
78 let first = split.next().unwrap();
79 let opt_second = split.next();
80 let first = match (first, extended) {
81 ("normal", _) => PpmSource(PpmNormal),
82 ("everybody_loops", true) => PpmSource(PpmEveryBodyLoops),
83 ("expanded", _) => PpmSource(PpmExpanded),
84 ("typed", _) => PpmSource(PpmTyped),
85 ("expanded,identified", _) => PpmSource(PpmExpandedIdentified),
86 ("expanded,hygiene", _) => PpmSource(PpmExpandedHygiene),
87 ("identified", _) => PpmSource(PpmIdentified),
88 ("flowgraph", true) => PpmFlowGraph(PpFlowGraphMode::Default),
89 ("flowgraph,unlabelled", true) => PpmFlowGraph(PpFlowGraphMode::UnlabelledEdges),
93 "argument to `xpretty` must be one of `normal`, \
94 `expanded`, `flowgraph[,unlabelled]=<nodeid>`, `typed`, `identified`, \
95 `expanded,identified`, or `everybody_loops`; got {}", name));
98 "argument to `pretty` must be one of `normal`, \
99 `expanded`, `typed`, `identified`, \
100 or `expanded,identified`; got {}", name));
104 let opt_second = opt_second.and_then(|s| s.parse::<UserIdentifiedItem>().ok());
110 // This slightly awkward construction is to allow for each PpMode to
111 // choose whether it needs to do analyses (which can consume the
112 // Session) and then pass through the session (now attached to the
113 // analysis results) on to the chosen pretty-printer, along with the
116 // Note that since the `&PrinterSupport` is freshly constructed on each
117 // call, it would not make sense to try to attach the lifetime of `self`
118 // to the lifetime of the `&PrinterObject`.
120 // (The `use_once_payload` is working around the current lack of once
121 // functions in the compiler.)
124 /// Constructs a `PrinterSupport` object and passes it to `f`.
125 fn call_with_pp_support<'tcx, A, B, F>(&self,
127 ast_map: Option<ast_map::Map<'tcx>>,
128 arenas: &'tcx ty::CtxtArenas<'tcx>,
132 F: FnOnce(&PrinterSupport, B) -> A,
135 PpmNormal | PpmEveryBodyLoops | PpmExpanded => {
136 let annotation = NoAnn { sess: sess, ast_map: ast_map };
137 f(&annotation, payload)
140 PpmIdentified | PpmExpandedIdentified => {
141 let annotation = IdentifiedAnnotation { sess: sess, ast_map: ast_map };
142 f(&annotation, payload)
144 PpmExpandedHygiene => {
145 let annotation = HygieneAnnotation { sess: sess, ast_map: ast_map };
146 f(&annotation, payload)
149 let ast_map = ast_map.expect("--pretty=typed missing ast_map");
150 let analysis = driver::phase_3_run_analysis_passes(sess,
154 resolve::MakeGlobMap::No);
155 let annotation = TypedAnnotation { analysis: analysis };
156 f(&annotation, payload)
162 trait PrinterSupport<'ast>: pprust::PpAnn {
163 /// Provides a uniform interface for re-extracting a reference to a
164 /// `Session` from a value that now owns it.
165 fn sess<'a>(&'a self) -> &'a Session;
167 /// Provides a uniform interface for re-extracting a reference to an
168 /// `ast_map::Map` from a value that now owns it.
169 fn ast_map<'a>(&'a self) -> Option<&'a ast_map::Map<'ast>>;
171 /// Produces the pretty-print annotation object.
173 /// (Rust does not yet support upcasting from a trait object to
174 /// an object for one of its super-traits.)
175 fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn;
180 ast_map: Option<ast_map::Map<'ast>>
183 impl<'ast> PrinterSupport<'ast> for NoAnn<'ast> {
184 fn sess<'a>(&'a self) -> &'a Session { &self.sess }
186 fn ast_map<'a>(&'a self) -> Option<&'a ast_map::Map<'ast>> {
187 self.ast_map.as_ref()
190 fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn { self }
193 impl<'ast> pprust::PpAnn for NoAnn<'ast> {}
195 struct IdentifiedAnnotation<'ast> {
197 ast_map: Option<ast_map::Map<'ast>>,
200 impl<'ast> PrinterSupport<'ast> for IdentifiedAnnotation<'ast> {
201 fn sess<'a>(&'a self) -> &'a Session { &self.sess }
203 fn ast_map<'a>(&'a self) -> Option<&'a ast_map::Map<'ast>> {
204 self.ast_map.as_ref()
207 fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn { self }
210 impl<'ast> pprust::PpAnn for IdentifiedAnnotation<'ast> {
212 s: &mut pprust::State,
213 node: pprust::AnnNode) -> io::Result<()> {
215 pprust::NodeExpr(_) => s.popen(),
220 s: &mut pprust::State,
221 node: pprust::AnnNode) -> io::Result<()> {
223 pprust::NodeIdent(_) | pprust::NodeName(_) => Ok(()),
225 pprust::NodeItem(item) => {
226 try!(pp::space(&mut s.s));
227 s.synth_comment(item.id.to_string())
229 pprust::NodeBlock(blk) => {
230 try!(pp::space(&mut s.s));
231 s.synth_comment(format!("block {}", blk.id))
233 pprust::NodeExpr(expr) => {
234 try!(pp::space(&mut s.s));
235 try!(s.synth_comment(expr.id.to_string()));
238 pprust::NodePat(pat) => {
239 try!(pp::space(&mut s.s));
240 s.synth_comment(format!("pat {}", pat.id))
246 struct HygieneAnnotation<'ast> {
248 ast_map: Option<ast_map::Map<'ast>>,
251 impl<'ast> PrinterSupport<'ast> for HygieneAnnotation<'ast> {
252 fn sess<'a>(&'a self) -> &'a Session { &self.sess }
254 fn ast_map<'a>(&'a self) -> Option<&'a ast_map::Map<'ast>> {
255 self.ast_map.as_ref()
258 fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn { self }
261 impl<'ast> pprust::PpAnn for HygieneAnnotation<'ast> {
263 s: &mut pprust::State,
264 node: pprust::AnnNode) -> io::Result<()> {
266 pprust::NodeIdent(&ast::Ident { name: ast::Name(nm), ctxt }) => {
267 try!(pp::space(&mut s.s));
268 // FIXME #16420: this doesn't display the connections
269 // between syntax contexts
270 s.synth_comment(format!("{}#{}", nm, ctxt))
272 pprust::NodeName(&ast::Name(nm)) => {
273 try!(pp::space(&mut s.s));
274 s.synth_comment(nm.to_string())
282 struct TypedAnnotation<'tcx> {
283 analysis: ty::CrateAnalysis<'tcx>,
286 impl<'tcx> PrinterSupport<'tcx> for TypedAnnotation<'tcx> {
287 fn sess<'a>(&'a self) -> &'a Session { &self.analysis.ty_cx.sess }
289 fn ast_map<'a>(&'a self) -> Option<&'a ast_map::Map<'tcx>> {
290 Some(&self.analysis.ty_cx.map)
293 fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn { self }
296 impl<'tcx> pprust::PpAnn for TypedAnnotation<'tcx> {
298 s: &mut pprust::State,
299 node: pprust::AnnNode) -> io::Result<()> {
301 pprust::NodeExpr(_) => s.popen(),
306 s: &mut pprust::State,
307 node: pprust::AnnNode) -> io::Result<()> {
308 let tcx = &self.analysis.ty_cx;
310 pprust::NodeExpr(expr) => {
311 try!(pp::space(&mut s.s));
312 try!(pp::word(&mut s.s, "as"));
313 try!(pp::space(&mut s.s));
314 try!(pp::word(&mut s.s,
315 &ppaux::ty_to_string(
317 ty::expr_ty(tcx, expr))));
325 fn gather_flowgraph_variants(sess: &Session) -> Vec<borrowck_dot::Variant> {
326 let print_loans = sess.opts.debugging_opts.flowgraph_print_loans;
327 let print_moves = sess.opts.debugging_opts.flowgraph_print_moves;
328 let print_assigns = sess.opts.debugging_opts.flowgraph_print_assigns;
329 let print_all = sess.opts.debugging_opts.flowgraph_print_all;
330 let mut variants = Vec::new();
331 if print_all || print_loans {
332 variants.push(borrowck_dot::Loans);
334 if print_all || print_moves {
335 variants.push(borrowck_dot::Moves);
337 if print_all || print_assigns {
338 variants.push(borrowck_dot::Assigns);
343 #[derive(Clone, Debug)]
344 pub enum UserIdentifiedItem {
345 ItemViaNode(ast::NodeId),
346 ItemViaPath(Vec<String>),
349 impl FromStr for UserIdentifiedItem {
351 fn from_str(s: &str) -> Result<UserIdentifiedItem, ()> {
352 Ok(s.parse().map(ItemViaNode).unwrap_or_else(|_| {
353 ItemViaPath(s.split("::").map(|s| s.to_string()).collect())
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 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<PathBuf>) {
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, 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[..])
552 let mut rdr = &src[..];
554 let mut out = Vec::new();
556 match (ppm, opt_uii) {
557 (PpmSource(s), None) => {
558 let out: &mut Write = &mut out;
559 s.call_with_pp_support(
560 sess, ast_map, &arenas, id, box out, |annotation, out| {
561 debug!("pretty printing source code {:?}", s);
562 let sess = annotation.sess();
563 pprust::print_crate(sess.codemap(),
566 src_name.to_string(),
574 (PpmSource(s), Some(uii)) => {
575 let out: &mut Write = &mut out;
576 s.call_with_pp_support(
577 sess, ast_map, &arenas, id, (out,uii), |annotation, (out,uii)| {
578 debug!("pretty printing source code {:?}", s);
579 let sess = annotation.sess();
580 let ast_map = annotation.ast_map()
581 .expect("--pretty missing ast_map");
583 pprust::State::new_from_input(sess.codemap(),
585 src_name.to_string(),
590 for node_id in uii.all_matching_node_ids(ast_map) {
591 let node = ast_map.get(node_id);
592 try!(pp_state.print_node(&node));
593 try!(pp::space(&mut pp_state.s));
594 try!(pp_state.synth_comment(ast_map.path_to_string(node_id)));
595 try!(pp::hardbreak(&mut pp_state.s));
597 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);
617 let out: &mut Write = &mut out;
620 let variants = gather_flowgraph_variants(&sess);
621 let analysis = driver::phase_3_run_analysis_passes(sess,
625 resolve::MakeGlobMap::No);
626 print_flowgraph(variants, analysis, code, mode, out)
629 let message = format!("--pretty=flowgraph needs \
630 block, fn, or method; got {:?}",
633 // point to what was found, if there's an
635 match ast_map.opt_span(nodeid) {
636 Some(sp) => sess.span_fatal(sp, &message[..]),
637 None => sess.fatal(&message[..])
645 None => print!("{}", String::from_utf8(out).unwrap()),
647 match File::create(&p) {
648 Ok(mut w) => w.write_all(&out).unwrap(),
649 Err(e) => panic!("print-print failed to open {} due to {}",
656 fn print_flowgraph<W: Write>(variants: Vec<borrowck_dot::Variant>,
657 analysis: ty::CrateAnalysis,
659 mode: PpFlowGraphMode,
660 mut out: W) -> io::Result<()> {
661 let ty_cx = &analysis.ty_cx;
662 let cfg = match code {
663 blocks::BlockCode(block) => cfg::CFG::new(ty_cx, &*block),
664 blocks::FnLikeCode(fn_like) => cfg::CFG::new(ty_cx, &*fn_like.body()),
666 let labelled_edges = mode != PpFlowGraphMode::UnlabelledEdges;
667 let lcfg = LabelledCFG {
670 name: format!("node_{}", code.id()),
671 labelled_edges: labelled_edges,
675 _ if variants.len() == 0 => {
676 let r = dot::render(&lcfg, &mut out);
677 return expand_err_details(r);
679 blocks::BlockCode(_) => {
680 ty_cx.sess.err("--pretty flowgraph with -Z flowgraph-print \
681 annotations requires fn-like node id.");
684 blocks::FnLikeCode(fn_like) => {
685 let fn_parts = borrowck::FnPartsWithCFG::from_fn_like(&fn_like, &cfg);
686 let (bccx, analysis_data) =
687 borrowck::build_borrowck_dataflow_data_for_fn(ty_cx, fn_parts);
689 let lcfg = borrowck_dot::DataflowLabeller {
692 borrowck_ctxt: &bccx,
693 analysis_data: &analysis_data,
695 let r = dot::render(&lcfg, &mut out);
696 return expand_err_details(r);
700 fn expand_err_details(r: io::Result<()>) -> io::Result<()> {
702 io::Error::new(io::ErrorKind::Other, "graphviz::render failed",
703 Some(ioerr.to_string()))