use hir::*;
use hir::intravisit::Visitor;
-use hir::print as pprust;
+use hir::print::Nested;
use arena::TypedArena;
use std::cell::RefCell;
pub fn node_to_user_string(&self, id: NodeId) -> String {
node_id_to_string(self, id, false)
}
+
+ pub fn node_to_pretty_string(&self, id: NodeId) -> String {
+ print::to_string(self, |s| s.print_node(self.get(id)))
+ }
}
pub struct NodesMatchingSuffix<'a, 'ast:'a> {
&ii.body
}
-pub trait NodePrinter {
- fn print_node(&mut self, node: &Node) -> io::Result<()>;
+/// Identical to the `PpAnn` implementation for `hir::Crate`,
+/// except it avoids creating a dependency on the whole crate.
+impl<'ast> print::PpAnn for Map<'ast> {
+ fn nested(&self, state: &mut print::State, nested: print::Nested) -> io::Result<()> {
+ match nested {
+ Nested::Item(id) => state.print_item(self.expect_item(id.id)),
+ Nested::TraitItem(id) => state.print_trait_item(self.trait_item(id)),
+ Nested::ImplItem(id) => state.print_impl_item(self.impl_item(id)),
+ Nested::Body(id) => state.print_expr(&self.body(id).value),
+ Nested::BodyArgPat(id, i) => state.print_pat(&self.body(id).arguments[i].pat)
+ }
+ }
}
-impl<'a> NodePrinter for pprust::State<'a> {
- fn print_node(&mut self, node: &Node) -> io::Result<()> {
- match *node {
+impl<'a> print::State<'a> {
+ pub fn print_node(&mut self, node: Node) -> io::Result<()> {
+ match node {
NodeItem(a) => self.print_item(&a),
NodeForeignItem(a) => self.print_foreign_item(&a),
NodeTraitItem(a) => self.print_trait_item(a),
NodeStmt(a) => self.print_stmt(&a),
NodeTy(a) => self.print_type(&a),
NodeTraitRef(a) => self.print_trait_ref(&a),
+ NodeLocal(a) |
NodePat(a) => self.print_pat(&a),
- NodeBlock(a) => self.print_block(&a),
+ NodeBlock(a) => {
+ use syntax::print::pprust::PrintState;
+
+ // containing cbox, will be closed by print-block at }
+ self.cbox(print::indent_unit)?;
+ // head-ibox, will be closed by print-block after {
+ self.ibox(0)?;
+ self.print_block(&a)
+ }
NodeLifetime(a) => self.print_lifetime(&a),
NodeVisibility(a) => self.print_visibility(&a),
NodeTyParam(_) => bug!("cannot print TyParam"),
// these cases do not carry enough information in the
// ast_map to reconstruct their full structure for pretty
// printing.
- NodeLocal(_) => bug!("cannot print isolated Local"),
NodeStructCtor(_) => bug!("cannot print isolated StructCtor"),
}
}
field.name,
path_str(), id_str)
}
- Some(NodeExpr(ref expr)) => {
- format!("expr {}{}", pprust::expr_to_string(&expr), id_str)
+ Some(NodeExpr(_)) => {
+ format!("expr {}{}", map.node_to_pretty_string(id), id_str)
}
- Some(NodeStmt(ref stmt)) => {
- format!("stmt {}{}", pprust::stmt_to_string(&stmt), id_str)
+ Some(NodeStmt(_)) => {
+ format!("stmt {}{}", map.node_to_pretty_string(id), id_str)
}
- Some(NodeTy(ref ty)) => {
- format!("type {}{}", pprust::ty_to_string(&ty), id_str)
+ Some(NodeTy(_)) => {
+ format!("type {}{}", map.node_to_pretty_string(id), id_str)
}
- Some(NodeTraitRef(ref tr)) => {
- format!("trait_ref {}{}", pprust::path_to_string(&tr.path), id_str)
+ Some(NodeTraitRef(_)) => {
+ format!("trait_ref {}{}", map.node_to_pretty_string(id), id_str)
}
- Some(NodeLocal(ref pat)) => {
- format!("local {}{}", pprust::pat_to_string(&pat), id_str)
+ Some(NodeLocal(_)) => {
+ format!("local {}{}", map.node_to_pretty_string(id), id_str)
}
- Some(NodePat(ref pat)) => {
- format!("pat {}{}", pprust::pat_to_string(&pat), id_str)
+ Some(NodePat(_)) => {
+ format!("pat {}{}", map.node_to_pretty_string(id), id_str)
}
- Some(NodeBlock(ref block)) => {
- format!("block {}{}", pprust::block_to_string(&block), id_str)
+ Some(NodeBlock(_)) => {
+ format!("block {}{}", map.node_to_pretty_string(id), id_str)
}
Some(NodeStructCtor(_)) => {
format!("struct_ctor {}{}", path_str(), id_str)
}
- Some(NodeLifetime(ref l)) => {
- format!("lifetime {}{}",
- pprust::lifetime_to_string(&l), id_str)
+ Some(NodeLifetime(_)) => {
+ format!("lifetime {}{}", map.node_to_pretty_string(id), id_str)
}
Some(NodeTyParam(ref ty_param)) => {
format!("typaram {:?}{}", ty_param, id_str)
write!(f,
"lifetime({}: {})",
self.id,
- print::lifetime_to_string(self))
+ print::to_string(print::NO_ANN, |s| s.print_lifetime(self)))
}
}
impl fmt::Debug for Path {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- write!(f, "path({})", print::path_to_string(self))
- }
-}
-
-impl fmt::Display for Path {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- write!(f, "{}", print::path_to_string(self))
+ write!(f, "path({})",
+ print::to_string(print::NO_ANN, |s| s.print_path(self, false)))
}
}
impl fmt::Debug for Pat {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- write!(f, "pat({}: {})", self.id, print::pat_to_string(self))
+ write!(f, "pat({}: {})", self.id,
+ print::to_string(print::NO_ANN, |s| s.print_pat(self)))
}
}
write!(f,
"stmt({}: {})",
spanned.node.id(),
- print::stmt_to_string(&spanned))
+ print::to_string(print::NO_ANN, |s| s.print_stmt(&spanned)))
}
}
impl fmt::Debug for Expr {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- write!(f, "expr({}: {})", self.id, print::expr_to_string(self))
+ write!(f, "expr({}: {})", self.id,
+ print::to_string(print::NO_ANN, |s| s.print_expr(self)))
}
}
TypeRelative(P<Ty>, P<PathSegment>)
}
-impl fmt::Display for QPath {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- write!(f, "{}", print::qpath_to_string(self))
- }
-}
-
/// Hints at the original code for a `match _ { .. }`
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
pub enum MatchSource {
impl fmt::Debug for Ty {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- write!(f, "type({})", print::ty_to_string(self))
+ write!(f, "type({})",
+ print::to_string(print::NO_ANN, |s| s.print_type(self)))
}
}
use syntax::abi::Abi;
use syntax::ast;
use syntax::codemap::{CodeMap, Spanned};
-use syntax::parse::token::{self, BinOpToken};
use syntax::parse::lexer::comments;
use syntax::print::pp::{self, break_offset, word, space, hardbreak};
use syntax::print::pp::{Breaks, eof};
use syntax::print::pp::Breaks::{Consistent, Inconsistent};
use syntax::print::pprust::{self as ast_pp, PrintState};
use syntax::ptr::P;
+use syntax::symbol::keywords;
use syntax_pos::{self, BytePos};
use errors;
use hir;
-use hir::{Crate, PatKind, RegionTyParamBound, TraitTyParamBound, TraitBoundModifier};
+use hir::{PatKind, RegionTyParamBound, TraitTyParamBound, TraitBoundModifier};
use std::io::{self, Write, Read};
NodePat(&'a hir::Pat),
}
+pub enum Nested {
+ Item(hir::ItemId),
+ TraitItem(hir::TraitItemId),
+ ImplItem(hir::ImplItemId),
+ Body(hir::BodyId),
+ BodyArgPat(hir::BodyId, usize)
+}
+
pub trait PpAnn {
+ fn nested(&self, _state: &mut State, _nested: Nested) -> io::Result<()> {
+ Ok(())
+ }
fn pre(&self, _state: &mut State, _node: AnnNode) -> io::Result<()> {
Ok(())
}
}
}
-#[derive(Copy, Clone)]
pub struct NoAnn;
-
impl PpAnn for NoAnn {}
+pub const NO_ANN: &'static PpAnn = &NoAnn;
+impl PpAnn for hir::Crate {
+ fn nested(&self, state: &mut State, nested: Nested) -> io::Result<()> {
+ match nested {
+ Nested::Item(id) => state.print_item(self.item(id.id)),
+ Nested::TraitItem(id) => state.print_trait_item(self.trait_item(id)),
+ Nested::ImplItem(id) => state.print_impl_item(self.impl_item(id)),
+ Nested::Body(id) => state.print_expr(&self.body(id).value),
+ Nested::BodyArgPat(id, i) => state.print_pat(&self.body(id).arguments[i].pat)
+ }
+ }
+}
pub struct State<'a> {
- krate: Option<&'a Crate>,
pub s: pp::Printer<'a>,
cm: Option<&'a CodeMap>,
comments: Option<Vec<comments::Comment>>,
}
}
-pub fn rust_printer<'a>(writer: Box<Write + 'a>, krate: Option<&'a Crate>) -> State<'a> {
- static NO_ANN: NoAnn = NoAnn;
- rust_printer_annotated(writer, &NO_ANN, krate)
-}
-
-pub fn rust_printer_annotated<'a>(writer: Box<Write + 'a>,
- ann: &'a PpAnn,
- krate: Option<&'a Crate>)
- -> State<'a> {
- State {
- krate: krate,
- s: pp::mk_printer(writer, default_columns),
- cm: None,
- comments: None,
- literals: None,
- cur_cmnt_and_lit: ast_pp::CurrentCommentAndLiteral {
- cur_cmnt: 0,
- cur_lit: 0,
- },
- boxes: Vec::new(),
- ann: ann,
- }
-}
-
#[allow(non_upper_case_globals)]
pub const indent_unit: usize = 4;
is_expanded: bool)
-> io::Result<()> {
let mut s = State::new_from_input(cm, span_diagnostic, filename, input,
- out, ann, is_expanded, Some(krate));
+ out, ann, is_expanded);
// When printing the AST, we sometimes need to inject `#[no_std]` here.
// Since you can't compile the HIR, it's not necessary.
input: &mut Read,
out: Box<Write + 'a>,
ann: &'a PpAnn,
- is_expanded: bool,
- krate: Option<&'a Crate>)
+ is_expanded: bool)
-> State<'a> {
let (cmnts, lits) = comments::gather_comments_and_literals(span_diagnostic,
filename,
None
} else {
Some(lits)
- },
- krate)
+ })
}
pub fn new(cm: &'a CodeMap,
out: Box<Write + 'a>,
ann: &'a PpAnn,
comments: Option<Vec<comments::Comment>>,
- literals: Option<Vec<comments::Literal>>,
- krate: Option<&'a Crate>)
+ literals: Option<Vec<comments::Literal>>)
-> State<'a> {
State {
- krate: krate,
s: pp::mk_printer(out, default_columns),
cm: Some(cm),
comments: comments.clone(),
}
}
-pub fn to_string<F>(f: F) -> String
+pub fn to_string<F>(ann: &PpAnn, f: F) -> String
where F: FnOnce(&mut State) -> io::Result<()>
{
let mut wr = Vec::new();
{
- let mut printer = rust_printer(Box::new(&mut wr), None);
+ let mut printer = State {
+ s: pp::mk_printer(Box::new(&mut wr), default_columns),
+ cm: None,
+ comments: None,
+ literals: None,
+ cur_cmnt_and_lit: ast_pp::CurrentCommentAndLiteral {
+ cur_cmnt: 0,
+ cur_lit: 0,
+ },
+ boxes: Vec::new(),
+ ann: ann,
+ };
f(&mut printer).unwrap();
eof(&mut printer.s).unwrap();
}
String::from_utf8(wr).unwrap()
}
-pub fn binop_to_string(op: BinOpToken) -> &'static str {
- match op {
- token::Plus => "+",
- token::Minus => "-",
- token::Star => "*",
- token::Slash => "/",
- token::Percent => "%",
- token::Caret => "^",
- token::And => "&",
- token::Or => "|",
- token::Shl => "<<",
- token::Shr => ">>",
- }
-}
-
-pub fn ty_to_string(ty: &hir::Ty) -> String {
- to_string(|s| s.print_type(ty))
-}
-
-pub fn bounds_to_string(bounds: &[hir::TyParamBound]) -> String {
- to_string(|s| s.print_bounds("", bounds))
-}
-
-pub fn pat_to_string(pat: &hir::Pat) -> String {
- to_string(|s| s.print_pat(pat))
-}
-
-pub fn arm_to_string(arm: &hir::Arm) -> String {
- to_string(|s| s.print_arm(arm))
-}
-
-pub fn expr_to_string(e: &hir::Expr) -> String {
- to_string(|s| s.print_expr(e))
-}
-
-pub fn lifetime_to_string(e: &hir::Lifetime) -> String {
- to_string(|s| s.print_lifetime(e))
-}
-
-pub fn stmt_to_string(stmt: &hir::Stmt) -> String {
- to_string(|s| s.print_stmt(stmt))
-}
-
-pub fn item_to_string(i: &hir::Item) -> String {
- to_string(|s| s.print_item(i))
-}
-
-pub fn impl_item_to_string(i: &hir::ImplItem) -> String {
- to_string(|s| s.print_impl_item(i))
-}
-
-pub fn trait_item_to_string(i: &hir::TraitItem) -> String {
- to_string(|s| s.print_trait_item(i))
-}
-
-pub fn generics_to_string(generics: &hir::Generics) -> String {
- to_string(|s| s.print_generics(generics))
-}
-
-pub fn where_clause_to_string(i: &hir::WhereClause) -> String {
- to_string(|s| s.print_where_clause(i))
-}
-
-pub fn path_to_string(p: &hir::Path) -> String {
- to_string(|s| s.print_path(p, false))
-}
-
-pub fn qpath_to_string(p: &hir::QPath) -> String {
- to_string(|s| s.print_qpath(p, false))
-}
-
-pub fn name_to_string(name: ast::Name) -> String {
- to_string(|s| s.print_name(name))
-}
-
-pub fn fn_decl_in_crate_to_string(krate: &hir::Crate,
- decl: &hir::FnDecl,
- unsafety: hir::Unsafety,
- constness: hir::Constness,
- name: ast::Name,
- generics: &hir::Generics,
- body_id: hir::BodyId)
- -> String {
-
- let mut wr = Vec::new();
- {
- let mut s = rust_printer(Box::new(&mut wr), Some(krate));
- (|s: &mut State| {
- s.head("")?;
- s.print_fn(decl,
- unsafety,
- constness,
- Abi::Rust,
- Some(name),
- generics,
- &hir::Inherited,
- &[],
- Some(body_id))?;
- s.end()?; // Close the head box
- s.end()?; // Close the outer box
- eof(&mut s.s)
- })(&mut s).unwrap();
- }
- String::from_utf8(wr).unwrap()
-}
-
-pub fn block_to_string(blk: &hir::Block) -> String {
- to_string(|s| {
- // containing cbox, will be closed by print-block at }
- s.cbox(indent_unit)?;
- // head-ibox, will be closed by print-block after {
- s.ibox(0)?;
- s.print_block(blk)
+pub fn visibility_qualified(vis: &hir::Visibility, w: &str) -> String {
+ to_string(NO_ANN, |s| {
+ s.print_visibility(vis)?;
+ word(&mut s.s, w)
})
}
-pub fn variant_to_string(var: &hir::Variant) -> String {
- to_string(|s| s.print_variant(var))
-}
-
-pub fn visibility_qualified(vis: &hir::Visibility, s: &str) -> String {
- match *vis {
- hir::Public => format!("pub {}", s),
- hir::Visibility::Crate => format!("pub(crate) {}", s),
- hir::Visibility::Restricted { ref path, .. } => format!("pub({}) {}", path, s),
- hir::Inherited => s.to_string(),
- }
-}
-
fn needs_parentheses(expr: &hir::Expr) -> bool {
match expr.node {
hir::ExprAssign(..) |
pub fn print_mod(&mut self, _mod: &hir::Mod, attrs: &[ast::Attribute]) -> io::Result<()> {
self.print_inner_attributes(attrs)?;
for &item_id in &_mod.item_ids {
- self.print_item_id(item_id)?;
+ self.ann.nested(self, Nested::Item(item_id))?;
}
Ok(())
}
word(&mut self.s, "[")?;
self.print_type(&ty)?;
word(&mut self.s, "; ")?;
- self.print_body_id(v)?;
+ self.ann.nested(self, Nested::Body(v))?;
word(&mut self.s, "]")?;
}
hir::TyTypeof(e) => {
word(&mut self.s, "typeof(")?;
- self.print_body_id(e)?;
+ self.ann.nested(self, Nested::Body(e))?;
word(&mut self.s, ")")?;
}
hir::TyInfer => {
if let Some(expr) = default {
space(&mut self.s)?;
self.word_space("=")?;
- self.print_body_id(expr)?;
+ self.ann.nested(self, Nested::Body(expr))?;
}
word(&mut self.s, ";")
}
word(&mut self.s, ";")
}
- pub fn print_item_id(&mut self, item_id: hir::ItemId) -> io::Result<()> {
- if let Some(krate) = self.krate {
- // skip nested items if krate context was not provided
- let item = &krate.items[&item_id.id];
- self.print_item(item)
- } else {
- Ok(())
- }
- }
-
- fn maybe_body(&mut self, body_id: hir::BodyId) -> Option<&'a hir::Body> {
- self.krate.map(|krate| krate.body(body_id))
- }
-
- fn print_body_id(&mut self, body_id: hir::BodyId) -> io::Result<()> {
- self.maybe_body(body_id).map_or(Ok(()), |body| {
- self.print_expr(&body.value)
- })
- }
-
/// Pretty-print an item
pub fn print_item(&mut self, item: &hir::Item) -> io::Result<()> {
self.hardbreak_if_not_bol()?;
self.end()?; // end the head-ibox
self.word_space("=")?;
- self.print_body_id(expr)?;
+ self.ann.nested(self, Nested::Body(expr))?;
word(&mut self.s, ";")?;
self.end()?; // end the outer cbox
}
self.end()?; // end the head-ibox
self.word_space("=")?;
- self.print_body_id(expr)?;
+ self.ann.nested(self, Nested::Body(expr))?;
word(&mut self.s, ";")?;
self.end()?; // end the outer cbox
}
word(&mut self.s, " ")?;
self.end()?; // need to close a box
self.end()?; // need to close a box
- self.print_body_id(body)?;
+ self.ann.nested(self, Nested::Body(body))?;
}
hir::ItemMod(ref _mod) => {
self.head(&visibility_qualified(&item.vis, "mod"))?;
self.bopen()?;
self.print_inner_attributes(&item.attrs)?;
for impl_item in impl_items {
- self.print_impl_item_ref(impl_item)?;
+ self.ann.nested(self, Nested::ImplItem(impl_item.id))?;
}
self.bclose(item.span)?;
}
word(&mut self.s, " ")?;
self.bopen()?;
for trait_item in trait_items {
- self.print_trait_item_ref(trait_item)?;
+ self.ann.nested(self, Nested::TraitItem(trait_item.id))?;
}
self.bclose(item.span)?;
}
match *vis {
hir::Public => self.word_nbsp("pub"),
hir::Visibility::Crate => self.word_nbsp("pub(crate)"),
- hir::Visibility::Restricted { ref path, .. } =>
- self.word_nbsp(&format!("pub({})", path)),
+ hir::Visibility::Restricted { ref path, .. } => {
+ word(&mut self.s, "pub(")?;
+ self.print_path(path, false)?;
+ self.word_nbsp(")")
+ }
hir::Inherited => Ok(()),
}
}
if let Some(d) = v.node.disr_expr {
space(&mut self.s)?;
self.word_space("=")?;
- self.print_body_id(d)?;
+ self.ann.nested(self, Nested::Body(d))?;
}
Ok(())
}
body_id)
}
- pub fn print_trait_item_ref(&mut self, item_ref: &hir::TraitItemRef) -> io::Result<()> {
- if let Some(krate) = self.krate {
- // skip nested items if krate context was not provided
- let item = &krate.trait_item(item_ref.id);
- self.print_trait_item(item)
- } else {
- Ok(())
- }
- }
-
pub fn print_trait_item(&mut self, ti: &hir::TraitItem) -> io::Result<()> {
self.ann.pre(self, NodeSubItem(ti.id))?;
self.hardbreak_if_not_bol()?;
self.nbsp()?;
self.end()?; // need to close a box
self.end()?; // need to close a box
- self.print_body_id(body)?;
+ self.ann.nested(self, Nested::Body(body))?;
}
hir::TraitItemKind::Type(ref bounds, ref default) => {
self.print_associated_type(ti.name,
self.ann.post(self, NodeSubItem(ti.id))
}
- pub fn print_impl_item_ref(&mut self, item_ref: &hir::ImplItemRef) -> io::Result<()> {
- if let Some(krate) = self.krate {
- // skip nested items if krate context was not provided
- let item = &krate.impl_item(item_ref.id);
- self.print_impl_item(item)
- } else {
- Ok(())
- }
- }
-
pub fn print_impl_item(&mut self, ii: &hir::ImplItem) -> io::Result<()> {
self.ann.pre(self, NodeSubItem(ii.id))?;
self.hardbreak_if_not_bol()?;
self.nbsp()?;
self.end()?; // need to close a box
self.end()?; // need to close a box
- self.print_body_id(body)?;
+ self.ann.nested(self, Nested::Body(body))?;
}
hir::ImplItemKind::Type(ref ty) => {
self.print_associated_type(ii.name, None, Some(ty))?;
word(&mut self.s, "[")?;
self.print_expr(element)?;
self.word_space(";")?;
- self.print_body_id(count)?;
+ self.ann.nested(self, Nested::Body(count))?;
word(&mut self.s, "]")?;
self.end()
}
space(&mut self.s)?;
// this is a bare expression
- self.print_body_id(body)?;
+ self.ann.nested(self, Nested::Body(body))?;
self.end()?; // need to close a box
// a box will be closed by print_expr, but we didn't want an overall
self.end()
}
hir::DeclItem(item) => {
- self.print_item_id(item)
+ self.ann.nested(self, Nested::Item(item))
}
}
}
self.print_expr(coll)
}
- fn print_path(&mut self,
- path: &hir::Path,
- colons_before_params: bool)
- -> io::Result<()> {
+ pub fn print_path(&mut self,
+ path: &hir::Path,
+ colons_before_params: bool)
+ -> io::Result<()> {
self.maybe_print_comment(path.span.lo)?;
for (i, segment) in path.segments.iter().enumerate() {
Ok(())
}
- fn print_qpath(&mut self,
- qpath: &hir::QPath,
- colons_before_params: bool)
- -> io::Result<()> {
+ pub fn print_qpath(&mut self,
+ qpath: &hir::QPath,
+ colons_before_params: bool)
+ -> io::Result<()> {
match *qpath {
hir::QPath::Resolved(None, ref path) => {
self.print_path(path, colons_before_params)
let mut i = 0;
// Make sure we aren't supplied *both* `arg_names` and `body_id`.
assert!(arg_names.is_empty() || body_id.is_none());
- let args = body_id.and_then(|body_id| self.maybe_body(body_id))
- .map_or(&[][..], |body| &body.arguments[..]);
self.commasep(Inconsistent, &decl.inputs, |s, ty| {
s.ibox(indent_unit)?;
if let Some(name) = arg_names.get(i) {
word(&mut s.s, &name.node.as_str())?;
word(&mut s.s, ":")?;
space(&mut s.s)?;
- } else if let Some(arg) = args.get(i) {
- s.print_pat(&arg.pat)?;
+ } else if let Some(body_id) = body_id {
+ s.ann.nested(s, Nested::BodyArgPat(body_id, i))?;
word(&mut s.s, ":")?;
space(&mut s.s)?;
}
fn print_closure_args(&mut self, decl: &hir::FnDecl, body_id: hir::BodyId) -> io::Result<()> {
word(&mut self.s, "|")?;
let mut i = 0;
- let args = self.maybe_body(body_id).map_or(&[][..], |body| &body.arguments[..]);
self.commasep(Inconsistent, &decl.inputs, |s, ty| {
s.ibox(indent_unit)?;
- if let Some(arg) = args.get(i) {
- s.print_pat(&arg.pat)?;
- } else {
- word(&mut s.s, "_")?;
- }
+ s.ann.nested(s, Nested::BodyArgPat(body_id, i))?;
i += 1;
if ty.node != hir::TyInfer {
use hir::map as ast_map;
use hir;
-use hir::print as pprust;
use lint;
use hir::def::Def;
generics: &hir::Generics,
span: Span,
body: hir::BodyId) {
- let s = pprust::fn_decl_in_crate_to_string(self.tcx.map.krate(),
- decl,
- unsafety,
- constness,
- name,
- generics,
- body);
+ let s = hir::print::to_string(&self.tcx.map, |s| {
+ use syntax::abi::Abi;
+ use syntax::print::pprust::PrintState;
+
+ s.head("")?;
+ s.print_fn(decl,
+ unsafety,
+ constness,
+ Abi::Rust,
+ Some(name),
+ generics,
+ &hir::Inherited,
+ &[],
+ Some(body))?;
+ s.end()?; // Close the head box
+ s.end() // Close the outer box
+ });
let msg = format!("consider using an explicit lifetime parameter as shown: {}", s);
err.span_help(span, &msg[..]);
}
}
impl<'a, 'tcx, O:DataFlowOperator> pprust::PpAnn for DataFlowContext<'a, 'tcx, O> {
+ fn nested(&self, state: &mut pprust::State, nested: pprust::Nested) -> io::Result<()> {
+ pprust::PpAnn::nested(&self.tcx.map, state, nested)
+ }
fn pre(&self,
ps: &mut pprust::State,
node: pprust::AnnNode) -> io::Result<()> {
}
debug!("Dataflow result for {}:", self.analysis_name);
- debug!("{}", {
- let mut v = Vec::new();
- self.pretty_print_to(box &mut v, body).unwrap();
- String::from_utf8(v).unwrap()
- });
- }
-
- fn pretty_print_to<'b>(&self, wr: Box<io::Write + 'b>,
- body: &hir::Body) -> io::Result<()> {
- let mut ps = pprust::rust_printer_annotated(wr, self, None);
- ps.cbox(pprust::indent_unit)?;
- ps.ibox(0)?;
- ps.print_expr(&body.value)?;
- pp::eof(&mut ps.s)
+ debug!("{}", pprust::to_string(self, |s| {
+ s.cbox(pprust::indent_unit)?;
+ s.ibox(0)?;
+ s.print_expr(&body.value)
+ }));
}
}
use hir::Expr;
use hir;
-use hir::print::{expr_to_string, block_to_string};
use hir::intravisit::{self, Visitor, FnKind, NestedVisitorMap};
/// For use with `propagate_through_loop`.
// effectively a return---this only occurs in `for` loops,
// where the body is really a closure.
- debug!("compute: using id for body, {}", expr_to_string(body));
+ debug!("compute: using id for body, {}", self.ir.tcx.map.node_to_pretty_string(body.id));
let exit_ln = self.s.exit_ln;
let entry_ln: LiveNode = self.with_loop_nodes(body.id, exit_ln, exit_ln, |this| {
fn propagate_through_expr(&mut self, expr: &Expr, succ: LiveNode)
-> LiveNode {
- debug!("propagate_through_expr: {}", expr_to_string(expr));
+ debug!("propagate_through_expr: {}", self.ir.tcx.map.node_to_pretty_string(expr.id));
match expr.node {
// Interesting cases with control flow or which gen/kill
hir::ExprClosure(.., blk_id, _) => {
debug!("{} is an ExprClosure",
- expr_to_string(expr));
+ self.ir.tcx.map.node_to_pretty_string(expr.id));
/*
The next-node for a break is the successor of the entire
}
}
debug!("propagate_through_loop: using id for loop body {} {}",
- expr.id, block_to_string(body));
+ expr.id, self.ir.tcx.map.node_to_pretty_string(body.id));
let cond_ln = match kind {
LoopLoop => ln,
use rustc_data_structures::fx::FxHashSet;
use hir;
-use hir::print::lifetime_to_string;
use hir::intravisit::{self, Visitor, FnKind, NestedVisitorMap};
#[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug)]
probably a bug in syntax::fold");
}
- debug!("lifetime_ref={:?} id={:?} resolved to {:?} span={:?}",
- lifetime_to_string(lifetime_ref),
- lifetime_ref.id,
+ debug!("{} resolved to {:?} span={:?}",
+ self.hir_map.node_to_string(lifetime_ref.id),
def,
self.sess.codemap().span_to_string(lifetime_ref.span));
self.map.defs.insert(lifetime_ref.id, def);
use rustc::hir::def::*;
use rustc::hir::intravisit::{self, Visitor, FnKind, NestedVisitorMap};
-use rustc::hir::print::pat_to_string;
use rustc::hir::{self, Pat, PatKind};
use rustc_back::slice;
Useful => bug!()
};
- let pattern_string = pat_to_string(witness[0].single_pattern());
+ let pattern_string = hir::print::to_string(&self.tcx.map, |s| {
+ s.print_pat(witness[0].single_pattern())
+ });
let mut diag = struct_span_err!(
self.tcx.sess, pat.span, E0005,
"refutable pattern in {}: `{}` not covered",
},
_ => bug!(),
};
- let pattern_string = pat_to_string(witness);
+ let pattern_string = hir::print::to_string(&cx.tcx.map, |s| {
+ s.print_pat(witness)
+ });
struct_span_err!(cx.tcx.sess, sp, E0297,
"refutable pattern in `for` loop binding: \
`{}` not covered",
},
_ => {
let pattern_strings: Vec<_> = witnesses.iter().map(|w| {
- pat_to_string(w)
+ hir::print::to_string(&cx.tcx.map, |s| s.print_pat(w))
}).collect();
const LIMIT: usize = 3;
let joined_patterns = match pattern_strings.len() {
if let hir::ExprPath(hir::QPath::Resolved(None, ref path)) = count_expr.node {
if let Def::Local(..) = path.def {
- diag.note(&format!("`{}` is a variable", path));
+ diag.note(&format!("`{}` is a variable",
+ tcx.map.node_to_pretty_string(count_expr.id)));
}
}
use std::str::FromStr;
use rustc::hir::map as hir_map;
-use rustc::hir::map::{blocks, NodePrinter};
+use rustc::hir::map::blocks;
use rustc::hir;
use rustc::hir::print as pprust_hir;
}
impl<'ast> pprust::PpAnn for NoAnn<'ast> {}
-impl<'ast> pprust_hir::PpAnn for NoAnn<'ast> {}
+impl<'ast> pprust_hir::PpAnn for NoAnn<'ast> {
+ fn nested(&self, state: &mut pprust_hir::State, nested: pprust_hir::Nested)
+ -> io::Result<()> {
+ if let Some(ref map) = self.ast_map {
+ pprust_hir::PpAnn::nested(map, state, nested)
+ } else {
+ Ok(())
+ }
+ }
+}
struct IdentifiedAnnotation<'ast> {
sess: &'ast Session,
}
impl<'ast> pprust_hir::PpAnn for IdentifiedAnnotation<'ast> {
+ fn nested(&self, state: &mut pprust_hir::State, nested: pprust_hir::Nested)
+ -> io::Result<()> {
+ if let Some(ref map) = self.ast_map {
+ pprust_hir::PpAnn::nested(map, state, nested)
+ } else {
+ Ok(())
+ }
+ }
fn pre(&self, s: &mut pprust_hir::State, node: pprust_hir::AnnNode) -> io::Result<()> {
match node {
pprust_hir::NodeExpr(_) => s.popen(),
}
impl<'a, 'tcx> pprust_hir::PpAnn for TypedAnnotation<'a, 'tcx> {
+ fn nested(&self, state: &mut pprust_hir::State, nested: pprust_hir::Nested)
+ -> io::Result<()> {
+ pprust_hir::PpAnn::nested(&self.tcx.map, state, nested)
+ }
fn pre(&self, s: &mut pprust_hir::State, node: pprust_hir::AnnNode) -> io::Result<()> {
match node {
pprust_hir::NodeExpr(_) => s.popen(),
&mut rdr,
box out,
annotation.pp_ann(),
- true,
- Some(ast_map.krate()));
+ true);
for node_id in uii.all_matching_node_ids(ast_map) {
let node = ast_map.get(node_id);
- pp_state.print_node(&node)?;
+ pp_state.print_node(node)?;
pp::space(&mut pp_state.s)?;
let path = annotation.node_path(node_id)
.expect("--unpretty missing node paths");
match item.node {
hir::ItemImpl(.., ref ty, _) => {
let mut result = String::from("<");
- result.push_str(&rustc::hir::print::ty_to_string(&ty));
+ result.push_str(&self.tcx.map.node_to_pretty_string(ty.id));
let trait_id = self.tcx.trait_id_of_impl(impl_id);
let mut decl_id = None;
use hir;
use hir::def::Def;
use hir::def_id::DefId;
-use hir::print as pprust;
use middle::resolve_lifetime as rl;
use rustc::lint;
use rustc::ty::subst::{Kind, Subst, Substs};
let help_name = if let Some(body) = parent {
let arg = &tcx.map.body(body).arguments[index];
- format!("`{}`", pprust::pat_to_string(&arg.pat))
+ format!("`{}`", tcx.map.node_to_pretty_string(arg.pat.id))
} else {
format!("argument {}", index + 1)
};
}
_ => {
span_fatal!(self.tcx().sess, path.span, E0245, "`{}` is not a trait",
- path);
+ self.tcx().map.node_to_pretty_string(trait_ref.ref_id));
}
}
}
let mut err = struct_span_err!(tcx.sess, ty.span, E0178,
"expected a path on the left-hand side \
of `+`, not `{}`",
- pprust::ty_to_string(ty));
+ tcx.map.node_to_pretty_string(ty.id));
err.span_label(ty.span, &format!("expected a path"));
let hi = bounds.iter().map(|x| match *x {
hir::TraitTyParamBound(ref tr, _) => tr.span.hi,
expn_id: ty.span.expn_id,
});
match (&ty.node, full_span) {
- (&hir::TyRptr(None, ref mut_ty), Some(full_span)) => {
- let mutbl_str = if mut_ty.mutbl == hir::MutMutable { "mut " } else { "" };
+ (&hir::TyRptr(ref lifetime, ref mut_ty), Some(full_span)) => {
+ let ty_str = hir::print::to_string(&tcx.map, |s| {
+ use syntax::print::pp::word;
+ use syntax::print::pprust::PrintState;
+
+ word(&mut s.s, "&")?;
+ s.print_opt_lifetime(lifetime)?;
+ s.print_mutability(mut_ty.mutbl)?;
+ s.popen()?;
+ s.print_type(&mut_ty.ty)?;
+ s.print_bounds(" +", bounds)?;
+ s.pclose()
+ });
err.span_suggestion(full_span, "try adding parentheses (per RFC 438):",
- format!("&{}({} +{})",
- mutbl_str,
- pprust::ty_to_string(&mut_ty.ty),
- pprust::bounds_to_string(bounds)));
- }
- (&hir::TyRptr(Some(ref lt), ref mut_ty), Some(full_span)) => {
- let mutbl_str = if mut_ty.mutbl == hir::MutMutable { "mut " } else { "" };
- err.span_suggestion(full_span, "try adding parentheses (per RFC 438):",
- format!("&{} {}({} +{})",
- pprust::lifetime_to_string(lt),
- mutbl_str,
- pprust::ty_to_string(&mut_ty.ty),
- pprust::bounds_to_string(bounds)));
+ ty_str);
}
_ => {
let report_unexpected_def = |def: Def| {
span_err!(tcx.sess, pat.span, E0533,
"expected unit struct/variant or constant, found {} `{}`",
- def.kind_name(), qpath);
+ def.kind_name(),
+ hir::print::to_string(&tcx.map, |s| s.print_qpath(qpath, false)));
};
// Resolve the path and check the definition for errors.
};
let report_unexpected_def = |def: Def| {
let msg = format!("expected tuple struct/variant, found {} `{}`",
- def.kind_name(), qpath);
+ def.kind_name(),
+ hir::print::to_string(&tcx.map, |s| s.print_qpath(qpath, false)));
struct_span_err!(tcx.sess, pat.span, E0164, "{}", msg)
.span_label(pat.span, &format!("not a tuple variant or struct")).emit();
on_error();
use CrateCtxt;
use hir::def::Def;
use hir::def_id::{DefId, LOCAL_CRATE};
-use hir::print;
use rustc::{infer, traits};
use rustc::ty::{self, LvaluePreference, Ty};
use syntax::symbol::Symbol;
if let &ty::TyAdt(adt_def, ..) = t {
if adt_def.is_enum() {
if let hir::ExprCall(ref expr, _) = call_expr.node {
- unit_variant = Some(print::expr_to_string(expr))
+ unit_variant = Some(self.tcx.map.node_to_pretty_string(expr.id))
}
}
}
use errors::DiagnosticBuilder;
use syntax_pos::Span;
-use rustc::hir::print as pprust;
use rustc::hir;
use rustc::infer::type_variable::TypeVariableOrigin;
let msg = if let Some(callee) = rcvr_expr {
format!("{}; use overloaded call notation instead (e.g., `{}()`)",
msg,
- pprust::expr_to_string(callee))
+ self.tcx.map.node_to_pretty_string(callee.id))
} else {
msg
};
use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
use rustc::hir::itemlikevisit::ItemLikeVisitor;
use rustc::hir::{self, PatKind};
-use rustc::hir::print as pprust;
use rustc::middle::lang_items;
use rustc_back::slice;
use rustc_const_eval::eval_length;
}
ty::TyRawPtr(..) => {
err.note(&format!("`{0}` is a native pointer; perhaps you need to deref with \
- `(*{0}).{1}`", pprust::expr_to_string(base), field.node));
+ `(*{0}).{1}`",
+ self.tcx.map.node_to_pretty_string(base.id),
+ field.node));
}
_ => {}
}
self.diverges.set(self.diverges.get() | old_diverges);
self.has_errors.set(self.has_errors.get() | old_has_errors);
- debug!("type of expr({}) {} is...", expr.id,
- pprust::expr_to_string(expr));
- debug!("... {:?}, expected is {:?}",
- ty,
- expected);
+ debug!("type of {} is...", self.tcx.map.node_to_string(expr.id));
+ debug!("... {:?}, expected is {:?}", ty, expected);
// Add adjustments to !-expressions
if ty.is_never() {
use syntax::ast;
use syntax_pos::Span;
-use rustc::hir::print::pat_to_string;
use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
use rustc::hir;
self.visit_node_id(ResolvingPattern(p.span), p.id);
debug!("Type for pattern binding {} (id {}) resolved to {:?}",
- pat_to_string(p),
+ self.tcx().map.node_to_pretty_string(p.id),
p.id,
self.tcx().tables().node_id_to_type(p.id));
the crate they're defined in; define a new trait instead")
.span_label(item_trait_ref.path.span,
&format!("`{}` trait not defined in this crate",
- item_trait_ref.path))
+ self.tcx.map.node_to_pretty_string(item_trait_ref.ref_id)))
.emit();
return;
}
use syntax::symbol::{Symbol, keywords};
use syntax_pos::Span;
-use rustc::hir::{self, map as hir_map, print as pprust};
+use rustc::hir::{self, map as hir_map};
use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
use rustc::hir::def::{Def, CtorKind};
use rustc::hir::def_id::DefId;
fn evaluate_disr_expr(ccx: &CrateCtxt, repr_ty: attr::IntType, e: &hir::Expr)
-> Option<ty::Disr> {
- debug!("disr expr, checking {}", pprust::expr_to_string(e));
+ debug!("disr expr, checking {}", ccx.tcx.map.node_to_pretty_string(e.id));
let ty_hint = repr_ty.to_ty(ccx.tcx);
let print_err = |cv: ConstVal| {
ccx.tcx.sess.struct_span_err(ast_ty.span,
&format!("use of SIMD type `{}` in FFI is highly experimental and \
may result in invalid code",
- pprust::ty_to_string(ast_ty)))
+ ccx.tcx.map.node_to_pretty_string(ast_ty.id)))
.help("add #![feature(simd_ffi)] to the crate attributes to enable")
.emit();
}
use rustc::hir::def::{Def, CtorKind};
use rustc::hir::def_id::DefId;
-use rustc::hir::print as pprust;
use rustc::ty;
use rustc::util::nodemap::FxHashSet;
match item.kind {
ty::AssociatedKind::Const => {
let default = if item.defaultness.has_value() {
- Some(pprust::expr_to_string(
- &tcx.sess.cstore.maybe_get_item_body(tcx, item.def_id).unwrap().value))
+ Some(hir::print::to_string(&cx.tcx.map, |s| s.print_expr(
+ &tcx.sess.cstore.maybe_get_item_body(tcx, item.def_id).unwrap().value)))
} else {
None
};
fn build_const(cx: &DocContext, did: DefId) -> clean::Constant {
clean::Constant {
type_: cx.tcx.item_type(did).clean(cx),
- expr: pprust::expr_to_string(
- &cx.tcx.sess.cstore.maybe_get_item_body(cx.tcx, did).unwrap().value)
+ expr: hir::print::to_string(&cx.tcx.map, |s| s.print_expr(
+ &cx.tcx.sess.cstore.maybe_get_item_body(cx.tcx, did).unwrap().value))
}
}
use rustc::middle::lang_items;
use rustc::hir::def::{Def, CtorKind};
use rustc::hir::def_id::{CrateNum, DefId, CRATE_DEF_INDEX, LOCAL_CRATE};
-use rustc::hir::print as pprust;
use rustc::ty::subst::Substs;
use rustc::ty::{self, AdtKind};
use rustc::middle::stability;
}
fn print_const_expr(cx: &DocContext, body: hir::BodyId) -> String {
- pprust::expr_to_string(&cx.tcx.map.body(body).value)
+ cx.tcx.map.node_to_pretty_string(body.node_id)
}
/// Given a type Path, resolve it to a Type using the TyCtxt
fn visit_item(&mut self, item: &'hir hir::Item) {
let name = if let hir::ItemImpl(.., ref ty, _) = item.node {
- hir::print::ty_to_string(ty)
+ self.map.node_to_pretty_string(ty.id)
} else {
item.name.to_string()
};
digraph block {
N0[label="entry"];
N1[label="exit"];
- N2[label="stmt "];
+ N2[label="stmt fn inner(x: isize) -> isize { x + x }"];
N3[label="expr inner"];
N4[label="expr inner"];
N5[label="expr 18"];
N6[label="expr inner(18)"];
N7[label="expr inner(inner(18))"];
N8[label="stmt inner(inner(18));"];
- N9[label="block { inner(inner(18)); }"];
- N10[label="expr { inner(inner(18)); }"];
+ N9[label="block {\l fn inner(x: isize) -> isize { x + x }\l inner(inner(18));\l}\l"];
+ N10[label="expr {\l fn inner(x: isize) -> isize { x + x }\l inner(inner(18));\l}\l"];
N0 -> N2;
N2 -> N3;
N3 -> N4;
digraph block {
N0[label="entry"];
N1[label="exit"];
- N2[label="stmt "];
- N3[label="stmt "];
+ N2[label="stmt struct S19 {\l x: isize,\l}\l"];
+ N3[label="stmt impl S19 {\l fn inner(self: Self) -> S19 { S19{x: self.x + self.x,} }\l}\l"];
N4[label="expr 19"];
N5[label="expr S19{x: 19,}"];
N6[label="local s"];
N9[label="expr s.inner()"];
N10[label="expr s.inner().inner()"];
N11[label="stmt s.inner().inner();"];
- N12[label="block { let s = S19{x: 19,}; s.inner().inner(); }"];
- N13[label="expr { let s = S19{x: 19,}; s.inner().inner(); }"];
+ N12[label="block {\l struct S19 {\l x: isize,\l }\l impl S19 {\l fn inner(self: Self) -> S19 { S19{x: self.x + self.x,} }\l }\l let s = S19{x: 19,};\l s.inner().inner();\l}\l"];
+ N13[label="expr {\l struct S19 {\l x: isize,\l }\l impl S19 {\l fn inner(self: Self) -> S19 { S19{x: self.x + self.x,} }\l }\l let s = S19{x: 19,};\l s.inner().inner();\l}\l"];
N0 -> N2;
N2 -> N3;
N3 -> N4;