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::borrowck::{mod, FnPartsWithCFG};
24 use rustc::middle::borrowck::graphviz as borrowck_dot;
25 use rustc::middle::cfg;
26 use rustc::middle::cfg::graphviz::LabelledCFG;
27 use rustc::session::Session;
28 use rustc::session::config::{mod, Input};
29 use rustc::util::ppaux;
32 use syntax::ast_map::{mod, blocks, NodePrinter};
33 use syntax::print::{pp, pprust};
37 use std::io::{mod, MemReader};
39 use std::str::FromStr;
40 use arena::TypedArena;
42 #[deriving(PartialEq, Show)]
43 pub enum PpSourceMode {
48 PpmExpandedIdentified,
52 #[deriving(PartialEq, Show)]
54 PpmSource(PpSourceMode),
58 pub fn parse_pretty(sess: &Session, name: &str) -> (PpMode, Option<UserIdentifiedItem>) {
59 let mut split = name.splitn(1, '=');
60 let first = split.next().unwrap();
61 let opt_second = split.next();
62 let first = match first {
63 "normal" => PpmSource(PpmNormal),
64 "expanded" => PpmSource(PpmExpanded),
65 "typed" => PpmSource(PpmTyped),
66 "expanded,identified" => PpmSource(PpmExpandedIdentified),
67 "expanded,hygiene" => PpmSource(PpmExpandedHygiene),
68 "identified" => PpmSource(PpmIdentified),
69 "flowgraph" => PpmFlowGraph,
72 "argument to `pretty` must be one of `normal`, \
73 `expanded`, `flowgraph=<nodeid>`, `typed`, `identified`, \
74 or `expanded,identified`; got {}", name).as_slice());
77 let opt_second = opt_second.and_then::<UserIdentifiedItem>(from_str);
83 // This slightly awkward construction is to allow for each PpMode to
84 // choose whether it needs to do analyses (which can consume the
85 // Session) and then pass through the session (now attached to the
86 // analysis results) on to the chosen pretty-printer, along with the
89 // Note that since the `&PrinterSupport` is freshly constructed on each
90 // call, it would not make sense to try to attach the lifetime of `self`
91 // to the lifetime of the `&PrinterObject`.
93 // (The `use_once_payload` is working around the current lack of once
94 // functions in the compiler.)
97 /// Constructs a `PrinterSupport` object and passes it to `f`.
98 fn call_with_pp_support<'tcx, A, B>(&self,
100 ast_map: Option<ast_map::Map<'tcx>>,
101 type_arena: &'tcx TypedArena<ty::TyS<'tcx>>,
104 f: |&PrinterSupport, B| -> A) -> A {
106 PpmNormal | PpmExpanded => {
107 let annotation = NoAnn { sess: sess, ast_map: ast_map };
108 f(&annotation, payload)
111 PpmIdentified | PpmExpandedIdentified => {
112 let annotation = IdentifiedAnnotation { sess: sess, ast_map: ast_map };
113 f(&annotation, payload)
115 PpmExpandedHygiene => {
116 let annotation = HygieneAnnotation { sess: sess, ast_map: ast_map };
117 f(&annotation, payload)
120 let ast_map = ast_map.expect("--pretty=typed missing ast_map");
121 let analysis = driver::phase_3_run_analysis_passes(sess, ast_map,
123 let annotation = TypedAnnotation { analysis: analysis };
124 f(&annotation, payload)
130 trait PrinterSupport<'ast>: pprust::PpAnn {
131 /// Provides a uniform interface for re-extracting a reference to a
132 /// `Session` from a value that now owns it.
133 fn sess<'a>(&'a self) -> &'a Session;
135 /// Provides a uniform interface for re-extracting a reference to an
136 /// `ast_map::Map` from a value that now owns it.
137 fn ast_map<'a>(&'a self) -> Option<&'a ast_map::Map<'ast>>;
139 /// Produces the pretty-print annotation object.
141 /// (Rust does not yet support upcasting from a trait object to
142 /// an object for one of its super-traits.)
143 fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn { self as &pprust::PpAnn }
148 ast_map: Option<ast_map::Map<'ast>>
151 impl<'ast> PrinterSupport<'ast> for NoAnn<'ast> {
152 fn sess<'a>(&'a self) -> &'a Session { &self.sess }
154 fn ast_map<'a>(&'a self) -> Option<&'a ast_map::Map<'ast>> {
155 self.ast_map.as_ref()
159 impl<'ast> pprust::PpAnn for NoAnn<'ast> {}
161 struct IdentifiedAnnotation<'ast> {
163 ast_map: Option<ast_map::Map<'ast>>,
166 impl<'ast> PrinterSupport<'ast> for IdentifiedAnnotation<'ast> {
167 fn sess<'a>(&'a self) -> &'a Session { &self.sess }
169 fn ast_map<'a>(&'a self) -> Option<&'a ast_map::Map<'ast>> {
170 self.ast_map.as_ref()
174 impl<'ast> pprust::PpAnn for IdentifiedAnnotation<'ast> {
176 s: &mut pprust::State,
177 node: pprust::AnnNode) -> io::IoResult<()> {
179 pprust::NodeExpr(_) => s.popen(),
184 s: &mut pprust::State,
185 node: pprust::AnnNode) -> io::IoResult<()> {
187 pprust::NodeIdent(_) | pprust::NodeName(_) => Ok(()),
189 pprust::NodeItem(item) => {
190 try!(pp::space(&mut s.s));
191 s.synth_comment(item.id.to_string())
193 pprust::NodeBlock(blk) => {
194 try!(pp::space(&mut s.s));
195 s.synth_comment(format!("block {}", blk.id))
197 pprust::NodeExpr(expr) => {
198 try!(pp::space(&mut s.s));
199 try!(s.synth_comment(expr.id.to_string()));
202 pprust::NodePat(pat) => {
203 try!(pp::space(&mut s.s));
204 s.synth_comment(format!("pat {}", pat.id))
210 struct HygieneAnnotation<'ast> {
212 ast_map: Option<ast_map::Map<'ast>>,
215 impl<'ast> PrinterSupport<'ast> for HygieneAnnotation<'ast> {
216 fn sess<'a>(&'a self) -> &'a Session { &self.sess }
218 fn ast_map<'a>(&'a self) -> Option<&'a ast_map::Map<'ast>> {
219 self.ast_map.as_ref()
223 impl<'ast> pprust::PpAnn for HygieneAnnotation<'ast> {
225 s: &mut pprust::State,
226 node: pprust::AnnNode) -> io::IoResult<()> {
228 pprust::NodeIdent(&ast::Ident { name: ast::Name(nm), ctxt }) => {
229 try!(pp::space(&mut s.s));
230 // FIXME #16420: this doesn't display the connections
231 // between syntax contexts
232 s.synth_comment(format!("{}#{}", nm, ctxt))
234 pprust::NodeName(&ast::Name(nm)) => {
235 try!(pp::space(&mut s.s));
236 s.synth_comment(nm.to_string())
244 struct TypedAnnotation<'tcx> {
245 analysis: ty::CrateAnalysis<'tcx>,
248 impl<'tcx> PrinterSupport<'tcx> for TypedAnnotation<'tcx> {
249 fn sess<'a>(&'a self) -> &'a Session { &self.analysis.ty_cx.sess }
251 fn ast_map<'a>(&'a self) -> Option<&'a ast_map::Map<'tcx>> {
252 Some(&self.analysis.ty_cx.map)
256 impl<'tcx> pprust::PpAnn for TypedAnnotation<'tcx> {
258 s: &mut pprust::State,
259 node: pprust::AnnNode) -> io::IoResult<()> {
261 pprust::NodeExpr(_) => s.popen(),
266 s: &mut pprust::State,
267 node: pprust::AnnNode) -> io::IoResult<()> {
268 let tcx = &self.analysis.ty_cx;
270 pprust::NodeExpr(expr) => {
271 try!(pp::space(&mut s.s));
272 try!(pp::word(&mut s.s, "as"));
273 try!(pp::space(&mut s.s));
274 try!(pp::word(&mut s.s,
277 ty::expr_ty(tcx, expr)).as_slice()));
285 fn gather_flowgraph_variants(sess: &Session) -> Vec<borrowck_dot::Variant> {
286 let print_loans = config::FLOWGRAPH_PRINT_LOANS;
287 let print_moves = config::FLOWGRAPH_PRINT_MOVES;
288 let print_assigns = config::FLOWGRAPH_PRINT_ASSIGNS;
289 let print_all = config::FLOWGRAPH_PRINT_ALL;
290 let opt = |print_which| sess.debugging_opt(print_which);
291 let mut variants = Vec::new();
292 if opt(print_all) || opt(print_loans) {
293 variants.push(borrowck_dot::Loans);
295 if opt(print_all) || opt(print_moves) {
296 variants.push(borrowck_dot::Moves);
298 if opt(print_all) || opt(print_assigns) {
299 variants.push(borrowck_dot::Assigns);
304 #[deriving(Clone, Show)]
305 pub enum UserIdentifiedItem {
306 ItemViaNode(ast::NodeId),
307 ItemViaPath(Vec<String>),
310 impl FromStr for UserIdentifiedItem {
311 fn from_str(s: &str) -> Option<UserIdentifiedItem> {
312 let extract_path_parts = || {
313 let v : Vec<_> = s.split_str("::")
314 .map(|x|x.to_string())
319 from_str(s).map(ItemViaNode).or_else(extract_path_parts)
323 enum NodesMatchingUII<'a, 'ast: 'a> {
324 NodesMatchingDirect(option::Item<ast::NodeId>),
325 NodesMatchingSuffix(ast_map::NodesMatchingSuffix<'a, 'ast, String>),
328 impl<'a, 'ast> Iterator<ast::NodeId> for NodesMatchingUII<'a, 'ast> {
329 fn next(&mut self) -> Option<ast::NodeId> {
331 &NodesMatchingDirect(ref mut iter) => iter.next(),
332 &NodesMatchingSuffix(ref mut iter) => iter.next(),
337 impl UserIdentifiedItem {
338 fn reconstructed_input(&self) -> String {
340 ItemViaNode(node_id) => node_id.to_string(),
341 ItemViaPath(ref parts) => parts.connect("::"),
345 fn all_matching_node_ids<'a, 'ast>(&'a self, map: &'a ast_map::Map<'ast>)
346 -> NodesMatchingUII<'a, 'ast> {
348 ItemViaNode(node_id) =>
349 NodesMatchingDirect(Some(node_id).into_iter()),
350 ItemViaPath(ref parts) =>
351 NodesMatchingSuffix(map.nodes_matching_suffix(parts.as_slice())),
355 fn to_one_node_id(self, user_option: &str, sess: &Session, map: &ast_map::Map) -> ast::NodeId {
356 let fail_because = |is_wrong_because| -> ast::NodeId {
358 format!("{} needs NodeId (int) or unique \
359 path suffix (b::c::d); got {}, which {}",
361 self.reconstructed_input(),
363 sess.fatal(message.as_slice())
366 let mut saw_node = ast::DUMMY_NODE_ID;
368 for node in self.all_matching_node_ids(map) {
372 fail_because("does not resolve uniquely");
376 fail_because("does not resolve to any item");
384 fn needs_ast_map(ppm: &PpMode, opt_uii: &Option<UserIdentifiedItem>) -> bool {
386 PpmSource(PpmNormal) |
387 PpmSource(PpmIdentified) => opt_uii.is_some(),
389 PpmSource(PpmExpanded) |
390 PpmSource(PpmExpandedIdentified) |
391 PpmSource(PpmExpandedHygiene) |
392 PpmSource(PpmTyped) |
397 fn needs_expansion(ppm: &PpMode) -> bool {
399 PpmSource(PpmNormal) |
400 PpmSource(PpmIdentified) => false,
402 PpmSource(PpmExpanded) |
403 PpmSource(PpmExpandedIdentified) |
404 PpmSource(PpmExpandedHygiene) |
405 PpmSource(PpmTyped) |
410 pub fn pretty_print_input(sess: Session,
411 cfg: ast::CrateConfig,
414 opt_uii: Option<UserIdentifiedItem>,
415 ofile: Option<Path>) {
416 let krate = driver::phase_1_parse_input(&sess, cfg, input);
417 let id = link::find_crate_name(Some(&sess), krate.attrs.as_slice(), input);
419 let is_expanded = needs_expansion(&ppm);
420 let compute_ast_map = needs_ast_map(&ppm, &opt_uii);
421 let krate = if compute_ast_map {
422 match driver::phase_2_configure_and_expand(&sess, krate, id.as_slice(), None) {
430 let mut forest = ast_map::Forest::new(krate);
431 let type_arena = TypedArena::new();
433 let (krate, ast_map) = if compute_ast_map {
434 let map = driver::assign_node_ids_and_map(&sess, &mut forest);
435 (map.krate(), Some(map))
437 (forest.krate(), None)
440 let src_name = driver::source_name(input);
441 let src = sess.codemap().get_filemap(src_name.as_slice())
442 .src.as_bytes().to_vec();
443 let mut rdr = MemReader::new(src);
445 let out = match ofile {
446 None => box io::stdout() as Box<Writer+'static>,
448 let r = io::File::create(&p);
450 Ok(w) => box w as Box<Writer+'static>,
451 Err(e) => panic!("print-print failed to open {} due to {}",
457 match (ppm, opt_uii) {
458 (PpmSource(s), None) =>
459 s.call_with_pp_support(
460 sess, ast_map, &type_arena, id, out, |annotation, out| {
461 debug!("pretty printing source code {}", s);
462 let sess = annotation.sess();
463 pprust::print_crate(sess.codemap(),
466 src_name.to_string(),
473 (PpmSource(s), Some(uii)) =>
474 s.call_with_pp_support(
475 sess, ast_map, &type_arena, id, (out,uii), |annotation, (out,uii)| {
476 debug!("pretty printing source code {}", s);
477 let sess = annotation.sess();
478 let ast_map = annotation.ast_map()
479 .expect("--pretty missing ast_map");
481 pprust::State::new_from_input(sess.codemap(),
483 src_name.to_string(),
488 for node_id in uii.all_matching_node_ids(ast_map) {
489 let node = ast_map.get(node_id);
490 try!(pp_state.print_node(&node));
491 try!(pp::space(&mut pp_state.s));
492 try!(pp_state.synth_comment(ast_map.path_to_string(node_id)));
493 try!(pp::hardbreak(&mut pp_state.s));
495 pp::eof(&mut pp_state.s)
498 (PpmFlowGraph, opt_uii) => {
499 debug!("pretty printing flow graph for {}", opt_uii);
500 let uii = opt_uii.unwrap_or_else(|| {
501 sess.fatal(format!("`pretty flowgraph=..` needs NodeId (int) or
502 unique path suffix (b::c::d)").as_slice())
505 let ast_map = ast_map.expect("--pretty flowgraph missing ast_map");
506 let nodeid = uii.to_one_node_id("--pretty", &sess, &ast_map);
508 let node = ast_map.find(nodeid).unwrap_or_else(|| {
509 sess.fatal(format!("--pretty flowgraph couldn't find id: {}",
513 let code = blocks::Code::from_node(node);
516 let variants = gather_flowgraph_variants(&sess);
517 let analysis = driver::phase_3_run_analysis_passes(sess, ast_map,
519 print_flowgraph(variants, analysis, code, out)
522 let message = format!("--pretty=flowgraph needs \
523 block, fn, or method; got {}",
526 // point to what was found, if there's an
528 match ast_map.opt_span(nodeid) {
529 Some(sp) => sess.span_fatal(sp, message.as_slice()),
530 None => sess.fatal(message.as_slice())
538 fn print_flowgraph<W:io::Writer>(variants: Vec<borrowck_dot::Variant>,
539 analysis: ty::CrateAnalysis,
541 mut out: W) -> io::IoResult<()> {
542 let ty_cx = &analysis.ty_cx;
543 let cfg = match code {
544 blocks::BlockCode(block) => cfg::CFG::new(ty_cx, &*block),
545 blocks::FnLikeCode(fn_like) => cfg::CFG::new(ty_cx, &*fn_like.body()),
549 _ if variants.len() == 0 => {
550 let lcfg = LabelledCFG {
553 name: format!("node_{}", code.id()),
555 let r = dot::render(&lcfg, &mut out);
556 return expand_err_details(r);
558 blocks::BlockCode(_) => {
559 ty_cx.sess.err("--pretty flowgraph with -Z flowgraph-print \
560 annotations requires fn-like node id.");
563 blocks::FnLikeCode(fn_like) => {
564 let fn_parts = FnPartsWithCFG::from_fn_like(&fn_like, &cfg);
565 let (bccx, analysis_data) =
566 borrowck::build_borrowck_dataflow_data_for_fn(ty_cx, fn_parts);
568 let lcfg = LabelledCFG {
571 name: format!("node_{}", code.id()),
573 let lcfg = borrowck_dot::DataflowLabeller {
576 borrowck_ctxt: &bccx,
577 analysis_data: &analysis_data,
579 let r = dot::render(&lcfg, &mut out);
580 return expand_err_details(r);
584 fn expand_err_details(r: io::IoResult<()>) -> io::IoResult<()> {
586 let orig_detail = ioerr.detail.clone();
587 let m = "graphviz::render failed";
589 detail: Some(match orig_detail {
590 None => m.into_string(),
591 Some(d) => format!("{}: {}", m, d)