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