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