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