pretty-printer: let users choose particular items to pretty print.

With this change:

  * `--pretty variant=<node-id>` will print the item associated with
    `<node-id>` (where `<node-id>` is an integer for some node-id in
    the AST, and `variant` means one of {`normal`,`expanded`,...}).

  * `--pretty variant=<path-suffix>` will print all of the items that
    match the `<path-suffix>` (where `<path-suffix>` is a suffix of a
    path, and `variant` again means one of {`normal`,`expanded`,...}).

    Example 1: the suffix `typeck::check::check_struct` matches the
    item with the path `rustc::middle::typeck::check::check_struct`
    when compiling the `rustc` crate.

    Example 2: the suffix `and` matches `core::option::Option::and`
    and `core::result::Result::and` when compiling the `core` crate.

Both of the `--pretty variant=...` modes will include the full path to
the item in a comment that follows the item.

Note that when multiple paths match, then either:

  1. all matching items are printed, in series; this is what happens in
     the usual pretty-print variants, or

  2. the compiler signals an error; this is what happens in flowgraph
     printing.

----

Some drive-by improvements:

Heavily refactored the pretty-printing glue in driver.rs, introducing
a couple local traits to avoid cut-and-pasting very code segments that
differed only in how they accessed the `Session` or the
`ast_map::Map`. (Note the previous code had three similar calls to
`print_crate` which have all been unified in this revision; the
addition of printing individual node-ids exacerbated the situation
beyond tolerance.) We may want to consider promoting some of these
traits, e.g. `SessionCarrier`, for use more generally elsewhere in the
compiler; right now I have to double check how to access the `Session`
depending on what context I am hacking in.

Refactored `PpMode` to make the data directly reflect the fundamental
difference in the categories (in terms of printing source-code with
various annotations, versus printing a control-flow graph).

(also, addressed review feedback.)
This commit is contained in:
Felix S. Klock II 2014-08-07 18:22:24 +02:00
parent 8a80e0fdab
commit 575ea18d46
2 changed files with 319 additions and 75 deletions

View file

