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