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