]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/print/pprust.rs
auto merge of #13600 : brandonw/rust/master, 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                 try!(self.head(visibility_qualified(item.vis, "struct")));
644                 try!(self.print_struct(struct_def, generics, item.ident, item.span));
645             }
646
647             ast::ItemImpl(ref generics, ref opt_trait, ty, ref methods) => {
648                 try!(self.head(visibility_qualified(item.vis, "impl")));
649                 if generics.is_parameterized() {
650                     try!(self.print_generics(generics));
651                     try!(space(&mut self.s));
652                 }
653
654                 match opt_trait {
655                     &Some(ref t) => {
656                         try!(self.print_trait_ref(t));
657                         try!(space(&mut self.s));
658                         try!(self.word_space("for"));
659                     }
660                     &None => {}
661                 }
662
663                 try!(self.print_type(ty));
664
665                 try!(space(&mut self.s));
666                 try!(self.bopen());
667                 try!(self.print_inner_attributes(item.attrs.as_slice()));
668                 for meth in methods.iter() {
669                     try!(self.print_method(*meth));
670                 }
671                 try!(self.bclose(item.span));
672             }
673             ast::ItemTrait(ref generics, ref traits, ref methods) => {
674                 try!(self.head(visibility_qualified(item.vis, "trait")));
675                 try!(self.print_ident(item.ident));
676                 try!(self.print_generics(generics));
677                 if traits.len() != 0u {
678                     try!(word(&mut self.s, ":"));
679                     for (i, trait_) in traits.iter().enumerate() {
680                         try!(self.nbsp());
681                         if i != 0 {
682                             try!(self.word_space("+"));
683                         }
684                         try!(self.print_path(&trait_.path, false));
685                     }
686                 }
687                 try!(word(&mut self.s, " "));
688                 try!(self.bopen());
689                 for meth in methods.iter() {
690                     try!(self.print_trait_method(meth));
691                 }
692                 try!(self.bclose(item.span));
693             }
694             // I think it's reasonable to hide the context here:
695             ast::ItemMac(codemap::Spanned { node: ast::MacInvocTT(ref pth, ref tts, _),
696                                             ..}) => {
697                 try!(self.print_visibility(item.vis));
698                 try!(self.print_path(pth, false));
699                 try!(word(&mut self.s, "! "));
700                 try!(self.print_ident(item.ident));
701                 try!(self.cbox(indent_unit));
702                 try!(self.popen());
703                 try!(self.print_tts(&(tts.as_slice())));
704                 try!(self.pclose());
705                 try!(self.end());
706             }
707         }
708         self.ann.post(self, NodeItem(item))
709     }
710
711     fn print_trait_ref(&mut self, t: &ast::TraitRef) -> IoResult<()> {
712         self.print_path(&t.path, false)
713     }
714
715     pub fn print_enum_def(&mut self, enum_definition: &ast::EnumDef,
716                           generics: &ast::Generics, ident: ast::Ident,
717                           span: codemap::Span,
718                           visibility: ast::Visibility) -> IoResult<()> {
719         try!(self.head(visibility_qualified(visibility, "enum")));
720         try!(self.print_ident(ident));
721         try!(self.print_generics(generics));
722         try!(space(&mut self.s));
723         self.print_variants(enum_definition.variants.as_slice(), span)
724     }
725
726     pub fn print_variants(&mut self,
727                           variants: &[P<ast::Variant>],
728                           span: codemap::Span) -> IoResult<()> {
729         try!(self.bopen());
730         for &v in variants.iter() {
731             try!(self.space_if_not_bol());
732             try!(self.maybe_print_comment(v.span.lo));
733             try!(self.print_outer_attributes(v.node.attrs.as_slice()));
734             try!(self.ibox(indent_unit));
735             try!(self.print_variant(v));
736             try!(word(&mut self.s, ","));
737             try!(self.end());
738             try!(self.maybe_print_trailing_comment(v.span, None));
739         }
740         self.bclose(span)
741     }
742
743     pub fn print_visibility(&mut self, vis: ast::Visibility) -> IoResult<()> {
744         match vis {
745             ast::Public => self.word_nbsp("pub"),
746             ast::Inherited => Ok(())
747         }
748     }
749
750     pub fn print_struct(&mut self,
751                         struct_def: &ast::StructDef,
752                         generics: &ast::Generics,
753                         ident: ast::Ident,
754                         span: codemap::Span) -> IoResult<()> {
755         try!(self.print_ident(ident));
756         try!(self.print_generics(generics));
757         if ast_util::struct_def_is_tuple_like(struct_def) {
758             if !struct_def.fields.is_empty() {
759                 try!(self.popen());
760                 try!(self.commasep(
761                     Inconsistent, struct_def.fields.as_slice(),
762                     |s, field| {
763                         match field.node.kind {
764                             ast::NamedField(..) => fail!("unexpected named field"),
765                             ast::UnnamedField(vis) => {
766                                 try!(s.print_visibility(vis));
767                                 try!(s.maybe_print_comment(field.span.lo));
768                                 s.print_type(field.node.ty)
769                             }
770                         }
771                     }
772                 ));
773                 try!(self.pclose());
774             }
775             try!(word(&mut self.s, ";"));
776             try!(self.end());
777             self.end() // close the outer-box
778         } else {
779             try!(self.nbsp());
780             try!(self.bopen());
781             try!(self.hardbreak_if_not_bol());
782
783             for field in struct_def.fields.iter() {
784                 match field.node.kind {
785                     ast::UnnamedField(..) => fail!("unexpected unnamed field"),
786                     ast::NamedField(ident, visibility) => {
787                         try!(self.hardbreak_if_not_bol());
788                         try!(self.maybe_print_comment(field.span.lo));
789                         try!(self.print_outer_attributes(field.node.attrs.as_slice()));
790                         try!(self.print_visibility(visibility));
791                         try!(self.print_ident(ident));
792                         try!(self.word_nbsp(":"));
793                         try!(self.print_type(field.node.ty));
794                         try!(word(&mut self.s, ","));
795                     }
796                 }
797             }
798
799             self.bclose(span)
800         }
801     }
802
803     /// This doesn't deserve to be called "pretty" printing, but it should be
804     /// meaning-preserving. A quick hack that might help would be to look at the
805     /// spans embedded in the TTs to decide where to put spaces and newlines.
806     /// But it'd be better to parse these according to the grammar of the
807     /// appropriate macro, transcribe back into the grammar we just parsed from,
808     /// and then pretty-print the resulting AST nodes (so, e.g., we print
809     /// expression arguments as expressions). It can be done! I think.
810     pub fn print_tt(&mut self, tt: &ast::TokenTree) -> IoResult<()> {
811         match *tt {
812             ast::TTDelim(ref tts) => self.print_tts(&(tts.as_slice())),
813             ast::TTTok(_, ref tk) => {
814                 word(&mut self.s, parse::token::to_str(tk))
815             }
816             ast::TTSeq(_, ref tts, ref sep, zerok) => {
817                 try!(word(&mut self.s, "$("));
818                 for tt_elt in (*tts).iter() {
819                     try!(self.print_tt(tt_elt));
820                 }
821                 try!(word(&mut self.s, ")"));
822                 match *sep {
823                     Some(ref tk) => {
824                         try!(word(&mut self.s, parse::token::to_str(tk)));
825                     }
826                     None => ()
827                 }
828                 word(&mut self.s, if zerok { "*" } else { "+" })
829             }
830             ast::TTNonterminal(_, name) => {
831                 try!(word(&mut self.s, "$"));
832                 self.print_ident(name)
833             }
834         }
835     }
836
837     pub fn print_tts(&mut self, tts: & &[ast::TokenTree]) -> IoResult<()> {
838         try!(self.ibox(0));
839         for (i, tt) in tts.iter().enumerate() {
840             if i != 0 {
841                 try!(space(&mut self.s));
842             }
843             try!(self.print_tt(tt));
844         }
845         self.end()
846     }
847
848     pub fn print_variant(&mut self, v: &ast::Variant) -> IoResult<()> {
849         try!(self.print_visibility(v.node.vis));
850         match v.node.kind {
851             ast::TupleVariantKind(ref args) => {
852                 try!(self.print_ident(v.node.name));
853                 if !args.is_empty() {
854                     try!(self.popen());
855                     try!(self.commasep(Consistent,
856                                        args.as_slice(),
857                                        |s, arg| s.print_type(arg.ty)));
858                     try!(self.pclose());
859                 }
860             }
861             ast::StructVariantKind(struct_def) => {
862                 try!(self.head(""));
863                 let generics = ast_util::empty_generics();
864                 try!(self.print_struct(struct_def, &generics, v.node.name, v.span));
865             }
866         }
867         match v.node.disr_expr {
868             Some(d) => {
869                 try!(space(&mut self.s));
870                 try!(self.word_space("="));
871                 self.print_expr(d)
872             }
873             _ => Ok(())
874         }
875     }
876
877     pub fn print_ty_method(&mut self, m: &ast::TypeMethod) -> IoResult<()> {
878         try!(self.hardbreak_if_not_bol());
879         try!(self.maybe_print_comment(m.span.lo));
880         try!(self.print_outer_attributes(m.attrs.as_slice()));
881         try!(self.print_ty_fn(None,
882                               None,
883                               &None,
884                               m.fn_style,
885                               ast::Many,
886                               m.decl,
887                               Some(m.ident),
888                               &None,
889                               Some(&m.generics),
890                               Some(m.explicit_self.node)));
891         word(&mut self.s, ";")
892     }
893
894     pub fn print_trait_method(&mut self,
895                               m: &ast::TraitMethod) -> IoResult<()> {
896         match *m {
897             Required(ref ty_m) => self.print_ty_method(ty_m),
898             Provided(m) => self.print_method(m)
899         }
900     }
901
902     pub fn print_method(&mut self, meth: &ast::Method) -> IoResult<()> {
903         try!(self.hardbreak_if_not_bol());
904         try!(self.maybe_print_comment(meth.span.lo));
905         try!(self.print_outer_attributes(meth.attrs.as_slice()));
906         try!(self.print_fn(meth.decl, Some(meth.fn_style), abi::Rust,
907                         meth.ident, &meth.generics, Some(meth.explicit_self.node),
908                         meth.vis));
909         try!(word(&mut self.s, " "));
910         self.print_block_with_attrs(meth.body, meth.attrs.as_slice())
911     }
912
913     pub fn print_outer_attributes(&mut self,
914                                   attrs: &[ast::Attribute]) -> IoResult<()> {
915         let mut count = 0;
916         for attr in attrs.iter() {
917             match attr.node.style {
918                 ast::AttrOuter => {
919                     try!(self.print_attribute(attr));
920                     count += 1;
921                 }
922                 _ => {/* fallthrough */ }
923             }
924         }
925         if count > 0 {
926             try!(self.hardbreak_if_not_bol());
927         }
928         Ok(())
929     }
930
931     pub fn print_inner_attributes(&mut self,
932                                   attrs: &[ast::Attribute]) -> IoResult<()> {
933         let mut count = 0;
934         for attr in attrs.iter() {
935             match attr.node.style {
936                 ast::AttrInner => {
937                     try!(self.print_attribute(attr));
938                     count += 1;
939                 }
940                 _ => {/* fallthrough */ }
941             }
942         }
943         if count > 0 {
944             try!(self.hardbreak_if_not_bol());
945         }
946         Ok(())
947     }
948
949     pub fn print_attribute(&mut self, attr: &ast::Attribute) -> IoResult<()> {
950         try!(self.hardbreak_if_not_bol());
951         try!(self.maybe_print_comment(attr.span.lo));
952         if attr.node.is_sugared_doc {
953             word(&mut self.s, attr.value_str().unwrap().get())
954         } else {
955             match attr.node.style {
956                 ast::AttrInner => try!(word(&mut self.s, "#![")),
957                 ast::AttrOuter => try!(word(&mut self.s, "#[")),
958             }
959             try!(self.print_meta_item(attr.meta()));
960             word(&mut self.s, "]")
961         }
962     }
963
964
965     pub fn print_stmt(&mut self, st: &ast::Stmt) -> IoResult<()> {
966         try!(self.maybe_print_comment(st.span.lo));
967         match st.node {
968             ast::StmtDecl(decl, _) => {
969                 try!(self.print_decl(decl));
970             }
971             ast::StmtExpr(expr, _) => {
972                 try!(self.space_if_not_bol());
973                 try!(self.print_expr(expr));
974             }
975             ast::StmtSemi(expr, _) => {
976                 try!(self.space_if_not_bol());
977                 try!(self.print_expr(expr));
978                 try!(word(&mut self.s, ";"));
979             }
980             ast::StmtMac(ref mac, semi) => {
981                 try!(self.space_if_not_bol());
982                 try!(self.print_mac(mac));
983                 if semi {
984                     try!(word(&mut self.s, ";"));
985                 }
986             }
987         }
988         if parse::classify::stmt_ends_with_semi(st) {
989             try!(word(&mut self.s, ";"));
990         }
991         self.maybe_print_trailing_comment(st.span, None)
992     }
993
994     pub fn print_block(&mut self, blk: &ast::Block) -> IoResult<()> {
995         self.print_block_with_attrs(blk, &[])
996     }
997
998     pub fn print_block_unclosed(&mut self, blk: &ast::Block) -> IoResult<()> {
999         self.print_block_unclosed_indent(blk, indent_unit)
1000     }
1001
1002     pub fn print_block_unclosed_indent(&mut self, blk: &ast::Block,
1003                                        indented: uint) -> IoResult<()> {
1004         self.print_block_maybe_unclosed(blk, indented, &[], false)
1005     }
1006
1007     pub fn print_block_with_attrs(&mut self,
1008                                   blk: &ast::Block,
1009                                   attrs: &[ast::Attribute]) -> IoResult<()> {
1010         self.print_block_maybe_unclosed(blk, indent_unit, attrs, true)
1011     }
1012
1013     pub fn print_block_maybe_unclosed(&mut self,
1014                                       blk: &ast::Block,
1015                                       indented: uint,
1016                                       attrs: &[ast::Attribute],
1017                                       close_box: bool) -> IoResult<()> {
1018         match blk.rules {
1019             ast::UnsafeBlock(..) => try!(self.word_space("unsafe")),
1020             ast::DefaultBlock => ()
1021         }
1022         try!(self.maybe_print_comment(blk.span.lo));
1023         try!(self.ann.pre(self, NodeBlock(blk)));
1024         try!(self.bopen());
1025
1026         try!(self.print_inner_attributes(attrs));
1027
1028         for vi in blk.view_items.iter() {
1029             try!(self.print_view_item(vi));
1030         }
1031         for st in blk.stmts.iter() {
1032             try!(self.print_stmt(*st));
1033         }
1034         match blk.expr {
1035             Some(expr) => {
1036                 try!(self.space_if_not_bol());
1037                 try!(self.print_expr(expr));
1038                 try!(self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi)));
1039             }
1040             _ => ()
1041         }
1042         try!(self.bclose_maybe_open(blk.span, indented, close_box));
1043         self.ann.post(self, NodeBlock(blk))
1044     }
1045
1046     fn print_else(&mut self, els: Option<@ast::Expr>) -> IoResult<()> {
1047         match els {
1048             Some(_else) => {
1049                 match _else.node {
1050                     // "another else-if"
1051                     ast::ExprIf(i, t, e) => {
1052                         try!(self.cbox(indent_unit - 1u));
1053                         try!(self.ibox(0u));
1054                         try!(word(&mut self.s, " else if "));
1055                         try!(self.print_expr(i));
1056                         try!(space(&mut self.s));
1057                         try!(self.print_block(t));
1058                         self.print_else(e)
1059                     }
1060                     // "final else"
1061                     ast::ExprBlock(b) => {
1062                         try!(self.cbox(indent_unit - 1u));
1063                         try!(self.ibox(0u));
1064                         try!(word(&mut self.s, " else "));
1065                         self.print_block(b)
1066                     }
1067                     // BLEAH, constraints would be great here
1068                     _ => {
1069                         fail!("print_if saw if with weird alternative");
1070                     }
1071                 }
1072             }
1073             _ => Ok(())
1074         }
1075     }
1076
1077     pub fn print_if(&mut self, test: &ast::Expr, blk: &ast::Block,
1078                     elseopt: Option<@ast::Expr>, chk: bool) -> IoResult<()> {
1079         try!(self.head("if"));
1080         if chk { try!(self.word_nbsp("check")); }
1081         try!(self.print_expr(test));
1082         try!(space(&mut self.s));
1083         try!(self.print_block(blk));
1084         self.print_else(elseopt)
1085     }
1086
1087     pub fn print_mac(&mut self, m: &ast::Mac) -> IoResult<()> {
1088         match m.node {
1089             // I think it's reasonable to hide the ctxt here:
1090             ast::MacInvocTT(ref pth, ref tts, _) => {
1091                 try!(self.print_path(pth, false));
1092                 try!(word(&mut self.s, "!"));
1093                 try!(self.popen());
1094                 try!(self.print_tts(&tts.as_slice()));
1095                 self.pclose()
1096             }
1097         }
1098     }
1099
1100     pub fn print_expr_vstore(&mut self, t: ast::ExprVstore) -> IoResult<()> {
1101         match t {
1102             ast::ExprVstoreUniq => word(&mut self.s, "~"),
1103             ast::ExprVstoreSlice => word(&mut self.s, "&"),
1104             ast::ExprVstoreMutSlice => {
1105                 try!(word(&mut self.s, "&"));
1106                 word(&mut self.s, "mut")
1107             }
1108         }
1109     }
1110
1111     fn print_call_post(&mut self, args: &[@ast::Expr]) -> IoResult<()> {
1112         try!(self.popen());
1113         try!(self.commasep_exprs(Inconsistent, args));
1114         self.pclose()
1115     }
1116
1117     pub fn print_expr(&mut self, expr: &ast::Expr) -> IoResult<()> {
1118         try!(self.maybe_print_comment(expr.span.lo));
1119         try!(self.ibox(indent_unit));
1120         try!(self.ann.pre(self, NodeExpr(expr)));
1121         match expr.node {
1122             ast::ExprVstore(e, v) => {
1123                 try!(self.print_expr_vstore(v));
1124                 try!(self.print_expr(e));
1125             },
1126             ast::ExprBox(p, e) => {
1127                 try!(word(&mut self.s, "box"));
1128                 try!(word(&mut self.s, "("));
1129                 try!(self.print_expr(p));
1130                 try!(self.word_space(")"));
1131                 try!(self.print_expr(e));
1132             }
1133             ast::ExprVec(ref exprs) => {
1134                 try!(self.ibox(indent_unit));
1135                 try!(word(&mut self.s, "["));
1136                 try!(self.commasep_exprs(Inconsistent, exprs.as_slice()));
1137                 try!(word(&mut self.s, "]"));
1138                 try!(self.end());
1139             }
1140
1141             ast::ExprRepeat(element, count) => {
1142                 try!(self.ibox(indent_unit));
1143                 try!(word(&mut self.s, "["));
1144                 try!(self.print_expr(element));
1145                 try!(word(&mut self.s, ","));
1146                 try!(word(&mut self.s, ".."));
1147                 try!(self.print_expr(count));
1148                 try!(word(&mut self.s, "]"));
1149                 try!(self.end());
1150             }
1151
1152             ast::ExprStruct(ref path, ref fields, wth) => {
1153                 try!(self.print_path(path, true));
1154                 try!(word(&mut self.s, "{"));
1155                 try!(self.commasep_cmnt(
1156                     Consistent,
1157                     fields.as_slice(),
1158                     |s, field| {
1159                         try!(s.ibox(indent_unit));
1160                         try!(s.print_ident(field.ident.node));
1161                         try!(s.word_space(":"));
1162                         try!(s.print_expr(field.expr));
1163                         s.end()
1164                     },
1165                     |f| f.span));
1166                 match wth {
1167                     Some(expr) => {
1168                         try!(self.ibox(indent_unit));
1169                         if !fields.is_empty() {
1170                             try!(word(&mut self.s, ","));
1171                             try!(space(&mut self.s));
1172                         }
1173                         try!(word(&mut self.s, ".."));
1174                         try!(self.print_expr(expr));
1175                         try!(self.end());
1176                     }
1177                     _ => try!(word(&mut self.s, ","))
1178                 }
1179                 try!(word(&mut self.s, "}"));
1180             }
1181             ast::ExprTup(ref exprs) => {
1182                 try!(self.popen());
1183                 try!(self.commasep_exprs(Inconsistent, exprs.as_slice()));
1184                 if exprs.len() == 1 {
1185                     try!(word(&mut self.s, ","));
1186                 }
1187                 try!(self.pclose());
1188             }
1189             ast::ExprCall(func, ref args) => {
1190                 try!(self.print_expr(func));
1191                 try!(self.print_call_post(args.as_slice()));
1192             }
1193             ast::ExprMethodCall(ident, ref tys, ref args) => {
1194                 let base_args = args.slice_from(1);
1195                 try!(self.print_expr(*args.get(0)));
1196                 try!(word(&mut self.s, "."));
1197                 try!(self.print_ident(ident));
1198                 if tys.len() > 0u {
1199                     try!(word(&mut self.s, "::<"));
1200                     try!(self.commasep(Inconsistent, tys.as_slice(),
1201                                        |s, ty| s.print_type_ref(ty)));
1202                     try!(word(&mut self.s, ">"));
1203                 }
1204                 try!(self.print_call_post(base_args));
1205             }
1206             ast::ExprBinary(op, lhs, rhs) => {
1207                 try!(self.print_expr(lhs));
1208                 try!(space(&mut self.s));
1209                 try!(self.word_space(ast_util::binop_to_str(op)));
1210                 try!(self.print_expr(rhs));
1211             }
1212             ast::ExprUnary(op, expr) => {
1213                 try!(word(&mut self.s, ast_util::unop_to_str(op)));
1214                 try!(self.print_expr(expr));
1215             }
1216             ast::ExprAddrOf(m, expr) => {
1217                 try!(word(&mut self.s, "&"));
1218                 try!(self.print_mutability(m));
1219                 // Avoid `& &e` => `&&e`.
1220                 match (m, &expr.node) {
1221                     (ast::MutImmutable, &ast::ExprAddrOf(..)) => try!(space(&mut self.s)),
1222                     _ => { }
1223                 }
1224                 try!(self.print_expr(expr));
1225             }
1226             ast::ExprLit(lit) => try!(self.print_literal(lit)),
1227             ast::ExprCast(expr, ty) => {
1228                 try!(self.print_expr(expr));
1229                 try!(space(&mut self.s));
1230                 try!(self.word_space("as"));
1231                 try!(self.print_type(ty));
1232             }
1233             ast::ExprIf(test, blk, elseopt) => {
1234                 try!(self.print_if(test, blk, elseopt, false));
1235             }
1236             ast::ExprWhile(test, blk) => {
1237                 try!(self.head("while"));
1238                 try!(self.print_expr(test));
1239                 try!(space(&mut self.s));
1240                 try!(self.print_block(blk));
1241             }
1242             ast::ExprForLoop(pat, iter, blk, opt_ident) => {
1243                 for ident in opt_ident.iter() {
1244                     try!(word(&mut self.s, "'"));
1245                     try!(self.print_ident(*ident));
1246                     try!(self.word_space(":"));
1247                 }
1248                 try!(self.head("for"));
1249                 try!(self.print_pat(pat));
1250                 try!(space(&mut self.s));
1251                 try!(self.word_space("in"));
1252                 try!(self.print_expr(iter));
1253                 try!(space(&mut self.s));
1254                 try!(self.print_block(blk));
1255             }
1256             ast::ExprLoop(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("loop"));
1263                 try!(space(&mut self.s));
1264                 try!(self.print_block(blk));
1265             }
1266             ast::ExprMatch(expr, ref arms) => {
1267                 try!(self.cbox(indent_unit));
1268                 try!(self.ibox(4));
1269                 try!(self.word_nbsp("match"));
1270                 try!(self.print_expr(expr));
1271                 try!(space(&mut self.s));
1272                 try!(self.bopen());
1273                 let len = arms.len();
1274                 for (i, arm) in arms.iter().enumerate() {
1275                     try!(space(&mut self.s));
1276                     try!(self.cbox(indent_unit));
1277                     try!(self.ibox(0u));
1278                     let mut first = true;
1279                     for p in arm.pats.iter() {
1280                         if first {
1281                             first = false;
1282                         } else {
1283                             try!(space(&mut self.s));
1284                             try!(self.word_space("|"));
1285                         }
1286                         try!(self.print_pat(*p));
1287                     }
1288                     try!(space(&mut self.s));
1289                     match arm.guard {
1290                         Some(e) => {
1291                             try!(self.word_space("if"));
1292                             try!(self.print_expr(e));
1293                             try!(space(&mut self.s));
1294                         }
1295                         None => ()
1296                     }
1297                     try!(self.word_space("=>"));
1298
1299                     match arm.body.node {
1300                         ast::ExprBlock(blk) => {
1301                             // the block will close the pattern's ibox
1302                             try!(self.print_block_unclosed_indent(blk, indent_unit));
1303                         }
1304                         _ => {
1305                             try!(self.end()); // close the ibox for the pattern
1306                             try!(self.print_expr(arm.body));
1307                         }
1308                     }
1309                     if !expr_is_simple_block(expr)
1310                         && i < len - 1 {
1311                         try!(word(&mut self.s, ","));
1312                     }
1313                     try!(self.end()); // close enclosing cbox
1314                 }
1315                 try!(self.bclose_(expr.span, indent_unit));
1316             }
1317             ast::ExprFnBlock(decl, body) => {
1318                 // in do/for blocks we don't want to show an empty
1319                 // argument list, but at this point we don't know which
1320                 // we are inside.
1321                 //
1322                 // if !decl.inputs.is_empty() {
1323                 try!(self.print_fn_block_args(decl));
1324                 try!(space(&mut self.s));
1325                 // }
1326
1327                 if !body.stmts.is_empty() || !body.expr.is_some() {
1328                     try!(self.print_block_unclosed(body));
1329                 } else {
1330                     // we extract the block, so as not to create another set of boxes
1331                     match body.expr.unwrap().node {
1332                         ast::ExprBlock(blk) => {
1333                             try!(self.print_block_unclosed(blk));
1334                         }
1335                         _ => {
1336                             // this is a bare expression
1337                             try!(self.print_expr(body.expr.unwrap()));
1338                             try!(self.end()); // need to close a box
1339                         }
1340                     }
1341                 }
1342                 // a box will be closed by print_expr, but we didn't want an overall
1343                 // wrapper so we closed the corresponding opening. so create an
1344                 // empty box to satisfy the close.
1345                 try!(self.ibox(0));
1346             }
1347             ast::ExprProc(decl, body) => {
1348                 // in do/for blocks we don't want to show an empty
1349                 // argument list, but at this point we don't know which
1350                 // we are inside.
1351                 //
1352                 // if !decl.inputs.is_empty() {
1353                 try!(self.print_proc_args(decl));
1354                 try!(space(&mut self.s));
1355                 // }
1356                 assert!(body.stmts.is_empty());
1357                 assert!(body.expr.is_some());
1358                 // we extract the block, so as not to create another set of boxes
1359                 match body.expr.unwrap().node {
1360                     ast::ExprBlock(blk) => {
1361                         try!(self.print_block_unclosed(blk));
1362                     }
1363                     _ => {
1364                         // this is a bare expression
1365                         try!(self.print_expr(body.expr.unwrap()));
1366                         try!(self.end()); // need to close a box
1367                     }
1368                 }
1369                 // a box will be closed by print_expr, but we didn't want an overall
1370                 // wrapper so we closed the corresponding opening. so create an
1371                 // empty box to satisfy the close.
1372                 try!(self.ibox(0));
1373             }
1374             ast::ExprBlock(blk) => {
1375                 // containing cbox, will be closed by print-block at }
1376                 try!(self.cbox(indent_unit));
1377                 // head-box, will be closed by print-block after {
1378                 try!(self.ibox(0u));
1379                 try!(self.print_block(blk));
1380             }
1381             ast::ExprAssign(lhs, rhs) => {
1382                 try!(self.print_expr(lhs));
1383                 try!(space(&mut self.s));
1384                 try!(self.word_space("="));
1385                 try!(self.print_expr(rhs));
1386             }
1387             ast::ExprAssignOp(op, lhs, rhs) => {
1388                 try!(self.print_expr(lhs));
1389                 try!(space(&mut self.s));
1390                 try!(word(&mut self.s, ast_util::binop_to_str(op)));
1391                 try!(self.word_space("="));
1392                 try!(self.print_expr(rhs));
1393             }
1394             ast::ExprField(expr, id, ref tys) => {
1395                 try!(self.print_expr(expr));
1396                 try!(word(&mut self.s, "."));
1397                 try!(self.print_ident(id));
1398                 if tys.len() > 0u {
1399                     try!(word(&mut self.s, "::<"));
1400                     try!(self.commasep(
1401                         Inconsistent, tys.as_slice(),
1402                         |s, ty| s.print_type_ref(ty)));
1403                     try!(word(&mut self.s, ">"));
1404                 }
1405             }
1406             ast::ExprIndex(expr, index) => {
1407                 try!(self.print_expr(expr));
1408                 try!(word(&mut self.s, "["));
1409                 try!(self.print_expr(index));
1410                 try!(word(&mut self.s, "]"));
1411             }
1412             ast::ExprPath(ref path) => try!(self.print_path(path, true)),
1413             ast::ExprBreak(opt_ident) => {
1414                 try!(word(&mut self.s, "break"));
1415                 try!(space(&mut self.s));
1416                 for ident in opt_ident.iter() {
1417                     try!(word(&mut self.s, "'"));
1418                     try!(self.print_ident(*ident));
1419                     try!(space(&mut self.s));
1420                 }
1421             }
1422             ast::ExprAgain(opt_ident) => {
1423                 try!(word(&mut self.s, "continue"));
1424                 try!(space(&mut self.s));
1425                 for ident in opt_ident.iter() {
1426                     try!(word(&mut self.s, "'"));
1427                     try!(self.print_ident(*ident));
1428                     try!(space(&mut self.s))
1429                 }
1430             }
1431             ast::ExprRet(result) => {
1432                 try!(word(&mut self.s, "return"));
1433                 match result {
1434                     Some(expr) => {
1435                         try!(word(&mut self.s, " "));
1436                         try!(self.print_expr(expr));
1437                     }
1438                     _ => ()
1439                 }
1440             }
1441             ast::ExprInlineAsm(ref a) => {
1442                 if a.volatile {
1443                     try!(word(&mut self.s, "__volatile__ asm!"));
1444                 } else {
1445                     try!(word(&mut self.s, "asm!"));
1446                 }
1447                 try!(self.popen());
1448                 try!(self.print_string(a.asm.get(), a.asm_str_style));
1449                 try!(self.word_space(":"));
1450                 for &(ref co, o) in a.outputs.iter() {
1451                     try!(self.print_string(co.get(), ast::CookedStr));
1452                     try!(self.popen());
1453                     try!(self.print_expr(o));
1454                     try!(self.pclose());
1455                     try!(self.word_space(","));
1456                 }
1457                 try!(self.word_space(":"));
1458                 for &(ref co, o) in a.inputs.iter() {
1459                     try!(self.print_string(co.get(), ast::CookedStr));
1460                     try!(self.popen());
1461                     try!(self.print_expr(o));
1462                     try!(self.pclose());
1463                     try!(self.word_space(","));
1464                 }
1465                 try!(self.word_space(":"));
1466                 try!(self.print_string(a.clobbers.get(), ast::CookedStr));
1467                 try!(self.pclose());
1468             }
1469             ast::ExprMac(ref m) => try!(self.print_mac(m)),
1470             ast::ExprParen(e) => {
1471                 try!(self.popen());
1472                 try!(self.print_expr(e));
1473                 try!(self.pclose());
1474             }
1475         }
1476         try!(self.ann.post(self, NodeExpr(expr)));
1477         self.end()
1478     }
1479
1480     pub fn print_local_decl(&mut self, loc: &ast::Local) -> IoResult<()> {
1481         try!(self.print_pat(loc.pat));
1482         match loc.ty.node {
1483             ast::TyInfer => Ok(()),
1484             _ => {
1485                 try!(self.word_space(":"));
1486                 self.print_type(loc.ty)
1487             }
1488         }
1489     }
1490
1491     pub fn print_decl(&mut self, decl: &ast::Decl) -> IoResult<()> {
1492         try!(self.maybe_print_comment(decl.span.lo));
1493         match decl.node {
1494             ast::DeclLocal(loc) => {
1495                 try!(self.space_if_not_bol());
1496                 try!(self.ibox(indent_unit));
1497                 try!(self.word_nbsp("let"));
1498
1499                 try!(self.ibox(indent_unit));
1500                 try!(self.print_local_decl(loc));
1501                 try!(self.end());
1502                 match loc.init {
1503                     Some(init) => {
1504                         try!(self.nbsp());
1505                         try!(self.word_space("="));
1506                         try!(self.print_expr(init));
1507                     }
1508                     _ => {}
1509                 }
1510                 self.end()
1511             }
1512             ast::DeclItem(item) => self.print_item(item)
1513         }
1514     }
1515
1516     pub fn print_ident(&mut self, ident: ast::Ident) -> IoResult<()> {
1517         word(&mut self.s, token::get_ident(ident).get())
1518     }
1519
1520     pub fn print_name(&mut self, name: ast::Name) -> IoResult<()> {
1521         word(&mut self.s, token::get_name(name).get())
1522     }
1523
1524     pub fn print_for_decl(&mut self, loc: &ast::Local,
1525                           coll: &ast::Expr) -> IoResult<()> {
1526         try!(self.print_local_decl(loc));
1527         try!(space(&mut self.s));
1528         try!(self.word_space("in"));
1529         self.print_expr(coll)
1530     }
1531
1532     fn print_path_(&mut self,
1533                    path: &ast::Path,
1534                    colons_before_params: bool,
1535                    opt_bounds: &Option<OwnedSlice<ast::TyParamBound>>)
1536         -> IoResult<()> {
1537         try!(self.maybe_print_comment(path.span.lo));
1538         if path.global {
1539             try!(word(&mut self.s, "::"));
1540         }
1541
1542         let mut first = true;
1543         for segment in path.segments.iter() {
1544             if first {
1545                 first = false
1546             } else {
1547                 try!(word(&mut self.s, "::"))
1548             }
1549
1550             try!(self.print_ident(segment.identifier));
1551
1552             if !segment.lifetimes.is_empty() || !segment.types.is_empty() {
1553                 if colons_before_params {
1554                     try!(word(&mut self.s, "::"))
1555                 }
1556                 try!(word(&mut self.s, "<"));
1557
1558                 let mut comma = false;
1559                 for lifetime in segment.lifetimes.iter() {
1560                     if comma {
1561                         try!(self.word_space(","))
1562                     }
1563                     try!(self.print_lifetime(lifetime));
1564                     comma = true;
1565                 }
1566
1567                 if !segment.types.is_empty() {
1568                     if comma {
1569                         try!(self.word_space(","))
1570                     }
1571                     try!(self.commasep(
1572                         Inconsistent,
1573                         segment.types.as_slice(),
1574                         |s, ty| s.print_type_ref(ty)));
1575                 }
1576
1577                 try!(word(&mut self.s, ">"))
1578             }
1579         }
1580
1581         match *opt_bounds {
1582             None => Ok(()),
1583             Some(ref bounds) => self.print_bounds(&None, bounds, true),
1584         }
1585     }
1586
1587     fn print_path(&mut self, path: &ast::Path,
1588                   colons_before_params: bool) -> IoResult<()> {
1589         self.print_path_(path, colons_before_params, &None)
1590     }
1591
1592     fn print_bounded_path(&mut self, path: &ast::Path,
1593                           bounds: &Option<OwnedSlice<ast::TyParamBound>>)
1594         -> IoResult<()> {
1595         self.print_path_(path, false, bounds)
1596     }
1597
1598     pub fn print_pat(&mut self, pat: &ast::Pat) -> IoResult<()> {
1599         try!(self.maybe_print_comment(pat.span.lo));
1600         try!(self.ann.pre(self, NodePat(pat)));
1601         /* Pat isn't normalized, but the beauty of it
1602          is that it doesn't matter */
1603         match pat.node {
1604             ast::PatWild => try!(word(&mut self.s, "_")),
1605             ast::PatWildMulti => try!(word(&mut self.s, "..")),
1606             ast::PatIdent(binding_mode, ref path, sub) => {
1607                 match binding_mode {
1608                     ast::BindByRef(mutbl) => {
1609                         try!(self.word_nbsp("ref"));
1610                         try!(self.print_mutability(mutbl));
1611                     }
1612                     ast::BindByValue(ast::MutImmutable) => {}
1613                     ast::BindByValue(ast::MutMutable) => {
1614                         try!(self.word_nbsp("mut"));
1615                     }
1616                 }
1617                 try!(self.print_path(path, true));
1618                 match sub {
1619                     Some(p) => {
1620                         try!(word(&mut self.s, "@"));
1621                         try!(self.print_pat(p));
1622                     }
1623                     None => ()
1624                 }
1625             }
1626             ast::PatEnum(ref path, ref args_) => {
1627                 try!(self.print_path(path, true));
1628                 match *args_ {
1629                     None => try!(word(&mut self.s, "(..)")),
1630                     Some(ref args) => {
1631                         if !args.is_empty() {
1632                             try!(self.popen());
1633                             try!(self.commasep(Inconsistent, args.as_slice(),
1634                                               |s, &p| s.print_pat(p)));
1635                             try!(self.pclose());
1636                         }
1637                     }
1638                 }
1639             }
1640             ast::PatStruct(ref path, ref fields, etc) => {
1641                 try!(self.print_path(path, true));
1642                 try!(word(&mut self.s, "{"));
1643                 try!(self.commasep_cmnt(
1644                     Consistent, fields.as_slice(),
1645                     |s, f| {
1646                         try!(s.cbox(indent_unit));
1647                         try!(s.print_ident(f.ident));
1648                         try!(s.word_space(":"));
1649                         try!(s.print_pat(f.pat));
1650                         s.end()
1651                     },
1652                     |f| f.pat.span));
1653                 if etc {
1654                     if fields.len() != 0u { try!(self.word_space(",")); }
1655                     try!(word(&mut self.s, ".."));
1656                 }
1657                 try!(word(&mut self.s, "}"));
1658             }
1659             ast::PatTup(ref elts) => {
1660                 try!(self.popen());
1661                 try!(self.commasep(Inconsistent,
1662                                    elts.as_slice(),
1663                                    |s, &p| s.print_pat(p)));
1664                 if elts.len() == 1 {
1665                     try!(word(&mut self.s, ","));
1666                 }
1667                 try!(self.pclose());
1668             }
1669             ast::PatUniq(inner) => {
1670                 try!(word(&mut self.s, "~"));
1671                 try!(self.print_pat(inner));
1672             }
1673             ast::PatRegion(inner) => {
1674                 try!(word(&mut self.s, "&"));
1675                 try!(self.print_pat(inner));
1676             }
1677             ast::PatLit(e) => try!(self.print_expr(e)),
1678             ast::PatRange(begin, end) => {
1679                 try!(self.print_expr(begin));
1680                 try!(space(&mut self.s));
1681                 try!(word(&mut self.s, ".."));
1682                 try!(self.print_expr(end));
1683             }
1684             ast::PatVec(ref before, slice, ref after) => {
1685                 try!(word(&mut self.s, "["));
1686                 try!(self.commasep(Inconsistent,
1687                                    before.as_slice(),
1688                                    |s, &p| s.print_pat(p)));
1689                 for &p in slice.iter() {
1690                     if !before.is_empty() { try!(self.word_space(",")); }
1691                     match *p {
1692                         ast::Pat { node: ast::PatWildMulti, .. } => {
1693                             // this case is handled by print_pat
1694                         }
1695                         _ => try!(word(&mut self.s, "..")),
1696                     }
1697                     try!(self.print_pat(p));
1698                     if !after.is_empty() { try!(self.word_space(",")); }
1699                 }
1700                 try!(self.commasep(Inconsistent,
1701                                    after.as_slice(),
1702                                    |s, &p| s.print_pat(p)));
1703                 try!(word(&mut self.s, "]"));
1704             }
1705         }
1706         self.ann.post(self, NodePat(pat))
1707     }
1708
1709     // Returns whether it printed anything
1710     fn print_explicit_self(&mut self,
1711                            explicit_self: ast::ExplicitSelf_,
1712                            mutbl: ast::Mutability) -> IoResult<bool> {
1713         try!(self.print_mutability(mutbl));
1714         match explicit_self {
1715             ast::SelfStatic => { return Ok(false); }
1716             ast::SelfValue => {
1717                 try!(word(&mut self.s, "self"));
1718             }
1719             ast::SelfUniq => {
1720                 try!(word(&mut self.s, "~self"));
1721             }
1722             ast::SelfRegion(ref lt, m) => {
1723                 try!(word(&mut self.s, "&"));
1724                 try!(self.print_opt_lifetime(lt));
1725                 try!(self.print_mutability(m));
1726                 try!(word(&mut self.s, "self"));
1727             }
1728         }
1729         return Ok(true);
1730     }
1731
1732     pub fn print_fn(&mut self,
1733                     decl: &ast::FnDecl,
1734                     fn_style: Option<ast::FnStyle>,
1735                     abi: abi::Abi,
1736                     name: ast::Ident,
1737                     generics: &ast::Generics,
1738                     opt_explicit_self: Option<ast::ExplicitSelf_>,
1739                     vis: ast::Visibility) -> IoResult<()> {
1740         try!(self.head(""));
1741         try!(self.print_fn_header_info(opt_explicit_self, fn_style, abi, vis));
1742         try!(self.nbsp());
1743         try!(self.print_ident(name));
1744         try!(self.print_generics(generics));
1745         self.print_fn_args_and_ret(decl, opt_explicit_self)
1746     }
1747
1748     pub fn print_fn_args(&mut self, decl: &ast::FnDecl,
1749                          opt_explicit_self: Option<ast::ExplicitSelf_>)
1750         -> IoResult<()> {
1751         // It is unfortunate to duplicate the commasep logic, but we want the
1752         // self type and the args all in the same box.
1753         try!(self.rbox(0u, Inconsistent));
1754         let mut first = true;
1755         for &explicit_self in opt_explicit_self.iter() {
1756             let m = match explicit_self {
1757                 ast::SelfStatic => ast::MutImmutable,
1758                 _ => match decl.inputs.get(0).pat.node {
1759                     ast::PatIdent(ast::BindByValue(m), _, _) => m,
1760                     _ => ast::MutImmutable
1761                 }
1762             };
1763             first = !try!(self.print_explicit_self(explicit_self, m));
1764         }
1765
1766         // HACK(eddyb) ignore the separately printed self argument.
1767         let args = if first {
1768             decl.inputs.as_slice()
1769         } else {
1770             decl.inputs.slice_from(1)
1771         };
1772
1773         for arg in args.iter() {
1774             if first { first = false; } else { try!(self.word_space(",")); }
1775             try!(self.print_arg(arg));
1776         }
1777
1778         self.end()
1779     }
1780
1781     pub fn print_fn_args_and_ret(&mut self, decl: &ast::FnDecl,
1782                                  opt_explicit_self: Option<ast::ExplicitSelf_>)
1783         -> IoResult<()> {
1784         try!(self.popen());
1785         try!(self.print_fn_args(decl, opt_explicit_self));
1786         if decl.variadic {
1787             try!(word(&mut self.s, ", ..."));
1788         }
1789         try!(self.pclose());
1790
1791         try!(self.maybe_print_comment(decl.output.span.lo));
1792         match decl.output.node {
1793             ast::TyNil => Ok(()),
1794             _ => {
1795                 try!(self.space_if_not_bol());
1796                 try!(self.word_space("->"));
1797                 self.print_type(decl.output)
1798             }
1799         }
1800     }
1801
1802     pub fn print_fn_block_args(&mut self,
1803                                decl: &ast::FnDecl) -> IoResult<()> {
1804         try!(word(&mut self.s, "|"));
1805         try!(self.print_fn_args(decl, None));
1806         try!(word(&mut self.s, "|"));
1807
1808         match decl.output.node {
1809             ast::TyInfer => {}
1810             _ => {
1811                 try!(self.space_if_not_bol());
1812                 try!(self.word_space("->"));
1813                 try!(self.print_type(decl.output));
1814             }
1815         }
1816
1817         self.maybe_print_comment(decl.output.span.lo)
1818     }
1819
1820     pub fn print_proc_args(&mut self, decl: &ast::FnDecl) -> IoResult<()> {
1821         try!(word(&mut self.s, "proc"));
1822         try!(word(&mut self.s, "("));
1823         try!(self.print_fn_args(decl, None));
1824         try!(word(&mut self.s, ")"));
1825
1826         match decl.output.node {
1827             ast::TyInfer => {}
1828             _ => {
1829                 try!(self.space_if_not_bol());
1830                 try!(self.word_space("->"));
1831                 try!(self.print_type(decl.output));
1832             }
1833         }
1834
1835         self.maybe_print_comment(decl.output.span.lo)
1836     }
1837
1838     pub fn print_bounds(&mut self,
1839                         region: &Option<ast::Lifetime>,
1840                         bounds: &OwnedSlice<ast::TyParamBound>,
1841                         print_colon_anyway: bool) -> IoResult<()> {
1842         if !bounds.is_empty() || region.is_some() {
1843             try!(word(&mut self.s, ":"));
1844             let mut first = true;
1845             match *region {
1846                 Some(ref lt) => {
1847                     let token = token::get_name(lt.name);
1848                     if token.get() != "static" {
1849                         try!(self.nbsp());
1850                         first = false;
1851                         try!(self.print_lifetime(lt));
1852                     }
1853                 }
1854                 None => {}
1855             }
1856             for bound in bounds.iter() {
1857                 try!(self.nbsp());
1858                 if first {
1859                     first = false;
1860                 } else {
1861                     try!(self.word_space("+"));
1862                 }
1863
1864                 try!(match *bound {
1865                     TraitTyParamBound(ref tref) => self.print_trait_ref(tref),
1866                     RegionTyParamBound => word(&mut self.s, "'static"),
1867                 })
1868             }
1869             Ok(())
1870         } else if print_colon_anyway {
1871             word(&mut self.s, ":")
1872         } else {
1873             Ok(())
1874         }
1875     }
1876
1877     pub fn print_lifetime(&mut self,
1878                           lifetime: &ast::Lifetime) -> IoResult<()> {
1879         try!(word(&mut self.s, "'"));
1880         self.print_name(lifetime.name)
1881     }
1882
1883     pub fn print_generics(&mut self,
1884                           generics: &ast::Generics) -> IoResult<()> {
1885         let total = generics.lifetimes.len() + generics.ty_params.len();
1886         if total > 0 {
1887             try!(word(&mut self.s, "<"));
1888
1889             let mut ints = Vec::new();
1890             for i in range(0u, total) {
1891                 ints.push(i);
1892             }
1893
1894             try!(self.commasep(
1895                 Inconsistent, ints.as_slice(),
1896                 |s, &idx| {
1897                     if idx < generics.lifetimes.len() {
1898                         let lifetime = generics.lifetimes.get(idx);
1899                         s.print_lifetime(lifetime)
1900                     } else {
1901                         let idx = idx - generics.lifetimes.len();
1902                         let param = generics.ty_params.get(idx);
1903                         try!(s.print_ident(param.ident));
1904                         try!(s.print_bounds(&None, &param.bounds, false));
1905                         match param.default {
1906                             Some(default) => {
1907                                 try!(space(&mut s.s));
1908                                 try!(s.word_space("="));
1909                                 s.print_type(default)
1910                             }
1911                             _ => Ok(())
1912                         }
1913                     }
1914                 }));
1915             word(&mut self.s, ">")
1916         } else {
1917             Ok(())
1918         }
1919     }
1920
1921     pub fn print_meta_item(&mut self, item: &ast::MetaItem) -> IoResult<()> {
1922         try!(self.ibox(indent_unit));
1923         match item.node {
1924             ast::MetaWord(ref name) => {
1925                 try!(word(&mut self.s, name.get()));
1926             }
1927             ast::MetaNameValue(ref name, ref value) => {
1928                 try!(self.word_space(name.get()));
1929                 try!(self.word_space("="));
1930                 try!(self.print_literal(value));
1931             }
1932             ast::MetaList(ref name, ref items) => {
1933                 try!(word(&mut self.s, name.get()));
1934                 try!(self.popen());
1935                 try!(self.commasep(Consistent,
1936                                    items.as_slice(),
1937                                    |s, &i| s.print_meta_item(i)));
1938                 try!(self.pclose());
1939             }
1940         }
1941         self.end()
1942     }
1943
1944     pub fn print_view_path(&mut self, vp: &ast::ViewPath) -> IoResult<()> {
1945         match vp.node {
1946             ast::ViewPathSimple(ident, ref path, _) => {
1947                 // FIXME(#6993) can't compare identifiers directly here
1948                 if path.segments.last().unwrap().identifier.name != ident.name {
1949                     try!(self.print_ident(ident));
1950                     try!(space(&mut self.s));
1951                     try!(self.word_space("="));
1952                 }
1953                 self.print_path(path, false)
1954             }
1955
1956             ast::ViewPathGlob(ref path, _) => {
1957                 try!(self.print_path(path, false));
1958                 word(&mut self.s, "::*")
1959             }
1960
1961             ast::ViewPathList(ref path, ref idents, _) => {
1962                 if path.segments.is_empty() {
1963                     try!(word(&mut self.s, "{"));
1964                 } else {
1965                     try!(self.print_path(path, false));
1966                     try!(word(&mut self.s, "::{"));
1967                 }
1968                 try!(self.commasep(Inconsistent, idents.as_slice(), |s, w| {
1969                     s.print_ident(w.node.name)
1970                 }));
1971                 word(&mut self.s, "}")
1972             }
1973         }
1974     }
1975
1976     pub fn print_view_paths(&mut self,
1977                             vps: &[@ast::ViewPath]) -> IoResult<()> {
1978         self.commasep(Inconsistent, vps, |s, &vp| s.print_view_path(vp))
1979     }
1980
1981     pub fn print_view_item(&mut self, item: &ast::ViewItem) -> IoResult<()> {
1982         try!(self.hardbreak_if_not_bol());
1983         try!(self.maybe_print_comment(item.span.lo));
1984         try!(self.print_outer_attributes(item.attrs.as_slice()));
1985         try!(self.print_visibility(item.vis));
1986         match item.node {
1987             ast::ViewItemExternCrate(id, ref optional_path, _) => {
1988                 try!(self.head("extern crate"));
1989                 try!(self.print_ident(id));
1990                 for &(ref p, style) in optional_path.iter() {
1991                     try!(space(&mut self.s));
1992                     try!(word(&mut self.s, "="));
1993                     try!(space(&mut self.s));
1994                     try!(self.print_string(p.get(), style));
1995                 }
1996             }
1997
1998             ast::ViewItemUse(ref vps) => {
1999                 try!(self.head("use"));
2000                 try!(self.print_view_paths(vps.as_slice()));
2001             }
2002         }
2003         try!(word(&mut self.s, ";"));
2004         try!(self.end()); // end inner head-block
2005         self.end() // end outer head-block
2006     }
2007
2008     pub fn print_mutability(&mut self,
2009                             mutbl: ast::Mutability) -> IoResult<()> {
2010         match mutbl {
2011             ast::MutMutable => self.word_nbsp("mut"),
2012             ast::MutImmutable => Ok(()),
2013         }
2014     }
2015
2016     pub fn print_mt(&mut self, mt: &ast::MutTy) -> IoResult<()> {
2017         try!(self.print_mutability(mt.mutbl));
2018         self.print_type(mt.ty)
2019     }
2020
2021     pub fn print_arg(&mut self, input: &ast::Arg) -> IoResult<()> {
2022         try!(self.ibox(indent_unit));
2023         match input.ty.node {
2024             ast::TyInfer => try!(self.print_pat(input.pat)),
2025             _ => {
2026                 match input.pat.node {
2027                     ast::PatIdent(_, ref path, _) if
2028                         path.segments.len() == 1 &&
2029                         path.segments.get(0).identifier.name ==
2030                             parse::token::special_idents::invalid.name => {
2031                         // Do nothing.
2032                     }
2033                     _ => {
2034                         try!(self.print_pat(input.pat));
2035                         try!(word(&mut self.s, ":"));
2036                         try!(space(&mut self.s));
2037                     }
2038                 }
2039                 try!(self.print_type(input.ty));
2040             }
2041         }
2042         self.end()
2043     }
2044
2045     pub fn print_ty_fn(&mut self,
2046                        opt_abi: Option<abi::Abi>,
2047                        opt_sigil: Option<char>,
2048                        opt_region: &Option<ast::Lifetime>,
2049                        fn_style: ast::FnStyle,
2050                        onceness: ast::Onceness,
2051                        decl: &ast::FnDecl,
2052                        id: Option<ast::Ident>,
2053                        opt_bounds: &Option<OwnedSlice<ast::TyParamBound>>,
2054                        generics: Option<&ast::Generics>,
2055                        opt_explicit_self: Option<ast::ExplicitSelf_>)
2056         -> IoResult<()> {
2057         try!(self.ibox(indent_unit));
2058
2059         // Duplicates the logic in `print_fn_header_info()`.  This is because that
2060         // function prints the sigil in the wrong place.  That should be fixed.
2061         if opt_sigil == Some('~') && onceness == ast::Once {
2062             try!(word(&mut self.s, "proc"));
2063         } else if opt_sigil == Some('&') {
2064             try!(self.print_extern_opt_abi(opt_abi));
2065             try!(self.print_fn_style(fn_style));
2066             try!(self.print_onceness(onceness));
2067         } else {
2068             assert!(opt_sigil.is_none());
2069             try!(self.print_opt_abi_and_extern_if_nondefault(opt_abi));
2070             try!(self.print_fn_style(fn_style));
2071             try!(self.print_onceness(onceness));
2072             try!(word(&mut self.s, "fn"));
2073         }
2074
2075         match id {
2076             Some(id) => {
2077                 try!(word(&mut self.s, " "));
2078                 try!(self.print_ident(id));
2079             }
2080             _ => ()
2081         }
2082
2083         match generics { Some(g) => try!(self.print_generics(g)), _ => () }
2084         try!(zerobreak(&mut self.s));
2085
2086         if opt_sigil == Some('&') {
2087             try!(word(&mut self.s, "|"));
2088         } else {
2089             try!(self.popen());
2090         }
2091
2092         try!(self.print_fn_args(decl, opt_explicit_self));
2093
2094         if opt_sigil == Some('&') {
2095             try!(word(&mut self.s, "|"));
2096         } else {
2097             if decl.variadic {
2098                 try!(word(&mut self.s, ", ..."));
2099             }
2100             try!(self.pclose());
2101         }
2102
2103         opt_bounds.as_ref().map(|bounds| {
2104             self.print_bounds(opt_region, bounds, true)
2105         });
2106
2107         try!(self.maybe_print_comment(decl.output.span.lo));
2108
2109         match decl.output.node {
2110             ast::TyNil => {}
2111             _ => {
2112                 try!(self.space_if_not_bol());
2113                 try!(self.ibox(indent_unit));
2114                 try!(self.word_space("->"));
2115                 if decl.cf == ast::NoReturn {
2116                     try!(self.word_nbsp("!"));
2117                 } else {
2118                     try!(self.print_type(decl.output));
2119                 }
2120                 try!(self.end());
2121             }
2122         }
2123
2124         self.end()
2125     }
2126
2127     pub fn maybe_print_trailing_comment(&mut self, span: codemap::Span,
2128                                         next_pos: Option<BytePos>)
2129         -> IoResult<()> {
2130         let cm = match self.cm {
2131             Some(cm) => cm,
2132             _ => return Ok(())
2133         };
2134         match self.next_comment() {
2135             Some(ref cmnt) => {
2136                 if (*cmnt).style != comments::Trailing { return Ok(()) }
2137                 let span_line = cm.lookup_char_pos(span.hi);
2138                 let comment_line = cm.lookup_char_pos((*cmnt).pos);
2139                 let mut next = (*cmnt).pos + BytePos(1);
2140                 match next_pos { None => (), Some(p) => next = p }
2141                 if span.hi < (*cmnt).pos && (*cmnt).pos < next &&
2142                     span_line.line == comment_line.line {
2143                         try!(self.print_comment(cmnt));
2144                         self.cur_cmnt_and_lit.cur_cmnt += 1u;
2145                     }
2146             }
2147             _ => ()
2148         }
2149         Ok(())
2150     }
2151
2152     pub fn print_remaining_comments(&mut self) -> IoResult<()> {
2153         // If there aren't any remaining comments, then we need to manually
2154         // make sure there is a line break at the end.
2155         if self.next_comment().is_none() {
2156             try!(hardbreak(&mut self.s));
2157         }
2158         loop {
2159             match self.next_comment() {
2160                 Some(ref cmnt) => {
2161                     try!(self.print_comment(cmnt));
2162                     self.cur_cmnt_and_lit.cur_cmnt += 1u;
2163                 }
2164                 _ => break
2165             }
2166         }
2167         Ok(())
2168     }
2169
2170     pub fn print_literal(&mut self, lit: &ast::Lit) -> IoResult<()> {
2171         try!(self.maybe_print_comment(lit.span.lo));
2172         match self.next_lit(lit.span.lo) {
2173             Some(ref ltrl) => {
2174                 return word(&mut self.s, (*ltrl).lit);
2175             }
2176             _ => ()
2177         }
2178         match lit.node {
2179             ast::LitStr(ref st, style) => self.print_string(st.get(), style),
2180             ast::LitChar(ch) => {
2181                 let mut res = StrBuf::from_str("'");
2182                 char::from_u32(ch).unwrap().escape_default(|c| res.push_char(c));
2183                 res.push_char('\'');
2184                 word(&mut self.s, res.into_owned())
2185             }
2186             ast::LitInt(i, t) => {
2187                 word(&mut self.s, ast_util::int_ty_to_str(t, Some(i)))
2188             }
2189             ast::LitUint(u, t) => {
2190                 word(&mut self.s, ast_util::uint_ty_to_str(t, Some(u)))
2191             }
2192             ast::LitIntUnsuffixed(i) => {
2193                 word(&mut self.s, format!("{}", i))
2194             }
2195             ast::LitFloat(ref f, t) => {
2196                 word(&mut self.s, f.get() + ast_util::float_ty_to_str(t))
2197             }
2198             ast::LitFloatUnsuffixed(ref f) => word(&mut self.s, f.get()),
2199             ast::LitNil => word(&mut self.s, "()"),
2200             ast::LitBool(val) => {
2201                 if val { word(&mut self.s, "true") } else { word(&mut self.s, "false") }
2202             }
2203             ast::LitBinary(ref arr) => {
2204                 try!(self.ibox(indent_unit));
2205                 try!(word(&mut self.s, "["));
2206                 try!(self.commasep_cmnt(Inconsistent, arr.as_slice(),
2207                                         |s, u| word(&mut s.s, format!("{}", *u)),
2208                                         |_| lit.span));
2209                 try!(word(&mut self.s, "]"));
2210                 self.end()
2211             }
2212         }
2213     }
2214
2215     pub fn next_lit(&mut self, pos: BytePos) -> Option<comments::Literal> {
2216         match self.literals {
2217             Some(ref lits) => {
2218                 while self.cur_cmnt_and_lit.cur_lit < lits.len() {
2219                     let ltrl = (*(*lits).get(self.cur_cmnt_and_lit.cur_lit)).clone();
2220                     if ltrl.pos > pos { return None; }
2221                     self.cur_cmnt_and_lit.cur_lit += 1u;
2222                     if ltrl.pos == pos { return Some(ltrl); }
2223                 }
2224                 None
2225             }
2226             _ => None
2227         }
2228     }
2229
2230     pub fn maybe_print_comment(&mut self, pos: BytePos) -> IoResult<()> {
2231         loop {
2232             match self.next_comment() {
2233                 Some(ref cmnt) => {
2234                     if (*cmnt).pos < pos {
2235                         try!(self.print_comment(cmnt));
2236                         self.cur_cmnt_and_lit.cur_cmnt += 1u;
2237                     } else { break; }
2238                 }
2239                 _ => break
2240             }
2241         }
2242         Ok(())
2243     }
2244
2245     pub fn print_comment(&mut self,
2246                          cmnt: &comments::Comment) -> IoResult<()> {
2247         match cmnt.style {
2248             comments::Mixed => {
2249                 assert_eq!(cmnt.lines.len(), 1u);
2250                 try!(zerobreak(&mut self.s));
2251                 try!(word(&mut self.s, *cmnt.lines.get(0)));
2252                 zerobreak(&mut self.s)
2253             }
2254             comments::Isolated => {
2255                 try!(self.hardbreak_if_not_bol());
2256                 for line in cmnt.lines.iter() {
2257                     // Don't print empty lines because they will end up as trailing
2258                     // whitespace
2259                     if !line.is_empty() {
2260                         try!(word(&mut self.s, *line));
2261                     }
2262                     try!(hardbreak(&mut self.s));
2263                 }
2264                 Ok(())
2265             }
2266             comments::Trailing => {
2267                 try!(word(&mut self.s, " "));
2268                 if cmnt.lines.len() == 1u {
2269                     try!(word(&mut self.s, *cmnt.lines.get(0)));
2270                     hardbreak(&mut self.s)
2271                 } else {
2272                     try!(self.ibox(0u));
2273                     for line in cmnt.lines.iter() {
2274                         if !line.is_empty() {
2275                             try!(word(&mut self.s, *line));
2276                         }
2277                         try!(hardbreak(&mut self.s));
2278                     }
2279                     self.end()
2280                 }
2281             }
2282             comments::BlankLine => {
2283                 // We need to do at least one, possibly two hardbreaks.
2284                 let is_semi = match self.s.last_token() {
2285                     pp::String(s, _) => ";" == s,
2286                     _ => false
2287                 };
2288                 if is_semi || self.is_begin() || self.is_end() {
2289                     try!(hardbreak(&mut self.s));
2290                 }
2291                 hardbreak(&mut self.s)
2292             }
2293         }
2294     }
2295
2296     pub fn print_string(&mut self, st: &str,
2297                         style: ast::StrStyle) -> IoResult<()> {
2298         let st = match style {
2299             ast::CookedStr => format!("\"{}\"", st.escape_default()),
2300             ast::RawStr(n) => format!("r{delim}\"{string}\"{delim}",
2301                                       delim="#".repeat(n), string=st)
2302         };
2303         word(&mut self.s, st)
2304     }
2305
2306     pub fn next_comment(&mut self) -> Option<comments::Comment> {
2307         match self.comments {
2308             Some(ref cmnts) => {
2309                 if self.cur_cmnt_and_lit.cur_cmnt < cmnts.len() {
2310                     Some((*cmnts.get(self.cur_cmnt_and_lit.cur_cmnt)).clone())
2311                 } else {
2312                     None
2313                 }
2314             }
2315             _ => None
2316         }
2317     }
2318
2319     pub fn print_opt_fn_style(&mut self,
2320                             opt_fn_style: Option<ast::FnStyle>) -> IoResult<()> {
2321         match opt_fn_style {
2322             Some(fn_style) => self.print_fn_style(fn_style),
2323             None => Ok(())
2324         }
2325     }
2326
2327     pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
2328                                                   opt_abi: Option<abi::Abi>)
2329         -> IoResult<()> {
2330         match opt_abi {
2331             Some(abi::Rust) => Ok(()),
2332             Some(abi) => {
2333                 try!(self.word_nbsp("extern"));
2334                 self.word_nbsp(abi.to_str())
2335             }
2336             None => Ok(())
2337         }
2338     }
2339
2340     pub fn print_extern_opt_abi(&mut self,
2341                                 opt_abi: Option<abi::Abi>) -> IoResult<()> {
2342         match opt_abi {
2343             Some(abi) => {
2344                 try!(self.word_nbsp("extern"));
2345                 self.word_nbsp(abi.to_str())
2346             }
2347             None => Ok(())
2348         }
2349     }
2350
2351     pub fn print_fn_header_info(&mut self,
2352                                 _opt_explicit_self: Option<ast::ExplicitSelf_>,
2353                                 opt_fn_style: Option<ast::FnStyle>,
2354                                 abi: abi::Abi,
2355                                 vis: ast::Visibility) -> IoResult<()> {
2356         try!(word(&mut self.s, visibility_qualified(vis, "")));
2357
2358         if abi != abi::Rust {
2359             try!(self.word_nbsp("extern"));
2360             try!(self.word_nbsp(abi.to_str()));
2361
2362             if opt_fn_style != Some(ast::ExternFn) {
2363                 try!(self.print_opt_fn_style(opt_fn_style));
2364             }
2365         } else {
2366             try!(self.print_opt_fn_style(opt_fn_style));
2367         }
2368
2369         word(&mut self.s, "fn")
2370     }
2371
2372     pub fn print_fn_style(&mut self, s: ast::FnStyle) -> IoResult<()> {
2373         match s {
2374             ast::NormalFn => Ok(()),
2375             ast::UnsafeFn => self.word_nbsp("unsafe"),
2376             ast::ExternFn => self.word_nbsp("extern")
2377         }
2378     }
2379
2380     pub fn print_onceness(&mut self, o: ast::Onceness) -> IoResult<()> {
2381         match o {
2382             ast::Once => self.word_nbsp("once"),
2383             ast::Many => Ok(())
2384         }
2385     }
2386 }
2387
2388 #[cfg(test)]
2389 mod test {
2390     use super::*;
2391
2392     use ast;
2393     use ast_util;
2394     use codemap;
2395     use parse::token;
2396
2397     #[test]
2398     fn test_fun_to_str() {
2399         let abba_ident = token::str_to_ident("abba");
2400
2401         let decl = ast::FnDecl {
2402             inputs: Vec::new(),
2403             output: ast::P(ast::Ty {id: 0,
2404                                     node: ast::TyNil,
2405                                     span: codemap::DUMMY_SP}),
2406             cf: ast::Return,
2407             variadic: false
2408         };
2409         let generics = ast_util::empty_generics();
2410         assert_eq!(&fun_to_str(&decl, ast::NormalFn, abba_ident,
2411                                None, &generics),
2412                    &~"fn abba()");
2413     }
2414
2415     #[test]
2416     fn test_variant_to_str() {
2417         let ident = token::str_to_ident("principal_skinner");
2418
2419         let var = codemap::respan(codemap::DUMMY_SP, ast::Variant_ {
2420             name: ident,
2421             attrs: Vec::new(),
2422             // making this up as I go.... ?
2423             kind: ast::TupleVariantKind(Vec::new()),
2424             id: 0,
2425             disr_expr: None,
2426             vis: ast::Public,
2427         });
2428
2429         let varstr = variant_to_str(&var);
2430         assert_eq!(&varstr,&~"pub principal_skinner");
2431     }
2432 }