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