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