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