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