]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/print/pprust.rs
auto merge of #15158 : alexcrichton/rust/windows-paths, r=brson
[rust.git] / src / libsyntax / print / pprust.rs
1 // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use abi;
12 use ast::{P, StaticRegionTyParamBound, OtherRegionTyParamBound};
13 use ast::{TraitTyParamBound, UnboxedFnTyParamBound, Required, Provided};
14 use ast;
15 use ast_util;
16 use owned_slice::OwnedSlice;
17 use attr::{AttrMetaMethods, AttributeMethods};
18 use codemap::{CodeMap, BytePos};
19 use codemap;
20 use diagnostic;
21 use parse::classify::expr_is_simple_block;
22 use parse::token;
23 use parse::lexer::comments;
24 use parse;
25 use print::pp::{break_offset, word, space, zerobreak, hardbreak};
26 use print::pp::{Breaks, Consistent, Inconsistent, eof};
27 use print::pp;
28
29 use std::gc::Gc;
30 use std::io::{IoResult, MemWriter};
31 use std::io;
32 use std::mem;
33 use std::str;
34
35 pub enum AnnNode<'a> {
36     NodeBlock(&'a ast::Block),
37     NodeItem(&'a ast::Item),
38     NodeExpr(&'a ast::Expr),
39     NodePat(&'a ast::Pat),
40 }
41
42 pub trait PpAnn {
43     fn pre(&self, _state: &mut State, _node: AnnNode) -> IoResult<()> { Ok(()) }
44     fn post(&self, _state: &mut State, _node: AnnNode) -> IoResult<()> { Ok(()) }
45 }
46
47 pub struct NoAnn;
48
49 impl PpAnn for NoAnn {}
50
51 pub struct CurrentCommentAndLiteral {
52     cur_cmnt: uint,
53     cur_lit: uint,
54 }
55
56 pub struct State<'a> {
57     pub s: pp::Printer,
58     cm: Option<&'a CodeMap>,
59     comments: Option<Vec<comments::Comment> >,
60     literals: Option<Vec<comments::Literal> >,
61     cur_cmnt_and_lit: CurrentCommentAndLiteral,
62     boxes: Vec<pp::Breaks>,
63     ann: &'a PpAnn
64 }
65
66 pub fn rust_printer(writer: Box<io::Writer>) -> State<'static> {
67     static NO_ANN: NoAnn = NoAnn;
68     rust_printer_annotated(writer, &NO_ANN)
69 }
70
71 pub fn rust_printer_annotated<'a>(writer: Box<io::Writer>,
72                                   ann: &'a PpAnn) -> State<'a> {
73     State {
74         s: pp::mk_printer(writer, default_columns),
75         cm: None,
76         comments: None,
77         literals: None,
78         cur_cmnt_and_lit: CurrentCommentAndLiteral {
79             cur_cmnt: 0,
80             cur_lit: 0
81         },
82         boxes: Vec::new(),
83         ann: ann
84     }
85 }
86
87 pub static indent_unit: uint = 4u;
88
89 pub static default_columns: uint = 78u;
90
91 /// Requires you to pass an input filename and reader so that
92 /// it can scan the input text for comments and literals to
93 /// copy forward.
94 pub fn print_crate<'a>(cm: &'a CodeMap,
95                        span_diagnostic: &diagnostic::SpanHandler,
96                        krate: &ast::Crate,
97                        filename: String,
98                        input: &mut io::Reader,
99                        out: Box<io::Writer>,
100                        ann: &'a PpAnn,
101                        is_expanded: bool) -> IoResult<()> {
102     let (cmnts, lits) = comments::gather_comments_and_literals(
103         span_diagnostic,
104         filename,
105         input
106     );
107     let mut s = State {
108         s: pp::mk_printer(out, default_columns),
109         cm: Some(cm),
110         comments: Some(cmnts),
111         // If the code is post expansion, don't use the table of
112         // literals, since it doesn't correspond with the literals
113         // in the AST anymore.
114         literals: if is_expanded {
115             None
116         } else {
117             Some(lits)
118         },
119         cur_cmnt_and_lit: CurrentCommentAndLiteral {
120             cur_cmnt: 0,
121             cur_lit: 0
122         },
123         boxes: Vec::new(),
124         ann: ann
125     };
126     try!(s.print_mod(&krate.module, krate.attrs.as_slice()));
127     try!(s.print_remaining_comments());
128     eof(&mut s.s)
129 }
130
131 pub fn to_string(f: |&mut State| -> IoResult<()>) -> String {
132     let mut s = rust_printer(box MemWriter::new());
133     f(&mut s).unwrap();
134     eof(&mut s.s).unwrap();
135     unsafe {
136         // FIXME(pcwalton): A nasty function to extract the string from an `io::Writer`
137         // that we "know" to be a `MemWriter` that works around the lack of checked
138         // downcasts.
139         let (_, wr): (uint, Box<MemWriter>) = mem::transmute_copy(&s.s.out);
140         let result =
141             str::from_utf8_owned(Vec::from_slice(wr.get_ref())).unwrap();
142         mem::forget(wr);
143         result.to_string()
144     }
145 }
146
147 pub fn ty_to_string(ty: &ast::Ty) -> String {
148     to_string(|s| s.print_type(ty))
149 }
150
151 pub fn pat_to_string(pat: &ast::Pat) -> String {
152     to_string(|s| s.print_pat(pat))
153 }
154
155 pub fn expr_to_string(e: &ast::Expr) -> String {
156     to_string(|s| s.print_expr(e))
157 }
158
159 pub fn lifetime_to_string(e: &ast::Lifetime) -> String {
160     to_string(|s| s.print_lifetime(e))
161 }
162
163 pub fn tt_to_string(tt: &ast::TokenTree) -> String {
164     to_string(|s| s.print_tt(tt))
165 }
166
167 pub fn tts_to_string(tts: &[ast::TokenTree]) -> String {
168     to_string(|s| s.print_tts(tts))
169 }
170
171 pub fn stmt_to_string(stmt: &ast::Stmt) -> String {
172     to_string(|s| s.print_stmt(stmt))
173 }
174
175 pub fn item_to_string(i: &ast::Item) -> String {
176     to_string(|s| s.print_item(i))
177 }
178
179 pub fn generics_to_string(generics: &ast::Generics) -> String {
180     to_string(|s| s.print_generics(generics))
181 }
182
183 pub fn ty_method_to_string(p: &ast::TypeMethod) -> String {
184     to_string(|s| s.print_ty_method(p))
185 }
186
187 pub fn method_to_string(p: &ast::Method) -> String {
188     to_string(|s| s.print_method(p))
189 }
190
191 pub fn fn_block_to_string(p: &ast::FnDecl) -> String {
192     to_string(|s| s.print_fn_block_args(p))
193 }
194
195 pub fn path_to_string(p: &ast::Path) -> String {
196     to_string(|s| s.print_path(p, false))
197 }
198
199 pub fn ident_to_string(id: &ast::Ident) -> String {
200     to_string(|s| s.print_ident(*id))
201 }
202
203 pub fn fun_to_string(decl: &ast::FnDecl, fn_style: ast::FnStyle, name: ast::Ident,
204                   opt_explicit_self: Option<ast::ExplicitSelf_>,
205                   generics: &ast::Generics) -> String {
206     to_string(|s| {
207         try!(s.print_fn(decl, Some(fn_style), abi::Rust,
208                         name, generics, opt_explicit_self, ast::Inherited));
209         try!(s.end()); // Close the head box
210         s.end() // Close the outer box
211     })
212 }
213
214 pub fn block_to_string(blk: &ast::Block) -> String {
215     to_string(|s| {
216         // containing cbox, will be closed by print-block at }
217         try!(s.cbox(indent_unit));
218         // head-ibox, will be closed by print-block after {
219         try!(s.ibox(0u));
220         s.print_block(blk)
221     })
222 }
223
224 pub fn meta_item_to_string(mi: &ast::MetaItem) -> String {
225     to_string(|s| s.print_meta_item(mi))
226 }
227
228 pub fn attribute_to_string(attr: &ast::Attribute) -> String {
229     to_string(|s| s.print_attribute(attr))
230 }
231
232 pub fn lit_to_string(l: &ast::Lit) -> String {
233     to_string(|s| s.print_literal(l))
234 }
235
236 pub fn explicit_self_to_string(explicit_self: ast::ExplicitSelf_) -> String {
237     to_string(|s| s.print_explicit_self(explicit_self, ast::MutImmutable).map(|_| {}))
238 }
239
240 pub fn variant_to_string(var: &ast::Variant) -> String {
241     to_string(|s| s.print_variant(var))
242 }
243
244 pub fn arg_to_string(arg: &ast::Arg) -> String {
245     to_string(|s| s.print_arg(arg))
246 }
247
248 pub fn mac_to_string(arg: &ast::Mac) -> String {
249     to_string(|s| s.print_mac(arg))
250 }
251
252 pub fn visibility_qualified(vis: ast::Visibility, s: &str) -> String {
253     match vis {
254         ast::Public => format!("pub {}", s),
255         ast::Inherited => s.to_string()
256     }
257 }
258
259 fn needs_parentheses(expr: &ast::Expr) -> bool {
260     match expr.node {
261         ast::ExprAssign(..) | ast::ExprBinary(..) |
262         ast::ExprFnBlock(..) | ast::ExprProc(..) |
263         ast::ExprAssignOp(..) | 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, ref generics, ref explicit_self, fn_style, decl, body, vis) => {
1009                 try!(self.print_fn(&*decl, Some(fn_style), abi::Rust,
1010                                    ident, generics, Some(explicit_self.node),
1011                                    vis));
1012                 try!(word(&mut self.s, " "));
1013                 self.print_block_with_attrs(&*body, meth.attrs.as_slice())
1014             },
1015             ast::MethMac(codemap::Spanned { node: ast::MacInvocTT(ref pth, ref tts, _),
1016                                             ..}) => {
1017                 // code copied from ItemMac:
1018                 try!(self.print_path(pth, false));
1019                 try!(word(&mut self.s, "! "));
1020                 try!(self.cbox(indent_unit));
1021                 try!(self.popen());
1022                 try!(self.print_tts(tts.as_slice()));
1023                 try!(self.pclose());
1024                 self.end()
1025             }
1026         }
1027     }
1028
1029     pub fn print_outer_attributes(&mut self,
1030                                   attrs: &[ast::Attribute]) -> IoResult<()> {
1031         let mut count = 0u;
1032         for attr in attrs.iter() {
1033             match attr.node.style {
1034                 ast::AttrOuter => {
1035                     try!(self.print_attribute(attr));
1036                     count += 1;
1037                 }
1038                 _ => {/* fallthrough */ }
1039             }
1040         }
1041         if count > 0 {
1042             try!(self.hardbreak_if_not_bol());
1043         }
1044         Ok(())
1045     }
1046
1047     pub fn print_inner_attributes(&mut self,
1048                                   attrs: &[ast::Attribute]) -> IoResult<()> {
1049         let mut count = 0u;
1050         for attr in attrs.iter() {
1051             match attr.node.style {
1052                 ast::AttrInner => {
1053                     try!(self.print_attribute(attr));
1054                     count += 1;
1055                 }
1056                 _ => {/* fallthrough */ }
1057             }
1058         }
1059         if count > 0 {
1060             try!(self.hardbreak_if_not_bol());
1061         }
1062         Ok(())
1063     }
1064
1065     pub fn print_attribute(&mut self, attr: &ast::Attribute) -> IoResult<()> {
1066         try!(self.hardbreak_if_not_bol());
1067         try!(self.maybe_print_comment(attr.span.lo));
1068         if attr.node.is_sugared_doc {
1069             word(&mut self.s, attr.value_str().unwrap().get())
1070         } else {
1071             match attr.node.style {
1072                 ast::AttrInner => try!(word(&mut self.s, "#![")),
1073                 ast::AttrOuter => try!(word(&mut self.s, "#[")),
1074             }
1075             try!(self.print_meta_item(&*attr.meta()));
1076             word(&mut self.s, "]")
1077         }
1078     }
1079
1080
1081     pub fn print_stmt(&mut self, st: &ast::Stmt) -> IoResult<()> {
1082         try!(self.maybe_print_comment(st.span.lo));
1083         match st.node {
1084             ast::StmtDecl(ref decl, _) => {
1085                 try!(self.print_decl(&**decl));
1086             }
1087             ast::StmtExpr(ref expr, _) => {
1088                 try!(self.space_if_not_bol());
1089                 try!(self.print_expr(&**expr));
1090             }
1091             ast::StmtSemi(ref expr, _) => {
1092                 try!(self.space_if_not_bol());
1093                 try!(self.print_expr(&**expr));
1094                 try!(word(&mut self.s, ";"));
1095             }
1096             ast::StmtMac(ref mac, semi) => {
1097                 try!(self.space_if_not_bol());
1098                 try!(self.print_mac(mac));
1099                 if semi {
1100                     try!(word(&mut self.s, ";"));
1101                 }
1102             }
1103         }
1104         if parse::classify::stmt_ends_with_semi(st) {
1105             try!(word(&mut self.s, ";"));
1106         }
1107         self.maybe_print_trailing_comment(st.span, None)
1108     }
1109
1110     pub fn print_block(&mut self, blk: &ast::Block) -> IoResult<()> {
1111         self.print_block_with_attrs(blk, &[])
1112     }
1113
1114     pub fn print_block_unclosed(&mut self, blk: &ast::Block) -> IoResult<()> {
1115         self.print_block_unclosed_indent(blk, indent_unit)
1116     }
1117
1118     pub fn print_block_unclosed_indent(&mut self, blk: &ast::Block,
1119                                        indented: uint) -> IoResult<()> {
1120         self.print_block_maybe_unclosed(blk, indented, &[], false)
1121     }
1122
1123     pub fn print_block_with_attrs(&mut self,
1124                                   blk: &ast::Block,
1125                                   attrs: &[ast::Attribute]) -> IoResult<()> {
1126         self.print_block_maybe_unclosed(blk, indent_unit, attrs, true)
1127     }
1128
1129     pub fn print_block_maybe_unclosed(&mut self,
1130                                       blk: &ast::Block,
1131                                       indented: uint,
1132                                       attrs: &[ast::Attribute],
1133                                       close_box: bool) -> IoResult<()> {
1134         match blk.rules {
1135             ast::UnsafeBlock(..) => try!(self.word_space("unsafe")),
1136             ast::DefaultBlock => ()
1137         }
1138         try!(self.maybe_print_comment(blk.span.lo));
1139         try!(self.ann.pre(self, NodeBlock(blk)));
1140         try!(self.bopen());
1141
1142         try!(self.print_inner_attributes(attrs));
1143
1144         for vi in blk.view_items.iter() {
1145             try!(self.print_view_item(vi));
1146         }
1147         for st in blk.stmts.iter() {
1148             try!(self.print_stmt(&**st));
1149         }
1150         match blk.expr {
1151             Some(ref expr) => {
1152                 try!(self.space_if_not_bol());
1153                 try!(self.print_expr(&**expr));
1154                 try!(self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi)));
1155             }
1156             _ => ()
1157         }
1158         try!(self.bclose_maybe_open(blk.span, indented, close_box));
1159         self.ann.post(self, NodeBlock(blk))
1160     }
1161
1162     fn print_else(&mut self, els: Option<Gc<ast::Expr>>) -> IoResult<()> {
1163         match els {
1164             Some(_else) => {
1165                 match _else.node {
1166                     // "another else-if"
1167                     ast::ExprIf(ref i, ref t, e) => {
1168                         try!(self.cbox(indent_unit - 1u));
1169                         try!(self.ibox(0u));
1170                         try!(word(&mut self.s, " else if "));
1171                         try!(self.print_expr(&**i));
1172                         try!(space(&mut self.s));
1173                         try!(self.print_block(&**t));
1174                         self.print_else(e)
1175                     }
1176                     // "final else"
1177                     ast::ExprBlock(ref b) => {
1178                         try!(self.cbox(indent_unit - 1u));
1179                         try!(self.ibox(0u));
1180                         try!(word(&mut self.s, " else "));
1181                         self.print_block(&**b)
1182                     }
1183                     // BLEAH, constraints would be great here
1184                     _ => {
1185                         fail!("print_if saw if with weird alternative");
1186                     }
1187                 }
1188             }
1189             _ => Ok(())
1190         }
1191     }
1192
1193     pub fn print_if(&mut self, test: &ast::Expr, blk: &ast::Block,
1194                     elseopt: Option<Gc<ast::Expr>>, chk: bool) -> IoResult<()> {
1195         try!(self.head("if"));
1196         if chk { try!(self.word_nbsp("check")); }
1197         try!(self.print_expr(test));
1198         try!(space(&mut self.s));
1199         try!(self.print_block(blk));
1200         self.print_else(elseopt)
1201     }
1202
1203     pub fn print_mac(&mut self, m: &ast::Mac) -> IoResult<()> {
1204         match m.node {
1205             // I think it's reasonable to hide the ctxt here:
1206             ast::MacInvocTT(ref pth, ref tts, _) => {
1207                 try!(self.print_path(pth, false));
1208                 try!(word(&mut self.s, "!"));
1209                 try!(self.popen());
1210                 try!(self.print_tts(tts.as_slice()));
1211                 self.pclose()
1212             }
1213         }
1214     }
1215
1216     pub fn print_expr_vstore(&mut self, t: ast::ExprVstore) -> IoResult<()> {
1217         match t {
1218             ast::ExprVstoreUniq => word(&mut self.s, "box "),
1219             ast::ExprVstoreSlice => word(&mut self.s, "&"),
1220             ast::ExprVstoreMutSlice => {
1221                 try!(word(&mut self.s, "&"));
1222                 word(&mut self.s, "mut")
1223             }
1224         }
1225     }
1226
1227     fn print_call_post(&mut self, args: &[Gc<ast::Expr>]) -> IoResult<()> {
1228         try!(self.popen());
1229         try!(self.commasep_exprs(Inconsistent, args));
1230         self.pclose()
1231     }
1232
1233     pub fn print_expr_maybe_paren(&mut self, expr: &ast::Expr) -> IoResult<()> {
1234         let needs_par = needs_parentheses(expr);
1235         if needs_par {
1236             try!(self.popen());
1237         }
1238         try!(self.print_expr(expr));
1239         if needs_par {
1240             try!(self.pclose());
1241         }
1242         Ok(())
1243     }
1244
1245     pub fn print_expr(&mut self, expr: &ast::Expr) -> IoResult<()> {
1246         try!(self.maybe_print_comment(expr.span.lo));
1247         try!(self.ibox(indent_unit));
1248         try!(self.ann.pre(self, NodeExpr(expr)));
1249         match expr.node {
1250             ast::ExprVstore(ref e, v) => {
1251                 try!(self.print_expr_vstore(v));
1252                 try!(self.print_expr(&**e));
1253             },
1254             ast::ExprBox(ref p, ref e) => {
1255                 try!(word(&mut self.s, "box"));
1256                 try!(word(&mut self.s, "("));
1257                 try!(self.print_expr(&**p));
1258                 try!(self.word_space(")"));
1259                 try!(self.print_expr(&**e));
1260             }
1261             ast::ExprVec(ref exprs) => {
1262                 try!(self.ibox(indent_unit));
1263                 try!(word(&mut self.s, "["));
1264                 try!(self.commasep_exprs(Inconsistent, exprs.as_slice()));
1265                 try!(word(&mut self.s, "]"));
1266                 try!(self.end());
1267             }
1268
1269             ast::ExprRepeat(ref element, ref count) => {
1270                 try!(self.ibox(indent_unit));
1271                 try!(word(&mut self.s, "["));
1272                 try!(self.print_expr(&**element));
1273                 try!(word(&mut self.s, ","));
1274                 try!(word(&mut self.s, ".."));
1275                 try!(self.print_expr(&**count));
1276                 try!(word(&mut self.s, "]"));
1277                 try!(self.end());
1278             }
1279
1280             ast::ExprStruct(ref path, ref fields, wth) => {
1281                 try!(self.print_path(path, true));
1282                 try!(word(&mut self.s, "{"));
1283                 try!(self.commasep_cmnt(
1284                     Consistent,
1285                     fields.as_slice(),
1286                     |s, field| {
1287                         try!(s.ibox(indent_unit));
1288                         try!(s.print_ident(field.ident.node));
1289                         try!(s.word_space(":"));
1290                         try!(s.print_expr(&*field.expr));
1291                         s.end()
1292                     },
1293                     |f| f.span));
1294                 match wth {
1295                     Some(ref expr) => {
1296                         try!(self.ibox(indent_unit));
1297                         if !fields.is_empty() {
1298                             try!(word(&mut self.s, ","));
1299                             try!(space(&mut self.s));
1300                         }
1301                         try!(word(&mut self.s, ".."));
1302                         try!(self.print_expr(&**expr));
1303                         try!(self.end());
1304                     }
1305                     _ => try!(word(&mut self.s, ","))
1306                 }
1307                 try!(word(&mut self.s, "}"));
1308             }
1309             ast::ExprTup(ref exprs) => {
1310                 try!(self.popen());
1311                 try!(self.commasep_exprs(Inconsistent, exprs.as_slice()));
1312                 if exprs.len() == 1 {
1313                     try!(word(&mut self.s, ","));
1314                 }
1315                 try!(self.pclose());
1316             }
1317             ast::ExprCall(ref func, ref args) => {
1318                 try!(self.print_expr_maybe_paren(&**func));
1319                 try!(self.print_call_post(args.as_slice()));
1320             }
1321             ast::ExprMethodCall(ident, ref tys, ref args) => {
1322                 let base_args = args.slice_from(1);
1323                 try!(self.print_expr(&**args.get(0)));
1324                 try!(word(&mut self.s, "."));
1325                 try!(self.print_ident(ident.node));
1326                 if tys.len() > 0u {
1327                     try!(word(&mut self.s, "::<"));
1328                     try!(self.commasep(Inconsistent, tys.as_slice(),
1329                                        |s, ty| s.print_type_ref(ty)));
1330                     try!(word(&mut self.s, ">"));
1331                 }
1332                 try!(self.print_call_post(base_args));
1333             }
1334             ast::ExprBinary(op, ref lhs, ref rhs) => {
1335                 try!(self.print_expr(&**lhs));
1336                 try!(space(&mut self.s));
1337                 try!(self.word_space(ast_util::binop_to_string(op)));
1338                 try!(self.print_expr(&**rhs));
1339             }
1340             ast::ExprUnary(op, ref expr) => {
1341                 try!(word(&mut self.s, ast_util::unop_to_string(op)));
1342                 try!(self.print_expr_maybe_paren(&**expr));
1343             }
1344             ast::ExprAddrOf(m, ref expr) => {
1345                 try!(word(&mut self.s, "&"));
1346                 try!(self.print_mutability(m));
1347                 try!(self.print_expr_maybe_paren(&**expr));
1348             }
1349             ast::ExprLit(ref lit) => try!(self.print_literal(&**lit)),
1350             ast::ExprCast(ref expr, ref ty) => {
1351                 try!(self.print_expr(&**expr));
1352                 try!(space(&mut self.s));
1353                 try!(self.word_space("as"));
1354                 try!(self.print_type(&**ty));
1355             }
1356             ast::ExprIf(ref test, ref blk, elseopt) => {
1357                 try!(self.print_if(&**test, &**blk, elseopt, false));
1358             }
1359             ast::ExprWhile(ref test, ref blk) => {
1360                 try!(self.head("while"));
1361                 try!(self.print_expr(&**test));
1362                 try!(space(&mut self.s));
1363                 try!(self.print_block(&**blk));
1364             }
1365             ast::ExprForLoop(ref pat, ref iter, ref blk, opt_ident) => {
1366                 for ident in opt_ident.iter() {
1367                     try!(self.print_ident(*ident));
1368                     try!(self.word_space(":"));
1369                 }
1370                 try!(self.head("for"));
1371                 try!(self.print_pat(&**pat));
1372                 try!(space(&mut self.s));
1373                 try!(self.word_space("in"));
1374                 try!(self.print_expr(&**iter));
1375                 try!(space(&mut self.s));
1376                 try!(self.print_block(&**blk));
1377             }
1378             ast::ExprLoop(ref blk, opt_ident) => {
1379                 for ident in opt_ident.iter() {
1380                     try!(self.print_ident(*ident));
1381                     try!(self.word_space(":"));
1382                 }
1383                 try!(self.head("loop"));
1384                 try!(space(&mut self.s));
1385                 try!(self.print_block(&**blk));
1386             }
1387             ast::ExprMatch(ref expr, ref arms) => {
1388                 try!(self.cbox(indent_unit));
1389                 try!(self.ibox(4));
1390                 try!(self.word_nbsp("match"));
1391                 try!(self.print_expr(&**expr));
1392                 try!(space(&mut self.s));
1393                 try!(self.bopen());
1394                 let len = arms.len();
1395                 for (i, arm) in arms.iter().enumerate() {
1396                     // I have no idea why this check is necessary, but here it
1397                     // is :(
1398                     if arm.attrs.is_empty() {
1399                         try!(space(&mut self.s));
1400                     }
1401                     try!(self.cbox(indent_unit));
1402                     try!(self.ibox(0u));
1403                     try!(self.print_outer_attributes(arm.attrs.as_slice()));
1404                     let mut first = true;
1405                     for p in arm.pats.iter() {
1406                         if first {
1407                             first = false;
1408                         } else {
1409                             try!(space(&mut self.s));
1410                             try!(self.word_space("|"));
1411                         }
1412                         try!(self.print_pat(&**p));
1413                     }
1414                     try!(space(&mut self.s));
1415                     match arm.guard {
1416                         Some(ref e) => {
1417                             try!(self.word_space("if"));
1418                             try!(self.print_expr(&**e));
1419                             try!(space(&mut self.s));
1420                         }
1421                         None => ()
1422                     }
1423                     try!(self.word_space("=>"));
1424
1425                     match arm.body.node {
1426                         ast::ExprBlock(ref blk) => {
1427                             // the block will close the pattern's ibox
1428                             try!(self.print_block_unclosed_indent(&**blk,
1429                                                                   indent_unit));
1430                         }
1431                         _ => {
1432                             try!(self.end()); // close the ibox for the pattern
1433                             try!(self.print_expr(&*arm.body));
1434                         }
1435                     }
1436                     if !expr_is_simple_block(expr.clone())
1437                         && i < len - 1 {
1438                         try!(word(&mut self.s, ","));
1439                     }
1440                     try!(self.end()); // close enclosing cbox
1441                 }
1442                 try!(self.bclose_(expr.span, indent_unit));
1443             }
1444             ast::ExprFnBlock(ref decl, ref body) => {
1445                 // in do/for blocks we don't want to show an empty
1446                 // argument list, but at this point we don't know which
1447                 // we are inside.
1448                 //
1449                 // if !decl.inputs.is_empty() {
1450                 try!(self.print_fn_block_args(&**decl));
1451                 try!(space(&mut self.s));
1452                 // }
1453
1454                 if !body.stmts.is_empty() || !body.expr.is_some() {
1455                     try!(self.print_block_unclosed(&**body));
1456                 } else {
1457                     // we extract the block, so as not to create another set of boxes
1458                     match body.expr.unwrap().node {
1459                         ast::ExprBlock(ref blk) => {
1460                             try!(self.print_block_unclosed(&**blk));
1461                         }
1462                         _ => {
1463                             // this is a bare expression
1464                             try!(self.print_expr(&*body.expr.unwrap()));
1465                             try!(self.end()); // need to close a box
1466                         }
1467                     }
1468                 }
1469                 // a box will be closed by print_expr, but we didn't want an overall
1470                 // wrapper so we closed the corresponding opening. so create an
1471                 // empty box to satisfy the close.
1472                 try!(self.ibox(0));
1473             }
1474             ast::ExprProc(ref decl, ref body) => {
1475                 // in do/for blocks we don't want to show an empty
1476                 // argument list, but at this point we don't know which
1477                 // we are inside.
1478                 //
1479                 // if !decl.inputs.is_empty() {
1480                 try!(self.print_proc_args(&**decl));
1481                 try!(space(&mut self.s));
1482                 // }
1483                 assert!(body.stmts.is_empty());
1484                 assert!(body.expr.is_some());
1485                 // we extract the block, so as not to create another set of boxes
1486                 match body.expr.unwrap().node {
1487                     ast::ExprBlock(ref blk) => {
1488                         try!(self.print_block_unclosed(&**blk));
1489                     }
1490                     _ => {
1491                         // this is a bare expression
1492                         try!(self.print_expr(&*body.expr.unwrap()));
1493                         try!(self.end()); // need to close a box
1494                     }
1495                 }
1496                 // a box will be closed by print_expr, but we didn't want an overall
1497                 // wrapper so we closed the corresponding opening. so create an
1498                 // empty box to satisfy the close.
1499                 try!(self.ibox(0));
1500             }
1501             ast::ExprBlock(ref blk) => {
1502                 // containing cbox, will be closed by print-block at }
1503                 try!(self.cbox(indent_unit));
1504                 // head-box, will be closed by print-block after {
1505                 try!(self.ibox(0u));
1506                 try!(self.print_block(&**blk));
1507             }
1508             ast::ExprAssign(ref lhs, ref rhs) => {
1509                 try!(self.print_expr(&**lhs));
1510                 try!(space(&mut self.s));
1511                 try!(self.word_space("="));
1512                 try!(self.print_expr(&**rhs));
1513             }
1514             ast::ExprAssignOp(op, ref lhs, ref rhs) => {
1515                 try!(self.print_expr(&**lhs));
1516                 try!(space(&mut self.s));
1517                 try!(word(&mut self.s, ast_util::binop_to_string(op)));
1518                 try!(self.word_space("="));
1519                 try!(self.print_expr(&**rhs));
1520             }
1521             ast::ExprField(ref expr, id, ref tys) => {
1522                 try!(self.print_expr(&**expr));
1523                 try!(word(&mut self.s, "."));
1524                 try!(self.print_ident(id.node));
1525                 if tys.len() > 0u {
1526                     try!(word(&mut self.s, "::<"));
1527                     try!(self.commasep(
1528                         Inconsistent, tys.as_slice(),
1529                         |s, ty| s.print_type_ref(ty)));
1530                     try!(word(&mut self.s, ">"));
1531                 }
1532             }
1533             ast::ExprIndex(ref expr, ref index) => {
1534                 try!(self.print_expr(&**expr));
1535                 try!(word(&mut self.s, "["));
1536                 try!(self.print_expr(&**index));
1537                 try!(word(&mut self.s, "]"));
1538             }
1539             ast::ExprPath(ref path) => try!(self.print_path(path, true)),
1540             ast::ExprBreak(opt_ident) => {
1541                 try!(word(&mut self.s, "break"));
1542                 try!(space(&mut self.s));
1543                 for ident in opt_ident.iter() {
1544                     try!(self.print_ident(*ident));
1545                     try!(space(&mut self.s));
1546                 }
1547             }
1548             ast::ExprAgain(opt_ident) => {
1549                 try!(word(&mut self.s, "continue"));
1550                 try!(space(&mut self.s));
1551                 for ident in opt_ident.iter() {
1552                     try!(self.print_ident(*ident));
1553                     try!(space(&mut self.s))
1554                 }
1555             }
1556             ast::ExprRet(ref result) => {
1557                 try!(word(&mut self.s, "return"));
1558                 match *result {
1559                     Some(ref expr) => {
1560                         try!(word(&mut self.s, " "));
1561                         try!(self.print_expr(&**expr));
1562                     }
1563                     _ => ()
1564                 }
1565             }
1566             ast::ExprInlineAsm(ref a) => {
1567                 if a.volatile {
1568                     try!(word(&mut self.s, "__volatile__ asm!"));
1569                 } else {
1570                     try!(word(&mut self.s, "asm!"));
1571                 }
1572                 try!(self.popen());
1573                 try!(self.print_string(a.asm.get(), a.asm_str_style));
1574                 try!(self.word_space(":"));
1575
1576                 try!(self.commasep(Inconsistent, a.outputs.as_slice(),
1577                                    |s, &(ref co, ref o)| {
1578                     try!(s.print_string(co.get(), ast::CookedStr));
1579                     try!(s.popen());
1580                     try!(s.print_expr(&**o));
1581                     try!(s.pclose());
1582                     Ok(())
1583                 }));
1584                 try!(space(&mut self.s));
1585                 try!(self.word_space(":"));
1586
1587                 try!(self.commasep(Inconsistent, a.inputs.as_slice(),
1588                                    |s, &(ref co, ref o)| {
1589                     try!(s.print_string(co.get(), ast::CookedStr));
1590                     try!(s.popen());
1591                     try!(s.print_expr(&**o));
1592                     try!(s.pclose());
1593                     Ok(())
1594                 }));
1595                 try!(space(&mut self.s));
1596                 try!(self.word_space(":"));
1597
1598                 try!(self.print_string(a.clobbers.get(), ast::CookedStr));
1599                 try!(self.pclose());
1600             }
1601             ast::ExprMac(ref m) => try!(self.print_mac(m)),
1602             ast::ExprParen(ref e) => {
1603                 try!(self.popen());
1604                 try!(self.print_expr(&**e));
1605                 try!(self.pclose());
1606             }
1607         }
1608         try!(self.ann.post(self, NodeExpr(expr)));
1609         self.end()
1610     }
1611
1612     pub fn print_local_decl(&mut self, loc: &ast::Local) -> IoResult<()> {
1613         try!(self.print_pat(&*loc.pat));
1614         match loc.ty.node {
1615             ast::TyInfer => Ok(()),
1616             _ => {
1617                 try!(self.word_space(":"));
1618                 self.print_type(&*loc.ty)
1619             }
1620         }
1621     }
1622
1623     pub fn print_decl(&mut self, decl: &ast::Decl) -> IoResult<()> {
1624         try!(self.maybe_print_comment(decl.span.lo));
1625         match decl.node {
1626             ast::DeclLocal(ref loc) => {
1627                 try!(self.space_if_not_bol());
1628                 try!(self.ibox(indent_unit));
1629                 try!(self.word_nbsp("let"));
1630
1631                 try!(self.ibox(indent_unit));
1632                 try!(self.print_local_decl(&**loc));
1633                 try!(self.end());
1634                 match loc.init {
1635                     Some(ref init) => {
1636                         try!(self.nbsp());
1637                         try!(self.word_space("="));
1638                         try!(self.print_expr(&**init));
1639                     }
1640                     _ => {}
1641                 }
1642                 self.end()
1643             }
1644             ast::DeclItem(ref item) => self.print_item(&**item)
1645         }
1646     }
1647
1648     pub fn print_ident(&mut self, ident: ast::Ident) -> IoResult<()> {
1649         word(&mut self.s, token::get_ident(ident).get())
1650     }
1651
1652     pub fn print_name(&mut self, name: ast::Name) -> IoResult<()> {
1653         word(&mut self.s, token::get_name(name).get())
1654     }
1655
1656     pub fn print_for_decl(&mut self, loc: &ast::Local,
1657                           coll: &ast::Expr) -> IoResult<()> {
1658         try!(self.print_local_decl(loc));
1659         try!(space(&mut self.s));
1660         try!(self.word_space("in"));
1661         self.print_expr(coll)
1662     }
1663
1664     fn print_path_(&mut self,
1665                    path: &ast::Path,
1666                    colons_before_params: bool,
1667                    opt_bounds: &Option<OwnedSlice<ast::TyParamBound>>)
1668         -> IoResult<()> {
1669         try!(self.maybe_print_comment(path.span.lo));
1670         if path.global {
1671             try!(word(&mut self.s, "::"));
1672         }
1673
1674         let mut first = true;
1675         for segment in path.segments.iter() {
1676             if first {
1677                 first = false
1678             } else {
1679                 try!(word(&mut self.s, "::"))
1680             }
1681
1682             try!(self.print_ident(segment.identifier));
1683
1684             if !segment.lifetimes.is_empty() || !segment.types.is_empty() {
1685                 if colons_before_params {
1686                     try!(word(&mut self.s, "::"))
1687                 }
1688                 try!(word(&mut self.s, "<"));
1689
1690                 let mut comma = false;
1691                 for lifetime in segment.lifetimes.iter() {
1692                     if comma {
1693                         try!(self.word_space(","))
1694                     }
1695                     try!(self.print_lifetime(lifetime));
1696                     comma = true;
1697                 }
1698
1699                 if !segment.types.is_empty() {
1700                     if comma {
1701                         try!(self.word_space(","))
1702                     }
1703                     try!(self.commasep(
1704                         Inconsistent,
1705                         segment.types.as_slice(),
1706                         |s, ty| s.print_type_ref(ty)));
1707                 }
1708
1709                 try!(word(&mut self.s, ">"))
1710             }
1711         }
1712
1713         match *opt_bounds {
1714             None => Ok(()),
1715             Some(ref bounds) => self.print_bounds(&None, bounds, true, true),
1716         }
1717     }
1718
1719     fn print_path(&mut self, path: &ast::Path,
1720                   colons_before_params: bool) -> IoResult<()> {
1721         self.print_path_(path, colons_before_params, &None)
1722     }
1723
1724     fn print_bounded_path(&mut self, path: &ast::Path,
1725                           bounds: &Option<OwnedSlice<ast::TyParamBound>>)
1726         -> IoResult<()> {
1727         self.print_path_(path, false, bounds)
1728     }
1729
1730     pub fn print_pat(&mut self, pat: &ast::Pat) -> IoResult<()> {
1731         try!(self.maybe_print_comment(pat.span.lo));
1732         try!(self.ann.pre(self, NodePat(pat)));
1733         /* Pat isn't normalized, but the beauty of it
1734          is that it doesn't matter */
1735         match pat.node {
1736             ast::PatWild => try!(word(&mut self.s, "_")),
1737             ast::PatWildMulti => try!(word(&mut self.s, "..")),
1738             ast::PatIdent(binding_mode, ref path1, sub) => {
1739                 match binding_mode {
1740                     ast::BindByRef(mutbl) => {
1741                         try!(self.word_nbsp("ref"));
1742                         try!(self.print_mutability(mutbl));
1743                     }
1744                     ast::BindByValue(ast::MutImmutable) => {}
1745                     ast::BindByValue(ast::MutMutable) => {
1746                         try!(self.word_nbsp("mut"));
1747                     }
1748                 }
1749                 try!(self.print_ident(path1.node));
1750                 match sub {
1751                     Some(ref p) => {
1752                         try!(word(&mut self.s, "@"));
1753                         try!(self.print_pat(&**p));
1754                     }
1755                     None => ()
1756                 }
1757             }
1758             ast::PatEnum(ref path, ref args_) => {
1759                 try!(self.print_path(path, true));
1760                 match *args_ {
1761                     None => try!(word(&mut self.s, "(..)")),
1762                     Some(ref args) => {
1763                         if !args.is_empty() {
1764                             try!(self.popen());
1765                             try!(self.commasep(Inconsistent, args.as_slice(),
1766                                               |s, p| s.print_pat(&**p)));
1767                             try!(self.pclose());
1768                         }
1769                     }
1770                 }
1771             }
1772             ast::PatStruct(ref path, ref fields, etc) => {
1773                 try!(self.print_path(path, true));
1774                 try!(self.nbsp());
1775                 try!(self.word_space("{"));
1776                 try!(self.commasep_cmnt(
1777                     Consistent, fields.as_slice(),
1778                     |s, f| {
1779                         try!(s.cbox(indent_unit));
1780                         try!(s.print_ident(f.ident));
1781                         try!(s.word_nbsp(":"));
1782                         try!(s.print_pat(&*f.pat));
1783                         s.end()
1784                     },
1785                     |f| f.pat.span));
1786                 if etc {
1787                     if fields.len() != 0u { try!(self.word_space(",")); }
1788                     try!(word(&mut self.s, ".."));
1789                 }
1790                 try!(space(&mut self.s));
1791                 try!(word(&mut self.s, "}"));
1792             }
1793             ast::PatTup(ref elts) => {
1794                 try!(self.popen());
1795                 try!(self.commasep(Inconsistent,
1796                                    elts.as_slice(),
1797                                    |s, p| s.print_pat(&**p)));
1798                 if elts.len() == 1 {
1799                     try!(word(&mut self.s, ","));
1800                 }
1801                 try!(self.pclose());
1802             }
1803             ast::PatBox(ref inner) => {
1804                 try!(word(&mut self.s, "box "));
1805                 try!(self.print_pat(&**inner));
1806             }
1807             ast::PatRegion(ref inner) => {
1808                 try!(word(&mut self.s, "&"));
1809                 try!(self.print_pat(&**inner));
1810             }
1811             ast::PatLit(ref e) => try!(self.print_expr(&**e)),
1812             ast::PatRange(ref begin, ref end) => {
1813                 try!(self.print_expr(&**begin));
1814                 try!(space(&mut self.s));
1815                 try!(word(&mut self.s, ".."));
1816                 try!(self.print_expr(&**end));
1817             }
1818             ast::PatVec(ref before, slice, ref after) => {
1819                 try!(word(&mut self.s, "["));
1820                 try!(self.commasep(Inconsistent,
1821                                    before.as_slice(),
1822                                    |s, p| s.print_pat(&**p)));
1823                 for p in slice.iter() {
1824                     if !before.is_empty() { try!(self.word_space(",")); }
1825                     match **p {
1826                         ast::Pat { node: ast::PatWildMulti, .. } => {
1827                             // this case is handled by print_pat
1828                         }
1829                         _ => try!(word(&mut self.s, "..")),
1830                     }
1831                     try!(self.print_pat(&**p));
1832                     if !after.is_empty() { try!(self.word_space(",")); }
1833                 }
1834                 try!(self.commasep(Inconsistent,
1835                                    after.as_slice(),
1836                                    |s, p| s.print_pat(&**p)));
1837                 try!(word(&mut self.s, "]"));
1838             }
1839             ast::PatMac(ref m) => try!(self.print_mac(m)),
1840         }
1841         self.ann.post(self, NodePat(pat))
1842     }
1843
1844     // Returns whether it printed anything
1845     fn print_explicit_self(&mut self,
1846                            explicit_self: ast::ExplicitSelf_,
1847                            mutbl: ast::Mutability) -> IoResult<bool> {
1848         try!(self.print_mutability(mutbl));
1849         match explicit_self {
1850             ast::SelfStatic => { return Ok(false); }
1851             ast::SelfValue(_) => {
1852                 try!(word(&mut self.s, "self"));
1853             }
1854             ast::SelfUniq(_) => {
1855                 try!(word(&mut self.s, "~self"));
1856             }
1857             ast::SelfRegion(ref lt, m, _) => {
1858                 try!(word(&mut self.s, "&"));
1859                 try!(self.print_opt_lifetime(lt));
1860                 try!(self.print_mutability(m));
1861                 try!(word(&mut self.s, "self"));
1862             }
1863         }
1864         return Ok(true);
1865     }
1866
1867     pub fn print_fn(&mut self,
1868                     decl: &ast::FnDecl,
1869                     fn_style: Option<ast::FnStyle>,
1870                     abi: abi::Abi,
1871                     name: ast::Ident,
1872                     generics: &ast::Generics,
1873                     opt_explicit_self: Option<ast::ExplicitSelf_>,
1874                     vis: ast::Visibility) -> IoResult<()> {
1875         try!(self.head(""));
1876         try!(self.print_fn_header_info(opt_explicit_self, fn_style, abi, vis));
1877         try!(self.nbsp());
1878         try!(self.print_ident(name));
1879         try!(self.print_generics(generics));
1880         self.print_fn_args_and_ret(decl, opt_explicit_self)
1881     }
1882
1883     pub fn print_fn_args(&mut self, decl: &ast::FnDecl,
1884                          opt_explicit_self: Option<ast::ExplicitSelf_>)
1885         -> IoResult<()> {
1886         // It is unfortunate to duplicate the commasep logic, but we want the
1887         // self type and the args all in the same box.
1888         try!(self.rbox(0u, Inconsistent));
1889         let mut first = true;
1890         for &explicit_self in opt_explicit_self.iter() {
1891             let m = match explicit_self {
1892                 ast::SelfStatic => ast::MutImmutable,
1893                 _ => match decl.inputs.get(0).pat.node {
1894                     ast::PatIdent(ast::BindByValue(m), _, _) => m,
1895                     _ => ast::MutImmutable
1896                 }
1897             };
1898             first = !try!(self.print_explicit_self(explicit_self, m));
1899         }
1900
1901         // HACK(eddyb) ignore the separately printed self argument.
1902         let args = if first {
1903             decl.inputs.as_slice()
1904         } else {
1905             decl.inputs.slice_from(1)
1906         };
1907
1908         for arg in args.iter() {
1909             if first { first = false; } else { try!(self.word_space(",")); }
1910             try!(self.print_arg(arg));
1911         }
1912
1913         self.end()
1914     }
1915
1916     pub fn print_fn_args_and_ret(&mut self, decl: &ast::FnDecl,
1917                                  opt_explicit_self: Option<ast::ExplicitSelf_>)
1918         -> IoResult<()> {
1919         try!(self.popen());
1920         try!(self.print_fn_args(decl, opt_explicit_self));
1921         if decl.variadic {
1922             try!(word(&mut self.s, ", ..."));
1923         }
1924         try!(self.pclose());
1925
1926         try!(self.maybe_print_comment(decl.output.span.lo));
1927         match decl.output.node {
1928             ast::TyNil => Ok(()),
1929             _ => {
1930                 try!(self.space_if_not_bol());
1931                 try!(self.word_space("->"));
1932                 self.print_type(&*decl.output)
1933             }
1934         }
1935     }
1936
1937     pub fn print_fn_block_args(&mut self,
1938                                decl: &ast::FnDecl) -> IoResult<()> {
1939         try!(word(&mut self.s, "|"));
1940         try!(self.print_fn_args(decl, None));
1941         try!(word(&mut self.s, "|"));
1942
1943         match decl.output.node {
1944             ast::TyInfer => {}
1945             _ => {
1946                 try!(self.space_if_not_bol());
1947                 try!(self.word_space("->"));
1948                 try!(self.print_type(&*decl.output));
1949             }
1950         }
1951
1952         self.maybe_print_comment(decl.output.span.lo)
1953     }
1954
1955     pub fn print_proc_args(&mut self, decl: &ast::FnDecl) -> IoResult<()> {
1956         try!(word(&mut self.s, "proc"));
1957         try!(word(&mut self.s, "("));
1958         try!(self.print_fn_args(decl, None));
1959         try!(word(&mut self.s, ")"));
1960
1961         match decl.output.node {
1962             ast::TyInfer => {}
1963             _ => {
1964                 try!(self.space_if_not_bol());
1965                 try!(self.word_space("->"));
1966                 try!(self.print_type(&*decl.output));
1967             }
1968         }
1969
1970         self.maybe_print_comment(decl.output.span.lo)
1971     }
1972
1973     pub fn print_bounds(&mut self,
1974                         region: &Option<ast::Lifetime>,
1975                         bounds: &OwnedSlice<ast::TyParamBound>,
1976                         print_colon_anyway: bool,
1977                         print_plus_before_bounds: bool)
1978                         -> IoResult<()> {
1979         let separator = if print_plus_before_bounds {
1980             "+"
1981         } else {
1982             ":"
1983         };
1984         if !bounds.is_empty() || region.is_some() {
1985             try!(word(&mut self.s, separator));
1986             let mut first = true;
1987             match *region {
1988                 Some(ref lt) => {
1989                     let token = token::get_name(lt.name);
1990                     if token.get() != "'static" {
1991                         try!(self.nbsp());
1992                         first = false;
1993                         try!(self.print_lifetime(lt));
1994                     }
1995                 }
1996                 None => {}
1997             }
1998             for bound in bounds.iter() {
1999                 try!(self.nbsp());
2000                 if first {
2001                     first = false;
2002                 } else {
2003                     try!(self.word_space("+"));
2004                 }
2005
2006                 try!(match *bound {
2007                     TraitTyParamBound(ref tref) => self.print_trait_ref(tref),
2008                     StaticRegionTyParamBound => word(&mut self.s, "'static"),
2009                     UnboxedFnTyParamBound(ref unboxed_function_type) => {
2010                         self.print_ty_fn(None,
2011                                          None,
2012                                          &None,
2013                                          ast::NormalFn,
2014                                          ast::Many,
2015                                          &*unboxed_function_type.decl,
2016                                          None,
2017                                          &None,
2018                                          None,
2019                                          None,
2020                                          true)
2021                     }
2022                     OtherRegionTyParamBound(_) => Ok(())
2023                 })
2024             }
2025             Ok(())
2026         } else if print_colon_anyway {
2027             word(&mut self.s, separator)
2028         } else {
2029             Ok(())
2030         }
2031     }
2032
2033     pub fn print_lifetime(&mut self,
2034                           lifetime: &ast::Lifetime) -> IoResult<()> {
2035         self.print_name(lifetime.name)
2036     }
2037
2038     pub fn print_generics(&mut self,
2039                           generics: &ast::Generics) -> IoResult<()> {
2040         let total = generics.lifetimes.len() + generics.ty_params.len();
2041         if total > 0 {
2042             try!(word(&mut self.s, "<"));
2043
2044             let mut ints = Vec::new();
2045             for i in range(0u, total) {
2046                 ints.push(i);
2047             }
2048
2049             try!(self.commasep(
2050                 Inconsistent, ints.as_slice(),
2051                 |s, &idx| {
2052                     if idx < generics.lifetimes.len() {
2053                         let lifetime = generics.lifetimes.get(idx);
2054                         s.print_lifetime(lifetime)
2055                     } else {
2056                         let idx = idx - generics.lifetimes.len();
2057                         let param = generics.ty_params.get(idx);
2058                         match param.unbound {
2059                             Some(TraitTyParamBound(ref tref)) => {
2060                                 try!(s.print_trait_ref(tref));
2061                                 try!(s.word_space("?"));
2062                             }
2063                             _ => {}
2064                         }
2065                         try!(s.print_ident(param.ident));
2066                         try!(s.print_bounds(&None,
2067                                             &param.bounds,
2068                                             false,
2069                                             false));
2070                         match param.default {
2071                             Some(ref default) => {
2072                                 try!(space(&mut s.s));
2073                                 try!(s.word_space("="));
2074                                 s.print_type(&**default)
2075                             }
2076                             _ => Ok(())
2077                         }
2078                     }
2079                 }));
2080             word(&mut self.s, ">")
2081         } else {
2082             Ok(())
2083         }
2084     }
2085
2086     pub fn print_meta_item(&mut self, item: &ast::MetaItem) -> IoResult<()> {
2087         try!(self.ibox(indent_unit));
2088         match item.node {
2089             ast::MetaWord(ref name) => {
2090                 try!(word(&mut self.s, name.get()));
2091             }
2092             ast::MetaNameValue(ref name, ref value) => {
2093                 try!(self.word_space(name.get()));
2094                 try!(self.word_space("="));
2095                 try!(self.print_literal(value));
2096             }
2097             ast::MetaList(ref name, ref items) => {
2098                 try!(word(&mut self.s, name.get()));
2099                 try!(self.popen());
2100                 try!(self.commasep(Consistent,
2101                                    items.as_slice(),
2102                                    |s, i| s.print_meta_item(&**i)));
2103                 try!(self.pclose());
2104             }
2105         }
2106         self.end()
2107     }
2108
2109     pub fn print_view_path(&mut self, vp: &ast::ViewPath) -> IoResult<()> {
2110         match vp.node {
2111             ast::ViewPathSimple(ident, ref path, _) => {
2112                 // FIXME(#6993) can't compare identifiers directly here
2113                 if path.segments.last().unwrap().identifier.name != ident.name {
2114                     try!(self.print_ident(ident));
2115                     try!(space(&mut self.s));
2116                     try!(self.word_space("="));
2117                 }
2118                 self.print_path(path, false)
2119             }
2120
2121             ast::ViewPathGlob(ref path, _) => {
2122                 try!(self.print_path(path, false));
2123                 word(&mut self.s, "::*")
2124             }
2125
2126             ast::ViewPathList(ref path, ref idents, _) => {
2127                 if path.segments.is_empty() {
2128                     try!(word(&mut self.s, "{"));
2129                 } else {
2130                     try!(self.print_path(path, false));
2131                     try!(word(&mut self.s, "::{"));
2132                 }
2133                 try!(self.commasep(Inconsistent, idents.as_slice(), |s, w| {
2134                     s.print_ident(w.node.name)
2135                 }));
2136                 word(&mut self.s, "}")
2137             }
2138         }
2139     }
2140
2141     pub fn print_view_item(&mut self, item: &ast::ViewItem) -> IoResult<()> {
2142         try!(self.hardbreak_if_not_bol());
2143         try!(self.maybe_print_comment(item.span.lo));
2144         try!(self.print_outer_attributes(item.attrs.as_slice()));
2145         try!(self.print_visibility(item.vis));
2146         match item.node {
2147             ast::ViewItemExternCrate(id, ref optional_path, _) => {
2148                 try!(self.head("extern crate"));
2149                 try!(self.print_ident(id));
2150                 for &(ref p, style) in optional_path.iter() {
2151                     try!(space(&mut self.s));
2152                     try!(word(&mut self.s, "="));
2153                     try!(space(&mut self.s));
2154                     try!(self.print_string(p.get(), style));
2155                 }
2156             }
2157
2158             ast::ViewItemUse(ref vp) => {
2159                 try!(self.head("use"));
2160                 try!(self.print_view_path(&**vp));
2161             }
2162         }
2163         try!(word(&mut self.s, ";"));
2164         try!(self.end()); // end inner head-block
2165         self.end() // end outer head-block
2166     }
2167
2168     pub fn print_mutability(&mut self,
2169                             mutbl: ast::Mutability) -> IoResult<()> {
2170         match mutbl {
2171             ast::MutMutable => self.word_nbsp("mut"),
2172             ast::MutImmutable => Ok(()),
2173         }
2174     }
2175
2176     pub fn print_mt(&mut self, mt: &ast::MutTy) -> IoResult<()> {
2177         try!(self.print_mutability(mt.mutbl));
2178         self.print_type(&*mt.ty)
2179     }
2180
2181     pub fn print_arg(&mut self, input: &ast::Arg) -> IoResult<()> {
2182         try!(self.ibox(indent_unit));
2183         match input.ty.node {
2184             ast::TyInfer => try!(self.print_pat(&*input.pat)),
2185             _ => {
2186                 match input.pat.node {
2187                     ast::PatIdent(_, ref path1, _) if
2188                         path1.node.name ==
2189                             parse::token::special_idents::invalid.name => {
2190                         // Do nothing.
2191                     }
2192                     _ => {
2193                         try!(self.print_pat(&*input.pat));
2194                         try!(word(&mut self.s, ":"));
2195                         try!(space(&mut self.s));
2196                     }
2197                 }
2198                 try!(self.print_type(&*input.ty));
2199             }
2200         }
2201         self.end()
2202     }
2203
2204     pub fn print_ty_fn(&mut self,
2205                        opt_abi: Option<abi::Abi>,
2206                        opt_sigil: Option<char>,
2207                        opt_region: &Option<ast::Lifetime>,
2208                        fn_style: ast::FnStyle,
2209                        onceness: ast::Onceness,
2210                        decl: &ast::FnDecl,
2211                        id: Option<ast::Ident>,
2212                        opt_bounds: &Option<OwnedSlice<ast::TyParamBound>>,
2213                        generics: Option<&ast::Generics>,
2214                        opt_explicit_self: Option<ast::ExplicitSelf_>,
2215                        is_unboxed: bool)
2216                        -> IoResult<()> {
2217         try!(self.ibox(indent_unit));
2218
2219         // Duplicates the logic in `print_fn_header_info()`.  This is because that
2220         // function prints the sigil in the wrong place.  That should be fixed.
2221         if opt_sigil == Some('~') && onceness == ast::Once {
2222             try!(word(&mut self.s, "proc"));
2223         } else if opt_sigil == Some('&') {
2224             try!(self.print_fn_style(fn_style));
2225             try!(self.print_extern_opt_abi(opt_abi));
2226             try!(self.print_onceness(onceness));
2227         } else {
2228             assert!(opt_sigil.is_none());
2229             try!(self.print_fn_style(fn_style));
2230             try!(self.print_opt_abi_and_extern_if_nondefault(opt_abi));
2231             try!(self.print_onceness(onceness));
2232             if !is_unboxed {
2233                 try!(word(&mut self.s, "fn"));
2234             }
2235         }
2236
2237         match id {
2238             Some(id) => {
2239                 try!(word(&mut self.s, " "));
2240                 try!(self.print_ident(id));
2241             }
2242             _ => ()
2243         }
2244
2245         match generics { Some(g) => try!(self.print_generics(g)), _ => () }
2246         try!(zerobreak(&mut self.s));
2247
2248         if is_unboxed || opt_sigil == Some('&') {
2249             try!(word(&mut self.s, "|"));
2250         } else {
2251             try!(self.popen());
2252         }
2253
2254         if is_unboxed {
2255             try!(word(&mut self.s, "&mut"));
2256             try!(self.word_space(":"));
2257         }
2258
2259         try!(self.print_fn_args(decl, opt_explicit_self));
2260
2261         if is_unboxed || opt_sigil == Some('&') {
2262             try!(word(&mut self.s, "|"));
2263         } else {
2264             if decl.variadic {
2265                 try!(word(&mut self.s, ", ..."));
2266             }
2267             try!(self.pclose());
2268         }
2269
2270         opt_bounds.as_ref().map(|bounds| {
2271             self.print_bounds(opt_region, bounds, true, false)
2272         });
2273
2274         try!(self.maybe_print_comment(decl.output.span.lo));
2275
2276         match decl.output.node {
2277             ast::TyNil => {}
2278             _ => {
2279                 try!(self.space_if_not_bol());
2280                 try!(self.ibox(indent_unit));
2281                 try!(self.word_space("->"));
2282                 if decl.cf == ast::NoReturn {
2283                     try!(self.word_nbsp("!"));
2284                 } else {
2285                     try!(self.print_type(&*decl.output));
2286                 }
2287                 try!(self.end());
2288             }
2289         }
2290
2291         self.end()
2292     }
2293
2294     pub fn maybe_print_trailing_comment(&mut self, span: codemap::Span,
2295                                         next_pos: Option<BytePos>)
2296         -> IoResult<()> {
2297         let cm = match self.cm {
2298             Some(cm) => cm,
2299             _ => return Ok(())
2300         };
2301         match self.next_comment() {
2302             Some(ref cmnt) => {
2303                 if (*cmnt).style != comments::Trailing { return Ok(()) }
2304                 let span_line = cm.lookup_char_pos(span.hi);
2305                 let comment_line = cm.lookup_char_pos((*cmnt).pos);
2306                 let mut next = (*cmnt).pos + BytePos(1);
2307                 match next_pos { None => (), Some(p) => next = p }
2308                 if span.hi < (*cmnt).pos && (*cmnt).pos < next &&
2309                     span_line.line == comment_line.line {
2310                         try!(self.print_comment(cmnt));
2311                         self.cur_cmnt_and_lit.cur_cmnt += 1u;
2312                     }
2313             }
2314             _ => ()
2315         }
2316         Ok(())
2317     }
2318
2319     pub fn print_remaining_comments(&mut self) -> IoResult<()> {
2320         // If there aren't any remaining comments, then we need to manually
2321         // make sure there is a line break at the end.
2322         if self.next_comment().is_none() {
2323             try!(hardbreak(&mut self.s));
2324         }
2325         loop {
2326             match self.next_comment() {
2327                 Some(ref cmnt) => {
2328                     try!(self.print_comment(cmnt));
2329                     self.cur_cmnt_and_lit.cur_cmnt += 1u;
2330                 }
2331                 _ => break
2332             }
2333         }
2334         Ok(())
2335     }
2336
2337     pub fn print_literal(&mut self, lit: &ast::Lit) -> IoResult<()> {
2338         try!(self.maybe_print_comment(lit.span.lo));
2339         match self.next_lit(lit.span.lo) {
2340             Some(ref ltrl) => {
2341                 return word(&mut self.s, (*ltrl).lit.as_slice());
2342             }
2343             _ => ()
2344         }
2345         match lit.node {
2346             ast::LitStr(ref st, style) => self.print_string(st.get(), style),
2347             ast::LitByte(byte) => {
2348                 let mut res = String::from_str("b'");
2349                 (byte as char).escape_default(|c| res.push_char(c));
2350                 res.push_char('\'');
2351                 word(&mut self.s, res.as_slice())
2352             }
2353             ast::LitChar(ch) => {
2354                 let mut res = String::from_str("'");
2355                 ch.escape_default(|c| res.push_char(c));
2356                 res.push_char('\'');
2357                 word(&mut self.s, res.as_slice())
2358             }
2359             ast::LitInt(i, t) => {
2360                 word(&mut self.s,
2361                      ast_util::int_ty_to_string(t, Some(i)).as_slice())
2362             }
2363             ast::LitUint(u, t) => {
2364                 word(&mut self.s,
2365                      ast_util::uint_ty_to_string(t, Some(u)).as_slice())
2366             }
2367             ast::LitIntUnsuffixed(i) => {
2368                 word(&mut self.s, format!("{}", i).as_slice())
2369             }
2370             ast::LitFloat(ref f, t) => {
2371                 word(&mut self.s,
2372                      format!(
2373                          "{}{}",
2374                          f.get(),
2375                          ast_util::float_ty_to_string(t).as_slice()).as_slice())
2376             }
2377             ast::LitFloatUnsuffixed(ref f) => word(&mut self.s, f.get()),
2378             ast::LitNil => word(&mut self.s, "()"),
2379             ast::LitBool(val) => {
2380                 if val { word(&mut self.s, "true") } else { word(&mut self.s, "false") }
2381             }
2382             ast::LitBinary(ref v) => {
2383                 let escaped: String = v.iter().map(|&b| b as char).collect();
2384                 word(&mut self.s, format!("b\"{}\"", escaped.escape_default()).as_slice())
2385             }
2386         }
2387     }
2388
2389     pub fn next_lit(&mut self, pos: BytePos) -> Option<comments::Literal> {
2390         match self.literals {
2391             Some(ref lits) => {
2392                 while self.cur_cmnt_and_lit.cur_lit < lits.len() {
2393                     let ltrl = (*(*lits).get(self.cur_cmnt_and_lit.cur_lit)).clone();
2394                     if ltrl.pos > pos { return None; }
2395                     self.cur_cmnt_and_lit.cur_lit += 1u;
2396                     if ltrl.pos == pos { return Some(ltrl); }
2397                 }
2398                 None
2399             }
2400             _ => None
2401         }
2402     }
2403
2404     pub fn maybe_print_comment(&mut self, pos: BytePos) -> IoResult<()> {
2405         loop {
2406             match self.next_comment() {
2407                 Some(ref cmnt) => {
2408                     if (*cmnt).pos < pos {
2409                         try!(self.print_comment(cmnt));
2410                         self.cur_cmnt_and_lit.cur_cmnt += 1u;
2411                     } else { break; }
2412                 }
2413                 _ => break
2414             }
2415         }
2416         Ok(())
2417     }
2418
2419     pub fn print_comment(&mut self,
2420                          cmnt: &comments::Comment) -> IoResult<()> {
2421         match cmnt.style {
2422             comments::Mixed => {
2423                 assert_eq!(cmnt.lines.len(), 1u);
2424                 try!(zerobreak(&mut self.s));
2425                 try!(word(&mut self.s, cmnt.lines.get(0).as_slice()));
2426                 zerobreak(&mut self.s)
2427             }
2428             comments::Isolated => {
2429                 try!(self.hardbreak_if_not_bol());
2430                 for line in cmnt.lines.iter() {
2431                     // Don't print empty lines because they will end up as trailing
2432                     // whitespace
2433                     if !line.is_empty() {
2434                         try!(word(&mut self.s, line.as_slice()));
2435                     }
2436                     try!(hardbreak(&mut self.s));
2437                 }
2438                 Ok(())
2439             }
2440             comments::Trailing => {
2441                 try!(word(&mut self.s, " "));
2442                 if cmnt.lines.len() == 1u {
2443                     try!(word(&mut self.s, cmnt.lines.get(0).as_slice()));
2444                     hardbreak(&mut self.s)
2445                 } else {
2446                     try!(self.ibox(0u));
2447                     for line in cmnt.lines.iter() {
2448                         if !line.is_empty() {
2449                             try!(word(&mut self.s, line.as_slice()));
2450                         }
2451                         try!(hardbreak(&mut self.s));
2452                     }
2453                     self.end()
2454                 }
2455             }
2456             comments::BlankLine => {
2457                 // We need to do at least one, possibly two hardbreaks.
2458                 let is_semi = match self.s.last_token() {
2459                     pp::String(s, _) => ";" == s.as_slice(),
2460                     _ => false
2461                 };
2462                 if is_semi || self.is_begin() || self.is_end() {
2463                     try!(hardbreak(&mut self.s));
2464                 }
2465                 hardbreak(&mut self.s)
2466             }
2467         }
2468     }
2469
2470     pub fn print_string(&mut self, st: &str,
2471                         style: ast::StrStyle) -> IoResult<()> {
2472         let st = match style {
2473             ast::CookedStr => {
2474                 (format!("\"{}\"", st.escape_default()))
2475             }
2476             ast::RawStr(n) => {
2477                 (format!("r{delim}\"{string}\"{delim}",
2478                          delim="#".repeat(n),
2479                          string=st))
2480             }
2481         };
2482         word(&mut self.s, st.as_slice())
2483     }
2484
2485     pub fn next_comment(&mut self) -> Option<comments::Comment> {
2486         match self.comments {
2487             Some(ref cmnts) => {
2488                 if self.cur_cmnt_and_lit.cur_cmnt < cmnts.len() {
2489                     Some((*cmnts.get(self.cur_cmnt_and_lit.cur_cmnt)).clone())
2490                 } else {
2491                     None
2492                 }
2493             }
2494             _ => None
2495         }
2496     }
2497
2498     pub fn print_opt_fn_style(&mut self,
2499                             opt_fn_style: Option<ast::FnStyle>) -> IoResult<()> {
2500         match opt_fn_style {
2501             Some(fn_style) => self.print_fn_style(fn_style),
2502             None => Ok(())
2503         }
2504     }
2505
2506     pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
2507                                                   opt_abi: Option<abi::Abi>)
2508         -> IoResult<()> {
2509         match opt_abi {
2510             Some(abi::Rust) => Ok(()),
2511             Some(abi) => {
2512                 try!(self.word_nbsp("extern"));
2513                 self.word_nbsp(abi.to_string().as_slice())
2514             }
2515             None => Ok(())
2516         }
2517     }
2518
2519     pub fn print_extern_opt_abi(&mut self,
2520                                 opt_abi: Option<abi::Abi>) -> IoResult<()> {
2521         match opt_abi {
2522             Some(abi) => {
2523                 try!(self.word_nbsp("extern"));
2524                 self.word_nbsp(abi.to_string().as_slice())
2525             }
2526             None => Ok(())
2527         }
2528     }
2529
2530     pub fn print_fn_header_info(&mut self,
2531                                 _opt_explicit_self: Option<ast::ExplicitSelf_>,
2532                                 opt_fn_style: Option<ast::FnStyle>,
2533                                 abi: abi::Abi,
2534                                 vis: ast::Visibility) -> IoResult<()> {
2535         try!(word(&mut self.s, visibility_qualified(vis, "").as_slice()));
2536         try!(self.print_opt_fn_style(opt_fn_style));
2537
2538         if abi != abi::Rust {
2539             try!(self.word_nbsp("extern"));
2540             try!(self.word_nbsp(abi.to_string().as_slice()));
2541         }
2542
2543         word(&mut self.s, "fn")
2544     }
2545
2546     pub fn print_fn_style(&mut self, s: ast::FnStyle) -> IoResult<()> {
2547         match s {
2548             ast::NormalFn => Ok(()),
2549             ast::UnsafeFn => self.word_nbsp("unsafe"),
2550         }
2551     }
2552
2553     pub fn print_onceness(&mut self, o: ast::Onceness) -> IoResult<()> {
2554         match o {
2555             ast::Once => self.word_nbsp("once"),
2556             ast::Many => Ok(())
2557         }
2558     }
2559 }
2560
2561 #[cfg(test)]
2562 mod test {
2563     use super::*;
2564
2565     use ast;
2566     use ast_util;
2567     use codemap;
2568     use parse::token;
2569
2570     #[test]
2571     fn test_fun_to_string() {
2572         let abba_ident = token::str_to_ident("abba");
2573
2574         let decl = ast::FnDecl {
2575             inputs: Vec::new(),
2576             output: ast::P(ast::Ty {id: 0,
2577                                     node: ast::TyNil,
2578                                     span: codemap::DUMMY_SP}),
2579             cf: ast::Return,
2580             variadic: false
2581         };
2582         let generics = ast_util::empty_generics();
2583         assert_eq!(&fun_to_string(&decl, ast::NormalFn, abba_ident,
2584                                None, &generics),
2585                    &"fn abba()".to_string());
2586     }
2587
2588     #[test]
2589     fn test_variant_to_string() {
2590         let ident = token::str_to_ident("principal_skinner");
2591
2592         let var = codemap::respan(codemap::DUMMY_SP, ast::Variant_ {
2593             name: ident,
2594             attrs: Vec::new(),
2595             // making this up as I go.... ?
2596             kind: ast::TupleVariantKind(Vec::new()),
2597             id: 0,
2598             disr_expr: None,
2599             vis: ast::Public,
2600         });
2601
2602         let varstr = variant_to_string(&var);
2603         assert_eq!(&varstr,&"pub principal_skinner".to_string());
2604     }
2605 }