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