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