Skip to content

Commit 87134c7

Browse files
committed
auto merge of #16326 : pnkfelix/rust/fsk-add-path-suffix-lookup, r=huonw
Extended `ast_map::Map` with an iterator over all node id's that match a path suffix. Extended pretty printer to let users choose particular items to pretty print, either by indicating an integer node-id, or by providing a path suffix. * 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. Refactored `pprust` slightly to support the pretty printer changes. (See individual commits for more description.)
2 parents a23d679 + db0e71f commit 87134c7

File tree

9 files changed

+613
-100
lines changed

9 files changed

+613
-100
lines changed

src/librustc/driver/driver.rs

+297-52
Large diffs are not rendered by default.

src/librustc/driver/mod.rs

+22-23
Original file line numberDiff line numberDiff line change
@@ -99,11 +99,11 @@ fn run_compiler(args: &[String]) {
9999
parse_pretty(&sess, a.as_slice())
100100
});
101101
match pretty {
102-
Some::<PpMode>(ppm) => {
103-
driver::pretty_print_input(sess, cfg, &input, ppm, ofile);
102+
Some((ppm, opt_uii)) => {
103+
driver::pretty_print_input(sess, cfg, &input, ppm, opt_uii, ofile);
104104
return;
105105
}
106-
None::<PpMode> => {/* continue */ }
106+
None => {/* continue */ }
107107
}
108108

109109
let r = matches.opt_strs("Z");
@@ -340,42 +340,41 @@ fn print_crate_info(sess: &Session,
340340
}
341341
}
342342

