]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/print/pprust.rs
rollup merge of #20554: huonw/mut-pattern
[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         if ast_util::struct_def_is_tuple_like(struct_def) {
1060             if !struct_def.fields.is_empty() {
1061                 try!(self.popen());
1062                 try!(self.commasep(
1063                     Inconsistent, struct_def.fields[],
1064                     |s, field| {
1065                         match field.node.kind {
1066                             ast::NamedField(..) => panic!("unexpected named field"),
1067                             ast::UnnamedField(vis) => {
1068                                 try!(s.print_visibility(vis));
1069                                 try!(s.maybe_print_comment(field.span.lo));
1070                                 s.print_type(&*field.node.ty)
1071                             }
1072                         }
1073                     }
1074                 ));
1075                 try!(self.pclose());
1076             }
1077             try!(self.print_where_clause(generics));
1078             try!(word(&mut self.s, ";"));
1079             try!(self.end());
1080             self.end() // close the outer-box
1081         } else {
1082             try!(self.print_where_clause(generics));
1083             try!(self.nbsp());
1084             try!(self.bopen());
1085             try!(self.hardbreak_if_not_bol());
1086
1087             for field in struct_def.fields.iter() {
1088                 match field.node.kind {
1089                     ast::UnnamedField(..) => panic!("unexpected unnamed field"),
1090                     ast::NamedField(ident, visibility) => {
1091                         try!(self.hardbreak_if_not_bol());
1092                         try!(self.maybe_print_comment(field.span.lo));
1093                         try!(self.print_outer_attributes(field.node.attrs[]));
1094                         try!(self.print_visibility(visibility));
1095                         try!(self.print_ident(ident));
1096                         try!(self.word_nbsp(":"));
1097                         try!(self.print_type(&*field.node.ty));
1098                         try!(word(&mut self.s, ","));
1099                     }
1100                 }
1101             }
1102
1103             self.bclose(span)
1104         }
1105     }
1106
1107     /// This doesn't deserve to be called "pretty" printing, but it should be
1108     /// meaning-preserving. A quick hack that might help would be to look at the
1109     /// spans embedded in the TTs to decide where to put spaces and newlines.
1110     /// But it'd be better to parse these according to the grammar of the
1111     /// appropriate macro, transcribe back into the grammar we just parsed from,
1112     /// and then pretty-print the resulting AST nodes (so, e.g., we print
1113     /// expression arguments as expressions). It can be done! I think.
1114     pub fn print_tt(&mut self, tt: &ast::TokenTree) -> IoResult<()> {
1115         match *tt {
1116             ast::TtToken(_, ref tk) => {
1117                 try!(word(&mut self.s, token_to_string(tk)[]));
1118                 match *tk {
1119                     parse::token::DocComment(..) => {
1120                         hardbreak(&mut self.s)
1121                     }
1122                     _ => Ok(())
1123                 }
1124             }
1125             ast::TtDelimited(_, ref delimed) => {
1126                 try!(word(&mut self.s, token_to_string(&delimed.open_token())[]));
1127                 try!(space(&mut self.s));
1128                 try!(self.print_tts(delimed.tts[]));
1129                 try!(space(&mut self.s));
1130                 word(&mut self.s, token_to_string(&delimed.close_token())[])
1131             },
1132             ast::TtSequence(_, ref seq) => {
1133                 try!(word(&mut self.s, "$("));
1134                 for tt_elt in seq.tts.iter() {
1135                     try!(self.print_tt(tt_elt));
1136                 }
1137                 try!(word(&mut self.s, ")"));
1138                 match seq.separator {
1139                     Some(ref tk) => {
1140                         try!(word(&mut self.s, token_to_string(tk)[]));
1141                     }
1142                     None => {},
1143                 }
1144                 match seq.op {
1145                     ast::ZeroOrMore => word(&mut self.s, "*"),
1146                     ast::OneOrMore => word(&mut self.s, "+"),
1147                 }
1148             }
1149         }
1150     }
1151
1152     pub fn print_tts(&mut self, tts: &[ast::TokenTree]) -> IoResult<()> {
1153         try!(self.ibox(0));
1154         for (i, tt) in tts.iter().enumerate() {
1155             if i != 0 {
1156                 try!(space(&mut self.s));
1157             }
1158             try!(self.print_tt(tt));
1159         }
1160         self.end()
1161     }
1162
1163     pub fn print_variant(&mut self, v: &ast::Variant) -> IoResult<()> {
1164         try!(self.print_visibility(v.node.vis));
1165         match v.node.kind {
1166             ast::TupleVariantKind(ref args) => {
1167                 try!(self.print_ident(v.node.name));
1168                 if !args.is_empty() {
1169                     try!(self.popen());
1170                     try!(self.commasep(Consistent,
1171                                        args[],
1172                                        |s, arg| s.print_type(&*arg.ty)));
1173                     try!(self.pclose());
1174                 }
1175             }
1176             ast::StructVariantKind(ref struct_def) => {
1177                 try!(self.head(""));
1178                 let generics = ast_util::empty_generics();
1179                 try!(self.print_struct(&**struct_def, &generics, v.node.name, v.span));
1180             }
1181         }
1182         match v.node.disr_expr {
1183             Some(ref d) => {
1184                 try!(space(&mut self.s));
1185                 try!(self.word_space("="));
1186                 self.print_expr(&**d)
1187             }
1188             _ => Ok(())
1189         }
1190     }
1191
1192     pub fn print_ty_method(&mut self, m: &ast::TypeMethod) -> IoResult<()> {
1193         try!(self.hardbreak_if_not_bol());
1194         try!(self.maybe_print_comment(m.span.lo));
1195         try!(self.print_outer_attributes(m.attrs[]));
1196         try!(self.print_ty_fn(None,
1197                               None,
1198                               m.unsafety,
1199                               ast::Many,
1200                               &*m.decl,
1201                               Some(m.ident),
1202                               &OwnedSlice::empty(),
1203                               Some(&m.generics),
1204                               Some(&m.explicit_self.node)));
1205         word(&mut self.s, ";")
1206     }
1207
1208     pub fn print_trait_method(&mut self,
1209                               m: &ast::TraitItem) -> IoResult<()> {
1210         match *m {
1211             RequiredMethod(ref ty_m) => self.print_ty_method(ty_m),
1212             ProvidedMethod(ref m) => self.print_method(&**m),
1213             TypeTraitItem(ref t) => self.print_associated_type(&**t),
1214         }
1215     }
1216
1217     pub fn print_impl_item(&mut self, ii: &ast::ImplItem) -> IoResult<()> {
1218         match *ii {
1219             MethodImplItem(ref m) => self.print_method(&**m),
1220             TypeImplItem(ref td) => self.print_typedef(&**td),
1221         }
1222     }
1223
1224     pub fn print_method(&mut self, meth: &ast::Method) -> IoResult<()> {
1225         try!(self.hardbreak_if_not_bol());
1226         try!(self.maybe_print_comment(meth.span.lo));
1227         try!(self.print_outer_attributes(meth.attrs[]));
1228         match meth.node {
1229             ast::MethDecl(ident,
1230                           ref generics,
1231                           abi,
1232                           ref explicit_self,
1233                           unsafety,
1234                           ref decl,
1235                           ref body,
1236                           vis) => {
1237                 try!(self.print_fn(&**decl,
1238                                    Some(unsafety),
1239                                    abi,
1240                                    ident,
1241                                    generics,
1242                                    Some(&explicit_self.node),
1243                                    vis));
1244                 try!(word(&mut self.s, " "));
1245                 self.print_block_with_attrs(&**body, meth.attrs[])
1246             },
1247             ast::MethMac(codemap::Spanned { node: ast::MacInvocTT(ref pth, ref tts, _),
1248                                             ..}) => {
1249                 // code copied from ItemMac:
1250                 try!(self.print_path(pth, false));
1251                 try!(word(&mut self.s, "! "));
1252                 try!(self.cbox(indent_unit));
1253                 try!(self.popen());
1254                 try!(self.print_tts(tts[]));
1255                 try!(self.pclose());
1256                 try!(word(&mut self.s, ";"));
1257                 self.end()
1258             }
1259         }
1260     }
1261
1262     pub fn print_outer_attributes(&mut self,
1263                                   attrs: &[ast::Attribute]) -> IoResult<()> {
1264         let mut count = 0u;
1265         for attr in attrs.iter() {
1266             match attr.node.style {
1267                 ast::AttrOuter => {
1268                     try!(self.print_attribute(attr));
1269                     count += 1;
1270                 }
1271                 _ => {/* fallthrough */ }
1272             }
1273         }
1274         if count > 0 {
1275             try!(self.hardbreak_if_not_bol());
1276         }
1277         Ok(())
1278     }
1279
1280     pub fn print_inner_attributes(&mut self,
1281                                   attrs: &[ast::Attribute]) -> IoResult<()> {
1282         let mut count = 0u;
1283         for attr in attrs.iter() {
1284             match attr.node.style {
1285                 ast::AttrInner => {
1286                     try!(self.print_attribute(attr));
1287                     count += 1;
1288                 }
1289                 _ => {/* fallthrough */ }
1290             }
1291         }
1292         if count > 0 {
1293             try!(self.hardbreak_if_not_bol());
1294         }
1295         Ok(())
1296     }
1297
1298     pub fn print_attribute(&mut self, attr: &ast::Attribute) -> IoResult<()> {
1299         try!(self.hardbreak_if_not_bol());
1300         try!(self.maybe_print_comment(attr.span.lo));
1301         if attr.node.is_sugared_doc {
1302             word(&mut self.s, attr.value_str().unwrap().get())
1303         } else {
1304             match attr.node.style {
1305                 ast::AttrInner => try!(word(&mut self.s, "#![")),
1306                 ast::AttrOuter => try!(word(&mut self.s, "#[")),
1307             }
1308             try!(self.print_meta_item(&*attr.meta()));
1309             word(&mut self.s, "]")
1310         }
1311     }
1312
1313
1314     pub fn print_stmt(&mut self, st: &ast::Stmt) -> IoResult<()> {
1315         try!(self.maybe_print_comment(st.span.lo));
1316         match st.node {
1317             ast::StmtDecl(ref decl, _) => {
1318                 try!(self.print_decl(&**decl));
1319             }
1320             ast::StmtExpr(ref expr, _) => {
1321                 try!(self.space_if_not_bol());
1322                 try!(self.print_expr(&**expr));
1323             }
1324             ast::StmtSemi(ref expr, _) => {
1325                 try!(self.space_if_not_bol());
1326                 try!(self.print_expr(&**expr));
1327                 try!(word(&mut self.s, ";"));
1328             }
1329             ast::StmtMac(ref mac, style) => {
1330                 try!(self.space_if_not_bol());
1331                 let delim = match style {
1332                     ast::MacStmtWithBraces => token::Brace,
1333                     _ => token::Paren
1334                 };
1335                 try!(self.print_mac(&**mac, delim));
1336                 match style {
1337                     ast::MacStmtWithBraces => {}
1338                     _ => try!(word(&mut self.s, ";")),
1339                 }
1340             }
1341         }
1342         if parse::classify::stmt_ends_with_semi(&st.node) {
1343             try!(word(&mut self.s, ";"));
1344         }
1345         self.maybe_print_trailing_comment(st.span, None)
1346     }
1347
1348     pub fn print_block(&mut self, blk: &ast::Block) -> IoResult<()> {
1349         self.print_block_with_attrs(blk, &[])
1350     }
1351
1352     pub fn print_block_unclosed(&mut self, blk: &ast::Block) -> IoResult<()> {
1353         self.print_block_unclosed_indent(blk, indent_unit)
1354     }
1355
1356     pub fn print_block_unclosed_indent(&mut self, blk: &ast::Block,
1357                                        indented: uint) -> IoResult<()> {
1358         self.print_block_maybe_unclosed(blk, indented, &[], false)
1359     }
1360
1361     pub fn print_block_with_attrs(&mut self,
1362                                   blk: &ast::Block,
1363                                   attrs: &[ast::Attribute]) -> IoResult<()> {
1364         self.print_block_maybe_unclosed(blk, indent_unit, attrs, true)
1365     }
1366
1367     pub fn print_block_maybe_unclosed(&mut self,
1368                                       blk: &ast::Block,
1369                                       indented: uint,
1370                                       attrs: &[ast::Attribute],
1371                                       close_box: bool) -> IoResult<()> {
1372         match blk.rules {
1373             ast::UnsafeBlock(..) => try!(self.word_space("unsafe")),
1374             ast::DefaultBlock => ()
1375         }
1376         try!(self.maybe_print_comment(blk.span.lo));
1377         try!(self.ann.pre(self, NodeBlock(blk)));
1378         try!(self.bopen());
1379
1380         try!(self.print_inner_attributes(attrs));
1381
1382         for vi in blk.view_items.iter() {
1383             try!(self.print_view_item(vi));
1384         }
1385         for st in blk.stmts.iter() {
1386             try!(self.print_stmt(&**st));
1387         }
1388         match blk.expr {
1389             Some(ref expr) => {
1390                 try!(self.space_if_not_bol());
1391                 try!(self.print_expr(&**expr));
1392                 try!(self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi)));
1393             }
1394             _ => ()
1395         }
1396         try!(self.bclose_maybe_open(blk.span, indented, close_box));
1397         self.ann.post(self, NodeBlock(blk))
1398     }
1399
1400     fn print_else(&mut self, els: Option<&ast::Expr>) -> IoResult<()> {
1401         match els {
1402             Some(_else) => {
1403                 match _else.node {
1404                     // "another else-if"
1405                     ast::ExprIf(ref i, ref then, ref e) => {
1406                         try!(self.cbox(indent_unit - 1u));
1407                         try!(self.ibox(0u));
1408                         try!(word(&mut self.s, " else if "));
1409                         try!(self.print_expr(&**i));
1410                         try!(space(&mut self.s));
1411                         try!(self.print_block(&**then));
1412                         self.print_else(e.as_ref().map(|e| &**e))
1413                     }
1414                     // "another else-if-let"
1415                     ast::ExprIfLet(ref pat, ref expr, ref then, ref e) => {
1416                         try!(self.cbox(indent_unit - 1u));
1417                         try!(self.ibox(0u));
1418                         try!(word(&mut self.s, " else if let "));
1419                         try!(self.print_pat(&**pat));
1420                         try!(space(&mut self.s));
1421                         try!(self.word_space("="));
1422                         try!(self.print_expr(&**expr));
1423                         try!(space(&mut self.s));
1424                         try!(self.print_block(&**then));
1425                         self.print_else(e.as_ref().map(|e| &**e))
1426                     }
1427                     // "final else"
1428                     ast::ExprBlock(ref b) => {
1429                         try!(self.cbox(indent_unit - 1u));
1430                         try!(self.ibox(0u));
1431                         try!(word(&mut self.s, " else "));
1432                         self.print_block(&**b)
1433                     }
1434                     // BLEAH, constraints would be great here
1435                     _ => {
1436                         panic!("print_if saw if with weird alternative");
1437                     }
1438                 }
1439             }
1440             _ => Ok(())
1441         }
1442     }
1443
1444     pub fn print_if(&mut self, test: &ast::Expr, blk: &ast::Block,
1445                     elseopt: Option<&ast::Expr>) -> IoResult<()> {
1446         try!(self.head("if"));
1447         try!(self.print_expr(test));
1448         try!(space(&mut self.s));
1449         try!(self.print_block(blk));
1450         self.print_else(elseopt)
1451     }
1452
1453     pub fn print_if_let(&mut self, pat: &ast::Pat, expr: &ast::Expr, blk: &ast::Block,
1454                         elseopt: Option<&ast::Expr>) -> IoResult<()> {
1455         try!(self.head("if let"));
1456         try!(self.print_pat(pat));
1457         try!(space(&mut self.s));
1458         try!(self.word_space("="));
1459         try!(self.print_expr(expr));
1460         try!(space(&mut self.s));
1461         try!(self.print_block(blk));
1462         self.print_else(elseopt)
1463     }
1464
1465     pub fn print_mac(&mut self, m: &ast::Mac, delim: token::DelimToken)
1466                      -> IoResult<()> {
1467         match m.node {
1468             // I think it's reasonable to hide the ctxt here:
1469             ast::MacInvocTT(ref pth, ref tts, _) => {
1470                 try!(self.print_path(pth, false));
1471                 try!(word(&mut self.s, "!"));
1472                 match delim {
1473                     token::Paren => try!(self.popen()),
1474                     token::Bracket => try!(word(&mut self.s, "[")),
1475                     token::Brace => try!(self.bopen()),
1476                 }
1477                 try!(self.print_tts(tts.as_slice()));
1478                 match delim {
1479                     token::Paren => self.pclose(),
1480                     token::Bracket => word(&mut self.s, "]"),
1481                     token::Brace => self.bclose(m.span),
1482                 }
1483             }
1484         }
1485     }
1486
1487
1488     fn print_call_post(&mut self, args: &[P<ast::Expr>]) -> IoResult<()> {
1489         try!(self.popen());
1490         try!(self.commasep_exprs(Inconsistent, args));
1491         self.pclose()
1492     }
1493
1494     pub fn print_expr_maybe_paren(&mut self, expr: &ast::Expr) -> IoResult<()> {
1495         let needs_par = needs_parentheses(expr);
1496         if needs_par {
1497             try!(self.popen());
1498         }
1499         try!(self.print_expr(expr));
1500         if needs_par {
1501             try!(self.pclose());
1502         }
1503         Ok(())
1504     }
1505
1506     pub fn print_expr(&mut self, expr: &ast::Expr) -> IoResult<()> {
1507         try!(self.maybe_print_comment(expr.span.lo));
1508         try!(self.ibox(indent_unit));
1509         try!(self.ann.pre(self, NodeExpr(expr)));
1510         match expr.node {
1511             ast::ExprBox(ref p, ref e) => {
1512                 try!(word(&mut self.s, "box"));
1513                 try!(word(&mut self.s, "("));
1514                 try!(p.as_ref().map_or(Ok(()), |e|self.print_expr(&**e)));
1515                 try!(self.word_space(")"));
1516                 try!(self.print_expr(&**e));
1517             }
1518             ast::ExprVec(ref exprs) => {
1519                 try!(self.ibox(indent_unit));
1520                 try!(word(&mut self.s, "["));
1521                 try!(self.commasep_exprs(Inconsistent, exprs[]));
1522                 try!(word(&mut self.s, "]"));
1523                 try!(self.end());
1524             }
1525
1526             ast::ExprRepeat(ref element, ref count) => {
1527                 try!(self.ibox(indent_unit));
1528                 try!(word(&mut self.s, "["));
1529                 try!(self.print_expr(&**element));
1530                 try!(self.word_space(";"));
1531                 try!(self.print_expr(&**count));
1532                 try!(word(&mut self.s, "]"));
1533                 try!(self.end());
1534             }
1535
1536             ast::ExprStruct(ref path, ref fields, ref wth) => {
1537                 try!(self.print_path(path, true));
1538                 try!(word(&mut self.s, "{"));
1539                 try!(self.commasep_cmnt(
1540                     Consistent,
1541                     fields[],
1542                     |s, field| {
1543                         try!(s.ibox(indent_unit));
1544                         try!(s.print_ident(field.ident.node));
1545                         try!(s.word_space(":"));
1546                         try!(s.print_expr(&*field.expr));
1547                         s.end()
1548                     },
1549                     |f| f.span));
1550                 match *wth {
1551                     Some(ref expr) => {
1552                         try!(self.ibox(indent_unit));
1553                         if !fields.is_empty() {
1554                             try!(word(&mut self.s, ","));
1555                             try!(space(&mut self.s));
1556                         }
1557                         try!(word(&mut self.s, ".."));
1558                         try!(self.print_expr(&**expr));
1559                         try!(self.end());
1560                     }
1561                     _ => try!(word(&mut self.s, ","))
1562                 }
1563                 try!(word(&mut self.s, "}"));
1564             }
1565             ast::ExprTup(ref exprs) => {
1566                 try!(self.popen());
1567                 try!(self.commasep_exprs(Inconsistent, exprs[]));
1568                 if exprs.len() == 1 {
1569                     try!(word(&mut self.s, ","));
1570                 }
1571                 try!(self.pclose());
1572             }
1573             ast::ExprCall(ref func, ref args) => {
1574                 try!(self.print_expr_maybe_paren(&**func));
1575                 try!(self.print_call_post(args[]));
1576             }
1577             ast::ExprMethodCall(ident, ref tys, ref args) => {
1578                 let base_args = args.slice_from(1);
1579                 try!(self.print_expr(&*args[0]));
1580                 try!(word(&mut self.s, "."));
1581                 try!(self.print_ident(ident.node));
1582                 if tys.len() > 0u {
1583                     try!(word(&mut self.s, "::<"));
1584                     try!(self.commasep(Inconsistent, tys[],
1585                                        |s, ty| s.print_type(&**ty)));
1586                     try!(word(&mut self.s, ">"));
1587                 }
1588                 try!(self.print_call_post(base_args));
1589             }
1590             ast::ExprBinary(op, ref lhs, ref rhs) => {
1591                 try!(self.print_expr(&**lhs));
1592                 try!(space(&mut self.s));
1593                 try!(self.word_space(ast_util::binop_to_string(op)));
1594                 try!(self.print_expr(&**rhs));
1595             }
1596             ast::ExprUnary(op, ref expr) => {
1597                 try!(word(&mut self.s, ast_util::unop_to_string(op)));
1598                 try!(self.print_expr_maybe_paren(&**expr));
1599             }
1600             ast::ExprAddrOf(m, ref expr) => {
1601                 try!(word(&mut self.s, "&"));
1602                 try!(self.print_mutability(m));
1603                 try!(self.print_expr_maybe_paren(&**expr));
1604             }
1605             ast::ExprLit(ref lit) => try!(self.print_literal(&**lit)),
1606             ast::ExprCast(ref expr, ref ty) => {
1607                 try!(self.print_expr(&**expr));
1608                 try!(space(&mut self.s));
1609                 try!(self.word_space("as"));
1610                 try!(self.print_type(&**ty));
1611             }
1612             ast::ExprIf(ref test, ref blk, ref elseopt) => {
1613                 try!(self.print_if(&**test, &**blk, elseopt.as_ref().map(|e| &**e)));
1614             }
1615             ast::ExprIfLet(ref pat, ref expr, ref blk, ref elseopt) => {
1616                 try!(self.print_if_let(&**pat, &**expr, &** blk, elseopt.as_ref().map(|e| &**e)));
1617             }
1618             ast::ExprWhile(ref test, ref blk, opt_ident) => {
1619                 for ident in opt_ident.iter() {
1620                     try!(self.print_ident(*ident));
1621                     try!(self.word_space(":"));
1622                 }
1623                 try!(self.head("while"));
1624                 try!(self.print_expr(&**test));
1625                 try!(space(&mut self.s));
1626                 try!(self.print_block(&**blk));
1627             }
1628             ast::ExprWhileLet(ref pat, ref expr, ref blk, opt_ident) => {
1629                 for ident in opt_ident.iter() {
1630                     try!(self.print_ident(*ident));
1631                     try!(self.word_space(":"));
1632                 }
1633                 try!(self.head("while let"));
1634                 try!(self.print_pat(&**pat));
1635                 try!(space(&mut self.s));
1636                 try!(self.word_space("="));
1637                 try!(self.print_expr(&**expr));
1638                 try!(space(&mut self.s));
1639                 try!(self.print_block(&**blk));
1640             }
1641             ast::ExprForLoop(ref pat, ref iter, ref blk, opt_ident) => {
1642                 for ident in opt_ident.iter() {
1643                     try!(self.print_ident(*ident));
1644                     try!(self.word_space(":"));
1645                 }
1646                 try!(self.head("for"));
1647                 try!(self.print_pat(&**pat));
1648                 try!(space(&mut self.s));
1649                 try!(self.word_space("in"));
1650                 try!(self.print_expr(&**iter));
1651                 try!(space(&mut self.s));
1652                 try!(self.print_block(&**blk));
1653             }
1654             ast::ExprLoop(ref blk, opt_ident) => {
1655                 for ident in opt_ident.iter() {
1656                     try!(self.print_ident(*ident));
1657                     try!(self.word_space(":"));
1658                 }
1659                 try!(self.head("loop"));
1660                 try!(space(&mut self.s));
1661                 try!(self.print_block(&**blk));
1662             }
1663             ast::ExprMatch(ref expr, ref arms, _) => {
1664                 try!(self.cbox(indent_unit));
1665                 try!(self.ibox(4));
1666                 try!(self.word_nbsp("match"));
1667                 try!(self.print_expr(&**expr));
1668                 try!(space(&mut self.s));
1669                 try!(self.bopen());
1670                 for arm in arms.iter() {
1671                     try!(self.print_arm(arm));
1672                 }
1673                 try!(self.bclose_(expr.span, indent_unit));
1674             }
1675             ast::ExprClosure(capture_clause, opt_kind, ref decl, ref body) => {
1676                 try!(self.print_capture_clause(capture_clause));
1677
1678                 try!(self.print_fn_block_args(&**decl, opt_kind));
1679                 try!(space(&mut self.s));
1680
1681                 if !body.stmts.is_empty() || !body.expr.is_some() {
1682                     try!(self.print_block_unclosed(&**body));
1683                 } else {
1684                     // we extract the block, so as not to create another set of boxes
1685                     match body.expr.as_ref().unwrap().node {
1686                         ast::ExprBlock(ref blk) => {
1687                             try!(self.print_block_unclosed(&**blk));
1688                         }
1689                         _ => {
1690                             // this is a bare expression
1691                             try!(self.print_expr(body.expr.as_ref().map(|e| &**e).unwrap()));
1692                             try!(self.end()); // need to close a box
1693                         }
1694                     }
1695                 }
1696                 // a box will be closed by print_expr, but we didn't want an overall
1697                 // wrapper so we closed the corresponding opening. so create an
1698                 // empty box to satisfy the close.
1699                 try!(self.ibox(0));
1700             }
1701             ast::ExprBlock(ref blk) => {
1702                 // containing cbox, will be closed by print-block at }
1703                 try!(self.cbox(indent_unit));
1704                 // head-box, will be closed by print-block after {
1705                 try!(self.ibox(0u));
1706                 try!(self.print_block(&**blk));
1707             }
1708             ast::ExprAssign(ref lhs, ref rhs) => {
1709                 try!(self.print_expr(&**lhs));
1710                 try!(space(&mut self.s));
1711                 try!(self.word_space("="));
1712                 try!(self.print_expr(&**rhs));
1713             }
1714             ast::ExprAssignOp(op, ref lhs, ref rhs) => {
1715                 try!(self.print_expr(&**lhs));
1716                 try!(space(&mut self.s));
1717                 try!(word(&mut self.s, ast_util::binop_to_string(op)));
1718                 try!(self.word_space("="));
1719                 try!(self.print_expr(&**rhs));
1720             }
1721             ast::ExprField(ref expr, id) => {
1722                 try!(self.print_expr(&**expr));
1723                 try!(word(&mut self.s, "."));
1724                 try!(self.print_ident(id.node));
1725             }
1726             ast::ExprTupField(ref expr, id) => {
1727                 try!(self.print_expr(&**expr));
1728                 try!(word(&mut self.s, "."));
1729                 try!(self.print_uint(id.node));
1730             }
1731             ast::ExprIndex(ref expr, ref index) => {
1732                 try!(self.print_expr(&**expr));
1733                 try!(word(&mut self.s, "["));
1734                 try!(self.print_expr(&**index));
1735                 try!(word(&mut self.s, "]"));
1736             }
1737             ast::ExprRange(ref start, ref end) => {
1738                 if let &Some(ref e) = start {
1739                     try!(self.print_expr(&**e));
1740                 }
1741                 if start.is_some() || end.is_some() {
1742                     try!(word(&mut self.s, ".."));
1743                 }
1744                 if let &Some(ref e) = end {
1745                     try!(self.print_expr(&**e));
1746                 }
1747             }
1748             ast::ExprPath(ref path) => try!(self.print_path(path, true)),
1749             ast::ExprBreak(opt_ident) => {
1750                 try!(word(&mut self.s, "break"));
1751                 try!(space(&mut self.s));
1752                 for ident in opt_ident.iter() {
1753                     try!(self.print_ident(*ident));
1754                     try!(space(&mut self.s));
1755                 }
1756             }
1757             ast::ExprAgain(opt_ident) => {
1758                 try!(word(&mut self.s, "continue"));
1759                 try!(space(&mut self.s));
1760                 for ident in opt_ident.iter() {
1761                     try!(self.print_ident(*ident));
1762                     try!(space(&mut self.s))
1763                 }
1764             }
1765             ast::ExprRet(ref result) => {
1766                 try!(word(&mut self.s, "return"));
1767                 match *result {
1768                     Some(ref expr) => {
1769                         try!(word(&mut self.s, " "));
1770                         try!(self.print_expr(&**expr));
1771                     }
1772                     _ => ()
1773                 }
1774             }
1775             ast::ExprInlineAsm(ref a) => {
1776                 try!(word(&mut self.s, "asm!"));
1777                 try!(self.popen());
1778                 try!(self.print_string(a.asm.get(), a.asm_str_style));
1779                 try!(self.word_space(":"));
1780
1781                 try!(self.commasep(Inconsistent, a.outputs[],
1782                                    |s, &(ref co, ref o, is_rw)| {
1783                     match co.get().slice_shift_char() {
1784                         Some(('=', operand)) if is_rw => {
1785                             try!(s.print_string(format!("+{}", operand)[],
1786                                                 ast::CookedStr))
1787                         }
1788                         _ => try!(s.print_string(co.get(), ast::CookedStr))
1789                     }
1790                     try!(s.popen());
1791                     try!(s.print_expr(&**o));
1792                     try!(s.pclose());
1793                     Ok(())
1794                 }));
1795                 try!(space(&mut self.s));
1796                 try!(self.word_space(":"));
1797
1798                 try!(self.commasep(Inconsistent, a.inputs[],
1799                                    |s, &(ref co, ref o)| {
1800                     try!(s.print_string(co.get(), ast::CookedStr));
1801                     try!(s.popen());
1802                     try!(s.print_expr(&**o));
1803                     try!(s.pclose());
1804                     Ok(())
1805                 }));
1806                 try!(space(&mut self.s));
1807                 try!(self.word_space(":"));
1808
1809                 try!(self.commasep(Inconsistent, a.clobbers[],
1810                                    |s, co| {
1811                     try!(s.print_string(co.get(), ast::CookedStr));
1812                     Ok(())
1813                 }));
1814
1815                 let mut options = vec!();
1816                 if a.volatile {
1817                     options.push("volatile");
1818                 }
1819                 if a.alignstack {
1820                     options.push("alignstack");
1821                 }
1822                 if a.dialect == ast::AsmDialect::AsmIntel {
1823                     options.push("intel");
1824                 }
1825
1826                 if options.len() > 0 {
1827                     try!(space(&mut self.s));
1828                     try!(self.word_space(":"));
1829                     try!(self.commasep(Inconsistent, &*options,
1830                                        |s, &co| {
1831                         try!(s.print_string(co, ast::CookedStr));
1832                         Ok(())
1833                     }));
1834                 }
1835
1836                 try!(self.pclose());
1837             }
1838             ast::ExprMac(ref m) => try!(self.print_mac(m, token::Paren)),
1839             ast::ExprParen(ref e) => {
1840                 try!(self.popen());
1841                 try!(self.print_expr(&**e));
1842                 try!(self.pclose());
1843             }
1844         }
1845         try!(self.ann.post(self, NodeExpr(expr)));
1846         self.end()
1847     }
1848
1849     pub fn print_local_decl(&mut self, loc: &ast::Local) -> IoResult<()> {
1850         try!(self.print_pat(&*loc.pat));
1851         if let Some(ref ty) = loc.ty {
1852             try!(self.word_space(":"));
1853             try!(self.print_type(&**ty));
1854         }
1855         Ok(())
1856     }
1857
1858     pub fn print_decl(&mut self, decl: &ast::Decl) -> IoResult<()> {
1859         try!(self.maybe_print_comment(decl.span.lo));
1860         match decl.node {
1861             ast::DeclLocal(ref loc) => {
1862                 try!(self.space_if_not_bol());
1863                 try!(self.ibox(indent_unit));
1864                 try!(self.word_nbsp("let"));
1865
1866                 try!(self.ibox(indent_unit));
1867                 try!(self.print_local_decl(&**loc));
1868                 try!(self.end());
1869                 if let Some(ref init) = loc.init {
1870                     try!(self.nbsp());
1871                     try!(self.word_space("="));
1872                     try!(self.print_expr(&**init));
1873                 }
1874                 self.end()
1875             }
1876             ast::DeclItem(ref item) => self.print_item(&**item)
1877         }
1878     }
1879
1880     pub fn print_ident(&mut self, ident: ast::Ident) -> IoResult<()> {
1881         if self.encode_idents_with_hygiene {
1882             let encoded = ident.encode_with_hygiene();
1883             try!(word(&mut self.s, encoded[]))
1884         } else {
1885             try!(word(&mut self.s, token::get_ident(ident).get()))
1886         }
1887         self.ann.post(self, NodeIdent(&ident))
1888     }
1889
1890     pub fn print_uint(&mut self, i: uint) -> IoResult<()> {
1891         word(&mut self.s, i.to_string()[])
1892     }
1893
1894     pub fn print_name(&mut self, name: ast::Name) -> IoResult<()> {
1895         try!(word(&mut self.s, token::get_name(name).get()));
1896         self.ann.post(self, NodeName(&name))
1897     }
1898
1899     pub fn print_for_decl(&mut self, loc: &ast::Local,
1900                           coll: &ast::Expr) -> IoResult<()> {
1901         try!(self.print_local_decl(loc));
1902         try!(space(&mut self.s));
1903         try!(self.word_space("in"));
1904         self.print_expr(coll)
1905     }
1906
1907     fn print_path(&mut self,
1908                   path: &ast::Path,
1909                   colons_before_params: bool)
1910                   -> IoResult<()>
1911     {
1912         try!(self.maybe_print_comment(path.span.lo));
1913         if path.global {
1914             try!(word(&mut self.s, "::"));
1915         }
1916
1917         let mut first = true;
1918         for segment in path.segments.iter() {
1919             if first {
1920                 first = false
1921             } else {
1922                 try!(word(&mut self.s, "::"))
1923             }
1924
1925             try!(self.print_ident(segment.identifier));
1926
1927             try!(self.print_path_parameters(&segment.parameters, colons_before_params));
1928         }
1929
1930         Ok(())
1931     }
1932
1933     fn print_path_parameters(&mut self,
1934                              parameters: &ast::PathParameters,
1935                              colons_before_params: bool)
1936                              -> IoResult<()>
1937     {
1938         if parameters.is_empty() {
1939             return Ok(());
1940         }
1941
1942         if colons_before_params {
1943             try!(word(&mut self.s, "::"))
1944         }
1945
1946         match *parameters {
1947             ast::AngleBracketedParameters(ref data) => {
1948                 try!(word(&mut self.s, "<"));
1949
1950                 let mut comma = false;
1951                 for lifetime in data.lifetimes.iter() {
1952                     if comma {
1953                         try!(self.word_space(","))
1954                     }
1955                     try!(self.print_lifetime(lifetime));
1956                     comma = true;
1957                 }
1958
1959                 if !data.types.is_empty() {
1960                     if comma {
1961                         try!(self.word_space(","))
1962                     }
1963                     try!(self.commasep(
1964                         Inconsistent,
1965                         data.types[],
1966                         |s, ty| s.print_type(&**ty)));
1967                         comma = true;
1968                 }
1969
1970                 for binding in data.bindings.iter() {
1971                     if comma {
1972                         try!(self.word_space(","))
1973                     }
1974                     try!(self.print_ident(binding.ident));
1975                     try!(space(&mut self.s));
1976                     try!(self.word_space("="));
1977                     try!(self.print_type(&*binding.ty));
1978                     comma = true;
1979                 }
1980
1981                 try!(word(&mut self.s, ">"))
1982             }
1983
1984             ast::ParenthesizedParameters(ref data) => {
1985                 try!(word(&mut self.s, "("));
1986                 try!(self.commasep(
1987                     Inconsistent,
1988                     data.inputs[],
1989                     |s, ty| s.print_type(&**ty)));
1990                 try!(word(&mut self.s, ")"));
1991
1992                 match data.output {
1993                     None => { }
1994                     Some(ref ty) => {
1995                         try!(self.space_if_not_bol());
1996                         try!(self.word_space("->"));
1997                         try!(self.print_type(&**ty));
1998                     }
1999                 }
2000             }
2001         }
2002
2003         Ok(())
2004     }
2005
2006     pub fn print_pat(&mut self, pat: &ast::Pat) -> IoResult<()> {
2007         try!(self.maybe_print_comment(pat.span.lo));
2008         try!(self.ann.pre(self, NodePat(pat)));
2009         /* Pat isn't normalized, but the beauty of it
2010          is that it doesn't matter */
2011         match pat.node {
2012             ast::PatWild(ast::PatWildSingle) => try!(word(&mut self.s, "_")),
2013             ast::PatWild(ast::PatWildMulti) => try!(word(&mut self.s, "..")),
2014             ast::PatIdent(binding_mode, ref path1, ref sub) => {
2015                 match binding_mode {
2016                     ast::BindByRef(mutbl) => {
2017                         try!(self.word_nbsp("ref"));
2018                         try!(self.print_mutability(mutbl));
2019                     }
2020                     ast::BindByValue(ast::MutImmutable) => {}
2021                     ast::BindByValue(ast::MutMutable) => {
2022                         try!(self.word_nbsp("mut"));
2023                     }
2024                 }
2025                 try!(self.print_ident(path1.node));
2026                 match *sub {
2027                     Some(ref p) => {
2028                         try!(word(&mut self.s, "@"));
2029                         try!(self.print_pat(&**p));
2030                     }
2031                     None => ()
2032                 }
2033             }
2034             ast::PatEnum(ref path, ref args_) => {
2035                 try!(self.print_path(path, true));
2036                 match *args_ {
2037                     None => try!(word(&mut self.s, "(..)")),
2038                     Some(ref args) => {
2039                         if !args.is_empty() {
2040                             try!(self.popen());
2041                             try!(self.commasep(Inconsistent, args[],
2042                                               |s, p| s.print_pat(&**p)));
2043                             try!(self.pclose());
2044                         }
2045                     }
2046                 }
2047             }
2048             ast::PatStruct(ref path, ref fields, etc) => {
2049                 try!(self.print_path(path, true));
2050                 try!(self.nbsp());
2051                 try!(self.word_space("{"));
2052                 try!(self.commasep_cmnt(
2053                     Consistent, fields[],
2054                     |s, f| {
2055                         try!(s.cbox(indent_unit));
2056                         if !f.node.is_shorthand {
2057                             try!(s.print_ident(f.node.ident));
2058                             try!(s.word_nbsp(":"));
2059                         }
2060                         try!(s.print_pat(&*f.node.pat));
2061                         s.end()
2062                     },
2063                     |f| f.node.pat.span));
2064                 if etc {
2065                     if fields.len() != 0u { try!(self.word_space(",")); }
2066                     try!(word(&mut self.s, ".."));
2067                 }
2068                 try!(space(&mut self.s));
2069                 try!(word(&mut self.s, "}"));
2070             }
2071             ast::PatTup(ref elts) => {
2072                 try!(self.popen());
2073                 try!(self.commasep(Inconsistent,
2074                                    elts[],
2075                                    |s, p| s.print_pat(&**p)));
2076                 if elts.len() == 1 {
2077                     try!(word(&mut self.s, ","));
2078                 }
2079                 try!(self.pclose());
2080             }
2081             ast::PatBox(ref inner) => {
2082                 try!(word(&mut self.s, "box "));
2083                 try!(self.print_pat(&**inner));
2084             }
2085             ast::PatRegion(ref inner, mutbl) => {
2086                 try!(word(&mut self.s, "&"));
2087                 if mutbl == ast::MutMutable {
2088                     try!(word(&mut self.s, "mut "));
2089                 }
2090                 try!(self.print_pat(&**inner));
2091             }
2092             ast::PatLit(ref e) => try!(self.print_expr(&**e)),
2093             ast::PatRange(ref begin, ref end) => {
2094                 try!(self.print_expr(&**begin));
2095                 try!(space(&mut self.s));
2096                 try!(word(&mut self.s, "..."));
2097                 try!(self.print_expr(&**end));
2098             }
2099             ast::PatVec(ref before, ref slice, ref after) => {
2100                 try!(word(&mut self.s, "["));
2101                 try!(self.commasep(Inconsistent,
2102                                    before[],
2103                                    |s, p| s.print_pat(&**p)));
2104                 for p in slice.iter() {
2105                     if !before.is_empty() { try!(self.word_space(",")); }
2106                     try!(self.print_pat(&**p));
2107                     match **p {
2108                         ast::Pat { node: ast::PatWild(ast::PatWildMulti), .. } => {
2109                             // this case is handled by print_pat
2110                         }
2111                         _ => try!(word(&mut self.s, "..")),
2112                     }
2113                     if !after.is_empty() { try!(self.word_space(",")); }
2114                 }
2115                 try!(self.commasep(Inconsistent,
2116                                    after[],
2117                                    |s, p| s.print_pat(&**p)));
2118                 try!(word(&mut self.s, "]"));
2119             }
2120             ast::PatMac(ref m) => try!(self.print_mac(m, token::Paren)),
2121         }
2122         self.ann.post(self, NodePat(pat))
2123     }
2124
2125     fn print_arm(&mut self, arm: &ast::Arm) -> IoResult<()> {
2126         // I have no idea why this check is necessary, but here it
2127         // is :(
2128         if arm.attrs.is_empty() {
2129             try!(space(&mut self.s));
2130         }
2131         try!(self.cbox(indent_unit));
2132         try!(self.ibox(0u));
2133         try!(self.print_outer_attributes(arm.attrs[]));
2134         let mut first = true;
2135         for p in arm.pats.iter() {
2136             if first {
2137                 first = false;
2138             } else {
2139                 try!(space(&mut self.s));
2140                 try!(self.word_space("|"));
2141             }
2142             try!(self.print_pat(&**p));
2143         }
2144         try!(space(&mut self.s));
2145         if let Some(ref e) = arm.guard {
2146             try!(self.word_space("if"));
2147             try!(self.print_expr(&**e));
2148             try!(space(&mut self.s));
2149         }
2150         try!(self.word_space("=>"));
2151
2152         match arm.body.node {
2153             ast::ExprBlock(ref blk) => {
2154                 // the block will close the pattern's ibox
2155                 try!(self.print_block_unclosed_indent(&**blk, indent_unit));
2156
2157                 // If it is a user-provided unsafe block, print a comma after it
2158                 if let ast::UnsafeBlock(ast::UserProvided) = blk.rules {
2159                     try!(word(&mut self.s, ","));
2160                 }
2161             }
2162             _ => {
2163                 try!(self.end()); // close the ibox for the pattern
2164                 try!(self.print_expr(&*arm.body));
2165                 try!(word(&mut self.s, ","));
2166             }
2167         }
2168         self.end() // close enclosing cbox
2169     }
2170
2171     // Returns whether it printed anything
2172     fn print_explicit_self(&mut self,
2173                            explicit_self: &ast::ExplicitSelf_,
2174                            mutbl: ast::Mutability) -> IoResult<bool> {
2175         try!(self.print_mutability(mutbl));
2176         match *explicit_self {
2177             ast::SelfStatic => { return Ok(false); }
2178             ast::SelfValue(_) => {
2179                 try!(word(&mut self.s, "self"));
2180             }
2181             ast::SelfRegion(ref lt, m, _) => {
2182                 try!(word(&mut self.s, "&"));
2183                 try!(self.print_opt_lifetime(lt));
2184                 try!(self.print_mutability(m));
2185                 try!(word(&mut self.s, "self"));
2186             }
2187             ast::SelfExplicit(ref typ, _) => {
2188                 try!(word(&mut self.s, "self"));
2189                 try!(self.word_space(":"));
2190                 try!(self.print_type(&**typ));
2191             }
2192         }
2193         return Ok(true);
2194     }
2195
2196     pub fn print_fn(&mut self,
2197                     decl: &ast::FnDecl,
2198                     unsafety: Option<ast::Unsafety>,
2199                     abi: abi::Abi,
2200                     name: ast::Ident,
2201                     generics: &ast::Generics,
2202                     opt_explicit_self: Option<&ast::ExplicitSelf_>,
2203                     vis: ast::Visibility) -> IoResult<()> {
2204         try!(self.head(""));
2205         try!(self.print_fn_header_info(opt_explicit_self, unsafety, abi, vis));
2206         try!(self.nbsp());
2207         try!(self.print_ident(name));
2208         try!(self.print_generics(generics));
2209         try!(self.print_fn_args_and_ret(decl, opt_explicit_self));
2210         self.print_where_clause(generics)
2211     }
2212
2213     pub fn print_fn_args(&mut self, decl: &ast::FnDecl,
2214                          opt_explicit_self: Option<&ast::ExplicitSelf_>)
2215         -> IoResult<()> {
2216         // It is unfortunate to duplicate the commasep logic, but we want the
2217         // self type and the args all in the same box.
2218         try!(self.rbox(0u, Inconsistent));
2219         let mut first = true;
2220         for &explicit_self in opt_explicit_self.iter() {
2221             let m = match explicit_self {
2222                 &ast::SelfStatic => ast::MutImmutable,
2223                 _ => match decl.inputs[0].pat.node {
2224                     ast::PatIdent(ast::BindByValue(m), _, _) => m,
2225                     _ => ast::MutImmutable
2226                 }
2227             };
2228             first = !try!(self.print_explicit_self(explicit_self, m));
2229         }
2230
2231         // HACK(eddyb) ignore the separately printed self argument.
2232         let args = if first {
2233             decl.inputs[]
2234         } else {
2235             decl.inputs.slice_from(1)
2236         };
2237
2238         for arg in args.iter() {
2239             if first { first = false; } else { try!(self.word_space(",")); }
2240             try!(self.print_arg(arg));
2241         }
2242
2243         self.end()
2244     }
2245
2246     pub fn print_fn_args_and_ret(&mut self, decl: &ast::FnDecl,
2247                                  opt_explicit_self: Option<&ast::ExplicitSelf_>)
2248         -> IoResult<()> {
2249         try!(self.popen());
2250         try!(self.print_fn_args(decl, opt_explicit_self));
2251         if decl.variadic {
2252             try!(word(&mut self.s, ", ..."));
2253         }
2254         try!(self.pclose());
2255
2256         self.print_fn_output(decl)
2257     }
2258
2259     pub fn print_fn_block_args(
2260             &mut self,
2261             decl: &ast::FnDecl,
2262             unboxed_closure_kind: Option<UnboxedClosureKind>)
2263             -> IoResult<()> {
2264         try!(word(&mut self.s, "|"));
2265         match unboxed_closure_kind {
2266             None => {}
2267             Some(FnUnboxedClosureKind) => try!(self.word_space("&:")),
2268             Some(FnMutUnboxedClosureKind) => try!(self.word_space("&mut:")),
2269             Some(FnOnceUnboxedClosureKind) => try!(self.word_space(":")),
2270         }
2271         try!(self.print_fn_args(decl, None));
2272         try!(word(&mut self.s, "|"));
2273
2274         if let ast::Return(ref ty) = decl.output {
2275             if ty.node == ast::TyInfer {
2276                 return self.maybe_print_comment(ty.span.lo);
2277             }
2278         }
2279
2280         try!(self.space_if_not_bol());
2281         try!(self.word_space("->"));
2282         match decl.output {
2283             ast::Return(ref ty) => {
2284                 try!(self.print_type(&**ty));
2285                 self.maybe_print_comment(ty.span.lo)
2286             }
2287             ast::NoReturn(span) => {
2288                 try!(self.word_nbsp("!"));
2289                 self.maybe_print_comment(span.lo)
2290             }
2291         }
2292     }
2293
2294     pub fn print_capture_clause(&mut self, capture_clause: ast::CaptureClause)
2295                                 -> IoResult<()> {
2296         match capture_clause {
2297             ast::CaptureByValue => self.word_space("move"),
2298             ast::CaptureByRef => Ok(()),
2299         }
2300     }
2301
2302     pub fn print_proc_args(&mut self, decl: &ast::FnDecl) -> IoResult<()> {
2303         try!(word(&mut self.s, "proc"));
2304         try!(word(&mut self.s, "("));
2305         try!(self.print_fn_args(decl, None));
2306         try!(word(&mut self.s, ")"));
2307
2308         if let ast::Return(ref ty) = decl.output {
2309             if ty.node == ast::TyInfer {
2310                 return self.maybe_print_comment(ty.span.lo);
2311             }
2312         }
2313
2314         try!(self.space_if_not_bol());
2315         try!(self.word_space("->"));
2316         match decl.output {
2317             ast::Return(ref ty) => {
2318                 try!(self.print_type(&**ty));
2319                 self.maybe_print_comment(ty.span.lo)
2320             }
2321             ast::NoReturn(span) => {
2322                 try!(self.word_nbsp("!"));
2323                 self.maybe_print_comment(span.lo)
2324             }
2325         }
2326     }
2327
2328     pub fn print_bounds(&mut self,
2329                         prefix: &str,
2330                         bounds: &[ast::TyParamBound])
2331                         -> IoResult<()> {
2332         if !bounds.is_empty() {
2333             try!(word(&mut self.s, prefix));
2334             let mut first = true;
2335             for bound in bounds.iter() {
2336                 try!(self.nbsp());
2337                 if first {
2338                     first = false;
2339                 } else {
2340                     try!(self.word_space("+"));
2341                 }
2342
2343                 try!(match *bound {
2344                     TraitTyParamBound(ref tref, TraitBoundModifier::None) => {
2345                         self.print_poly_trait_ref(tref)
2346                     }
2347                     TraitTyParamBound(ref tref, TraitBoundModifier::Maybe) => {
2348                         try!(word(&mut self.s, "?"));
2349                         self.print_poly_trait_ref(tref)
2350                     }
2351                     RegionTyParamBound(ref lt) => {
2352                         self.print_lifetime(lt)
2353                     }
2354                 })
2355             }
2356             Ok(())
2357         } else {
2358             Ok(())
2359         }
2360     }
2361
2362     pub fn print_lifetime(&mut self,
2363                           lifetime: &ast::Lifetime)
2364                           -> IoResult<()>
2365     {
2366         self.print_name(lifetime.name)
2367     }
2368
2369     pub fn print_lifetime_def(&mut self,
2370                               lifetime: &ast::LifetimeDef)
2371                               -> IoResult<()>
2372     {
2373         try!(self.print_lifetime(&lifetime.lifetime));
2374         let mut sep = ":";
2375         for v in lifetime.bounds.iter() {
2376             try!(word(&mut self.s, sep));
2377             try!(self.print_lifetime(v));
2378             sep = "+";
2379         }
2380         Ok(())
2381     }
2382
2383     pub fn print_generics(&mut self,
2384                           generics: &ast::Generics)
2385                           -> IoResult<()>
2386     {
2387         let total = generics.lifetimes.len() + generics.ty_params.len();
2388         if total == 0 {
2389             return Ok(());
2390         }
2391
2392         try!(word(&mut self.s, "<"));
2393
2394         let mut ints = Vec::new();
2395         for i in range(0u, total) {
2396             ints.push(i);
2397         }
2398
2399         try!(self.commasep(Inconsistent, ints[], |s, &idx| {
2400             if idx < generics.lifetimes.len() {
2401                 let lifetime = &generics.lifetimes[idx];
2402                 s.print_lifetime_def(lifetime)
2403             } else {
2404                 let idx = idx - generics.lifetimes.len();
2405                 let param = &generics.ty_params[idx];
2406                 s.print_ty_param(param)
2407             }
2408         }));
2409
2410         try!(word(&mut self.s, ">"));
2411         Ok(())
2412     }
2413
2414     pub fn print_ty_param(&mut self, param: &ast::TyParam) -> IoResult<()> {
2415         try!(self.print_ident(param.ident));
2416         try!(self.print_bounds(":", param.bounds[]));
2417         match param.default {
2418             Some(ref default) => {
2419                 try!(space(&mut self.s));
2420                 try!(self.word_space("="));
2421                 self.print_type(&**default)
2422             }
2423             _ => Ok(())
2424         }
2425     }
2426
2427     pub fn print_where_clause(&mut self, generics: &ast::Generics)
2428                               -> IoResult<()> {
2429         if generics.where_clause.predicates.len() == 0 {
2430             return Ok(())
2431         }
2432
2433         try!(space(&mut self.s));
2434         try!(self.word_space("where"));
2435
2436         for (i, predicate) in generics.where_clause
2437                                       .predicates
2438                                       .iter()
2439                                       .enumerate() {
2440             if i != 0 {
2441                 try!(self.word_space(","));
2442             }
2443
2444             match predicate {
2445                 &ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate{ref bounded_ty,
2446                                                                               ref bounds,
2447                                                                               ..}) => {
2448                     try!(self.print_type(&**bounded_ty));
2449                     try!(self.print_bounds(":", bounds.as_slice()));
2450                 }
2451                 &ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate{ref lifetime,
2452                                                                                 ref bounds,
2453                                                                                 ..}) => {
2454                     try!(self.print_lifetime(lifetime));
2455                     try!(word(&mut self.s, ":"));
2456
2457                     for (i, bound) in bounds.iter().enumerate() {
2458                         try!(self.print_lifetime(bound));
2459
2460                         if i != 0 {
2461                             try!(word(&mut self.s, ":"));
2462                         }
2463                     }
2464                 }
2465                 &ast::WherePredicate::EqPredicate(ast::WhereEqPredicate{ref path, ref ty, ..}) => {
2466                     try!(self.print_path(path, false));
2467                     try!(space(&mut self.s));
2468                     try!(self.word_space("="));
2469                     try!(self.print_type(&**ty));
2470                 }
2471             }
2472         }
2473
2474         Ok(())
2475     }
2476
2477     pub fn print_meta_item(&mut self, item: &ast::MetaItem) -> IoResult<()> {
2478         try!(self.ibox(indent_unit));
2479         match item.node {
2480             ast::MetaWord(ref name) => {
2481                 try!(word(&mut self.s, name.get()));
2482             }
2483             ast::MetaNameValue(ref name, ref value) => {
2484                 try!(self.word_space(name.get()));
2485                 try!(self.word_space("="));
2486                 try!(self.print_literal(value));
2487             }
2488             ast::MetaList(ref name, ref items) => {
2489                 try!(word(&mut self.s, name.get()));
2490                 try!(self.popen());
2491                 try!(self.commasep(Consistent,
2492                                    items[],
2493                                    |s, i| s.print_meta_item(&**i)));
2494                 try!(self.pclose());
2495             }
2496         }
2497         self.end()
2498     }
2499
2500     pub fn print_view_path(&mut self, vp: &ast::ViewPath) -> IoResult<()> {
2501         match vp.node {
2502             ast::ViewPathSimple(ident, ref path, _) => {
2503                 try!(self.print_path(path, false));
2504
2505                 // FIXME(#6993) can't compare identifiers directly here
2506                 if path.segments.last().unwrap().identifier.name !=
2507                         ident.name {
2508                     try!(space(&mut self.s));
2509                     try!(self.word_space("as"));
2510                     try!(self.print_ident(ident));
2511                 }
2512
2513                 Ok(())
2514             }
2515
2516             ast::ViewPathGlob(ref path, _) => {
2517                 try!(self.print_path(path, false));
2518                 word(&mut self.s, "::*")
2519             }
2520
2521             ast::ViewPathList(ref path, ref idents, _) => {
2522                 if path.segments.is_empty() {
2523                     try!(word(&mut self.s, "{"));
2524                 } else {
2525                     try!(self.print_path(path, false));
2526                     try!(word(&mut self.s, "::{"));
2527                 }
2528                 try!(self.commasep(Inconsistent, idents[], |s, w| {
2529                     match w.node {
2530                         ast::PathListIdent { name, .. } => {
2531                             s.print_ident(name)
2532                         },
2533                         ast::PathListMod { .. } => {
2534                             word(&mut s.s, "self")
2535                         }
2536                     }
2537                 }));
2538                 word(&mut self.s, "}")
2539             }
2540         }
2541     }
2542
2543     pub fn print_view_item(&mut self, item: &ast::ViewItem) -> IoResult<()> {
2544         try!(self.hardbreak_if_not_bol());
2545         try!(self.maybe_print_comment(item.span.lo));
2546         try!(self.print_outer_attributes(item.attrs[]));
2547         try!(self.print_visibility(item.vis));
2548         match item.node {
2549             ast::ViewItemExternCrate(id, ref optional_path, _) => {
2550                 try!(self.head("extern crate"));
2551                 for &(ref p, style) in optional_path.iter() {
2552                     try!(self.print_string(p.get(), style));
2553                     try!(space(&mut self.s));
2554                     try!(word(&mut self.s, "as"));
2555                     try!(space(&mut self.s));
2556                 }
2557                 try!(self.print_ident(id));
2558             }
2559
2560             ast::ViewItemUse(ref vp) => {
2561                 try!(self.head("use"));
2562                 try!(self.print_view_path(&**vp));
2563             }
2564         }
2565         try!(word(&mut self.s, ";"));
2566         try!(self.end()); // end inner head-block
2567         self.end() // end outer head-block
2568     }
2569
2570     pub fn print_mutability(&mut self,
2571                             mutbl: ast::Mutability) -> IoResult<()> {
2572         match mutbl {
2573             ast::MutMutable => self.word_nbsp("mut"),
2574             ast::MutImmutable => Ok(()),
2575         }
2576     }
2577
2578     pub fn print_mt(&mut self, mt: &ast::MutTy) -> IoResult<()> {
2579         try!(self.print_mutability(mt.mutbl));
2580         self.print_type(&*mt.ty)
2581     }
2582
2583     pub fn print_arg(&mut self, input: &ast::Arg) -> IoResult<()> {
2584         try!(self.ibox(indent_unit));
2585         match input.ty.node {
2586             ast::TyInfer => try!(self.print_pat(&*input.pat)),
2587             _ => {
2588                 match input.pat.node {
2589                     ast::PatIdent(_, ref path1, _) if
2590                         path1.node.name ==
2591                             parse::token::special_idents::invalid.name => {
2592                         // Do nothing.
2593                     }
2594                     _ => {
2595                         try!(self.print_pat(&*input.pat));
2596                         try!(word(&mut self.s, ":"));
2597                         try!(space(&mut self.s));
2598                     }
2599                 }
2600                 try!(self.print_type(&*input.ty));
2601             }
2602         }
2603         self.end()
2604     }
2605
2606     pub fn print_fn_output(&mut self, decl: &ast::FnDecl) -> IoResult<()> {
2607         if let ast::Return(ref ty) = decl.output {
2608             match ty.node {
2609                 ast::TyTup(ref tys) if tys.is_empty() => {
2610                     return self.maybe_print_comment(ty.span.lo);
2611                 }
2612                 _ => ()
2613             }
2614         }
2615
2616         try!(self.space_if_not_bol());
2617         try!(self.ibox(indent_unit));
2618         try!(self.word_space("->"));
2619         match decl.output {
2620             ast::NoReturn(_) =>
2621                 try!(self.word_nbsp("!")),
2622             ast::Return(ref ty) =>
2623                 try!(self.print_type(&**ty))
2624         }
2625         try!(self.end());
2626
2627         match decl.output {
2628             ast::Return(ref output) => self.maybe_print_comment(output.span.lo),
2629             _ => Ok(())
2630         }
2631     }
2632
2633     pub fn print_ty_fn(&mut self,
2634                        opt_abi: Option<abi::Abi>,
2635                        opt_sigil: Option<char>,
2636                        unsafety: ast::Unsafety,
2637                        onceness: ast::Onceness,
2638                        decl: &ast::FnDecl,
2639                        id: Option<ast::Ident>,
2640                        bounds: &OwnedSlice<ast::TyParamBound>,
2641                        generics: Option<&ast::Generics>,
2642                        opt_explicit_self: Option<&ast::ExplicitSelf_>)
2643                        -> IoResult<()> {
2644         try!(self.ibox(indent_unit));
2645
2646         // Duplicates the logic in `print_fn_header_info()`.  This is because that
2647         // function prints the sigil in the wrong place.  That should be fixed.
2648         if opt_sigil == Some('~') && onceness == ast::Once {
2649             try!(word(&mut self.s, "proc"));
2650         } else if opt_sigil == Some('&') {
2651             try!(self.print_unsafety(unsafety));
2652             try!(self.print_extern_opt_abi(opt_abi));
2653         } else {
2654             assert!(opt_sigil.is_none());
2655             try!(self.print_unsafety(unsafety));
2656             try!(self.print_opt_abi_and_extern_if_nondefault(opt_abi));
2657             try!(word(&mut self.s, "fn"));
2658         }
2659
2660         match id {
2661             Some(id) => {
2662                 try!(word(&mut self.s, " "));
2663                 try!(self.print_ident(id));
2664             }
2665             _ => ()
2666         }
2667
2668         match generics { Some(g) => try!(self.print_generics(g)), _ => () }
2669         try!(zerobreak(&mut self.s));
2670
2671         if opt_sigil == Some('&') {
2672             try!(word(&mut self.s, "|"));
2673         } else {
2674             try!(self.popen());
2675         }
2676
2677         try!(self.print_fn_args(decl, opt_explicit_self));
2678
2679         if opt_sigil == Some('&') {
2680             try!(word(&mut self.s, "|"));
2681         } else {
2682             if decl.variadic {
2683                 try!(word(&mut self.s, ", ..."));
2684             }
2685             try!(self.pclose());
2686         }
2687
2688         try!(self.print_bounds(":", bounds[]));
2689
2690         try!(self.print_fn_output(decl));
2691
2692         match generics {
2693             Some(generics) => try!(self.print_where_clause(generics)),
2694             None => {}
2695         }
2696
2697         self.end()
2698     }
2699
2700     pub fn maybe_print_trailing_comment(&mut self, span: codemap::Span,
2701                                         next_pos: Option<BytePos>)
2702         -> IoResult<()> {
2703         let cm = match self.cm {
2704             Some(cm) => cm,
2705             _ => return Ok(())
2706         };
2707         match self.next_comment() {
2708             Some(ref cmnt) => {
2709                 if (*cmnt).style != comments::Trailing { return Ok(()) }
2710                 let span_line = cm.lookup_char_pos(span.hi);
2711                 let comment_line = cm.lookup_char_pos((*cmnt).pos);
2712                 let mut next = (*cmnt).pos + BytePos(1);
2713                 match next_pos { None => (), Some(p) => next = p }
2714                 if span.hi < (*cmnt).pos && (*cmnt).pos < next &&
2715                     span_line.line == comment_line.line {
2716                         try!(self.print_comment(cmnt));
2717                         self.cur_cmnt_and_lit.cur_cmnt += 1u;
2718                     }
2719             }
2720             _ => ()
2721         }
2722         Ok(())
2723     }
2724
2725     pub fn print_remaining_comments(&mut self) -> IoResult<()> {
2726         // If there aren't any remaining comments, then we need to manually
2727         // make sure there is a line break at the end.
2728         if self.next_comment().is_none() {
2729             try!(hardbreak(&mut self.s));
2730         }
2731         loop {
2732             match self.next_comment() {
2733                 Some(ref cmnt) => {
2734                     try!(self.print_comment(cmnt));
2735                     self.cur_cmnt_and_lit.cur_cmnt += 1u;
2736                 }
2737                 _ => break
2738             }
2739         }
2740         Ok(())
2741     }
2742
2743     pub fn print_literal(&mut self, lit: &ast::Lit) -> IoResult<()> {
2744         try!(self.maybe_print_comment(lit.span.lo));
2745         match self.next_lit(lit.span.lo) {
2746             Some(ref ltrl) => {
2747                 return word(&mut self.s, (*ltrl).lit[]);
2748             }
2749             _ => ()
2750         }
2751         match lit.node {
2752             ast::LitStr(ref st, style) => self.print_string(st.get(), style),
2753             ast::LitByte(byte) => {
2754                 let mut res = String::from_str("b'");
2755                 ascii::escape_default(byte, |c| res.push(c as char));
2756                 res.push('\'');
2757                 word(&mut self.s, res[])
2758             }
2759             ast::LitChar(ch) => {
2760                 let mut res = String::from_str("'");
2761                 for c in ch.escape_default() {
2762                     res.push(c);
2763                 }
2764                 res.push('\'');
2765                 word(&mut self.s, res[])
2766             }
2767             ast::LitInt(i, t) => {
2768                 match t {
2769                     ast::SignedIntLit(st, ast::Plus) => {
2770                         word(&mut self.s,
2771                              ast_util::int_ty_to_string(st, Some(i as i64))[])
2772                     }
2773                     ast::SignedIntLit(st, ast::Minus) => {
2774                         let istr = ast_util::int_ty_to_string(st, Some(-(i as i64)));
2775                         word(&mut self.s,
2776                              format!("-{}", istr)[])
2777                     }
2778                     ast::UnsignedIntLit(ut) => {
2779                         word(&mut self.s, ast_util::uint_ty_to_string(ut, Some(i))[])
2780                     }
2781                     ast::UnsuffixedIntLit(ast::Plus) => {
2782                         word(&mut self.s, format!("{}", i)[])
2783                     }
2784                     ast::UnsuffixedIntLit(ast::Minus) => {
2785                         word(&mut self.s, format!("-{}", i)[])
2786                     }
2787                 }
2788             }
2789             ast::LitFloat(ref f, t) => {
2790                 word(&mut self.s,
2791                      format!(
2792                          "{}{}",
2793                          f.get(),
2794                          ast_util::float_ty_to_string(t)[])[])
2795             }
2796             ast::LitFloatUnsuffixed(ref f) => word(&mut self.s, f.get()),
2797             ast::LitBool(val) => {
2798                 if val { word(&mut self.s, "true") } else { word(&mut self.s, "false") }
2799             }
2800             ast::LitBinary(ref v) => {
2801                 let mut escaped: String = String::new();
2802                 for &ch in v.iter() {
2803                     ascii::escape_default(ch as u8,
2804                                           |ch| escaped.push(ch as char));
2805                 }
2806                 word(&mut self.s, format!("b\"{}\"", escaped)[])
2807             }
2808         }
2809     }
2810
2811     pub fn next_lit(&mut self, pos: BytePos) -> Option<comments::Literal> {
2812         match self.literals {
2813             Some(ref lits) => {
2814                 while self.cur_cmnt_and_lit.cur_lit < lits.len() {
2815                     let ltrl = (*lits)[self.cur_cmnt_and_lit.cur_lit].clone();
2816                     if ltrl.pos > pos { return None; }
2817                     self.cur_cmnt_and_lit.cur_lit += 1u;
2818                     if ltrl.pos == pos { return Some(ltrl); }
2819                 }
2820                 None
2821             }
2822             _ => None
2823         }
2824     }
2825
2826     pub fn maybe_print_comment(&mut self, pos: BytePos) -> IoResult<()> {
2827         loop {
2828             match self.next_comment() {
2829                 Some(ref cmnt) => {
2830                     if (*cmnt).pos < pos {
2831                         try!(self.print_comment(cmnt));
2832                         self.cur_cmnt_and_lit.cur_cmnt += 1u;
2833                     } else { break; }
2834                 }
2835                 _ => break
2836             }
2837         }
2838         Ok(())
2839     }
2840
2841     pub fn print_comment(&mut self,
2842                          cmnt: &comments::Comment) -> IoResult<()> {
2843         match cmnt.style {
2844             comments::Mixed => {
2845                 assert_eq!(cmnt.lines.len(), 1u);
2846                 try!(zerobreak(&mut self.s));
2847                 try!(word(&mut self.s, cmnt.lines[0][]));
2848                 zerobreak(&mut self.s)
2849             }
2850             comments::Isolated => {
2851                 try!(self.hardbreak_if_not_bol());
2852                 for line in cmnt.lines.iter() {
2853                     // Don't print empty lines because they will end up as trailing
2854                     // whitespace
2855                     if !line.is_empty() {
2856                         try!(word(&mut self.s, line[]));
2857                     }
2858                     try!(hardbreak(&mut self.s));
2859                 }
2860                 Ok(())
2861             }
2862             comments::Trailing => {
2863                 try!(word(&mut self.s, " "));
2864                 if cmnt.lines.len() == 1u {
2865                     try!(word(&mut self.s, cmnt.lines[0][]));
2866                     hardbreak(&mut self.s)
2867                 } else {
2868                     try!(self.ibox(0u));
2869                     for line in cmnt.lines.iter() {
2870                         if !line.is_empty() {
2871                             try!(word(&mut self.s, line[]));
2872                         }
2873                         try!(hardbreak(&mut self.s));
2874                     }
2875                     self.end()
2876                 }
2877             }
2878             comments::BlankLine => {
2879                 // We need to do at least one, possibly two hardbreaks.
2880                 let is_semi = match self.s.last_token() {
2881                     pp::String(s, _) => ";" == s,
2882                     _ => false
2883                 };
2884                 if is_semi || self.is_begin() || self.is_end() {
2885                     try!(hardbreak(&mut self.s));
2886                 }
2887                 hardbreak(&mut self.s)
2888             }
2889         }
2890     }
2891
2892     pub fn print_string(&mut self, st: &str,
2893                         style: ast::StrStyle) -> IoResult<()> {
2894         let st = match style {
2895             ast::CookedStr => {
2896                 (format!("\"{}\"", st.escape_default()))
2897             }
2898             ast::RawStr(n) => {
2899                 (format!("r{delim}\"{string}\"{delim}",
2900                          delim=repeat("#", n),
2901                          string=st))
2902             }
2903         };
2904         word(&mut self.s, st[])
2905     }
2906
2907     pub fn next_comment(&mut self) -> Option<comments::Comment> {
2908         match self.comments {
2909             Some(ref cmnts) => {
2910                 if self.cur_cmnt_and_lit.cur_cmnt < cmnts.len() {
2911                     Some(cmnts[self.cur_cmnt_and_lit.cur_cmnt].clone())
2912                 } else {
2913                     None
2914                 }
2915             }
2916             _ => None
2917         }
2918     }
2919
2920     pub fn print_opt_unsafety(&mut self,
2921                             opt_unsafety: Option<ast::Unsafety>) -> IoResult<()> {
2922         match opt_unsafety {
2923             Some(unsafety) => self.print_unsafety(unsafety),
2924             None => Ok(())
2925         }
2926     }
2927
2928     pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
2929                                                   opt_abi: Option<abi::Abi>)
2930         -> IoResult<()> {
2931         match opt_abi {
2932             Some(abi::Rust) => Ok(()),
2933             Some(abi) => {
2934                 try!(self.word_nbsp("extern"));
2935                 self.word_nbsp(abi.to_string()[])
2936             }
2937             None => Ok(())
2938         }
2939     }
2940
2941     pub fn print_extern_opt_abi(&mut self,
2942                                 opt_abi: Option<abi::Abi>) -> IoResult<()> {
2943         match opt_abi {
2944             Some(abi) => {
2945                 try!(self.word_nbsp("extern"));
2946                 self.word_nbsp(abi.to_string()[])
2947             }
2948             None => Ok(())
2949         }
2950     }
2951
2952     pub fn print_fn_header_info(&mut self,
2953                                 _opt_explicit_self: Option<&ast::ExplicitSelf_>,
2954                                 opt_unsafety: Option<ast::Unsafety>,
2955                                 abi: abi::Abi,
2956                                 vis: ast::Visibility) -> IoResult<()> {
2957         try!(word(&mut self.s, visibility_qualified(vis, "").as_slice()));
2958         try!(self.print_opt_unsafety(opt_unsafety));
2959
2960         if abi != abi::Rust {
2961             try!(self.word_nbsp("extern"));
2962             try!(self.word_nbsp(abi.to_string()[]));
2963         }
2964
2965         word(&mut self.s, "fn")
2966     }
2967
2968     pub fn print_unsafety(&mut self, s: ast::Unsafety) -> IoResult<()> {
2969         match s {
2970             ast::Unsafety::Normal => Ok(()),
2971             ast::Unsafety::Unsafe => self.word_nbsp("unsafe"),
2972         }
2973     }
2974 }
2975
2976 fn repeat(s: &str, n: uint) -> String { iter::repeat(s).take(n).collect() }
2977
2978 #[cfg(test)]
2979 mod test {
2980     use super::*;
2981
2982     use ast;
2983     use ast_util;
2984     use codemap;
2985     use parse::token;
2986     use ptr::P;
2987
2988     #[test]
2989     fn test_fun_to_string() {
2990         let abba_ident = token::str_to_ident("abba");
2991
2992         let decl = ast::FnDecl {
2993             inputs: Vec::new(),
2994             output: ast::Return(P(ast::Ty {id: 0,
2995                                node: ast::TyTup(vec![]),
2996                                span: codemap::DUMMY_SP})),
2997             variadic: false
2998         };
2999         let generics = ast_util::empty_generics();
3000         assert_eq!(fun_to_string(&decl, ast::Unsafety::Normal, abba_ident,
3001                                None, &generics),
3002                    "fn abba()");
3003     }
3004
3005     #[test]
3006     fn test_variant_to_string() {
3007         let ident = token::str_to_ident("principal_skinner");
3008
3009         let var = codemap::respan(codemap::DUMMY_SP, ast::Variant_ {
3010             name: ident,
3011             attrs: Vec::new(),
3012             // making this up as I go.... ?
3013             kind: ast::TupleVariantKind(Vec::new()),
3014             id: 0,
3015             disr_expr: None,
3016             vis: ast::Public,
3017         });
3018
3019         let varstr = variant_to_string(&var);
3020         assert_eq!(varstr, "pub principal_skinner");
3021     }
3022
3023     #[test]
3024     fn test_signed_int_to_string() {
3025         let pos_int = ast::LitInt(42, ast::SignedIntLit(ast::TyI32, ast::Plus));
3026         let neg_int = ast::LitInt((-42) as u64, ast::SignedIntLit(ast::TyI32, ast::Minus));
3027         assert_eq!(format!("-{}", lit_to_string(&codemap::dummy_spanned(pos_int))),
3028                    lit_to_string(&codemap::dummy_spanned(neg_int)));
3029     }
3030 }