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