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