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