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