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