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