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