@ -11,9 +11,9 @@
use back::link;
use driver::session::Session;
use driver::{config, PpMode};
use driver::{config, PpMode, PpSourceMode};
use driver::{PpmFlowGraph, PpmExpanded, PpmExpandedIdentified, PpmTyped};
use driver::{PpmIdentified};
use driver::{PpmIdentified, PpmNormal, PpmSource};
use front;
use lint;
use llvm::{ContextRef, ModuleRef};
@ -39,11 +39,15 @@ use dot = graphviz;
use serialize::{json, Encodable};
use std::from_str::FromStr;
use std::io;
use std::io::fs;
use std::io::MemReader;
use std::option;
use syntax::ast;
use syntax::ast_map;
use syntax::ast_map::blocks;
use syntax::ast_map::NodePrinter;
use syntax::attr;
use syntax::attr::{AttrMetaMethods};
use syntax::diagnostics;
@ -602,7 +606,90 @@ fn write_out_deps(sess: &Session,
}
}
struct IdentifiedAnnotation;
// This slightly awkward construction is to allow for each PpMode to
// choose whether it needs to do analyses (which can consume the
// Session) and then pass through the session (now attached to the
// analysis results) on to the chosen pretty-printer, along with the
// `&PpAnn` object.
//
// Note that since the `&PrinterSupport` is freshly constructed on each
// call, it would not make sense to try to attach the lifetime of `self`
// to the lifetime of the `&PrinterObject`.
//
// (The `use_once_payload` is working around the current lack of once
// functions in the compiler.)
trait CratePrinter {
/// Constructs a `PrinterSupport` object and passes it to `f`.
fn call_with_pp_support<A,B>(&self,
sess: Session,
krate: &ast::Crate,
ast_map: Option<syntax::ast_map::Map>,
id: String,
use_once_payload: B,
f: |&PrinterSupport, B| -> A) -> A;
}
trait SessionCarrier {
/// Provides a uniform interface for re-extracting a reference to a
/// `Session` from a value that now owns it.
fn sess<'a>(&'a self) -> &'a Session;
}
trait AstMapCarrier {
/// Provides a uniform interface for re-extracting a reference to an
/// `ast_map::Map` from a value that now owns it.
fn ast_map<'a>(&'a self) -> Option<&'a ast_map::Map>;
}
trait PrinterSupport : SessionCarrier + AstMapCarrier {
/// Produces the pretty-print annotation object.
///
/// Usually implemented via `self as &pprust::PpAnn`.
///
/// (Rust does not yet support upcasting from a trait object to
/// an object for one of its super-traits.)
fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn;
}
struct NoAnn {
sess: Session,
ast_map: Option<ast_map::Map>,
}
impl PrinterSupport for NoAnn {
fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn { self as &pprust::PpAnn }
}
impl SessionCarrier for NoAnn {
fn sess<'a>(&'a self) -> &'a Session { &self.sess }
}
impl AstMapCarrier for NoAnn {
fn ast_map<'a>(&'a self) -> Option<&'a ast_map::Map> {
self.ast_map.as_ref()
}
}
impl pprust::PpAnn for NoAnn {}
struct IdentifiedAnnotation {
sess: Session,
ast_map: Option<ast_map::Map>,
}
impl PrinterSupport for IdentifiedAnnotation {
fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn { self as &pprust::PpAnn }
}
impl SessionCarrier for IdentifiedAnnotation {
fn sess<'a>(&'a self) -> &'a Session { &self.sess }
}
impl AstMapCarrier for IdentifiedAnnotation {
fn ast_map<'a>(&'a self) -> Option<&'a ast_map::Map> {
self.ast_map.as_ref()
}
}
impl pprust::PpAnn for IdentifiedAnnotation {
fn pre(&self,
@ -642,6 +729,20 @@ struct TypedAnnotation {
analysis: CrateAnalysis,
}
impl PrinterSupport for TypedAnnotation {
fn pp_ann<'a>(&'a self) -> &'a pprust::PpAnn { self as &pprust::PpAnn }
}
impl SessionCarrier for TypedAnnotation {
fn sess<'a>(&'a self) -> &'a Session { &self.analysis.ty_cx.sess }
}
impl AstMapCarrier for TypedAnnotation {
fn ast_map<'a>(&'a self) -> Option<&'a ast_map::Map> {
Some(&self.analysis.ty_cx.map)
}
}
impl pprust::PpAnn for TypedAnnotation {
fn pre(&self,
s: &mut pprust::State,
@ -690,25 +791,155 @@ fn gather_flowgraph_variants(sess: &Session) -> Vec<borrowck_dot::Variant> {
variants
}
#[deriving(Clone, Show)]
pub enum UserIdentifiedItem {
ItemViaNode(ast::NodeId),
ItemViaPath(Vec<String>),
}
impl FromStr for UserIdentifiedItem {
fn from_str(s: &str) -> Option<UserIdentifiedItem> {
let extract_path_parts = || {
let v : Vec<_> = s.split_str("::")
.map(|x|x.to_string())
.collect();
Some(ItemViaPath(v))
};
from_str(s).map(ItemViaNode).or_else(extract_path_parts)
}
}
enum NodesMatchingUII<'a> {
NodesMatchingDirect(option::Item<ast::NodeId>),
NodesMatchingSuffix(ast_map::NodesMatchingSuffix<'a, String>),
}
impl<'a> Iterator<ast::NodeId> for NodesMatchingUII<'a> {
fn next(&mut self) -> Option<ast::NodeId> {
match self {
&NodesMatchingDirect(ref mut iter) => iter.next(),
&NodesMatchingSuffix(ref mut iter) => iter.next(),
}
}
}
impl UserIdentifiedItem {
fn reconstructed_input(&self) -> String {
match *self {
ItemViaNode(node_id) => node_id.to_string(),
ItemViaPath(ref parts) => parts.connect("::"),
}
}
fn all_matching_node_ids<'a>(&'a self, map: &'a ast_map::Map) -> NodesMatchingUII<'a> {
match *self {
ItemViaNode(node_id) =>
NodesMatchingDirect(Some(node_id).move_iter()),
ItemViaPath(ref parts) =>
NodesMatchingSuffix(map.nodes_matching_suffix(parts.as_slice())),
}
}
fn to_one_node_id(self, user_option: &str, sess: &Session, map: &ast_map::Map) -> ast::NodeId {
let fail_because = |is_wrong_because| -> ast::NodeId {
let message =
format!("{:s} needs NodeId (int) or unique \
path suffix (b::c::d); got {:s}, which {:s}",
user_option,
self.reconstructed_input(),
is_wrong_because);
sess.fatal(message.as_slice())
};
let mut saw_node = ast::DUMMY_NODE_ID;
let mut seen = 0u;
for node in self.all_matching_node_ids(map) {
saw_node = node;
seen += 1;
if seen > 1 {
fail_because("does not resolve uniquely");
}
}
if seen == 0 {
fail_because("does not resolve to any item");
}
assert!(seen == 1);
return saw_node;
}
}
impl CratePrinter for PpSourceMode {
fn call_with_pp_support<A,B>(&self,
sess: Session,
krate: &ast::Crate,
ast_map: Option<syntax::ast_map::Map>,
id: String,
payload: B,
f: |&PrinterSupport, B| -> A) -> A {
match *self {
PpmNormal | PpmExpanded => {
let annotation = NoAnn { sess: sess, ast_map: ast_map };
f(&annotation, payload)
}
PpmIdentified | PpmExpandedIdentified => {
let annotation = IdentifiedAnnotation { sess: sess, ast_map: ast_map };
f(&annotation, payload)
}
PpmTyped => {
let ast_map = ast_map.expect("--pretty=typed missing ast_map");
let analysis = phase_3_run_analysis_passes(sess, krate, ast_map, id);
let annotation = TypedAnnotation { analysis: analysis };
f(&annotation, payload)
}
}
}
}
fn needs_ast_map(ppm: &PpMode, opt_uii: &Option<UserIdentifiedItem>) -> bool {
match *ppm {
PpmSource(PpmNormal) |
PpmSource(PpmIdentified) => opt_uii.is_some(),
PpmSource(PpmExpanded) |
PpmSource(PpmExpandedIdentified) |
PpmSource(PpmTyped) |
PpmFlowGraph => true
}
}
fn needs_expansion(ppm: &PpMode) -> bool {
match *ppm {
PpmSource(PpmNormal) |
PpmSource(PpmIdentified) => false,
PpmSource(PpmExpanded) |
PpmSource(PpmExpandedIdentified) |
PpmSource(PpmTyped) |
PpmFlowGraph => true
}
}
pub fn pretty_print_input(sess: Session,
cfg: ast::CrateConfig,
input: &Input,
ppm: PpMode,
opt_uii: Option<UserIdentifiedItem>,
ofile: Option<Path>) {
let krate = phase_1_parse_input(&sess, cfg, input);
let id = link::find_crate_name(Some(&sess), krate.attrs.as_slice(), input);
let (krate, ast_map, is_expanded) = match ppm {
PpmExpanded | PpmExpandedIdentified | PpmTyped | PpmFlowGraph(_) => {
let (krate, ast_map)
= match phase_2_configure_and_expand(&sess, krate,
id.as_slice(), None) {
None => return,
Some(p) => p,
};
(krate, Some(ast_map), true)
}
_ => (krate, None, false)
let is_expanded = needs_expansion(&ppm);
let (krate, ast_map) = if needs_ast_map(&ppm, &opt_uii) {
let k = phase_2_configure_and_expand(&sess, krate, id.as_slice(), None);
let (krate, ast_map) = match k {
None => return,
Some(p) => p,
};
(krate, Some(ast_map))
} else {
(krate, None)
};
let src_name = source_name(input);
@ -729,38 +960,63 @@ pub fn pretty_print_input(sess: Session,
}
}
};
match ppm {
PpmIdentified | PpmExpandedIdentified => {
pprust::print_crate(sess.codemap(),
sess.diagnostic(),
&krate,
src_name.to_string(),
&mut rdr,
out,
&IdentifiedAnnotation,
is_expanded)
}
PpmTyped => {
let ast_map = ast_map.expect("--pretty=typed missing ast_map");
let analysis = phase_3_run_analysis_passes(sess, &krate, ast_map, id);
let annotation = TypedAnnotation {
analysis: analysis
};
pprust::print_crate(annotation.analysis.ty_cx.sess.codemap(),
annotation.analysis.ty_cx.sess.diagnostic(),
&krate,
src_name.to_string(),
&mut rdr,
out,
&annotation,
is_expanded)
}
PpmFlowGraph(nodeid) => {
match (ppm, opt_uii) {
(PpmSource(s), None) =>
s.call_with_pp_support(
sess, &krate, ast_map, id, out, |annotation, out| {
debug!("pretty printing source code {}", s);
let sess = annotation.sess();
pprust::print_crate(sess.codemap(),
sess.diagnostic(),
&krate,
src_name.to_string(),
&mut rdr,
out,
annotation.pp_ann(),
is_expanded)
}),
(PpmSource(s), Some(uii)) =>
s.call_with_pp_support(
sess, &krate, ast_map, id, (out,uii), |annotation, (out,uii)| {
debug!("pretty printing source code {}", s);
let sess = annotation.sess();
let ast_map = annotation.ast_map()
.expect("--pretty missing ast_map");
let mut pp_state =
pprust::State::new_from_input(sess.codemap(),
sess.diagnostic(),
src_name.to_string(),
&mut rdr,
out,
annotation.pp_ann(),
is_expanded);
for node_id in uii.all_matching_node_ids(ast_map) {
let node = ast_map.get(node_id);
try!(pp_state.print_node(&node));
try!(pp::space(&mut pp_state.s));
try!(pp_state.synth_comment(ast_map.path_to_string(node_id)));
try!(pp::hardbreak(&mut pp_state.s));
}
pp::eof(&mut pp_state.s)
}),
(PpmFlowGraph, opt_uii) => {
debug!("pretty printing flow graph for {}", opt_uii);
let uii = opt_uii.unwrap_or_else(|| {
sess.fatal(format!("`pretty flowgraph=..` needs NodeId (int) or
unique path suffix (b::c::d)").as_slice())
});
let ast_map = ast_map.expect("--pretty flowgraph missing ast_map");
let nodeid = uii.to_one_node_id("--pretty", &sess, &ast_map);
let node = ast_map.find(nodeid).unwrap_or_else(|| {
sess.fatal(format!("--pretty flowgraph couldn't find id: {}",
nodeid).as_slice())
});
let code = blocks::Code::from_node(node);
match code {
Some(code) => {
@ -783,18 +1039,7 @@ pub fn pretty_print_input(sess: Session,
}
}
}
_ => {
pprust::print_crate(sess.codemap(),
sess.diagnostic(),
&krate,
src_name.to_string(),
&mut rdr,
out,
&pprust::NoAnn,
is_expanded)
}
}.unwrap()
}
fn print_flowgraph<W:io::Writer>(variants: Vec<borrowck_dot::Variant>,

View file

@ -99,11 +99,11 @@ fn run_compiler(args: &[String]) {
parse_pretty(&sess, a.as_slice())
});
match pretty {
Some::<PpMode>(ppm) => {
driver::pretty_print_input(sess, cfg, &input, ppm, ofile);
Some((ppm, opt_uii)) => {
driver::pretty_print_input(sess, cfg, &input, ppm, opt_uii, ofile);
return;
}
None::<PpMode> => {/* continue */ }
None => {/* continue */ }
}
let r = matches.opt_strs("Z");
@ -340,42 +340,41 @@ fn print_crate_info(sess: &Session,
}
}
pub enum PpMode {
#[deriving(PartialEq, Show)]
pub enum PpSourceMode {
PpmNormal,
PpmExpanded,
PpmTyped,
PpmIdentified,
PpmExpandedIdentified,
PpmFlowGraph(ast::NodeId),
}
pub fn parse_pretty(sess: &Session, name: &str) -> PpMode {
#[deriving(PartialEq, Show)]
pub enum PpMode {
PpmSource(PpSourceMode),
PpmFlowGraph,
}
fn parse_pretty(sess: &Session, name: &str) -> (PpMode, Option<driver::UserIdentifiedItem>) {
let mut split = name.splitn('=', 1);
let first = split.next().unwrap();
let opt_second = split.next();
match (opt_second, first) {
(None, "normal") => PpmNormal,
(None, "expanded") => PpmExpanded,
(None, "typed") => PpmTyped,
(None, "expanded,identified") => PpmExpandedIdentified,
(None, "identified") => PpmIdentified,
(arg, "flowgraph") => {
match arg.and_then(from_str) {
Some(id) => PpmFlowGraph(id),
None => {
sess.fatal(format!("`pretty flowgraph=<nodeid>` needs \
an integer <nodeid>; got {}",
arg.unwrap_or("nothing")).as_slice())
}
}
}
let first = match first {
"normal" => PpmSource(PpmNormal),
"expanded" => PpmSource(PpmExpanded),
"typed" => PpmSource(PpmTyped),
"expanded,identified" => PpmSource(PpmExpandedIdentified),
"identified" => PpmSource(PpmIdentified),
"flowgraph" => PpmFlowGraph,
_ => {
sess.fatal(format!(
"argument to `pretty` must be one of `normal`, \
`expanded`, `flowgraph=<nodeid>`, `typed`, `identified`, \
or `expanded,identified`; got {}", name).as_slice());
}
}
};
let opt_second = opt_second.and_then::<driver::UserIdentifiedItem>(from_str);
(first, opt_second)
}
fn parse_crate_attrs(sess: &Session, input: &Input) ->