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