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