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