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