about summary refs log tree commit diff
diff options
context:
space:
mode:
authorbors <bors@rust-lang.org>2014-08-09 09:51:23 +0000
committerbors <bors@rust-lang.org>2014-08-09 09:51:23 +0000
commit87134c7d72d0a39f696051a22c05aa2b328a6d00 (patch)
tree64c50551faef0e4df76fd4b0c0e5ceba788851e3
parenta23d6795a50cf0b51d61d2b9d6d79127876796c1 (diff)
parentdb0e71f10a157c211863ac844ceb0572967df298 (diff)
downloadrust-87134c7d72d0a39f696051a22c05aa2b328a6d00.tar.gz
rust-87134c7d72d0a39f696051a22c05aa2b328a6d00.zip
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.)
-rw-r--r--src/librustc/driver/driver.rs349
-rw-r--r--src/librustc/driver/mod.rs45
-rw-r--r--src/libsyntax/ast_map/mod.rs162
-rw-r--r--src/libsyntax/print/pprust.rs75
-rw-r--r--src/test/run-make/pretty-print-path-suffix/Makefile9
-rw-r--r--src/test/run-make/pretty-print-path-suffix/foo.pp15
-rw-r--r--src/test/run-make/pretty-print-path-suffix/foo_method.pp16
-rw-r--r--src/test/run-make/pretty-print-path-suffix/input.rs28
-rw-r--r--src/test/run-make/pretty-print-path-suffix/nest_foo.pp14
9 files changed, 613 insertions, 100 deletions
diff --git a/src/librustc/driver/driver.rs b/src/librustc/driver/driver.rs
index 9796aab51fb..477fc5e1c0f 100644
--- a/src/librustc/driver/driver.rs
+++ b/src/librustc/driver/driver.rs
@@ -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>,
diff --git a/src/librustc/driver/mod.rs b/src/librustc/driver/mod.rs
index a5df63a9e23..05762aa3db2 100644
--- a/src/librustc/driver/mod.rs
+++ b/src/librustc/driver/mod.rs
@@ -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) ->
diff --git a/src/libsyntax/ast_map/mod.rs b/src/libsyntax/ast_map/mod.rs
index 67de8e7aba1..881ee4fd8d1 100644
--- a/src/libsyntax/ast_map/mod.rs
+++ b/src/libsyntax/ast_map/mod.rs
@@ -11,7 +11,7 @@
 use abi;
 use ast::*;
 use ast_util;
-use codemap::Span;
+use codemap::{Span, Spanned};
 use fold::Folder;
 use fold;
 use parse::token;
@@ -21,6 +21,7 @@ use util::small_vector::SmallVector;
 use std::cell::RefCell;
 use std::fmt;
 use std::gc::{Gc, GC};
+use std::io::IoResult;
 use std::iter;
 use std::slice;
 
