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