]> git.proxmox.com Git - rustc.git/blobdiff - src/libsyntax/print/pprust.rs
New upstream version 1.20.0+dfsg1
[rustc.git] / src / libsyntax / print / pprust.rs
index 0c79cbca039a6e9623aba3456c80eb1004cfb19c..b052b2cdbbb5a74fa31c52371b64432abedf513e 100644 (file)
@@ -1,4 +1,4 @@
-// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
+// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
 // file at the top-level directory of this distribution and at
 // http://rust-lang.org/COPYRIGHT.
 //
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-use core::prelude::*;
+pub use self::AnnNode::*;
 
-use abi::AbiSet;
-use ast::{RegionTyParamBound, TraitTyParamBound, required, provided};
-use ast;
-use ast_util;
-use opt_vec::OptVec;
-use opt_vec;
+use abi::{self, Abi};
+use ast::{self, BlockCheckMode, PatKind, RangeEnd};
+use ast::{SelfKind, RegionTyParamBound, TraitTyParamBound, TraitBoundModifier};
+use ast::Attribute;
+use util::parser::AssocOp;
 use attr;
-use codemap::{CodeMap, BytePos};
-use codemap;
-use diagnostic;
-use parse::classify::expr_is_simple_block;
-use parse::token::ident_interner;
-use parse::{comments, token};
-use parse;
-use print::pp::{break_offset, word, space, zerobreak, hardbreak};
-use print::pp::{breaks, consistent, inconsistent, eof};
-use print::pp;
-use print::pprust;
-
-use core::char;
-use core::io;
-use core::str;
-use core::u64;
-use core::vec;
-
-// The @ps is stored here to prevent recursive type.
-pub enum ann_node<'self> {
-    node_block(@ps, &'self ast::blk),
-    node_item(@ps, @ast::item),
-    node_expr(@ps, @ast::expr),
-    node_pat(@ps, @ast::pat),
-}
-pub struct pp_ann {
-    pre: @fn(ann_node),
-    post: @fn(ann_node)
-}
+use codemap::{self, CodeMap};
+use syntax_pos::{self, BytePos};
+use parse::token::{self, BinOpToken, Token};
+use parse::lexer::comments;
+use parse::{self, ParseSess};
+use print::pp::{self, Breaks};
+use print::pp::Breaks::{Consistent, Inconsistent};
+use ptr::P;
+use std_inject;
+use symbol::{Symbol, keywords};
+use syntax_pos::DUMMY_SP;
+use tokenstream::{self, TokenStream, TokenTree};
+
+use std::ascii;
+use std::io::{self, Write, Read};
+use std::iter::{self, Peekable};
+use std::vec;
+
+pub enum AnnNode<'a> {
+    NodeIdent(&'a ast::Ident),
+    NodeName(&'a ast::Name),
+    NodeBlock(&'a ast::Block),
+    NodeItem(&'a ast::Item),
+    NodeSubItem(ast::NodeId),
+    NodeExpr(&'a ast::Expr),
+    NodePat(&'a ast::Pat),
+}
+
+pub trait PpAnn {
+    fn pre(&self, _state: &mut State, _node: AnnNode) -> io::Result<()> { Ok(()) }
+    fn post(&self, _state: &mut State, _node: AnnNode) -> io::Result<()> { Ok(()) }
+}
+
+#[derive(Copy, Clone)]
+pub struct NoAnn;
+
+impl PpAnn for NoAnn {}
+
+pub struct State<'a> {
+    pub s: pp::Printer<'a>,
+    cm: Option<&'a CodeMap>,
+    comments: Option<Vec<comments::Comment> >,
+    literals: Peekable<vec::IntoIter<comments::Literal>>,
+    cur_cmnt: usize,
+    boxes: Vec<pp::Breaks>,
+    ann: &'a (PpAnn+'a),
+}
+
+fn rust_printer<'a>(writer: Box<Write+'a>, ann: &'a PpAnn) -> State<'a> {
+    State {
+        s: pp::mk_printer(writer, DEFAULT_COLUMNS),
+        cm: None,
+        comments: None,
+        literals: vec![].into_iter().peekable(),
+        cur_cmnt: 0,
+        boxes: Vec::new(),
+        ann: ann,
+    }
+}
+
+pub const INDENT_UNIT: usize = 4;
+
+pub const DEFAULT_COLUMNS: usize = 78;
+
+/// Requires you to pass an input filename and reader so that
+/// it can scan the input text for comments and literals to
+/// copy forward.
+pub fn print_crate<'a>(cm: &'a CodeMap,
+                       sess: &ParseSess,
+                       krate: &ast::Crate,
+                       filename: String,
+                       input: &mut Read,
+                       out: Box<Write+'a>,
+                       ann: &'a PpAnn,
+                       is_expanded: bool) -> io::Result<()> {
+    let mut s = State::new_from_input(cm, sess, filename, input, out, ann, is_expanded);
+
+    if is_expanded && !std_inject::injected_crate_name(krate).is_none() {
+        // We need to print `#![no_std]` (and its feature gate) so that
+        // compiling pretty-printed source won't inject libstd again.
+        // However we don't want these attributes in the AST because
+        // of the feature gate, so we fake them up here.
+
+        // #![feature(prelude_import)]
+        let prelude_import_meta = attr::mk_list_word_item(Symbol::intern("prelude_import"));
+        let list = attr::mk_list_item(Symbol::intern("feature"), vec![prelude_import_meta]);
+        let fake_attr = attr::mk_attr_inner(DUMMY_SP, attr::mk_attr_id(), list);
+        s.print_attribute(&fake_attr)?;
+
+        // #![no_std]
+        let no_std_meta = attr::mk_word_item(Symbol::intern("no_std"));
+        let fake_attr = attr::mk_attr_inner(DUMMY_SP, attr::mk_attr_id(), no_std_meta);
+        s.print_attribute(&fake_attr)?;
+    }
+
+    s.print_mod(&krate.module, &krate.attrs)?;
+    s.print_remaining_comments()?;
+    s.s.eof()
+}
+
+impl<'a> State<'a> {
+    pub fn new_from_input(cm: &'a CodeMap,
+                          sess: &ParseSess,
+                          filename: String,
+                          input: &mut Read,
+                          out: Box<Write+'a>,
+                          ann: &'a PpAnn,
+                          is_expanded: bool) -> State<'a> {
+        let (cmnts, lits) = comments::gather_comments_and_literals(sess, 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<Write+'a>,
+               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.unwrap_or_default().into_iter().peekable(),
+            cur_cmnt: 0,
+            boxes: Vec::new(),
+            ann: ann,
+        }
+    }
+}
+
+pub fn to_string<F>(f: F) -> String where
+    F: FnOnce(&mut State) -> io::Result<()>,
+{
+    let mut wr = Vec::new();
+    {
+        let ann = NoAnn;
+        let mut printer = rust_printer(Box::new(&mut wr), &ann);
+        f(&mut printer).unwrap();
+        printer.s.eof().unwrap();
+    }
+    String::from_utf8(wr).unwrap()
+}
+
+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 token_to_string(tok: &Token) -> String {
+    match *tok {
+        token::Eq                   => "=".to_string(),
+        token::Lt                   => "<".to_string(),
+        token::Le                   => "<=".to_string(),
+        token::EqEq                 => "==".to_string(),
+        token::Ne                   => "!=".to_string(),
+        token::Ge                   => ">=".to_string(),
+        token::Gt                   => ">".to_string(),
+        token::Not                  => "!".to_string(),
+        token::Tilde                => "~".to_string(),
+        token::OrOr                 => "||".to_string(),
+        token::AndAnd               => "&&".to_string(),
+        token::BinOp(op)            => binop_to_string(op).to_string(),
+        token::BinOpEq(op)          => format!("{}=", binop_to_string(op)),
+
+        /* Structural symbols */
+        token::At                   => "@".to_string(),
+        token::Dot                  => ".".to_string(),
+        token::DotDot               => "..".to_string(),
+        token::DotDotDot            => "...".to_string(),
+        token::Comma                => ",".to_string(),
+        token::Semi                 => ";".to_string(),
+        token::Colon                => ":".to_string(),
+        token::ModSep               => "::".to_string(),
+        token::RArrow               => "->".to_string(),
+        token::LArrow               => "<-".to_string(),
+        token::FatArrow             => "=>".to_string(),
+        token::OpenDelim(token::Paren) => "(".to_string(),
+        token::CloseDelim(token::Paren) => ")".to_string(),
+        token::OpenDelim(token::Bracket) => "[".to_string(),
+        token::CloseDelim(token::Bracket) => "]".to_string(),
+        token::OpenDelim(token::Brace) => "{".to_string(),
+        token::CloseDelim(token::Brace) => "}".to_string(),
+        token::OpenDelim(token::NoDelim) |
+        token::CloseDelim(token::NoDelim) => " ".to_string(),
+        token::Pound                => "#".to_string(),
+        token::Dollar               => "$".to_string(),
+        token::Question             => "?".to_string(),
+
+        /* Literals */
+        token::Literal(lit, suf) => {
+            let mut out = match lit {
+                token::Byte(b)           => format!("b'{}'", b),
+                token::Char(c)           => format!("'{}'", c),
+                token::Float(c)          |
+                token::Integer(c)        => c.to_string(),
+                token::Str_(s)           => format!("\"{}\"", s),
+                token::StrRaw(s, n)      => format!("r{delim}\"{string}\"{delim}",
+                                                    delim=repeat("#", n),
+                                                    string=s),
+                token::ByteStr(v)         => format!("b\"{}\"", v),
+                token::ByteStrRaw(s, n)   => format!("br{delim}\"{string}\"{delim}",
+                                                    delim=repeat("#", n),
+                                                    string=s),
+            };
 
-pub fn no_ann() -> pp_ann {
-    fn ignore(_node: ann_node) { }
-    return pp_ann {pre: ignore, post: ignore};
-}
+            if let Some(s) = suf {
+                out.push_str(&s.as_str())
+            }
 
-pub struct CurrentCommentAndLiteral {
-    cur_cmnt: uint,
-    cur_lit: uint,
-}
+            out
+        }
 
-pub struct ps {
-    s: @mut pp::Printer,
-    cm: Option<@CodeMap>,
-    intr: @token::ident_interner,
-    comments: Option<~[comments::cmnt]>,
-    literals: Option<~[comments::lit]>,
-    cur_cmnt_and_lit: @mut CurrentCommentAndLiteral,
-    boxes: @mut ~[pp::breaks],
-    ann: pp_ann
-}
+        /* Name components */
+        token::Ident(s)             => s.to_string(),
+        token::Lifetime(s)          => s.to_string(),
+        token::Underscore           => "_".to_string(),
 
-pub fn ibox(s: @ps, u: uint) {
-    s.boxes.push(pp::inconsistent);
-    pp::ibox(s.s, u);
-}
+        /* Other */
+        token::DocComment(s)        => s.to_string(),
+        token::Eof                  => "<eof>".to_string(),
+        token::Whitespace           => " ".to_string(),
+        token::Comment              => "/* */".to_string(),
+        token::Shebang(s)           => format!("/* shebang: {}*/", s),
 
-pub fn end(s: @ps) {
-    s.boxes.pop();
-    pp::end(s.s);
+        token::Interpolated(ref nt) => match nt.0 {
+            token::NtExpr(ref e)        => expr_to_string(e),
+            token::NtMeta(ref e)        => meta_item_to_string(e),
+            token::NtTy(ref e)          => ty_to_string(e),
+            token::NtPath(ref e)        => path_to_string(e),
+            token::NtItem(ref e)        => item_to_string(e),
+            token::NtBlock(ref e)       => block_to_string(e),
+            token::NtStmt(ref e)        => stmt_to_string(e),
+            token::NtPat(ref e)         => pat_to_string(e),
+            token::NtIdent(ref e)       => ident_to_string(e.node),
+            token::NtTT(ref tree)       => tt_to_string(tree.clone()),
+            token::NtArm(ref e)         => arm_to_string(e),
+            token::NtImplItem(ref e)    => impl_item_to_string(e),
+            token::NtTraitItem(ref e)   => trait_item_to_string(e),
+            token::NtGenerics(ref e)    => generics_to_string(e),
+            token::NtWhereClause(ref e) => where_clause_to_string(e),
+            token::NtArg(ref e)         => arg_to_string(e),
+            token::NtVis(ref e)         => vis_to_string(e),
+        }
+    }
 }
 
-pub fn rust_printer(writer: @io::Writer, intr: @ident_interner) -> @ps {
-    return @ps {
-        s: pp::mk_printer(writer, default_columns),
-        cm: None::<@CodeMap>,
-        intr: intr,
-        comments: None::<~[comments::cmnt]>,
-        literals: None::<~[comments::lit]>,
-        cur_cmnt_and_lit: @mut CurrentCommentAndLiteral {
-            cur_cmnt: 0,
-            cur_lit: 0
-        },
-        boxes: @mut ~[],
-        ann: no_ann()
-    };
+pub fn ty_to_string(ty: &ast::Ty) -> String {
+    to_string(|s| s.print_type(ty))
 }
 
-pub static indent_unit: uint = 4u;
-pub static match_indent_unit: uint = 2u;
-
-pub static default_columns: uint = 78u;
-
-// Requires you to pass an input filename and reader so that
-// it can scan the input text for comments and literals to
-// copy forward.
-pub fn print_crate(cm: @CodeMap,
-                   intr: @ident_interner,
-                   span_diagnostic: @diagnostic::span_handler,
-                   crate: @ast::crate,
-                   filename: ~str,
-                   in: @io::Reader,
-                   out: @io::Writer,
-                   ann: pp_ann,
-                   is_expanded: bool) {
-    let (cmnts, lits) = comments::gather_comments_and_literals(
-        span_diagnostic,
-        copy filename,
-        in
-    );
-    let s = @ps {
-        s: pp::mk_printer(out, default_columns),
-        cm: Some(cm),
-        intr: intr,
-        comments: Some(copy 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(copy lits) },
-        cur_cmnt_and_lit: @mut CurrentCommentAndLiteral {
-            cur_cmnt: 0,
-            cur_lit: 0
-        },
-        boxes: @mut ~[],
-        ann: ann
-    };
-    print_crate_(s, crate);
+pub fn bounds_to_string(bounds: &[ast::TyParamBound]) -> String {
+    to_string(|s| s.print_bounds("", bounds))
 }
 
-pub fn print_crate_(s: @ps, &&crate: @ast::crate) {
-    print_mod(s, &crate.node.module, crate.node.attrs);
-    print_remaining_comments(s);
-    eof(s.s);
+pub fn pat_to_string(pat: &ast::Pat) -> String {
+    to_string(|s| s.print_pat(pat))
 }
 
-pub fn ty_to_str(ty: @ast::Ty, intr: @ident_interner) -> ~str {
-    to_str(ty, print_type, intr)
+pub fn arm_to_string(arm: &ast::Arm) -> String {
+    to_string(|s| s.print_arm(arm))
 }
 
-pub fn pat_to_str(pat: @ast::pat, intr: @ident_interner) -> ~str {
-    to_str(pat, print_irrefutable_pat, intr)
+pub fn expr_to_string(e: &ast::Expr) -> String {
+    to_string(|s| s.print_expr(e))
 }
 
-pub fn expr_to_str(e: @ast::expr, intr: @ident_interner) -> ~str {
-    to_str(e, print_expr, intr)
+pub fn lifetime_to_string(e: &ast::Lifetime) -> String {
+    to_string(|s| s.print_lifetime(e))
 }
 
-pub fn lifetime_to_str(e: &ast::Lifetime, intr: @ident_interner) -> ~str {
-    to_str(e, print_lifetime, intr)
+pub fn tt_to_string(tt: tokenstream::TokenTree) -> String {
+    to_string(|s| s.print_tt(tt))
 }
 
-pub fn tt_to_str(tt: ast::token_tree, intr: @ident_interner) -> ~str {
-    to_str(tt, print_tt, intr)
+pub fn tts_to_string(tts: &[tokenstream::TokenTree]) -> String {
+    to_string(|s| s.print_tts(tts.iter().cloned().collect()))
 }
 
-pub fn tts_to_str(tts: &[ast::token_tree], intr: @ident_interner) -> ~str {
-    to_str(tts, print_tts, intr)
+pub fn tokens_to_string(tokens: TokenStream) -> String {
+    to_string(|s| s.print_tts(tokens))
 }
 
-pub fn stmt_to_str(s: ast::stmt, intr: @ident_interner) -> ~str {
-    to_str(s, print_stmt, intr)
+pub fn stmt_to_string(stmt: &ast::Stmt) -> String {
+    to_string(|s| s.print_stmt(stmt))
 }
 
-pub fn item_to_str(i: @ast::item, intr: @ident_interner) -> ~str {
-    to_str(i, print_item, intr)
+pub fn attr_to_string(attr: &ast::Attribute) -> String {
+    to_string(|s| s.print_attribute(attr))
 }
 
-pub fn generics_to_str(generics: &ast::Generics,
-                       intr: @ident_interner) -> ~str {
-    to_str(generics, print_generics, intr)
+pub fn item_to_string(i: &ast::Item) -> String {
+    to_string(|s| s.print_item(i))
 }
 
-pub fn path_to_str(&&p: @ast::path, intr: @ident_interner) -> ~str {
-    to_str(p, |a,b| print_path(a, b, false), intr)
+pub fn impl_item_to_string(i: &ast::ImplItem) -> String {
+    to_string(|s| s.print_impl_item(i))
 }
 
-pub fn fun_to_str(decl: &ast::fn_decl, purity: ast::purity, name: ast::ident,
-                  opt_self_ty: Option<ast::self_ty_>,
-                  generics: &ast::Generics, intr: @ident_interner) -> ~str {
-    do io::with_str_writer |wr| {
-        let s = rust_printer(wr, intr);
-        print_fn(s, decl, Some(purity), AbiSet::Rust(),
-                 name, generics, opt_self_ty, ast::inherited);
-        end(s); // Close the head box
-        end(s); // Close the outer box
-        eof(s.s);
-    }
+pub fn trait_item_to_string(i: &ast::TraitItem) -> String {
+    to_string(|s| s.print_trait_item(i))
 }
 
-pub fn block_to_str(blk: &ast::blk, intr: @ident_interner) -> ~str {
-    do io::with_str_writer |wr| {
-        let s = rust_printer(wr, intr);
-        // containing cbox, will be closed by print-block at }
-        cbox(s, indent_unit);
-        // head-ibox, will be closed by print-block after {
-        ibox(s, 0u);
-        print_block(s, blk);
-        eof(s.s);
-    }
+pub fn generics_to_string(generics: &ast::Generics) -> String {
+    to_string(|s| s.print_generics(generics))
 }
 
-pub fn meta_item_to_str(mi: @ast::meta_item, intr: @ident_interner) -> ~str {
-    to_str(mi, print_meta_item, intr)
+pub fn where_clause_to_string(i: &ast::WhereClause) -> String {
+    to_string(|s| s.print_where_clause(i))
 }
 
-pub fn attribute_to_str(attr: ast::attribute, intr: @ident_interner) -> ~str {
-    to_str(attr, print_attribute, intr)
+pub fn fn_block_to_string(p: &ast::FnDecl) -> String {
+    to_string(|s| s.print_fn_block_args(p))
 }
 
-pub fn variant_to_str(var: ast::variant, intr: @ident_interner) -> ~str {
-    to_str(var, print_variant, intr)
+pub fn path_to_string(p: &ast::Path) -> String {
+    to_string(|s| s.print_path(p, false, 0, false))
 }
 
-pub fn cbox(s: @ps, u: uint) {
-    s.boxes.push(pp::consistent);
-    pp::cbox(s.s, u);
+pub fn path_segment_to_string(p: &ast::PathSegment) -> String {
+    to_string(|s| s.print_path_segment(p, false))
 }
 
-pub fn box(s: @ps, u: uint, b: pp::breaks) {
-    s.boxes.push(b);
-    pp::box(s.s, u, b);
+pub fn ident_to_string(id: ast::Ident) -> String {
+    to_string(|s| s.print_ident(id))
 }
 
-pub fn nbsp(s: @ps) { word(s.s, ~" "); }
-
-pub fn word_nbsp(s: @ps, w: ~str) { word(s.s, w); nbsp(s); }
-
-pub fn word_space(s: @ps, w: ~str) { word(s.s, w); space(s.s); }
-
-pub fn popen(s: @ps) { word(s.s, ~"("); }
-
-pub fn pclose(s: @ps) { word(s.s, ~")"); }
+pub fn vis_to_string(v: &ast::Visibility) -> String {
+    to_string(|s| s.print_visibility(v))
+}
 
-pub fn head(s: @ps, w: ~str) {
-    // outer-box is consistent
-    cbox(s, indent_unit);
-    // head-box is inconsistent
-    ibox(s, str::len(w) + 1);
-    // keyword that starts the head
-    if !w.is_empty() {
-        word_nbsp(s, w);
-    }
+pub fn fun_to_string(decl: &ast::FnDecl,
+                     unsafety: ast::Unsafety,
+                     constness: ast::Constness,
+                     name: ast::Ident,
+                     generics: &ast::Generics)
+                     -> String {
+    to_string(|s| {
+        s.head("")?;
+        s.print_fn(decl, unsafety, constness, Abi::Rust, Some(name),
+                   generics, &ast::Visibility::Inherited)?;
+        s.end()?; // Close the head box
+        s.end() // Close the outer box
+    })
 }
 
-pub fn bopen(s: @ps) {
-    word(s.s, ~"{");
-    end(s); // close the head-box
+pub fn block_to_string(blk: &ast::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 bclose_(s: @ps, span: codemap::span, indented: uint) {
-    bclose_maybe_open(s, span, indented, true);
+pub fn meta_list_item_to_string(li: &ast::NestedMetaItem) -> String {
+    to_string(|s| s.print_meta_list_item(li))
 }
-pub fn bclose_maybe_open (s: @ps, span: codemap::span, indented: uint,
-                          close_box: bool) {
-    maybe_print_comment(s, span.hi);
-    break_offset_if_not_bol(s, 1u, -(indented as int));
-    word(s.s, ~"}");
-    if close_box {
-        end(s); // close the outer-box
-    }
+
+pub fn meta_item_to_string(mi: &ast::MetaItem) -> String {
+    to_string(|s| s.print_meta_item(mi))
 }
-pub fn bclose(s: @ps, span: codemap::span) { bclose_(s, span, indent_unit); }
 
-pub fn is_begin(s: @ps) -> bool {
-    match s.s.last_token() { pp::BEGIN(_) => true, _ => false }
+pub fn attribute_to_string(attr: &ast::Attribute) -> String {
+    to_string(|s| s.print_attribute(attr))
 }
 
-pub fn is_end(s: @ps) -> bool {
-    match s.s.last_token() { pp::END => true, _ => false }
+pub fn lit_to_string(l: &ast::Lit) -> String {
+    to_string(|s| s.print_literal(l))
 }
 
-pub fn is_bol(s: @ps) -> bool {
-    return s.s.last_token().is_eof() || s.s.last_token().is_hardbreak_tok();
+pub fn variant_to_string(var: &ast::Variant) -> String {
+    to_string(|s| s.print_variant(var))
 }
 
-pub fn in_cbox(s: @ps) -> bool {
-    let boxes = &*s.boxes;
-    let len = boxes.len();
-    if len == 0u { return false; }
-    return boxes[len - 1u] == pp::consistent;
+pub fn arg_to_string(arg: &ast::Arg) -> String {
+    to_string(|s| s.print_arg(arg, false))
 }
 
-pub fn hardbreak_if_not_bol(s: @ps) { if !is_bol(s) { hardbreak(s.s); } }
-pub fn space_if_not_bol(s: @ps) { if !is_bol(s) { space(s.s); } }
-pub fn break_offset_if_not_bol(s: @ps, n: uint, off: int) {
-    if !is_bol(s) {
-        break_offset(s.s, n, off);
-    } else {
-        if off != 0 && s.s.last_token().is_hardbreak_tok() {
-            // We do something pretty sketchy here: tuck the nonzero
-            // offset-adjustment we were going to deposit along with the
-            // break into the previous hardbreak.
-            s.s.replace_last_token(pp::hardbreak_tok_offset(off));
-        }
-    }
+pub fn mac_to_string(arg: &ast::Mac) -> String {
+    to_string(|s| s.print_mac(arg, ::parse::token::Paren))
 }
 
-// Synthesizes a comment that was not textually present in the original source
-// file.
-pub fn synth_comment(s: @ps, text: ~str) {
-    word(s.s, ~"/*");
-    space(s.s);
-    word(s.s, text);
-    space(s.s);
-    word(s.s, ~"*/");
+pub fn visibility_qualified(vis: &ast::Visibility, s: &str) -> String {
+    format!("{}{}", to_string(|s| s.print_visibility(vis)), s)
 }
 
-pub fn commasep<IN>(s: @ps, b: breaks, elts: &[IN], op: &fn(@ps, IN)) {
-    box(s, 0u, b);
-    let mut first = true;
-    for elts.each |elt| {
-        if first { first = false; } else { word_space(s, ~","); }
-        op(s, *elt);
+fn needs_parentheses(expr: &ast::Expr) -> bool {
+    match expr.node {
+        ast::ExprKind::Assign(..) | ast::ExprKind::Binary(..) |
+        ast::ExprKind::Closure(..) |
+        ast::ExprKind::AssignOp(..) | ast::ExprKind::Cast(..) |
+        ast::ExprKind::InPlace(..) | ast::ExprKind::Type(..) => true,
+        _ => false,
     }
-    end(s);
 }
 
+pub trait PrintState<'a> {
+    fn writer(&mut self) -> &mut pp::Printer<'a>;
+    fn boxes(&mut self) -> &mut Vec<pp::Breaks>;
+    fn comments(&mut self) -> &mut Option<Vec<comments::Comment>>;
+    fn cur_cmnt(&mut self) -> &mut usize;
+    fn cur_lit(&mut self) -> Option<&comments::Literal>;
+    fn bump_lit(&mut self) -> Option<comments::Literal>;
 
-pub fn commasep_cmnt<IN>(s: @ps, b: breaks, elts: &[IN], op: &fn(@ps, IN),
-                         get_span: &fn(IN) -> codemap::span) {
-    box(s, 0u, b);
-    let len = elts.len();
-    let mut i = 0u;
-    for elts.each |elt| {
-        maybe_print_comment(s, get_span(*elt).hi);
-        op(s, *elt);
-        i += 1u;
-        if i < len {
-            word(s.s, ~",");
-            maybe_print_trailing_comment(s, get_span(*elt),
-                                         Some(get_span(elts[i]).hi));
-            space_if_not_bol(s);
-        }
+    fn word_space(&mut self, w: &str) -> io::Result<()> {
+        self.writer().word(w)?;
+        self.writer().space()
     }
-    end(s);
-}
 
-pub fn commasep_exprs(s: @ps, b: breaks, exprs: &[@ast::expr]) {
-    fn expr_span(&&expr: @ast::expr) -> codemap::span { return expr.span; }
-    commasep_cmnt(s, b, exprs, print_expr, expr_span);
-}
+    fn popen(&mut self) -> io::Result<()> { self.writer().word("(") }
 
-pub fn print_mod(s: @ps, _mod: &ast::_mod, attrs: ~[ast::attribute]) {
-    print_inner_attributes(s, attrs);
-    for _mod.view_items.each |vitem| {
-        print_view_item(s, *vitem);
-    }
-    for _mod.items.each |item| { print_item(s, *item); }
-}
+    fn pclose(&mut self) -> io::Result<()> { self.writer().word(")") }
 
-pub fn print_foreign_mod(s: @ps, nmod: &ast::foreign_mod,
-                         attrs: ~[ast::attribute]) {
-    print_inner_attributes(s, attrs);
-    for nmod.view_items.each |vitem| {
-        print_view_item(s, *vitem);
+    fn is_begin(&mut self) -> bool {
+        match self.writer().last_token() {
+            pp::Token::Begin(_) => true,
+            _ => false,
+        }
     }
-    for nmod.items.each |item| { print_foreign_item(s, *item); }
-}
 
-pub fn print_opt_lifetime(s: @ps, lifetime: Option<@ast::Lifetime>) {
-    for lifetime.each |l| {
-        print_lifetime(s, *l);
-        nbsp(s);
+    fn is_end(&mut self) -> bool {
+        match self.writer().last_token() {
+            pp::Token::End => true,
+            _ => false,
+        }
     }
-}
 
-pub fn print_type(s: @ps, &&ty: @ast::Ty) {
-    maybe_print_comment(s, ty.span.lo);
-    ibox(s, 0u);
-    match ty.node {
-      ast::ty_nil => word(s.s, ~"()"),
-      ast::ty_bot => word(s.s, ~"!"),
-      ast::ty_box(ref mt) => { word(s.s, ~"@"); print_mt(s, mt); }
-      ast::ty_uniq(ref mt) => { word(s.s, ~"~"); print_mt(s, mt); }
-      ast::ty_vec(ref mt) => {
-        word(s.s, ~"[");
-        match mt.mutbl {
-          ast::m_mutbl => word_space(s, ~"mut"),
-          ast::m_const => word_space(s, ~"const"),
-          ast::m_imm => ()
-        }
-        print_type(s, mt.ty);
-        word(s.s, ~"]");
-      }
-      ast::ty_ptr(ref mt) => { word(s.s, ~"*"); print_mt(s, mt); }
-      ast::ty_rptr(lifetime, ref mt) => {
-          word(s.s, ~"&");
-          print_opt_lifetime(s, lifetime);
-          print_mt(s, mt);
-      }
-      ast::ty_tup(ref elts) => {
-        popen(s);
-        commasep(s, inconsistent, *elts, print_type);
-        if elts.len() == 1 {
-            word(s.s, ~",");
-        }
-        pclose(s);
-      }
-      ast::ty_bare_fn(f) => {
-          let generics = ast::Generics {lifetimes: copy f.lifetimes,
-                                        ty_params: opt_vec::Empty};
-          print_ty_fn(s, Some(f.abis), None, None,
-                      f.purity, ast::Many, &f.decl, None,
-                      Some(&generics), None);
-      }
-      ast::ty_closure(f) => {
-          let generics = ast::Generics {lifetimes: copy f.lifetimes,
-                                        ty_params: opt_vec::Empty};
-          print_ty_fn(s, None, Some(f.sigil), f.region,
-                      f.purity, f.onceness, &f.decl, None,
-                      Some(&generics), None);
-      }
-      ast::ty_path(path, _) => print_path(s, path, false),
-      ast::ty_fixed_length_vec(ref mt, v) => {
-        word(s.s, ~"[");
-        match mt.mutbl {
-            ast::m_mutbl => word_space(s, ~"mut"),
-            ast::m_const => word_space(s, ~"const"),
-            ast::m_imm => ()
-        }
-        print_type(s, mt.ty);
-        word(s.s, ~", ..");
-        print_expr(s, v);
-        word(s.s, ~"]");
-      }
-      ast::ty_mac(_) => {
-          fail!(~"print_type doesn't know how to print a ty_mac");
-      }
-      ast::ty_infer => {
-          fail!(~"print_type shouldn't see a ty_infer");
-      }
-
-    }
-    end(s);
-}
+    // is this the beginning of a line?
+    fn is_bol(&mut self) -> bool {
+        self.writer().last_token().is_eof() || self.writer().last_token().is_hardbreak_tok()
+    }
 
-pub fn print_foreign_item(s: @ps, item: @ast::foreign_item) {
-    hardbreak_if_not_bol(s);
-    maybe_print_comment(s, item.span.lo);
-    print_outer_attributes(s, item.attrs);
-    match item.node {
-      ast::foreign_item_fn(ref decl, purity, ref generics) => {
-        print_fn(s, decl, Some(purity), AbiSet::Rust(), item.ident, generics, None,
-                 ast::inherited);
-        end(s); // end head-ibox
-        word(s.s, ~";");
-        end(s); // end the outer fn box
-      }
-      ast::foreign_item_const(t) => {
-        head(s, ~"static");
-        print_ident(s, item.ident);
-        word_space(s, ~":");
-        print_type(s, t);
-        word(s.s, ~";");
-        end(s); // end the head-ibox
-        end(s); // end the outer cbox
-      }
+    fn hardbreak_if_not_bol(&mut self) -> io::Result<()> {
+        if !self.is_bol() {
+            self.writer().hardbreak()?
+        }
+        Ok(())
     }
-}
 
-pub fn print_item(s: @ps, &&item: @ast::item) {
-    hardbreak_if_not_bol(s);
-    maybe_print_comment(s, item.span.lo);
-    print_outer_attributes(s, item.attrs);
-    let ann_node = node_item(s, item);
-    (s.ann.pre)(ann_node);
-    match item.node {
-      ast::item_const(ty, expr) => {
-        head(s, visibility_qualified(item.vis, ~"static"));
-        print_ident(s, item.ident);
-        word_space(s, ~":");
-        print_type(s, ty);
-        space(s.s);
-        end(s); // end the head-ibox
-
-        word_space(s, ~"=");
-        print_expr(s, expr);
-        word(s.s, ~";");
-        end(s); // end the outer cbox
-
-      }
-      ast::item_fn(ref decl, purity, abi, ref typarams, ref body) => {
-        print_fn(
-            s,
-            decl,
-            Some(purity),
-            abi,
-            item.ident,
-            typarams,
-            None,
-            item.vis
-        );
-        word(s.s, ~" ");
-        print_block_with_attrs(s, body, item.attrs);
-      }
-      ast::item_mod(ref _mod) => {
-        head(s, visibility_qualified(item.vis, ~"mod"));
-        print_ident(s, item.ident);
-        nbsp(s);
-        bopen(s);
-        print_mod(s, _mod, item.attrs);
-        bclose(s, item.span);
-      }
-      ast::item_foreign_mod(ref nmod) => {
-        head(s, visibility_qualified(item.vis, ~"extern"));
-        word_nbsp(s, nmod.abis.to_str());
-        match nmod.sort {
-            ast::named => {
-                word_nbsp(s, ~"mod");
-                print_ident(s, item.ident);
-                nbsp(s);
-            }
-            ast::anonymous => {}
-        }
-        bopen(s);
-        print_foreign_mod(s, nmod, item.attrs);
-        bclose(s, item.span);
-      }
-      ast::item_ty(ty, ref params) => {
-        ibox(s, indent_unit);
-        ibox(s, 0u);
-        word_nbsp(s, visibility_qualified(item.vis, ~"type"));
-        print_ident(s, item.ident);
-        print_generics(s, params);
-        end(s); // end the inner ibox
-
-        space(s.s);
-        word_space(s, ~"=");
-        print_type(s, ty);
-        word(s.s, ~";");
-        end(s); // end the outer ibox
-      }
-      ast::item_enum(ref enum_definition, ref params) => {
-        print_enum_def(
-            s,
-            *enum_definition,
-            params,
-            item.ident,
-            item.span,
-            item.vis
-        );
-      }
-      ast::item_struct(struct_def, ref generics) => {
-          head(s, visibility_qualified(item.vis, ~"struct"));
-          print_struct(s, struct_def, generics, item.ident, item.span);
-      }
-
-      ast::item_impl(ref generics, opt_trait, ty, ref methods) => {
-        head(s, visibility_qualified(item.vis, ~"impl"));
-        if generics.is_parameterized() {
-            print_generics(s, generics);
-            space(s.s);
-        }
-
-        match opt_trait {
-            Some(t) => {
-                print_path(s, t.path, false);
-                space(s.s);
-                word_space(s, ~"for");
-            }
-            None => ()
-        };
+    // "raw box"
+    fn rbox(&mut self, u: usize, b: pp::Breaks) -> io::Result<()> {
+        self.boxes().push(b);
+        self.writer().rbox(u, b)
+    }
 
-        print_type(s, ty);
-        space(s.s);
+    fn ibox(&mut self, u: usize) -> io::Result<()> {
+        self.boxes().push(pp::Breaks::Inconsistent);
+        self.writer().ibox(u)
+    }
 
-        if methods.len() == 0 {
-            word(s.s, ~";");
-        } else {
-            bopen(s);
-            for methods.each |meth| {
-               print_method(s, *meth);
-            }
-            bclose(s, item.span);
-        }
-      }
-      ast::item_trait(ref generics, ref traits, ref methods) => {
-        head(s, visibility_qualified(item.vis, ~"trait"));
-        print_ident(s, item.ident);
-        print_generics(s, generics);
-        if traits.len() != 0u {
-            word(s.s, ~":");
-            for traits.eachi |i, trait_| {
-                nbsp(s);
-                if i != 0 {
-                    word_space(s, ~"+");
-                }
-                print_path(s, trait_.path, false);
-            }
-        }
-        word(s.s, ~" ");
-        bopen(s);
-        for methods.each |meth| {
-            print_trait_method(s, meth);
-        }
-        bclose(s, item.span);
-      }
-      ast::item_mac(codemap::spanned { node: ast::mac_invoc_tt(pth, ref tts),
-                                   _}) => {
-        print_visibility(s, item.vis);
-        print_path(s, pth, false);
-        word(s.s, ~"! ");
-        print_ident(s, item.ident);
-        cbox(s, indent_unit);
-        popen(s);
-        print_tts(s, *tts);
-        pclose(s);
-        end(s);
-      }
-    }
-    (s.ann.post)(ann_node);
-}
+    fn end(&mut self) -> io::Result<()> {
+        self.boxes().pop().unwrap();
+        self.writer().end()
+    }
 
-pub fn print_enum_def(s: @ps, enum_definition: ast::enum_def,
-                      generics: &ast::Generics, ident: ast::ident,
-                      span: codemap::span, visibility: ast::visibility) {
-    head(s, visibility_qualified(visibility, ~"enum"));
-    print_ident(s, ident);
-    print_generics(s, generics);
-    space(s.s);
-    print_variants(s, enum_definition.variants, span);
-}
+    fn commasep<T, F>(&mut self, b: Breaks, elts: &[T], mut op: F) -> io::Result<()>
+        where F: FnMut(&mut Self, &T) -> io::Result<()>,
+    {
+        self.rbox(0, b)?;
+        let mut first = true;
+        for elt in elts {
+            if first { first = false; } else { self.word_space(",")?; }
+            op(self, elt)?;
+        }
+        self.end()
+    }
 
-pub fn print_variants(s: @ps,
-                      variants: ~[ast::variant],
-                      span: codemap::span) {
-    bopen(s);
-    for variants.each |v| {
-        space_if_not_bol(s);
-        maybe_print_comment(s, v.span.lo);
-        print_outer_attributes(s, v.node.attrs);
-        ibox(s, indent_unit);
-        print_variant(s, *v);
-        word(s.s, ~",");
-        end(s);
-        maybe_print_trailing_comment(s, v.span, None);
-    }
-    bclose(s, span);
-}
+    fn next_lit(&mut self, pos: BytePos) -> Option<comments::Literal> {
+        while let Some(ltrl) = self.cur_lit().cloned() {
+            if ltrl.pos > pos { break; }
 
-pub fn visibility_to_str(vis: ast::visibility) -> ~str {
-    match vis {
-        ast::private => ~"priv",
-        ast::public => ~"pub",
-        ast::inherited => ~""
-    }
-}
+            // we don't need the value here since we're forced to clone cur_lit
+            // due to lack of NLL.
+            self.bump_lit();
+            if ltrl.pos == pos {
+                return Some(ltrl);
+            }
+        }
 
-pub fn visibility_qualified(vis: ast::visibility, s: ~str) -> ~str {
-    match vis {
-        ast::private | ast::public => visibility_to_str(vis) + " " + s,
-        ast::inherited => copy s
+        None
     }
-}
 
-pub fn print_visibility(s: @ps, vis: ast::visibility) {
-    match vis {
-        ast::private | ast::public =>
-        word_nbsp(s, visibility_to_str(vis)),
-        ast::inherited => ()
+    fn maybe_print_comment(&mut self, pos: BytePos) -> io::Result<()> {
+        while let Some(ref cmnt) = self.next_comment() {
+            if cmnt.pos < pos {
+                self.print_comment(cmnt)?;
+            } else {
+                break
+            }
+        }
+        Ok(())
     }
-}
 
-pub fn print_struct(s: @ps,
-                    struct_def: @ast::struct_def,
-                    generics: &ast::Generics,
-                    ident: ast::ident,
-                    span: codemap::span) {
-    print_ident(s, ident);
-    print_generics(s, generics);
-    if ast_util::struct_def_is_tuple_like(struct_def) {
-        if !struct_def.fields.is_empty() {
-            popen(s);
-            do commasep(s, inconsistent, struct_def.fields) |s, field| {
-                match field.node.kind {
-                    ast::named_field(*) => fail!(~"unexpected named field"),
-                    ast::unnamed_field => {
-                        maybe_print_comment(s, field.span.lo);
-                        print_type(s, field.node.ty);
+    fn print_comment(&mut self,
+                     cmnt: &comments::Comment) -> io::Result<()> {
+        let r = match cmnt.style {
+            comments::Mixed => {
+                assert_eq!(cmnt.lines.len(), 1);
+                self.writer().zerobreak()?;
+                self.writer().word(&cmnt.lines[0])?;
+                self.writer().zerobreak()
+            }
+            comments::Isolated => {
+                self.hardbreak_if_not_bol()?;
+                for line in &cmnt.lines {
+                    // Don't print empty lines because they will end up as trailing
+                    // whitespace
+                    if !line.is_empty() {
+                        self.writer().word(&line[..])?;
                     }
+                    self.writer().hardbreak()?;
                 }
+                Ok(())
             }
-            pclose(s);
-        }
-        word(s.s, ~";");
-        end(s);
-        end(s); // close the outer-box
-    } else {
-        nbsp(s);
-        bopen(s);
-        hardbreak_if_not_bol(s);
-        for struct_def.dtor.each |dtor| {
-          hardbreak_if_not_bol(s);
-          maybe_print_comment(s, dtor.span.lo);
-          print_outer_attributes(s, dtor.node.attrs);
-          head(s, ~"drop");
-          print_block(s, &dtor.node.body);
-        }
-
-        for struct_def.fields.each |field| {
-            match field.node.kind {
-                ast::unnamed_field => fail!(~"unexpected unnamed field"),
-                ast::named_field(ident, mutability, visibility) => {
-                    hardbreak_if_not_bol(s);
-                    maybe_print_comment(s, field.span.lo);
-                    print_visibility(s, visibility);
-                    if mutability == ast::struct_mutable {
-                        word_nbsp(s, ~"mut");
+            comments::Trailing => {
+                if !self.is_bol() {
+                    self.writer().word(" ")?;
+                }
+                if cmnt.lines.len() == 1 {
+                    self.writer().word(&cmnt.lines[0])?;
+                    self.writer().hardbreak()
+                } else {
+                    self.ibox(0)?;
+                    for line in &cmnt.lines {
+                        if !line.is_empty() {
+                            self.writer().word(&line[..])?;
+                        }
+                        self.writer().hardbreak()?;
                     }
-                    print_ident(s, ident);
-                    word_nbsp(s, ~":");
-                    print_type(s, field.node.ty);
-                    word(s.s, ~",");
+                    self.end()
+                }
+            }
+            comments::BlankLine => {
+                // We need to do at least one, possibly two hardbreaks.
+                let is_semi = match self.writer().last_token() {
+                    pp::Token::String(s, _) => ";" == s,
+                    _ => false
+                };
+                if is_semi || self.is_begin() || self.is_end() {
+                    self.writer().hardbreak()?;
                 }
+                self.writer().hardbreak()
+            }
+        };
+        match r {
+            Ok(()) => {
+                *self.cur_cmnt() = *self.cur_cmnt() + 1;
+                Ok(())
             }
+            Err(e) => Err(e),
         }
-
-        bclose(s, span);
-    }
-}
-
-/// This doesn't deserve to be called "pretty" printing, but it should be
-/// meaning-preserving. A quick hack that might help would be to look at the
-/// spans embedded in the TTs to decide where to put spaces and newlines.
-/// But it'd be better to parse these according to the grammar of the
-/// appropriate macro, transcribe back into the grammar we just parsed from,
-/// and then pretty-print the resulting AST nodes (so, e.g., we print
-/// expression arguments as expressions). It can be done! I think.
-pub fn print_tt(s: @ps, tt: ast::token_tree) {
-    match tt {
-      ast::tt_delim(ref tts) => print_tts(s, *tts),
-      ast::tt_tok(_, ref tk) => {
-          word(s.s, parse::token::to_str(s.intr, tk));
-      }
-      ast::tt_seq(_, ref tts, ref sep, zerok) => {
-        word(s.s, ~"$(");
-        for (*tts).each() |tt_elt| { print_tt(s, *tt_elt); }
-        word(s.s, ~")");
-        match (*sep) {
-          Some(ref tk) => word(s.s, parse::token::to_str(s.intr, tk)),
-          None => ()
-        }
-        word(s.s, if zerok { ~"*" } else { ~"+" });
-      }
-      ast::tt_nonterminal(_, name) => {
-        word(s.s, ~"$");
-        print_ident(s, name);
-      }
     }
-}
 
-pub fn print_tts(s: @ps, &&tts: &[ast::token_tree]) {
-    ibox(s, 0);
-    for tts.eachi |i, tt| {
-        if i != 0 {
-            space(s.s);
+    fn next_comment(&mut self) -> Option<comments::Comment> {
+        let cur_cmnt = *self.cur_cmnt();
+        match *self.comments() {
+            Some(ref cmnts) => {
+                if cur_cmnt < cmnts.len() {
+                    Some(cmnts[cur_cmnt].clone())
+                } else {
+                    None
+                }
+            }
+            _ => None
         }
-        print_tt(s, *tt);
     }
-    end(s);
-}
 
-pub fn print_variant(s: @ps, v: ast::variant) {
-    print_visibility(s, v.node.vis);
-    match v.node.kind {
-        ast::tuple_variant_kind(ref args) => {
-            print_ident(s, v.node.name);
-            if !args.is_empty() {
-                popen(s);
-                fn print_variant_arg(s: @ps, arg: ast::variant_arg) {
-                    print_type(s, arg.ty);
+    fn print_literal(&mut self, lit: &ast::Lit) -> io::Result<()> {
+        self.maybe_print_comment(lit.span.lo)?;
+        if let Some(ltrl) = self.next_lit(lit.span.lo) {
+            return self.writer().word(&ltrl.lit);
+        }
+        match lit.node {
+            ast::LitKind::Str(st, style) => self.print_string(&st.as_str(), style),
+            ast::LitKind::Byte(byte) => {
+                let mut res = String::from("b'");
+                res.extend(ascii::escape_default(byte).map(|c| c as char));
+                res.push('\'');
+                self.writer().word(&res[..])
+            }
+            ast::LitKind::Char(ch) => {
+                let mut res = String::from("'");
+                res.extend(ch.escape_default());
+                res.push('\'');
+                self.writer().word(&res[..])
+            }
+            ast::LitKind::Int(i, t) => {
+                match t {
+                    ast::LitIntType::Signed(st) => {
+                        self.writer().word(&st.val_to_string(i as i128))
+                    }
+                    ast::LitIntType::Unsigned(ut) => {
+                        self.writer().word(&ut.val_to_string(i))
+                    }
+                    ast::LitIntType::Unsuffixed => {
+                        self.writer().word(&format!("{}", i))
+                    }
                 }
-                commasep(s, consistent, *args, print_variant_arg);
-                pclose(s);
             }
-        }
-        ast::struct_variant_kind(struct_def) => {
-            head(s, ~"");
-            let generics = ast_util::empty_generics();
-            print_struct(s, struct_def, &generics, v.node.name, v.span);
+            ast::LitKind::Float(ref f, t) => {
+                self.writer().word(&format!("{}{}", &f, t.ty_to_string()))
+            }
+            ast::LitKind::FloatUnsuffixed(ref f) => self.writer().word(&f.as_str()),
+            ast::LitKind::Bool(val) => {
+                if val { self.writer().word("true") } else { self.writer().word("false") }
+            }
+            ast::LitKind::ByteStr(ref v) => {
+                let mut escaped: String = String::new();
+                for &ch in v.iter() {
+                    escaped.extend(ascii::escape_default(ch)
+                                         .map(|c| c as char));
+                }
+                self.writer().word(&format!("b\"{}\"", escaped))
+            }
         }
     }
-    match v.node.disr_expr {
-      Some(d) => {
-        space(s.s);
-        word_space(s, ~"=");
-        print_expr(s, d);
-      }
-      _ => ()
-    }
-}
-
-pub fn print_ty_method(s: @ps, m: &ast::ty_method) {
-    hardbreak_if_not_bol(s);
-    maybe_print_comment(s, m.span.lo);
-    print_outer_attributes(s, m.attrs);
-    print_ty_fn(s, None, None, None, m.purity, ast::Many,
-                &m.decl, Some(m.ident), Some(&m.generics),
-                Some(/*bad*/ copy m.self_ty.node));
-    word(s.s, ~";");
-}
 
-pub fn print_trait_method(s: @ps, m: &ast::trait_method) {
-    match *m {
-        required(ref ty_m) => print_ty_method(s, ty_m),
-        provided(m) => print_method(s, m)
+    fn print_string(&mut self, st: &str,
+                    style: ast::StrStyle) -> io::Result<()> {
+        let st = match style {
+            ast::StrStyle::Cooked => {
+                (format!("\"{}\"", parse::escape_default(st)))
+            }
+            ast::StrStyle::Raw(n) => {
+                (format!("r{delim}\"{string}\"{delim}",
+                         delim=repeat("#", n),
+                         string=st))
+            }
+        };
+        self.writer().word(&st[..])
     }
-}
 
-pub fn print_method(s: @ps, meth: @ast::method) {
-    hardbreak_if_not_bol(s);
-    maybe_print_comment(s, meth.span.lo);
-    print_outer_attributes(s, meth.attrs);
-    print_fn(s, &meth.decl, Some(meth.purity), AbiSet::Rust(),
-             meth.ident, &meth.generics, Some(meth.self_ty.node),
-             meth.vis);
-    word(s.s, ~" ");
-    print_block_with_attrs(s, &meth.body, meth.attrs);
-}
-
-pub fn print_outer_attributes(s: @ps, attrs: ~[ast::attribute]) {
-    let mut count = 0;
-    for attrs.each |attr| {
-        match attr.node.style {
-          ast::attr_outer => { print_attribute(s, *attr); count += 1; }
-          _ => {/* fallthrough */ }
-        }
+    fn print_inner_attributes(&mut self,
+                              attrs: &[ast::Attribute]) -> io::Result<()> {
+        self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, true)
     }
-    if count > 0 { hardbreak_if_not_bol(s); }
-}
 
-pub fn print_inner_attributes(s: @ps, attrs: ~[ast::attribute]) {
-    let mut count = 0;
-    for attrs.each |attr| {
-        match attr.node.style {
-          ast::attr_inner => {
-            print_attribute(s, *attr);
-            if !attr.node.is_sugared_doc {
-                word(s.s, ~";");
-            }
-            count += 1;
-          }
-          _ => {/* fallthrough */ }
-        }
+    fn print_inner_attributes_no_trailing_hardbreak(&mut self,
+                                                   attrs: &[ast::Attribute])
+                                                   -> io::Result<()> {
+        self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, false)
     }
-    if count > 0 { hardbreak_if_not_bol(s); }
-}
 
-pub fn print_attribute(s: @ps, attr: ast::attribute) {
-    hardbreak_if_not_bol(s);
-    maybe_print_comment(s, attr.span.lo);
-    if attr.node.is_sugared_doc {
-        let meta = attr::attr_meta(attr);
-        let comment = attr::get_meta_item_value_str(meta).get();
-        word(s.s, *comment);
-    } else {
-        word(s.s, ~"#[");
-        print_meta_item(s, attr.node.value);
-        word(s.s, ~"]");
+    fn print_outer_attributes(&mut self,
+                              attrs: &[ast::Attribute]) -> io::Result<()> {
+        self.print_either_attributes(attrs, ast::AttrStyle::Outer, false, true)
     }
-}
-
-
-pub fn print_stmt(s: @ps, st: ast::stmt) {
-    maybe_print_comment(s, st.span.lo);
-    match st.node {
-      ast::stmt_decl(decl, _) => {
-        print_decl(s, decl);
-      }
-      ast::stmt_expr(expr, _) => {
-        space_if_not_bol(s);
-        print_expr(s, expr);
-      }
-      ast::stmt_semi(expr, _) => {
-        space_if_not_bol(s);
-        print_expr(s, expr);
-        word(s.s, ~";");
-      }
-      ast::stmt_mac(ref mac, semi) => {
-        space_if_not_bol(s);
-        print_mac(s, (*mac));
-        if semi { word(s.s, ~";"); }
-      }
-    }
-    if parse::classify::stmt_ends_with_semi(st) { word(s.s, ~";"); }
-    maybe_print_trailing_comment(s, st.span, None);
-}
-
-pub fn print_block(s: @ps, blk: &ast::blk) {
-    print_possibly_embedded_block(s, blk, block_normal, indent_unit);
-}
-
-pub fn print_block_unclosed(s: @ps, blk: &ast::blk) {
-    print_possibly_embedded_block_(s, blk, block_normal, indent_unit, ~[],
-                                 false);
-}
-
-pub fn print_block_unclosed_indent(s: @ps, blk: &ast::blk, indented: uint) {
-    print_possibly_embedded_block_(s, blk, block_normal, indented, ~[],
-                                   false);
-}
-
-pub fn print_block_with_attrs(s: @ps,
-                              blk: &ast::blk,
-                              attrs: ~[ast::attribute]) {
-    print_possibly_embedded_block_(s, blk, block_normal, indent_unit, attrs,
-                                  true);
-}
-
-pub enum embed_type { block_block_fn, block_normal, }
 
-pub fn print_possibly_embedded_block(s: @ps,
-                                     blk: &ast::blk,
-                                     embedded: embed_type,
-                                     indented: uint) {
-    print_possibly_embedded_block_(
-        s, blk, embedded, indented, ~[], true);
-}
-
-pub fn print_possibly_embedded_block_(s: @ps,
-                                      blk: &ast::blk,
-                                      embedded: embed_type,
-                                      indented: uint,
-                                      attrs: ~[ast::attribute],
-                                      close_box: bool) {
-    match blk.node.rules {
-      ast::unsafe_blk => word_space(s, ~"unsafe"),
-      ast::default_blk => ()
-    }
-    maybe_print_comment(s, blk.span.lo);
-    let ann_node = node_block(s, blk);
-    (s.ann.pre)(ann_node);
-    match embedded {
-      block_block_fn => end(s),
-      block_normal => bopen(s)
-    }
-
-    print_inner_attributes(s, attrs);
-
-    for blk.node.view_items.each |vi| { print_view_item(s, *vi); }
-    for blk.node.stmts.each |st| {
-        print_stmt(s, **st);
-    }
-    match blk.node.expr {
-      Some(expr) => {
-        space_if_not_bol(s);
-        print_expr(s, expr);
-        maybe_print_trailing_comment(s, expr.span, Some(blk.span.hi));
-      }
-      _ => ()
-    }
-    bclose_maybe_open(s, blk.span, indented, close_box);
-    (s.ann.post)(ann_node);
-}
-
-pub fn print_if(s: @ps, test: @ast::expr, blk: &ast::blk,
-                elseopt: Option<@ast::expr>, chk: bool) {
-    head(s, ~"if");
-    if chk { word_nbsp(s, ~"check"); }
-    print_expr(s, test);
-    space(s.s);
-    print_block(s, blk);
-    fn do_else(s: @ps, els: Option<@ast::expr>) {
-        match els {
-          Some(_else) => {
-            match _else.node {
-              // "another else-if"
-              ast::expr_if(i, ref t, e) => {
-                cbox(s, indent_unit - 1u);
-                ibox(s, 0u);
-                word(s.s, ~" else if ");
-                print_expr(s, i);
-                space(s.s);
-                print_block(s, t);
-                do_else(s, e);
-              }
-              // "final else"
-              ast::expr_block(ref b) => {
-                cbox(s, indent_unit - 1u);
-                ibox(s, 0u);
-                word(s.s, ~" else ");
-                print_block(s, b);
-              }
-              // BLEAH, constraints would be great here
-              _ => {
-                  fail!(~"print_if saw if with weird alternative");
-              }
-            }
-          }
-          _ => {/* fall through */ }
-        }
-    }
-    do_else(s, elseopt);
-}
+    fn print_inner_attributes_inline(&mut self,
+                                     attrs: &[ast::Attribute]) -> io::Result<()> {
+        self.print_either_attributes(attrs, ast::AttrStyle::Inner, true, true)
+    }
 
-pub fn print_mac(s: @ps, m: ast::mac) {
-    match m.node {
-      ast::mac_invoc_tt(pth, ref tts) => {
-        print_path(s, pth, false);
-        word(s.s, ~"!");
-        popen(s);
-        print_tts(s, *tts);
-        pclose(s);
-      }
+    fn print_outer_attributes_inline(&mut self,
+                                     attrs: &[ast::Attribute]) -> io::Result<()> {
+        self.print_either_attributes(attrs, ast::AttrStyle::Outer, true, true)
     }
-}
 
-pub fn print_vstore(s: @ps, t: ast::vstore) {
-    match t {
-        ast::vstore_fixed(Some(i)) => word(s.s, fmt!("%u", i)),
-        ast::vstore_fixed(None) => word(s.s, ~"_"),
-        ast::vstore_uniq => word(s.s, ~"~"),
-        ast::vstore_box => word(s.s, ~"@"),
-        ast::vstore_slice(r) => {
-            word(s.s, ~"&");
-            print_opt_lifetime(s, r);
+    fn print_either_attributes(&mut self,
+                              attrs: &[ast::Attribute],
+                              kind: ast::AttrStyle,
+                              is_inline: bool,
+                              trailing_hardbreak: bool) -> io::Result<()> {
+        let mut count = 0;
+        for attr in attrs {
+            if attr.style == kind {
+                self.print_attribute_inline(attr, is_inline)?;
+                if is_inline {
+                    self.nbsp()?;
+                }
+                count += 1;
+            }
         }
+        if count > 0 && trailing_hardbreak && !is_inline {
+            self.hardbreak_if_not_bol()?;
+        }
+        Ok(())
     }
-}
 
-pub fn print_expr_vstore(s: @ps, t: ast::expr_vstore) {
-    match t {
-      ast::expr_vstore_uniq => word(s.s, ~"~"),
-      ast::expr_vstore_box => word(s.s, ~"@"),
-      ast::expr_vstore_mut_box => {
-        word(s.s, ~"@");
-        word(s.s, ~"mut");
-      }
-      ast::expr_vstore_slice => word(s.s, ~"&"),
-      ast::expr_vstore_mut_slice => {
-        word(s.s, ~"&");
-        word(s.s, ~"mut");
-      }
+    fn print_attribute(&mut self, attr: &ast::Attribute) -> io::Result<()> {
+        self.print_attribute_inline(attr, false)
     }
-}
 
-pub fn print_call_pre(s: @ps,
-                      sugar: ast::CallSugar,
-                      base_args: &mut ~[@ast::expr])
-                   -> Option<@ast::expr> {
-    match sugar {
-        ast::DoSugar => {
-            head(s, ~"do");
-            Some(base_args.pop())
+    fn print_attribute_inline(&mut self, attr: &ast::Attribute,
+                              is_inline: bool) -> io::Result<()> {
+        if !is_inline {
+            self.hardbreak_if_not_bol()?;
         }
-        ast::ForSugar => {
-            head(s, ~"for");
-            Some(base_args.pop())
+        self.maybe_print_comment(attr.span.lo)?;
+        if attr.is_sugared_doc {
+            self.writer().word(&attr.value_str().unwrap().as_str())?;
+            self.writer().hardbreak()
+        } else {
+            match attr.style {
+                ast::AttrStyle::Inner => self.writer().word("#![")?,
+                ast::AttrStyle::Outer => self.writer().word("#[")?,
+            }
+            if let Some(mi) = attr.meta() {
+                self.print_meta_item(&mi)?
+            } else {
+                for (i, segment) in attr.path.segments.iter().enumerate() {
+                    if i > 0 {
+                        self.writer().word("::")?
+                    }
+                    if segment.identifier.name != keywords::CrateRoot.name() &&
+                       segment.identifier.name != keywords::DollarCrate.name() {
+                        self.writer().word(&segment.identifier.name.as_str())?;
+                    }
+                }
+                self.writer().space()?;
+                self.print_tts(attr.tokens.clone())?;
+            }
+            self.writer().word("]")
         }
-        ast::NoSugar => None
     }
-}
 
-pub fn print_call_post(s: @ps,
-                       sugar: ast::CallSugar,
-                       blk: &Option<@ast::expr>,
-                       base_args: &mut ~[@ast::expr]) {
-    if sugar == ast::NoSugar || !base_args.is_empty() {
-        popen(s);
-        commasep_exprs(s, inconsistent, *base_args);
-        pclose(s);
-    }
-    if sugar != ast::NoSugar {
-        nbsp(s);
-        match blk.get().node {
-          // need to handle closures specifically
-          ast::expr_do_body(e) | ast::expr_loop_body(e) => {
-            end(s); // we close our head box; closure
-                    // will create it's own.
-            print_expr(s, e);
-            end(s); // close outer box, as closures don't
-          }
-          _ => {
-            // not sure if this can happen.
-            print_expr(s, blk.get());
-          }
+    fn print_meta_list_item(&mut self, item: &ast::NestedMetaItem) -> io::Result<()> {
+        match item.node {
+            ast::NestedMetaItemKind::MetaItem(ref mi) => {
+                self.print_meta_item(mi)
+            },
+            ast::NestedMetaItemKind::Literal(ref lit) => {
+                self.print_literal(lit)
+            }
         }
     }
-}
 
-pub fn print_expr(s: @ps, &&expr: @ast::expr) {
-    fn print_field(s: @ps, field: ast::field) {
-        ibox(s, indent_unit);
-        if field.node.mutbl == ast::m_mutbl { word_nbsp(s, ~"mut"); }
-        print_ident(s, field.node.ident);
-        word_space(s, ~":");
-        print_expr(s, field.node.expr);
-        end(s);
-    }
-    fn get_span(field: ast::field) -> codemap::span { return field.span; }
-
-    maybe_print_comment(s, expr.span.lo);
-    ibox(s, indent_unit);
-    let ann_node = node_expr(s, expr);
-    (s.ann.pre)(ann_node);
-    match expr.node {
-        ast::expr_vstore(e, v) => {
-            print_expr_vstore(s, v);
-            print_expr(s, e);
-        },
-      ast::expr_vec(ref exprs, mutbl) => {
-        ibox(s, indent_unit);
-        word(s.s, ~"[");
-        if mutbl == ast::m_mutbl {
-            word(s.s, ~"mut");
-            if exprs.len() > 0u { nbsp(s); }
-        }
-        commasep_exprs(s, inconsistent, *exprs);
-        word(s.s, ~"]");
-        end(s);
-      }
-
-      ast::expr_repeat(element, count, mutbl) => {
-        ibox(s, indent_unit);
-        word(s.s, ~"[");
-        if mutbl == ast::m_mutbl {
-            word(s.s, ~"mut");
-            nbsp(s);
-        }
-        print_expr(s, element);
-        word(s.s, ~",");
-        word(s.s, ~"..");
-        print_expr(s, count);
-        word(s.s, ~"]");
-        end(s);
-      }
-
-      ast::expr_struct(path, ref fields, wth) => {
-        print_path(s, path, true);
-        word(s.s, ~"{");
-        commasep_cmnt(s, consistent, (*fields), print_field, get_span);
-        match wth {
-            Some(expr) => {
-                ibox(s, indent_unit);
-                word(s.s, ~",");
-                space(s.s);
-                word(s.s, ~"..");
-                print_expr(s, expr);
-                end(s);
-            }
-            _ => (word(s.s, ~","))
-        }
-        word(s.s, ~"}");
-      }
-      ast::expr_tup(ref exprs) => {
-        popen(s);
-        commasep_exprs(s, inconsistent, *exprs);
-        if exprs.len() == 1 {
-            word(s.s, ~",");
-        }
-        pclose(s);
-      }
-      ast::expr_call(func, ref args, sugar) => {
-        let mut base_args = copy *args;
-        let blk = print_call_pre(s, sugar, &mut base_args);
-        print_expr(s, func);
-        print_call_post(s, sugar, &blk, &mut base_args);
-      }
-      ast::expr_method_call(func, ident, ref tys, ref args, sugar) => {
-        let mut base_args = copy *args;
-        let blk = print_call_pre(s, sugar, &mut base_args);
-        print_expr(s, func);
-        word(s.s, ~".");
-        print_ident(s, ident);
-        if tys.len() > 0u {
-            word(s.s, ~"::<");
-            commasep(s, inconsistent, *tys, print_type);
-            word(s.s, ~">");
-        }
-        print_call_post(s, sugar, &blk, &mut base_args);
-      }
-      ast::expr_binary(op, lhs, rhs) => {
-        print_expr(s, lhs);
-        space(s.s);
-        word_space(s, ast_util::binop_to_str(op));
-        print_expr(s, rhs);
-      }
-      ast::expr_unary(op, expr) => {
-        word(s.s, ast_util::unop_to_str(op));
-        print_expr(s, expr);
-      }
-      ast::expr_addr_of(m, expr) => {
-        word(s.s, ~"&");
-        print_mutability(s, m);
-        // Avoid `& &e` => `&&e`.
-        match (m, &expr.node) {
-            (ast::m_imm, &ast::expr_addr_of(*)) => space(s.s),
-            _ => { }
-        }
-        print_expr(s, expr);
-      }
-      ast::expr_lit(lit) => print_literal(s, lit),
-      ast::expr_cast(expr, ty) => {
-        print_expr(s, expr);
-        space(s.s);
-        word_space(s, ~"as");
-        print_type(s, ty);
-      }
-      ast::expr_if(test, ref blk, elseopt) => {
-        print_if(s, test, blk, elseopt, false);
-      }
-      ast::expr_while(test, ref blk) => {
-        head(s, ~"while");
-        print_expr(s, test);
-        space(s.s);
-        print_block(s, blk);
-      }
-      ast::expr_loop(ref blk, opt_ident) => {
-        head(s, ~"loop");
-        space(s.s);
-        for opt_ident.each |ident| {
-            print_ident(s, *ident);
-            word_space(s, ~":");
-        }
-        print_block(s, blk);
-      }
-      ast::expr_match(expr, ref arms) => {
-        cbox(s, match_indent_unit);
-        ibox(s, 4);
-        word_nbsp(s, ~"match");
-        print_expr(s, expr);
-        space(s.s);
-        bopen(s);
-        let len = (*arms).len();
-        for (*arms).eachi |i, arm| {
-            space(s.s);
-            cbox(s, match_indent_unit);
-            ibox(s, 0u);
-            let mut first = true;
-            for arm.pats.each |p| {
-                if first {
-                    first = false;
-                } else { space(s.s); word_space(s, ~"|"); }
-                print_refutable_pat(s, *p);
-            }
-            space(s.s);
-            match arm.guard {
-              Some(e) => {
-                word_space(s, ~"if");
-                print_expr(s, e);
-                space(s.s);
-              }
-              None => ()
-            }
-            word_space(s, ~"=>");
-
-            // Extract the expression from the extra block the parser adds
-            // in the case of foo => expr
-            if arm.body.node.view_items.is_empty() &&
-                arm.body.node.stmts.is_empty() &&
-                arm.body.node.rules == ast::default_blk &&
-                arm.body.node.expr.is_some()
-            {
-                match arm.body.node.expr {
-                    Some(expr) => {
-                        match expr.node {
-                            ast::expr_block(ref blk) => {
-                                // the block will close the pattern's ibox
-                                print_block_unclosed_indent(
-                                    s, blk, match_indent_unit);
-                            }
-                            _ => {
-                                end(s); // close the ibox for the pattern
-                                print_expr(s, expr);
-                            }
-                        }
-                        if !expr_is_simple_block(expr)
-                            && i < len - 1 {
-                            word(s.s, ~",");
-                        }
-                        end(s); // close enclosing cbox
+    fn print_meta_item(&mut self, item: &ast::MetaItem) -> io::Result<()> {
+        self.ibox(INDENT_UNIT)?;
+        match item.node {
+            ast::MetaItemKind::Word => {
+                self.writer().word(&item.name.as_str())?;
+            }
+            ast::MetaItemKind::NameValue(ref value) => {
+                self.word_space(&item.name.as_str())?;
+                self.word_space("=")?;
+                self.print_literal(value)?;
+            }
+            ast::MetaItemKind::List(ref items) => {
+                self.writer().word(&item.name.as_str())?;
+                self.popen()?;
+                self.commasep(Consistent,
+                              &items[..],
+                              |s, i| s.print_meta_list_item(i))?;
+                self.pclose()?;
+            }
+        }
+        self.end()
+    }
+
+    /// This doesn't deserve to be called "pretty" printing, but it should be
+    /// meaning-preserving. A quick hack that might help would be to look at the
+    /// spans embedded in the TTs to decide where to put spaces and newlines.
+    /// But it'd be better to parse these according to the grammar of the
+    /// appropriate macro, transcribe back into the grammar we just parsed from,
+    /// and then pretty-print the resulting AST nodes (so, e.g., we print
+    /// expression arguments as expressions). It can be done! I think.
+    fn print_tt(&mut self, tt: tokenstream::TokenTree) -> io::Result<()> {
+        match tt {
+            TokenTree::Token(_, ref tk) => {
+                self.writer().word(&token_to_string(tk))?;
+                match *tk {
+                    parse::token::DocComment(..) => {
+                        self.writer().hardbreak()
                     }
-                    None => fail!()
+                    _ => Ok(())
                 }
-            } else {
-                // the block will close the pattern's ibox
-                print_block_unclosed_indent(s, &arm.body, match_indent_unit);
-            }
-        }
-        bclose_(s, expr.span, match_indent_unit);
-      }
-      ast::expr_fn_block(ref decl, ref body) => {
-        // in do/for blocks we don't want to show an empty
-        // argument list, but at this point we don't know which
-        // we are inside.
-        //
-        // if !decl.inputs.is_empty() {
-        print_fn_block_args(s, decl);
-        space(s.s);
-        // }
-        assert!(body.node.stmts.is_empty());
-        assert!(body.node.expr.is_some());
-        // we extract the block, so as not to create another set of boxes
-        match body.node.expr.get().node {
-            ast::expr_block(ref blk) => {
-                print_block_unclosed(s, blk);
             }
-            _ => {
-                // this is a bare expression
-                print_expr(s, body.node.expr.get());
-                end(s); // need to close a box
-            }
-        }
-        // a box will be closed by print_expr, but we didn't want an overall
-        // wrapper so we closed the corresponding opening. so create an
-        // empty box to satisfy the close.
-        ibox(s, 0);
-      }
-      ast::expr_loop_body(body) => {
-        print_expr(s, body);
-      }
-      ast::expr_do_body(body) => {
-        print_expr(s, body);
-      }
-      ast::expr_block(ref blk) => {
-        // containing cbox, will be closed by print-block at }
-        cbox(s, indent_unit);
-        // head-box, will be closed by print-block after {
-        ibox(s, 0u);
-        print_block(s, blk);
-      }
-      ast::expr_copy(e) => { word_space(s, ~"copy"); print_expr(s, e); }
-      ast::expr_assign(lhs, rhs) => {
-        print_expr(s, lhs);
-        space(s.s);
-        word_space(s, ~"=");
-        print_expr(s, rhs);
-      }
-      ast::expr_swap(lhs, rhs) => {
-        print_expr(s, lhs);
-        space(s.s);
-        word_space(s, ~"<->");
-        print_expr(s, rhs);
-      }
-      ast::expr_assign_op(op, lhs, rhs) => {
-        print_expr(s, lhs);
-        space(s.s);
-        word(s.s, ast_util::binop_to_str(op));
-        word_space(s, ~"=");
-        print_expr(s, rhs);
-      }
-      ast::expr_field(expr, id, ref tys) => {
-        print_expr(s, expr);
-        word(s.s, ~".");
-        print_ident(s, id);
-        if tys.len() > 0u {
-            word(s.s, ~"::<");
-            commasep(s, inconsistent, *tys, print_type);
-            word(s.s, ~">");
-        }
-      }
-      ast::expr_index(expr, index) => {
-        print_expr(s, expr);
-        word(s.s, ~"[");
-        print_expr(s, index);
-        word(s.s, ~"]");
-      }
-      ast::expr_path(path) => print_path(s, path, true),
-      ast::expr_break(opt_ident) => {
-        word(s.s, ~"break");
-        space(s.s);
-        for opt_ident.each |ident| { print_ident(s, *ident); space(s.s) }
-      }
-      ast::expr_again(opt_ident) => {
-        word(s.s, ~"loop");
-        space(s.s);
-        for opt_ident.each |ident| { print_ident(s, *ident); space(s.s) }
-      }
-      ast::expr_ret(result) => {
-        word(s.s, ~"return");
-        match result {
-          Some(expr) => { word(s.s, ~" "); print_expr(s, expr); }
-          _ => ()
-        }
-      }
-      ast::expr_log(lexp, expr) => {
-        word(s.s, ~"__log");
-        popen(s);
-        print_expr(s, lexp);
-        word(s.s, ~",");
-        space_if_not_bol(s);
-        print_expr(s, expr);
-        pclose(s);
-      }
-      ast::expr_inline_asm(a) => {
-        if a.volatile {
-            word(s.s, ~"__volatile__ asm!");
-        } else {
-            word(s.s, ~"asm!");
-        }
-        popen(s);
-        print_string(s, *a.asm);
-        word_space(s, ~":");
-        for a.outputs.each |&(co, o)| {
-            print_string(s, *co);
-            popen(s);
-            print_expr(s, o);
-            pclose(s);
-            word_space(s, ~",");
-        }
-        word_space(s, ~":");
-        for a.inputs.each |&(co, o)| {
-            print_string(s, *co);
-            popen(s);
-            print_expr(s, o);
-            pclose(s);
-            word_space(s, ~",");
-        }
-        word_space(s, ~":");
-        print_string(s, *a.clobbers);
-        pclose(s);
-      }
-      ast::expr_mac(ref m) => print_mac(s, (*m)),
-      ast::expr_paren(e) => {
-          popen(s);
-          print_expr(s, e);
-          pclose(s);
-      }
-    }
-    (s.ann.post)(ann_node);
-    end(s);
-}
-
-pub fn print_local_decl(s: @ps, loc: @ast::local) {
-    print_irrefutable_pat(s, loc.node.pat);
-    match loc.node.ty.node {
-      ast::ty_infer => (),
-      _ => { word_space(s, ~":"); print_type(s, loc.node.ty); }
-    }
-}
-
-pub fn print_decl(s: @ps, decl: @ast::decl) {
-    maybe_print_comment(s, decl.span.lo);
-    match decl.node {
-      ast::decl_local(ref locs) => {
-        space_if_not_bol(s);
-        ibox(s, indent_unit);
-        word_nbsp(s, ~"let");
-
-        // if any are mut, all are mut
-        if locs.any(|l| l.node.is_mutbl) {
-            assert!(locs.all(|l| l.node.is_mutbl));
-            word_nbsp(s, ~"mut");
-        }
-
-        fn print_local(s: @ps, &&loc: @ast::local) {
-            ibox(s, indent_unit);
-            print_local_decl(s, loc);
-            end(s);
-            match loc.node.init {
-              Some(init) => {
-                nbsp(s);
-                word_space(s, ~"=");
-                print_expr(s, init);
-              }
-              _ => ()
-            }
-        }
-        commasep(s, consistent, *locs, print_local);
-        end(s);
-      }
-      ast::decl_item(item) => print_item(s, item)
-    }
-}
-
-pub fn print_ident(s: @ps, ident: ast::ident) {
-    word(s.s, *s.intr.get(ident));
-}
-
-pub fn print_for_decl(s: @ps, loc: @ast::local, coll: @ast::expr) {
-    print_local_decl(s, loc);
-    space(s.s);
-    word_space(s, ~"in");
-    print_expr(s, coll);
-}
-
-pub fn print_path(s: @ps, &&path: @ast::path, colons_before_params: bool) {
-    maybe_print_comment(s, path.span.lo);
-    if path.global { word(s.s, ~"::"); }
-    let mut first = true;
-    for path.idents.each |id| {
-        if first { first = false; } else { word(s.s, ~"::"); }
-        print_ident(s, *id);
+            TokenTree::Delimited(_, ref delimed) => {
+                self.writer().word(&token_to_string(&delimed.open_token()))?;
+                self.writer().space()?;
+                self.print_tts(delimed.stream())?;
+                self.writer().space()?;
+                self.writer().word(&token_to_string(&delimed.close_token()))
+            },
+        }
     }
-    if path.rp.is_some() || !path.types.is_empty() {
-        if colons_before_params { word(s.s, ~"::"); }
 
-        if path.rp.is_some() || !path.types.is_empty() {
-            word(s.s, ~"<");
-
-            for path.rp.each |r| {
-                print_lifetime(s, *r);
-                if !path.types.is_empty() {
-                    word_space(s, ~",");
-                }
+    fn print_tts(&mut self, tts: tokenstream::TokenStream) -> io::Result<()> {
+        self.ibox(0)?;
+        for (i, tt) in tts.into_trees().enumerate() {
+            if i != 0 {
+                self.writer().space()?;
             }
-
-            commasep(s, inconsistent, path.types, print_type);
-
-            word(s.s, ~">");
+            self.print_tt(tt)?;
         }
+        self.end()
     }
-}
-
-pub fn print_irrefutable_pat(s: @ps, &&pat: @ast::pat) {
-    print_pat(s, pat, false)
-}
-
-pub fn print_refutable_pat(s: @ps, &&pat: @ast::pat) {
-    print_pat(s, pat, true)
-}
-
-pub fn print_pat(s: @ps, &&pat: @ast::pat, refutable: bool) {
-    maybe_print_comment(s, pat.span.lo);
-    let ann_node = node_pat(s, pat);
-    (s.ann.pre)(ann_node);
-    /* Pat isn't normalized, but the beauty of it
-     is that it doesn't matter */
-    match pat.node {
-      ast::pat_wild => word(s.s, ~"_"),
-      ast::pat_ident(binding_mode, path, sub) => {
-          if refutable {
-              match binding_mode {
-                  ast::bind_by_ref(mutbl) => {
-                      word_nbsp(s, ~"ref");
-                      print_mutability(s, mutbl);
-                  }
-                  ast::bind_by_copy => {
-                      word_nbsp(s, ~"copy");
-                  }
-                  ast::bind_infer => {}
-              }
-          }
-          print_path(s, path, true);
-          match sub {
-              Some(p) => {
-                  word(s.s, ~"@");
-                  print_pat(s, p, refutable);
-              }
-              None => ()
-          }
-      }
-      ast::pat_enum(path, ref args_) => {
-        print_path(s, path, true);
-        match *args_ {
-          None => word(s.s, ~"(*)"),
-          Some(ref args) => {
-            if !args.is_empty() {
-              popen(s);
-              commasep(s, inconsistent, *args,
-                       |s, p| print_pat(s, p, refutable));
-              pclose(s);
-            } else { }
-          }
-        }
-      }
-      ast::pat_struct(path, fields, etc) => {
-        print_path(s, path, true);
-        word(s.s, ~"{");
-        fn print_field(s: @ps, f: ast::field_pat, refutable: bool) {
-            cbox(s, indent_unit);
-            print_ident(s, f.ident);
-            word_space(s, ~":");
-            print_pat(s, f.pat, refutable);
-            end(s);
-        }
-        fn get_span(f: ast::field_pat) -> codemap::span { return f.pat.span; }
-        commasep_cmnt(s, consistent, fields,
-                      |s, f| print_field(s,f,refutable),
-                      get_span);
-        if etc {
-            if vec::len(fields) != 0u { word_space(s, ~","); }
-            word(s.s, ~"_");
-        }
-        word(s.s, ~"}");
-      }
-      ast::pat_tup(elts) => {
-        popen(s);
-        commasep(s, inconsistent, elts, |s, p| print_pat(s, p, refutable));
-        if elts.len() == 1 {
-            word(s.s, ~",");
-        }
-        pclose(s);
-      }
-      ast::pat_box(inner) => {
-          word(s.s, ~"@");
-          print_pat(s, inner, refutable);
-      }
-      ast::pat_uniq(inner) => {
-          word(s.s, ~"~");
-          print_pat(s, inner, refutable);
-      }
-      ast::pat_region(inner) => {
-          word(s.s, ~"&");
-          print_pat(s, inner, refutable);
-      }
-      ast::pat_lit(e) => print_expr(s, e),
-      ast::pat_range(begin, end) => {
-        print_expr(s, begin);
-        space(s.s);
-        word(s.s, ~"..");
-        print_expr(s, end);
-      }
-      ast::pat_vec(before, slice, after) => {
-        word(s.s, ~"[");
-        do commasep(s, inconsistent, before) |s, p| {
-            print_pat(s, p, refutable);
-        }
-        for slice.each |&p| {
-            if !before.is_empty() { word_space(s, ~","); }
-            word(s.s, ~"..");
-            print_pat(s, p, refutable);
-            if !after.is_empty() { word_space(s, ~","); }
-        }
-        do commasep(s, inconsistent, after) |s, p| {
-            print_pat(s, p, refutable);
-        }
-        word(s.s, ~"]");
-      }
-    }
-    (s.ann.post)(ann_node);
-}
 
-// Returns whether it printed anything
-pub fn print_self_ty(s: @ps, self_ty: ast::self_ty_) -> bool {
-    match self_ty {
-        ast::sty_static => { return false; }
-        ast::sty_value => { word(s.s, ~"self"); }
-        ast::sty_region(lt, m) => {
-            word(s.s, ~"&");
-            print_opt_lifetime(s, lt);
-            print_mutability(s, m);
-            word(s.s, ~"self");
-        }
-        ast::sty_box(m) => {
-            word(s.s, ~"@"); print_mutability(s, m); word(s.s, ~"self");
-        }
-        ast::sty_uniq(m) => {
-            word(s.s, ~"~"); print_mutability(s, m); word(s.s, ~"self");
-        }
+    fn space_if_not_bol(&mut self) -> io::Result<()> {
+        if !self.is_bol() { self.writer().space()?; }
+        Ok(())
     }
-    return true;
-}
 
-pub fn print_fn(s: @ps,
-                decl: &ast::fn_decl,
-                purity: Option<ast::purity>,
-                abis: AbiSet,
-                name: ast::ident,
-                generics: &ast::Generics,
-                opt_self_ty: Option<ast::self_ty_>,
-                vis: ast::visibility) {
-    head(s, ~"");
-    print_fn_header_info(s, opt_self_ty, purity, abis, ast::Many, None, vis);
-    nbsp(s);
-    print_ident(s, name);
-    print_generics(s, generics);
-    print_fn_args_and_ret(s, decl, opt_self_ty);
+    fn nbsp(&mut self) -> io::Result<()> { self.writer().word(" ") }
 }
 
-pub fn print_fn_args(s: @ps, decl: &ast::fn_decl,
-                 opt_self_ty: Option<ast::self_ty_>) {
-    // It is unfortunate to duplicate the commasep logic, but we we want the
-    // self type and the args all in the same box.
-    box(s, 0u, inconsistent);
-    let mut first = true;
-    for opt_self_ty.each |self_ty| {
-        first = !print_self_ty(s, *self_ty);
+impl<'a> PrintState<'a> for State<'a> {
+    fn writer(&mut self) -> &mut pp::Printer<'a> {
+        &mut self.s
     }
 
-    for decl.inputs.each |arg| {
-        if first { first = false; } else { word_space(s, ~","); }
-        print_arg(s, *arg);
+    fn boxes(&mut self) -> &mut Vec<pp::Breaks> {
+        &mut self.boxes
     }
 
-    end(s);
-}
-
-pub fn print_fn_args_and_ret(s: @ps, decl: &ast::fn_decl,
-                             opt_self_ty: Option<ast::self_ty_>) {
-    popen(s);
-    print_fn_args(s, decl, opt_self_ty);
-    pclose(s);
-
-    maybe_print_comment(s, decl.output.span.lo);
-    match decl.output.node {
-        ast::ty_nil => {}
-        _ => {
-            space_if_not_bol(s);
-            word_space(s, ~"->");
-            print_type(s, decl.output);
-        }
+    fn comments(&mut self) -> &mut Option<Vec<comments::Comment>> {
+        &mut self.comments
     }
-}
 
-pub fn print_fn_block_args(s: @ps, decl: &ast::fn_decl) {
-    word(s.s, ~"|");
-    print_fn_args(s, decl, None);
-    word(s.s, ~"|");
-
-    match decl.output.node {
-        ast::ty_infer => {}
-        _ => {
-            space_if_not_bol(s);
-            word_space(s, ~"->");
-            print_type(s, decl.output);
-        }
+    fn cur_cmnt(&mut self) -> &mut usize {
+        &mut self.cur_cmnt
     }
 
-    maybe_print_comment(s, decl.output.span.lo);
-}
-
-pub fn mode_to_str(m: ast::mode) -> ~str {
-    match m {
-      ast::expl(ast::by_ref) => ~"&&",
-      ast::expl(ast::by_copy) => ~"+",
-      ast::infer(_) => ~""
+    fn cur_lit(&mut self) -> Option<&comments::Literal> {
+        self.literals.peek()
     }
-}
-
-pub fn print_arg_mode(s: @ps, m: ast::mode) {
-    let ms = mode_to_str(m);
-    if ms != ~"" { word(s.s, ms); }
-}
-
-pub fn print_bounds(s: @ps, bounds: @OptVec<ast::TyParamBound>) {
-    if !bounds.is_empty() {
-        word(s.s, ~":");
-        let mut first = true;
-        for bounds.each |bound| {
-            nbsp(s);
-            if first {
-                first = false;
-            } else {
-                word_space(s, ~"+");
-            }
 
-            match *bound {
-                TraitTyParamBound(ty) => print_type(s, ty),
-                RegionTyParamBound => word(s.s, ~"'static"),
-            }
-        }
+    fn bump_lit(&mut self) -> Option<comments::Literal> {
+        self.literals.next()
     }
 }
 
-pub fn print_lifetime(s: @ps, &&lifetime: &ast::Lifetime) {
-    word(s.s, ~"'");
-    print_ident(s, lifetime.ident);
-}
-
-pub fn print_generics(s: @ps, &&generics: &ast::Generics) {
-    let total = generics.lifetimes.len() + generics.ty_params.len();
-    if total > 0 {
-        word(s.s, ~"<");
-        fn print_item(s: @ps, generics: &ast::Generics, idx: uint) {
-            if idx < generics.lifetimes.len() {
-                let lifetime = generics.lifetimes.get(idx);
-                print_lifetime(s, lifetime);
-            } else {
-                let idx = idx - generics.lifetimes.len();
-                let param = generics.ty_params.get(idx);
-                print_ident(s, param.ident);
-                print_bounds(s, param.bounds);
-            }
-        }
-
-        let mut ints = ~[];
-        for uint::range(0, total) |i| {
-            ints.push(i);
-        }
-
-        commasep(s, inconsistent, ints,
-                 |s, i| print_item(s, generics, i));
-        word(s.s, ~">");
+impl<'a> State<'a> {
+    pub fn cbox(&mut self, u: usize) -> io::Result<()> {
+        self.boxes.push(pp::Breaks::Consistent);
+        self.s.cbox(u)
     }
-}
-
-pub fn print_meta_item(s: @ps, &&item: @ast::meta_item) {
-    ibox(s, indent_unit);
-    match item.node {
-      ast::meta_word(name) => word(s.s, *name),
-      ast::meta_name_value(name, value) => {
-        word_space(s, *name);
-        word_space(s, ~"=");
-        print_literal(s, @value);
-      }
-      ast::meta_list(name, ref items) => {
-        word(s.s, *name);
-        popen(s);
-        commasep(
-            s,
-            consistent,
-            /* FIXME (#2543) */ copy *items,
-            print_meta_item
-        );
-        pclose(s);
-      }
-    }
-    end(s);
-}
-
-pub fn print_view_path(s: @ps, &&vp: @ast::view_path) {
-    match vp.node {
-      ast::view_path_simple(ident, path, namespace, _) => {
-        if namespace == ast::module_ns {
-            word_space(s, ~"mod");
-        }
-        if path.idents[vec::len(path.idents)-1u] != ident {
-            print_ident(s, ident);
-            space(s.s);
-            word_space(s, ~"=");
-        }
-        print_path(s, path, false);
-      }
 
-      ast::view_path_glob(path, _) => {
-        print_path(s, path, false);
-        word(s.s, ~"::*");
-      }
+    pub fn word_nbsp(&mut self, w: &str) -> io::Result<()> {
+        self.s.word(w)?;
+        self.nbsp()
+    }
 
-      ast::view_path_list(path, ref idents, _) => {
-        print_path(s, path, false);
-        word(s.s, ~"::{");
-        do commasep(s, inconsistent, (*idents)) |s, w| {
-            print_ident(s, w.node.name);
+    pub fn head(&mut self, w: &str) -> io::Result<()> {
+        // outer-box is consistent
+        self.cbox(INDENT_UNIT)?;
+        // head-box is inconsistent
+        self.ibox(w.len() + 1)?;
+        // keyword that starts the head
+        if !w.is_empty() {
+            self.word_nbsp(w)?;
         }
-        word(s.s, ~"}");
-      }
+        Ok(())
     }
-}
-
-pub fn print_view_paths(s: @ps, vps: &[@ast::view_path]) {
-    commasep(s, inconsistent, vps, print_view_path);
-}
 
-pub fn print_view_item(s: @ps, item: @ast::view_item) {
-    hardbreak_if_not_bol(s);
-    maybe_print_comment(s, item.span.lo);
-    print_outer_attributes(s, item.attrs);
-    print_visibility(s, item.vis);
-    match item.node {
-        ast::view_item_extern_mod(id, mta, _) => {
-            head(s, ~"extern mod");
-            print_ident(s, id);
-            if !mta.is_empty() {
-                popen(s);
-                commasep(s, consistent, mta, print_meta_item);
-                pclose(s);
-            }
-        }
+    pub fn bopen(&mut self) -> io::Result<()> {
+        self.s.word("{")?;
+        self.end() // close the head-box
+    }
 
-        ast::view_item_use(ref vps) => {
-            head(s, ~"use");
-            print_view_paths(s, *vps);
+    pub fn bclose_(&mut self, span: syntax_pos::Span,
+                   indented: usize) -> io::Result<()> {
+        self.bclose_maybe_open(span, indented, true)
+    }
+    pub fn bclose_maybe_open(&mut self, span: syntax_pos::Span,
+                             indented: usize, close_box: bool) -> io::Result<()> {
+        self.maybe_print_comment(span.hi)?;
+        self.break_offset_if_not_bol(1, -(indented as isize))?;
+        self.s.word("}")?;
+        if close_box {
+            self.end()?; // close the outer-box
         }
+        Ok(())
     }
-    word(s.s, ~";");
-    end(s); // end inner head-block
-    end(s); // end outer head-block
-}
-
-pub fn print_mutability(s: @ps, mutbl: ast::mutability) {
-    match mutbl {
-      ast::m_mutbl => word_nbsp(s, ~"mut"),
-      ast::m_const => word_nbsp(s, ~"const"),
-      ast::m_imm => {/* nothing */ }
+    pub fn bclose(&mut self, span: syntax_pos::Span) -> io::Result<()> {
+        self.bclose_(span, INDENT_UNIT)
     }
-}
 
-pub fn print_mt(s: @ps, mt: &ast::mt) {
-    print_mutability(s, mt.mutbl);
-    print_type(s, mt.ty);
-}
+    pub fn in_cbox(&self) -> bool {
+        match self.boxes.last() {
+            Some(&last_box) => last_box == pp::Breaks::Consistent,
+            None => false
+        }
+    }
 
-pub fn print_arg(s: @ps, input: ast::arg) {
-    ibox(s, indent_unit);
-    print_arg_mode(s, input.mode);
-    if input.is_mutbl {
-        word_space(s, ~"mut");
-    }
-    match input.ty.node {
-      ast::ty_infer => print_irrefutable_pat(s, input.pat),
-      _ => {
-        match input.pat.node {
-            ast::pat_ident(_, path, _) if
-                path.idents.len() == 1 &&
-                path.idents[0] == parse::token::special_idents::invalid => {
-                // Do nothing.
+    pub fn break_offset_if_not_bol(&mut self, n: usize,
+                                   off: isize) -> io::Result<()> {
+        if !self.is_bol() {
+            self.s.break_offset(n, off)
+        } else {
+            if off != 0 && self.s.last_token().is_hardbreak_tok() {
+                // We do something pretty sketchy here: tuck the nonzero
+                // offset-adjustment we were going to deposit along with the
+                // break into the previous hardbreak.
+                self.s.replace_last_token(pp::Printer::hardbreak_tok_offset(off));
             }
-            _ => {
-                print_irrefutable_pat(s, input.pat);
-                word(s.s, ~":");
-                space(s.s);
+            Ok(())
+        }
+    }
+
+    // Synthesizes a comment that was not textually present in the original source
+    // file.
+    pub fn synth_comment(&mut self, text: String) -> io::Result<()> {
+        self.s.word("/*")?;
+        self.s.space()?;
+        self.s.word(&text[..])?;
+        self.s.space()?;
+        self.s.word("*/")
+    }
+
+
+
+    pub fn commasep_cmnt<T, F, G>(&mut self,
+                                  b: Breaks,
+                                  elts: &[T],
+                                  mut op: F,
+                                  mut get_span: G) -> io::Result<()> where
+        F: FnMut(&mut State, &T) -> io::Result<()>,
+        G: FnMut(&T) -> syntax_pos::Span,
+    {
+        self.rbox(0, b)?;
+        let len = elts.len();
+        let mut i = 0;
+        for elt in elts {
+            self.maybe_print_comment(get_span(elt).hi)?;
+            op(self, elt)?;
+            i += 1;
+            if i < len {
+                self.s.word(",")?;
+                self.maybe_print_trailing_comment(get_span(elt),
+                                                  Some(get_span(&elts[i]).hi))?;
+                self.space_if_not_bol()?;
             }
         }
-        print_type(s, input.ty);
-      }
+        self.end()
     }
-    end(s);
-}
-
-pub fn print_ty_fn(s: @ps,
-                   opt_abis: Option<AbiSet>,
-                   opt_sigil: Option<ast::Sigil>,
-                   opt_region: Option<@ast::Lifetime>,
-                   purity: ast::purity,
-                   onceness: ast::Onceness,
-                   decl: &ast::fn_decl,
-                   id: Option<ast::ident>,
-                   generics: Option<&ast::Generics>,
-                   opt_self_ty: Option<ast::self_ty_>) {
-    ibox(s, indent_unit);
-
-    // Duplicates the logic in `print_fn_header_info()`.  This is because that
-    // function prints the sigil in the wrong place.  That should be fixed.
-    print_extern_opt_abis(s, opt_abis);
-    print_opt_sigil(s, opt_sigil);
-    print_opt_lifetime(s, opt_region);
-    print_purity(s, purity);
-    print_onceness(s, onceness);
-    word(s.s, ~"fn");
-    match id { Some(id) => { word(s.s, ~" "); print_ident(s, id); } _ => () }
-    match generics { Some(g) => print_generics(s, g), _ => () }
-    zerobreak(s.s);
-
-    popen(s);
-    // It is unfortunate to duplicate the commasep logic, but we we want the
-    // self type and the args all in the same box.
-    box(s, 0u, inconsistent);
-    let mut first = true;
-    for opt_self_ty.each |self_ty| {
-        first = !print_self_ty(s, *self_ty);
-    }
-    for decl.inputs.each |arg| {
-        if first { first = false; } else { word_space(s, ~","); }
-        print_arg(s, *arg);
-    }
-    end(s);
-    pclose(s);
-
-    maybe_print_comment(s, decl.output.span.lo);
-
-    match decl.output.node {
-        ast::ty_nil => {}
-        _ => {
-            space_if_not_bol(s);
-            ibox(s, indent_unit);
-            word_space(s, ~"->");
-            if decl.cf == ast::noreturn { word_nbsp(s, ~"!"); }
-            else { print_type(s, decl.output); }
-            end(s);
-        }
-    }
-
-    end(s);
-}
 
-pub fn maybe_print_trailing_comment(s: @ps, span: codemap::span,
-                                    next_pos: Option<BytePos>) {
-    let mut cm;
-    match s.cm { Some(ccm) => cm = ccm, _ => return }
-    match next_comment(s) {
-      Some(ref cmnt) => {
-        if (*cmnt).style != comments::trailing { return; }
-        let span_line = cm.lookup_char_pos(span.hi);
-        let comment_line = cm.lookup_char_pos((*cmnt).pos);
-        let mut next = (*cmnt).pos + BytePos(1u);
-        match next_pos { None => (), Some(p) => next = p }
-        if span.hi < (*cmnt).pos && (*cmnt).pos < next &&
-               span_line.line == comment_line.line {
-            print_comment(s, (*cmnt));
-            s.cur_cmnt_and_lit.cur_cmnt += 1u;
-        }
-      }
-      _ => ()
+    pub fn commasep_exprs(&mut self, b: Breaks,
+                          exprs: &[P<ast::Expr>]) -> io::Result<()> {
+        self.commasep_cmnt(b, exprs, |s, e| s.print_expr(e), |e| e.span)
     }
-}
 
-pub fn print_remaining_comments(s: @ps) {
-    // If there aren't any remaining comments, then we need to manually
-    // make sure there is a line break at the end.
-    if next_comment(s).is_none() { hardbreak(s.s); }
-    loop {
-        match next_comment(s) {
-          Some(ref cmnt) => {
-            print_comment(s, (*cmnt));
-            s.cur_cmnt_and_lit.cur_cmnt += 1u;
-          }
-          _ => break
+    pub fn print_mod(&mut self, _mod: &ast::Mod,
+                     attrs: &[ast::Attribute]) -> io::Result<()> {
+        self.print_inner_attributes(attrs)?;
+        for item in &_mod.items {
+            self.print_item(item)?;
         }
+        Ok(())
     }
-}
-
-pub fn print_literal(s: @ps, &&lit: @ast::lit) {
-    maybe_print_comment(s, lit.span.lo);
-    match next_lit(s, lit.span.lo) {
-      Some(ref ltrl) => {
-        word(s.s, (*ltrl).lit);
-        return;
-      }
-      _ => ()
-    }
-    match lit.node {
-      ast::lit_str(st) => print_string(s, *st),
-      ast::lit_int(ch, ast::ty_char) => {
-        word(s.s, ~"'" + char::escape_default(ch as char) + ~"'");
-      }
-      ast::lit_int(i, t) => {
-        if i < 0_i64 {
-            word(s.s,
-                 ~"-" + u64::to_str_radix(-i as u64, 10u)
-                 + ast_util::int_ty_to_str(t));
-        } else {
-            word(s.s,
-                 u64::to_str_radix(i as u64, 10u)
-                 + ast_util::int_ty_to_str(t));
-        }
-      }
-      ast::lit_uint(u, t) => {
-        word(s.s,
-             u64::to_str_radix(u, 10u)
-             + ast_util::uint_ty_to_str(t));
-      }
-      ast::lit_int_unsuffixed(i) => {
-        if i < 0_i64 {
-            word(s.s, ~"-" + u64::to_str_radix(-i as u64, 10u));
-        } else {
-            word(s.s, u64::to_str_radix(i as u64, 10u));
-        }
-      }
-      ast::lit_float(f, t) => {
-        word(s.s, *f + ast_util::float_ty_to_str(t));
-      }
-      ast::lit_float_unsuffixed(f) => word(s.s, *f),
-      ast::lit_nil => word(s.s, ~"()"),
-      ast::lit_bool(val) => {
-        if val { word(s.s, ~"true"); } else { word(s.s, ~"false"); }
-      }
-    }
-}
-
-pub fn lit_to_str(l: @ast::lit) -> ~str {
-    return to_str(l, print_literal, parse::token::mk_fake_ident_interner());
-}
 
-pub fn next_lit(s: @ps, pos: BytePos) -> Option<comments::lit> {
-    match s.literals {
-      Some(ref lits) => {
-        while s.cur_cmnt_and_lit.cur_lit < vec::len((*lits)) {
-            let ltrl = /*bad*/ copy (*lits)[s.cur_cmnt_and_lit.cur_lit];
-            if ltrl.pos > pos { return None; }
-            s.cur_cmnt_and_lit.cur_lit += 1u;
-            if ltrl.pos == pos { return Some(ltrl); }
+    pub fn print_foreign_mod(&mut self, nmod: &ast::ForeignMod,
+                             attrs: &[ast::Attribute]) -> io::Result<()> {
+        self.print_inner_attributes(attrs)?;
+        for item in &nmod.items {
+            self.print_foreign_item(item)?;
         }
-        return None;
-      }
-      _ => return None
+        Ok(())
     }
-}
 
-pub fn maybe_print_comment(s: @ps, pos: BytePos) {
-    loop {
-        match next_comment(s) {
-          Some(ref cmnt) => {
-            if (*cmnt).pos < pos {
-                print_comment(s, (*cmnt));
-                s.cur_cmnt_and_lit.cur_cmnt += 1u;
-            } else { break; }
-          }
-          _ => break
+    pub fn print_opt_lifetime(&mut self,
+                              lifetime: &Option<ast::Lifetime>) -> io::Result<()> {
+        if let Some(l) = *lifetime {
+            self.print_lifetime(&l)?;
+            self.nbsp()?;
         }
+        Ok(())
     }
-}
 
-pub fn print_comment(s: @ps, cmnt: comments::cmnt) {
-    match cmnt.style {
-      comments::mixed => {
-        assert!((vec::len(cmnt.lines) == 1u));
-        zerobreak(s.s);
-        word(s.s, cmnt.lines[0]);
-        zerobreak(s.s);
-      }
-      comments::isolated => {
-        pprust::hardbreak_if_not_bol(s);
-        for cmnt.lines.each |line| {
-            // Don't print empty lines because they will end up as trailing
-            // whitespace
-            if !line.is_empty() { word(s.s, *line); }
-            hardbreak(s.s);
-        }
-      }
-      comments::trailing => {
-        word(s.s, ~" ");
-        if vec::len(cmnt.lines) == 1u {
-            word(s.s, cmnt.lines[0]);
-            hardbreak(s.s);
-        } else {
-            ibox(s, 0u);
-            for cmnt.lines.each |line| {
-                if !line.is_empty() { word(s.s, *line); }
-                hardbreak(s.s);
-            }
-            end(s);
-        }
-      }
-      comments::blank_line => {
-        // We need to do at least one, possibly two hardbreaks.
-        let is_semi =
-            match s.s.last_token() {
-              pp::STRING(s, _) => *s == ~";",
-              _ => false
-            };
-        if is_semi || is_begin(s) || is_end(s) { hardbreak(s.s); }
-        hardbreak(s.s);
-      }
+    pub fn print_type(&mut self, ty: &ast::Ty) -> io::Result<()> {
+        self.maybe_print_comment(ty.span.lo)?;
+        self.ibox(0)?;
+        match ty.node {
+            ast::TyKind::Slice(ref ty) => {
+                self.s.word("[")?;
+                self.print_type(ty)?;
+                self.s.word("]")?;
+            }
+            ast::TyKind::Ptr(ref mt) => {
+                self.s.word("*")?;
+                match mt.mutbl {
+                    ast::Mutability::Mutable => self.word_nbsp("mut")?,
+                    ast::Mutability::Immutable => self.word_nbsp("const")?,
+                }
+                self.print_type(&mt.ty)?;
+            }
+            ast::TyKind::Rptr(ref lifetime, ref mt) => {
+                self.s.word("&")?;
+                self.print_opt_lifetime(lifetime)?;
+                self.print_mt(mt)?;
+            }
+            ast::TyKind::Never => {
+                self.s.word("!")?;
+            },
+            ast::TyKind::Tup(ref elts) => {
+                self.popen()?;
+                self.commasep(Inconsistent, &elts[..],
+                              |s, ty| s.print_type(ty))?;
+                if elts.len() == 1 {
+                    self.s.word(",")?;
+                }
+                self.pclose()?;
+            }
+            ast::TyKind::Paren(ref typ) => {
+                self.popen()?;
+                self.print_type(typ)?;
+                self.pclose()?;
+            }
+            ast::TyKind::BareFn(ref f) => {
+                let generics = ast::Generics {
+                    lifetimes: f.lifetimes.clone(),
+                    ty_params: Vec::new(),
+                    where_clause: ast::WhereClause {
+                        id: ast::DUMMY_NODE_ID,
+                        predicates: Vec::new(),
+                    },
+                    span: syntax_pos::DUMMY_SP,
+                };
+                self.print_ty_fn(f.abi,
+                                 f.unsafety,
+                                 &f.decl,
+                                 None,
+                                 &generics)?;
+            }
+            ast::TyKind::Path(None, ref path) => {
+                self.print_path(path, false, 0, false)?;
+            }
+            ast::TyKind::Path(Some(ref qself), ref path) => {
+                self.print_qpath(path, qself, false)?
+            }
+            ast::TyKind::TraitObject(ref bounds) => {
+                self.print_bounds("", &bounds[..])?;
+            }
+            ast::TyKind::ImplTrait(ref bounds) => {
+                self.print_bounds("impl ", &bounds[..])?;
+            }
+            ast::TyKind::Array(ref ty, ref v) => {
+                self.s.word("[")?;
+                self.print_type(ty)?;
+                self.s.word("; ")?;
+                self.print_expr(v)?;
+                self.s.word("]")?;
+            }
+            ast::TyKind::Typeof(ref e) => {
+                self.s.word("typeof(")?;
+                self.print_expr(e)?;
+                self.s.word(")")?;
+            }
+            ast::TyKind::Infer => {
+                self.s.word("_")?;
+            }
+            ast::TyKind::Err => {
+                self.s.word("?")?;
+            }
+            ast::TyKind::ImplicitSelf => {
+                self.s.word("Self")?;
+            }
+            ast::TyKind::Mac(ref m) => {
+                self.print_mac(m, token::Paren)?;
+            }
+        }
+        self.end()
+    }
+
+    pub fn print_foreign_item(&mut self,
+                              item: &ast::ForeignItem) -> io::Result<()> {
+        self.hardbreak_if_not_bol()?;
+        self.maybe_print_comment(item.span.lo)?;
+        self.print_outer_attributes(&item.attrs)?;
+        match item.node {
+            ast::ForeignItemKind::Fn(ref decl, ref generics) => {
+                self.head("")?;
+                self.print_fn(decl, ast::Unsafety::Normal,
+                              ast::Constness::NotConst,
+                              Abi::Rust, Some(item.ident),
+                              generics, &item.vis)?;
+                self.end()?; // end head-ibox
+                self.s.word(";")?;
+                self.end() // end the outer fn box
+            }
+            ast::ForeignItemKind::Static(ref t, m) => {
+                self.head(&visibility_qualified(&item.vis, "static"))?;
+                if m {
+                    self.word_space("mut")?;
+                }
+                self.print_ident(item.ident)?;
+                self.word_space(":")?;
+                self.print_type(t)?;
+                self.s.word(";")?;
+                self.end()?; // end the head-ibox
+                self.end() // end the outer cbox
+            }
+        }
     }
-}
 
-pub fn print_string(s: @ps, st: &str) {
-    word(s.s, ~"\"");
-    word(s.s, str::escape_default(st));
-    word(s.s, ~"\"");
-}
+    fn print_associated_const(&mut self,
+                              ident: ast::Ident,
+                              ty: &ast::Ty,
+                              default: Option<&ast::Expr>,
+                              vis: &ast::Visibility)
+                              -> io::Result<()>
+    {
+        self.s.word(&visibility_qualified(vis, ""))?;
+        self.word_space("const")?;
+        self.print_ident(ident)?;
+        self.word_space(":")?;
+        self.print_type(ty)?;
+        if let Some(expr) = default {
+            self.s.space()?;
+            self.word_space("=")?;
+            self.print_expr(expr)?;
+        }
+        self.s.word(";")
+    }
+
+    fn print_associated_type(&mut self,
+                             ident: ast::Ident,
+                             bounds: Option<&ast::TyParamBounds>,
+                             ty: Option<&ast::Ty>)
+                             -> io::Result<()> {
+        self.word_space("type")?;
+        self.print_ident(ident)?;
+        if let Some(bounds) = bounds {
+            self.print_bounds(":", bounds)?;
+        }
+        if let Some(ty) = ty {
+            self.s.space()?;
+            self.word_space("=")?;
+            self.print_type(ty)?;
+        }
+        self.s.word(";")
+    }
+
+    /// Pretty-print an item
+    pub fn print_item(&mut self, item: &ast::Item) -> io::Result<()> {
+        self.hardbreak_if_not_bol()?;
+        self.maybe_print_comment(item.span.lo)?;
+        self.print_outer_attributes(&item.attrs)?;
+        self.ann.pre(self, NodeItem(item))?;
+        match item.node {
+            ast::ItemKind::ExternCrate(ref optional_path) => {
+                self.head(&visibility_qualified(&item.vis, "extern crate"))?;
+                if let Some(p) = *optional_path {
+                    let val = p.as_str();
+                    if val.contains('-') {
+                        self.print_string(&val, ast::StrStyle::Cooked)?;
+                    } else {
+                        self.print_name(p)?;
+                    }
+                    self.s.space()?;
+                    self.s.word("as")?;
+                    self.s.space()?;
+                }
+                self.print_ident(item.ident)?;
+                self.s.word(";")?;
+                self.end()?; // end inner head-block
+                self.end()?; // end outer head-block
+            }
+            ast::ItemKind::Use(ref vp) => {
+                self.head(&visibility_qualified(&item.vis, "use"))?;
+                self.print_view_path(vp)?;
+                self.s.word(";")?;
+                self.end()?; // end inner head-block
+                self.end()?; // end outer head-block
+            }
+            ast::ItemKind::Static(ref ty, m, ref expr) => {
+                self.head(&visibility_qualified(&item.vis, "static"))?;
+                if m == ast::Mutability::Mutable {
+                    self.word_space("mut")?;
+                }
+                self.print_ident(item.ident)?;
+                self.word_space(":")?;
+                self.print_type(ty)?;
+                self.s.space()?;
+                self.end()?; // end the head-ibox
+
+                self.word_space("=")?;
+                self.print_expr(expr)?;
+                self.s.word(";")?;
+                self.end()?; // end the outer cbox
+            }
+            ast::ItemKind::Const(ref ty, ref expr) => {
+                self.head(&visibility_qualified(&item.vis, "const"))?;
+                self.print_ident(item.ident)?;
+                self.word_space(":")?;
+                self.print_type(ty)?;
+                self.s.space()?;
+                self.end()?; // end the head-ibox
+
+                self.word_space("=")?;
+                self.print_expr(expr)?;
+                self.s.word(";")?;
+                self.end()?; // end the outer cbox
+            }
+            ast::ItemKind::Fn(ref decl, unsafety, constness, abi, ref typarams, ref body) => {
+                self.head("")?;
+                self.print_fn(
+                    decl,
+                    unsafety,
+                    constness.node,
+                    abi,
+                    Some(item.ident),
+                    typarams,
+                    &item.vis
+                )?;
+                self.s.word(" ")?;
+                self.print_block_with_attrs(body, &item.attrs)?;
+            }
+            ast::ItemKind::Mod(ref _mod) => {
+                self.head(&visibility_qualified(&item.vis, "mod"))?;
+                self.print_ident(item.ident)?;
+                self.nbsp()?;
+                self.bopen()?;
+                self.print_mod(_mod, &item.attrs)?;
+                self.bclose(item.span)?;
+            }
+            ast::ItemKind::ForeignMod(ref nmod) => {
+                self.head("extern")?;
+                self.word_nbsp(&nmod.abi.to_string())?;
+                self.bopen()?;
+                self.print_foreign_mod(nmod, &item.attrs)?;
+                self.bclose(item.span)?;
+            }
+            ast::ItemKind::GlobalAsm(ref ga) => {
+                self.head(&visibility_qualified(&item.vis, "global_asm!"))?;
+                self.s.word(&ga.asm.as_str())?;
+                self.end()?;
+            }
+            ast::ItemKind::Ty(ref ty, ref params) => {
+                self.ibox(INDENT_UNIT)?;
+                self.ibox(0)?;
+                self.word_nbsp(&visibility_qualified(&item.vis, "type"))?;
+                self.print_ident(item.ident)?;
+                self.print_generics(params)?;
+                self.end()?; // end the inner ibox
+
+                self.print_where_clause(&params.where_clause)?;
+                self.s.space()?;
+                self.word_space("=")?;
+                self.print_type(ty)?;
+                self.s.word(";")?;
+                self.end()?; // end the outer ibox
+            }
+            ast::ItemKind::Enum(ref enum_definition, ref params) => {
+                self.print_enum_def(
+                    enum_definition,
+                    params,
+                    item.ident,
+                    item.span,
+                    &item.vis
+                )?;
+            }
+            ast::ItemKind::Struct(ref struct_def, ref generics) => {
+                self.head(&visibility_qualified(&item.vis, "struct"))?;
+                self.print_struct(struct_def, generics, item.ident, item.span, true)?;
+            }
+            ast::ItemKind::Union(ref struct_def, ref generics) => {
+                self.head(&visibility_qualified(&item.vis, "union"))?;
+                self.print_struct(struct_def, generics, item.ident, item.span, true)?;
+            }
+            ast::ItemKind::DefaultImpl(unsafety, ref trait_ref) => {
+                self.head("")?;
+                self.print_visibility(&item.vis)?;
+                self.print_unsafety(unsafety)?;
+                self.word_nbsp("impl")?;
+                self.print_trait_ref(trait_ref)?;
+                self.s.space()?;
+                self.word_space("for")?;
+                self.word_space("..")?;
+                self.bopen()?;
+                self.bclose(item.span)?;
+            }
+            ast::ItemKind::Impl(unsafety,
+                          polarity,
+                          defaultness,
+                          ref generics,
+                          ref opt_trait,
+                          ref ty,
+                          ref impl_items) => {
+                self.head("")?;
+                self.print_visibility(&item.vis)?;
+                self.print_defaultness(defaultness)?;
+                self.print_unsafety(unsafety)?;
+                self.word_nbsp("impl")?;
+
+                if generics.is_parameterized() {
+                    self.print_generics(generics)?;
+                    self.s.space()?;
+                }
 
-pub fn to_str<T>(t: T, f: @fn(@ps, T), intr: @ident_interner) -> ~str {
-    do io::with_str_writer |wr| {
-        let s = rust_printer(wr, intr);
-        f(s, t);
-        eof(s.s);
+                if polarity == ast::ImplPolarity::Negative {
+                    self.s.word("!")?;
+                }
+
+                if let Some(ref t) = *opt_trait {
+                    self.print_trait_ref(t)?;
+                    self.s.space()?;
+                    self.word_space("for")?;
+                }
+
+                self.print_type(ty)?;
+                self.print_where_clause(&generics.where_clause)?;
+
+                self.s.space()?;
+                self.bopen()?;
+                self.print_inner_attributes(&item.attrs)?;
+                for impl_item in impl_items {
+                    self.print_impl_item(impl_item)?;
+                }
+                self.bclose(item.span)?;
+            }
+            ast::ItemKind::Trait(unsafety, ref generics, ref bounds, ref trait_items) => {
+                self.head("")?;
+                self.print_visibility(&item.vis)?;
+                self.print_unsafety(unsafety)?;
+                self.word_nbsp("trait")?;
+                self.print_ident(item.ident)?;
+                self.print_generics(generics)?;
+                let mut real_bounds = Vec::with_capacity(bounds.len());
+                for b in bounds.iter() {
+                    if let TraitTyParamBound(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
+                        self.s.space()?;
+                        self.word_space("for ?")?;
+                        self.print_trait_ref(&ptr.trait_ref)?;
+                    } else {
+                        real_bounds.push(b.clone());
+                    }
+                }
+                self.print_bounds(":", &real_bounds[..])?;
+                self.print_where_clause(&generics.where_clause)?;
+                self.s.word(" ")?;
+                self.bopen()?;
+                for trait_item in trait_items {
+                    self.print_trait_item(trait_item)?;
+                }
+                self.bclose(item.span)?;
+            }
+            ast::ItemKind::Mac(codemap::Spanned { ref node, .. }) => {
+                self.print_path(&node.path, false, 0, false)?;
+                self.s.word("! ")?;
+                self.print_ident(item.ident)?;
+                self.cbox(INDENT_UNIT)?;
+                self.popen()?;
+                self.print_tts(node.stream())?;
+                self.pclose()?;
+                self.s.word(";")?;
+                self.end()?;
+            }
+            ast::ItemKind::MacroDef(ref tts) => {
+                self.s.word("macro_rules! ")?;
+                self.print_ident(item.ident)?;
+                self.cbox(INDENT_UNIT)?;
+                self.popen()?;
+                self.print_tts(tts.stream())?;
+                self.pclose()?;
+                self.s.word(";")?;
+                self.end()?;
+            }
+        }
+        self.ann.post(self, NodeItem(item))
     }
-}
 
-pub fn next_comment(s: @ps) -> Option<comments::cmnt> {
-    match s.comments {
-      Some(ref cmnts) => {
-        if s.cur_cmnt_and_lit.cur_cmnt < vec::len((*cmnts)) {
-            return Some(copy cmnts[s.cur_cmnt_and_lit.cur_cmnt]);
-        } else { return None::<comments::cmnt>; }
-      }
-      _ => return None::<comments::cmnt>
+    fn print_trait_ref(&mut self, t: &ast::TraitRef) -> io::Result<()> {
+        self.print_path(&t.path, false, 0, false)
     }
-}
 
-pub fn print_opt_purity(s: @ps, opt_purity: Option<ast::purity>) {
-    match opt_purity {
-        Some(ast::impure_fn) => { }
-        Some(purity) => {
-            word_nbsp(s, purity_to_str(purity));
+    fn print_formal_lifetime_list(&mut self, lifetimes: &[ast::LifetimeDef]) -> io::Result<()> {
+        if !lifetimes.is_empty() {
+            self.s.word("for<")?;
+            let mut comma = false;
+            for lifetime_def in lifetimes {
+                if comma {
+                    self.word_space(",")?
+                }
+                self.print_outer_attributes_inline(&lifetime_def.attrs)?;
+                self.print_lifetime_bounds(&lifetime_def.lifetime, &lifetime_def.bounds)?;
+                comma = true;
+            }
+            self.s.word(">")?;
+        }
+        Ok(())
+    }
+
+    fn print_poly_trait_ref(&mut self, t: &ast::PolyTraitRef) -> io::Result<()> {
+        self.print_formal_lifetime_list(&t.bound_lifetimes)?;
+        self.print_trait_ref(&t.trait_ref)
+    }
+
+    pub fn print_enum_def(&mut self, enum_definition: &ast::EnumDef,
+                          generics: &ast::Generics, ident: ast::Ident,
+                          span: syntax_pos::Span,
+                          visibility: &ast::Visibility) -> io::Result<()> {
+        self.head(&visibility_qualified(visibility, "enum"))?;
+        self.print_ident(ident)?;
+        self.print_generics(generics)?;
+        self.print_where_clause(&generics.where_clause)?;
+        self.s.space()?;
+        self.print_variants(&enum_definition.variants, span)
+    }
+
+    pub fn print_variants(&mut self,
+                          variants: &[ast::Variant],
+                          span: syntax_pos::Span) -> io::Result<()> {
+        self.bopen()?;
+        for v in variants {
+            self.space_if_not_bol()?;
+            self.maybe_print_comment(v.span.lo)?;
+            self.print_outer_attributes(&v.node.attrs)?;
+            self.ibox(INDENT_UNIT)?;
+            self.print_variant(v)?;
+            self.s.word(",")?;
+            self.end()?;
+            self.maybe_print_trailing_comment(v.span, None)?;
+        }
+        self.bclose(span)
+    }
+
+    pub fn print_visibility(&mut self, vis: &ast::Visibility) -> io::Result<()> {
+        match *vis {
+            ast::Visibility::Public => self.word_nbsp("pub"),
+            ast::Visibility::Crate(_) => self.word_nbsp("pub(crate)"),
+            ast::Visibility::Restricted { ref path, .. } => {
+                let path = to_string(|s| s.print_path(path, false, 0, true));
+                if path == "self" || path == "super" {
+                    self.word_nbsp(&format!("pub({})", path))
+                } else {
+                    self.word_nbsp(&format!("pub(in {})", path))
+                }
+            }
+            ast::Visibility::Inherited => Ok(())
+        }
+    }
+
+    pub fn print_defaultness(&mut self, defatulness: ast::Defaultness) -> io::Result<()> {
+        if let ast::Defaultness::Default = defatulness {
+            try!(self.word_nbsp("default"));
+        }
+        Ok(())
+    }
+
+    pub fn print_struct(&mut self,
+                        struct_def: &ast::VariantData,
+                        generics: &ast::Generics,
+                        ident: ast::Ident,
+                        span: syntax_pos::Span,
+                        print_finalizer: bool) -> io::Result<()> {
+        self.print_ident(ident)?;
+        self.print_generics(generics)?;
+        if !struct_def.is_struct() {
+            if struct_def.is_tuple() {
+                self.popen()?;
+                self.commasep(
+                    Inconsistent, struct_def.fields(),
+                    |s, field| {
+                        s.maybe_print_comment(field.span.lo)?;
+                        s.print_outer_attributes(&field.attrs)?;
+                        s.print_visibility(&field.vis)?;
+                        s.print_type(&field.ty)
+                    }
+                )?;
+                self.pclose()?;
+            }
+            self.print_where_clause(&generics.where_clause)?;
+            if print_finalizer {
+                self.s.word(";")?;
+            }
+            self.end()?;
+            self.end() // close the outer-box
+        } else {
+            self.print_where_clause(&generics.where_clause)?;
+            self.nbsp()?;
+            self.bopen()?;
+            self.hardbreak_if_not_bol()?;
+
+            for field in struct_def.fields() {
+                self.hardbreak_if_not_bol()?;
+                self.maybe_print_comment(field.span.lo)?;
+                self.print_outer_attributes(&field.attrs)?;
+                self.print_visibility(&field.vis)?;
+                self.print_ident(field.ident.unwrap())?;
+                self.word_nbsp(":")?;
+                self.print_type(&field.ty)?;
+                self.s.word(",")?;
+            }
+
+            self.bclose(span)
         }
-        None => {}
     }
-}
 
-pub fn print_extern_opt_abis(s: @ps, opt_abis: Option<AbiSet>) {
-    match opt_abis {
-        Some(abis) => {
-            word_nbsp(s, ~"extern");
-            word_nbsp(s, abis.to_str());
+    pub fn print_variant(&mut self, v: &ast::Variant) -> io::Result<()> {
+        self.head("")?;
+        let generics = ast::Generics::default();
+        self.print_struct(&v.node.data, &generics, v.node.name, v.span, false)?;
+        match v.node.disr_expr {
+            Some(ref d) => {
+                self.s.space()?;
+                self.word_space("=")?;
+                self.print_expr(d)
+            }
+            _ => Ok(())
+        }
+    }
+
+    pub fn print_method_sig(&mut self,
+                            ident: ast::Ident,
+                            m: &ast::MethodSig,
+                            vis: &ast::Visibility)
+                            -> io::Result<()> {
+        self.print_fn(&m.decl,
+                      m.unsafety,
+                      m.constness.node,
+                      m.abi,
+                      Some(ident),
+                      &m.generics,
+                      vis)
+    }
+
+    pub fn print_trait_item(&mut self, ti: &ast::TraitItem)
+                            -> io::Result<()> {
+        self.ann.pre(self, NodeSubItem(ti.id))?;
+        self.hardbreak_if_not_bol()?;
+        self.maybe_print_comment(ti.span.lo)?;
+        self.print_outer_attributes(&ti.attrs)?;
+        match ti.node {
+            ast::TraitItemKind::Const(ref ty, ref default) => {
+                self.print_associated_const(ti.ident, ty,
+                                            default.as_ref().map(|expr| &**expr),
+                                            &ast::Visibility::Inherited)?;
+            }
+            ast::TraitItemKind::Method(ref sig, ref body) => {
+                if body.is_some() {
+                    self.head("")?;
+                }
+                self.print_method_sig(ti.ident, sig, &ast::Visibility::Inherited)?;
+                if let Some(ref body) = *body {
+                    self.nbsp()?;
+                    self.print_block_with_attrs(body, &ti.attrs)?;
+                } else {
+                    self.s.word(";")?;
+                }
+            }
+            ast::TraitItemKind::Type(ref bounds, ref default) => {
+                self.print_associated_type(ti.ident, Some(bounds),
+                                           default.as_ref().map(|ty| &**ty))?;
+            }
+            ast::TraitItemKind::Macro(codemap::Spanned { ref node, .. }) => {
+                // code copied from ItemKind::Mac:
+                self.print_path(&node.path, false, 0, false)?;
+                self.s.word("! ")?;
+                self.cbox(INDENT_UNIT)?;
+                self.popen()?;
+                self.print_tts(node.stream())?;
+                self.pclose()?;
+                self.s.word(";")?;
+                self.end()?
+            }
         }
-        None => {}
-    };
-}
+        self.ann.post(self, NodeSubItem(ti.id))
+    }
 
-pub fn print_opt_sigil(s: @ps, opt_sigil: Option<ast::Sigil>) {
-    match opt_sigil {
-        Some(ast::BorrowedSigil) => { word(s.s, ~"&"); }
-        Some(ast::OwnedSigil) => { word(s.s, ~"~"); }
-        Some(ast::ManagedSigil) => { word(s.s, ~"@"); }
-        None => {}
-    };
-}
+    pub fn print_impl_item(&mut self, ii: &ast::ImplItem) -> io::Result<()> {
+        self.ann.pre(self, NodeSubItem(ii.id))?;
+        self.hardbreak_if_not_bol()?;
+        self.maybe_print_comment(ii.span.lo)?;
+        self.print_outer_attributes(&ii.attrs)?;
+        self.print_defaultness(ii.defaultness)?;
+        match ii.node {
+            ast::ImplItemKind::Const(ref ty, ref expr) => {
+                self.print_associated_const(ii.ident, ty, Some(expr), &ii.vis)?;
+            }
+            ast::ImplItemKind::Method(ref sig, ref body) => {
+                self.head("")?;
+                self.print_method_sig(ii.ident, sig, &ii.vis)?;
+                self.nbsp()?;
+                self.print_block_with_attrs(body, &ii.attrs)?;
+            }
+            ast::ImplItemKind::Type(ref ty) => {
+                self.print_associated_type(ii.ident, None, Some(ty))?;
+            }
+            ast::ImplItemKind::Macro(codemap::Spanned { ref node, .. }) => {
+                // code copied from ItemKind::Mac:
+                self.print_path(&node.path, false, 0, false)?;
+                self.s.word("! ")?;
+                self.cbox(INDENT_UNIT)?;
+                self.popen()?;
+                self.print_tts(node.stream())?;
+                self.pclose()?;
+                self.s.word(";")?;
+                self.end()?
+            }
+        }
+        self.ann.post(self, NodeSubItem(ii.id))
+    }
+
+    pub fn print_stmt(&mut self, st: &ast::Stmt) -> io::Result<()> {
+        self.maybe_print_comment(st.span.lo)?;
+        match st.node {
+            ast::StmtKind::Local(ref loc) => {
+                self.print_outer_attributes(&loc.attrs)?;
+                self.space_if_not_bol()?;
+                self.ibox(INDENT_UNIT)?;
+                self.word_nbsp("let")?;
+
+                self.ibox(INDENT_UNIT)?;
+                self.print_local_decl(loc)?;
+                self.end()?;
+                if let Some(ref init) = loc.init {
+                    self.nbsp()?;
+                    self.word_space("=")?;
+                    self.print_expr(init)?;
+                }
+                self.s.word(";")?;
+                self.end()?;
+            }
+            ast::StmtKind::Item(ref item) => self.print_item(item)?,
+            ast::StmtKind::Expr(ref expr) => {
+                self.space_if_not_bol()?;
+                self.print_expr_outer_attr_style(expr, false)?;
+                if parse::classify::expr_requires_semi_to_be_stmt(expr) {
+                    self.s.word(";")?;
+                }
+            }
+            ast::StmtKind::Semi(ref expr) => {
+                self.space_if_not_bol()?;
+                self.print_expr_outer_attr_style(expr, false)?;
+                self.s.word(";")?;
+            }
+            ast::StmtKind::Mac(ref mac) => {
+                let (ref mac, style, ref attrs) = **mac;
+                self.space_if_not_bol()?;
+                self.print_outer_attributes(attrs)?;
+                let delim = match style {
+                    ast::MacStmtStyle::Braces => token::Brace,
+                    _ => token::Paren
+                };
+                self.print_mac(mac, delim)?;
+                if style == ast::MacStmtStyle::Semicolon {
+                    self.s.word(";")?;
+                }
+            }
+        }
+        self.maybe_print_trailing_comment(st.span, None)
+    }
 
-pub fn print_fn_header_info(s: @ps,
-                            _opt_sty: Option<ast::self_ty_>,
-                            opt_purity: Option<ast::purity>,
-                            abis: AbiSet,
-                            onceness: ast::Onceness,
-                            opt_sigil: Option<ast::Sigil>,
-                            vis: ast::visibility) {
-    word(s.s, visibility_qualified(vis, ~""));
+    pub fn print_block(&mut self, blk: &ast::Block) -> io::Result<()> {
+        self.print_block_with_attrs(blk, &[])
+    }
 
-    if abis != AbiSet::Rust() {
-        word_nbsp(s, ~"extern");
-        word_nbsp(s, abis.to_str());
+    pub fn print_block_unclosed(&mut self, blk: &ast::Block) -> io::Result<()> {
+        self.print_block_unclosed_indent(blk, INDENT_UNIT)
+    }
 
-        if opt_purity != Some(ast::extern_fn) {
-            print_opt_purity(s, opt_purity);
+    pub fn print_block_unclosed_with_attrs(&mut self, blk: &ast::Block,
+                                            attrs: &[ast::Attribute])
+                                           -> io::Result<()> {
+        self.print_block_maybe_unclosed(blk, INDENT_UNIT, attrs, false)
+    }
+
+    pub fn print_block_unclosed_indent(&mut self, blk: &ast::Block,
+                                       indented: usize) -> io::Result<()> {
+        self.print_block_maybe_unclosed(blk, indented, &[], false)
+    }
+
+    pub fn print_block_with_attrs(&mut self,
+                                  blk: &ast::Block,
+                                  attrs: &[ast::Attribute]) -> io::Result<()> {
+        self.print_block_maybe_unclosed(blk, INDENT_UNIT, attrs, true)
+    }
+
+    pub fn print_block_maybe_unclosed(&mut self,
+                                      blk: &ast::Block,
+                                      indented: usize,
+                                      attrs: &[ast::Attribute],
+                                      close_box: bool) -> io::Result<()> {
+        match blk.rules {
+            BlockCheckMode::Unsafe(..) => self.word_space("unsafe")?,
+            BlockCheckMode::Default => ()
+        }
+        self.maybe_print_comment(blk.span.lo)?;
+        self.ann.pre(self, NodeBlock(blk))?;
+        self.bopen()?;
+
+        self.print_inner_attributes(attrs)?;
+
+        for (i, st) in blk.stmts.iter().enumerate() {
+            match st.node {
+                ast::StmtKind::Expr(ref expr) if i == blk.stmts.len() - 1 => {
+                    self.maybe_print_comment(st.span.lo)?;
+                    self.space_if_not_bol()?;
+                    self.print_expr_outer_attr_style(expr, false)?;
+                    self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi))?;
+                }
+                _ => self.print_stmt(st)?,
+            }
+        }
+
+        self.bclose_maybe_open(blk.span, indented, close_box)?;
+        self.ann.post(self, NodeBlock(blk))
+    }
+
+    fn print_else(&mut self, els: Option<&ast::Expr>) -> io::Result<()> {
+        match els {
+            Some(_else) => {
+                match _else.node {
+                    // "another else-if"
+                    ast::ExprKind::If(ref i, ref then, ref e) => {
+                        self.cbox(INDENT_UNIT - 1)?;
+                        self.ibox(0)?;
+                        self.s.word(" else if ")?;
+                        self.print_expr(i)?;
+                        self.s.space()?;
+                        self.print_block(then)?;
+                        self.print_else(e.as_ref().map(|e| &**e))
+                    }
+                    // "another else-if-let"
+                    ast::ExprKind::IfLet(ref pat, ref expr, ref then, ref e) => {
+                        self.cbox(INDENT_UNIT - 1)?;
+                        self.ibox(0)?;
+                        self.s.word(" else if let ")?;
+                        self.print_pat(pat)?;
+                        self.s.space()?;
+                        self.word_space("=")?;
+                        self.print_expr(expr)?;
+                        self.s.space()?;
+                        self.print_block(then)?;
+                        self.print_else(e.as_ref().map(|e| &**e))
+                    }
+                    // "final else"
+                    ast::ExprKind::Block(ref b) => {
+                        self.cbox(INDENT_UNIT - 1)?;
+                        self.ibox(0)?;
+                        self.s.word(" else ")?;
+                        self.print_block(b)
+                    }
+                    // BLEAH, constraints would be great here
+                    _ => {
+                        panic!("print_if saw if with weird alternative");
+                    }
+                }
+            }
+            _ => Ok(())
+        }
+    }
+
+    pub fn print_if(&mut self, test: &ast::Expr, blk: &ast::Block,
+                    elseopt: Option<&ast::Expr>) -> io::Result<()> {
+        self.head("if")?;
+        self.print_expr(test)?;
+        self.s.space()?;
+        self.print_block(blk)?;
+        self.print_else(elseopt)
+    }
+
+    pub fn print_if_let(&mut self, pat: &ast::Pat, expr: &ast::Expr, blk: &ast::Block,
+                        elseopt: Option<&ast::Expr>) -> io::Result<()> {
+        self.head("if let")?;
+        self.print_pat(pat)?;
+        self.s.space()?;
+        self.word_space("=")?;
+        self.print_expr(expr)?;
+        self.s.space()?;
+        self.print_block(blk)?;
+        self.print_else(elseopt)
+    }
+
+    pub fn print_mac(&mut self, m: &ast::Mac, delim: token::DelimToken)
+                     -> io::Result<()> {
+        self.print_path(&m.node.path, false, 0, false)?;
+        self.s.word("!")?;
+        match delim {
+            token::Paren => self.popen()?,
+            token::Bracket => self.s.word("[")?,
+            token::Brace => {
+                self.head("")?;
+                self.bopen()?;
+            }
+            token::NoDelim => {}
+        }
+        self.print_tts(m.node.stream())?;
+        match delim {
+            token::Paren => self.pclose(),
+            token::Bracket => self.s.word("]"),
+            token::Brace => self.bclose(m.span),
+            token::NoDelim => Ok(()),
         }
-    } else {
-        print_opt_purity(s, opt_purity);
     }
 
-    print_onceness(s, onceness);
-    word(s.s, ~"fn");
-    print_opt_sigil(s, opt_sigil);
-}
 
-pub fn opt_sigil_to_str(opt_p: Option<ast::Sigil>) -> ~str {
-    match opt_p {
-      None => ~"fn",
-      Some(p) => fmt!("fn%s", p.to_str())
+    fn print_call_post(&mut self, args: &[P<ast::Expr>]) -> io::Result<()> {
+        self.popen()?;
+        self.commasep_exprs(Inconsistent, args)?;
+        self.pclose()
+    }
+
+    pub fn check_expr_bin_needs_paren(&mut self, sub_expr: &ast::Expr,
+                                      binop: ast::BinOp) -> bool {
+        match sub_expr.node {
+            ast::ExprKind::Binary(ref sub_op, _, _) => {
+                AssocOp::from_ast_binop(sub_op.node).precedence() <
+                    AssocOp::from_ast_binop(binop.node).precedence()
+            }
+            _ => true
+        }
+    }
+
+    pub fn print_expr_maybe_paren(&mut self, expr: &ast::Expr) -> io::Result<()> {
+        let needs_par = needs_parentheses(expr);
+        if needs_par {
+            self.popen()?;
+        }
+        self.print_expr(expr)?;
+        if needs_par {
+            self.pclose()?;
+        }
+        Ok(())
+    }
+
+    fn print_expr_in_place(&mut self,
+                           place: &ast::Expr,
+                           expr: &ast::Expr) -> io::Result<()> {
+        self.print_expr_maybe_paren(place)?;
+        self.s.space()?;
+        self.word_space("<-")?;
+        self.print_expr_maybe_paren(expr)
+    }
+
+    fn print_expr_vec(&mut self, exprs: &[P<ast::Expr>],
+                      attrs: &[Attribute]) -> io::Result<()> {
+        self.ibox(INDENT_UNIT)?;
+        self.s.word("[")?;
+        self.print_inner_attributes_inline(attrs)?;
+        self.commasep_exprs(Inconsistent, &exprs[..])?;
+        self.s.word("]")?;
+        self.end()
+    }
+
+    fn print_expr_repeat(&mut self,
+                         element: &ast::Expr,
+                         count: &ast::Expr,
+                         attrs: &[Attribute]) -> io::Result<()> {
+        self.ibox(INDENT_UNIT)?;
+        self.s.word("[")?;
+        self.print_inner_attributes_inline(attrs)?;
+        self.print_expr(element)?;
+        self.word_space(";")?;
+        self.print_expr(count)?;
+        self.s.word("]")?;
+        self.end()
+    }
+
+    fn print_expr_struct(&mut self,
+                         path: &ast::Path,
+                         fields: &[ast::Field],
+                         wth: &Option<P<ast::Expr>>,
+                         attrs: &[Attribute]) -> io::Result<()> {
+        self.print_path(path, true, 0, false)?;
+        self.s.word("{")?;
+        self.print_inner_attributes_inline(attrs)?;
+        self.commasep_cmnt(
+            Consistent,
+            &fields[..],
+            |s, field| {
+                s.ibox(INDENT_UNIT)?;
+                if !field.is_shorthand {
+                    s.print_ident(field.ident.node)?;
+                    s.word_space(":")?;
+                }
+                s.print_expr(&field.expr)?;
+                s.end()
+            },
+            |f| f.span)?;
+        match *wth {
+            Some(ref expr) => {
+                self.ibox(INDENT_UNIT)?;
+                if !fields.is_empty() {
+                    self.s.word(",")?;
+                    self.s.space()?;
+                }
+                self.s.word("..")?;
+                self.print_expr(expr)?;
+                self.end()?;
+            }
+            _ => if !fields.is_empty() {
+                self.s.word(",")?
+            }
+        }
+        self.s.word("}")?;
+        Ok(())
     }
-}
 
-pub fn purity_to_str(p: ast::purity) -> ~str {
-    match p {
-      ast::impure_fn => ~"impure",
-      ast::unsafe_fn => ~"unsafe",
-      ast::pure_fn => ~"pure",
-      ast::extern_fn => ~"extern"
+    fn print_expr_tup(&mut self, exprs: &[P<ast::Expr>],
+                      attrs: &[Attribute]) -> io::Result<()> {
+        self.popen()?;
+        self.print_inner_attributes_inline(attrs)?;
+        self.commasep_exprs(Inconsistent, &exprs[..])?;
+        if exprs.len() == 1 {
+            self.s.word(",")?;
+        }
+        self.pclose()
     }
-}
 
-pub fn onceness_to_str(o: ast::Onceness) -> ~str {
-    match o {
-        ast::Once => ~"once",
-        ast::Many => ~"many"
+    fn print_expr_call(&mut self,
+                       func: &ast::Expr,
+                       args: &[P<ast::Expr>]) -> io::Result<()> {
+        self.print_expr_maybe_paren(func)?;
+        self.print_call_post(args)
     }
-}
 
-pub fn print_purity(s: @ps, p: ast::purity) {
-    match p {
-      ast::impure_fn => (),
-      _ => word_nbsp(s, purity_to_str(p))
+    fn print_expr_method_call(&mut self,
+                              segment: &ast::PathSegment,
+                              args: &[P<ast::Expr>]) -> io::Result<()> {
+        let base_args = &args[1..];
+        self.print_expr(&args[0])?;
+        self.s.word(".")?;
+        self.print_ident(segment.identifier)?;
+        if let Some(ref parameters) = segment.parameters {
+            self.print_path_parameters(parameters, true)?;
+        }
+        self.print_call_post(base_args)
+    }
+
+    fn print_expr_binary(&mut self,
+                         op: ast::BinOp,
+                         lhs: &ast::Expr,
+                         rhs: &ast::Expr) -> io::Result<()> {
+        if self.check_expr_bin_needs_paren(lhs, op) {
+            self.print_expr_maybe_paren(lhs)?;
+        } else {
+            self.print_expr(lhs)?;
+        }
+        self.s.space()?;
+        self.word_space(op.node.to_string())?;
+        if self.check_expr_bin_needs_paren(rhs, op) {
+            self.print_expr_maybe_paren(rhs)
+        } else {
+            self.print_expr(rhs)
+        }
+    }
+
+    fn print_expr_unary(&mut self,
+                        op: ast::UnOp,
+                        expr: &ast::Expr) -> io::Result<()> {
+        self.s.word(ast::UnOp::to_string(op))?;
+        self.print_expr_maybe_paren(expr)
+    }
+
+    fn print_expr_addr_of(&mut self,
+                          mutability: ast::Mutability,
+                          expr: &ast::Expr) -> io::Result<()> {
+        self.s.word("&")?;
+        self.print_mutability(mutability)?;
+        self.print_expr_maybe_paren(expr)
+    }
+
+    pub fn print_expr(&mut self, expr: &ast::Expr) -> io::Result<()> {
+        self.print_expr_outer_attr_style(expr, true)
+    }
+
+    fn print_expr_outer_attr_style(&mut self,
+                                  expr: &ast::Expr,
+                                  is_inline: bool) -> io::Result<()> {
+        self.maybe_print_comment(expr.span.lo)?;
+
+        let attrs = &expr.attrs;
+        if is_inline {
+            self.print_outer_attributes_inline(attrs)?;
+        } else {
+            self.print_outer_attributes(attrs)?;
+        }
+
+        self.ibox(INDENT_UNIT)?;
+        self.ann.pre(self, NodeExpr(expr))?;
+        match expr.node {
+            ast::ExprKind::Box(ref expr) => {
+                self.word_space("box")?;
+                self.print_expr(expr)?;
+            }
+            ast::ExprKind::InPlace(ref place, ref expr) => {
+                self.print_expr_in_place(place, expr)?;
+            }
+            ast::ExprKind::Array(ref exprs) => {
+                self.print_expr_vec(&exprs[..], attrs)?;
+            }
+            ast::ExprKind::Repeat(ref element, ref count) => {
+                self.print_expr_repeat(element, count, attrs)?;
+            }
+            ast::ExprKind::Struct(ref path, ref fields, ref wth) => {
+                self.print_expr_struct(path, &fields[..], wth, attrs)?;
+            }
+            ast::ExprKind::Tup(ref exprs) => {
+                self.print_expr_tup(&exprs[..], attrs)?;
+            }
+            ast::ExprKind::Call(ref func, ref args) => {
+                self.print_expr_call(func, &args[..])?;
+            }
+            ast::ExprKind::MethodCall(ref segment, ref args) => {
+                self.print_expr_method_call(segment, &args[..])?;
+            }
+            ast::ExprKind::Binary(op, ref lhs, ref rhs) => {
+                self.print_expr_binary(op, lhs, rhs)?;
+            }
+            ast::ExprKind::Unary(op, ref expr) => {
+                self.print_expr_unary(op, expr)?;
+            }
+            ast::ExprKind::AddrOf(m, ref expr) => {
+                self.print_expr_addr_of(m, expr)?;
+            }
+            ast::ExprKind::Lit(ref lit) => {
+                self.print_literal(lit)?;
+            }
+            ast::ExprKind::Cast(ref expr, ref ty) => {
+                if let ast::ExprKind::Cast(..) = expr.node {
+                    self.print_expr(expr)?;
+                } else {
+                    self.print_expr_maybe_paren(expr)?;
+                }
+                self.s.space()?;
+                self.word_space("as")?;
+                self.print_type(ty)?;
+            }
+            ast::ExprKind::Type(ref expr, ref ty) => {
+                self.print_expr(expr)?;
+                self.word_space(":")?;
+                self.print_type(ty)?;
+            }
+            ast::ExprKind::If(ref test, ref blk, ref elseopt) => {
+                self.print_if(test, blk, elseopt.as_ref().map(|e| &**e))?;
+            }
+            ast::ExprKind::IfLet(ref pat, ref expr, ref blk, ref elseopt) => {
+                self.print_if_let(pat, expr, blk, elseopt.as_ref().map(|e| &**e))?;
+            }
+            ast::ExprKind::While(ref test, ref blk, opt_ident) => {
+                if let Some(ident) = opt_ident {
+                    self.print_ident(ident.node)?;
+                    self.word_space(":")?;
+                }
+                self.head("while")?;
+                self.print_expr(test)?;
+                self.s.space()?;
+                self.print_block_with_attrs(blk, attrs)?;
+            }
+            ast::ExprKind::WhileLet(ref pat, ref expr, ref blk, opt_ident) => {
+                if let Some(ident) = opt_ident {
+                    self.print_ident(ident.node)?;
+                    self.word_space(":")?;
+                }
+                self.head("while let")?;
+                self.print_pat(pat)?;
+                self.s.space()?;
+                self.word_space("=")?;
+                self.print_expr(expr)?;
+                self.s.space()?;
+                self.print_block_with_attrs(blk, attrs)?;
+            }
+            ast::ExprKind::ForLoop(ref pat, ref iter, ref blk, opt_ident) => {
+                if let Some(ident) = opt_ident {
+                    self.print_ident(ident.node)?;
+                    self.word_space(":")?;
+                }
+                self.head("for")?;
+                self.print_pat(pat)?;
+                self.s.space()?;
+                self.word_space("in")?;
+                self.print_expr(iter)?;
+                self.s.space()?;
+                self.print_block_with_attrs(blk, attrs)?;
+            }
+            ast::ExprKind::Loop(ref blk, opt_ident) => {
+                if let Some(ident) = opt_ident {
+                    self.print_ident(ident.node)?;
+                    self.word_space(":")?;
+                }
+                self.head("loop")?;
+                self.s.space()?;
+                self.print_block_with_attrs(blk, attrs)?;
+            }
+            ast::ExprKind::Match(ref expr, ref arms) => {
+                self.cbox(INDENT_UNIT)?;
+                self.ibox(4)?;
+                self.word_nbsp("match")?;
+                self.print_expr(expr)?;
+                self.s.space()?;
+                self.bopen()?;
+                self.print_inner_attributes_no_trailing_hardbreak(attrs)?;
+                for arm in arms {
+                    self.print_arm(arm)?;
+                }
+                self.bclose_(expr.span, INDENT_UNIT)?;
+            }
+            ast::ExprKind::Closure(capture_clause, ref decl, ref body, _) => {
+                self.print_capture_clause(capture_clause)?;
+
+                self.print_fn_block_args(decl)?;
+                self.s.space()?;
+                self.print_expr(body)?;
+                self.end()?; // need to close a box
+
+                // a box will be closed by print_expr, but we didn't want an overall
+                // wrapper so we closed the corresponding opening. so create an
+                // empty box to satisfy the close.
+                self.ibox(0)?;
+            }
+            ast::ExprKind::Block(ref blk) => {
+                // containing cbox, will be closed by print-block at }
+                self.cbox(INDENT_UNIT)?;
+                // head-box, will be closed by print-block after {
+                self.ibox(0)?;
+                self.print_block_with_attrs(blk, attrs)?;
+            }
+            ast::ExprKind::Assign(ref lhs, ref rhs) => {
+                self.print_expr(lhs)?;
+                self.s.space()?;
+                self.word_space("=")?;
+                self.print_expr(rhs)?;
+            }
+            ast::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
+                self.print_expr(lhs)?;
+                self.s.space()?;
+                self.s.word(op.node.to_string())?;
+                self.word_space("=")?;
+                self.print_expr(rhs)?;
+            }
+            ast::ExprKind::Field(ref expr, id) => {
+                self.print_expr(expr)?;
+                self.s.word(".")?;
+                self.print_ident(id.node)?;
+            }
+            ast::ExprKind::TupField(ref expr, id) => {
+                self.print_expr(expr)?;
+                self.s.word(".")?;
+                self.print_usize(id.node)?;
+            }
+            ast::ExprKind::Index(ref expr, ref index) => {
+                self.print_expr(expr)?;
+                self.s.word("[")?;
+                self.print_expr(index)?;
+                self.s.word("]")?;
+            }
+            ast::ExprKind::Range(ref start, ref end, limits) => {
+                if let Some(ref e) = *start {
+                    self.print_expr(e)?;
+                }
+                if limits == ast::RangeLimits::HalfOpen {
+                    self.s.word("..")?;
+                } else {
+                    self.s.word("...")?;
+                }
+                if let Some(ref e) = *end {
+                    self.print_expr(e)?;
+                }
+            }
+            ast::ExprKind::Path(None, ref path) => {
+                self.print_path(path, true, 0, false)?
+            }
+            ast::ExprKind::Path(Some(ref qself), ref path) => {
+                self.print_qpath(path, qself, true)?
+            }
+            ast::ExprKind::Break(opt_ident, ref opt_expr) => {
+                self.s.word("break")?;
+                self.s.space()?;
+                if let Some(ident) = opt_ident {
+                    self.print_ident(ident.node)?;
+                    self.s.space()?;
+                }
+                if let Some(ref expr) = *opt_expr {
+                    self.print_expr(expr)?;
+                    self.s.space()?;
+                }
+            }
+            ast::ExprKind::Continue(opt_ident) => {
+                self.s.word("continue")?;
+                self.s.space()?;
+                if let Some(ident) = opt_ident {
+                    self.print_ident(ident.node)?;
+                    self.s.space()?
+                }
+            }
+            ast::ExprKind::Ret(ref result) => {
+                self.s.word("return")?;
+                if let Some(ref expr) = *result {
+                    self.s.word(" ")?;
+                    self.print_expr(expr)?;
+                }
+            }
+            ast::ExprKind::InlineAsm(ref a) => {
+                self.s.word("asm!")?;
+                self.popen()?;
+                self.print_string(&a.asm.as_str(), a.asm_str_style)?;
+                self.word_space(":")?;
+
+                self.commasep(Inconsistent, &a.outputs, |s, out| {
+                    let constraint = out.constraint.as_str();
+                    let mut ch = constraint.chars();
+                    match ch.next() {
+                        Some('=') if out.is_rw => {
+                            s.print_string(&format!("+{}", ch.as_str()),
+                                           ast::StrStyle::Cooked)?
+                        }
+                        _ => s.print_string(&constraint, ast::StrStyle::Cooked)?
+                    }
+                    s.popen()?;
+                    s.print_expr(&out.expr)?;
+                    s.pclose()?;
+                    Ok(())
+                })?;
+                self.s.space()?;
+                self.word_space(":")?;
+
+                self.commasep(Inconsistent, &a.inputs, |s, &(co, ref o)| {
+                    s.print_string(&co.as_str(), ast::StrStyle::Cooked)?;
+                    s.popen()?;
+                    s.print_expr(o)?;
+                    s.pclose()?;
+                    Ok(())
+                })?;
+                self.s.space()?;
+                self.word_space(":")?;
+
+                self.commasep(Inconsistent, &a.clobbers,
+                                   |s, co| {
+                    s.print_string(&co.as_str(), ast::StrStyle::Cooked)?;
+                    Ok(())
+                })?;
+
+                let mut options = vec![];
+                if a.volatile {
+                    options.push("volatile");
+                }
+                if a.alignstack {
+                    options.push("alignstack");
+                }
+                if a.dialect == ast::AsmDialect::Intel {
+                    options.push("intel");
+                }
+
+                if !options.is_empty() {
+                    self.s.space()?;
+                    self.word_space(":")?;
+                    self.commasep(Inconsistent, &options,
+                                  |s, &co| {
+                                      s.print_string(co, ast::StrStyle::Cooked)?;
+                                      Ok(())
+                                  })?;
+                }
+
+                self.pclose()?;
+            }
+            ast::ExprKind::Mac(ref m) => self.print_mac(m, token::Paren)?,
+            ast::ExprKind::Paren(ref e) => {
+                self.popen()?;
+                self.print_inner_attributes_inline(attrs)?;
+                self.print_expr(e)?;
+                self.pclose()?;
+            },
+            ast::ExprKind::Try(ref e) => {
+                self.print_expr(e)?;
+                self.s.word("?")?
+            }
+            ast::ExprKind::Catch(ref blk) => {
+                self.head("do catch")?;
+                self.s.space()?;
+                self.print_block_with_attrs(blk, attrs)?
+            }
+        }
+        self.ann.post(self, NodeExpr(expr))?;
+        self.end()
+    }
+
+    pub fn print_local_decl(&mut self, loc: &ast::Local) -> io::Result<()> {
+        self.print_pat(&loc.pat)?;
+        if let Some(ref ty) = loc.ty {
+            self.word_space(":")?;
+            self.print_type(ty)?;
+        }
+        Ok(())
+    }
+
+    pub fn print_ident(&mut self, ident: ast::Ident) -> io::Result<()> {
+        self.s.word(&ident.name.as_str())?;
+        self.ann.post(self, NodeIdent(&ident))
+    }
+
+    pub fn print_usize(&mut self, i: usize) -> io::Result<()> {
+        self.s.word(&i.to_string())
+    }
+
+    pub fn print_name(&mut self, name: ast::Name) -> io::Result<()> {
+        self.s.word(&name.as_str())?;
+        self.ann.post(self, NodeName(&name))
     }
-}
 
-pub fn print_onceness(s: @ps, o: ast::Onceness) {
-    match o {
-        ast::Once => { word_nbsp(s, ~"once"); }
-        ast::Many => {}
+    pub fn print_for_decl(&mut self, loc: &ast::Local,
+                          coll: &ast::Expr) -> io::Result<()> {
+        self.print_local_decl(loc)?;
+        self.s.space()?;
+        self.word_space("in")?;
+        self.print_expr(coll)
+    }
+
+    fn print_path(&mut self,
+                  path: &ast::Path,
+                  colons_before_params: bool,
+                  depth: usize,
+                  defaults_to_global: bool)
+                  -> io::Result<()>
+    {
+        self.maybe_print_comment(path.span.lo)?;
+
+        let mut segments = path.segments[..path.segments.len()-depth].iter();
+        if defaults_to_global && path.is_global() {
+            segments.next();
+        }
+        for (i, segment) in segments.enumerate() {
+            if i > 0 {
+                self.s.word("::")?
+            }
+            self.print_path_segment(segment, colons_before_params)?;
+        }
+
+        Ok(())
+    }
+
+    fn print_path_segment(&mut self,
+                          segment: &ast::PathSegment,
+                          colons_before_params: bool)
+                          -> io::Result<()>
+    {
+        if segment.identifier.name != keywords::CrateRoot.name() &&
+           segment.identifier.name != keywords::DollarCrate.name() {
+            self.print_ident(segment.identifier)?;
+            if let Some(ref parameters) = segment.parameters {
+                self.print_path_parameters(parameters, colons_before_params)?;
+            }
+        }
+        Ok(())
+    }
+
+    fn print_qpath(&mut self,
+                   path: &ast::Path,
+                   qself: &ast::QSelf,
+                   colons_before_params: bool)
+                   -> io::Result<()>
+    {
+        self.s.word("<")?;
+        self.print_type(&qself.ty)?;
+        if qself.position > 0 {
+            self.s.space()?;
+            self.word_space("as")?;
+            let depth = path.segments.len() - qself.position;
+            self.print_path(path, false, depth, false)?;
+        }
+        self.s.word(">")?;
+        self.s.word("::")?;
+        let item_segment = path.segments.last().unwrap();
+        self.print_ident(item_segment.identifier)?;
+        match item_segment.parameters {
+            Some(ref parameters) => self.print_path_parameters(parameters, colons_before_params),
+            None => Ok(()),
+        }
+    }
+
+    fn print_path_parameters(&mut self,
+                             parameters: &ast::PathParameters,
+                             colons_before_params: bool)
+                             -> io::Result<()>
+    {
+        if colons_before_params {
+            self.s.word("::")?
+        }
+
+        match *parameters {
+            ast::PathParameters::AngleBracketed(ref data) => {
+                self.s.word("<")?;
+
+                let mut comma = false;
+                for lifetime in &data.lifetimes {
+                    if comma {
+                        self.word_space(",")?
+                    }
+                    self.print_lifetime(lifetime)?;
+                    comma = true;
+                }
+
+                if !data.types.is_empty() {
+                    if comma {
+                        self.word_space(",")?
+                    }
+                    self.commasep(
+                        Inconsistent,
+                        &data.types,
+                        |s, ty| s.print_type(ty))?;
+                        comma = true;
+                }
+
+                for binding in data.bindings.iter() {
+                    if comma {
+                        self.word_space(",")?
+                    }
+                    self.print_ident(binding.ident)?;
+                    self.s.space()?;
+                    self.word_space("=")?;
+                    self.print_type(&binding.ty)?;
+                    comma = true;
+                }
+
+                self.s.word(">")?
+            }
+
+            ast::PathParameters::Parenthesized(ref data) => {
+                self.s.word("(")?;
+                self.commasep(
+                    Inconsistent,
+                    &data.inputs,
+                    |s, ty| s.print_type(ty))?;
+                self.s.word(")")?;
+
+                if let Some(ref ty) = data.output {
+                    self.space_if_not_bol()?;
+                    self.word_space("->")?;
+                    self.print_type(ty)?;
+                }
+            }
+        }
+
+        Ok(())
+    }
+
+    pub fn print_pat(&mut self, pat: &ast::Pat) -> io::Result<()> {
+        self.maybe_print_comment(pat.span.lo)?;
+        self.ann.pre(self, NodePat(pat))?;
+        /* Pat isn't normalized, but the beauty of it
+         is that it doesn't matter */
+        match pat.node {
+            PatKind::Wild => self.s.word("_")?,
+            PatKind::Ident(binding_mode, ref path1, ref sub) => {
+                match binding_mode {
+                    ast::BindingMode::ByRef(mutbl) => {
+                        self.word_nbsp("ref")?;
+                        self.print_mutability(mutbl)?;
+                    }
+                    ast::BindingMode::ByValue(ast::Mutability::Immutable) => {}
+                    ast::BindingMode::ByValue(ast::Mutability::Mutable) => {
+                        self.word_nbsp("mut")?;
+                    }
+                }
+                self.print_ident(path1.node)?;
+                if let Some(ref p) = *sub {
+                    self.s.word("@")?;
+                    self.print_pat(p)?;
+                }
+            }
+            PatKind::TupleStruct(ref path, ref elts, ddpos) => {
+                self.print_path(path, true, 0, false)?;
+                self.popen()?;
+                if let Some(ddpos) = ddpos {
+                    self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(p))?;
+                    if ddpos != 0 {
+                        self.word_space(",")?;
+                    }
+                    self.s.word("..")?;
+                    if ddpos != elts.len() {
+                        self.s.word(",")?;
+                        self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(p))?;
+                    }
+                } else {
+                    self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(p))?;
+                }
+                self.pclose()?;
+            }
+            PatKind::Path(None, ref path) => {
+                self.print_path(path, true, 0, false)?;
+            }
+            PatKind::Path(Some(ref qself), ref path) => {
+                self.print_qpath(path, qself, false)?;
+            }
+            PatKind::Struct(ref path, ref fields, etc) => {
+                self.print_path(path, true, 0, false)?;
+                self.nbsp()?;
+                self.word_space("{")?;
+                self.commasep_cmnt(
+                    Consistent, &fields[..],
+                    |s, f| {
+                        s.cbox(INDENT_UNIT)?;
+                        if !f.node.is_shorthand {
+                            s.print_ident(f.node.ident)?;
+                            s.word_nbsp(":")?;
+                        }
+                        s.print_pat(&f.node.pat)?;
+                        s.end()
+                    },
+                    |f| f.node.pat.span)?;
+                if etc {
+                    if !fields.is_empty() { self.word_space(",")?; }
+                    self.s.word("..")?;
+                }
+                self.s.space()?;
+                self.s.word("}")?;
+            }
+            PatKind::Tuple(ref elts, ddpos) => {
+                self.popen()?;
+                if let Some(ddpos) = ddpos {
+                    self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(p))?;
+                    if ddpos != 0 {
+                        self.word_space(",")?;
+                    }
+                    self.s.word("..")?;
+                    if ddpos != elts.len() {
+                        self.s.word(",")?;
+                        self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(p))?;
+                    }
+                } else {
+                    self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(p))?;
+                    if elts.len() == 1 {
+                        self.s.word(",")?;
+                    }
+                }
+                self.pclose()?;
+            }
+            PatKind::Box(ref inner) => {
+                self.s.word("box ")?;
+                self.print_pat(inner)?;
+            }
+            PatKind::Ref(ref inner, mutbl) => {
+                self.s.word("&")?;
+                if mutbl == ast::Mutability::Mutable {
+                    self.s.word("mut ")?;
+                }
+                self.print_pat(inner)?;
+            }
+            PatKind::Lit(ref e) => self.print_expr(&**e)?,
+            PatKind::Range(ref begin, ref end, ref end_kind) => {
+                self.print_expr(begin)?;
+                self.s.space()?;
+                match *end_kind {
+                    RangeEnd::Included => self.s.word("...")?,
+                    RangeEnd::Excluded => self.s.word("..")?,
+                }
+                self.print_expr(end)?;
+            }
+            PatKind::Slice(ref before, ref slice, ref after) => {
+                self.s.word("[")?;
+                self.commasep(Inconsistent,
+                                   &before[..],
+                                   |s, p| s.print_pat(p))?;
+                if let Some(ref p) = *slice {
+                    if !before.is_empty() { self.word_space(",")?; }
+                    if p.node != PatKind::Wild {
+                        self.print_pat(p)?;
+                    }
+                    self.s.word("..")?;
+                    if !after.is_empty() { self.word_space(",")?; }
+                }
+                self.commasep(Inconsistent,
+                                   &after[..],
+                                   |s, p| s.print_pat(p))?;
+                self.s.word("]")?;
+            }
+            PatKind::Mac(ref m) => self.print_mac(m, token::Paren)?,
+        }
+        self.ann.post(self, NodePat(pat))
+    }
+
+    fn print_arm(&mut self, arm: &ast::Arm) -> io::Result<()> {
+        // I have no idea why this check is necessary, but here it
+        // is :(
+        if arm.attrs.is_empty() {
+            self.s.space()?;
+        }
+        self.cbox(INDENT_UNIT)?;
+        self.ibox(0)?;
+        self.maybe_print_comment(arm.pats[0].span.lo)?;
+        self.print_outer_attributes(&arm.attrs)?;
+        let mut first = true;
+        for p in &arm.pats {
+            if first {
+                first = false;
+            } else {
+                self.s.space()?;
+                self.word_space("|")?;
+            }
+            self.print_pat(p)?;
+        }
+        self.s.space()?;
+        if let Some(ref e) = arm.guard {
+            self.word_space("if")?;
+            self.print_expr(e)?;
+            self.s.space()?;
+        }
+        self.word_space("=>")?;
+
+        match arm.body.node {
+            ast::ExprKind::Block(ref blk) => {
+                // the block will close the pattern's ibox
+                self.print_block_unclosed_indent(blk, INDENT_UNIT)?;
+
+                // If it is a user-provided unsafe block, print a comma after it
+                if let BlockCheckMode::Unsafe(ast::UserProvided) = blk.rules {
+                    self.s.word(",")?;
+                }
+            }
+            _ => {
+                self.end()?; // close the ibox for the pattern
+                self.print_expr(&arm.body)?;
+                self.s.word(",")?;
+            }
+        }
+        self.end() // close enclosing cbox
+    }
+
+    fn print_explicit_self(&mut self, explicit_self: &ast::ExplicitSelf) -> io::Result<()> {
+        match explicit_self.node {
+            SelfKind::Value(m) => {
+                self.print_mutability(m)?;
+                self.s.word("self")
+            }
+            SelfKind::Region(ref lt, m) => {
+                self.s.word("&")?;
+                self.print_opt_lifetime(lt)?;
+                self.print_mutability(m)?;
+                self.s.word("self")
+            }
+            SelfKind::Explicit(ref typ, m) => {
+                self.print_mutability(m)?;
+                self.s.word("self")?;
+                self.word_space(":")?;
+                self.print_type(typ)
+            }
+        }
+    }
+
+    pub fn print_fn(&mut self,
+                    decl: &ast::FnDecl,
+                    unsafety: ast::Unsafety,
+                    constness: ast::Constness,
+                    abi: abi::Abi,
+                    name: Option<ast::Ident>,
+                    generics: &ast::Generics,
+                    vis: &ast::Visibility) -> io::Result<()> {
+        self.print_fn_header_info(unsafety, constness, abi, vis)?;
+
+        if let Some(name) = name {
+            self.nbsp()?;
+            self.print_ident(name)?;
+        }
+        self.print_generics(generics)?;
+        self.print_fn_args_and_ret(decl)?;
+        self.print_where_clause(&generics.where_clause)
+    }
+
+    pub fn print_fn_args_and_ret(&mut self, decl: &ast::FnDecl)
+        -> io::Result<()> {
+        self.popen()?;
+        self.commasep(Inconsistent, &decl.inputs, |s, arg| s.print_arg(arg, false))?;
+        if decl.variadic {
+            self.s.word(", ...")?;
+        }
+        self.pclose()?;
+
+        self.print_fn_output(decl)
+    }
+
+    pub fn print_fn_block_args(
+            &mut self,
+            decl: &ast::FnDecl)
+            -> io::Result<()> {
+        self.s.word("|")?;
+        self.commasep(Inconsistent, &decl.inputs, |s, arg| s.print_arg(arg, true))?;
+        self.s.word("|")?;
+
+        if let ast::FunctionRetTy::Default(..) = decl.output {
+            return Ok(());
+        }
+
+        self.space_if_not_bol()?;
+        self.word_space("->")?;
+        match decl.output {
+            ast::FunctionRetTy::Ty(ref ty) => {
+                self.print_type(ty)?;
+                self.maybe_print_comment(ty.span.lo)
+            }
+            ast::FunctionRetTy::Default(..) => unreachable!(),
+        }
+    }
+
+    pub fn print_capture_clause(&mut self, capture_clause: ast::CaptureBy)
+                                -> io::Result<()> {
+        match capture_clause {
+            ast::CaptureBy::Value => self.word_space("move"),
+            ast::CaptureBy::Ref => Ok(()),
+        }
+    }
+
+    pub fn print_bounds(&mut self,
+                        prefix: &str,
+                        bounds: &[ast::TyParamBound])
+                        -> io::Result<()> {
+        if !bounds.is_empty() {
+            self.s.word(prefix)?;
+            let mut first = true;
+            for bound in bounds {
+                self.nbsp()?;
+                if first {
+                    first = false;
+                } else {
+                    self.word_space("+")?;
+                }
+
+                (match *bound {
+                    TraitTyParamBound(ref tref, TraitBoundModifier::None) => {
+                        self.print_poly_trait_ref(tref)
+                    }
+                    TraitTyParamBound(ref tref, TraitBoundModifier::Maybe) => {
+                        self.s.word("?")?;
+                        self.print_poly_trait_ref(tref)
+                    }
+                    RegionTyParamBound(ref lt) => {
+                        self.print_lifetime(lt)
+                    }
+                })?
+            }
+            Ok(())
+        } else {
+            Ok(())
+        }
+    }
+
+    pub fn print_lifetime(&mut self,
+                          lifetime: &ast::Lifetime)
+                          -> io::Result<()>
+    {
+        self.print_name(lifetime.ident.name)
+    }
+
+    pub fn print_lifetime_bounds(&mut self,
+                                 lifetime: &ast::Lifetime,
+                                 bounds: &[ast::Lifetime])
+                                 -> io::Result<()>
+    {
+        self.print_lifetime(lifetime)?;
+        if !bounds.is_empty() {
+            self.s.word(": ")?;
+            for (i, bound) in bounds.iter().enumerate() {
+                if i != 0 {
+                    self.s.word(" + ")?;
+                }
+                self.print_lifetime(bound)?;
+            }
+        }
+        Ok(())
+    }
+
+    pub fn print_generics(&mut self,
+                          generics: &ast::Generics)
+                          -> io::Result<()>
+    {
+        let total = generics.lifetimes.len() + generics.ty_params.len();
+        if total == 0 {
+            return Ok(());
+        }
+
+        self.s.word("<")?;
+
+        let mut ints = Vec::new();
+        for i in 0..total {
+            ints.push(i);
+        }
+
+        self.commasep(Inconsistent, &ints[..], |s, &idx| {
+            if idx < generics.lifetimes.len() {
+                let lifetime_def = &generics.lifetimes[idx];
+                s.print_outer_attributes_inline(&lifetime_def.attrs)?;
+                s.print_lifetime_bounds(&lifetime_def.lifetime, &lifetime_def.bounds)
+            } else {
+                let idx = idx - generics.lifetimes.len();
+                let param = &generics.ty_params[idx];
+                s.print_ty_param(param)
+            }
+        })?;
+
+        self.s.word(">")?;
+        Ok(())
+    }
+
+    pub fn print_ty_param(&mut self, param: &ast::TyParam) -> io::Result<()> {
+        self.print_outer_attributes_inline(&param.attrs)?;
+        self.print_ident(param.ident)?;
+        self.print_bounds(":", &param.bounds)?;
+        match param.default {
+            Some(ref default) => {
+                self.s.space()?;
+                self.word_space("=")?;
+                self.print_type(default)
+            }
+            _ => Ok(())
+        }
+    }
+
+    pub fn print_where_clause(&mut self, where_clause: &ast::WhereClause)
+                              -> io::Result<()> {
+        if where_clause.predicates.is_empty() {
+            return Ok(())
+        }
+
+        self.s.space()?;
+        self.word_space("where")?;
+
+        for (i, predicate) in where_clause.predicates.iter().enumerate() {
+            if i != 0 {
+                self.word_space(",")?;
+            }
+
+            match *predicate {
+                ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate{ref bound_lifetimes,
+                                                                             ref bounded_ty,
+                                                                             ref bounds,
+                                                                             ..}) => {
+                    self.print_formal_lifetime_list(bound_lifetimes)?;
+                    self.print_type(bounded_ty)?;
+                    self.print_bounds(":", bounds)?;
+                }
+                ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate{ref lifetime,
+                                                                               ref bounds,
+                                                                               ..}) => {
+                    self.print_lifetime_bounds(lifetime, bounds)?;
+                }
+                ast::WherePredicate::EqPredicate(ast::WhereEqPredicate{ref lhs_ty,
+                                                                       ref rhs_ty,
+                                                                       ..}) => {
+                    self.print_type(lhs_ty)?;
+                    self.s.space()?;
+                    self.word_space("=")?;
+                    self.print_type(rhs_ty)?;
+                }
+            }
+        }
+
+        Ok(())
+    }
+
+    pub fn print_view_path(&mut self, vp: &ast::ViewPath) -> io::Result<()> {
+        match vp.node {
+            ast::ViewPathSimple(ident, ref path) => {
+                self.print_path(path, false, 0, true)?;
+
+                if path.segments.last().unwrap().identifier.name !=
+                        ident.name {
+                    self.s.space()?;
+                    self.word_space("as")?;
+                    self.print_ident(ident)?;
+                }
+
+                Ok(())
+            }
+
+            ast::ViewPathGlob(ref path) => {
+                self.print_path(path, false, 0, true)?;
+                self.s.word("::*")
+            }
+
+            ast::ViewPathList(ref path, ref idents) => {
+                if path.segments.is_empty() {
+                    self.s.word("{")?;
+                } else {
+                    self.print_path(path, false, 0, true)?;
+                    self.s.word("::{")?;
+                }
+                self.commasep(Inconsistent, &idents[..], |s, w| {
+                    s.print_ident(w.node.name)?;
+                    if let Some(ident) = w.node.rename {
+                        s.s.space()?;
+                        s.word_space("as")?;
+                        s.print_ident(ident)?;
+                    }
+                    Ok(())
+                })?;
+                self.s.word("}")
+            }
+        }
+    }
+
+    pub fn print_mutability(&mut self,
+                            mutbl: ast::Mutability) -> io::Result<()> {
+        match mutbl {
+            ast::Mutability::Mutable => self.word_nbsp("mut"),
+            ast::Mutability::Immutable => Ok(()),
+        }
+    }
+
+    pub fn print_mt(&mut self, mt: &ast::MutTy) -> io::Result<()> {
+        self.print_mutability(mt.mutbl)?;
+        self.print_type(&mt.ty)
+    }
+
+    pub fn print_arg(&mut self, input: &ast::Arg, is_closure: bool) -> io::Result<()> {
+        self.ibox(INDENT_UNIT)?;
+        match input.ty.node {
+            ast::TyKind::Infer if is_closure => self.print_pat(&input.pat)?,
+            _ => {
+                if let Some(eself) = input.to_self() {
+                    self.print_explicit_self(&eself)?;
+                } else {
+                    let invalid = if let PatKind::Ident(_, ident, _) = input.pat.node {
+                        ident.node.name == keywords::Invalid.name()
+                    } else {
+                        false
+                    };
+                    if !invalid {
+                        self.print_pat(&input.pat)?;
+                        self.s.word(":")?;
+                        self.s.space()?;
+                    }
+                    self.print_type(&input.ty)?;
+                }
+            }
+        }
+        self.end()
+    }
+
+    pub fn print_fn_output(&mut self, decl: &ast::FnDecl) -> io::Result<()> {
+        if let ast::FunctionRetTy::Default(..) = decl.output {
+            return Ok(());
+        }
+
+        self.space_if_not_bol()?;
+        self.ibox(INDENT_UNIT)?;
+        self.word_space("->")?;
+        match decl.output {
+            ast::FunctionRetTy::Default(..) => unreachable!(),
+            ast::FunctionRetTy::Ty(ref ty) =>
+                self.print_type(ty)?
+        }
+        self.end()?;
+
+        match decl.output {
+            ast::FunctionRetTy::Ty(ref output) => self.maybe_print_comment(output.span.lo),
+            _ => Ok(())
+        }
+    }
+
+    pub fn print_ty_fn(&mut self,
+                       abi: abi::Abi,
+                       unsafety: ast::Unsafety,
+                       decl: &ast::FnDecl,
+                       name: Option<ast::Ident>,
+                       generics: &ast::Generics)
+                       -> io::Result<()> {
+        self.ibox(INDENT_UNIT)?;
+        if !generics.lifetimes.is_empty() || !generics.ty_params.is_empty() {
+            self.s.word("for")?;
+            self.print_generics(generics)?;
+        }
+        let generics = ast::Generics {
+            lifetimes: Vec::new(),
+            ty_params: Vec::new(),
+            where_clause: ast::WhereClause {
+                id: ast::DUMMY_NODE_ID,
+                predicates: Vec::new(),
+            },
+            span: syntax_pos::DUMMY_SP,
+        };
+        self.print_fn(decl,
+                      unsafety,
+                      ast::Constness::NotConst,
+                      abi,
+                      name,
+                      &generics,
+                      &ast::Visibility::Inherited)?;
+        self.end()
+    }
+
+    pub fn maybe_print_trailing_comment(&mut self, span: syntax_pos::Span,
+                                        next_pos: Option<BytePos>)
+        -> io::Result<()> {
+        let cm = match self.cm {
+            Some(cm) => cm,
+            _ => return Ok(())
+        };
+        if let Some(ref cmnt) = self.next_comment() {
+            if cmnt.style != comments::Trailing { return Ok(()) }
+            let span_line = cm.lookup_char_pos(span.hi);
+            let comment_line = cm.lookup_char_pos(cmnt.pos);
+            let next = next_pos.unwrap_or(cmnt.pos + BytePos(1));
+            if span.hi < cmnt.pos && cmnt.pos < next && span_line.line == comment_line.line {
+                self.print_comment(cmnt)?;
+            }
+        }
+        Ok(())
+    }
+
+    pub fn print_remaining_comments(&mut self) -> io::Result<()> {
+        // If there aren't any remaining comments, then we need to manually
+        // make sure there is a line break at the end.
+        if self.next_comment().is_none() {
+            self.s.hardbreak()?;
+        }
+        while let Some(ref cmnt) = self.next_comment() {
+            self.print_comment(cmnt)?;
+        }
+        Ok(())
+    }
+
+    pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
+                                                  opt_abi: Option<Abi>)
+        -> io::Result<()> {
+        match opt_abi {
+            Some(Abi::Rust) => Ok(()),
+            Some(abi) => {
+                self.word_nbsp("extern")?;
+                self.word_nbsp(&abi.to_string())
+            }
+            None => Ok(())
+        }
+    }
+
+    pub fn print_extern_opt_abi(&mut self,
+                                opt_abi: Option<Abi>) -> io::Result<()> {
+        match opt_abi {
+            Some(abi) => {
+                self.word_nbsp("extern")?;
+                self.word_nbsp(&abi.to_string())
+            }
+            None => Ok(())
+        }
+    }
+
+    pub fn print_fn_header_info(&mut self,
+                                unsafety: ast::Unsafety,
+                                constness: ast::Constness,
+                                abi: Abi,
+                                vis: &ast::Visibility) -> io::Result<()> {
+        self.s.word(&visibility_qualified(vis, ""))?;
+
+        match constness {
+            ast::Constness::NotConst => {}
+            ast::Constness::Const => self.word_nbsp("const")?
+        }
+
+        self.print_unsafety(unsafety)?;
+
+        if abi != Abi::Rust {
+            self.word_nbsp("extern")?;
+            self.word_nbsp(&abi.to_string())?;
+        }
+
+        self.s.word("fn")
+    }
+
+    pub fn print_unsafety(&mut self, s: ast::Unsafety) -> io::Result<()> {
+        match s {
+            ast::Unsafety::Normal => Ok(()),
+            ast::Unsafety::Unsafe => self.word_nbsp("unsafe"),
+        }
     }
 }
 
+fn repeat(s: &str, n: usize) -> String { iter::repeat(s).take(n).collect() }
+
 #[cfg(test)]
-pub mod test {
+mod tests {
     use super::*;
 
     use ast;
-    use ast_util;
     use codemap;
-    use core::cmp::Eq;
-    use core::option::None;
-    use parse;
-
-    fn string_check<T:Eq> (given : &T, expected: &T) {
-        if !(given == expected) {
-            fail!(fmt!("given %?, expected %?",given,expected));
-        }
-    }
+    use syntax_pos;
 
     #[test]
-    fn test_fun_to_str() {
-        let mock_interner = parse::token::mk_fake_ident_interner();
-        let abba_ident = mock_interner.intern(@~"abba");
-
-        let decl = ast::fn_decl {
-            inputs: ~[],
-            output: @ast::Ty {id: 0,
-                              node: ast::ty_nil,
-                              span: codemap::dummy_sp()},
-            cf: ast::return_val
+    fn test_fun_to_string() {
+        let abba_ident = ast::Ident::from_str("abba");
+
+        let decl = ast::FnDecl {
+            inputs: Vec::new(),
+            output: ast::FunctionRetTy::Default(syntax_pos::DUMMY_SP),
+            variadic: false
         };
-        let generics = ast_util::empty_generics();
-        assert_eq!(&fun_to_str(&decl, ast::impure_fn, abba_ident,
-                               None, &generics, mock_interner),
-                   &~"fn abba()");
+        let generics = ast::Generics::default();
+        assert_eq!(fun_to_string(&decl, ast::Unsafety::Normal,
+                                 ast::Constness::NotConst,
+                                 abba_ident, &generics),
+                   "fn abba()");
     }
 
     #[test]
-    fn test_variant_to_str() {
-        let mock_interner = parse::token::mk_fake_ident_interner();
-        let ident = mock_interner.intern(@~"principal_skinner");
+    fn test_variant_to_string() {
+        let ident = ast::Ident::from_str("principal_skinner");
 
-        let var = codemap::respan(codemap::dummy_sp(), ast::variant_ {
+        let var = codemap::respan(syntax_pos::DUMMY_SP, ast::Variant_ {
             name: ident,
-            attrs: ~[],
+            attrs: Vec::new(),
             // making this up as I go.... ?
-            kind: ast::tuple_variant_kind(~[]),
-            id: 0,
+            data: ast::VariantData::Unit(ast::DUMMY_NODE_ID),
             disr_expr: None,
-            vis: ast::public,
         });
 
-        let varstr = variant_to_str(var,mock_interner);
-        assert_eq!(&varstr,&~"pub principal_skinner");
+        let varstr = variant_to_string(&var);
+        assert_eq!(varstr, "principal_skinner");
     }
 }
-
-//
-// Local Variables:
-// mode: rust
-// fill-column: 78;
-// indent-tabs-mode: nil
-// c-basic-offset: 4
-// buffer-file-coding-system: utf-8-unix
-// End:
-//