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