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