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