]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/print/pprust.rs
rollup merge of #20247: steveklabnik/gh20088
[rust.git] / src / libsyntax / print / pprust.rs
1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 pub use self::AnnNode::*;
12
13 use abi;
14 use ast::{mod, FnUnboxedClosureKind, FnMutUnboxedClosureKind};
15 use ast::{FnOnceUnboxedClosureKind};
16 use ast::{MethodImplItem, RegionTyParamBound, TraitTyParamBound, TraitBoundModifier};
17 use ast::{RequiredMethod, ProvidedMethod, TypeImplItem, TypeTraitItem};
18 use ast::{UnboxedClosureKind};
19 use ast_util;
20 use owned_slice::OwnedSlice;
21 use attr::{AttrMetaMethods, AttributeMethods};
22 use codemap::{mod, CodeMap, BytePos};
23 use diagnostic;
24 use parse::token::{mod, BinOpToken, Token};
25 use parse::lexer::comments;
26 use parse;
27 use print::pp::{mod, break_offset, word, space, zerobreak, hardbreak};
28 use print::pp::{Breaks, Consistent, Inconsistent, eof};
29 use ptr::P;
30
31 use std::{ascii, mem};
32 use std::io::{mod, IoResult};
33 use std::iter;
34
35 pub enum AnnNode<'a> {
36     NodeIdent(&'a ast::Ident),
37     NodeName(&'a ast::Name),
38     NodeBlock(&'a ast::Block),
39     NodeItem(&'a ast::Item),
40     NodeExpr(&'a ast::Expr),
41     NodePat(&'a ast::Pat),
42 }
43
44 pub trait PpAnn {
45     fn pre(&self, _state: &mut State, _node: AnnNode) -> IoResult<()> { Ok(()) }
46     fn post(&self, _state: &mut State, _node: AnnNode) -> IoResult<()> { Ok(()) }
47 }
48
49 #[deriving(Copy)]
50 pub struct NoAnn;
51
52 impl PpAnn for NoAnn {}
53
54 #[deriving(Copy)]
55 pub struct CurrentCommentAndLiteral {
56     cur_cmnt: uint,
57     cur_lit: uint,
58 }
59
60 pub struct State<'a> {
61     pub s: pp::Printer,
62     cm: Option<&'a CodeMap>,
63     comments: Option<Vec<comments::Comment> >,
64     literals: Option<Vec<comments::Literal> >,
65     cur_cmnt_and_lit: CurrentCommentAndLiteral,
66     boxes: Vec<pp::Breaks>,
67     ann: &'a (PpAnn+'a),
68     encode_idents_with_hygiene: bool,
69 }
70
71 pub fn rust_printer(writer: Box<io::Writer+'static>) -> State<'static> {
72     static NO_ANN: NoAnn = NoAnn;
73     rust_printer_annotated(writer, &NO_ANN)
74 }
75
76 pub fn rust_printer_annotated<'a>(writer: Box<io::Writer+'static>,
77                                   ann: &'a PpAnn) -> State<'a> {
78     State {
79         s: pp::mk_printer(writer, default_columns),
80         cm: None,
81         comments: None,
82         literals: None,
83         cur_cmnt_and_lit: CurrentCommentAndLiteral {
84             cur_cmnt: 0,
85             cur_lit: 0
86         },
87         boxes: Vec::new(),
88         ann: ann,
89         encode_idents_with_hygiene: false,
90     }
91 }
92
93 #[allow(non_upper_case_globals)]
94 pub const indent_unit: uint = 4u;
95
96 #[allow(non_upper_case_globals)]
97 pub const default_columns: uint = 78u;
98
99 /// Requires you to pass an input filename and reader so that
100 /// it can scan the input text for comments and literals to
101 /// copy forward.
102 pub fn print_crate<'a>(cm: &'a CodeMap,
103                        span_diagnostic: &diagnostic::SpanHandler,
104                        krate: &ast::Crate,
105                        filename: String,
106                        input: &mut io::Reader,
107                        out: Box<io::Writer+'static>,
108                        ann: &'a PpAnn,
109                        is_expanded: bool) -> IoResult<()> {
110     let mut s = State::new_from_input(cm,
111                                       span_diagnostic,
112                                       filename,
113                                       input,
114                                       out,
115                                       ann,
116                                       is_expanded);
117     try!(s.print_mod(&krate.module, krate.attrs[]));
118     try!(s.print_remaining_comments());
119     eof(&mut s.s)
120 }
121
122 impl<'a> State<'a> {
123     pub fn new_from_input(cm: &'a CodeMap,
124                           span_diagnostic: &diagnostic::SpanHandler,
125                           filename: String,
126                           input: &mut io::Reader,
127                           out: Box<io::Writer+'static>,
128                           ann: &'a PpAnn,
129                           is_expanded: bool) -> State<'a> {
130         let (cmnts, lits) = comments::gather_comments_and_literals(
131             span_diagnostic,
132             filename,
133             input);
134
135         State::new(
136             cm,
137             out,
138             ann,
139             Some(cmnts),
140             // If the code is post expansion, don't use the table of
141             // literals, since it doesn't correspond with the literals
142             // in the AST anymore.
143             if is_expanded { None } else { Some(lits) })
144     }
145
146     pub fn new(cm: &'a CodeMap,
147                out: Box<io::Writer+'static>,
148                ann: &'a PpAnn,
149                comments: Option<Vec<comments::Comment>>,
150                literals: Option<Vec<comments::Literal>>) -> State<'a> {
151         State {
152             s: pp::mk_printer(out, default_columns),
153             cm: Some(cm),
154             comments: comments,
155             literals: literals,
156             cur_cmnt_and_lit: CurrentCommentAndLiteral {
157                 cur_cmnt: 0,
158                 cur_lit: 0
159             },
160             boxes: Vec::new(),
161             ann: ann,
162             encode_idents_with_hygiene: false,
163         }
164     }
165 }
166
167 pub fn to_string<F>(f: F) -> String where
168     F: FnOnce(&mut State) -> IoResult<()>,
169 {
170     use std::raw::TraitObject;
171     let mut s = rust_printer(box Vec::new());
172     f(&mut s).unwrap();
173     eof(&mut s.s).unwrap();
174     let wr = unsafe {
175         // FIXME(pcwalton): A nasty function to extract the string from an `io::Writer`
176         // that we "know" to be a `Vec<u8>` that works around the lack of checked
177         // downcasts.
178         let obj: &TraitObject = mem::transmute(&s.s.out);
179         mem::transmute::<*mut (), &Vec<u8>>(obj.data)
180     };
181     String::from_utf8(wr.clone()).unwrap()
182 }
183
184 pub fn binop_to_string(op: BinOpToken) -> &'static str {
185     match op {
186         token::Plus     => "+",
187         token::Minus    => "-",
188         token::Star     => "*",
189         token::Slash    => "/",
190         token::Percent  => "%",
191         token::Caret    => "^",
192         token::And      => "&",
193         token::Or       => "|",
194         token::Shl      => "<<",
195         token::Shr      => ">>",
196     }
197 }
198
199 pub fn token_to_string(tok: &Token) -> String {
200     match *tok {
201         token::Eq                   => "=".to_string(),
202         token::Lt                   => "<".to_string(),
203         token::Le                   => "<=".to_string(),
204         token::EqEq                 => "==".to_string(),
205         token::Ne                   => "!=".to_string(),
206         token::Ge                   => ">=".to_string(),
207         token::Gt                   => ">".to_string(),
208         token::Not                  => "!".to_string(),
209         token::Tilde                => "~".to_string(),
210         token::OrOr                 => "||".to_string(),
211         token::AndAnd               => "&&".to_string(),
212         token::BinOp(op)            => binop_to_string(op).to_string(),
213         token::BinOpEq(op)          => format!("{}=", binop_to_string(op)),
214
215         /* Structural symbols */
216         token::At                   => "@".to_string(),
217         token::Dot                  => ".".to_string(),
218         token::DotDot               => "..".to_string(),
219         token::DotDotDot            => "...".to_string(),
220         token::Comma                => ",".to_string(),
221         token::Semi                 => ";".to_string(),
222         token::Colon                => ":".to_string(),
223         token::ModSep               => "::".to_string(),
224         token::RArrow               => "->".to_string(),
225         token::LArrow               => "<-".to_string(),
226         token::FatArrow             => "=>".to_string(),
227         token::OpenDelim(token::Paren) => "(".to_string(),
228         token::CloseDelim(token::Paren) => ")".to_string(),
229         token::OpenDelim(token::Bracket) => "[".to_string(),
230         token::CloseDelim(token::Bracket) => "]".to_string(),
231         token::OpenDelim(token::Brace) => "{".to_string(),
232         token::CloseDelim(token::Brace) => "}".to_string(),
233         token::Pound                => "#".to_string(),
234         token::Dollar               => "$".to_string(),
235         token::Question             => "?".to_string(),
236
237         /* Literals */
238         token::Literal(lit, suf) => {
239             let mut out = match lit {
240                 token::Byte(b)           => format!("b'{}'", b.as_str()),
241                 token::Char(c)           => format!("'{}'", c.as_str()),
242                 token::Float(c)          => c.as_str().to_string(),
243                 token::Integer(c)        => c.as_str().to_string(),
244                 token::Str_(s)           => format!("\"{}\"", s.as_str()),
245                 token::StrRaw(s, n)      => format!("r{delim}\"{string}\"{delim}",
246                                                     delim=repeat("#", n),
247                                                     string=s.as_str()),
248                 token::Binary(v)         => format!("b\"{}\"", v.as_str()),
249                 token::BinaryRaw(s, n)   => format!("br{delim}\"{string}\"{delim}",
250                                                     delim=repeat("#", n),
251                                                     string=s.as_str()),
252             };
253
254             if let Some(s) = suf {
255                 out.push_str(s.as_str())
256             }
257
258             out
259         }
260
261         /* Name components */
262         token::Ident(s, _)          => token::get_ident(s).get().to_string(),
263         token::Lifetime(s)          => format!("{}", token::get_ident(s)),
264         token::Underscore           => "_".to_string(),
265
266         /* Other */
267         token::DocComment(s)        => s.as_str().to_string(),
268         token::SubstNt(s, _)        => format!("${}", s),
269         token::MatchNt(s, t, _, _)  => format!("${}:{}", s, t),
270         token::Eof                  => "<eof>".to_string(),
271         token::Whitespace           => " ".to_string(),
272         token::Comment              => "/* */".to_string(),
273         token::Shebang(s)           => format!("/* shebang: {}*/", s.as_str()),
274
275         token::Interpolated(ref nt) => match *nt {
276             token::NtExpr(ref e)  => expr_to_string(&**e),
277             token::NtMeta(ref e)  => meta_item_to_string(&**e),
278             token::NtTy(ref e)    => ty_to_string(&**e),
279             token::NtPath(ref e)  => path_to_string(&**e),
280             token::NtItem(..)     => "an interpolated item".to_string(),
281             token::NtBlock(..)    => "an interpolated block".to_string(),
282             token::NtStmt(..)     => "an interpolated statement".to_string(),
283             token::NtPat(..)      => "an interpolated pattern".to_string(),
284             token::NtIdent(..)    => "an interpolated identifier".to_string(),
285             token::NtTT(..)       => "an interpolated tt".to_string(),
286         }
287     }
288 }
289
290 // FIXME (Issue #16472): the thing_to_string_impls macro should go away
291 // after we revise the syntax::ext::quote::ToToken impls to go directly
292 // to token-trees instead of thing -> string -> token-trees.
293
294 macro_rules! thing_to_string_impls {
295     ($to_string:ident) => {
296
297 pub fn ty_to_string(ty: &ast::Ty) -> String {
298     $to_string(|s| s.print_type(ty))
299 }
300
301 pub fn bounds_to_string(bounds: &[ast::TyParamBound]) -> String {
302     $to_string(|s| s.print_bounds("", bounds))
303 }
304
305 pub fn pat_to_string(pat: &ast::Pat) -> String {
306     $to_string(|s| s.print_pat(pat))
307 }
308
309 pub fn arm_to_string(arm: &ast::Arm) -> String {
310     $to_string(|s| s.print_arm(arm))
311 }
312
313 pub fn expr_to_string(e: &ast::Expr) -> String {
314     $to_string(|s| s.print_expr(e))
315 }
316
317 pub fn lifetime_to_string(e: &ast::Lifetime) -> String {
318     $to_string(|s| s.print_lifetime(e))
319 }
320
321 pub fn tt_to_string(tt: &ast::TokenTree) -> String {
322     $to_string(|s| s.print_tt(tt))
323 }
324
325 pub fn tts_to_string(tts: &[ast::TokenTree]) -> String {
326     $to_string(|s| s.print_tts(tts))
327 }
328
329 pub fn stmt_to_string(stmt: &ast::Stmt) -> String {
330     $to_string(|s| s.print_stmt(stmt))
331 }
332
333 pub fn item_to_string(i: &ast::Item) -> String {
334     $to_string(|s| s.print_item(i))
335 }
336
337 pub fn view_item_to_string(i: &ast::ViewItem) -> String {
338     $to_string(|s| s.print_view_item(i))
339 }
340
341 pub fn generics_to_string(generics: &ast::Generics) -> String {
342     $to_string(|s| s.print_generics(generics))
343 }
344
345 pub fn ty_method_to_string(p: &ast::TypeMethod) -> String {
346     $to_string(|s| s.print_ty_method(p))
347 }
348
349 pub fn method_to_string(p: &ast::Method) -> String {
350     $to_string(|s| s.print_method(p))
351 }
352
353 pub fn fn_block_to_string(p: &ast::FnDecl) -> String {
354     $to_string(|s| s.print_fn_block_args(p, None))
355 }
356
357 pub fn path_to_string(p: &ast::Path) -> String {
358     $to_string(|s| s.print_path(p, false))
359 }
360
361 pub fn ident_to_string(id: &ast::Ident) -> String {
362     $to_string(|s| s.print_ident(*id))
363 }
364
365 pub fn fun_to_string(decl: &ast::FnDecl, unsafety: ast::Unsafety, name: ast::Ident,
366                   opt_explicit_self: Option<&ast::ExplicitSelf_>,
367                   generics: &ast::Generics) -> String {
368     $to_string(|s| {
369         try!(s.print_fn(decl, Some(unsafety), abi::Rust,
370                         name, generics, opt_explicit_self, ast::Inherited));
371         try!(s.end()); // Close the head box
372         s.end() // Close the outer box
373     })
374 }
375
376 pub fn block_to_string(blk: &ast::Block) -> String {
377     $to_string(|s| {
378         // containing cbox, will be closed by print-block at }
379         try!(s.cbox(indent_unit));
380         // head-ibox, will be closed by print-block after {
381         try!(s.ibox(0u));
382         s.print_block(blk)
383     })
384 }
385
386 pub fn meta_item_to_string(mi: &ast::MetaItem) -> String {
387     $to_string(|s| s.print_meta_item(mi))
388 }
389
390 pub fn attribute_to_string(attr: &ast::Attribute) -> String {
391     $to_string(|s| s.print_attribute(attr))
392 }
393
394 pub fn lit_to_string(l: &ast::Lit) -> String {
395     $to_string(|s| s.print_literal(l))
396 }
397
398 pub fn explicit_self_to_string(explicit_self: &ast::ExplicitSelf_) -> String {
399     $to_string(|s| s.print_explicit_self(explicit_self, ast::MutImmutable).map(|_| {}))
400 }
401
402 pub fn variant_to_string(var: &ast::Variant) -> String {
403     $to_string(|s| s.print_variant(var))
404 }
405
406 pub fn arg_to_string(arg: &ast::Arg) -> String {
407     $to_string(|s| s.print_arg(arg))
408 }
409
410 pub fn mac_to_string(arg: &ast::Mac) -> String {
411     $to_string(|s| s.print_mac(arg, ::parse::token::Paren))
412 }
413
414 } }
415
416 thing_to_string_impls! { to_string }
417
418 // FIXME (Issue #16472): the whole `with_hygiene` mod should go away
419 // after we revise the syntax::ext::quote::ToToken impls to go directly
420 // to token-trees instea of thing -> string -> token-trees.
421
422 pub mod with_hygiene {
423     use abi;
424     use ast;
425     use std::io::IoResult;
426     use super::indent_unit;
427
428     // This function is the trick that all the rest of the routines
429     // hang on.
430     pub fn to_string_hyg<F>(f: F) -> String where
431         F: FnOnce(&mut super::State) -> IoResult<()>,
432     {
433         super::to_string(move |s| {
434             s.encode_idents_with_hygiene = true;
435             f(s)
436         })
437     }
438
439     thing_to_string_impls! { to_string_hyg }
440 }
441
442 pub fn visibility_qualified(vis: ast::Visibility, s: &str) -> String {
443     match vis {
444         ast::Public => format!("pub {}", s),
445         ast::Inherited => s.to_string()
446     }
447 }
448
449 fn needs_parentheses(expr: &ast::Expr) -> bool {
450     match expr.node {
451         ast::ExprAssign(..) | ast::ExprBinary(..) |
452         ast::ExprClosure(..) |
453         ast::ExprAssignOp(..) | ast::ExprCast(..) => true,
454         _ => false,
455     }
456 }
457
458 impl<'a> State<'a> {
459     pub fn ibox(&mut self, u: uint) -> IoResult<()> {
460         self.boxes.push(pp::Inconsistent);
461         pp::ibox(&mut self.s, u)
462     }
463
464     pub fn end(&mut self) -> IoResult<()> {
465         self.boxes.pop().unwrap();
466         pp::end(&mut self.s)
467     }
468
469     pub fn cbox(&mut self, u: uint) -> IoResult<()> {
470         self.boxes.push(pp::Consistent);
471         pp::cbox(&mut self.s, u)
472     }
473
474     // "raw box"
475     pub fn rbox(&mut self, u: uint, b: pp::Breaks) -> IoResult<()> {
476         self.boxes.push(b);
477         pp::rbox(&mut self.s, u, b)
478     }
479
480     pub fn nbsp(&mut self) -> IoResult<()> { word(&mut self.s, " ") }
481
482     pub fn word_nbsp(&mut self, w: &str) -> IoResult<()> {
483         try!(word(&mut self.s, w));
484         self.nbsp()
485     }
486
487     pub fn word_space(&mut self, w: &str) -> IoResult<()> {
488         try!(word(&mut self.s, w));
489         space(&mut self.s)
490     }
491
492     pub fn popen(&mut self) -> IoResult<()> { word(&mut self.s, "(") }
493
494     pub fn pclose(&mut self) -> IoResult<()> { word(&mut self.s, ")") }
495
496     pub fn head(&mut self, w: &str) -> IoResult<()> {
497         // outer-box is consistent
498         try!(self.cbox(indent_unit));
499         // head-box is inconsistent
500         try!(self.ibox(w.len() + 1));
501         // keyword that starts the head
502         if !w.is_empty() {
503             try!(self.word_nbsp(w));
504         }
505         Ok(())
506     }
507
508     pub fn bopen(&mut self) -> IoResult<()> {
509         try!(word(&mut self.s, "{"));
510         self.end() // close the head-box
511     }
512
513     pub fn bclose_(&mut self, span: codemap::Span,
514                    indented: uint) -> IoResult<()> {
515         self.bclose_maybe_open(span, indented, true)
516     }
517     pub fn bclose_maybe_open (&mut self, span: codemap::Span,
518                               indented: uint, close_box: bool) -> IoResult<()> {
519         try!(self.maybe_print_comment(span.hi));
520         try!(self.break_offset_if_not_bol(1u, -(indented as int)));
521         try!(word(&mut self.s, "}"));
522         if close_box {
523             try!(self.end()); // close the outer-box
524         }
525         Ok(())
526     }
527     pub fn bclose(&mut self, span: codemap::Span) -> IoResult<()> {
528         self.bclose_(span, indent_unit)
529     }
530
531     pub fn is_begin(&mut self) -> bool {
532         match self.s.last_token() { pp::Begin(_) => true, _ => false }
533     }
534
535     pub fn is_end(&mut self) -> bool {
536         match self.s.last_token() { pp::End => true, _ => false }
537     }
538
539     // is this the beginning of a line?
540     pub fn is_bol(&mut self) -> bool {
541         self.s.last_token().is_eof() || self.s.last_token().is_hardbreak_tok()
542     }
543
544     pub fn in_cbox(&self) -> bool {
545         match self.boxes.last() {
546             Some(&last_box) => last_box == pp::Consistent,
547             None => false
548         }
549     }
550
551     pub fn hardbreak_if_not_bol(&mut self) -> IoResult<()> {
552         if !self.is_bol() {
553             try!(hardbreak(&mut self.s))
554         }
555         Ok(())
556     }
557     pub fn space_if_not_bol(&mut self) -> IoResult<()> {
558         if !self.is_bol() { try!(space(&mut self.s)); }
559         Ok(())
560     }
561     pub fn break_offset_if_not_bol(&mut self, n: uint,
562                                    off: int) -> IoResult<()> {
563         if !self.is_bol() {
564             break_offset(&mut self.s, n, off)
565         } else {
566             if off != 0 && self.s.last_token().is_hardbreak_tok() {
567                 // We do something pretty sketchy here: tuck the nonzero
568                 // offset-adjustment we were going to deposit along with the
569                 // break into the previous hardbreak.
570                 self.s.replace_last_token(pp::hardbreak_tok_offset(off));
571             }
572             Ok(())
573         }
574     }
575
576     // Synthesizes a comment that was not textually present in the original source
577     // file.
578     pub fn synth_comment(&mut self, text: String) -> IoResult<()> {
579         try!(word(&mut self.s, "/*"));
580         try!(space(&mut self.s));
581         try!(word(&mut self.s, text[]));
582         try!(space(&mut self.s));
583         word(&mut self.s, "*/")
584     }
585
586     pub fn commasep<T, F>(&mut self, b: Breaks, elts: &[T], mut op: F) -> IoResult<()> where
587         F: FnMut(&mut State, &T) -> IoResult<()>,
588     {
589         try!(self.rbox(0u, b));
590         let mut first = true;
591         for elt in elts.iter() {
592             if first { first = false; } else { try!(self.word_space(",")); }
593             try!(op(self, elt));
594         }
595         self.end()
596     }
597
598
599     pub fn commasep_cmnt<T, F, G>(&mut self,
600                                   b: Breaks,
601                                   elts: &[T],
602                                   mut op: F,
603                                   mut get_span: G) -> IoResult<()> where
604         F: FnMut(&mut State, &T) -> IoResult<()>,
605         G: FnMut(&T) -> codemap::Span,
606     {
607         try!(self.rbox(0u, b));
608         let len = elts.len();
609         let mut i = 0u;
610         for elt in elts.iter() {
611             try!(self.maybe_print_comment(get_span(elt).hi));
612             try!(op(self, elt));
613             i += 1u;
614             if i < len {
615                 try!(word(&mut self.s, ","));
616                 try!(self.maybe_print_trailing_comment(get_span(elt),
617                                                     Some(get_span(&elts[i]).hi)));
618                 try!(self.space_if_not_bol());
619             }
620         }
621         self.end()
622     }
623
624     pub fn commasep_exprs(&mut self, b: Breaks,
625                           exprs: &[P<ast::Expr>]) -> IoResult<()> {
626         self.commasep_cmnt(b, exprs, |s, e| s.print_expr(&**e), |e| e.span)
627     }
628
629     pub fn print_mod(&mut self, _mod: &ast::Mod,
630                      attrs: &[ast::Attribute]) -> IoResult<()> {
631         try!(self.print_inner_attributes(attrs));
632         for vitem in _mod.view_items.iter() {
633             try!(self.print_view_item(vitem));
634         }
635         for item in _mod.items.iter() {
636             try!(self.print_item(&**item));
637         }
638         Ok(())
639     }
640
641     pub fn print_foreign_mod(&mut self, nmod: &ast::ForeignMod,
642                              attrs: &[ast::Attribute]) -> IoResult<()> {
643         try!(self.print_inner_attributes(attrs));
644         for vitem in nmod.view_items.iter() {
645             try!(self.print_view_item(vitem));
646         }
647         for item in nmod.items.iter() {
648             try!(self.print_foreign_item(&**item));
649         }
650         Ok(())
651     }
652
653     pub fn print_opt_lifetime(&mut self,
654                               lifetime: &Option<ast::Lifetime>) -> IoResult<()> {
655         for l in lifetime.iter() {
656             try!(self.print_lifetime(l));
657             try!(self.nbsp());
658         }
659         Ok(())
660     }
661
662     pub fn print_type(&mut self, ty: &ast::Ty) -> IoResult<()> {
663         try!(self.maybe_print_comment(ty.span.lo));
664         try!(self.ibox(0u));
665         match ty.node {
666             ast::TyVec(ref ty) => {
667                 try!(word(&mut self.s, "["));
668                 try!(self.print_type(&**ty));
669                 try!(word(&mut self.s, "]"));
670             }
671             ast::TyPtr(ref mt) => {
672                 try!(word(&mut self.s, "*"));
673                 match mt.mutbl {
674                     ast::MutMutable => try!(self.word_nbsp("mut")),
675                     ast::MutImmutable => try!(self.word_nbsp("const")),
676                 }
677                 try!(self.print_type(&*mt.ty));
678             }
679             ast::TyRptr(ref lifetime, ref mt) => {
680                 try!(word(&mut self.s, "&"));
681                 try!(self.print_opt_lifetime(lifetime));
682                 try!(self.print_mt(mt));
683             }
684             ast::TyTup(ref elts) => {
685                 try!(self.popen());
686                 try!(self.commasep(Inconsistent, elts[],
687                                    |s, ty| s.print_type(&**ty)));
688                 if elts.len() == 1 {
689                     try!(word(&mut self.s, ","));
690                 }
691                 try!(self.pclose());
692             }
693             ast::TyParen(ref typ) => {
694                 try!(self.popen());
695                 try!(self.print_type(&**typ));
696                 try!(self.pclose());
697             }
698             ast::TyBareFn(ref f) => {
699                 let generics = ast::Generics {
700                     lifetimes: f.lifetimes.clone(),
701                     ty_params: OwnedSlice::empty(),
702                     where_clause: ast::WhereClause {
703                         id: ast::DUMMY_NODE_ID,
704                         predicates: Vec::new(),
705                     },
706                 };
707                 try!(self.print_ty_fn(Some(f.abi),
708                                       None,
709                                       f.unsafety,
710                                       ast::Many,
711                                       &*f.decl,
712                                       None,
713                                       &OwnedSlice::empty(),
714                                       Some(&generics),
715                                       None));
716             }
717             ast::TyClosure(ref f) => {
718                 let generics = ast::Generics {
719                     lifetimes: f.lifetimes.clone(),
720                     ty_params: OwnedSlice::empty(),
721                     where_clause: ast::WhereClause {
722                         id: ast::DUMMY_NODE_ID,
723                         predicates: Vec::new(),
724                     },
725                 };
726                 try!(self.print_ty_fn(None,
727                                       Some('&'),
728                                       f.unsafety,
729                                       f.onceness,
730                                       &*f.decl,
731                                       None,
732                                       &f.bounds,
733                                       Some(&generics),
734                                       None));
735             }
736             ast::TyPath(ref path, _) => {
737                 try!(self.print_path(path, false));
738             }
739             ast::TyObjectSum(ref ty, ref bounds) => {
740                 try!(self.print_type(&**ty));
741                 try!(self.print_bounds("+", bounds[]));
742             }
743             ast::TyPolyTraitRef(ref bounds) => {
744                 try!(self.print_bounds("", bounds[]));
745             }
746             ast::TyQPath(ref qpath) => {
747                 try!(word(&mut self.s, "<"));
748                 try!(self.print_type(&*qpath.self_type));
749                 try!(space(&mut self.s));
750                 try!(self.word_space("as"));
751                 try!(self.print_trait_ref(&*qpath.trait_ref));
752                 try!(word(&mut self.s, ">"));
753                 try!(word(&mut self.s, "::"));
754                 try!(self.print_ident(qpath.item_name));
755             }
756             ast::TyFixedLengthVec(ref ty, ref v) => {
757                 try!(word(&mut self.s, "["));
758                 try!(self.print_type(&**ty));
759                 try!(word(&mut self.s, "; "));
760                 try!(self.print_expr(&**v));
761                 try!(word(&mut self.s, "]"));
762             }
763             ast::TyTypeof(ref e) => {
764                 try!(word(&mut self.s, "typeof("));
765                 try!(self.print_expr(&**e));
766                 try!(word(&mut self.s, ")"));
767             }
768             ast::TyInfer => {
769                 try!(word(&mut self.s, "_"));
770             }
771         }
772         self.end()
773     }
774
775     pub fn print_foreign_item(&mut self,
776                               item: &ast::ForeignItem) -> IoResult<()> {
777         try!(self.hardbreak_if_not_bol());
778         try!(self.maybe_print_comment(item.span.lo));
779         try!(self.print_outer_attributes(item.attrs[]));
780         match item.node {
781             ast::ForeignItemFn(ref decl, ref generics) => {
782                 try!(self.print_fn(&**decl, None, abi::Rust, item.ident, generics,
783                                    None, item.vis));
784                 try!(self.end()); // end head-ibox
785                 try!(word(&mut self.s, ";"));
786                 self.end() // end the outer fn box
787             }
788             ast::ForeignItemStatic(ref t, m) => {
789                 try!(self.head(visibility_qualified(item.vis,
790                                                     "static")[]));
791                 if m {
792                     try!(self.word_space("mut"));
793                 }
794                 try!(self.print_ident(item.ident));
795                 try!(self.word_space(":"));
796                 try!(self.print_type(&**t));
797                 try!(word(&mut self.s, ";"));
798                 try!(self.end()); // end the head-ibox
799                 self.end() // end the outer cbox
800             }
801         }
802     }
803
804     fn print_associated_type(&mut self, typedef: &ast::AssociatedType)
805                              -> IoResult<()>
806     {
807         try!(self.print_outer_attributes(typedef.attrs[]));
808         try!(self.word_space("type"));
809         try!(self.print_ty_param(&typedef.ty_param));
810         word(&mut self.s, ";")
811     }
812
813     fn print_typedef(&mut self, typedef: &ast::Typedef) -> IoResult<()> {
814         try!(self.word_space("type"));
815         try!(self.print_ident(typedef.ident));
816         try!(space(&mut self.s));
817         try!(self.word_space("="));
818         try!(self.print_type(&*typedef.typ));
819         word(&mut self.s, ";")
820     }
821
822     /// Pretty-print an item
823     pub fn print_item(&mut self, item: &ast::Item) -> IoResult<()> {
824         try!(self.hardbreak_if_not_bol());
825         try!(self.maybe_print_comment(item.span.lo));
826         try!(self.print_outer_attributes(item.attrs[]));
827         try!(self.ann.pre(self, NodeItem(item)));
828         match item.node {
829             ast::ItemStatic(ref ty, m, ref expr) => {
830                 try!(self.head(visibility_qualified(item.vis,
831                                                     "static")[]));
832                 if m == ast::MutMutable {
833                     try!(self.word_space("mut"));
834                 }
835                 try!(self.print_ident(item.ident));
836                 try!(self.word_space(":"));
837                 try!(self.print_type(&**ty));
838                 try!(space(&mut self.s));
839                 try!(self.end()); // end the head-ibox
840
841                 try!(self.word_space("="));
842                 try!(self.print_expr(&**expr));
843                 try!(word(&mut self.s, ";"));
844                 try!(self.end()); // end the outer cbox
845             }
846             ast::ItemConst(ref ty, ref expr) => {
847                 try!(self.head(visibility_qualified(item.vis,
848                                                     "const")[]));
849                 try!(self.print_ident(item.ident));
850                 try!(self.word_space(":"));
851                 try!(self.print_type(&**ty));
852                 try!(space(&mut self.s));
853                 try!(self.end()); // end the head-ibox
854
855                 try!(self.word_space("="));
856                 try!(self.print_expr(&**expr));
857                 try!(word(&mut self.s, ";"));
858                 try!(self.end()); // end the outer cbox
859             }
860             ast::ItemFn(ref decl, unsafety, abi, ref typarams, ref body) => {
861                 try!(self.print_fn(
862                     &**decl,
863                     Some(unsafety),
864                     abi,
865                     item.ident,
866                     typarams,
867                     None,
868                     item.vis
869                 ));
870                 try!(word(&mut self.s, " "));
871                 try!(self.print_block_with_attrs(&**body, item.attrs[]));
872             }
873             ast::ItemMod(ref _mod) => {
874                 try!(self.head(visibility_qualified(item.vis,
875                                                     "mod")[]));
876                 try!(self.print_ident(item.ident));
877                 try!(self.nbsp());
878                 try!(self.bopen());
879                 try!(self.print_mod(_mod, item.attrs[]));
880                 try!(self.bclose(item.span));
881             }
882             ast::ItemForeignMod(ref nmod) => {
883                 try!(self.head("extern"));
884                 try!(self.word_nbsp(nmod.abi.to_string()[]));
885                 try!(self.bopen());
886                 try!(self.print_foreign_mod(nmod, item.attrs[]));
887                 try!(self.bclose(item.span));
888             }
889             ast::ItemTy(ref ty, ref params) => {
890                 try!(self.ibox(indent_unit));
891                 try!(self.ibox(0u));
892                 try!(self.word_nbsp(visibility_qualified(item.vis,
893                                                          "type")[]));
894                 try!(self.print_ident(item.ident));
895                 try!(self.print_generics(params));
896                 try!(self.end()); // end the inner ibox
897
898                 try!(space(&mut self.s));
899                 try!(self.word_space("="));
900                 try!(self.print_type(&**ty));
901                 try!(self.print_where_clause(params));
902                 try!(word(&mut self.s, ";"));
903                 try!(self.end()); // end the outer ibox
904             }
905             ast::ItemEnum(ref enum_definition, ref params) => {
906                 try!(self.print_enum_def(
907                     enum_definition,
908                     params,
909                     item.ident,
910                     item.span,
911                     item.vis
912                 ));
913             }
914             ast::ItemStruct(ref struct_def, ref generics) => {
915                 try!(self.head(visibility_qualified(item.vis,"struct")[]));
916                 try!(self.print_struct(&**struct_def, generics, item.ident, item.span));
917             }
918
919             ast::ItemImpl(unsafety,
920                           ref generics,
921                           ref opt_trait,
922                           ref ty,
923                           ref impl_items) => {
924                 try!(self.head(""));
925                 try!(self.print_visibility(item.vis));
926                 try!(self.print_unsafety(unsafety));
927                 try!(self.word_nbsp("impl"));
928
929                 if generics.is_parameterized() {
930                     try!(self.print_generics(generics));
931                     try!(space(&mut self.s));
932                 }
933
934                 match opt_trait {
935                     &Some(ref t) => {
936                         try!(self.print_trait_ref(t));
937                         try!(space(&mut self.s));
938                         try!(self.word_space("for"));
939                     }
940                     &None => {}
941                 }
942
943                 try!(self.print_type(&**ty));
944                 try!(self.print_where_clause(generics));
945
946                 try!(space(&mut self.s));
947                 try!(self.bopen());
948                 try!(self.print_inner_attributes(item.attrs[]));
949                 for impl_item in impl_items.iter() {
950                     match *impl_item {
951                         ast::MethodImplItem(ref meth) => {
952                             try!(self.print_method(&**meth));
953                         }
954                         ast::TypeImplItem(ref typ) => {
955                             try!(self.print_typedef(&**typ));
956                         }
957                     }
958                 }
959                 try!(self.bclose(item.span));
960             }
961             ast::ItemTrait(unsafety, ref generics, ref bounds, ref methods) => {
962                 try!(self.head(""));
963                 try!(self.print_visibility(item.vis));
964                 try!(self.print_unsafety(unsafety));
965                 try!(self.word_nbsp("trait"));
966                 try!(self.print_ident(item.ident));
967                 try!(self.print_generics(generics));
968                 let bounds: Vec<_> = bounds.iter().map(|b| b.clone()).collect();
969                 let mut real_bounds = Vec::with_capacity(bounds.len());
970                 for b in bounds.into_iter() {
971                     if let TraitTyParamBound(ref ptr, ast::TraitBoundModifier::Maybe) = b {
972                         try!(space(&mut self.s));
973                         try!(self.word_space("for ?"));
974                         try!(self.print_trait_ref(&ptr.trait_ref));
975                     } else {
976                         real_bounds.push(b);
977                     }
978                 }
979                 try!(self.print_bounds(":", real_bounds[]));
980                 try!(self.print_where_clause(generics));
981                 try!(word(&mut self.s, " "));
982                 try!(self.bopen());
983                 for meth in methods.iter() {
984                     try!(self.print_trait_method(meth));
985                 }
986                 try!(self.bclose(item.span));
987             }
988             // I think it's reasonable to hide the context here:
989             ast::ItemMac(codemap::Spanned { node: ast::MacInvocTT(ref pth, ref tts, _),
990                                             ..}) => {
991                 try!(self.print_visibility(item.vis));
992                 try!(self.print_path(pth, false));
993                 try!(word(&mut self.s, "! "));
994                 try!(self.print_ident(item.ident));
995                 try!(self.cbox(indent_unit));
996                 try!(self.popen());
997                 try!(self.print_tts(tts[]));
998                 try!(self.pclose());
999                 try!(word(&mut self.s, ";"));
1000                 try!(self.end());
1001             }
1002         }
1003         self.ann.post(self, NodeItem(item))
1004     }
1005
1006     fn print_trait_ref(&mut self, t: &ast::TraitRef) -> IoResult<()> {
1007         self.print_path(&t.path, false)
1008     }
1009
1010     fn print_poly_trait_ref(&mut self, t: &ast::PolyTraitRef) -> IoResult<()> {
1011         if !t.bound_lifetimes.is_empty() {
1012             try!(word(&mut self.s, "for<"));
1013             let mut comma = false;
1014             for lifetime_def in t.bound_lifetimes.iter() {
1015                 if comma {
1016                     try!(self.word_space(","))
1017                 }
1018                 try!(self.print_lifetime_def(lifetime_def));
1019                 comma = true;
1020             }
1021             try!(word(&mut self.s, ">"));
1022         }
1023
1024         self.print_trait_ref(&t.trait_ref)
1025     }
1026
1027     pub fn print_enum_def(&mut self, enum_definition: &ast::EnumDef,
1028                           generics: &ast::Generics, ident: ast::Ident,
1029                           span: codemap::Span,
1030                           visibility: ast::Visibility) -> IoResult<()> {
1031         try!(self.head(visibility_qualified(visibility, "enum")[]));
1032         try!(self.print_ident(ident));
1033         try!(self.print_generics(generics));
1034         try!(self.print_where_clause(generics));
1035         try!(space(&mut self.s));
1036         self.print_variants(enum_definition.variants[], span)
1037     }
1038
1039     pub fn print_variants(&mut self,
1040                           variants: &[P<ast::Variant>],
1041                           span: codemap::Span) -> IoResult<()> {
1042         try!(self.bopen());
1043         for v in variants.iter() {
1044             try!(self.space_if_not_bol());
1045             try!(self.maybe_print_comment(v.span.lo));
1046             try!(self.print_outer_attributes(v.node.attrs[]));
1047             try!(self.ibox(indent_unit));
1048             try!(self.print_variant(&**v));
1049             try!(word(&mut self.s, ","));
1050             try!(self.end());
1051             try!(self.maybe_print_trailing_comment(v.span, None));
1052         }
1053         self.bclose(span)
1054     }
1055
1056     pub fn print_visibility(&mut self, vis: ast::Visibility) -> IoResult<()> {
1057         match vis {
1058             ast::Public => self.word_nbsp("pub"),
1059             ast::Inherited => Ok(())
1060         }
1061     }
1062
1063     pub fn print_struct(&mut self,
1064                         struct_def: &ast::StructDef,
1065                         generics: &ast::Generics,
1066                         ident: ast::Ident,
1067                         span: codemap::Span) -> IoResult<()> {
1068         try!(self.print_ident(ident));
1069         try!(self.print_generics(generics));
1070         try!(self.print_where_clause(generics));
1071         if ast_util::struct_def_is_tuple_like(struct_def) {
1072             if !struct_def.fields.is_empty() {
1073                 try!(self.popen());
1074                 try!(self.commasep(
1075                     Inconsistent, struct_def.fields[],
1076                     |s, field| {
1077                         match field.node.kind {
1078                             ast::NamedField(..) => panic!("unexpected named field"),
1079                             ast::UnnamedField(vis) => {
1080                                 try!(s.print_visibility(vis));
1081                                 try!(s.maybe_print_comment(field.span.lo));
1082                                 s.print_type(&*field.node.ty)
1083                             }
1084                         }
1085                     }
1086                 ));
1087                 try!(self.pclose());
1088             }
1089             try!(word(&mut self.s, ";"));
1090             try!(self.end());
1091             self.end() // close the outer-box
1092         } else {
1093             try!(self.nbsp());
1094             try!(self.bopen());
1095             try!(self.hardbreak_if_not_bol());
1096
1097             for field in struct_def.fields.iter() {
1098                 match field.node.kind {
1099                     ast::UnnamedField(..) => panic!("unexpected unnamed field"),
1100                     ast::NamedField(ident, visibility) => {
1101                         try!(self.hardbreak_if_not_bol());
1102                         try!(self.maybe_print_comment(field.span.lo));
1103                         try!(self.print_outer_attributes(field.node.attrs[]));
1104                         try!(self.print_visibility(visibility));
1105                         try!(self.print_ident(ident));
1106                         try!(self.word_nbsp(":"));
1107                         try!(self.print_type(&*field.node.ty));
1108                         try!(word(&mut self.s, ","));
1109                     }
1110                 }
1111             }
1112
1113             self.bclose(span)
1114         }
1115     }
1116
1117     /// This doesn't deserve to be called "pretty" printing, but it should be
1118     /// meaning-preserving. A quick hack that might help would be to look at the
1119     /// spans embedded in the TTs to decide where to put spaces and newlines.
1120     /// But it'd be better to parse these according to the grammar of the
1121     /// appropriate macro, transcribe back into the grammar we just parsed from,
1122     /// and then pretty-print the resulting AST nodes (so, e.g., we print
1123     /// expression arguments as expressions). It can be done! I think.
1124     pub fn print_tt(&mut self, tt: &ast::TokenTree) -> IoResult<()> {
1125         match *tt {
1126             ast::TtToken(_, ref tk) => {
1127                 try!(word(&mut self.s, token_to_string(tk)[]));
1128                 match *tk {
1129                     parse::token::DocComment(..) => {
1130                         hardbreak(&mut self.s)
1131                     }
1132                     _ => Ok(())
1133                 }
1134             }
1135             ast::TtDelimited(_, ref delimed) => {
1136                 try!(word(&mut self.s, token_to_string(&delimed.open_token())[]));
1137                 try!(space(&mut self.s));
1138                 try!(self.print_tts(delimed.tts[]));
1139                 try!(space(&mut self.s));
1140                 word(&mut self.s, token_to_string(&delimed.close_token())[])
1141             },
1142             ast::TtSequence(_, ref seq) => {
1143                 try!(word(&mut self.s, "$("));
1144                 for tt_elt in seq.tts.iter() {
1145                     try!(self.print_tt(tt_elt));
1146                 }
1147                 try!(word(&mut self.s, ")"));
1148                 match seq.separator {
1149                     Some(ref tk) => {
1150                         try!(word(&mut self.s, token_to_string(tk)[]));
1151                     }
1152                     None => {},
1153                 }
1154                 match seq.op {
1155                     ast::ZeroOrMore => word(&mut self.s, "*"),
1156                     ast::OneOrMore => word(&mut self.s, "+"),
1157                 }
1158             }
1159         }
1160     }
1161
1162     pub fn print_tts(&mut self, tts: &[ast::TokenTree]) -> IoResult<()> {
1163         try!(self.ibox(0));
1164         for (i, tt) in tts.iter().enumerate() {
1165             if i != 0 {
1166                 try!(space(&mut self.s));
1167             }
1168             try!(self.print_tt(tt));
1169         }
1170         self.end()
1171     }
1172
1173     pub fn print_variant(&mut self, v: &ast::Variant) -> IoResult<()> {
1174         try!(self.print_visibility(v.node.vis));
1175         match v.node.kind {
1176             ast::TupleVariantKind(ref args) => {
1177                 try!(self.print_ident(v.node.name));
1178                 if !args.is_empty() {
1179                     try!(self.popen());
1180                     try!(self.commasep(Consistent,
1181                                        args[],
1182                                        |s, arg| s.print_type(&*arg.ty)));
1183                     try!(self.pclose());
1184                 }
1185             }
1186             ast::StructVariantKind(ref struct_def) => {
1187                 try!(self.head(""));
1188                 let generics = ast_util::empty_generics();
1189                 try!(self.print_struct(&**struct_def, &generics, v.node.name, v.span));
1190             }
1191         }
1192         match v.node.disr_expr {
1193             Some(ref d) => {
1194                 try!(space(&mut self.s));
1195                 try!(self.word_space("="));
1196                 self.print_expr(&**d)
1197             }
1198             _ => Ok(())
1199         }
1200     }
1201
1202     pub fn print_ty_method(&mut self, m: &ast::TypeMethod) -> IoResult<()> {
1203         try!(self.hardbreak_if_not_bol());
1204         try!(self.maybe_print_comment(m.span.lo));
1205         try!(self.print_outer_attributes(m.attrs[]));
1206         try!(self.print_ty_fn(None,
1207                               None,
1208                               m.unsafety,
1209                               ast::Many,
1210                               &*m.decl,
1211                               Some(m.ident),
1212                               &OwnedSlice::empty(),
1213                               Some(&m.generics),
1214                               Some(&m.explicit_self.node)));
1215         word(&mut self.s, ";")
1216     }
1217
1218     pub fn print_trait_method(&mut self,
1219                               m: &ast::TraitItem) -> IoResult<()> {
1220         match *m {
1221             RequiredMethod(ref ty_m) => self.print_ty_method(ty_m),
1222             ProvidedMethod(ref m) => self.print_method(&**m),
1223             TypeTraitItem(ref t) => self.print_associated_type(&**t),
1224         }
1225     }
1226
1227     pub fn print_impl_item(&mut self, ii: &ast::ImplItem) -> IoResult<()> {
1228         match *ii {
1229             MethodImplItem(ref m) => self.print_method(&**m),
1230             TypeImplItem(ref td) => self.print_typedef(&**td),
1231         }
1232     }
1233
1234     pub fn print_method(&mut self, meth: &ast::Method) -> IoResult<()> {
1235         try!(self.hardbreak_if_not_bol());
1236         try!(self.maybe_print_comment(meth.span.lo));
1237         try!(self.print_outer_attributes(meth.attrs[]));
1238         match meth.node {
1239             ast::MethDecl(ident,
1240                           ref generics,
1241                           abi,
1242                           ref explicit_self,
1243                           unsafety,
1244                           ref decl,
1245                           ref body,
1246                           vis) => {
1247                 try!(self.print_fn(&**decl,
1248                                    Some(unsafety),
1249                                    abi,
1250                                    ident,
1251                                    generics,
1252                                    Some(&explicit_self.node),
1253                                    vis));
1254                 try!(word(&mut self.s, " "));
1255                 self.print_block_with_attrs(&**body, meth.attrs[])
1256             },
1257             ast::MethMac(codemap::Spanned { node: ast::MacInvocTT(ref pth, ref tts, _),
1258                                             ..}) => {
1259                 // code copied from ItemMac:
1260                 try!(self.print_path(pth, false));
1261                 try!(word(&mut self.s, "! "));
1262                 try!(self.cbox(indent_unit));
1263                 try!(self.popen());
1264                 try!(self.print_tts(tts[]));
1265                 try!(self.pclose());
1266                 try!(word(&mut self.s, ";"));
1267                 self.end()
1268             }
1269         }
1270     }
1271
1272     pub fn print_outer_attributes(&mut self,
1273                                   attrs: &[ast::Attribute]) -> IoResult<()> {
1274         let mut count = 0u;
1275         for attr in attrs.iter() {
1276             match attr.node.style {
1277                 ast::AttrOuter => {
1278                     try!(self.print_attribute(attr));
1279                     count += 1;
1280                 }
1281                 _ => {/* fallthrough */ }
1282             }
1283         }
1284         if count > 0 {
1285             try!(self.hardbreak_if_not_bol());
1286         }
1287         Ok(())
1288     }
1289
1290     pub fn print_inner_attributes(&mut self,
1291                                   attrs: &[ast::Attribute]) -> IoResult<()> {
1292         let mut count = 0u;
1293         for attr in attrs.iter() {
1294             match attr.node.style {
1295                 ast::AttrInner => {
1296                     try!(self.print_attribute(attr));
1297                     count += 1;
1298                 }
1299                 _ => {/* fallthrough */ }
1300             }
1301         }
1302         if count > 0 {
1303             try!(self.hardbreak_if_not_bol());
1304         }
1305         Ok(())
1306     }
1307
1308     pub fn print_attribute(&mut self, attr: &ast::Attribute) -> IoResult<()> {
1309         try!(self.hardbreak_if_not_bol());
1310         try!(self.maybe_print_comment(attr.span.lo));
1311         if attr.node.is_sugared_doc {
1312             word(&mut self.s, attr.value_str().unwrap().get())
1313         } else {
1314             match attr.node.style {
1315                 ast::AttrInner => try!(word(&mut self.s, "#![")),
1316                 ast::AttrOuter => try!(word(&mut self.s, "#[")),
1317             }
1318             try!(self.print_meta_item(&*attr.meta()));
1319             word(&mut self.s, "]")
1320         }
1321     }
1322
1323
1324     pub fn print_stmt(&mut self, st: &ast::Stmt) -> IoResult<()> {
1325         try!(self.maybe_print_comment(st.span.lo));
1326         match st.node {
1327             ast::StmtDecl(ref decl, _) => {
1328                 try!(self.print_decl(&**decl));
1329             }
1330             ast::StmtExpr(ref expr, _) => {
1331                 try!(self.space_if_not_bol());
1332                 try!(self.print_expr(&**expr));
1333             }
1334             ast::StmtSemi(ref expr, _) => {
1335                 try!(self.space_if_not_bol());
1336                 try!(self.print_expr(&**expr));
1337                 try!(word(&mut self.s, ";"));
1338             }
1339             ast::StmtMac(ref mac, style) => {
1340                 try!(self.space_if_not_bol());
1341                 let delim = match style {
1342                     ast::MacStmtWithBraces => token::Brace,
1343                     _ => token::Paren
1344                 };
1345                 try!(self.print_mac(&**mac, delim));
1346                 match style {
1347                     ast::MacStmtWithBraces => {}
1348                     _ => try!(word(&mut self.s, ";")),
1349                 }
1350             }
1351         }
1352         if parse::classify::stmt_ends_with_semi(&st.node) {
1353             try!(word(&mut self.s, ";"));
1354         }
1355         self.maybe_print_trailing_comment(st.span, None)
1356     }
1357
1358     pub fn print_block(&mut self, blk: &ast::Block) -> IoResult<()> {
1359         self.print_block_with_attrs(blk, &[])
1360     }
1361
1362     pub fn print_block_unclosed(&mut self, blk: &ast::Block) -> IoResult<()> {
1363         self.print_block_unclosed_indent(blk, indent_unit)
1364     }
1365
1366     pub fn print_block_unclosed_indent(&mut self, blk: &ast::Block,
1367                                        indented: uint) -> IoResult<()> {
1368         self.print_block_maybe_unclosed(blk, indented, &[], false)
1369     }
1370
1371     pub fn print_block_with_attrs(&mut self,
1372                                   blk: &ast::Block,
1373                                   attrs: &[ast::Attribute]) -> IoResult<()> {
1374         self.print_block_maybe_unclosed(blk, indent_unit, attrs, true)
1375     }
1376
1377     pub fn print_block_maybe_unclosed(&mut self,
1378                                       blk: &ast::Block,
1379                                       indented: uint,
1380                                       attrs: &[ast::Attribute],
1381                                       close_box: bool) -> IoResult<()> {
1382         match blk.rules {
1383             ast::UnsafeBlock(..) => try!(self.word_space("unsafe")),
1384             ast::DefaultBlock => ()
1385         }
1386         try!(self.maybe_print_comment(blk.span.lo));
1387         try!(self.ann.pre(self, NodeBlock(blk)));
1388         try!(self.bopen());
1389
1390         try!(self.print_inner_attributes(attrs));
1391
1392         for vi in blk.view_items.iter() {
1393             try!(self.print_view_item(vi));
1394         }
1395         for st in blk.stmts.iter() {
1396             try!(self.print_stmt(&**st));
1397         }
1398         match blk.expr {
1399             Some(ref expr) => {
1400                 try!(self.space_if_not_bol());
1401                 try!(self.print_expr(&**expr));
1402                 try!(self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi)));
1403             }
1404             _ => ()
1405         }
1406         try!(self.bclose_maybe_open(blk.span, indented, close_box));
1407         self.ann.post(self, NodeBlock(blk))
1408     }
1409
1410     fn print_else(&mut self, els: Option<&ast::Expr>) -> IoResult<()> {
1411         match els {
1412             Some(_else) => {
1413                 match _else.node {
1414                     // "another else-if"
1415                     ast::ExprIf(ref i, ref then, ref e) => {
1416                         try!(self.cbox(indent_unit - 1u));
1417                         try!(self.ibox(0u));
1418                         try!(word(&mut self.s, " else if "));
1419                         try!(self.print_expr(&**i));
1420                         try!(space(&mut self.s));
1421                         try!(self.print_block(&**then));
1422                         self.print_else(e.as_ref().map(|e| &**e))
1423                     }
1424                     // "another else-if-let"
1425                     ast::ExprIfLet(ref pat, ref expr, ref then, ref e) => {
1426                         try!(self.cbox(indent_unit - 1u));
1427                         try!(self.ibox(0u));
1428                         try!(word(&mut self.s, " else if let "));
1429                         try!(self.print_pat(&**pat));
1430                         try!(space(&mut self.s));
1431                         try!(self.word_space("="));
1432                         try!(self.print_expr(&**expr));
1433                         try!(space(&mut self.s));
1434                         try!(self.print_block(&**then));
1435                         self.print_else(e.as_ref().map(|e| &**e))
1436                     }
1437                     // "final else"
1438                     ast::ExprBlock(ref b) => {
1439                         try!(self.cbox(indent_unit - 1u));
1440                         try!(self.ibox(0u));
1441                         try!(word(&mut self.s, " else "));
1442                         self.print_block(&**b)
1443                     }
1444                     // BLEAH, constraints would be great here
1445                     _ => {
1446                         panic!("print_if saw if with weird alternative");
1447                     }
1448                 }
1449             }
1450             _ => Ok(())
1451         }
1452     }
1453
1454     pub fn print_if(&mut self, test: &ast::Expr, blk: &ast::Block,
1455                     elseopt: Option<&ast::Expr>) -> IoResult<()> {
1456         try!(self.head("if"));
1457         try!(self.print_expr(test));
1458         try!(space(&mut self.s));
1459         try!(self.print_block(blk));
1460         self.print_else(elseopt)
1461     }
1462
1463     pub fn print_if_let(&mut self, pat: &ast::Pat, expr: &ast::Expr, blk: &ast::Block,
1464                         elseopt: Option<&ast::Expr>) -> IoResult<()> {
1465         try!(self.head("if let"));
1466         try!(self.print_pat(pat));
1467         try!(space(&mut self.s));
1468         try!(self.word_space("="));
1469         try!(self.print_expr(expr));
1470         try!(space(&mut self.s));
1471         try!(self.print_block(blk));
1472         self.print_else(elseopt)
1473     }
1474
1475     pub fn print_mac(&mut self, m: &ast::Mac, delim: token::DelimToken)
1476                      -> IoResult<()> {
1477         match m.node {
1478             // I think it's reasonable to hide the ctxt here:
1479             ast::MacInvocTT(ref pth, ref tts, _) => {
1480                 try!(self.print_path(pth, false));
1481                 try!(word(&mut self.s, "!"));
1482                 match delim {
1483                     token::Paren => try!(self.popen()),
1484                     token::Bracket => try!(word(&mut self.s, "[")),
1485                     token::Brace => try!(self.bopen()),
1486                 }
1487                 try!(self.print_tts(tts.as_slice()));
1488                 match delim {
1489                     token::Paren => self.pclose(),
1490                     token::Bracket => word(&mut self.s, "]"),
1491                     token::Brace => self.bclose(m.span),
1492                 }
1493             }
1494         }
1495     }
1496
1497
1498     fn print_call_post(&mut self, args: &[P<ast::Expr>]) -> IoResult<()> {
1499         try!(self.popen());
1500         try!(self.commasep_exprs(Inconsistent, args));
1501         self.pclose()
1502     }
1503
1504     pub fn print_expr_maybe_paren(&mut self, expr: &ast::Expr) -> IoResult<()> {
1505         let needs_par = needs_parentheses(expr);
1506         if needs_par {
1507             try!(self.popen());
1508         }
1509         try!(self.print_expr(expr));
1510         if needs_par {
1511             try!(self.pclose());
1512         }
1513         Ok(())
1514     }
1515
1516     pub fn print_expr(&mut self, expr: &ast::Expr) -> IoResult<()> {
1517         try!(self.maybe_print_comment(expr.span.lo));
1518         try!(self.ibox(indent_unit));
1519         try!(self.ann.pre(self, NodeExpr(expr)));
1520         match expr.node {
1521             ast::ExprBox(ref p, ref e) => {
1522                 try!(word(&mut self.s, "box"));
1523                 try!(word(&mut self.s, "("));
1524                 try!(p.as_ref().map_or(Ok(()), |e|self.print_expr(&**e)));
1525                 try!(self.word_space(")"));
1526                 try!(self.print_expr(&**e));
1527             }
1528             ast::ExprVec(ref exprs) => {
1529                 try!(self.ibox(indent_unit));
1530                 try!(word(&mut self.s, "["));
1531                 try!(self.commasep_exprs(Inconsistent, exprs[]));
1532                 try!(word(&mut self.s, "]"));
1533                 try!(self.end());
1534             }
1535
1536             ast::ExprRepeat(ref element, ref count) => {
1537                 try!(self.ibox(indent_unit));
1538                 try!(word(&mut self.s, "["));
1539                 try!(self.print_expr(&**element));
1540                 try!(self.word_space(";"));
1541                 try!(self.print_expr(&**count));
1542                 try!(word(&mut self.s, "]"));
1543                 try!(self.end());
1544             }
1545
1546             ast::ExprStruct(ref path, ref fields, ref wth) => {
1547                 try!(self.print_path(path, true));
1548                 try!(word(&mut self.s, "{"));
1549                 try!(self.commasep_cmnt(
1550                     Consistent,
1551                     fields[],
1552                     |s, field| {
1553                         try!(s.ibox(indent_unit));
1554                         try!(s.print_ident(field.ident.node));
1555                         try!(s.word_space(":"));
1556                         try!(s.print_expr(&*field.expr));
1557                         s.end()
1558                     },
1559                     |f| f.span));
1560                 match *wth {
1561                     Some(ref expr) => {
1562                         try!(self.ibox(indent_unit));
1563                         if !fields.is_empty() {
1564                             try!(word(&mut self.s, ","));
1565                             try!(space(&mut self.s));
1566                         }
1567                         try!(word(&mut self.s, ".."));
1568                         try!(self.print_expr(&**expr));
1569                         try!(self.end());
1570                     }
1571                     _ => try!(word(&mut self.s, ","))
1572                 }
1573                 try!(word(&mut self.s, "}"));
1574             }
1575             ast::ExprTup(ref exprs) => {
1576                 try!(self.popen());
1577                 try!(self.commasep_exprs(Inconsistent, exprs[]));
1578                 if exprs.len() == 1 {
1579                     try!(word(&mut self.s, ","));
1580                 }
1581                 try!(self.pclose());
1582             }
1583             ast::ExprCall(ref func, ref args) => {
1584                 try!(self.print_expr_maybe_paren(&**func));
1585                 try!(self.print_call_post(args[]));
1586             }
1587             ast::ExprMethodCall(ident, ref tys, ref args) => {
1588                 let base_args = args.slice_from(1);
1589                 try!(self.print_expr(&*args[0]));
1590                 try!(word(&mut self.s, "."));
1591                 try!(self.print_ident(ident.node));
1592                 if tys.len() > 0u {
1593                     try!(word(&mut self.s, "::<"));
1594                     try!(self.commasep(Inconsistent, tys[],
1595                                        |s, ty| s.print_type(&**ty)));
1596                     try!(word(&mut self.s, ">"));
1597                 }
1598                 try!(self.print_call_post(base_args));
1599             }
1600             ast::ExprBinary(op, ref lhs, ref rhs) => {
1601                 try!(self.print_expr(&**lhs));
1602                 try!(space(&mut self.s));
1603                 try!(self.word_space(ast_util::binop_to_string(op)));
1604                 try!(self.print_expr(&**rhs));
1605             }
1606             ast::ExprUnary(op, ref expr) => {
1607                 try!(word(&mut self.s, ast_util::unop_to_string(op)));
1608                 try!(self.print_expr_maybe_paren(&**expr));
1609             }
1610             ast::ExprAddrOf(m, ref expr) => {
1611                 try!(word(&mut self.s, "&"));
1612                 try!(self.print_mutability(m));
1613                 try!(self.print_expr_maybe_paren(&**expr));
1614             }
1615             ast::ExprLit(ref lit) => try!(self.print_literal(&**lit)),
1616             ast::ExprCast(ref expr, ref ty) => {
1617                 try!(self.print_expr(&**expr));
1618                 try!(space(&mut self.s));
1619                 try!(self.word_space("as"));
1620                 try!(self.print_type(&**ty));
1621             }
1622             ast::ExprIf(ref test, ref blk, ref elseopt) => {
1623                 try!(self.print_if(&**test, &**blk, elseopt.as_ref().map(|e| &**e)));
1624             }
1625             ast::ExprIfLet(ref pat, ref expr, ref blk, ref elseopt) => {
1626                 try!(self.print_if_let(&**pat, &**expr, &** blk, elseopt.as_ref().map(|e| &**e)));
1627             }
1628             ast::ExprWhile(ref test, ref blk, opt_ident) => {
1629                 for ident in opt_ident.iter() {
1630                     try!(self.print_ident(*ident));
1631                     try!(self.word_space(":"));
1632                 }
1633                 try!(self.head("while"));
1634                 try!(self.print_expr(&**test));
1635                 try!(space(&mut self.s));
1636                 try!(self.print_block(&**blk));
1637             }
1638             ast::ExprWhileLet(ref pat, ref expr, ref blk, opt_ident) => {
1639                 for ident in opt_ident.iter() {
1640                     try!(self.print_ident(*ident));
1641                     try!(self.word_space(":"));
1642                 }
1643                 try!(self.head("while let"));
1644                 try!(self.print_pat(&**pat));
1645                 try!(space(&mut self.s));
1646                 try!(self.word_space("="));
1647                 try!(self.print_expr(&**expr));
1648                 try!(space(&mut self.s));
1649                 try!(self.print_block(&**blk));
1650             }
1651             ast::ExprForLoop(ref pat, ref iter, ref blk, opt_ident) => {
1652                 for ident in opt_ident.iter() {
1653                     try!(self.print_ident(*ident));
1654                     try!(self.word_space(":"));
1655                 }
1656                 try!(self.head("for"));
1657                 try!(self.print_pat(&**pat));
1658                 try!(space(&mut self.s));
1659                 try!(self.word_space("in"));
1660                 try!(self.print_expr(&**iter));
1661                 try!(space(&mut self.s));
1662                 try!(self.print_block(&**blk));
1663             }
1664             ast::ExprLoop(ref blk, opt_ident) => {
1665                 for ident in opt_ident.iter() {
1666                     try!(self.print_ident(*ident));
1667                     try!(self.word_space(":"));
1668                 }
1669                 try!(self.head("loop"));
1670                 try!(space(&mut self.s));
1671                 try!(self.print_block(&**blk));
1672             }
1673             ast::ExprMatch(ref expr, ref arms, _) => {
1674                 try!(self.cbox(indent_unit));
1675                 try!(self.ibox(4));
1676                 try!(self.word_nbsp("match"));
1677                 try!(self.print_expr(&**expr));
1678                 try!(space(&mut self.s));
1679                 try!(self.bopen());
1680                 for arm in arms.iter() {
1681                     try!(self.print_arm(arm));
1682                 }
1683                 try!(self.bclose_(expr.span, indent_unit));
1684             }
1685             ast::ExprClosure(capture_clause, opt_kind, ref decl, ref body) => {
1686                 try!(self.print_capture_clause(capture_clause));
1687
1688                 try!(self.print_fn_block_args(&**decl, opt_kind));
1689                 try!(space(&mut self.s));
1690
1691                 if !body.stmts.is_empty() || !body.expr.is_some() {
1692                     try!(self.print_block_unclosed(&**body));
1693                 } else {
1694                     // we extract the block, so as not to create another set of boxes
1695                     match body.expr.as_ref().unwrap().node {
1696                         ast::ExprBlock(ref blk) => {
1697                             try!(self.print_block_unclosed(&**blk));
1698                         }
1699                         _ => {
1700                             // this is a bare expression
1701                             try!(self.print_expr(body.expr.as_ref().map(|e| &**e).unwrap()));
1702                             try!(self.end()); // need to close a box
1703                         }
1704                     }
1705                 }
1706                 // a box will be closed by print_expr, but we didn't want an overall
1707                 // wrapper so we closed the corresponding opening. so create an
1708                 // empty box to satisfy the close.
1709                 try!(self.ibox(0));
1710             }
1711             ast::ExprBlock(ref blk) => {
1712                 // containing cbox, will be closed by print-block at }
1713                 try!(self.cbox(indent_unit));
1714                 // head-box, will be closed by print-block after {
1715                 try!(self.ibox(0u));
1716                 try!(self.print_block(&**blk));
1717             }
1718             ast::ExprAssign(ref lhs, ref rhs) => {
1719                 try!(self.print_expr(&**lhs));
1720                 try!(space(&mut self.s));
1721                 try!(self.word_space("="));
1722                 try!(self.print_expr(&**rhs));
1723             }
1724             ast::ExprAssignOp(op, ref lhs, ref rhs) => {
1725                 try!(self.print_expr(&**lhs));
1726                 try!(space(&mut self.s));
1727                 try!(word(&mut self.s, ast_util::binop_to_string(op)));
1728                 try!(self.word_space("="));
1729                 try!(self.print_expr(&**rhs));
1730             }
1731             ast::ExprField(ref expr, id) => {
1732                 try!(self.print_expr(&**expr));
1733                 try!(word(&mut self.s, "."));
1734                 try!(self.print_ident(id.node));
1735             }
1736             ast::ExprTupField(ref expr, id) => {
1737                 try!(self.print_expr(&**expr));
1738                 try!(word(&mut self.s, "."));
1739                 try!(self.print_uint(id.node));
1740             }
1741             ast::ExprIndex(ref expr, ref index) => {
1742                 try!(self.print_expr(&**expr));
1743                 try!(word(&mut self.s, "["));
1744                 try!(self.print_expr(&**index));
1745                 try!(word(&mut self.s, "]"));
1746             }
1747             ast::ExprRange(ref start, ref end) => {
1748                 if let &Some(ref e) = start {
1749                     try!(self.print_expr(&**e));
1750                 }
1751                 if start.is_some() || end.is_some() {
1752                     try!(word(&mut self.s, ".."));
1753                 }
1754                 if let &Some(ref e) = end {
1755                     try!(self.print_expr(&**e));
1756                 }
1757             }
1758             ast::ExprPath(ref path) => try!(self.print_path(path, true)),
1759             ast::ExprBreak(opt_ident) => {
1760                 try!(word(&mut self.s, "break"));
1761                 try!(space(&mut self.s));
1762                 for ident in opt_ident.iter() {
1763                     try!(self.print_ident(*ident));
1764                     try!(space(&mut self.s));
1765                 }
1766             }
1767             ast::ExprAgain(opt_ident) => {
1768                 try!(word(&mut self.s, "continue"));
1769                 try!(space(&mut self.s));
1770                 for ident in opt_ident.iter() {
1771                     try!(self.print_ident(*ident));
1772                     try!(space(&mut self.s))
1773                 }
1774             }
1775             ast::ExprRet(ref result) => {
1776                 try!(word(&mut self.s, "return"));
1777                 match *result {
1778                     Some(ref expr) => {
1779                         try!(word(&mut self.s, " "));
1780                         try!(self.print_expr(&**expr));
1781                     }
1782                     _ => ()
1783                 }
1784             }
1785             ast::ExprInlineAsm(ref a) => {
1786                 try!(word(&mut self.s, "asm!"));
1787                 try!(self.popen());
1788                 try!(self.print_string(a.asm.get(), a.asm_str_style));
1789                 try!(self.word_space(":"));
1790
1791                 try!(self.commasep(Inconsistent, a.outputs[],
1792                                    |s, &(ref co, ref o, is_rw)| {
1793                     match co.get().slice_shift_char() {
1794                         Some(('=', operand)) if is_rw => {
1795                             try!(s.print_string(format!("+{}", operand)[],
1796                                                 ast::CookedStr))
1797                         }
1798                         _ => try!(s.print_string(co.get(), ast::CookedStr))
1799                     }
1800                     try!(s.popen());
1801                     try!(s.print_expr(&**o));
1802                     try!(s.pclose());
1803                     Ok(())
1804                 }));
1805                 try!(space(&mut self.s));
1806                 try!(self.word_space(":"));
1807
1808                 try!(self.commasep(Inconsistent, a.inputs[],
1809                                    |s, &(ref co, ref o)| {
1810                     try!(s.print_string(co.get(), ast::CookedStr));
1811                     try!(s.popen());
1812                     try!(s.print_expr(&**o));
1813                     try!(s.pclose());
1814                     Ok(())
1815                 }));
1816                 try!(space(&mut self.s));
1817                 try!(self.word_space(":"));
1818
1819                 try!(self.commasep(Inconsistent, a.clobbers[],
1820                                    |s, co| {
1821                     try!(s.print_string(co.get(), ast::CookedStr));
1822                     Ok(())
1823                 }));
1824
1825                 let mut options = vec!();
1826                 if a.volatile {
1827                     options.push("volatile");
1828                 }
1829                 if a.alignstack {
1830                     options.push("alignstack");
1831                 }
1832                 if a.dialect == ast::AsmDialect::AsmIntel {
1833                     options.push("intel");
1834                 }
1835
1836                 if options.len() > 0 {
1837                     try!(space(&mut self.s));
1838                     try!(self.word_space(":"));
1839                     try!(self.commasep(Inconsistent, &*options,
1840                                        |s, &co| {
1841                         try!(s.print_string(co, ast::CookedStr));
1842                         Ok(())
1843                     }));
1844                 }
1845
1846                 try!(self.pclose());
1847             }
1848             ast::ExprMac(ref m) => try!(self.print_mac(m, token::Paren)),
1849             ast::ExprParen(ref e) => {
1850                 try!(self.popen());
1851                 try!(self.print_expr(&**e));
1852                 try!(self.pclose());
1853             }
1854         }
1855         try!(self.ann.post(self, NodeExpr(expr)));
1856         self.end()
1857     }
1858
1859     pub fn print_local_decl(&mut self, loc: &ast::Local) -> IoResult<()> {
1860         try!(self.print_pat(&*loc.pat));
1861         match loc.ty.node {
1862             ast::TyInfer => Ok(()),
1863             _ => {
1864                 try!(self.word_space(":"));
1865                 self.print_type(&*loc.ty)
1866             }
1867         }
1868     }
1869
1870     pub fn print_decl(&mut self, decl: &ast::Decl) -> IoResult<()> {
1871         try!(self.maybe_print_comment(decl.span.lo));
1872         match decl.node {
1873             ast::DeclLocal(ref loc) => {
1874                 try!(self.space_if_not_bol());
1875                 try!(self.ibox(indent_unit));
1876                 try!(self.word_nbsp("let"));
1877
1878                 try!(self.ibox(indent_unit));
1879                 try!(self.print_local_decl(&**loc));
1880                 try!(self.end());
1881                 if let Some(ref init) = loc.init {
1882                     try!(self.nbsp());
1883                     try!(self.word_space("="));
1884                     try!(self.print_expr(&**init));
1885                 }
1886                 self.end()
1887             }
1888             ast::DeclItem(ref item) => self.print_item(&**item)
1889         }
1890     }
1891
1892     pub fn print_ident(&mut self, ident: ast::Ident) -> IoResult<()> {
1893         if self.encode_idents_with_hygiene {
1894             let encoded = ident.encode_with_hygiene();
1895             try!(word(&mut self.s, encoded[]))
1896         } else {
1897             try!(word(&mut self.s, token::get_ident(ident).get()))
1898         }
1899         self.ann.post(self, NodeIdent(&ident))
1900     }
1901
1902     pub fn print_uint(&mut self, i: uint) -> IoResult<()> {
1903         word(&mut self.s, i.to_string()[])
1904     }
1905
1906     pub fn print_name(&mut self, name: ast::Name) -> IoResult<()> {
1907         try!(word(&mut self.s, token::get_name(name).get()));
1908         self.ann.post(self, NodeName(&name))
1909     }
1910
1911     pub fn print_for_decl(&mut self, loc: &ast::Local,
1912                           coll: &ast::Expr) -> IoResult<()> {
1913         try!(self.print_local_decl(loc));
1914         try!(space(&mut self.s));
1915         try!(self.word_space("in"));
1916         self.print_expr(coll)
1917     }
1918
1919     fn print_path(&mut self,
1920                   path: &ast::Path,
1921                   colons_before_params: bool)
1922                   -> IoResult<()>
1923     {
1924         try!(self.maybe_print_comment(path.span.lo));
1925         if path.global {
1926             try!(word(&mut self.s, "::"));
1927         }
1928
1929         let mut first = true;
1930         for segment in path.segments.iter() {
1931             if first {
1932                 first = false
1933             } else {
1934                 try!(word(&mut self.s, "::"))
1935             }
1936
1937             try!(self.print_ident(segment.identifier));
1938
1939             try!(self.print_path_parameters(&segment.parameters, colons_before_params));
1940         }
1941
1942         Ok(())
1943     }
1944
1945     fn print_path_parameters(&mut self,
1946                              parameters: &ast::PathParameters,
1947                              colons_before_params: bool)
1948                              -> IoResult<()>
1949     {
1950         if parameters.is_empty() {
1951             return Ok(());
1952         }
1953
1954         if colons_before_params {
1955             try!(word(&mut self.s, "::"))
1956         }
1957
1958         match *parameters {
1959             ast::AngleBracketedParameters(ref data) => {
1960                 try!(word(&mut self.s, "<"));
1961
1962                 let mut comma = false;
1963                 for lifetime in data.lifetimes.iter() {
1964                     if comma {
1965                         try!(self.word_space(","))
1966                     }
1967                     try!(self.print_lifetime(lifetime));
1968                     comma = true;
1969                 }
1970
1971                 if !data.types.is_empty() {
1972                     if comma {
1973                         try!(self.word_space(","))
1974                     }
1975                     try!(self.commasep(
1976                         Inconsistent,
1977                         data.types[],
1978                         |s, ty| s.print_type(&**ty)));
1979                         comma = true;
1980                 }
1981
1982                 for binding in data.bindings.iter() {
1983                     if comma {
1984                         try!(self.word_space(","))
1985                     }
1986                     try!(self.print_ident(binding.ident));
1987                     try!(space(&mut self.s));
1988                     try!(self.word_space("="));
1989                     try!(self.print_type(&*binding.ty));
1990                     comma = true;
1991                 }
1992
1993                 try!(word(&mut self.s, ">"))
1994             }
1995
1996             ast::ParenthesizedParameters(ref data) => {
1997                 try!(word(&mut self.s, "("));
1998                 try!(self.commasep(
1999                     Inconsistent,
2000                     data.inputs[],
2001                     |s, ty| s.print_type(&**ty)));
2002                 try!(word(&mut self.s, ")"));
2003
2004                 match data.output {
2005                     None => { }
2006                     Some(ref ty) => {
2007                         try!(self.space_if_not_bol());
2008                         try!(self.word_space("->"));
2009                         try!(self.print_type(&**ty));
2010                     }
2011                 }
2012             }
2013         }
2014
2015         Ok(())
2016     }
2017
2018     pub fn print_pat(&mut self, pat: &ast::Pat) -> IoResult<()> {
2019         try!(self.maybe_print_comment(pat.span.lo));
2020         try!(self.ann.pre(self, NodePat(pat)));
2021         /* Pat isn't normalized, but the beauty of it
2022          is that it doesn't matter */
2023         match pat.node {
2024             ast::PatWild(ast::PatWildSingle) => try!(word(&mut self.s, "_")),
2025             ast::PatWild(ast::PatWildMulti) => try!(word(&mut self.s, "..")),
2026             ast::PatIdent(binding_mode, ref path1, ref sub) => {
2027                 match binding_mode {
2028                     ast::BindByRef(mutbl) => {
2029                         try!(self.word_nbsp("ref"));
2030                         try!(self.print_mutability(mutbl));
2031                     }
2032                     ast::BindByValue(ast::MutImmutable) => {}
2033                     ast::BindByValue(ast::MutMutable) => {
2034                         try!(self.word_nbsp("mut"));
2035                     }
2036                 }
2037                 try!(self.print_ident(path1.node));
2038                 match *sub {
2039                     Some(ref p) => {
2040                         try!(word(&mut self.s, "@"));
2041                         try!(self.print_pat(&**p));
2042                     }
2043                     None => ()
2044                 }
2045             }
2046             ast::PatEnum(ref path, ref args_) => {
2047                 try!(self.print_path(path, true));
2048                 match *args_ {
2049                     None => try!(word(&mut self.s, "(..)")),
2050                     Some(ref args) => {
2051                         if !args.is_empty() {
2052                             try!(self.popen());
2053                             try!(self.commasep(Inconsistent, args[],
2054                                               |s, p| s.print_pat(&**p)));
2055                             try!(self.pclose());
2056                         }
2057                     }
2058                 }
2059             }
2060             ast::PatStruct(ref path, ref fields, etc) => {
2061                 try!(self.print_path(path, true));
2062                 try!(self.nbsp());
2063                 try!(self.word_space("{"));
2064                 try!(self.commasep_cmnt(
2065                     Consistent, fields[],
2066                     |s, f| {
2067                         try!(s.cbox(indent_unit));
2068                         if !f.node.is_shorthand {
2069                             try!(s.print_ident(f.node.ident));
2070                             try!(s.word_nbsp(":"));
2071                         }
2072                         try!(s.print_pat(&*f.node.pat));
2073                         s.end()
2074                     },
2075                     |f| f.node.pat.span));
2076                 if etc {
2077                     if fields.len() != 0u { try!(self.word_space(",")); }
2078                     try!(word(&mut self.s, ".."));
2079                 }
2080                 try!(space(&mut self.s));
2081                 try!(word(&mut self.s, "}"));
2082             }
2083             ast::PatTup(ref elts) => {
2084                 try!(self.popen());
2085                 try!(self.commasep(Inconsistent,
2086                                    elts[],
2087                                    |s, p| s.print_pat(&**p)));
2088                 if elts.len() == 1 {
2089                     try!(word(&mut self.s, ","));
2090                 }
2091                 try!(self.pclose());
2092             }
2093             ast::PatBox(ref inner) => {
2094                 try!(word(&mut self.s, "box "));
2095                 try!(self.print_pat(&**inner));
2096             }
2097             ast::PatRegion(ref inner) => {
2098                 try!(word(&mut self.s, "&"));
2099                 try!(self.print_pat(&**inner));
2100             }
2101             ast::PatLit(ref e) => try!(self.print_expr(&**e)),
2102             ast::PatRange(ref begin, ref end) => {
2103                 try!(self.print_expr(&**begin));
2104                 try!(space(&mut self.s));
2105                 try!(word(&mut self.s, "..."));
2106                 try!(self.print_expr(&**end));
2107             }
2108             ast::PatVec(ref before, ref slice, ref after) => {
2109                 try!(word(&mut self.s, "["));
2110                 try!(self.commasep(Inconsistent,
2111                                    before[],
2112                                    |s, p| s.print_pat(&**p)));
2113                 for p in slice.iter() {
2114                     if !before.is_empty() { try!(self.word_space(",")); }
2115                     try!(self.print_pat(&**p));
2116                     match **p {
2117                         ast::Pat { node: ast::PatWild(ast::PatWildMulti), .. } => {
2118                             // this case is handled by print_pat
2119                         }
2120                         _ => try!(word(&mut self.s, "..")),
2121                     }
2122                     if !after.is_empty() { try!(self.word_space(",")); }
2123                 }
2124                 try!(self.commasep(Inconsistent,
2125                                    after[],
2126                                    |s, p| s.print_pat(&**p)));
2127                 try!(word(&mut self.s, "]"));
2128             }
2129             ast::PatMac(ref m) => try!(self.print_mac(m, token::Paren)),
2130         }
2131         self.ann.post(self, NodePat(pat))
2132     }
2133
2134     fn print_arm(&mut self, arm: &ast::Arm) -> IoResult<()> {
2135         // I have no idea why this check is necessary, but here it
2136         // is :(
2137         if arm.attrs.is_empty() {
2138             try!(space(&mut self.s));
2139         }
2140         try!(self.cbox(indent_unit));
2141         try!(self.ibox(0u));
2142         try!(self.print_outer_attributes(arm.attrs[]));
2143         let mut first = true;
2144         for p in arm.pats.iter() {
2145             if first {
2146                 first = false;
2147             } else {
2148                 try!(space(&mut self.s));
2149                 try!(self.word_space("|"));
2150             }
2151             try!(self.print_pat(&**p));
2152         }
2153         try!(space(&mut self.s));
2154         if let Some(ref e) = arm.guard {
2155             try!(self.word_space("if"));
2156             try!(self.print_expr(&**e));
2157             try!(space(&mut self.s));
2158         }
2159         try!(self.word_space("=>"));
2160
2161         match arm.body.node {
2162             ast::ExprBlock(ref blk) => {
2163                 // the block will close the pattern's ibox
2164                 try!(self.print_block_unclosed_indent(&**blk, indent_unit));
2165
2166                 // If it is a user-provided unsafe block, print a comma after it
2167                 if let ast::UnsafeBlock(ast::UserProvided) = blk.rules {
2168                     try!(word(&mut self.s, ","));
2169                 }
2170             }
2171             _ => {
2172                 try!(self.end()); // close the ibox for the pattern
2173                 try!(self.print_expr(&*arm.body));
2174                 try!(word(&mut self.s, ","));
2175             }
2176         }
2177         self.end() // close enclosing cbox
2178     }
2179
2180     // Returns whether it printed anything
2181     fn print_explicit_self(&mut self,
2182                            explicit_self: &ast::ExplicitSelf_,
2183                            mutbl: ast::Mutability) -> IoResult<bool> {
2184         try!(self.print_mutability(mutbl));
2185         match *explicit_self {
2186             ast::SelfStatic => { return Ok(false); }
2187             ast::SelfValue(_) => {
2188                 try!(word(&mut self.s, "self"));
2189             }
2190             ast::SelfRegion(ref lt, m, _) => {
2191                 try!(word(&mut self.s, "&"));
2192                 try!(self.print_opt_lifetime(lt));
2193                 try!(self.print_mutability(m));
2194                 try!(word(&mut self.s, "self"));
2195             }
2196             ast::SelfExplicit(ref typ, _) => {
2197                 try!(word(&mut self.s, "self"));
2198                 try!(self.word_space(":"));
2199                 try!(self.print_type(&**typ));
2200             }
2201         }
2202         return Ok(true);
2203     }
2204
2205     pub fn print_fn(&mut self,
2206                     decl: &ast::FnDecl,
2207                     unsafety: Option<ast::Unsafety>,
2208                     abi: abi::Abi,
2209                     name: ast::Ident,
2210                     generics: &ast::Generics,
2211                     opt_explicit_self: Option<&ast::ExplicitSelf_>,
2212                     vis: ast::Visibility) -> IoResult<()> {
2213         try!(self.head(""));
2214         try!(self.print_fn_header_info(opt_explicit_self, unsafety, abi, vis));
2215         try!(self.nbsp());
2216         try!(self.print_ident(name));
2217         try!(self.print_generics(generics));
2218         try!(self.print_fn_args_and_ret(decl, opt_explicit_self));
2219         self.print_where_clause(generics)
2220     }
2221
2222     pub fn print_fn_args(&mut self, decl: &ast::FnDecl,
2223                          opt_explicit_self: Option<&ast::ExplicitSelf_>)
2224         -> IoResult<()> {
2225         // It is unfortunate to duplicate the commasep logic, but we want the
2226         // self type and the args all in the same box.
2227         try!(self.rbox(0u, Inconsistent));
2228         let mut first = true;
2229         for &explicit_self in opt_explicit_self.iter() {
2230             let m = match explicit_self {
2231                 &ast::SelfStatic => ast::MutImmutable,
2232                 _ => match decl.inputs[0].pat.node {
2233                     ast::PatIdent(ast::BindByValue(m), _, _) => m,
2234                     _ => ast::MutImmutable
2235                 }
2236             };
2237             first = !try!(self.print_explicit_self(explicit_self, m));
2238         }
2239
2240         // HACK(eddyb) ignore the separately printed self argument.
2241         let args = if first {
2242             decl.inputs[]
2243         } else {
2244             decl.inputs.slice_from(1)
2245         };
2246
2247         for arg in args.iter() {
2248             if first { first = false; } else { try!(self.word_space(",")); }
2249             try!(self.print_arg(arg));
2250         }
2251
2252         self.end()
2253     }
2254
2255     pub fn print_fn_args_and_ret(&mut self, decl: &ast::FnDecl,
2256                                  opt_explicit_self: Option<&ast::ExplicitSelf_>)
2257         -> IoResult<()> {
2258         try!(self.popen());
2259         try!(self.print_fn_args(decl, opt_explicit_self));
2260         if decl.variadic {
2261             try!(word(&mut self.s, ", ..."));
2262         }
2263         try!(self.pclose());
2264
2265         self.print_fn_output(decl)
2266     }
2267
2268     pub fn print_fn_block_args(
2269             &mut self,
2270             decl: &ast::FnDecl,
2271             unboxed_closure_kind: Option<UnboxedClosureKind>)
2272             -> IoResult<()> {
2273         try!(word(&mut self.s, "|"));
2274         match unboxed_closure_kind {
2275             None => {}
2276             Some(FnUnboxedClosureKind) => try!(self.word_space("&:")),
2277             Some(FnMutUnboxedClosureKind) => try!(self.word_space("&mut:")),
2278             Some(FnOnceUnboxedClosureKind) => try!(self.word_space(":")),
2279         }
2280         try!(self.print_fn_args(decl, None));
2281         try!(word(&mut self.s, "|"));
2282
2283         if let ast::Return(ref ty) = decl.output {
2284             if ty.node == ast::TyInfer {
2285                 return self.maybe_print_comment(ty.span.lo);
2286             }
2287         }
2288
2289         try!(self.space_if_not_bol());
2290         try!(self.word_space("->"));
2291         match decl.output {
2292             ast::Return(ref ty) => {
2293                 try!(self.print_type(&**ty));
2294                 self.maybe_print_comment(ty.span.lo)
2295             }
2296             ast::NoReturn(span) => {
2297                 try!(self.word_nbsp("!"));
2298                 self.maybe_print_comment(span.lo)
2299             }
2300         }
2301     }
2302
2303     pub fn print_capture_clause(&mut self, capture_clause: ast::CaptureClause)
2304                                 -> IoResult<()> {
2305         match capture_clause {
2306             ast::CaptureByValue => self.word_space("move"),
2307             ast::CaptureByRef => Ok(()),
2308         }
2309     }
2310
2311     pub fn print_proc_args(&mut self, decl: &ast::FnDecl) -> IoResult<()> {
2312         try!(word(&mut self.s, "proc"));
2313         try!(word(&mut self.s, "("));
2314         try!(self.print_fn_args(decl, None));
2315         try!(word(&mut self.s, ")"));
2316
2317         if let ast::Return(ref ty) = decl.output {
2318             if ty.node == ast::TyInfer {
2319                 return self.maybe_print_comment(ty.span.lo);
2320             }
2321         }
2322
2323         try!(self.space_if_not_bol());
2324         try!(self.word_space("->"));
2325         match decl.output {
2326             ast::Return(ref ty) => {
2327                 try!(self.print_type(&**ty));
2328                 self.maybe_print_comment(ty.span.lo)
2329             }
2330             ast::NoReturn(span) => {
2331                 try!(self.word_nbsp("!"));
2332                 self.maybe_print_comment(span.lo)
2333             }
2334         }
2335     }
2336
2337     pub fn print_bounds(&mut self,
2338                         prefix: &str,
2339                         bounds: &[ast::TyParamBound])
2340                         -> IoResult<()> {
2341         if !bounds.is_empty() {
2342             try!(word(&mut self.s, prefix));
2343             let mut first = true;
2344             for bound in bounds.iter() {
2345                 try!(self.nbsp());
2346                 if first {
2347                     first = false;
2348                 } else {
2349                     try!(self.word_space("+"));
2350                 }
2351
2352                 try!(match *bound {
2353                     TraitTyParamBound(ref tref, TraitBoundModifier::None) => {
2354                         self.print_poly_trait_ref(tref)
2355                     }
2356                     TraitTyParamBound(ref tref, TraitBoundModifier::Maybe) => {
2357                         try!(word(&mut self.s, "?"));
2358                         self.print_poly_trait_ref(tref)
2359                     }
2360                     RegionTyParamBound(ref lt) => {
2361                         self.print_lifetime(lt)
2362                     }
2363                 })
2364             }
2365             Ok(())
2366         } else {
2367             Ok(())
2368         }
2369     }
2370
2371     pub fn print_lifetime(&mut self,
2372                           lifetime: &ast::Lifetime)
2373                           -> IoResult<()>
2374     {
2375         self.print_name(lifetime.name)
2376     }
2377
2378     pub fn print_lifetime_def(&mut self,
2379                               lifetime: &ast::LifetimeDef)
2380                               -> IoResult<()>
2381     {
2382         try!(self.print_lifetime(&lifetime.lifetime));
2383         let mut sep = ":";
2384         for v in lifetime.bounds.iter() {
2385             try!(word(&mut self.s, sep));
2386             try!(self.print_lifetime(v));
2387             sep = "+";
2388         }
2389         Ok(())
2390     }
2391
2392     pub fn print_generics(&mut self,
2393                           generics: &ast::Generics)
2394                           -> IoResult<()>
2395     {
2396         let total = generics.lifetimes.len() + generics.ty_params.len();
2397         if total == 0 {
2398             return Ok(());
2399         }
2400
2401         try!(word(&mut self.s, "<"));
2402
2403         let mut ints = Vec::new();
2404         for i in range(0u, total) {
2405             ints.push(i);
2406         }
2407
2408         try!(self.commasep(Inconsistent, ints[], |s, &idx| {
2409             if idx < generics.lifetimes.len() {
2410                 let lifetime = &generics.lifetimes[idx];
2411                 s.print_lifetime_def(lifetime)
2412             } else {
2413                 let idx = idx - generics.lifetimes.len();
2414                 let param = &generics.ty_params[idx];
2415                 s.print_ty_param(param)
2416             }
2417         }));
2418
2419         try!(word(&mut self.s, ">"));
2420         Ok(())
2421     }
2422
2423     pub fn print_ty_param(&mut self, param: &ast::TyParam) -> IoResult<()> {
2424         try!(self.print_ident(param.ident));
2425         try!(self.print_bounds(":", param.bounds[]));
2426         match param.default {
2427             Some(ref default) => {
2428                 try!(space(&mut self.s));
2429                 try!(self.word_space("="));
2430                 self.print_type(&**default)
2431             }
2432             _ => Ok(())
2433         }
2434     }
2435
2436     pub fn print_where_clause(&mut self, generics: &ast::Generics)
2437                               -> IoResult<()> {
2438         if generics.where_clause.predicates.len() == 0 {
2439             return Ok(())
2440         }
2441
2442         try!(space(&mut self.s));
2443         try!(self.word_space("where"));
2444
2445         for (i, predicate) in generics.where_clause
2446                                       .predicates
2447                                       .iter()
2448                                       .enumerate() {
2449             if i != 0 {
2450                 try!(self.word_space(","));
2451             }
2452
2453             match predicate {
2454                 &ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate{ref bounded_ty,
2455                                                                               ref bounds,
2456                                                                               ..}) => {
2457                     try!(self.print_type(&**bounded_ty));
2458                     try!(self.print_bounds(":", bounds.as_slice()));
2459                 }
2460                 &ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate{ref lifetime,
2461                                                                                 ref bounds,
2462                                                                                 ..}) => {
2463                     try!(self.print_lifetime(lifetime));
2464                     try!(word(&mut self.s, ":"));
2465
2466                     for (i, bound) in bounds.iter().enumerate() {
2467                         try!(self.print_lifetime(bound));
2468
2469                         if i != 0 {
2470                             try!(word(&mut self.s, ":"));
2471                         }
2472                     }
2473                 }
2474                 &ast::WherePredicate::EqPredicate(ast::WhereEqPredicate{ref path, ref ty, ..}) => {
2475                     try!(self.print_path(path, false));
2476                     try!(space(&mut self.s));
2477                     try!(self.word_space("="));
2478                     try!(self.print_type(&**ty));
2479                 }
2480             }
2481         }
2482
2483         Ok(())
2484     }
2485
2486     pub fn print_meta_item(&mut self, item: &ast::MetaItem) -> IoResult<()> {
2487         try!(self.ibox(indent_unit));
2488         match item.node {
2489             ast::MetaWord(ref name) => {
2490                 try!(word(&mut self.s, name.get()));
2491             }
2492             ast::MetaNameValue(ref name, ref value) => {
2493                 try!(self.word_space(name.get()));
2494                 try!(self.word_space("="));
2495                 try!(self.print_literal(value));
2496             }
2497             ast::MetaList(ref name, ref items) => {
2498                 try!(word(&mut self.s, name.get()));
2499                 try!(self.popen());
2500                 try!(self.commasep(Consistent,
2501                                    items[],
2502                                    |s, i| s.print_meta_item(&**i)));
2503                 try!(self.pclose());
2504             }
2505         }
2506         self.end()
2507     }
2508
2509     pub fn print_view_path(&mut self, vp: &ast::ViewPath) -> IoResult<()> {
2510         match vp.node {
2511             ast::ViewPathSimple(ident, ref path, _) => {
2512                 try!(self.print_path(path, false));
2513
2514                 // FIXME(#6993) can't compare identifiers directly here
2515                 if path.segments.last().unwrap().identifier.name !=
2516                         ident.name {
2517                     try!(space(&mut self.s));
2518                     try!(self.word_space("as"));
2519                     try!(self.print_ident(ident));
2520                 }
2521
2522                 Ok(())
2523             }
2524
2525             ast::ViewPathGlob(ref path, _) => {
2526                 try!(self.print_path(path, false));
2527                 word(&mut self.s, "::*")
2528             }
2529
2530             ast::ViewPathList(ref path, ref idents, _) => {
2531                 if path.segments.is_empty() {
2532                     try!(word(&mut self.s, "{"));
2533                 } else {
2534                     try!(self.print_path(path, false));
2535                     try!(word(&mut self.s, "::{"));
2536                 }
2537                 try!(self.commasep(Inconsistent, idents[], |s, w| {
2538                     match w.node {
2539                         ast::PathListIdent { name, .. } => {
2540                             s.print_ident(name)
2541                         },
2542                         ast::PathListMod { .. } => {
2543                             word(&mut s.s, "mod")
2544                         }
2545                     }
2546                 }));
2547                 word(&mut self.s, "}")
2548             }
2549         }
2550     }
2551
2552     pub fn print_view_item(&mut self, item: &ast::ViewItem) -> IoResult<()> {
2553         try!(self.hardbreak_if_not_bol());
2554         try!(self.maybe_print_comment(item.span.lo));
2555         try!(self.print_outer_attributes(item.attrs[]));
2556         try!(self.print_visibility(item.vis));
2557         match item.node {
2558             ast::ViewItemExternCrate(id, ref optional_path, _) => {
2559                 try!(self.head("extern crate"));
2560                 for &(ref p, style) in optional_path.iter() {
2561                     try!(self.print_string(p.get(), style));
2562                     try!(space(&mut self.s));
2563                     try!(word(&mut self.s, "as"));
2564                     try!(space(&mut self.s));
2565                 }
2566                 try!(self.print_ident(id));
2567             }
2568
2569             ast::ViewItemUse(ref vp) => {
2570                 try!(self.head("use"));
2571                 try!(self.print_view_path(&**vp));
2572             }
2573         }
2574         try!(word(&mut self.s, ";"));
2575         try!(self.end()); // end inner head-block
2576         self.end() // end outer head-block
2577     }
2578
2579     pub fn print_mutability(&mut self,
2580                             mutbl: ast::Mutability) -> IoResult<()> {
2581         match mutbl {
2582             ast::MutMutable => self.word_nbsp("mut"),
2583             ast::MutImmutable => Ok(()),
2584         }
2585     }
2586
2587     pub fn print_mt(&mut self, mt: &ast::MutTy) -> IoResult<()> {
2588         try!(self.print_mutability(mt.mutbl));
2589         self.print_type(&*mt.ty)
2590     }
2591
2592     pub fn print_arg(&mut self, input: &ast::Arg) -> IoResult<()> {
2593         try!(self.ibox(indent_unit));
2594         match input.ty.node {
2595             ast::TyInfer => try!(self.print_pat(&*input.pat)),
2596             _ => {
2597                 match input.pat.node {
2598                     ast::PatIdent(_, ref path1, _) if
2599                         path1.node.name ==
2600                             parse::token::special_idents::invalid.name => {
2601                         // Do nothing.
2602                     }
2603                     _ => {
2604                         try!(self.print_pat(&*input.pat));
2605                         try!(word(&mut self.s, ":"));
2606                         try!(space(&mut self.s));
2607                     }
2608                 }
2609                 try!(self.print_type(&*input.ty));
2610             }
2611         }
2612         self.end()
2613     }
2614
2615     pub fn print_fn_output(&mut self, decl: &ast::FnDecl) -> IoResult<()> {
2616         if let ast::Return(ref ty) = decl.output {
2617             match ty.node {
2618                 ast::TyTup(ref tys) if tys.is_empty() => {
2619                     return self.maybe_print_comment(ty.span.lo);
2620                 }
2621                 _ => ()
2622             }
2623         }
2624
2625         try!(self.space_if_not_bol());
2626         try!(self.ibox(indent_unit));
2627         try!(self.word_space("->"));
2628         match decl.output {
2629             ast::NoReturn(_) =>
2630                 try!(self.word_nbsp("!")),
2631             ast::Return(ref ty) =>
2632                 try!(self.print_type(&**ty))
2633         }
2634         try!(self.end());
2635
2636         match decl.output {
2637             ast::Return(ref output) => self.maybe_print_comment(output.span.lo),
2638             _ => Ok(())
2639         }
2640     }
2641
2642     pub fn print_ty_fn(&mut self,
2643                        opt_abi: Option<abi::Abi>,
2644                        opt_sigil: Option<char>,
2645                        unsafety: ast::Unsafety,
2646                        onceness: ast::Onceness,
2647                        decl: &ast::FnDecl,
2648                        id: Option<ast::Ident>,
2649                        bounds: &OwnedSlice<ast::TyParamBound>,
2650                        generics: Option<&ast::Generics>,
2651                        opt_explicit_self: Option<&ast::ExplicitSelf_>)
2652                        -> IoResult<()> {
2653         try!(self.ibox(indent_unit));
2654
2655         // Duplicates the logic in `print_fn_header_info()`.  This is because that
2656         // function prints the sigil in the wrong place.  That should be fixed.
2657         if opt_sigil == Some('~') && onceness == ast::Once {
2658             try!(word(&mut self.s, "proc"));
2659         } else if opt_sigil == Some('&') {
2660             try!(self.print_unsafety(unsafety));
2661             try!(self.print_extern_opt_abi(opt_abi));
2662         } else {
2663             assert!(opt_sigil.is_none());
2664             try!(self.print_unsafety(unsafety));
2665             try!(self.print_opt_abi_and_extern_if_nondefault(opt_abi));
2666             try!(word(&mut self.s, "fn"));
2667         }
2668
2669         match id {
2670             Some(id) => {
2671                 try!(word(&mut self.s, " "));
2672                 try!(self.print_ident(id));
2673             }
2674             _ => ()
2675         }
2676
2677         match generics { Some(g) => try!(self.print_generics(g)), _ => () }
2678         try!(zerobreak(&mut self.s));
2679
2680         if opt_sigil == Some('&') {
2681             try!(word(&mut self.s, "|"));
2682         } else {
2683             try!(self.popen());
2684         }
2685
2686         try!(self.print_fn_args(decl, opt_explicit_self));
2687
2688         if opt_sigil == Some('&') {
2689             try!(word(&mut self.s, "|"));
2690         } else {
2691             if decl.variadic {
2692                 try!(word(&mut self.s, ", ..."));
2693             }
2694             try!(self.pclose());
2695         }
2696
2697         try!(self.print_bounds(":", bounds[]));
2698
2699         try!(self.print_fn_output(decl));
2700
2701         match generics {
2702             Some(generics) => try!(self.print_where_clause(generics)),
2703             None => {}
2704         }
2705
2706         self.end()
2707     }
2708
2709     pub fn maybe_print_trailing_comment(&mut self, span: codemap::Span,
2710                                         next_pos: Option<BytePos>)
2711         -> IoResult<()> {
2712         let cm = match self.cm {
2713             Some(cm) => cm,
2714             _ => return Ok(())
2715         };
2716         match self.next_comment() {
2717             Some(ref cmnt) => {
2718                 if (*cmnt).style != comments::Trailing { return Ok(()) }
2719                 let span_line = cm.lookup_char_pos(span.hi);
2720                 let comment_line = cm.lookup_char_pos((*cmnt).pos);
2721                 let mut next = (*cmnt).pos + BytePos(1);
2722                 match next_pos { None => (), Some(p) => next = p }
2723                 if span.hi < (*cmnt).pos && (*cmnt).pos < next &&
2724                     span_line.line == comment_line.line {
2725                         try!(self.print_comment(cmnt));
2726                         self.cur_cmnt_and_lit.cur_cmnt += 1u;
2727                     }
2728             }
2729             _ => ()
2730         }
2731         Ok(())
2732     }
2733
2734     pub fn print_remaining_comments(&mut self) -> IoResult<()> {
2735         // If there aren't any remaining comments, then we need to manually
2736         // make sure there is a line break at the end.
2737         if self.next_comment().is_none() {
2738             try!(hardbreak(&mut self.s));
2739         }
2740         loop {
2741             match self.next_comment() {
2742                 Some(ref cmnt) => {
2743                     try!(self.print_comment(cmnt));
2744                     self.cur_cmnt_and_lit.cur_cmnt += 1u;
2745                 }
2746                 _ => break
2747             }
2748         }
2749         Ok(())
2750     }
2751
2752     pub fn print_literal(&mut self, lit: &ast::Lit) -> IoResult<()> {
2753         try!(self.maybe_print_comment(lit.span.lo));
2754         match self.next_lit(lit.span.lo) {
2755             Some(ref ltrl) => {
2756                 return word(&mut self.s, (*ltrl).lit[]);
2757             }
2758             _ => ()
2759         }
2760         match lit.node {
2761             ast::LitStr(ref st, style) => self.print_string(st.get(), style),
2762             ast::LitByte(byte) => {
2763                 let mut res = String::from_str("b'");
2764                 ascii::escape_default(byte, |c| res.push(c as char));
2765                 res.push('\'');
2766                 word(&mut self.s, res[])
2767             }
2768             ast::LitChar(ch) => {
2769                 let mut res = String::from_str("'");
2770                 for c in ch.escape_default() {
2771                     res.push(c);
2772                 }
2773                 res.push('\'');
2774                 word(&mut self.s, res[])
2775             }
2776             ast::LitInt(i, t) => {
2777                 match t {
2778                     ast::SignedIntLit(st, ast::Plus) => {
2779                         word(&mut self.s,
2780                              ast_util::int_ty_to_string(st, Some(i as i64))[])
2781                     }
2782                     ast::SignedIntLit(st, ast::Minus) => {
2783                         let istr = ast_util::int_ty_to_string(st, Some(-(i as i64)));
2784                         word(&mut self.s,
2785                              format!("-{}", istr)[])
2786                     }
2787                     ast::UnsignedIntLit(ut) => {
2788                         word(&mut self.s, ast_util::uint_ty_to_string(ut, Some(i))[])
2789                     }
2790                     ast::UnsuffixedIntLit(ast::Plus) => {
2791                         word(&mut self.s, format!("{}", i)[])
2792                     }
2793                     ast::UnsuffixedIntLit(ast::Minus) => {
2794                         word(&mut self.s, format!("-{}", i)[])
2795                     }
2796                 }
2797             }
2798             ast::LitFloat(ref f, t) => {
2799                 word(&mut self.s,
2800                      format!(
2801                          "{}{}",
2802                          f.get(),
2803                          ast_util::float_ty_to_string(t)[])[])
2804             }
2805             ast::LitFloatUnsuffixed(ref f) => word(&mut self.s, f.get()),
2806             ast::LitBool(val) => {
2807                 if val { word(&mut self.s, "true") } else { word(&mut self.s, "false") }
2808             }
2809             ast::LitBinary(ref v) => {
2810                 let mut escaped: String = String::new();
2811                 for &ch in v.iter() {
2812                     ascii::escape_default(ch as u8,
2813                                           |ch| escaped.push(ch as char));
2814                 }
2815                 word(&mut self.s, format!("b\"{}\"", escaped)[])
2816             }
2817         }
2818     }
2819
2820     pub fn next_lit(&mut self, pos: BytePos) -> Option<comments::Literal> {
2821         match self.literals {
2822             Some(ref lits) => {
2823                 while self.cur_cmnt_and_lit.cur_lit < lits.len() {
2824                     let ltrl = (*lits)[self.cur_cmnt_and_lit.cur_lit].clone();
2825                     if ltrl.pos > pos { return None; }
2826                     self.cur_cmnt_and_lit.cur_lit += 1u;
2827                     if ltrl.pos == pos { return Some(ltrl); }
2828                 }
2829                 None
2830             }
2831             _ => None
2832         }
2833     }
2834
2835     pub fn maybe_print_comment(&mut self, pos: BytePos) -> IoResult<()> {
2836         loop {
2837             match self.next_comment() {
2838                 Some(ref cmnt) => {
2839                     if (*cmnt).pos < pos {
2840                         try!(self.print_comment(cmnt));
2841                         self.cur_cmnt_and_lit.cur_cmnt += 1u;
2842                     } else { break; }
2843                 }
2844                 _ => break
2845             }
2846         }
2847         Ok(())
2848     }
2849
2850     pub fn print_comment(&mut self,
2851                          cmnt: &comments::Comment) -> IoResult<()> {
2852         match cmnt.style {
2853             comments::Mixed => {
2854                 assert_eq!(cmnt.lines.len(), 1u);
2855                 try!(zerobreak(&mut self.s));
2856                 try!(word(&mut self.s, cmnt.lines[0][]));
2857                 zerobreak(&mut self.s)
2858             }
2859             comments::Isolated => {
2860                 try!(self.hardbreak_if_not_bol());
2861                 for line in cmnt.lines.iter() {
2862                     // Don't print empty lines because they will end up as trailing
2863                     // whitespace
2864                     if !line.is_empty() {
2865                         try!(word(&mut self.s, line[]));
2866                     }
2867                     try!(hardbreak(&mut self.s));
2868                 }
2869                 Ok(())
2870             }
2871             comments::Trailing => {
2872                 try!(word(&mut self.s, " "));
2873                 if cmnt.lines.len() == 1u {
2874                     try!(word(&mut self.s, cmnt.lines[0][]));
2875                     hardbreak(&mut self.s)
2876                 } else {
2877                     try!(self.ibox(0u));
2878                     for line in cmnt.lines.iter() {
2879                         if !line.is_empty() {
2880                             try!(word(&mut self.s, line[]));
2881                         }
2882                         try!(hardbreak(&mut self.s));
2883                     }
2884                     self.end()
2885                 }
2886             }
2887             comments::BlankLine => {
2888                 // We need to do at least one, possibly two hardbreaks.
2889                 let is_semi = match self.s.last_token() {
2890                     pp::String(s, _) => ";" == s,
2891                     _ => false
2892                 };
2893                 if is_semi || self.is_begin() || self.is_end() {
2894                     try!(hardbreak(&mut self.s));
2895                 }
2896                 hardbreak(&mut self.s)
2897             }
2898         }
2899     }
2900
2901     pub fn print_string(&mut self, st: &str,
2902                         style: ast::StrStyle) -> IoResult<()> {
2903         let st = match style {
2904             ast::CookedStr => {
2905                 (format!("\"{}\"", st.escape_default()))
2906             }
2907             ast::RawStr(n) => {
2908                 (format!("r{delim}\"{string}\"{delim}",
2909                          delim=repeat("#", n),
2910                          string=st))
2911             }
2912         };
2913         word(&mut self.s, st[])
2914     }
2915
2916     pub fn next_comment(&mut self) -> Option<comments::Comment> {
2917         match self.comments {
2918             Some(ref cmnts) => {
2919                 if self.cur_cmnt_and_lit.cur_cmnt < cmnts.len() {
2920                     Some(cmnts[self.cur_cmnt_and_lit.cur_cmnt].clone())
2921                 } else {
2922                     None
2923                 }
2924             }
2925             _ => None
2926         }
2927     }
2928
2929     pub fn print_opt_unsafety(&mut self,
2930                             opt_unsafety: Option<ast::Unsafety>) -> IoResult<()> {
2931         match opt_unsafety {
2932             Some(unsafety) => self.print_unsafety(unsafety),
2933             None => Ok(())
2934         }
2935     }
2936
2937     pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
2938                                                   opt_abi: Option<abi::Abi>)
2939         -> IoResult<()> {
2940         match opt_abi {
2941             Some(abi::Rust) => Ok(()),
2942             Some(abi) => {
2943                 try!(self.word_nbsp("extern"));
2944                 self.word_nbsp(abi.to_string()[])
2945             }
2946             None => Ok(())
2947         }
2948     }
2949
2950     pub fn print_extern_opt_abi(&mut self,
2951                                 opt_abi: Option<abi::Abi>) -> IoResult<()> {
2952         match opt_abi {
2953             Some(abi) => {
2954                 try!(self.word_nbsp("extern"));
2955                 self.word_nbsp(abi.to_string()[])
2956             }
2957             None => Ok(())
2958         }
2959     }
2960
2961     pub fn print_fn_header_info(&mut self,
2962                                 _opt_explicit_self: Option<&ast::ExplicitSelf_>,
2963                                 opt_unsafety: Option<ast::Unsafety>,
2964                                 abi: abi::Abi,
2965                                 vis: ast::Visibility) -> IoResult<()> {
2966         try!(word(&mut self.s, visibility_qualified(vis, "").as_slice()));
2967         try!(self.print_opt_unsafety(opt_unsafety));
2968
2969         if abi != abi::Rust {
2970             try!(self.word_nbsp("extern"));
2971             try!(self.word_nbsp(abi.to_string()[]));
2972         }
2973
2974         word(&mut self.s, "fn")
2975     }
2976
2977     pub fn print_unsafety(&mut self, s: ast::Unsafety) -> IoResult<()> {
2978         match s {
2979             ast::Unsafety::Normal => Ok(()),
2980             ast::Unsafety::Unsafe => self.word_nbsp("unsafe"),
2981         }
2982     }
2983 }
2984
2985 fn repeat(s: &str, n: uint) -> String { iter::repeat(s).take(n).collect() }
2986
2987 #[cfg(test)]
2988 mod test {
2989     use super::*;
2990
2991     use ast;
2992     use ast_util;
2993     use codemap;
2994     use parse::token;
2995     use ptr::P;
2996
2997     #[test]
2998     fn test_fun_to_string() {
2999         let abba_ident = token::str_to_ident("abba");
3000
3001         let decl = ast::FnDecl {
3002             inputs: Vec::new(),
3003             output: ast::Return(P(ast::Ty {id: 0,
3004                                node: ast::TyTup(vec![]),
3005                                span: codemap::DUMMY_SP})),
3006             variadic: false
3007         };
3008         let generics = ast_util::empty_generics();
3009         assert_eq!(fun_to_string(&decl, ast::Unsafety::Normal, abba_ident,
3010                                None, &generics),
3011                    "fn abba()");
3012     }
3013
3014     #[test]
3015     fn test_variant_to_string() {
3016         let ident = token::str_to_ident("principal_skinner");
3017
3018         let var = codemap::respan(codemap::DUMMY_SP, ast::Variant_ {
3019             name: ident,
3020             attrs: Vec::new(),
3021             // making this up as I go.... ?
3022             kind: ast::TupleVariantKind(Vec::new()),
3023             id: 0,
3024             disr_expr: None,
3025             vis: ast::Public,
3026         });
3027
3028         let varstr = variant_to_string(&var);
3029         assert_eq!(varstr, "pub principal_skinner");
3030     }
3031
3032     #[test]
3033     fn test_signed_int_to_string() {
3034         let pos_int = ast::LitInt(42, ast::SignedIntLit(ast::TyI32, ast::Plus));
3035         let neg_int = ast::LitInt((-42) as u64, ast::SignedIntLit(ast::TyI32, ast::Minus));
3036         assert_eq!(format!("-{}", lit_to_string(&codemap::dummy_spanned(pos_int))),
3037                    lit_to_string(&codemap::dummy_spanned(neg_int)));
3038     }
3039 }