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