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