]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/print/pprust.rs
auto merge of #14696 : jakub-/rust/dead-struct-fields, r=alexcrichton
[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           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::io::{IoResult, MemWriter};
30 use std::io;
31 use std::mem;
32 use std::str;
33 use std::string::String;
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: &[@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(ty) => {
468                 try!(word(&mut self.s, "@"));
469                 try!(self.print_type(ty));
470             }
471             ast::TyUniq(ty) => {
472                 try!(word(&mut self.s, "~"));
473                 try!(self.print_type(ty));
474             }
475             ast::TyVec(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(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(ty, 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(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(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(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(ty, m, 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(decl, fn_style, abi, ref typarams, 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(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(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, item.span));
700             }
701
702             ast::ItemImpl(ref generics, ref opt_trait, ty, ref methods) => {
703                 try!(self.head(visibility_qualified(item.vis,
704                                                     "impl").as_slice()));
705                 if generics.is_parameterized() {
706                     try!(self.print_generics(generics));
707                     try!(space(&mut self.s));
708                 }
709
710                 match opt_trait {
711                     &Some(ref t) => {
712                         try!(self.print_trait_ref(t));
713                         try!(space(&mut self.s));
714                         try!(self.word_space("for"));
715                     }
716                     &None => {}
717                 }
718
719                 try!(self.print_type(ty));
720
721                 try!(space(&mut self.s));
722                 try!(self.bopen());
723                 try!(self.print_inner_attributes(item.attrs.as_slice()));
724                 for meth in methods.iter() {
725                     try!(self.print_method(*meth));
726                 }
727                 try!(self.bclose(item.span));
728             }
729             ast::ItemTrait(ref generics, ref sized, ref traits, ref methods) => {
730                 try!(self.head(visibility_qualified(item.vis,
731                                                     "trait").as_slice()));
732                 try!(self.print_ident(item.ident));
733                 try!(self.print_generics(generics));
734                 if *sized == ast::DynSize {
735                     try!(space(&mut self.s));
736                     try!(word(&mut self.s, "for type"));
737                 }
738                 if traits.len() != 0u {
739                     try!(word(&mut self.s, ":"));
740                     for (i, trait_) in traits.iter().enumerate() {
741                         try!(self.nbsp());
742                         if i != 0 {
743                             try!(self.word_space("+"));
744                         }
745                         try!(self.print_path(&trait_.path, false));
746                     }
747                 }
748                 try!(word(&mut self.s, " "));
749                 try!(self.bopen());
750                 for meth in methods.iter() {
751                     try!(self.print_trait_method(meth));
752                 }
753                 try!(self.bclose(item.span));
754             }
755             // I think it's reasonable to hide the context here:
756             ast::ItemMac(codemap::Spanned { node: ast::MacInvocTT(ref pth, ref tts, _),
757                                             ..}) => {
758                 try!(self.print_visibility(item.vis));
759                 try!(self.print_path(pth, false));
760                 try!(word(&mut self.s, "! "));
761                 try!(self.print_ident(item.ident));
762                 try!(self.cbox(indent_unit));
763                 try!(self.popen());
764                 try!(self.print_tts(tts.as_slice()));
765                 try!(self.pclose());
766                 try!(self.end());
767             }
768         }
769         self.ann.post(self, NodeItem(item))
770     }
771
772     fn print_trait_ref(&mut self, t: &ast::TraitRef) -> IoResult<()> {
773         self.print_path(&t.path, false)
774     }
775
776     pub fn print_enum_def(&mut self, enum_definition: &ast::EnumDef,
777                           generics: &ast::Generics, ident: ast::Ident,
778                           span: codemap::Span,
779                           visibility: ast::Visibility) -> IoResult<()> {
780         try!(self.head(visibility_qualified(visibility, "enum").as_slice()));
781         try!(self.print_ident(ident));
782         try!(self.print_generics(generics));
783         try!(space(&mut self.s));
784         self.print_variants(enum_definition.variants.as_slice(), span)
785     }
786
787     pub fn print_variants(&mut self,
788                           variants: &[P<ast::Variant>],
789                           span: codemap::Span) -> IoResult<()> {
790         try!(self.bopen());
791         for &v in variants.iter() {
792             try!(self.space_if_not_bol());
793             try!(self.maybe_print_comment(v.span.lo));
794             try!(self.print_outer_attributes(v.node.attrs.as_slice()));
795             try!(self.ibox(indent_unit));
796             try!(self.print_variant(v));
797             try!(word(&mut self.s, ","));
798             try!(self.end());
799             try!(self.maybe_print_trailing_comment(v.span, None));
800         }
801         self.bclose(span)
802     }
803
804     pub fn print_visibility(&mut self, vis: ast::Visibility) -> IoResult<()> {
805         match vis {
806             ast::Public => self.word_nbsp("pub"),
807             ast::Inherited => Ok(())
808         }
809     }
810
811     pub fn print_struct(&mut self,
812                         struct_def: &ast::StructDef,
813                         generics: &ast::Generics,
814                         ident: ast::Ident,
815                         span: codemap::Span) -> IoResult<()> {
816         try!(self.print_ident(ident));
817         try!(self.print_generics(generics));
818         match struct_def.super_struct {
819             Some(t) => {
820                 try!(self.word_space(":"));
821                 try!(self.print_type(t));
822             },
823             None => {},
824         }
825         if ast_util::struct_def_is_tuple_like(struct_def) {
826             if !struct_def.fields.is_empty() {
827                 try!(self.popen());
828                 try!(self.commasep(
829                     Inconsistent, struct_def.fields.as_slice(),
830                     |s, field| {
831                         match field.node.kind {
832                             ast::NamedField(..) => fail!("unexpected named field"),
833                             ast::UnnamedField(vis) => {
834                                 try!(s.print_visibility(vis));
835                                 try!(s.maybe_print_comment(field.span.lo));
836                                 s.print_type(field.node.ty)
837                             }
838                         }
839                     }
840                 ));
841                 try!(self.pclose());
842             }
843             try!(word(&mut self.s, ";"));
844             try!(self.end());
845             self.end() // close the outer-box
846         } else {
847             try!(self.nbsp());
848             try!(self.bopen());
849             try!(self.hardbreak_if_not_bol());
850
851             for field in struct_def.fields.iter() {
852                 match field.node.kind {
853                     ast::UnnamedField(..) => fail!("unexpected unnamed field"),
854                     ast::NamedField(ident, visibility) => {
855                         try!(self.hardbreak_if_not_bol());
856                         try!(self.maybe_print_comment(field.span.lo));
857                         try!(self.print_outer_attributes(field.node.attrs.as_slice()));
858                         try!(self.print_visibility(visibility));
859                         try!(self.print_ident(ident));
860                         try!(self.word_nbsp(":"));
861                         try!(self.print_type(field.node.ty));
862                         try!(word(&mut self.s, ","));
863                     }
864                 }
865             }
866
867             self.bclose(span)
868         }
869     }
870
871     /// This doesn't deserve to be called "pretty" printing, but it should be
872     /// meaning-preserving. A quick hack that might help would be to look at the
873     /// spans embedded in the TTs to decide where to put spaces and newlines.
874     /// But it'd be better to parse these according to the grammar of the
875     /// appropriate macro, transcribe back into the grammar we just parsed from,
876     /// and then pretty-print the resulting AST nodes (so, e.g., we print
877     /// expression arguments as expressions). It can be done! I think.
878     pub fn print_tt(&mut self, tt: &ast::TokenTree) -> IoResult<()> {
879         match *tt {
880             ast::TTDelim(ref tts) => self.print_tts(tts.as_slice()),
881             ast::TTTok(_, ref tk) => {
882                 try!(word(&mut self.s, parse::token::to_str(tk).as_slice()));
883                 match *tk {
884                     parse::token::DOC_COMMENT(..) => {
885                         hardbreak(&mut self.s)
886                     }
887                     _ => Ok(())
888                 }
889             }
890             ast::TTSeq(_, ref tts, ref sep, zerok) => {
891                 try!(word(&mut self.s, "$("));
892                 for tt_elt in (*tts).iter() {
893                     try!(self.print_tt(tt_elt));
894                 }
895                 try!(word(&mut self.s, ")"));
896                 match *sep {
897                     Some(ref tk) => {
898                         try!(word(&mut self.s,
899                                   parse::token::to_str(tk).as_slice()));
900                     }
901                     None => ()
902                 }
903                 word(&mut self.s, if zerok { "*" } else { "+" })
904             }
905             ast::TTNonterminal(_, name) => {
906                 try!(word(&mut self.s, "$"));
907                 self.print_ident(name)
908             }
909         }
910     }
911
912     pub fn print_tts(&mut self, tts: &[ast::TokenTree]) -> IoResult<()> {
913         try!(self.ibox(0));
914         for (i, tt) in tts.iter().enumerate() {
915             if i != 0 {
916                 try!(space(&mut self.s));
917             }
918             try!(self.print_tt(tt));
919         }
920         self.end()
921     }
922
923     pub fn print_variant(&mut self, v: &ast::Variant) -> IoResult<()> {
924         try!(self.print_visibility(v.node.vis));
925         match v.node.kind {
926             ast::TupleVariantKind(ref args) => {
927                 try!(self.print_ident(v.node.name));
928                 if !args.is_empty() {
929                     try!(self.popen());
930                     try!(self.commasep(Consistent,
931                                        args.as_slice(),
932                                        |s, arg| s.print_type(arg.ty)));
933                     try!(self.pclose());
934                 }
935             }
936             ast::StructVariantKind(struct_def) => {
937                 try!(self.head(""));
938                 let generics = ast_util::empty_generics();
939                 try!(self.print_struct(struct_def, &generics, v.node.name, v.span));
940             }
941         }
942         match v.node.disr_expr {
943             Some(d) => {
944                 try!(space(&mut self.s));
945                 try!(self.word_space("="));
946                 self.print_expr(d)
947             }
948             _ => Ok(())
949         }
950     }
951
952     pub fn print_ty_method(&mut self, m: &ast::TypeMethod) -> IoResult<()> {
953         try!(self.hardbreak_if_not_bol());
954         try!(self.maybe_print_comment(m.span.lo));
955         try!(self.print_outer_attributes(m.attrs.as_slice()));
956         try!(self.print_ty_fn(None,
957                               None,
958                               &None,
959                               m.fn_style,
960                               ast::Many,
961                               m.decl,
962                               Some(m.ident),
963                               &None,
964                               Some(&m.generics),
965                               Some(m.explicit_self.node),
966                               false));
967         word(&mut self.s, ";")
968     }
969
970     pub fn print_trait_method(&mut self,
971                               m: &ast::TraitMethod) -> IoResult<()> {
972         match *m {
973             Required(ref ty_m) => self.print_ty_method(ty_m),
974             Provided(m) => self.print_method(m)
975         }
976     }
977
978     pub fn print_method(&mut self, meth: &ast::Method) -> IoResult<()> {
979         try!(self.hardbreak_if_not_bol());
980         try!(self.maybe_print_comment(meth.span.lo));
981         try!(self.print_outer_attributes(meth.attrs.as_slice()));
982         try!(self.print_fn(meth.decl, Some(meth.fn_style), abi::Rust,
983                         meth.ident, &meth.generics, Some(meth.explicit_self.node),
984                         meth.vis));
985         try!(word(&mut self.s, " "));
986         self.print_block_with_attrs(meth.body, meth.attrs.as_slice())
987     }
988
989     pub fn print_outer_attributes(&mut self,
990                                   attrs: &[ast::Attribute]) -> IoResult<()> {
991         let mut count = 0;
992         for attr in attrs.iter() {
993             match attr.node.style {
994                 ast::AttrOuter => {
995                     try!(self.print_attribute(attr));
996                     count += 1;
997                 }
998                 _ => {/* fallthrough */ }
999             }
1000         }
1001         if count > 0 {
1002             try!(self.hardbreak_if_not_bol());
1003         }
1004         Ok(())
1005     }
1006
1007     pub fn print_inner_attributes(&mut self,
1008                                   attrs: &[ast::Attribute]) -> IoResult<()> {
1009         let mut count = 0;
1010         for attr in attrs.iter() {
1011             match attr.node.style {
1012                 ast::AttrInner => {
1013                     try!(self.print_attribute(attr));
1014                     count += 1;
1015                 }
1016                 _ => {/* fallthrough */ }
1017             }
1018         }
1019         if count > 0 {
1020             try!(self.hardbreak_if_not_bol());
1021         }
1022         Ok(())
1023     }
1024
1025     pub fn print_attribute(&mut self, attr: &ast::Attribute) -> IoResult<()> {
1026         try!(self.hardbreak_if_not_bol());
1027         try!(self.maybe_print_comment(attr.span.lo));
1028         if attr.node.is_sugared_doc {
1029             word(&mut self.s, attr.value_str().unwrap().get())
1030         } else {
1031             match attr.node.style {
1032                 ast::AttrInner => try!(word(&mut self.s, "#![")),
1033                 ast::AttrOuter => try!(word(&mut self.s, "#[")),
1034             }
1035             try!(self.print_meta_item(attr.meta()));
1036             word(&mut self.s, "]")
1037         }
1038     }
1039
1040
1041     pub fn print_stmt(&mut self, st: &ast::Stmt) -> IoResult<()> {
1042         try!(self.maybe_print_comment(st.span.lo));
1043         match st.node {
1044             ast::StmtDecl(decl, _) => {
1045                 try!(self.print_decl(decl));
1046             }
1047             ast::StmtExpr(expr, _) => {
1048                 try!(self.space_if_not_bol());
1049                 try!(self.print_expr(expr));
1050             }
1051             ast::StmtSemi(expr, _) => {
1052                 try!(self.space_if_not_bol());
1053                 try!(self.print_expr(expr));
1054                 try!(word(&mut self.s, ";"));
1055             }
1056             ast::StmtMac(ref mac, semi) => {
1057                 try!(self.space_if_not_bol());
1058                 try!(self.print_mac(mac));
1059                 if semi {
1060                     try!(word(&mut self.s, ";"));
1061                 }
1062             }
1063         }
1064         if parse::classify::stmt_ends_with_semi(st) {
1065             try!(word(&mut self.s, ";"));
1066         }
1067         self.maybe_print_trailing_comment(st.span, None)
1068     }
1069
1070     pub fn print_block(&mut self, blk: &ast::Block) -> IoResult<()> {
1071         self.print_block_with_attrs(blk, &[])
1072     }
1073
1074     pub fn print_block_unclosed(&mut self, blk: &ast::Block) -> IoResult<()> {
1075         self.print_block_unclosed_indent(blk, indent_unit)
1076     }
1077
1078     pub fn print_block_unclosed_indent(&mut self, blk: &ast::Block,
1079                                        indented: uint) -> IoResult<()> {
1080         self.print_block_maybe_unclosed(blk, indented, &[], false)
1081     }
1082
1083     pub fn print_block_with_attrs(&mut self,
1084                                   blk: &ast::Block,
1085                                   attrs: &[ast::Attribute]) -> IoResult<()> {
1086         self.print_block_maybe_unclosed(blk, indent_unit, attrs, true)
1087     }
1088
1089     pub fn print_block_maybe_unclosed(&mut self,
1090                                       blk: &ast::Block,
1091                                       indented: uint,
1092                                       attrs: &[ast::Attribute],
1093                                       close_box: bool) -> IoResult<()> {
1094         match blk.rules {
1095             ast::UnsafeBlock(..) => try!(self.word_space("unsafe")),
1096             ast::DefaultBlock => ()
1097         }
1098         try!(self.maybe_print_comment(blk.span.lo));
1099         try!(self.ann.pre(self, NodeBlock(blk)));
1100         try!(self.bopen());
1101
1102         try!(self.print_inner_attributes(attrs));
1103
1104         for vi in blk.view_items.iter() {
1105             try!(self.print_view_item(vi));
1106         }
1107         for st in blk.stmts.iter() {
1108             try!(self.print_stmt(*st));
1109         }
1110         match blk.expr {
1111             Some(expr) => {
1112                 try!(self.space_if_not_bol());
1113                 try!(self.print_expr(expr));
1114                 try!(self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi)));
1115             }
1116             _ => ()
1117         }
1118         try!(self.bclose_maybe_open(blk.span, indented, close_box));
1119         self.ann.post(self, NodeBlock(blk))
1120     }
1121
1122     fn print_else(&mut self, els: Option<@ast::Expr>) -> IoResult<()> {
1123         match els {
1124             Some(_else) => {
1125                 match _else.node {
1126                     // "another else-if"
1127                     ast::ExprIf(i, t, e) => {
1128                         try!(self.cbox(indent_unit - 1u));
1129                         try!(self.ibox(0u));
1130                         try!(word(&mut self.s, " else if "));
1131                         try!(self.print_expr(i));
1132                         try!(space(&mut self.s));
1133                         try!(self.print_block(t));
1134                         self.print_else(e)
1135                     }
1136                     // "final else"
1137                     ast::ExprBlock(b) => {
1138                         try!(self.cbox(indent_unit - 1u));
1139                         try!(self.ibox(0u));
1140                         try!(word(&mut self.s, " else "));
1141                         self.print_block(b)
1142                     }
1143                     // BLEAH, constraints would be great here
1144                     _ => {
1145                         fail!("print_if saw if with weird alternative");
1146                     }
1147                 }
1148             }
1149             _ => Ok(())
1150         }
1151     }
1152
1153     pub fn print_if(&mut self, test: &ast::Expr, blk: &ast::Block,
1154                     elseopt: Option<@ast::Expr>, chk: bool) -> IoResult<()> {
1155         try!(self.head("if"));
1156         if chk { try!(self.word_nbsp("check")); }
1157         try!(self.print_expr(test));
1158         try!(space(&mut self.s));
1159         try!(self.print_block(blk));
1160         self.print_else(elseopt)
1161     }
1162
1163     pub fn print_mac(&mut self, m: &ast::Mac) -> IoResult<()> {
1164         match m.node {
1165             // I think it's reasonable to hide the ctxt here:
1166             ast::MacInvocTT(ref pth, ref tts, _) => {
1167                 try!(self.print_path(pth, false));
1168                 try!(word(&mut self.s, "!"));
1169                 try!(self.popen());
1170                 try!(self.print_tts(tts.as_slice()));
1171                 self.pclose()
1172             }
1173         }
1174     }
1175
1176     pub fn print_expr_vstore(&mut self, t: ast::ExprVstore) -> IoResult<()> {
1177         match t {
1178             ast::ExprVstoreUniq => word(&mut self.s, "box "),
1179             ast::ExprVstoreSlice => word(&mut self.s, "&"),
1180             ast::ExprVstoreMutSlice => {
1181                 try!(word(&mut self.s, "&"));
1182                 word(&mut self.s, "mut")
1183             }
1184         }
1185     }
1186
1187     fn print_call_post(&mut self, args: &[@ast::Expr]) -> IoResult<()> {
1188         try!(self.popen());
1189         try!(self.commasep_exprs(Inconsistent, args));
1190         self.pclose()
1191     }
1192
1193     pub fn print_expr_maybe_paren(&mut self, expr: &ast::Expr) -> IoResult<()> {
1194         let needs_par = needs_parentheses(expr);
1195         if needs_par {
1196             try!(self.popen());
1197         }
1198         try!(self.print_expr(expr));
1199         if needs_par {
1200             try!(self.pclose());
1201         }
1202         Ok(())
1203     }
1204
1205     pub fn print_expr(&mut self, expr: &ast::Expr) -> IoResult<()> {
1206         try!(self.maybe_print_comment(expr.span.lo));
1207         try!(self.ibox(indent_unit));
1208         try!(self.ann.pre(self, NodeExpr(expr)));
1209         match expr.node {
1210             ast::ExprVstore(e, v) => {
1211                 try!(self.print_expr_vstore(v));
1212                 try!(self.print_expr(e));
1213             },
1214             ast::ExprBox(p, e) => {
1215                 try!(word(&mut self.s, "box"));
1216                 try!(word(&mut self.s, "("));
1217                 try!(self.print_expr(p));
1218                 try!(self.word_space(")"));
1219                 try!(self.print_expr(e));
1220             }
1221             ast::ExprVec(ref exprs) => {
1222                 try!(self.ibox(indent_unit));
1223                 try!(word(&mut self.s, "["));
1224                 try!(self.commasep_exprs(Inconsistent, exprs.as_slice()));
1225                 try!(word(&mut self.s, "]"));
1226                 try!(self.end());
1227             }
1228
1229             ast::ExprRepeat(element, count) => {
1230                 try!(self.ibox(indent_unit));
1231                 try!(word(&mut self.s, "["));
1232                 try!(self.print_expr(element));
1233                 try!(word(&mut self.s, ","));
1234                 try!(word(&mut self.s, ".."));
1235                 try!(self.print_expr(count));
1236                 try!(word(&mut self.s, "]"));
1237                 try!(self.end());
1238             }
1239
1240             ast::ExprStruct(ref path, ref fields, wth) => {
1241                 try!(self.print_path(path, true));
1242                 try!(word(&mut self.s, "{"));
1243                 try!(self.commasep_cmnt(
1244                     Consistent,
1245                     fields.as_slice(),
1246                     |s, field| {
1247                         try!(s.ibox(indent_unit));
1248                         try!(s.print_ident(field.ident.node));
1249                         try!(s.word_space(":"));
1250                         try!(s.print_expr(field.expr));
1251                         s.end()
1252                     },
1253                     |f| f.span));
1254                 match wth {
1255                     Some(expr) => {
1256                         try!(self.ibox(indent_unit));
1257                         if !fields.is_empty() {
1258                             try!(word(&mut self.s, ","));
1259                             try!(space(&mut self.s));
1260                         }
1261                         try!(word(&mut self.s, ".."));
1262                         try!(self.print_expr(expr));
1263                         try!(self.end());
1264                     }
1265                     _ => try!(word(&mut self.s, ","))
1266                 }
1267                 try!(word(&mut self.s, "}"));
1268             }
1269             ast::ExprTup(ref exprs) => {
1270                 try!(self.popen());
1271                 try!(self.commasep_exprs(Inconsistent, exprs.as_slice()));
1272                 if exprs.len() == 1 {
1273                     try!(word(&mut self.s, ","));
1274                 }
1275                 try!(self.pclose());
1276             }
1277             ast::ExprCall(func, ref args) => {
1278                 try!(self.print_expr_maybe_paren(func));
1279                 try!(self.print_call_post(args.as_slice()));
1280             }
1281             ast::ExprMethodCall(ident, ref tys, ref args) => {
1282                 let base_args = args.slice_from(1);
1283                 try!(self.print_expr(*args.get(0)));
1284                 try!(word(&mut self.s, "."));
1285                 try!(self.print_ident(ident.node));
1286                 if tys.len() > 0u {
1287                     try!(word(&mut self.s, "::<"));
1288                     try!(self.commasep(Inconsistent, tys.as_slice(),
1289                                        |s, ty| s.print_type_ref(ty)));
1290                     try!(word(&mut self.s, ">"));
1291                 }
1292                 try!(self.print_call_post(base_args));
1293             }
1294             ast::ExprBinary(op, lhs, rhs) => {
1295                 try!(self.print_expr(lhs));
1296                 try!(space(&mut self.s));
1297                 try!(self.word_space(ast_util::binop_to_str(op)));
1298                 try!(self.print_expr(rhs));
1299             }
1300             ast::ExprUnary(op, expr) => {
1301                 try!(word(&mut self.s, ast_util::unop_to_str(op)));
1302                 try!(self.print_expr_maybe_paren(expr));
1303             }
1304             ast::ExprAddrOf(m, expr) => {
1305                 try!(word(&mut self.s, "&"));
1306                 try!(self.print_mutability(m));
1307                 try!(self.print_expr_maybe_paren(expr));
1308             }
1309             ast::ExprLit(lit) => try!(self.print_literal(lit)),
1310             ast::ExprCast(expr, ty) => {
1311                 try!(self.print_expr(expr));
1312                 try!(space(&mut self.s));
1313                 try!(self.word_space("as"));
1314                 try!(self.print_type(ty));
1315             }
1316             ast::ExprIf(test, blk, elseopt) => {
1317                 try!(self.print_if(test, blk, elseopt, false));
1318             }
1319             ast::ExprWhile(test, blk) => {
1320                 try!(self.head("while"));
1321                 try!(self.print_expr(test));
1322                 try!(space(&mut self.s));
1323                 try!(self.print_block(blk));
1324             }
1325             ast::ExprForLoop(pat, iter, blk, opt_ident) => {
1326                 for ident in opt_ident.iter() {
1327                     try!(word(&mut self.s, "'"));
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(blk, opt_ident) => {
1340                 for ident in opt_ident.iter() {
1341                     try!(word(&mut self.s, "'"));
1342                     try!(self.print_ident(*ident));
1343                     try!(self.word_space(":"));
1344                 }
1345                 try!(self.head("loop"));
1346                 try!(space(&mut self.s));
1347                 try!(self.print_block(blk));
1348             }
1349             ast::ExprMatch(expr, ref arms) => {
1350                 try!(self.cbox(indent_unit));
1351                 try!(self.ibox(4));
1352                 try!(self.word_nbsp("match"));
1353                 try!(self.print_expr(expr));
1354                 try!(space(&mut self.s));
1355                 try!(self.bopen());
1356                 let len = arms.len();
1357                 for (i, arm) in arms.iter().enumerate() {
1358                     // I have no idea why this check is necessary, but here it
1359                     // is :(
1360                     if arm.attrs.is_empty() {
1361                         try!(space(&mut self.s));
1362                     }
1363                     try!(self.cbox(indent_unit));
1364                     try!(self.ibox(0u));
1365                     try!(self.print_outer_attributes(arm.attrs.as_slice()));
1366                     let mut first = true;
1367                     for p in arm.pats.iter() {
1368                         if first {
1369                             first = false;
1370                         } else {
1371                             try!(space(&mut self.s));
1372                             try!(self.word_space("|"));
1373                         }
1374                         try!(self.print_pat(*p));
1375                     }
1376                     try!(space(&mut self.s));
1377                     match arm.guard {
1378                         Some(e) => {
1379                             try!(self.word_space("if"));
1380                             try!(self.print_expr(e));
1381                             try!(space(&mut self.s));
1382                         }
1383                         None => ()
1384                     }
1385                     try!(self.word_space("=>"));
1386
1387                     match arm.body.node {
1388                         ast::ExprBlock(blk) => {
1389                             // the block will close the pattern's ibox
1390                             try!(self.print_block_unclosed_indent(blk, 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)
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(decl, 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(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(decl, 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(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(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(lhs, 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, lhs, 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(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(expr, 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!(word(&mut self.s, "'"));
1506                     try!(self.print_ident(*ident));
1507                     try!(space(&mut self.s));
1508                 }
1509             }
1510             ast::ExprAgain(opt_ident) => {
1511                 try!(word(&mut self.s, "continue"));
1512                 try!(space(&mut self.s));
1513                 for ident in opt_ident.iter() {
1514                     try!(word(&mut self.s, "'"));
1515                     try!(self.print_ident(*ident));
1516                     try!(space(&mut self.s))
1517                 }
1518             }
1519             ast::ExprRet(result) => {
1520                 try!(word(&mut self.s, "return"));
1521                 match result {
1522                     Some(expr) => {
1523                         try!(word(&mut self.s, " "));
1524                         try!(self.print_expr(expr));
1525                     }
1526                     _ => ()
1527                 }
1528             }
1529             ast::ExprInlineAsm(ref a) => {
1530                 if a.volatile {
1531                     try!(word(&mut self.s, "__volatile__ asm!"));
1532                 } else {
1533                     try!(word(&mut self.s, "asm!"));
1534                 }
1535                 try!(self.popen());
1536                 try!(self.print_string(a.asm.get(), a.asm_str_style));
1537                 try!(self.word_space(":"));
1538
1539                 try!(self.commasep(Inconsistent, a.outputs.as_slice(), |s, &(ref co, o)| {
1540                     try!(s.print_string(co.get(), ast::CookedStr));
1541                     try!(s.popen());
1542                     try!(s.print_expr(o));
1543                     try!(s.pclose());
1544                     Ok(())
1545                 }));
1546                 try!(space(&mut self.s));
1547                 try!(self.word_space(":"));
1548
1549                 try!(self.commasep(Inconsistent, a.inputs.as_slice(), |s, &(ref co, 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(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(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(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(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(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(inner) => {
1763                 try!(word(&mut self.s, "box "));
1764                 try!(self.print_pat(inner));
1765             }
1766             ast::PatRegion(inner) => {
1767                 try!(word(&mut self.s, "&"));
1768                 try!(self.print_pat(inner));
1769             }
1770             ast::PatLit(e) => try!(self.print_expr(e)),
1771             ast::PatRange(begin, 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         try!(word(&mut self.s, "'"));
1988         self.print_name(lifetime.name)
1989     }
1990
1991     pub fn print_generics(&mut self,
1992                           generics: &ast::Generics) -> IoResult<()> {
1993         let total = generics.lifetimes.len() + generics.ty_params.len();
1994         if total > 0 {
1995             try!(word(&mut self.s, "<"));
1996
1997             let mut ints = Vec::new();
1998             for i in range(0u, total) {
1999                 ints.push(i);
2000             }
2001
2002             try!(self.commasep(
2003                 Inconsistent, ints.as_slice(),
2004                 |s, &idx| {
2005                     if idx < generics.lifetimes.len() {
2006                         let lifetime = generics.lifetimes.get(idx);
2007                         s.print_lifetime(lifetime)
2008                     } else {
2009                         let idx = idx - generics.lifetimes.len();
2010                         let param = generics.ty_params.get(idx);
2011                         if param.sized == ast::DynSize {
2012                             try!(s.word_space("type"));
2013                         }
2014                         try!(s.print_ident(param.ident));
2015                         try!(s.print_bounds(&None, &param.bounds, false));
2016                         match param.default {
2017                             Some(default) => {
2018                                 try!(space(&mut s.s));
2019                                 try!(s.word_space("="));
2020                                 s.print_type(default)
2021                             }
2022                             _ => Ok(())
2023                         }
2024                     }
2025                 }));
2026             word(&mut self.s, ">")
2027         } else {
2028             Ok(())
2029         }
2030     }
2031
2032     pub fn print_meta_item(&mut self, item: &ast::MetaItem) -> IoResult<()> {
2033         try!(self.ibox(indent_unit));
2034         match item.node {
2035             ast::MetaWord(ref name) => {
2036                 try!(word(&mut self.s, name.get()));
2037             }
2038             ast::MetaNameValue(ref name, ref value) => {
2039                 try!(self.word_space(name.get()));
2040                 try!(self.word_space("="));
2041                 try!(self.print_literal(value));
2042             }
2043             ast::MetaList(ref name, ref items) => {
2044                 try!(word(&mut self.s, name.get()));
2045                 try!(self.popen());
2046                 try!(self.commasep(Consistent,
2047                                    items.as_slice(),
2048                                    |s, &i| s.print_meta_item(i)));
2049                 try!(self.pclose());
2050             }
2051         }
2052         self.end()
2053     }
2054
2055     pub fn print_view_path(&mut self, vp: &ast::ViewPath) -> IoResult<()> {
2056         match vp.node {
2057             ast::ViewPathSimple(ident, ref path, _) => {
2058                 // FIXME(#6993) can't compare identifiers directly here
2059                 if path.segments.last().unwrap().identifier.name != ident.name {
2060                     try!(self.print_ident(ident));
2061                     try!(space(&mut self.s));
2062                     try!(self.word_space("="));
2063                 }
2064                 self.print_path(path, false)
2065             }
2066
2067             ast::ViewPathGlob(ref path, _) => {
2068                 try!(self.print_path(path, false));
2069                 word(&mut self.s, "::*")
2070             }
2071
2072             ast::ViewPathList(ref path, ref idents, _) => {
2073                 if path.segments.is_empty() {
2074                     try!(word(&mut self.s, "{"));
2075                 } else {
2076                     try!(self.print_path(path, false));
2077                     try!(word(&mut self.s, "::{"));
2078                 }
2079                 try!(self.commasep(Inconsistent, idents.as_slice(), |s, w| {
2080                     s.print_ident(w.node.name)
2081                 }));
2082                 word(&mut self.s, "}")
2083             }
2084         }
2085     }
2086
2087     pub fn print_view_item(&mut self, item: &ast::ViewItem) -> IoResult<()> {
2088         try!(self.hardbreak_if_not_bol());
2089         try!(self.maybe_print_comment(item.span.lo));
2090         try!(self.print_outer_attributes(item.attrs.as_slice()));
2091         try!(self.print_visibility(item.vis));
2092         match item.node {
2093             ast::ViewItemExternCrate(id, ref optional_path, _) => {
2094                 try!(self.head("extern crate"));
2095                 try!(self.print_ident(id));
2096                 for &(ref p, style) in optional_path.iter() {
2097                     try!(space(&mut self.s));
2098                     try!(word(&mut self.s, "="));
2099                     try!(space(&mut self.s));
2100                     try!(self.print_string(p.get(), style));
2101                 }
2102             }
2103
2104             ast::ViewItemUse(ref vp) => {
2105                 try!(self.head("use"));
2106                 try!(self.print_view_path(*vp));
2107             }
2108         }
2109         try!(word(&mut self.s, ";"));
2110         try!(self.end()); // end inner head-block
2111         self.end() // end outer head-block
2112     }
2113
2114     pub fn print_mutability(&mut self,
2115                             mutbl: ast::Mutability) -> IoResult<()> {
2116         match mutbl {
2117             ast::MutMutable => self.word_nbsp("mut"),
2118             ast::MutImmutable => Ok(()),
2119         }
2120     }
2121
2122     pub fn print_mt(&mut self, mt: &ast::MutTy) -> IoResult<()> {
2123         try!(self.print_mutability(mt.mutbl));
2124         self.print_type(mt.ty)
2125     }
2126
2127     pub fn print_arg(&mut self, input: &ast::Arg) -> IoResult<()> {
2128         try!(self.ibox(indent_unit));
2129         match input.ty.node {
2130             ast::TyInfer => try!(self.print_pat(input.pat)),
2131             _ => {
2132                 match input.pat.node {
2133                     ast::PatIdent(_, ref path, _) if
2134                         path.segments.len() == 1 &&
2135                         path.segments.get(0).identifier.name ==
2136                             parse::token::special_idents::invalid.name => {
2137                         // Do nothing.
2138                     }
2139                     _ => {
2140                         try!(self.print_pat(input.pat));
2141                         try!(word(&mut self.s, ":"));
2142                         try!(space(&mut self.s));
2143                     }
2144                 }
2145                 try!(self.print_type(input.ty));
2146             }
2147         }
2148         self.end()
2149     }
2150
2151     pub fn print_ty_fn(&mut self,
2152                        opt_abi: Option<abi::Abi>,
2153                        opt_sigil: Option<char>,
2154                        opt_region: &Option<ast::Lifetime>,
2155                        fn_style: ast::FnStyle,
2156                        onceness: ast::Onceness,
2157                        decl: &ast::FnDecl,
2158                        id: Option<ast::Ident>,
2159                        opt_bounds: &Option<OwnedSlice<ast::TyParamBound>>,
2160                        generics: Option<&ast::Generics>,
2161                        opt_explicit_self: Option<ast::ExplicitSelf_>,
2162                        is_unboxed: bool)
2163                        -> IoResult<()> {
2164         try!(self.ibox(indent_unit));
2165
2166         // Duplicates the logic in `print_fn_header_info()`.  This is because that
2167         // function prints the sigil in the wrong place.  That should be fixed.
2168         if opt_sigil == Some('~') && onceness == ast::Once {
2169             try!(word(&mut self.s, "proc"));
2170         } else if opt_sigil == Some('&') {
2171             try!(self.print_fn_style(fn_style));
2172             try!(self.print_extern_opt_abi(opt_abi));
2173             try!(self.print_onceness(onceness));
2174         } else {
2175             assert!(opt_sigil.is_none());
2176             try!(self.print_fn_style(fn_style));
2177             try!(self.print_opt_abi_and_extern_if_nondefault(opt_abi));
2178             try!(self.print_onceness(onceness));
2179             if !is_unboxed {
2180                 try!(word(&mut self.s, "fn"));
2181             }
2182         }
2183
2184         match id {
2185             Some(id) => {
2186                 try!(word(&mut self.s, " "));
2187                 try!(self.print_ident(id));
2188             }
2189             _ => ()
2190         }
2191
2192         match generics { Some(g) => try!(self.print_generics(g)), _ => () }
2193         try!(zerobreak(&mut self.s));
2194
2195         if is_unboxed || opt_sigil == Some('&') {
2196             try!(word(&mut self.s, "|"));
2197         } else {
2198             try!(self.popen());
2199         }
2200
2201         if is_unboxed {
2202             try!(word(&mut self.s, "&mut"));
2203             try!(self.word_space(":"));
2204         }
2205
2206         try!(self.print_fn_args(decl, opt_explicit_self));
2207
2208         if is_unboxed || opt_sigil == Some('&') {
2209             try!(word(&mut self.s, "|"));
2210         } else {
2211             if decl.variadic {
2212                 try!(word(&mut self.s, ", ..."));
2213             }
2214             try!(self.pclose());
2215         }
2216
2217         opt_bounds.as_ref().map(|bounds| {
2218             self.print_bounds(opt_region, bounds, true)
2219         });
2220
2221         try!(self.maybe_print_comment(decl.output.span.lo));
2222
2223         match decl.output.node {
2224             ast::TyNil => {}
2225             _ => {
2226                 try!(self.space_if_not_bol());
2227                 try!(self.ibox(indent_unit));
2228                 try!(self.word_space("->"));
2229                 if decl.cf == ast::NoReturn {
2230                     try!(self.word_nbsp("!"));
2231                 } else {
2232                     try!(self.print_type(decl.output));
2233                 }
2234                 try!(self.end());
2235             }
2236         }
2237
2238         self.end()
2239     }
2240
2241     pub fn maybe_print_trailing_comment(&mut self, span: codemap::Span,
2242                                         next_pos: Option<BytePos>)
2243         -> IoResult<()> {
2244         let cm = match self.cm {
2245             Some(cm) => cm,
2246             _ => return Ok(())
2247         };
2248         match self.next_comment() {
2249             Some(ref cmnt) => {
2250                 if (*cmnt).style != comments::Trailing { return Ok(()) }
2251                 let span_line = cm.lookup_char_pos(span.hi);
2252                 let comment_line = cm.lookup_char_pos((*cmnt).pos);
2253                 let mut next = (*cmnt).pos + BytePos(1);
2254                 match next_pos { None => (), Some(p) => next = p }
2255                 if span.hi < (*cmnt).pos && (*cmnt).pos < next &&
2256                     span_line.line == comment_line.line {
2257                         try!(self.print_comment(cmnt));
2258                         self.cur_cmnt_and_lit.cur_cmnt += 1u;
2259                     }
2260             }
2261             _ => ()
2262         }
2263         Ok(())
2264     }
2265
2266     pub fn print_remaining_comments(&mut self) -> IoResult<()> {
2267         // If there aren't any remaining comments, then we need to manually
2268         // make sure there is a line break at the end.
2269         if self.next_comment().is_none() {
2270             try!(hardbreak(&mut self.s));
2271         }
2272         loop {
2273             match self.next_comment() {
2274                 Some(ref cmnt) => {
2275                     try!(self.print_comment(cmnt));
2276                     self.cur_cmnt_and_lit.cur_cmnt += 1u;
2277                 }
2278                 _ => break
2279             }
2280         }
2281         Ok(())
2282     }
2283
2284     pub fn print_literal(&mut self, lit: &ast::Lit) -> IoResult<()> {
2285         try!(self.maybe_print_comment(lit.span.lo));
2286         match self.next_lit(lit.span.lo) {
2287             Some(ref ltrl) => {
2288                 return word(&mut self.s, (*ltrl).lit.as_slice());
2289             }
2290             _ => ()
2291         }
2292         match lit.node {
2293             ast::LitStr(ref st, style) => self.print_string(st.get(), style),
2294             ast::LitChar(ch) => {
2295                 let mut res = String::from_str("'");
2296                 ch.escape_default(|c| res.push_char(c));
2297                 res.push_char('\'');
2298                 word(&mut self.s, res.as_slice())
2299             }
2300             ast::LitInt(i, t) => {
2301                 word(&mut self.s,
2302                      ast_util::int_ty_to_str(t, Some(i),
2303                                              ast_util::AutoSuffix).as_slice())
2304             }
2305             ast::LitUint(u, t) => {
2306                 word(&mut self.s,
2307                      ast_util::uint_ty_to_str(t, Some(u),
2308                                               ast_util::ForceSuffix).as_slice())
2309             }
2310             ast::LitIntUnsuffixed(i) => {
2311                 word(&mut self.s, format!("{}", i).as_slice())
2312             }
2313             ast::LitFloat(ref f, t) => {
2314                 word(&mut self.s,
2315                      format!(
2316                          "{}{}",
2317                          f.get(),
2318                          ast_util::float_ty_to_str(t).as_slice()).as_slice())
2319             }
2320             ast::LitFloatUnsuffixed(ref f) => word(&mut self.s, f.get()),
2321             ast::LitNil => word(&mut self.s, "()"),
2322             ast::LitBool(val) => {
2323                 if val { word(&mut self.s, "true") } else { word(&mut self.s, "false") }
2324             }
2325             ast::LitBinary(ref arr) => {
2326                 try!(self.ibox(indent_unit));
2327                 try!(word(&mut self.s, "["));
2328                 try!(self.commasep_cmnt(Inconsistent,
2329                                         arr.as_slice(),
2330                                         |s, u| {
2331                                             word(&mut s.s,
2332                                                  format!("{}",
2333                                                          *u).as_slice())
2334                                         },
2335                                         |_| lit.span));
2336                 try!(word(&mut self.s, "]"));
2337                 self.end()
2338             }
2339         }
2340     }
2341
2342     pub fn next_lit(&mut self, pos: BytePos) -> Option<comments::Literal> {
2343         match self.literals {
2344             Some(ref lits) => {
2345                 while self.cur_cmnt_and_lit.cur_lit < lits.len() {
2346                     let ltrl = (*(*lits).get(self.cur_cmnt_and_lit.cur_lit)).clone();
2347                     if ltrl.pos > pos { return None; }
2348                     self.cur_cmnt_and_lit.cur_lit += 1u;
2349                     if ltrl.pos == pos { return Some(ltrl); }
2350                 }
2351                 None
2352             }
2353             _ => None
2354         }
2355     }
2356
2357     pub fn maybe_print_comment(&mut self, pos: BytePos) -> IoResult<()> {
2358         loop {
2359             match self.next_comment() {
2360                 Some(ref cmnt) => {
2361                     if (*cmnt).pos < pos {
2362                         try!(self.print_comment(cmnt));
2363                         self.cur_cmnt_and_lit.cur_cmnt += 1u;
2364                     } else { break; }
2365                 }
2366                 _ => break
2367             }
2368         }
2369         Ok(())
2370     }
2371
2372     pub fn print_comment(&mut self,
2373                          cmnt: &comments::Comment) -> IoResult<()> {
2374         match cmnt.style {
2375             comments::Mixed => {
2376                 assert_eq!(cmnt.lines.len(), 1u);
2377                 try!(zerobreak(&mut self.s));
2378                 try!(word(&mut self.s, cmnt.lines.get(0).as_slice()));
2379                 zerobreak(&mut self.s)
2380             }
2381             comments::Isolated => {
2382                 try!(self.hardbreak_if_not_bol());
2383                 for line in cmnt.lines.iter() {
2384                     // Don't print empty lines because they will end up as trailing
2385                     // whitespace
2386                     if !line.is_empty() {
2387                         try!(word(&mut self.s, line.as_slice()));
2388                     }
2389                     try!(hardbreak(&mut self.s));
2390                 }
2391                 Ok(())
2392             }
2393             comments::Trailing => {
2394                 try!(word(&mut self.s, " "));
2395                 if cmnt.lines.len() == 1u {
2396                     try!(word(&mut self.s, cmnt.lines.get(0).as_slice()));
2397                     hardbreak(&mut self.s)
2398                 } else {
2399                     try!(self.ibox(0u));
2400                     for line in cmnt.lines.iter() {
2401                         if !line.is_empty() {
2402                             try!(word(&mut self.s, line.as_slice()));
2403                         }
2404                         try!(hardbreak(&mut self.s));
2405                     }
2406                     self.end()
2407                 }
2408             }
2409             comments::BlankLine => {
2410                 // We need to do at least one, possibly two hardbreaks.
2411                 let is_semi = match self.s.last_token() {
2412                     pp::String(s, _) => ";" == s.as_slice(),
2413                     _ => false
2414                 };
2415                 if is_semi || self.is_begin() || self.is_end() {
2416                     try!(hardbreak(&mut self.s));
2417                 }
2418                 hardbreak(&mut self.s)
2419             }
2420         }
2421     }
2422
2423     pub fn print_string(&mut self, st: &str,
2424                         style: ast::StrStyle) -> IoResult<()> {
2425         let st = match style {
2426             ast::CookedStr => {
2427                 (format!("\"{}\"", st.escape_default()))
2428             }
2429             ast::RawStr(n) => {
2430                 (format!("r{delim}\"{string}\"{delim}",
2431                          delim="#".repeat(n),
2432                          string=st))
2433             }
2434         };
2435         word(&mut self.s, st.as_slice())
2436     }
2437
2438     pub fn next_comment(&mut self) -> Option<comments::Comment> {
2439         match self.comments {
2440             Some(ref cmnts) => {
2441                 if self.cur_cmnt_and_lit.cur_cmnt < cmnts.len() {
2442                     Some((*cmnts.get(self.cur_cmnt_and_lit.cur_cmnt)).clone())
2443                 } else {
2444                     None
2445                 }
2446             }
2447             _ => None
2448         }
2449     }
2450
2451     pub fn print_opt_fn_style(&mut self,
2452                             opt_fn_style: Option<ast::FnStyle>) -> IoResult<()> {
2453         match opt_fn_style {
2454             Some(fn_style) => self.print_fn_style(fn_style),
2455             None => Ok(())
2456         }
2457     }
2458
2459     pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
2460                                                   opt_abi: Option<abi::Abi>)
2461         -> IoResult<()> {
2462         match opt_abi {
2463             Some(abi::Rust) => Ok(()),
2464             Some(abi) => {
2465                 try!(self.word_nbsp("extern"));
2466                 self.word_nbsp(abi.to_str().as_slice())
2467             }
2468             None => Ok(())
2469         }
2470     }
2471
2472     pub fn print_extern_opt_abi(&mut self,
2473                                 opt_abi: Option<abi::Abi>) -> IoResult<()> {
2474         match opt_abi {
2475             Some(abi) => {
2476                 try!(self.word_nbsp("extern"));
2477                 self.word_nbsp(abi.to_str().as_slice())
2478             }
2479             None => Ok(())
2480         }
2481     }
2482
2483     pub fn print_fn_header_info(&mut self,
2484                                 _opt_explicit_self: Option<ast::ExplicitSelf_>,
2485                                 opt_fn_style: Option<ast::FnStyle>,
2486                                 abi: abi::Abi,
2487                                 vis: ast::Visibility) -> IoResult<()> {
2488         try!(word(&mut self.s, visibility_qualified(vis, "").as_slice()));
2489         try!(self.print_opt_fn_style(opt_fn_style));
2490
2491         if abi != abi::Rust {
2492             try!(self.word_nbsp("extern"));
2493             try!(self.word_nbsp(abi.to_str().as_slice()));
2494         }
2495
2496         word(&mut self.s, "fn")
2497     }
2498
2499     pub fn print_fn_style(&mut self, s: ast::FnStyle) -> IoResult<()> {
2500         match s {
2501             ast::NormalFn => Ok(()),
2502             ast::UnsafeFn => self.word_nbsp("unsafe"),
2503         }
2504     }
2505
2506     pub fn print_onceness(&mut self, o: ast::Onceness) -> IoResult<()> {
2507         match o {
2508             ast::Once => self.word_nbsp("once"),
2509             ast::Many => Ok(())
2510         }
2511     }
2512 }
2513
2514 #[cfg(test)]
2515 mod test {
2516     use super::*;
2517
2518     use ast;
2519     use ast_util;
2520     use codemap;
2521     use parse::token;
2522
2523     #[test]
2524     fn test_fun_to_str() {
2525         let abba_ident = token::str_to_ident("abba");
2526
2527         let decl = ast::FnDecl {
2528             inputs: Vec::new(),
2529             output: ast::P(ast::Ty {id: 0,
2530                                     node: ast::TyNil,
2531                                     span: codemap::DUMMY_SP}),
2532             cf: ast::Return,
2533             variadic: false
2534         };
2535         let generics = ast_util::empty_generics();
2536         assert_eq!(&fun_to_str(&decl, ast::NormalFn, abba_ident,
2537                                None, &generics),
2538                    &"fn abba()".to_string());
2539     }
2540
2541     #[test]
2542     fn test_variant_to_str() {
2543         let ident = token::str_to_ident("principal_skinner");
2544
2545         let var = codemap::respan(codemap::DUMMY_SP, ast::Variant_ {
2546             name: ident,
2547             attrs: Vec::new(),
2548             // making this up as I go.... ?
2549             kind: ast::TupleVariantKind(Vec::new()),
2550             id: 0,
2551             disr_expr: None,
2552             vis: ast::Public,
2553         });
2554
2555         let varstr = variant_to_str(&var);
2556         assert_eq!(&varstr,&"pub principal_skinner".to_string());
2557     }
2558 }