@@ -203,6 +204,10 @@ pub struct Map {
 }
 
 impl Map {
+    fn entry_count(&self) -> uint {
+        self.map.borrow().len()
+    }
+
     fn find_entry(&self, id: NodeId) -> Option<MapEntry> {
         let map = self.map.borrow();
         if map.len() > id as uint {
@@ -405,6 +410,20 @@ impl Map {
         f(attrs)
     }
 
+    /// Returns an iterator that yields the node id's with paths that
+    /// match `parts`.  (Requires `parts` is non-empty.)
+    ///
+    /// For example, if given `parts` equal to `["bar", "quux"]`, then
+    /// the iterator will produce node id's for items with paths
+    /// such as `foo::bar::quux`, `bar::quux`, `other::bar::quux`, and
+    /// any other such items it can find in the map.
+    pub fn nodes_matching_suffix<'a, S:Str>(&'a self, parts: &'a [S]) -> NodesMatchingSuffix<'a,S> {
+        NodesMatchingSuffix { map: self,
+                              item_name: parts.last().unwrap(),
+                              where: parts.slice_to(parts.len() - 1),
+                              idx: 0 }
+    }
+
     pub fn opt_span(&self, id: NodeId) -> Option<Span> {
         let sp = match self.find(id) {
             Some(NodeItem(item)) => item.span,
@@ -438,6 +457,119 @@ impl Map {
     }
 }
 
+pub struct NodesMatchingSuffix<'a, S> {
+    map: &'a Map,
+    item_name: &'a S,
+    where: &'a [S],
+    idx: NodeId,
+}
+
+impl<'a,S:Str> NodesMatchingSuffix<'a,S> {
+    /// Returns true only if some suffix of the module path for parent
+    /// matches `self.where`.
+    ///
+    /// In other words: let `[x_0,x_1,...,x_k]` be `self.where`;
+    /// returns true if parent's path ends with the suffix
+    /// `x_0::x_1::...::x_k`.
+    fn suffix_matches(&self, parent: NodeId) -> bool {
+        let mut cursor = parent;
+        for part in self.where.iter().rev() {
+            let (mod_id, mod_name) = match find_first_mod_parent(self.map, cursor) {
+                None => return false,
+                Some((node_id, name)) => (node_id, name),
+            };
+            if part.as_slice() != mod_name.as_str() {
+                return false;
+            }
+            cursor = self.map.get_parent(mod_id);
+        }
+        return true;
+
+        // Finds the first mod in parent chain for `id`, along with
+        // that mod's name.
+        //
+        // If `id` itself is a mod named `m` with parent `p`, then
+        // returns `Some(id, m, p)`.  If `id` has no mod in its parent
+        // chain, then returns `None`.
+        fn find_first_mod_parent<'a>(map: &'a Map, mut id: NodeId) -> Option<(NodeId, Name)> {
+            loop {
+                match map.find(id) {
+                    None => return None,
+                    Some(NodeItem(item)) if item_is_mod(&*item) =>
+                        return Some((id, item.ident.name)),
+                    _ => {}
+                }
+                let parent = map.get_parent(id);
+                if parent == id { return None }
+                id = parent;
+            }
+
+            fn item_is_mod(item: &Item) -> bool {
+                match item.node {
+                    ItemMod(_) => true,
+                    _ => false,
+                }
+            }
+        }
+    }
+
+    // We are looking at some node `n` with a given name and parent
+    // id; do their names match what I am seeking?
+    fn matches_names(&self, parent_of_n: NodeId, name: Name) -> bool {
+        name.as_str() == self.item_name.as_slice() &&
+            self.suffix_matches(parent_of_n)
+    }
+}
+
+impl<'a,S:Str> Iterator<NodeId> for NodesMatchingSuffix<'a,S> {
+    fn next(&mut self) -> Option<NodeId> {
+        loop {
+            let idx = self.idx;
+            if idx as uint >= self.map.entry_count() {
+                return None;
+            }
+            self.idx += 1;
+            let (p, name) = match self.map.find_entry(idx) {
+                Some(EntryItem(p, n))        => (p, n.name()),
+                Some(EntryForeignItem(p, n)) => (p, n.name()),
+                Some(EntryTraitMethod(p, n)) => (p, n.name()),
+                Some(EntryMethod(p, n))      => (p, n.name()),
+                Some(EntryVariant(p, n))     => (p, n.name()),
+                _ => continue,
+            };
+            if self.matches_names(p, name) {
+                return Some(idx)
+            }
+        }
+    }
+}
+
+trait Named {
+    fn name(&self) -> Name;
+}
+
+impl<T:Named> Named for Spanned<T> { fn name(&self) -> Name { self.node.name() } }
+
+impl Named for Item { fn name(&self) -> Name { self.ident.name } }
+impl Named for ForeignItem { fn name(&self) -> Name { self.ident.name } }
+impl Named for Variant_ { fn name(&self) -> Name { self.name.name } }
+impl Named for TraitMethod {
+    fn name(&self) -> Name {
+        match *self {
+            Required(ref tm) => tm.ident.name,
+            Provided(m) => m.name(),
+        }
+    }
+}
+impl Named for Method {
+    fn name(&self) -> Name {
+        match self.node {
+            MethDecl(i, _, _, _, _, _, _, _) => i.name,
+            MethMac(_) => fail!("encountered unexpanded method macro."),
+        }
+    }
+}
+
 pub trait FoldOps {
     fn new_id(&self, id: NodeId) -> NodeId {
         id
@@ -688,6 +820,34 @@ pub fn map_decoded_item<F: FoldOps>(map: &Map,
     ii
 }
 
+pub trait NodePrinter {
+    fn print_node(&mut self, node: &Node) -> IoResult<()>;
+}
+
+impl<'a> NodePrinter for pprust::State<'a> {
+    fn print_node(&mut self, node: &Node) -> IoResult<()> {
+        match *node {
+            NodeItem(a)        => self.print_item(&*a),
+            NodeForeignItem(a) => self.print_foreign_item(&*a),
+            NodeTraitMethod(a) => self.print_trait_method(&*a),
+            NodeMethod(a)      => self.print_method(&*a),
+            NodeVariant(a)     => self.print_variant(&*a),
+            NodeExpr(a)        => self.print_expr(&*a),
+            NodeStmt(a)        => self.print_stmt(&*a),
+            NodePat(a)         => self.print_pat(&*a),
+            NodeBlock(a)       => self.print_block(&*a),
+            NodeLifetime(a)    => self.print_lifetime(&*a),
+
+            // these cases do not carry enough information in the
+            // ast_map to reconstruct their full structure for pretty
+            // printing.
+            NodeLocal(_)       => fail!("cannot print isolated Local"),
+            NodeArg(_)         => fail!("cannot print isolated Arg"),
+            NodeStructCtor(_)  => fail!("cannot print isolated StructCtor"),
+        }
+    }
+}
+
 fn node_id_to_string(map: &Map, id: NodeId) -> String {
     match map.find(id) {
         Some(NodeItem(item)) => {
diff --git a/src/libsyntax/print/pprust.rs b/src/libsyntax/print/pprust.rs
index d60e4cb3b54..9d4b7343c8a 100644
--- a/src/libsyntax/print/pprust.rs
+++ b/src/libsyntax/print/pprust.rs
@@ -97,35 +97,62 @@ pub fn print_crate<'a>(cm: &'a CodeMap,
                        out: Box<io::Writer>,
                        ann: &'a PpAnn,
                        is_expanded: bool) -> IoResult<()> {
-    let (cmnts, lits) = comments::gather_comments_and_literals(
-        span_diagnostic,
-        filename,
-        input
-    );
-    let mut s = State {
-        s: pp::mk_printer(out, default_columns),
-        cm: Some(cm),
-        comments: Some(cmnts),
-        // If the code is post expansion, don't use the table of
-        // literals, since it doesn't correspond with the literals
-        // in the AST anymore.
-        literals: if is_expanded {
-            None
-        } else {
-            Some(lits)
-        },
-        cur_cmnt_and_lit: CurrentCommentAndLiteral {
-            cur_cmnt: 0,
-            cur_lit: 0
-        },
-        boxes: Vec::new(),
-        ann: ann
-    };
+    let mut s = State::new_from_input(cm,
+                                      span_diagnostic,
+                                      filename,
+                                      input,
+                                      out,
+                                      ann,
+                                      is_expanded);
     try!(s.print_mod(&krate.module, krate.attrs.as_slice()));
     try!(s.print_remaining_comments());
     eof(&mut s.s)
 }
 
+impl<'a> State<'a> {
+    pub fn new_from_input(cm: &'a CodeMap,
+                          span_diagnostic: &diagnostic::SpanHandler,
+                          filename: String,
+                          input: &mut io::Reader,
+                          out: Box<io::Writer>,
+                          ann: &'a PpAnn,
+                          is_expanded: bool) -> State<'a> {
+        let (cmnts, lits) = comments::gather_comments_and_literals(
+            span_diagnostic,
+            filename,
+            input);
+
+        State::new(
+            cm,
+            out,
+            ann,
+            Some(cmnts),
+            // If the code is post expansion, don't use the table of
+            // literals, since it doesn't correspond with the literals
+            // in the AST anymore.
+            if is_expanded { None } else { Some(lits) })
+    }
+
+    pub fn new(cm: &'a CodeMap,
+               out: Box<io::Writer>,
+               ann: &'a PpAnn,
+               comments: Option<Vec<comments::Comment>>,
+               literals: Option<Vec<comments::Literal>>) -> State<'a> {
+        State {
+            s: pp::mk_printer(out, default_columns),
+            cm: Some(cm),
+            comments: comments,
+            literals: literals,
+            cur_cmnt_and_lit: CurrentCommentAndLiteral {
+                cur_cmnt: 0,
+                cur_lit: 0
+            },
+            boxes: Vec::new(),
+            ann: ann
+        }
+    }
+}
+
 pub fn to_string(f: |&mut State| -> IoResult<()>) -> String {
     let mut s = rust_printer(box MemWriter::new());
     f(&mut s).unwrap();
diff --git a/src/test/run-make/pretty-print-path-suffix/Makefile b/src/test/run-make/pretty-print-path-suffix/Makefile
new file mode 100644
index 00000000000..f58a6527ac6
--- /dev/null
+++ b/src/test/run-make/pretty-print-path-suffix/Makefile
@@ -0,0 +1,9 @@
+-include ../tools.mk
+
+all:
+	$(RUSTC) -o $(TMPDIR)/foo.out --pretty normal=foo input.rs
+	$(RUSTC) -o $(TMPDIR)/nest_foo.out --pretty normal=nest::foo input.rs
+	$(RUSTC) -o $(TMPDIR)/foo_method.out --pretty normal=foo_method input.rs
+	diff -u $(TMPDIR)/foo.out foo.pp
+	diff -u $(TMPDIR)/nest_foo.out nest_foo.pp
+	diff -u $(TMPDIR)/foo_method.out foo_method.pp
diff --git a/src/test/run-make/pretty-print-path-suffix/foo.pp b/src/test/run-make/pretty-print-path-suffix/foo.pp
new file mode 100644
index 00000000000..f3130a8044a
--- /dev/null
+++ b/src/test/run-make/pretty-print-path-suffix/foo.pp
@@ -0,0 +1,15 @@
+// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+
+pub fn foo() -> i32 { 45 } /* foo */
+
+
+pub fn foo() -> &'static str { "i am a foo." } /* nest::foo */
diff --git a/src/test/run-make/pretty-print-path-suffix/foo_method.pp b/src/test/run-make/pretty-print-path-suffix/foo_method.pp
new file mode 100644
index 00000000000..acf3f90cb0e
--- /dev/null
+++ b/src/test/run-make/pretty-print-path-suffix/foo_method.pp
@@ -0,0 +1,16 @@
+// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+
+
+
+
+fn foo_method(&self) -> &'static str { return "i am very similiar to foo."; }
+/* nest::S::foo_method */
diff --git a/src/test/run-make/pretty-print-path-suffix/input.rs b/src/test/run-make/pretty-print-path-suffix/input.rs
new file mode 100644
index 00000000000..4942540126b
--- /dev/null
+++ b/src/test/run-make/pretty-print-path-suffix/input.rs
@@ -0,0 +1,28 @@
+// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+#![crate_type="lib"]
+
+pub fn
+foo() -> i32
+{ 45 }
+
+pub fn bar() -> &'static str { "i am not a foo." }
+
+pub mod nest {
+    pub fn foo() -> &'static str { "i am a foo." }
+
+    struct S;
+    impl S {
+        fn foo_method(&self) -> &'static str {
+            return "i am very similiar to foo.";
+        }
+    }
+}
diff --git a/src/test/run-make/pretty-print-path-suffix/nest_foo.pp b/src/test/run-make/pretty-print-path-suffix/nest_foo.pp
new file mode 100644
index 00000000000..88eaa062b03
--- /dev/null
+++ b/src/test/run-make/pretty-print-path-suffix/nest_foo.pp
@@ -0,0 +1,14 @@
+// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
+// file at the top-level directory of this distribution and at
+// http://rust-lang.org/COPYRIGHT.
+//
+// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+
+
+
+pub fn foo() -> &'static str { "i am a foo." } /* nest::foo */