343-
pub enum PpMode {
343+
#[deriving(PartialEq, Show)]
344+
pub enum PpSourceMode {
344345
PpmNormal,
345346
PpmExpanded,
346347
PpmTyped,
347348
PpmIdentified,
348349
PpmExpandedIdentified,
349-
PpmFlowGraph(ast::NodeId),
350350
}
351351

352-
pub fn parse_pretty(sess: &Session, name: &str) -> PpMode {
352+
#[deriving(PartialEq, Show)]
353+
pub enum PpMode {
354+
PpmSource(PpSourceMode),
355+
PpmFlowGraph,
356+
}
357+
358+
fn parse_pretty(sess: &Session, name: &str) -> (PpMode, Option<driver::UserIdentifiedItem>) {
353359
let mut split = name.splitn('=', 1);
354360
let first = split.next().unwrap();
355361
let opt_second = split.next();
356-
match (opt_second, first) {
357-
(None, "normal") => PpmNormal,
358-
(None, "expanded") => PpmExpanded,
359-
(None, "typed") => PpmTyped,
360-
(None, "expanded,identified") => PpmExpandedIdentified,
361-
(None, "identified") => PpmIdentified,
362-
(arg, "flowgraph") => {
363-
match arg.and_then(from_str) {
364-
Some(id) => PpmFlowGraph(id),
365-
None => {
366-
sess.fatal(format!("`pretty flowgraph=<nodeid>` needs \
367-
an integer <nodeid>; got {}",
368-
arg.unwrap_or("nothing")).as_slice())
369-
}
370-
}
371-
}
362+
let first = match first {
363+
"normal" => PpmSource(PpmNormal),
364+
"expanded" => PpmSource(PpmExpanded),
365+
"typed" => PpmSource(PpmTyped),
366+
"expanded,identified" => PpmSource(PpmExpandedIdentified),
367+
"identified" => PpmSource(PpmIdentified),
368+
"flowgraph" => PpmFlowGraph,
372369
_ => {
373370
sess.fatal(format!(
374371
"argument to `pretty` must be one of `normal`, \
375372
`expanded`, `flowgraph=<nodeid>`, `typed`, `identified`, \
376373
or `expanded,identified`; got {}", name).as_slice());
377374
}
378-
}
375+
};
376+
let opt_second = opt_second.and_then::<driver::UserIdentifiedItem>(from_str);
377+
(first, opt_second)
379378
}
380379

381380
fn parse_crate_attrs(sess: &Session, input: &Input) ->

src/libsyntax/ast_map/mod.rs

+161-1
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
use abi;
1212
use ast::*;
1313
use ast_util;
14-
use codemap::Span;
14+
use codemap::{Span, Spanned};
1515
use fold::Folder;
1616
use fold;
1717
use parse::token;
@@ -21,6 +21,7 @@ use util::small_vector::SmallVector;
2121
use std::cell::RefCell;
2222
use std::fmt;
2323
use std::gc::{Gc, GC};
24+
use std::io::IoResult;
2425
use std::iter;
2526
use std::slice;
2627

@@ -203,6 +204,10 @@ pub struct Map {
203204
}
204205

205206
impl Map {
207+
fn entry_count(&self) -> uint {
208+
self.map.borrow().len()
209+
}
210+
206211
fn find_entry(&self, id: NodeId) -> Option<MapEntry> {
207212
let map = self.map.borrow();
208213
if map.len() > id as uint {
@@ -405,6 +410,20 @@ impl Map {
405410
f(attrs)
406411
}
407412

413+
/// Returns an iterator that yields the node id's with paths that
414+
/// match `parts`. (Requires `parts` is non-empty.)
415+
///
416+
/// For example, if given `parts` equal to `["bar", "quux"]`, then
417+
/// the iterator will produce node id's for items with paths
418+
/// such as `foo::bar::quux`, `bar::quux`, `other::bar::quux`, and
419+
/// any other such items it can find in the map.
420+
pub fn nodes_matching_suffix<'a, S:Str>(&'a self, parts: &'a [S]) -> NodesMatchingSuffix<'a,S> {
421+
NodesMatchingSuffix { map: self,
422+
item_name: parts.last().unwrap(),
423+
where: parts.slice_to(parts.len() - 1),
424+
idx: 0 }
425+
}
426+
408427
pub fn opt_span(&self, id: NodeId) -> Option<Span> {
409428
let sp = match self.find(id) {
410429
Some(NodeItem(item)) => item.span,
@@ -438,6 +457,119 @@ impl Map {
438457
}
439458
}
440459

460+
pub struct NodesMatchingSuffix<'a, S> {
461+
map: &'a Map,
462+
item_name: &'a S,
463+
where: &'a [S],
464+
idx: NodeId,
465+
}
466+
467+
impl<'a,S:Str> NodesMatchingSuffix<'a,S> {
468+
/// Returns true only if some suffix of the module path for parent
469+
/// matches `self.where`.
470+
///
471+
/// In other words: let `[x_0,x_1,...,x_k]` be `self.where`;
472+
/// returns true if parent's path ends with the suffix
473+
/// `x_0::x_1::...::x_k`.
474+
fn suffix_matches(&self, parent: NodeId) -> bool {
475+
let mut cursor = parent;
476+
for part in self.where.iter().rev() {
477+
let (mod_id, mod_name) = match find_first_mod_parent(self.map, cursor) {
478+
None => return false,
479+
Some((node_id, name)) => (node_id, name),
480+
};
481+
if part.as_slice() != mod_name.as_str() {
482+
return false;
483+
}
484+
cursor = self.map.get_parent(mod_id);
485+
}
486+
return true;
487+
488+
// Finds the first mod in parent chain for `id`, along with
489+
// that mod's name.
490+
//
491+
// If `id` itself is a mod named `m` with parent `p`, then
492+
// returns `Some(id, m, p)`. If `id` has no mod in its parent
493+
// chain, then returns `None`.
494+
fn find_first_mod_parent<'a>(map: &'a Map, mut id: NodeId) -> Option<(NodeId, Name)> {
495+
loop {
496+
match map.find(id) {
497+
None => return None,
498+
Some(NodeItem(item)) if item_is_mod(&*item) =>
499+
return Some((id, item.ident.name)),
500+
_ => {}
501+
}
502+
let parent = map.get_parent(id);
503+
if parent == id { return None }
504+
id = parent;
505+
}
506+
507+
fn item_is_mod(item: &Item) -> bool {
508+
match item.node {
509+
ItemMod(_) => true,
510+
_ => false,
511+
}
512+
}
513+
}
514+
}
515+
516+
// We are looking at some node `n` with a given name and parent
517+
// id; do their names match what I am seeking?
518+
fn matches_names(&self, parent_of_n: NodeId, name: Name) -> bool {
519+
name.as_str() == self.item_name.as_slice() &&
520+
self.suffix_matches(parent_of_n)
521+
}
522+
}
523+
524+
impl<'a,S:Str> Iterator<NodeId> for NodesMatchingSuffix<'a,S> {
525+
fn next(&mut self) -> Option<NodeId> {
526+
loop {
527+
let idx = self.idx;
528+
if idx as uint >= self.map.entry_count() {
529+
return None;
530+
}
531+
self.idx += 1;
532+
let (p, name) = match self.map.find_entry(idx) {
533+
Some(EntryItem(p, n)) => (p, n.name()),
534+
Some(EntryForeignItem(p, n)) => (p, n.name()),
535+
Some(EntryTraitMethod(p, n)) => (p, n.name()),
536+
Some(EntryMethod(p, n)) => (p, n.name()),
537+
Some(EntryVariant(p, n)) => (p, n.name()),
538+
_ => continue,
539+
};
540+
if self.matches_names(p, name) {
541+
return Some(idx)
542+
}
543+
}
544+
}
545+
}
546+
547+
trait Named {
548+
fn name(&self) -> Name;
549+
}
550+
551+
impl<T:Named> Named for Spanned<T> { fn name(&self) -> Name { self.node.name() } }
552+
553+
impl Named for Item { fn name(&self) -> Name { self.ident.name } }
554+
impl Named for ForeignItem { fn name(&self) -> Name { self.ident.name } }
555+
impl Named for Variant_ { fn name(&self) -> Name { self.name.name } }
556+
impl Named for TraitMethod {
557+
fn name(&self) -> Name {
558+
match *self {
559+
Required(ref tm) => tm.ident.name,
560+
Provided(m) => m.name(),
561+
}
562+
}
563+
}
564+
impl Named for Method {
565+
fn name(&self) -> Name {
566+
match self.node {
567+
MethDecl(i, _, _, _, _, _, _, _) => i.name,
568+
MethMac(_) => fail!("encountered unexpanded method macro."),
569+
}
570+
}
571+
}
572+
441573
pub trait FoldOps {
442574
fn new_id(&self, id: NodeId) -> NodeId {
443575
id
@@ -688,6 +820,34 @@ pub fn map_decoded_item<F: FoldOps>(map: &Map,
688820
ii
689821
}
690822

823+
pub trait NodePrinter {
824+
fn print_node(&mut self, node: &Node) -> IoResult<()>;
825+
}
826+
827+
impl<'a> NodePrinter for pprust::State<'a> {
828+
fn print_node(&mut self, node: &Node) -> IoResult<()> {
829+
match *node {
830+
NodeItem(a) => self.print_item(&*a),
831+
NodeForeignItem(a) => self.print_foreign_item(&*a),
832+
NodeTraitMethod(a) => self.print_trait_method(&*a),
833+
NodeMethod(a) => self.print_method(&*a),
834+
NodeVariant(a) => self.print_variant(&*a),
835+
NodeExpr(a) => self.print_expr(&*a),
836+
NodeStmt(a) => self.print_stmt(&*a),
837+
NodePat(a) => self.print_pat(&*a),
838+
NodeBlock(a) => self.print_block(&*a),
839+
NodeLifetime(a) => self.print_lifetime(&*a),
840+
841+
// these cases do not carry enough information in the
842+
// ast_map to reconstruct their full structure for pretty
843+
// printing.
844+
NodeLocal(_) => fail!("cannot print isolated Local"),
845+
NodeArg(_) => fail!("cannot print isolated Arg"),
846+
NodeStructCtor(_) => fail!("cannot print isolated StructCtor"),
847+
}
848+
}
849+
}
850+
691851
fn node_id_to_string(map: &Map, id: NodeId) -> String {
692852
match map.find(id) {
693853
Some(NodeItem(item)) => {

src/libsyntax/print/pprust.rs

+51-24
Original file line numberDiff line numberDiff line change
@@ -97,35 +97,62 @@ pub fn print_crate<'a>(cm: &'a CodeMap,
9797
out: Box<io::Writer>,
9898
ann: &'a PpAnn,
9999
is_expanded: bool) -> IoResult<()> {
100-
let (cmnts, lits) = comments::gather_comments_and_literals(
101-
span_diagnostic,
102-
filename,
103-
input
104-
);
105-
let mut s = State {
106-
s: pp::mk_printer(out, default_columns),
107-
cm: Some(cm),
108-
comments: Some(cmnts),
109-
// If the code is post expansion, don't use the table of
110-
// literals, since it doesn't correspond with the literals
111-
// in the AST anymore.
112-
literals: if is_expanded {
113-
None
114-
} else {
115-
Some(lits)
116-
},
117-
cur_cmnt_and_lit: CurrentCommentAndLiteral {
118-
cur_cmnt: 0,
119-
cur_lit: 0
120-
},
121-
boxes: Vec::new(),
122-
ann: ann
123-
};
100+
let mut s = State::new_from_input(cm,
101+
span_diagnostic,
102+
filename,
103+
input,
104+
out,
105+
ann,
106+
is_expanded);
124107
try!(s.print_mod(&krate.module, krate.attrs.as_slice()));
125108
try!(s.print_remaining_comments());
126109
eof(&mut s.s)
127110
}
128111

112+
impl<'a> State<'a> {
113+
pub fn new_from_input(cm: &'a CodeMap,
114+
span_diagnostic: &diagnostic::SpanHandler,
115+
filename: String,
116+
input: &mut io::Reader,
117+
out: Box<io::Writer>,
118+
ann: &'a PpAnn,
119+
is_expanded: bool) -> State<'a> {
120+
let (cmnts, lits) = comments::gather_comments_and_literals(
121+
span_diagnostic,
122+
filename,
123+
input);
124+
125+
State::new(
126+
cm,
127+
out,
128+
ann,
129+
Some(cmnts),
130+
// If the code is post expansion, don't use the table of
131+
// literals, since it doesn't correspond with the literals
132+
// in the AST anymore.
133+
if is_expanded { None } else { Some(lits) })
134+
}
135+
136+
pub fn new(cm: &'a CodeMap,
137+
out: Box<io::Writer>,
138+
ann: &'a PpAnn,
139+
comments: Option<Vec<comments::Comment>>,
140+
literals: Option<Vec<comments::Literal>>) -> State<'a> {
141+
State {
142+
s: pp::mk_printer(out, default_columns),
143+
cm: Some(cm),
144+
comments: comments,
145+
literals: literals,
146+
cur_cmnt_and_lit: CurrentCommentAndLiteral {
147+
cur_cmnt: 0,
148+
cur_lit: 0
149+
},
150+
boxes: Vec::new(),
151+
ann: ann
152+
}
153+
}
154+
}
155+
129156
pub fn to_string(f: |&mut State| -> IoResult<()>) -> String {
130157
let mut s = rust_printer(box MemWriter::new());
131158
f(&mut s).unwrap();
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
-include ../tools.mk
2+
3+
all:
4+
$(RUSTC) -o $(TMPDIR)/foo.out --pretty normal=foo input.rs
5+
$(RUSTC) -o $(TMPDIR)/nest_foo.out --pretty normal=nest::foo input.rs
6+
$(RUSTC) -o $(TMPDIR)/foo_method.out --pretty normal=foo_method input.rs
7+
diff -u $(TMPDIR)/foo.out foo.pp
8+
diff -u $(TMPDIR)/nest_foo.out nest_foo.pp
9+
diff -u $(TMPDIR)/foo_method.out foo_method.pp
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
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.
4+
//
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.
10+
11+
12+
pub fn foo() -> i32 { 45 } /* foo */
13+
14+
15+
pub fn foo() -> &'static str { "i am a foo." } /* nest::foo */

0 commit comments

Comments
 (0)