]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/print/pprust.rs
Refactor struct parsing and add tests
[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::{self, 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::{self, CodeMap, BytePos};
23 use diagnostic;
24 use parse::token::{self, BinOpToken, Token};
25 use parse::lexer::comments;
26 use parse;
27 use print::pp::{self, 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::{self, 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 #[derive(Copy)]
50 pub struct NoAnn;
51
52 impl PpAnn for NoAnn {}
53
54 #[derive(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         if ast_util::struct_def_is_tuple_like(struct_def) {
1071             if !struct_def.fields.is_empty() {
1072                 try!(self.popen());
1073                 try!(self.commasep(
1074                     Inconsistent, struct_def.fields[],
1075                     |s, field| {
1076                         match field.node.kind {
1077                             ast::NamedField(..) => panic!("unexpected named field"),
1078                             ast::UnnamedField(vis) => {
1079                                 try!(s.print_visibility(vis));
1080                                 try!(s.maybe_print_comment(field.span.lo));
1081                                 s.print_type(&*field.node.ty)
1082                             }
1083                         }
1084                     }
1085                 ));
1086                 try!(self.pclose());
1087             }
1088             try!(self.print_where_clause(generics));
1089             try!(word(&mut self.s, ";"));
1090             try!(self.end());
1091             self.end() // close the outer-box
1092         } else {
1093             try!(self.print_where_clause(generics));
1094             try!(self.nbsp());
1095             try!(self.bopen());
1096             try!(self.hardbreak_if_not_bol());
1097
1098             for field in struct_def.fields.iter() {
1099                 match field.node.kind {
1100                     ast::UnnamedField(..) => panic!("unexpected unnamed field"),
1101                     ast::NamedField(ident, visibility) => {
1102                         try!(self.hardbreak_if_not_bol());
1103                         try!(self.maybe_print_comment(field.span.lo));
1104                         try!(self.print_outer_attributes(field.node.attrs[]));
1105                         try!(self.print_visibility(visibility));
1106                         try!(self.print_ident(ident));
1107                         try!(self.word_nbsp(":"));
1108                         try!(self.print_type(&*field.node.ty));
1109                         try!(word(&mut self.s, ","));
1110                     }
1111                 }
1112             }
1113
1114             self.bclose(span)
1115         }
1116     }
1117
1118     /// This doesn't deserve to be called "pretty" printing, but it should be
1119     /// meaning-preserving. A quick hack that might help would be to look at the
1120     /// spans embedded in the TTs to decide where to put spaces and newlines.
1121     /// But it'd be better to parse these according to the grammar of the
1122     /// appropriate macro, transcribe back into the grammar we just parsed from,
1123     /// and then pretty-print the resulting AST nodes (so, e.g., we print
1124     /// expression arguments as expressions). It can be done! I think.
1125     pub fn print_tt(&mut self, tt: &ast::TokenTree) -> IoResult<()> {
1126         match *tt {
1127             ast::TtToken(_, ref tk) => {
1128                 try!(word(&mut self.s, token_to_string(tk)[]));
1129                 match *tk {
1130                     parse::token::DocComment(..) => {
1131                         hardbreak(&mut self.s)
1132                     }
1133                     _ => Ok(())
1134                 }
1135             }
1136             ast::TtDelimited(_, ref delimed) => {
1137                 try!(word(&mut self.s, token_to_string(&delimed.open_token())[]));
1138                 try!(space(&mut self.s));
1139                 try!(self.print_tts(delimed.tts[]));
1140                 try!(space(&mut self.s));
1141                 word(&mut self.s, token_to_string(&delimed.close_token())[])
1142             },
1143             ast::TtSequence(_, ref seq) => {
1144                 try!(word(&mut self.s, "$("));
1145                 for tt_elt in seq.tts.iter() {
1146                     try!(self.print_tt(tt_elt));
1147                 }
1148                 try!(word(&mut self.s, ")"));
1149                 match seq.separator {
1150                     Some(ref tk) => {
1151                         try!(word(&mut self.s, token_to_string(tk)[]));
1152                     }
1153                     None => {},
1154                 }
1155                 match seq.op {
1156                     ast::ZeroOrMore => word(&mut self.s, "*"),
1157                     ast::OneOrMore => word(&mut self.s, "+"),
1158                 }
1159             }
1160         }
1161     }
1162
1163     pub fn print_tts(&mut self, tts: &[ast::TokenTree]) -> IoResult<()> {
1164         try!(self.ibox(0));
1165         for (i, tt) in tts.iter().enumerate() {
1166             if i != 0 {
1167                 try!(space(&mut self.s));
1168             }
1169             try!(self.print_tt(tt));
1170         }
1171         self.end()
1172     }
1173
1174     pub fn print_variant(&mut self, v: &ast::Variant) -> IoResult<()> {
1175         try!(self.print_visibility(v.node.vis));
1176         match v.node.kind {
1177             ast::TupleVariantKind(ref args) => {
1178                 try!(self.print_ident(v.node.name));
1179                 if !args.is_empty() {
1180                     try!(self.popen());
1181                     try!(self.commasep(Consistent,
1182                                        args[],
1183                                        |s, arg| s.print_type(&*arg.ty)));
1184                     try!(self.pclose());
1185                 }
1186             }
1187             ast::StructVariantKind(ref struct_def) => {
1188                 try!(self.head(""));
1189                 let generics = ast_util::empty_generics();
1190                 try!(self.print_struct(&**struct_def, &generics, v.node.name, v.span));
1191             }
1192         }
1193         match v.node.disr_expr {
1194             Some(ref d) => {
1195                 try!(space(&mut self.s));
1196                 try!(self.word_space("="));
1197                 self.print_expr(&**d)
1198             }
1199             _ => Ok(())
1200         }
1201     }
1202
1203     pub fn print_ty_method(&mut self, m: &ast::TypeMethod) -> IoResult<()> {
1204         try!(self.hardbreak_if_not_bol());
1205         try!(self.maybe_print_comment(m.span.lo));
1206         try!(self.print_outer_attributes(m.attrs[]));
1207         try!(self.print_ty_fn(None,
1208                               None,
1209                               m.unsafety,
1210                               ast::Many,
1211                               &*m.decl,
1212                               Some(m.ident),
1213                               &OwnedSlice::empty(),
1214                               Some(&m.generics),
1215                               Some(&m.explicit_self.node)));
1216         word(&mut self.s, ";")
1217     }
1218
1219     pub fn print_trait_method(&mut self,
1220                               m: &ast::TraitItem) -> IoResult<()> {
1221         match *m {
1222             RequiredMethod(ref ty_m) => self.print_ty_method(ty_m),
1223             ProvidedMethod(ref m) => self.print_method(&**m),
1224             TypeTraitItem(ref t) => self.print_associated_type(&**t),
1225         }
1226     }
1227
1228     pub fn print_impl_item(&mut self, ii: &ast::ImplItem) -> IoResult<()> {
1229         match *ii {
1230             MethodImplItem(ref m) => self.print_method(&**m),
1231             TypeImplItem(ref td) => self.print_typedef(&**td),
1232         }
1233     }
1234
1235     pub fn print_method(&mut self, meth: &ast::Method) -> IoResult<()> {
1236         try!(self.hardbreak_if_not_bol());
1237         try!(self.maybe_print_comment(meth.span.lo));
1238         try!(self.print_outer_attributes(meth.attrs[]));
1239         match meth.node {
1240             ast::MethDecl(ident,
1241                           ref generics,
1242                           abi,
1243                           ref explicit_self,
1244                           unsafety,
1245                           ref decl,
1246                           ref body,
1247                           vis) => {
1248                 try!(self.print_fn(&**decl,
1249                                    Some(unsafety),
1250                                    abi,
1251                                    ident,
1252                                    generics,
1253                                    Some(&explicit_self.node),
1254                                    vis));
1255                 try!(word(&mut self.s, " "));
1256                 self.print_block_with_attrs(&**body, meth.attrs[])
1257             },
1258             ast::MethMac(codemap::Spanned { node: ast::MacInvocTT(ref pth, ref tts, _),
1259                                             ..}) => {
1260                 // code copied from ItemMac:
1261                 try!(self.print_path(pth, false));
1262                 try!(word(&mut self.s, "! "));
1263                 try!(self.cbox(indent_unit));
1264                 try!(self.popen());
1265                 try!(self.print_tts(tts[]));
1266                 try!(self.pclose());
1267                 try!(word(&mut self.s, ";"));
1268                 self.end()
1269             }
1270         }
1271     }
1272
1273     pub fn print_outer_attributes(&mut self,
1274                                   attrs: &[ast::Attribute]) -> IoResult<()> {
1275         let mut count = 0u;
1276         for attr in attrs.iter() {
1277             match attr.node.style {
1278                 ast::AttrOuter => {
1279                     try!(self.print_attribute(attr));
1280                     count += 1;
1281                 }
1282                 _ => {/* fallthrough */ }
1283             }
1284         }
1285         if count > 0 {
1286             try!(self.hardbreak_if_not_bol());
1287         }
1288         Ok(())
1289     }
1290
1291     pub fn print_inner_attributes(&mut self,
1292                                   attrs: &[ast::Attribute]) -> IoResult<()> {
1293         let mut count = 0u;
1294         for attr in attrs.iter() {
1295             match attr.node.style {
1296                 ast::AttrInner => {
1297                     try!(self.print_attribute(attr));
1298                     count += 1;
1299                 }
1300                 _ => {/* fallthrough */ }
1301             }
1302         }
1303         if count > 0 {
1304             try!(self.hardbreak_if_not_bol());
1305         }
1306         Ok(())
1307     }
1308
1309     pub fn print_attribute(&mut self, attr: &ast::Attribute) -> IoResult<()> {
1310         try!(self.hardbreak_if_not_bol());
1311         try!(self.maybe_print_comment(attr.span.lo));
1312         if attr.node.is_sugared_doc {
1313             word(&mut self.s, attr.value_str().unwrap().get())
1314         } else {
1315             match attr.node.style {
1316                 ast::AttrInner => try!(word(&mut self.s, "#![")),
1317                 ast::AttrOuter => try!(word(&mut self.s, "#[")),
1318             }
1319             try!(self.print_meta_item(&*attr.meta()));
1320             word(&mut self.s, "]")
1321         }
1322     }
1323
1324
1325     pub fn print_stmt(&mut self, st: &ast::Stmt) -> IoResult<()> {
1326         try!(self.maybe_print_comment(st.span.lo));
1327         match st.node {
1328             ast::StmtDecl(ref decl, _) => {
1329                 try!(self.print_decl(&**decl));
1330             }
1331             ast::StmtExpr(ref expr, _) => {
1332                 try!(self.space_if_not_bol());
1333                 try!(self.print_expr(&**expr));
1334             }
1335             ast::StmtSemi(ref expr, _) => {
1336                 try!(self.space_if_not_bol());
1337                 try!(self.print_expr(&**expr));
1338                 try!(word(&mut self.s, ";"));
1339             }
1340             ast::StmtMac(ref mac, style) => {
1341                 try!(self.space_if_not_bol());
1342                 let delim = match style {
1343                     ast::MacStmtWithBraces => token::Brace,
1344                     _ => token::Paren
1345                 };
1346                 try!(self.print_mac(&**mac, delim));
1347                 match style {
1348                     ast::MacStmtWithBraces => {}
1349                     _ => try!(word(&mut self.s, ";")),
1350                 }
1351             }
1352         }
1353         if parse::classify::stmt_ends_with_semi(&st.node) {
1354             try!(word(&mut self.s, ";"));
1355         }
1356         self.maybe_print_trailing_comment(st.span, None)
1357     }
1358
1359     pub fn print_block(&mut self, blk: &ast::Block) -> IoResult<()> {
1360         self.print_block_with_attrs(blk, &[])
1361     }
1362
1363     pub fn print_block_unclosed(&mut self, blk: &ast::Block) -> IoResult<()> {
1364         self.print_block_unclosed_indent(blk, indent_unit)
1365     }
1366
1367     pub fn print_block_unclosed_indent(&mut self, blk: &ast::Block,
1368                                        indented: uint) -> IoResult<()> {
1369         self.print_block_maybe_unclosed(blk, indented, &[], false)
1370     }
1371
1372     pub fn print_block_with_attrs(&mut self,
1373                                   blk: &ast::Block,
1374                                   attrs: &[ast::Attribute]) -> IoResult<()> {
1375         self.print_block_maybe_unclosed(blk, indent_unit, attrs, true)
1376     }
1377
1378     pub fn print_block_maybe_unclosed(&mut self,
1379                                       blk: &ast::Block,
1380                                       indented: uint,
1381                                       attrs: &[ast::Attribute],
1382                                       close_box: bool) -> IoResult<()> {
1383         match blk.rules {
1384             ast::UnsafeBlock(..) => try!(self.word_space("unsafe")),
1385             ast::DefaultBlock => ()
1386         }
1387         try!(self.maybe_print_comment(blk.span.lo));
1388         try!(self.ann.pre(self, NodeBlock(blk)));
1389         try!(self.bopen());
1390
1391         try!(self.print_inner_attributes(attrs));
1392
1393         for vi in blk.view_items.iter() {
1394             try!(self.print_view_item(vi));
1395         }
1396         for st in blk.stmts.iter() {
1397             try!(self.print_stmt(&**st));
1398         }
1399         match blk.expr {
1400             Some(ref expr) => {
1401                 try!(self.space_if_not_bol());
1402                 try!(self.print_expr(&**expr));
1403                 try!(self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi)));
1404             }
1405             _ => ()
1406         }
1407         try!(self.bclose_maybe_open(blk.span, indented, close_box));
1408         self.ann.post(self, NodeBlock(blk))
1409     }
1410
1411     fn print_else(&mut self, els: Option<&ast::Expr>) -> IoResult<()> {
1412         match els {
1413             Some(_else) => {
1414                 match _else.node {
1415                     // "another else-if"
1416                     ast::ExprIf(ref i, ref then, ref e) => {
1417                         try!(self.cbox(indent_unit - 1u));
1418                         try!(self.ibox(0u));
1419                         try!(word(&mut self.s, " else if "));
1420                         try!(self.print_expr(&**i));
1421                         try!(space(&mut self.s));
1422                         try!(self.print_block(&**then));
1423                         self.print_else(e.as_ref().map(|e| &**e))
1424                     }
1425                     // "another else-if-let"
1426                     ast::ExprIfLet(ref pat, ref expr, ref then, ref e) => {
1427                         try!(self.cbox(indent_unit - 1u));
1428                         try!(self.ibox(0u));
1429                         try!(word(&mut self.s, " else if let "));
1430                         try!(self.print_pat(&**pat));
1431                         try!(space(&mut self.s));
1432                         try!(self.word_space("="));
1433                         try!(self.print_expr(&**expr));
1434                         try!(space(&mut self.s));
1435                         try!(self.print_block(&**then));
1436                         self.print_else(e.as_ref().map(|e| &**e))
1437                     }
1438                     // "final else"
1439                     ast::ExprBlock(ref b) => {
1440                         try!(self.cbox(indent_unit - 1u));
1441                         try!(self.ibox(0u));
1442                         try!(word(&mut self.s, " else "));
1443                         self.print_block(&**b)
1444                     }
1445                     // BLEAH, constraints would be great here
1446                     _ => {
1447                         panic!("print_if saw if with weird alternative");
1448                     }
1449                 }
1450             }
1451             _ => Ok(())
1452         }
1453     }
1454
1455     pub fn print_if(&mut self, test: &ast::Expr, blk: &ast::Block,
1456                     elseopt: Option<&ast::Expr>) -> IoResult<()> {
1457         try!(self.head("if"));
1458         try!(self.print_expr(test));
1459         try!(space(&mut self.s));
1460         try!(self.print_block(blk));
1461         self.print_else(elseopt)
1462     }
1463
1464     pub fn print_if_let(&mut self, pat: &ast::Pat, expr: &ast::Expr, blk: &ast::Block,
1465                         elseopt: Option<&ast::Expr>) -> IoResult<()> {
1466         try!(self.head("if let"));
1467         try!(self.print_pat(pat));
1468         try!(space(&mut self.s));
1469         try!(self.word_space("="));
1470         try!(self.print_expr(expr));
1471         try!(space(&mut self.s));
1472         try!(self.print_block(blk));
1473         self.print_else(elseopt)
1474     }
1475
1476     pub fn print_mac(&mut self, m: &ast::Mac, delim: token::DelimToken)
1477                      -> IoResult<()> {
1478         match m.node {
1479             // I think it's reasonable to hide the ctxt here:
1480             ast::MacInvocTT(ref pth, ref tts, _) => {
1481                 try!(self.print_path(pth, false));
1482                 try!(word(&mut self.s, "!"));
1483                 match delim {
1484                     token::Paren => try!(self.popen()),
1485                     token::Bracket => try!(word(&mut self.s, "[")),
1486                     token::Brace => try!(self.bopen()),
1487                 }
1488                 try!(self.print_tts(tts.as_slice()));
1489                 match delim {
1490                     token::Paren => self.pclose(),
1491                     token::Bracket => word(&mut self.s, "]"),
1492                     token::Brace => self.bclose(m.span),
1493                 }
1494             }
1495         }
1496     }
1497
1498
1499     fn print_call_post(&mut self, args: &[P<ast::Expr>]) -> IoResult<()> {
1500         try!(self.popen());
1501         try!(self.commasep_exprs(Inconsistent, args));
1502         self.pclose()
1503     }
1504
1505     pub fn print_expr_maybe_paren(&mut self, expr: &ast::Expr) -> IoResult<()> {
1506         let needs_par = needs_parentheses(expr);
1507         if needs_par {
1508             try!(self.popen());
1509         }
1510         try!(self.print_expr(expr));
1511         if needs_par {
1512             try!(self.pclose());
1513         }
1514         Ok(())
1515     }
1516
1517     pub fn print_expr(&mut self, expr: &ast::Expr) -> IoResult<()> {
1518         try!(self.maybe_print_comment(expr.span.lo));
1519         try!(self.ibox(indent_unit));
1520         try!(self.ann.pre(self, NodeExpr(expr)));
1521         match expr.node {
1522             ast::ExprBox(ref p, ref e) => {
1523                 try!(word(&mut self.s, "box"));
1524                 try!(word(&mut self.s, "("));
1525                 try!(p.as_ref().map_or(Ok(()), |e|self.print_expr(&**e)));
1526                 try!(self.word_space(")"));
1527                 try!(self.print_expr(&**e));
1528             }
1529             ast::ExprVec(ref exprs) => {
1530                 try!(self.ibox(indent_unit));
1531                 try!(word(&mut self.s, "["));
1532                 try!(self.commasep_exprs(Inconsistent, exprs[]));
1533                 try!(word(&mut self.s, "]"));
1534                 try!(self.end());
1535             }
1536
1537             ast::ExprRepeat(ref element, ref count) => {
1538                 try!(self.ibox(indent_unit));
1539                 try!(word(&mut self.s, "["));
1540                 try!(self.print_expr(&**element));
1541                 try!(self.word_space(";"));
1542                 try!(self.print_expr(&**count));
1543                 try!(word(&mut self.s, "]"));
1544                 try!(self.end());
1545             }
1546
1547             ast::ExprStruct(ref path, ref fields, ref wth) => {
1548                 try!(self.print_path(path, true));
1549                 try!(word(&mut self.s, "{"));
1550                 try!(self.commasep_cmnt(
1551                     Consistent,
1552                     fields[],
1553                     |s, field| {
1554                         try!(s.ibox(indent_unit));
1555                         try!(s.print_ident(field.ident.node));
1556                         try!(s.word_space(":"));
1557                         try!(s.print_expr(&*field.expr));
1558                         s.end()
1559                     },
1560                     |f| f.span));
1561                 match *wth {
1562                     Some(ref expr) => {
1563                         try!(self.ibox(indent_unit));
1564                         if !fields.is_empty() {
1565                             try!(word(&mut self.s, ","));
1566                             try!(space(&mut self.s));
1567                         }
1568                         try!(word(&mut self.s, ".."));
1569                         try!(self.print_expr(&**expr));
1570                         try!(self.end());
1571                     }
1572                     _ => try!(word(&mut self.s, ","))
1573                 }
1574                 try!(word(&mut self.s, "}"));
1575             }
1576             ast::ExprTup(ref exprs) => {
1577                 try!(self.popen());
1578                 try!(self.commasep_exprs(Inconsistent, exprs[]));
1579                 if exprs.len() == 1 {
1580                     try!(word(&mut self.s, ","));
1581                 }
1582                 try!(self.pclose());
1583             }
1584             ast::ExprCall(ref func, ref args) => {
1585                 try!(self.print_expr_maybe_paren(&**func));
1586                 try!(self.print_call_post(args[]));
1587             }
1588             ast::ExprMethodCall(ident, ref tys, ref args) => {
1589                 let base_args = args.slice_from(1);
1590                 try!(self.print_expr(&*args[0]));
1591                 try!(word(&mut self.s, "."));
1592                 try!(self.print_ident(ident.node));
1593                 if tys.len() > 0u {
1594                     try!(word(&mut self.s, "::<"));
1595                     try!(self.commasep(Inconsistent, tys[],
1596                                        |s, ty| s.print_type(&**ty)));
1597                     try!(word(&mut self.s, ">"));
1598                 }
1599                 try!(self.print_call_post(base_args));
1600             }
1601             ast::ExprBinary(op, ref lhs, ref rhs) => {
1602                 try!(self.print_expr(&**lhs));
1603                 try!(space(&mut self.s));
1604                 try!(self.word_space(ast_util::binop_to_string(op)));
1605                 try!(self.print_expr(&**rhs));
1606             }
1607             ast::ExprUnary(op, ref expr) => {
1608                 try!(word(&mut self.s, ast_util::unop_to_string(op)));
1609                 try!(self.print_expr_maybe_paren(&**expr));
1610             }
1611             ast::ExprAddrOf(m, ref expr) => {
1612                 try!(word(&mut self.s, "&"));
1613                 try!(self.print_mutability(m));
1614                 try!(self.print_expr_maybe_paren(&**expr));
1615             }
1616             ast::ExprLit(ref lit) => try!(self.print_literal(&**lit)),
1617             ast::ExprCast(ref expr, ref ty) => {
1618                 try!(self.print_expr(&**expr));
1619                 try!(space(&mut self.s));
1620                 try!(self.word_space("as"));
1621                 try!(self.print_type(&**ty));
1622             }
1623             ast::ExprIf(ref test, ref blk, ref elseopt) => {
1624                 try!(self.print_if(&**test, &**blk, elseopt.as_ref().map(|e| &**e)));
1625             }
1626             ast::ExprIfLet(ref pat, ref expr, ref blk, ref elseopt) => {
1627                 try!(self.print_if_let(&**pat, &**expr, &** blk, elseopt.as_ref().map(|e| &**e)));
1628             }
1629             ast::ExprWhile(ref test, ref blk, opt_ident) => {
1630                 for ident in opt_ident.iter() {
1631                     try!(self.print_ident(*ident));
1632                     try!(self.word_space(":"));
1633                 }
1634                 try!(self.head("while"));
1635                 try!(self.print_expr(&**test));
1636                 try!(space(&mut self.s));
1637                 try!(self.print_block(&**blk));
1638             }
1639             ast::ExprWhileLet(ref pat, ref expr, ref blk, opt_ident) => {
1640                 for ident in opt_ident.iter() {
1641                     try!(self.print_ident(*ident));
1642                     try!(self.word_space(":"));
1643                 }
1644                 try!(self.head("while let"));
1645                 try!(self.print_pat(&**pat));
1646                 try!(space(&mut self.s));
1647                 try!(self.word_space("="));
1648                 try!(self.print_expr(&**expr));
1649                 try!(space(&mut self.s));
1650                 try!(self.print_block(&**blk));
1651             }
1652             ast::ExprForLoop(ref pat, ref iter, ref blk, opt_ident) => {
1653                 for ident in opt_ident.iter() {
1654                     try!(self.print_ident(*ident));
1655                     try!(self.word_space(":"));
1656                 }
1657                 try!(self.head("for"));
1658                 try!(self.print_pat(&**pat));
1659                 try!(space(&mut self.s));
1660                 try!(self.word_space("in"));
1661                 try!(self.print_expr(&**iter));
1662                 try!(space(&mut self.s));
1663                 try!(self.print_block(&**blk));
1664             }
1665             ast::ExprLoop(ref blk, opt_ident) => {
1666                 for ident in opt_ident.iter() {
1667                     try!(self.print_ident(*ident));
1668                     try!(self.word_space(":"));
1669                 }
1670                 try!(self.head("loop"));
1671                 try!(space(&mut self.s));
1672                 try!(self.print_block(&**blk));
1673             }
1674             ast::ExprMatch(ref expr, ref arms, _) => {
1675                 try!(self.cbox(indent_unit));
1676                 try!(self.ibox(4));
1677                 try!(self.word_nbsp("match"));
1678                 try!(self.print_expr(&**expr));
1679                 try!(space(&mut self.s));
1680                 try!(self.bopen());
1681                 for arm in arms.iter() {
1682                     try!(self.print_arm(arm));
1683                 }
1684                 try!(self.bclose_(expr.span, indent_unit));
1685             }
1686             ast::ExprClosure(capture_clause, opt_kind, ref decl, ref body) => {
1687                 try!(self.print_capture_clause(capture_clause));
1688
1689                 try!(self.print_fn_block_args(&**decl, opt_kind));
1690                 try!(space(&mut self.s));
1691
1692                 if !body.stmts.is_empty() || !body.expr.is_some() {
1693                     try!(self.print_block_unclosed(&**body));
1694                 } else {
1695                     // we extract the block, so as not to create another set of boxes
1696                     match body.expr.as_ref().unwrap().node {
1697                         ast::ExprBlock(ref blk) => {
1698                             try!(self.print_block_unclosed(&**blk));
1699                         }
1700                         _ => {
1701                             // this is a bare expression
1702                             try!(self.print_expr(body.expr.as_ref().map(|e| &**e).unwrap()));
1703                             try!(self.end()); // need to close a box
1704                         }
1705                     }
1706                 }
1707                 // a box will be closed by print_expr, but we didn't want an overall
1708                 // wrapper so we closed the corresponding opening. so create an
1709                 // empty box to satisfy the close.
1710                 try!(self.ibox(0));
1711             }
1712             ast::ExprBlock(ref blk) => {
1713                 // containing cbox, will be closed by print-block at }
1714                 try!(self.cbox(indent_unit));
1715                 // head-box, will be closed by print-block after {
1716                 try!(self.ibox(0u));
1717                 try!(self.print_block(&**blk));
1718             }
1719             ast::ExprAssign(ref lhs, ref rhs) => {
1720                 try!(self.print_expr(&**lhs));
1721                 try!(space(&mut self.s));
1722                 try!(self.word_space("="));
1723                 try!(self.print_expr(&**rhs));
1724             }
1725             ast::ExprAssignOp(op, ref lhs, ref rhs) => {
1726                 try!(self.print_expr(&**lhs));
1727                 try!(space(&mut self.s));
1728                 try!(word(&mut self.s, ast_util::binop_to_string(op)));
1729                 try!(self.word_space("="));
1730                 try!(self.print_expr(&**rhs));
1731             }
1732             ast::ExprField(ref expr, id) => {
1733                 try!(self.print_expr(&**expr));
1734                 try!(word(&mut self.s, "."));
1735                 try!(self.print_ident(id.node));
1736             }
1737             ast::ExprTupField(ref expr, id) => {
1738                 try!(self.print_expr(&**expr));
1739                 try!(word(&mut self.s, "."));
1740                 try!(self.print_uint(id.node));
1741             }
1742             ast::ExprIndex(ref expr, ref index) => {
1743                 try!(self.print_expr(&**expr));
1744                 try!(word(&mut self.s, "["));
1745                 try!(self.print_expr(&**index));
1746                 try!(word(&mut self.s, "]"));
1747             }
1748             ast::ExprRange(ref start, ref end) => {
1749                 if let &Some(ref e) = start {
1750                     try!(self.print_expr(&**e));
1751                 }
1752                 if start.is_some() || end.is_some() {
1753                     try!(word(&mut self.s, ".."));
1754                 }
1755                 if let &Some(ref e) = end {
1756                     try!(self.print_expr(&**e));
1757                 }
1758             }
1759             ast::ExprPath(ref path) => try!(self.print_path(path, true)),
1760             ast::ExprBreak(opt_ident) => {
1761                 try!(word(&mut self.s, "break"));
1762                 try!(space(&mut self.s));
1763                 for ident in opt_ident.iter() {
1764                     try!(self.print_ident(*ident));
1765                     try!(space(&mut self.s));
1766                 }
1767             }
1768             ast::ExprAgain(opt_ident) => {
1769                 try!(word(&mut self.s, "continue"));
1770                 try!(space(&mut self.s));
1771                 for ident in opt_ident.iter() {
1772                     try!(self.print_ident(*ident));
1773                     try!(space(&mut self.s))
1774                 }
1775             }
1776             ast::ExprRet(ref result) => {
1777                 try!(word(&mut self.s, "return"));
1778                 match *result {
1779                     Some(ref expr) => {
1780                         try!(word(&mut self.s, " "));
1781                         try!(self.print_expr(&**expr));
1782                     }
1783                     _ => ()
1784                 }
1785             }
1786             ast::ExprInlineAsm(ref a) => {
1787                 try!(word(&mut self.s, "asm!"));
1788                 try!(self.popen());
1789                 try!(self.print_string(a.asm.get(), a.asm_str_style));
1790                 try!(self.word_space(":"));
1791
1792                 try!(self.commasep(Inconsistent, a.outputs[],
1793                                    |s, &(ref co, ref o, is_rw)| {
1794                     match co.get().slice_shift_char() {
1795                         Some(('=', operand)) if is_rw => {
1796                             try!(s.print_string(format!("+{}", operand)[],
1797                                                 ast::CookedStr))
1798                         }
1799                         _ => try!(s.print_string(co.get(), ast::CookedStr))
1800                     }
1801                     try!(s.popen());
1802                     try!(s.print_expr(&**o));
1803                     try!(s.pclose());
1804                     Ok(())
1805                 }));
1806                 try!(space(&mut self.s));
1807                 try!(self.word_space(":"));
1808
1809                 try!(self.commasep(Inconsistent, a.inputs[],
1810                                    |s, &(ref co, ref o)| {
1811                     try!(s.print_string(co.get(), ast::CookedStr));
1812                     try!(s.popen());
1813                     try!(s.print_expr(&**o));
1814                     try!(s.pclose());
1815                     Ok(())
1816                 }));
1817                 try!(space(&mut self.s));
1818                 try!(self.word_space(":"));
1819
1820                 try!(self.commasep(Inconsistent, a.clobbers[],
1821                                    |s, co| {
1822                     try!(s.print_string(co.get(), ast::CookedStr));
1823                     Ok(())
1824                 }));
1825
1826                 let mut options = vec!();
1827                 if a.volatile {
1828                     options.push("volatile");
1829                 }
1830                 if a.alignstack {
1831                     options.push("alignstack");
1832                 }
1833                 if a.dialect == ast::AsmDialect::AsmIntel {
1834                     options.push("intel");
1835                 }
1836
1837                 if options.len() > 0 {
1838                     try!(space(&mut self.s));
1839                     try!(self.word_space(":"));
1840                     try!(self.commasep(Inconsistent, &*options,
1841                                        |s, &co| {
1842                         try!(s.print_string(co, ast::CookedStr));
1843                         Ok(())
1844                     }));
1845                 }
1846
1847                 try!(self.pclose());
1848             }
1849             ast::ExprMac(ref m) => try!(self.print_mac(m, token::Paren)),
1850             ast::ExprParen(ref e) => {
1851                 try!(self.popen());
1852                 try!(self.print_expr(&**e));
1853                 try!(self.pclose());
1854             }
1855         }
1856         try!(self.ann.post(self, NodeExpr(expr)));
1857         self.end()
1858     }
1859
1860     pub fn print_local_decl(&mut self, loc: &ast::Local) -> IoResult<()> {
1861         try!(self.print_pat(&*loc.pat));
1862         if let Some(ref ty) = loc.ty {
1863             try!(self.word_space(":"));
1864             try!(self.print_type(&**ty));
1865         }
1866         Ok(())
1867     }
1868
1869     pub fn print_decl(&mut self, decl: &ast::Decl) -> IoResult<()> {
1870         try!(self.maybe_print_comment(decl.span.lo));
1871         match decl.node {
1872             ast::DeclLocal(ref loc) => {
1873                 try!(self.space_if_not_bol());
1874                 try!(self.ibox(indent_unit));
1875                 try!(self.word_nbsp("let"));
1876
1877                 try!(self.ibox(indent_unit));
1878                 try!(self.print_local_decl(&**loc));
1879                 try!(self.end());
1880                 if let Some(ref init) = loc.init {
1881                     try!(self.nbsp());
1882                     try!(self.word_space("="));
1883                     try!(self.print_expr(&**init));
1884                 }
1885                 self.end()
1886             }
1887             ast::DeclItem(ref item) => self.print_item(&**item)
1888         }
1889     }
1890
1891     pub fn print_ident(&mut self, ident: ast::Ident) -> IoResult<()> {
1892         if self.encode_idents_with_hygiene {
1893             let encoded = ident.encode_with_hygiene();
1894             try!(word(&mut self.s, encoded[]))
1895         } else {
1896             try!(word(&mut self.s, token::get_ident(ident).get()))
1897         }
1898         self.ann.post(self, NodeIdent(&ident))
1899     }
1900
1901     pub fn print_uint(&mut self, i: uint) -> IoResult<()> {
1902         word(&mut self.s, i.to_string()[])
1903     }
1904
1905     pub fn print_name(&mut self, name: ast::Name) -> IoResult<()> {
1906         try!(word(&mut self.s, token::get_name(name).get()));
1907         self.ann.post(self, NodeName(&name))
1908     }
1909
1910     pub fn print_for_decl(&mut self, loc: &ast::Local,
1911                           coll: &ast::Expr) -> IoResult<()> {
1912         try!(self.print_local_decl(loc));
1913         try!(space(&mut self.s));
1914         try!(self.word_space("in"));
1915         self.print_expr(coll)
1916     }
1917
1918     fn print_path(&mut self,
1919                   path: &ast::Path,
1920                   colons_before_params: bool)
1921                   -> IoResult<()>
1922     {
1923         try!(self.maybe_print_comment(path.span.lo));
1924         if path.global {
1925             try!(word(&mut self.s, "::"));
1926         }
1927
1928         let mut first = true;
1929         for segment in path.segments.iter() {
1930             if first {
1931                 first = false
1932             } else {
1933                 try!(word(&mut self.s, "::"))
1934             }
1935
1936             try!(self.print_ident(segment.identifier));
1937
1938             try!(self.print_path_parameters(&segment.parameters, colons_before_params));
1939         }
1940
1941         Ok(())
1942     }
1943
1944     fn print_path_parameters(&mut self,
1945                              parameters: &ast::PathParameters,
1946                              colons_before_params: bool)
1947                              -> IoResult<()>
1948     {
1949         if parameters.is_empty() {
1950             return Ok(());
1951         }
1952
1953         if colons_before_params {
1954             try!(word(&mut self.s, "::"))
1955         }
1956
1957         match *parameters {
1958             ast::AngleBracketedParameters(ref data) => {
1959                 try!(word(&mut self.s, "<"));
1960
1961                 let mut comma = false;
1962                 for lifetime in data.lifetimes.iter() {
1963                     if comma {
1964                         try!(self.word_space(","))
1965                     }
1966                     try!(self.print_lifetime(lifetime));
1967                     comma = true;
1968                 }
1969
1970                 if !data.types.is_empty() {
1971                     if comma {
1972                         try!(self.word_space(","))
1973                     }
1974                     try!(self.commasep(
1975                         Inconsistent,
1976                         data.types[],
1977                         |s, ty| s.print_type(&**ty)));
1978                         comma = true;
1979                 }
1980
1981                 for binding in data.bindings.iter() {
1982                     if comma {
1983                         try!(self.word_space(","))
1984                     }
1985                     try!(self.print_ident(binding.ident));
1986                     try!(space(&mut self.s));
1987                     try!(self.word_space("="));
1988                     try!(self.print_type(&*binding.ty));
1989                     comma = true;
1990                 }
1991
1992                 try!(word(&mut self.s, ">"))
1993             }
1994
1995             ast::ParenthesizedParameters(ref data) => {
1996                 try!(word(&mut self.s, "("));
1997                 try!(self.commasep(
1998                     Inconsistent,
1999                     data.inputs[],
2000                     |s, ty| s.print_type(&**ty)));
2001                 try!(word(&mut self.s, ")"));
2002
2003                 match data.output {
2004                     None => { }
2005                     Some(ref ty) => {
2006                         try!(self.space_if_not_bol());
2007                         try!(self.word_space("->"));
2008                         try!(self.print_type(&**ty));
2009                     }
2010                 }
2011             }
2012         }
2013
2014         Ok(())
2015     }
2016
2017     pub fn print_pat(&mut self, pat: &ast::Pat) -> IoResult<()> {
2018         try!(self.maybe_print_comment(pat.span.lo));
2019         try!(self.ann.pre(self, NodePat(pat)));
2020         /* Pat isn't normalized, but the beauty of it
2021          is that it doesn't matter */
2022         match pat.node {
2023             ast::PatWild(ast::PatWildSingle) => try!(word(&mut self.s, "_")),
2024             ast::PatWild(ast::PatWildMulti) => try!(word(&mut self.s, "..")),
2025             ast::PatIdent(binding_mode, ref path1, ref sub) => {
2026                 match binding_mode {
2027                     ast::BindByRef(mutbl) => {
2028                         try!(self.word_nbsp("ref"));
2029                         try!(self.print_mutability(mutbl));
2030                     }
2031                     ast::BindByValue(ast::MutImmutable) => {}
2032                     ast::BindByValue(ast::MutMutable) => {
2033                         try!(self.word_nbsp("mut"));
2034                     }
2035                 }
2036                 try!(self.print_ident(path1.node));
2037                 match *sub {
2038                     Some(ref p) => {
2039                         try!(word(&mut self.s, "@"));
2040                         try!(self.print_pat(&**p));
2041                     }
2042                     None => ()
2043                 }
2044             }
2045             ast::PatEnum(ref path, ref args_) => {
2046                 try!(self.print_path(path, true));
2047                 match *args_ {
2048                     None => try!(word(&mut self.s, "(..)")),
2049                     Some(ref args) => {
2050                         if !args.is_empty() {
2051                             try!(self.popen());
2052                             try!(self.commasep(Inconsistent, args[],
2053                                               |s, p| s.print_pat(&**p)));
2054                             try!(self.pclose());
2055                         }
2056                     }
2057                 }
2058             }
2059             ast::PatStruct(ref path, ref fields, etc) => {
2060                 try!(self.print_path(path, true));
2061                 try!(self.nbsp());
2062                 try!(self.word_space("{"));
2063                 try!(self.commasep_cmnt(
2064                     Consistent, fields[],
2065                     |s, f| {
2066                         try!(s.cbox(indent_unit));
2067                         if !f.node.is_shorthand {
2068                             try!(s.print_ident(f.node.ident));
2069                             try!(s.word_nbsp(":"));
2070                         }
2071                         try!(s.print_pat(&*f.node.pat));
2072                         s.end()
2073                     },
2074                     |f| f.node.pat.span));
2075                 if etc {
2076                     if fields.len() != 0u { try!(self.word_space(",")); }
2077                     try!(word(&mut self.s, ".."));
2078                 }
2079                 try!(space(&mut self.s));
2080                 try!(word(&mut self.s, "}"));
2081             }
2082             ast::PatTup(ref elts) => {
2083                 try!(self.popen());
2084                 try!(self.commasep(Inconsistent,
2085                                    elts[],
2086                                    |s, p| s.print_pat(&**p)));
2087                 if elts.len() == 1 {
2088                     try!(word(&mut self.s, ","));
2089                 }
2090                 try!(self.pclose());
2091             }
2092             ast::PatBox(ref inner) => {
2093                 try!(word(&mut self.s, "box "));
2094                 try!(self.print_pat(&**inner));
2095             }
2096             ast::PatRegion(ref inner) => {
2097                 try!(word(&mut self.s, "&"));
2098                 try!(self.print_pat(&**inner));
2099             }
2100             ast::PatLit(ref e) => try!(self.print_expr(&**e)),
2101             ast::PatRange(ref begin, ref end) => {
2102                 try!(self.print_expr(&**begin));
2103                 try!(space(&mut self.s));
2104                 try!(word(&mut self.s, "..."));
2105                 try!(self.print_expr(&**end));
2106             }
2107             ast::PatVec(ref before, ref slice, ref after) => {
2108                 try!(word(&mut self.s, "["));
2109                 try!(self.commasep(Inconsistent,
2110                                    before[],
2111                                    |s, p| s.print_pat(&**p)));
2112                 for p in slice.iter() {
2113                     if !before.is_empty() { try!(self.word_space(",")); }
2114                     try!(self.print_pat(&**p));
2115                     match **p {
2116                         ast::Pat { node: ast::PatWild(ast::PatWildMulti), .. } => {
2117                             // this case is handled by print_pat
2118                         }
2119                         _ => try!(word(&mut self.s, "..")),
2120                     }
2121                     if !after.is_empty() { try!(self.word_space(",")); }
2122                 }
2123                 try!(self.commasep(Inconsistent,
2124                                    after[],
2125                                    |s, p| s.print_pat(&**p)));
2126                 try!(word(&mut self.s, "]"));
2127             }
2128             ast::PatMac(ref m) => try!(self.print_mac(m, token::Paren)),
2129         }
2130         self.ann.post(self, NodePat(pat))
2131     }
2132
2133     fn print_arm(&mut self, arm: &ast::Arm) -> IoResult<()> {
2134         // I have no idea why this check is necessary, but here it
2135         // is :(
2136         if arm.attrs.is_empty() {
2137             try!(space(&mut self.s));
2138         }
2139         try!(self.cbox(indent_unit));
2140         try!(self.ibox(0u));
2141         try!(self.print_outer_attributes(arm.attrs[]));
2142         let mut first = true;
2143         for p in arm.pats.iter() {
2144             if first {
2145                 first = false;
2146             } else {
2147                 try!(space(&mut self.s));
2148                 try!(self.word_space("|"));
2149             }
2150             try!(self.print_pat(&**p));
2151         }
2152         try!(space(&mut self.s));
2153         if let Some(ref e) = arm.guard {
2154             try!(self.word_space("if"));
2155             try!(self.print_expr(&**e));
2156             try!(space(&mut self.s));
2157         }
2158         try!(self.word_space("=>"));
2159
2160         match arm.body.node {
2161             ast::ExprBlock(ref blk) => {
2162                 // the block will close the pattern's ibox
2163                 try!(self.print_block_unclosed_indent(&**blk, indent_unit));
2164
2165                 // If it is a user-provided unsafe block, print a comma after it
2166                 if let ast::UnsafeBlock(ast::UserProvided) = blk.rules {
2167                     try!(word(&mut self.s, ","));
2168                 }
2169             }
2170             _ => {
2171                 try!(self.end()); // close the ibox for the pattern
2172                 try!(self.print_expr(&*arm.body));
2173                 try!(word(&mut self.s, ","));
2174             }
2175         }
2176         self.end() // close enclosing cbox
2177     }
2178
2179     // Returns whether it printed anything
2180     fn print_explicit_self(&mut self,
2181                            explicit_self: &ast::ExplicitSelf_,
2182                            mutbl: ast::Mutability) -> IoResult<bool> {
2183         try!(self.print_mutability(mutbl));
2184         match *explicit_self {
2185             ast::SelfStatic => { return Ok(false); }
2186             ast::SelfValue(_) => {
2187                 try!(word(&mut self.s, "self"));
2188             }
2189             ast::SelfRegion(ref lt, m, _) => {
2190                 try!(word(&mut self.s, "&"));
2191                 try!(self.print_opt_lifetime(lt));
2192                 try!(self.print_mutability(m));
2193                 try!(word(&mut self.s, "self"));
2194             }
2195             ast::SelfExplicit(ref typ, _) => {
2196                 try!(word(&mut self.s, "self"));
2197                 try!(self.word_space(":"));
2198                 try!(self.print_type(&**typ));
2199             }
2200         }
2201         return Ok(true);
2202     }
2203
2204     pub fn print_fn(&mut self,
2205                     decl: &ast::FnDecl,
2206                     unsafety: Option<ast::Unsafety>,
2207                     abi: abi::Abi,
2208                     name: ast::Ident,
2209                     generics: &ast::Generics,
2210                     opt_explicit_self: Option<&ast::ExplicitSelf_>,
2211                     vis: ast::Visibility) -> IoResult<()> {
2212         try!(self.head(""));
2213         try!(self.print_fn_header_info(opt_explicit_self, unsafety, abi, vis));
2214         try!(self.nbsp());
2215         try!(self.print_ident(name));
2216         try!(self.print_generics(generics));
2217         try!(self.print_fn_args_and_ret(decl, opt_explicit_self));
2218         self.print_where_clause(generics)
2219     }
2220
2221     pub fn print_fn_args(&mut self, decl: &ast::FnDecl,
2222                          opt_explicit_self: Option<&ast::ExplicitSelf_>)
2223         -> IoResult<()> {
2224         // It is unfortunate to duplicate the commasep logic, but we want the
2225         // self type and the args all in the same box.
2226         try!(self.rbox(0u, Inconsistent));
2227         let mut first = true;
2228         for &explicit_self in opt_explicit_self.iter() {
2229             let m = match explicit_self {
2230                 &ast::SelfStatic => ast::MutImmutable,
2231                 _ => match decl.inputs[0].pat.node {
2232                     ast::PatIdent(ast::BindByValue(m), _, _) => m,
2233                     _ => ast::MutImmutable
2234                 }
2235             };
2236             first = !try!(self.print_explicit_self(explicit_self, m));
2237         }
2238
2239         // HACK(eddyb) ignore the separately printed self argument.
2240         let args = if first {
2241             decl.inputs[]
2242         } else {
2243             decl.inputs.slice_from(1)
2244         };
2245
2246         for arg in args.iter() {
2247             if first { first = false; } else { try!(self.word_space(",")); }
2248             try!(self.print_arg(arg));
2249         }
2250
2251         self.end()
2252     }
2253
2254     pub fn print_fn_args_and_ret(&mut self, decl: &ast::FnDecl,
2255                                  opt_explicit_self: Option<&ast::ExplicitSelf_>)
2256         -> IoResult<()> {
2257         try!(self.popen());
2258         try!(self.print_fn_args(decl, opt_explicit_self));
2259         if decl.variadic {
2260             try!(word(&mut self.s, ", ..."));
2261         }
2262         try!(self.pclose());
2263
2264         self.print_fn_output(decl)
2265     }
2266
2267     pub fn print_fn_block_args(
2268             &mut self,
2269             decl: &ast::FnDecl,
2270             unboxed_closure_kind: Option<UnboxedClosureKind>)
2271             -> IoResult<()> {
2272         try!(word(&mut self.s, "|"));
2273         match unboxed_closure_kind {
2274             None => {}
2275             Some(FnUnboxedClosureKind) => try!(self.word_space("&:")),
2276             Some(FnMutUnboxedClosureKind) => try!(self.word_space("&mut:")),
2277             Some(FnOnceUnboxedClosureKind) => try!(self.word_space(":")),
2278         }
2279         try!(self.print_fn_args(decl, None));
2280         try!(word(&mut self.s, "|"));
2281
2282         if let ast::Return(ref ty) = decl.output {
2283             if ty.node == ast::TyInfer {
2284                 return self.maybe_print_comment(ty.span.lo);
2285             }
2286         }
2287
2288         try!(self.space_if_not_bol());
2289         try!(self.word_space("->"));
2290         match decl.output {
2291             ast::Return(ref ty) => {
2292                 try!(self.print_type(&**ty));
2293                 self.maybe_print_comment(ty.span.lo)
2294             }
2295             ast::NoReturn(span) => {
2296                 try!(self.word_nbsp("!"));
2297                 self.maybe_print_comment(span.lo)
2298             }
2299         }
2300     }
2301
2302     pub fn print_capture_clause(&mut self, capture_clause: ast::CaptureClause)
2303                                 -> IoResult<()> {
2304         match capture_clause {
2305             ast::CaptureByValue => self.word_space("move"),
2306             ast::CaptureByRef => Ok(()),
2307         }
2308     }
2309
2310     pub fn print_proc_args(&mut self, decl: &ast::FnDecl) -> IoResult<()> {
2311         try!(word(&mut self.s, "proc"));
2312         try!(word(&mut self.s, "("));
2313         try!(self.print_fn_args(decl, None));
2314         try!(word(&mut self.s, ")"));
2315
2316         if let ast::Return(ref ty) = decl.output {
2317             if ty.node == ast::TyInfer {
2318                 return self.maybe_print_comment(ty.span.lo);
2319             }
2320         }
2321
2322         try!(self.space_if_not_bol());
2323         try!(self.word_space("->"));
2324         match decl.output {
2325             ast::Return(ref ty) => {
2326                 try!(self.print_type(&**ty));
2327                 self.maybe_print_comment(ty.span.lo)
2328             }
2329             ast::NoReturn(span) => {
2330                 try!(self.word_nbsp("!"));
2331                 self.maybe_print_comment(span.lo)
2332             }
2333         }
2334     }
2335
2336     pub fn print_bounds(&mut self,
2337                         prefix: &str,
2338                         bounds: &[ast::TyParamBound])
2339                         -> IoResult<()> {
2340         if !bounds.is_empty() {
2341             try!(word(&mut self.s, prefix));
2342             let mut first = true;
2343             for bound in bounds.iter() {
2344                 try!(self.nbsp());
2345                 if first {
2346                     first = false;
2347                 } else {
2348                     try!(self.word_space("+"));
2349                 }
2350
2351                 try!(match *bound {
2352                     TraitTyParamBound(ref tref, TraitBoundModifier::None) => {
2353                         self.print_poly_trait_ref(tref)
2354                     }
2355                     TraitTyParamBound(ref tref, TraitBoundModifier::Maybe) => {
2356                         try!(word(&mut self.s, "?"));
2357                         self.print_poly_trait_ref(tref)
2358                     }
2359                     RegionTyParamBound(ref lt) => {
2360                         self.print_lifetime(lt)
2361                     }
2362                 })
2363             }
2364             Ok(())
2365         } else {
2366             Ok(())
2367         }
2368     }
2369
2370     pub fn print_lifetime(&mut self,
2371                           lifetime: &ast::Lifetime)
2372                           -> IoResult<()>
2373     {
2374         self.print_name(lifetime.name)
2375     }
2376
2377     pub fn print_lifetime_def(&mut self,
2378                               lifetime: &ast::LifetimeDef)
2379                               -> IoResult<()>
2380     {
2381         try!(self.print_lifetime(&lifetime.lifetime));
2382         let mut sep = ":";
2383         for v in lifetime.bounds.iter() {
2384             try!(word(&mut self.s, sep));
2385             try!(self.print_lifetime(v));
2386             sep = "+";
2387         }
2388         Ok(())
2389     }
2390
2391     pub fn print_generics(&mut self,
2392                           generics: &ast::Generics)
2393                           -> IoResult<()>
2394     {
2395         let total = generics.lifetimes.len() + generics.ty_params.len();
2396         if total == 0 {
2397             return Ok(());
2398         }
2399
2400         try!(word(&mut self.s, "<"));
2401
2402         let mut ints = Vec::new();
2403         for i in range(0u, total) {
2404             ints.push(i);
2405         }
2406
2407         try!(self.commasep(Inconsistent, ints[], |s, &idx| {
2408             if idx < generics.lifetimes.len() {
2409                 let lifetime = &generics.lifetimes[idx];
2410                 s.print_lifetime_def(lifetime)
2411             } else {
2412                 let idx = idx - generics.lifetimes.len();
2413                 let param = &generics.ty_params[idx];
2414                 s.print_ty_param(param)
2415             }
2416         }));
2417
2418         try!(word(&mut self.s, ">"));
2419         Ok(())
2420     }
2421
2422     pub fn print_ty_param(&mut self, param: &ast::TyParam) -> IoResult<()> {
2423         try!(self.print_ident(param.ident));
2424         try!(self.print_bounds(":", param.bounds[]));
2425         match param.default {
2426             Some(ref default) => {
2427                 try!(space(&mut self.s));
2428                 try!(self.word_space("="));
2429                 self.print_type(&**default)
2430             }
2431             _ => Ok(())
2432         }
2433     }
2434
2435     pub fn print_where_clause(&mut self, generics: &ast::Generics)
2436                               -> IoResult<()> {
2437         if generics.where_clause.predicates.len() == 0 {
2438             return Ok(())
2439         }
2440
2441         try!(space(&mut self.s));
2442         try!(self.word_space("where"));
2443
2444         for (i, predicate) in generics.where_clause
2445                                       .predicates
2446                                       .iter()
2447                                       .enumerate() {
2448             if i != 0 {
2449                 try!(self.word_space(","));
2450             }
2451
2452             match predicate {
2453                 &ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate{ref bounded_ty,
2454                                                                               ref bounds,
2455                                                                               ..}) => {
2456                     try!(self.print_type(&**bounded_ty));
2457                     try!(self.print_bounds(":", bounds.as_slice()));
2458                 }
2459                 &ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate{ref lifetime,
2460                                                                                 ref bounds,
2461                                                                                 ..}) => {
2462                     try!(self.print_lifetime(lifetime));
2463                     try!(word(&mut self.s, ":"));
2464
2465                     for (i, bound) in bounds.iter().enumerate() {
2466                         try!(self.print_lifetime(bound));
2467
2468                         if i != 0 {
2469                             try!(word(&mut self.s, ":"));
2470                         }
2471                     }
2472                 }
2473                 &ast::WherePredicate::EqPredicate(ast::WhereEqPredicate{ref path, ref ty, ..}) => {
2474                     try!(self.print_path(path, false));
2475                     try!(space(&mut self.s));
2476                     try!(self.word_space("="));
2477                     try!(self.print_type(&**ty));
2478                 }
2479             }
2480         }
2481
2482         Ok(())
2483     }
2484
2485     pub fn print_meta_item(&mut self, item: &ast::MetaItem) -> IoResult<()> {
2486         try!(self.ibox(indent_unit));
2487         match item.node {
2488             ast::MetaWord(ref name) => {
2489                 try!(word(&mut self.s, name.get()));
2490             }
2491             ast::MetaNameValue(ref name, ref value) => {
2492                 try!(self.word_space(name.get()));
2493                 try!(self.word_space("="));
2494                 try!(self.print_literal(value));
2495             }
2496             ast::MetaList(ref name, ref items) => {
2497                 try!(word(&mut self.s, name.get()));
2498                 try!(self.popen());
2499                 try!(self.commasep(Consistent,
2500                                    items[],
2501                                    |s, i| s.print_meta_item(&**i)));
2502                 try!(self.pclose());
2503             }
2504         }
2505         self.end()
2506     }
2507
2508     pub fn print_view_path(&mut self, vp: &ast::ViewPath) -> IoResult<()> {
2509         match vp.node {
2510             ast::ViewPathSimple(ident, ref path, _) => {
2511                 try!(self.print_path(path, false));
2512
2513                 // FIXME(#6993) can't compare identifiers directly here
2514                 if path.segments.last().unwrap().identifier.name !=
2515                         ident.name {
2516                     try!(space(&mut self.s));
2517                     try!(self.word_space("as"));
2518                     try!(self.print_ident(ident));
2519                 }
2520
2521                 Ok(())
2522             }
2523
2524             ast::ViewPathGlob(ref path, _) => {
2525                 try!(self.print_path(path, false));
2526                 word(&mut self.s, "::*")
2527             }
2528
2529             ast::ViewPathList(ref path, ref idents, _) => {
2530                 if path.segments.is_empty() {
2531                     try!(word(&mut self.s, "{"));
2532                 } else {
2533                     try!(self.print_path(path, false));
2534                     try!(word(&mut self.s, "::{"));
2535                 }
2536                 try!(self.commasep(Inconsistent, idents[], |s, w| {
2537                     match w.node {
2538                         ast::PathListIdent { name, .. } => {
2539                             s.print_ident(name)
2540                         },
2541                         ast::PathListMod { .. } => {
2542                             word(&mut s.s, "self")
2543                         }
2544                     }
2545                 }));
2546                 word(&mut self.s, "}")
2547             }
2548         }
2549     }
2550
2551     pub fn print_view_item(&mut self, item: &ast::ViewItem) -> IoResult<()> {
2552         try!(self.hardbreak_if_not_bol());
2553         try!(self.maybe_print_comment(item.span.lo));
2554         try!(self.print_outer_attributes(item.attrs[]));
2555         try!(self.print_visibility(item.vis));
2556         match item.node {
2557             ast::ViewItemExternCrate(id, ref optional_path, _) => {
2558                 try!(self.head("extern crate"));
2559                 for &(ref p, style) in optional_path.iter() {
2560                     try!(self.print_string(p.get(), style));
2561                     try!(space(&mut self.s));
2562                     try!(word(&mut self.s, "as"));
2563                     try!(space(&mut self.s));
2564                 }
2565                 try!(self.print_ident(id));
2566             }
2567
2568             ast::ViewItemUse(ref vp) => {
2569                 try!(self.head("use"));
2570                 try!(self.print_view_path(&**vp));
2571             }
2572         }
2573         try!(word(&mut self.s, ";"));
2574         try!(self.end()); // end inner head-block
2575         self.end() // end outer head-block
2576     }
2577
2578     pub fn print_mutability(&mut self,
2579                             mutbl: ast::Mutability) -> IoResult<()> {
2580         match mutbl {
2581             ast::MutMutable => self.word_nbsp("mut"),
2582             ast::MutImmutable => Ok(()),
2583         }
2584     }
2585
2586     pub fn print_mt(&mut self, mt: &ast::MutTy) -> IoResult<()> {
2587         try!(self.print_mutability(mt.mutbl));
2588         self.print_type(&*mt.ty)
2589     }
2590
2591     pub fn print_arg(&mut self, input: &ast::Arg) -> IoResult<()> {
2592         try!(self.ibox(indent_unit));
2593         match input.ty.node {
2594             ast::TyInfer => try!(self.print_pat(&*input.pat)),
2595             _ => {
2596                 match input.pat.node {
2597                     ast::PatIdent(_, ref path1, _) if
2598                         path1.node.name ==
2599                             parse::token::special_idents::invalid.name => {
2600                         // Do nothing.
2601                     }
2602                     _ => {
2603                         try!(self.print_pat(&*input.pat));
2604                         try!(word(&mut self.s, ":"));
2605                         try!(space(&mut self.s));
2606                     }
2607                 }
2608                 try!(self.print_type(&*input.ty));
2609             }
2610         }
2611         self.end()
2612     }
2613
2614     pub fn print_fn_output(&mut self, decl: &ast::FnDecl) -> IoResult<()> {
2615         if let ast::Return(ref ty) = decl.output {
2616             match ty.node {
2617                 ast::TyTup(ref tys) if tys.is_empty() => {
2618                     return self.maybe_print_comment(ty.span.lo);
2619                 }
2620                 _ => ()
2621             }
2622         }
2623
2624         try!(self.space_if_not_bol());
2625         try!(self.ibox(indent_unit));
2626         try!(self.word_space("->"));
2627         match decl.output {
2628             ast::NoReturn(_) =>
2629                 try!(self.word_nbsp("!")),
2630             ast::Return(ref ty) =>
2631                 try!(self.print_type(&**ty))
2632         }
2633         try!(self.end());
2634
2635         match decl.output {
2636             ast::Return(ref output) => self.maybe_print_comment(output.span.lo),
2637             _ => Ok(())
2638         }
2639     }
2640
2641     pub fn print_ty_fn(&mut self,
2642                        opt_abi: Option<abi::Abi>,
2643                        opt_sigil: Option<char>,
2644                        unsafety: ast::Unsafety,
2645                        onceness: ast::Onceness,
2646                        decl: &ast::FnDecl,
2647                        id: Option<ast::Ident>,
2648                        bounds: &OwnedSlice<ast::TyParamBound>,
2649                        generics: Option<&ast::Generics>,
2650                        opt_explicit_self: Option<&ast::ExplicitSelf_>)
2651                        -> IoResult<()> {
2652         try!(self.ibox(indent_unit));
2653
2654         // Duplicates the logic in `print_fn_header_info()`.  This is because that
2655         // function prints the sigil in the wrong place.  That should be fixed.
2656         if opt_sigil == Some('~') && onceness == ast::Once {
2657             try!(word(&mut self.s, "proc"));
2658         } else if opt_sigil == Some('&') {
2659             try!(self.print_unsafety(unsafety));
2660             try!(self.print_extern_opt_abi(opt_abi));
2661         } else {
2662             assert!(opt_sigil.is_none());
2663             try!(self.print_unsafety(unsafety));
2664             try!(self.print_opt_abi_and_extern_if_nondefault(opt_abi));
2665             try!(word(&mut self.s, "fn"));
2666         }
2667
2668         match id {
2669             Some(id) => {
2670                 try!(word(&mut self.s, " "));
2671                 try!(self.print_ident(id));
2672             }
2673             _ => ()
2674         }
2675
2676         match generics { Some(g) => try!(self.print_generics(g)), _ => () }
2677         try!(zerobreak(&mut self.s));
2678
2679         if opt_sigil == Some('&') {
2680             try!(word(&mut self.s, "|"));
2681         } else {
2682             try!(self.popen());
2683         }
2684
2685         try!(self.print_fn_args(decl, opt_explicit_self));
2686
2687         if opt_sigil == Some('&') {
2688             try!(word(&mut self.s, "|"));
2689         } else {
2690             if decl.variadic {
2691                 try!(word(&mut self.s, ", ..."));
2692             }
2693             try!(self.pclose());
2694         }
2695
2696         try!(self.print_bounds(":", bounds[]));
2697
2698         try!(self.print_fn_output(decl));
2699
2700         match generics {
2701             Some(generics) => try!(self.print_where_clause(generics)),
2702             None => {}
2703         }
2704
2705         self.end()
2706     }
2707
2708     pub fn maybe_print_trailing_comment(&mut self, span: codemap::Span,
2709                                         next_pos: Option<BytePos>)
2710         -> IoResult<()> {
2711         let cm = match self.cm {
2712             Some(cm) => cm,
2713             _ => return Ok(())
2714         };
2715         match self.next_comment() {
2716             Some(ref cmnt) => {
2717                 if (*cmnt).style != comments::Trailing { return Ok(()) }
2718                 let span_line = cm.lookup_char_pos(span.hi);
2719                 let comment_line = cm.lookup_char_pos((*cmnt).pos);
2720                 let mut next = (*cmnt).pos + BytePos(1);
2721                 match next_pos { None => (), Some(p) => next = p }
2722                 if span.hi < (*cmnt).pos && (*cmnt).pos < next &&
2723                     span_line.line == comment_line.line {
2724                         try!(self.print_comment(cmnt));
2725                         self.cur_cmnt_and_lit.cur_cmnt += 1u;
2726                     }
2727             }
2728             _ => ()
2729         }
2730         Ok(())
2731     }
2732
2733     pub fn print_remaining_comments(&mut self) -> IoResult<()> {
2734         // If there aren't any remaining comments, then we need to manually
2735         // make sure there is a line break at the end.
2736         if self.next_comment().is_none() {
2737             try!(hardbreak(&mut self.s));
2738         }
2739         loop {
2740             match self.next_comment() {
2741                 Some(ref cmnt) => {
2742                     try!(self.print_comment(cmnt));
2743                     self.cur_cmnt_and_lit.cur_cmnt += 1u;
2744                 }
2745                 _ => break
2746             }
2747         }
2748         Ok(())
2749     }
2750
2751     pub fn print_literal(&mut self, lit: &ast::Lit) -> IoResult<()> {
2752         try!(self.maybe_print_comment(lit.span.lo));
2753         match self.next_lit(lit.span.lo) {
2754             Some(ref ltrl) => {
2755                 return word(&mut self.s, (*ltrl).lit[]);
2756             }
2757             _ => ()
2758         }
2759         match lit.node {
2760             ast::LitStr(ref st, style) => self.print_string(st.get(), style),
2761             ast::LitByte(byte) => {
2762                 let mut res = String::from_str("b'");
2763                 ascii::escape_default(byte, |c| res.push(c as char));
2764                 res.push('\'');
2765                 word(&mut self.s, res[])
2766             }
2767             ast::LitChar(ch) => {
2768                 let mut res = String::from_str("'");
2769                 for c in ch.escape_default() {
2770                     res.push(c);
2771                 }
2772                 res.push('\'');
2773                 word(&mut self.s, res[])
2774             }
2775             ast::LitInt(i, t) => {
2776                 match t {
2777                     ast::SignedIntLit(st, ast::Plus) => {
2778                         word(&mut self.s,
2779                              ast_util::int_ty_to_string(st, Some(i as i64))[])
2780                     }
2781                     ast::SignedIntLit(st, ast::Minus) => {
2782                         let istr = ast_util::int_ty_to_string(st, Some(-(i as i64)));
2783                         word(&mut self.s,
2784                              format!("-{}", istr)[])
2785                     }
2786                     ast::UnsignedIntLit(ut) => {
2787                         word(&mut self.s, ast_util::uint_ty_to_string(ut, Some(i))[])
2788                     }
2789                     ast::UnsuffixedIntLit(ast::Plus) => {
2790                         word(&mut self.s, format!("{}", i)[])
2791                     }
2792                     ast::UnsuffixedIntLit(ast::Minus) => {
2793                         word(&mut self.s, format!("-{}", i)[])
2794                     }
2795                 }
2796             }
2797             ast::LitFloat(ref f, t) => {
2798                 word(&mut self.s,
2799                      format!(
2800                          "{}{}",
2801                          f.get(),
2802                          ast_util::float_ty_to_string(t)[])[])
2803             }
2804             ast::LitFloatUnsuffixed(ref f) => word(&mut self.s, f.get()),
2805             ast::LitBool(val) => {
2806                 if val { word(&mut self.s, "true") } else { word(&mut self.s, "false") }
2807             }
2808             ast::LitBinary(ref v) => {
2809                 let mut escaped: String = String::new();
2810                 for &ch in v.iter() {
2811                     ascii::escape_default(ch as u8,
2812                                           |ch| escaped.push(ch as char));
2813                 }
2814                 word(&mut self.s, format!("b\"{}\"", escaped)[])
2815             }
2816         }
2817     }
2818
2819     pub fn next_lit(&mut self, pos: BytePos) -> Option<comments::Literal> {
2820         match self.literals {
2821             Some(ref lits) => {
2822                 while self.cur_cmnt_and_lit.cur_lit < lits.len() {
2823                     let ltrl = (*lits)[self.cur_cmnt_and_lit.cur_lit].clone();
2824                     if ltrl.pos > pos { return None; }
2825                     self.cur_cmnt_and_lit.cur_lit += 1u;
2826                     if ltrl.pos == pos { return Some(ltrl); }
2827                 }
2828                 None
2829             }
2830             _ => None
2831         }
2832     }
2833
2834     pub fn maybe_print_comment(&mut self, pos: BytePos) -> IoResult<()> {
2835         loop {
2836             match self.next_comment() {
2837                 Some(ref cmnt) => {
2838                     if (*cmnt).pos < pos {
2839                         try!(self.print_comment(cmnt));
2840                         self.cur_cmnt_and_lit.cur_cmnt += 1u;
2841                     } else { break; }
2842                 }
2843                 _ => break
2844             }
2845         }
2846         Ok(())
2847     }
2848
2849     pub fn print_comment(&mut self,
2850                          cmnt: &comments::Comment) -> IoResult<()> {
2851         match cmnt.style {
2852             comments::Mixed => {
2853                 assert_eq!(cmnt.lines.len(), 1u);
2854                 try!(zerobreak(&mut self.s));
2855                 try!(word(&mut self.s, cmnt.lines[0][]));
2856                 zerobreak(&mut self.s)
2857             }
2858             comments::Isolated => {
2859                 try!(self.hardbreak_if_not_bol());
2860                 for line in cmnt.lines.iter() {
2861                     // Don't print empty lines because they will end up as trailing
2862                     // whitespace
2863                     if !line.is_empty() {
2864                         try!(word(&mut self.s, line[]));
2865                     }
2866                     try!(hardbreak(&mut self.s));
2867                 }
2868                 Ok(())
2869             }
2870             comments::Trailing => {
2871                 try!(word(&mut self.s, " "));
2872                 if cmnt.lines.len() == 1u {
2873                     try!(word(&mut self.s, cmnt.lines[0][]));
2874                     hardbreak(&mut self.s)
2875                 } else {
2876                     try!(self.ibox(0u));
2877                     for line in cmnt.lines.iter() {
2878                         if !line.is_empty() {
2879                             try!(word(&mut self.s, line[]));
2880                         }
2881                         try!(hardbreak(&mut self.s));
2882                     }
2883                     self.end()
2884                 }
2885             }
2886             comments::BlankLine => {
2887                 // We need to do at least one, possibly two hardbreaks.
2888                 let is_semi = match self.s.last_token() {
2889                     pp::String(s, _) => ";" == s,
2890                     _ => false
2891                 };
2892                 if is_semi || self.is_begin() || self.is_end() {
2893                     try!(hardbreak(&mut self.s));
2894                 }
2895                 hardbreak(&mut self.s)
2896             }
2897         }
2898     }
2899
2900     pub fn print_string(&mut self, st: &str,
2901                         style: ast::StrStyle) -> IoResult<()> {
2902         let st = match style {
2903             ast::CookedStr => {
2904                 (format!("\"{}\"", st.escape_default()))
2905             }
2906             ast::RawStr(n) => {
2907                 (format!("r{delim}\"{string}\"{delim}",
2908                          delim=repeat("#", n),
2909                          string=st))
2910             }
2911         };
2912         word(&mut self.s, st[])
2913     }
2914
2915     pub fn next_comment(&mut self) -> Option<comments::Comment> {
2916         match self.comments {
2917             Some(ref cmnts) => {
2918                 if self.cur_cmnt_and_lit.cur_cmnt < cmnts.len() {
2919                     Some(cmnts[self.cur_cmnt_and_lit.cur_cmnt].clone())
2920                 } else {
2921                     None
2922                 }
2923             }
2924             _ => None
2925         }
2926     }
2927
2928     pub fn print_opt_unsafety(&mut self,
2929                             opt_unsafety: Option<ast::Unsafety>) -> IoResult<()> {
2930         match opt_unsafety {
2931             Some(unsafety) => self.print_unsafety(unsafety),
2932             None => Ok(())
2933         }
2934     }
2935
2936     pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
2937                                                   opt_abi: Option<abi::Abi>)
2938         -> IoResult<()> {
2939         match opt_abi {
2940             Some(abi::Rust) => Ok(()),
2941             Some(abi) => {
2942                 try!(self.word_nbsp("extern"));
2943                 self.word_nbsp(abi.to_string()[])
2944             }
2945             None => Ok(())
2946         }
2947     }
2948
2949     pub fn print_extern_opt_abi(&mut self,
2950                                 opt_abi: Option<abi::Abi>) -> IoResult<()> {
2951         match opt_abi {
2952             Some(abi) => {
2953                 try!(self.word_nbsp("extern"));
2954                 self.word_nbsp(abi.to_string()[])
2955             }
2956             None => Ok(())
2957         }
2958     }
2959
2960     pub fn print_fn_header_info(&mut self,
2961                                 _opt_explicit_self: Option<&ast::ExplicitSelf_>,
2962                                 opt_unsafety: Option<ast::Unsafety>,
2963                                 abi: abi::Abi,
2964                                 vis: ast::Visibility) -> IoResult<()> {
2965         try!(word(&mut self.s, visibility_qualified(vis, "").as_slice()));
2966         try!(self.print_opt_unsafety(opt_unsafety));
2967
2968         if abi != abi::Rust {
2969             try!(self.word_nbsp("extern"));
2970             try!(self.word_nbsp(abi.to_string()[]));
2971         }
2972
2973         word(&mut self.s, "fn")
2974     }
2975
2976     pub fn print_unsafety(&mut self, s: ast::Unsafety) -> IoResult<()> {
2977         match s {
2978             ast::Unsafety::Normal => Ok(()),
2979             ast::Unsafety::Unsafe => self.word_nbsp("unsafe"),
2980         }
2981     }
2982 }
2983
2984 fn repeat(s: &str, n: uint) -> String { iter::repeat(s).take(n).collect() }
2985
2986 #[cfg(test)]
2987 mod test {
2988     use super::*;
2989
2990     use ast;
2991     use ast_util;
2992     use codemap;
2993     use parse::token;
2994     use ptr::P;
2995
2996     #[test]
2997     fn test_fun_to_string() {
2998         let abba_ident = token::str_to_ident("abba");
2999
3000         let decl = ast::FnDecl {
3001             inputs: Vec::new(),
3002             output: ast::Return(P(ast::Ty {id: 0,
3003                                node: ast::TyTup(vec![]),
3004                                span: codemap::DUMMY_SP})),
3005             variadic: false
3006         };
3007         let generics = ast_util::empty_generics();
3008         assert_eq!(fun_to_string(&decl, ast::Unsafety::Normal, abba_ident,
3009                                None, &generics),
3010                    "fn abba()");
3011     }
3012
3013     #[test]
3014     fn test_variant_to_string() {
3015         let ident = token::str_to_ident("principal_skinner");
3016
3017         let var = codemap::respan(codemap::DUMMY_SP, ast::Variant_ {
3018             name: ident,
3019             attrs: Vec::new(),
3020             // making this up as I go.... ?
3021             kind: ast::TupleVariantKind(Vec::new()),
3022             id: 0,
3023             disr_expr: None,
3024             vis: ast::Public,
3025         });
3026
3027         let varstr = variant_to_string(&var);
3028         assert_eq!(varstr, "pub principal_skinner");
3029     }
3030
3031     #[test]
3032     fn test_signed_int_to_string() {
3033         let pos_int = ast::LitInt(42, ast::SignedIntLit(ast::TyI32, ast::Plus));
3034         let neg_int = ast::LitInt((-42) as u64, ast::SignedIntLit(ast::TyI32, ast::Minus));
3035         assert_eq!(format!("-{}", lit_to_string(&codemap::dummy_spanned(pos_int))),
3036                    lit_to_string(&codemap::dummy_spanned(neg_int)));
3037     }
3038 }