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