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