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