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