]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/print/pprust.rs
Rename `Item.node` to `Item.kind`
[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::attr;
6 use crate::source_map::{self, SourceMap, Spanned};
7 use crate::parse::token::{self, BinOpToken, DelimToken, Nonterminal, Token, TokenKind};
8 use crate::parse::lexer::comments;
9 use crate::parse::{self, ParseSess};
10 use crate::print::pp::{self, Breaks};
11 use crate::print::pp::Breaks::{Consistent, Inconsistent};
12 use crate::ptr::P;
13 use crate::symbol::{kw, sym};
14 use crate::tokenstream::{self, TokenStream, TokenTree};
15
16 use rustc_target::spec::abi::{self, Abi};
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)        => meta_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 pub fn meta_item_to_string(mi: &ast::MetaItem) -> String {
416     to_string(|s| s.print_meta_item(mi))
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         if attr.is_sugared_doc {
625             self.word(attr.value_str().unwrap().as_str().to_string());
626             self.hardbreak()
627         } else {
628             match attr.style {
629                 ast::AttrStyle::Inner => self.word("#!["),
630                 ast::AttrStyle::Outer => self.word("#["),
631             }
632             self.ibox(0);
633             match attr.tokens.trees().next() {
634                 Some(TokenTree::Delimited(_, delim, tts)) => {
635                     self.print_mac_common(
636                         Some(MacHeader::Path(&attr.path)), false, None, delim, tts, true, attr.span
637                     );
638                 }
639                 tree => {
640                     self.print_path(&attr.path, false, 0);
641                     if tree.is_some() {
642                         self.space();
643                         self.print_tts(attr.tokens.clone(), true);
644                     }
645                 }
646             }
647             self.end();
648             self.word("]");
649         }
650     }
651
652     fn print_meta_list_item(&mut self, item: &ast::NestedMetaItem) {
653         match item {
654             ast::NestedMetaItem::MetaItem(ref mi) => {
655                 self.print_meta_item(mi)
656             },
657             ast::NestedMetaItem::Literal(ref lit) => {
658                 self.print_literal(lit)
659             }
660         }
661     }
662
663     fn print_meta_item(&mut self, item: &ast::MetaItem) {
664         self.ibox(INDENT_UNIT);
665         match item.node {
666             ast::MetaItemKind::Word => self.print_path(&item.path, false, 0),
667             ast::MetaItemKind::NameValue(ref value) => {
668                 self.print_path(&item.path, false, 0);
669                 self.space();
670                 self.word_space("=");
671                 self.print_literal(value);
672             }
673             ast::MetaItemKind::List(ref items) => {
674                 self.print_path(&item.path, false, 0);
675                 self.popen();
676                 self.commasep(Consistent,
677                               &items[..],
678                               |s, i| s.print_meta_list_item(i));
679                 self.pclose();
680             }
681         }
682         self.end();
683     }
684
685     /// This doesn't deserve to be called "pretty" printing, but it should be
686     /// meaning-preserving. A quick hack that might help would be to look at the
687     /// spans embedded in the TTs to decide where to put spaces and newlines.
688     /// But it'd be better to parse these according to the grammar of the
689     /// appropriate macro, transcribe back into the grammar we just parsed from,
690     /// and then pretty-print the resulting AST nodes (so, e.g., we print
691     /// expression arguments as expressions). It can be done! I think.
692     fn print_tt(&mut self, tt: tokenstream::TokenTree, convert_dollar_crate: bool) {
693         match tt {
694             TokenTree::Token(ref token) => {
695                 self.word(token_to_string_ext(&token, convert_dollar_crate));
696                 match token.kind {
697                     token::DocComment(..) => {
698                         self.hardbreak()
699                     }
700                     _ => {}
701                 }
702             }
703             TokenTree::Delimited(dspan, delim, tts) => {
704                 self.print_mac_common(
705                     None, false, None, delim, tts, convert_dollar_crate, dspan.entire()
706                 );
707             }
708         }
709     }
710
711     fn print_tts(&mut self, tts: tokenstream::TokenStream, convert_dollar_crate: bool) {
712         for (i, tt) in tts.into_trees().enumerate() {
713             if i != 0 && tt_prepend_space(&tt) {
714                 self.space();
715             }
716             self.print_tt(tt, convert_dollar_crate);
717         }
718     }
719
720     fn print_mac_common(
721         &mut self,
722         header: Option<MacHeader<'_>>,
723         has_bang: bool,
724         ident: Option<ast::Ident>,
725         delim: DelimToken,
726         tts: TokenStream,
727         convert_dollar_crate: bool,
728         span: Span,
729     ) {
730         if delim == DelimToken::Brace {
731             self.cbox(INDENT_UNIT);
732         }
733         match header {
734             Some(MacHeader::Path(path)) => self.print_path(path, false, 0),
735             Some(MacHeader::Keyword(kw)) => self.word(kw),
736             None => {}
737         }
738         if has_bang {
739             self.word("!");
740         }
741         if let Some(ident) = ident {
742             self.nbsp();
743             self.print_ident(ident);
744         }
745         match delim {
746             DelimToken::Brace => {
747                 if header.is_some() || has_bang || ident.is_some() {
748                     self.nbsp();
749                 }
750                 self.word("{");
751                 if !tts.is_empty() {
752                     self.space();
753                 }
754             }
755             _ => self.word(token_kind_to_string(&token::OpenDelim(delim))),
756         }
757         self.ibox(0);
758         self.print_tts(tts, convert_dollar_crate);
759         self.end();
760         match delim {
761             DelimToken::Brace => self.bclose(span),
762             _ => self.word(token_kind_to_string(&token::CloseDelim(delim))),
763         }
764     }
765
766     fn print_path(&mut self, path: &ast::Path, colons_before_params: bool, depth: usize) {
767         self.maybe_print_comment(path.span.lo());
768
769         for (i, segment) in path.segments[..path.segments.len() - depth].iter().enumerate() {
770             if i > 0 {
771                 self.word("::")
772             }
773             self.print_path_segment(segment, colons_before_params);
774         }
775     }
776
777     fn print_path_segment(&mut self, segment: &ast::PathSegment, colons_before_params: bool) {
778         if segment.ident.name != kw::PathRoot {
779             self.print_ident(segment.ident);
780             if let Some(ref args) = segment.args {
781                 self.print_generic_args(args, colons_before_params);
782             }
783         }
784     }
785
786     fn head<S: Into<Cow<'static, str>>>(&mut self, w: S) {
787         let w = w.into();
788         // Outer-box is consistent.
789         self.cbox(INDENT_UNIT);
790         // Head-box is inconsistent.
791         self.ibox(w.len() + 1);
792         // Keyword that starts the head.
793         if !w.is_empty() {
794             self.word_nbsp(w);
795         }
796     }
797
798     fn bopen(&mut self) {
799         self.word("{");
800         self.end(); // Close the head-box.
801     }
802
803     fn bclose_maybe_open(&mut self, span: syntax_pos::Span, close_box: bool) {
804         self.maybe_print_comment(span.hi());
805         self.break_offset_if_not_bol(1, -(INDENT_UNIT as isize));
806         self.word("}");
807         if close_box {
808             self.end(); // Close the outer-box.
809         }
810     }
811
812     fn bclose(&mut self, span: syntax_pos::Span) {
813         self.bclose_maybe_open(span, true)
814     }
815
816     fn break_offset_if_not_bol(&mut self, n: usize, off: isize) {
817         if !self.is_beginning_of_line() {
818             self.break_offset(n, off)
819         } else {
820             if off != 0 && self.last_token().is_hardbreak_tok() {
821                 // We do something pretty sketchy here: tuck the nonzero
822                 // offset-adjustment we were going to deposit along with the
823                 // break into the previous hardbreak.
824                 self.replace_last_token(pp::Printer::hardbreak_tok_offset(off));
825             }
826         }
827     }
828 }
829
830 impl<'a> PrintState<'a> for State<'a> {
831     fn comments(&mut self) -> &mut Option<Comments<'a>> {
832         &mut self.comments
833     }
834
835     fn print_ident(&mut self, ident: ast::Ident) {
836         self.s.word(ast_ident_to_string(ident, ident.is_raw_guess()));
837         self.ann.post(self, AnnNode::Ident(&ident))
838     }
839
840     fn print_generic_args(&mut self, args: &ast::GenericArgs, colons_before_params: bool) {
841         if colons_before_params {
842             self.s.word("::")
843         }
844
845         match *args {
846             ast::GenericArgs::AngleBracketed(ref data) => {
847                 self.s.word("<");
848
849                 self.commasep(Inconsistent, &data.args, |s, generic_arg| {
850                     s.print_generic_arg(generic_arg)
851                 });
852
853                 let mut comma = data.args.len() != 0;
854
855                 for constraint in data.constraints.iter() {
856                     if comma {
857                         self.word_space(",")
858                     }
859                     self.print_ident(constraint.ident);
860                     self.s.space();
861                     match constraint.kind {
862                         ast::AssocTyConstraintKind::Equality { ref ty } => {
863                             self.word_space("=");
864                             self.print_type(ty);
865                         }
866                         ast::AssocTyConstraintKind::Bound { ref bounds } => {
867                             self.print_type_bounds(":", &*bounds);
868                         }
869                     }
870                     comma = true;
871                 }
872
873                 self.s.word(">")
874             }
875
876             ast::GenericArgs::Parenthesized(ref data) => {
877                 self.s.word("(");
878                 self.commasep(
879                     Inconsistent,
880                     &data.inputs,
881                     |s, ty| s.print_type(ty));
882                 self.s.word(")");
883
884                 if let Some(ref ty) = data.output {
885                     self.space_if_not_bol();
886                     self.word_space("->");
887                     self.print_type(ty);
888                 }
889             }
890         }
891     }
892 }
893
894 impl<'a> State<'a> {
895     // Synthesizes a comment that was not textually present in the original source
896     // file.
897     pub fn synth_comment(&mut self, text: String) {
898         self.s.word("/*");
899         self.s.space();
900         self.s.word(text);
901         self.s.space();
902         self.s.word("*/")
903     }
904
905     crate fn commasep_cmnt<T, F, G>(&mut self,
906                                   b: Breaks,
907                                   elts: &[T],
908                                   mut op: F,
909                                   mut get_span: G) where
910         F: FnMut(&mut State<'_>, &T),
911         G: FnMut(&T) -> syntax_pos::Span,
912     {
913         self.rbox(0, b);
914         let len = elts.len();
915         let mut i = 0;
916         for elt in elts {
917             self.maybe_print_comment(get_span(elt).hi());
918             op(self, elt);
919             i += 1;
920             if i < len {
921                 self.s.word(",");
922                 self.maybe_print_trailing_comment(get_span(elt),
923                                                   Some(get_span(&elts[i]).hi()));
924                 self.space_if_not_bol();
925             }
926         }
927         self.end();
928     }
929
930     crate fn commasep_exprs(&mut self, b: Breaks,
931                             exprs: &[P<ast::Expr>]) {
932         self.commasep_cmnt(b, exprs, |s, e| s.print_expr(e), |e| e.span)
933     }
934
935     crate fn print_mod(&mut self, _mod: &ast::Mod,
936                        attrs: &[ast::Attribute]) {
937         self.print_inner_attributes(attrs);
938         for item in &_mod.items {
939             self.print_item(item);
940         }
941     }
942
943     crate fn print_foreign_mod(&mut self, nmod: &ast::ForeignMod,
944                                attrs: &[ast::Attribute]) {
945         self.print_inner_attributes(attrs);
946         for item in &nmod.items {
947             self.print_foreign_item(item);
948         }
949     }
950
951     crate fn print_opt_lifetime(&mut self, lifetime: &Option<ast::Lifetime>) {
952         if let Some(lt) = *lifetime {
953             self.print_lifetime(lt);
954             self.nbsp();
955         }
956     }
957
958     crate fn print_generic_arg(&mut self, generic_arg: &GenericArg) {
959         match generic_arg {
960             GenericArg::Lifetime(lt) => self.print_lifetime(*lt),
961             GenericArg::Type(ty) => self.print_type(ty),
962             GenericArg::Const(ct) => self.print_expr(&ct.value),
963         }
964     }
965
966     crate fn print_type(&mut self, ty: &ast::Ty) {
967         self.maybe_print_comment(ty.span.lo());
968         self.ibox(0);
969         match ty.kind {
970             ast::TyKind::Slice(ref ty) => {
971                 self.s.word("[");
972                 self.print_type(ty);
973                 self.s.word("]");
974             }
975             ast::TyKind::Ptr(ref mt) => {
976                 self.s.word("*");
977                 match mt.mutbl {
978                     ast::Mutability::Mutable => self.word_nbsp("mut"),
979                     ast::Mutability::Immutable => self.word_nbsp("const"),
980                 }
981                 self.print_type(&mt.ty);
982             }
983             ast::TyKind::Rptr(ref lifetime, ref mt) => {
984                 self.s.word("&");
985                 self.print_opt_lifetime(lifetime);
986                 self.print_mt(mt);
987             }
988             ast::TyKind::Never => {
989                 self.s.word("!");
990             },
991             ast::TyKind::Tup(ref elts) => {
992                 self.popen();
993                 self.commasep(Inconsistent, &elts[..],
994                               |s, ty| s.print_type(ty));
995                 if elts.len() == 1 {
996                     self.s.word(",");
997                 }
998                 self.pclose();
999             }
1000             ast::TyKind::Paren(ref typ) => {
1001                 self.popen();
1002                 self.print_type(typ);
1003                 self.pclose();
1004             }
1005             ast::TyKind::BareFn(ref f) => {
1006                 self.print_ty_fn(f.abi,
1007                                  f.unsafety,
1008                                  &f.decl,
1009                                  None,
1010                                  &f.generic_params);
1011             }
1012             ast::TyKind::Path(None, ref path) => {
1013                 self.print_path(path, false, 0);
1014             }
1015             ast::TyKind::Path(Some(ref qself), ref path) => {
1016                 self.print_qpath(path, qself, false)
1017             }
1018             ast::TyKind::TraitObject(ref bounds, syntax) => {
1019                 let prefix = if syntax == ast::TraitObjectSyntax::Dyn { "dyn" } else { "" };
1020                 self.print_type_bounds(prefix, &bounds[..]);
1021             }
1022             ast::TyKind::ImplTrait(_, ref bounds) => {
1023                 self.print_type_bounds("impl", &bounds[..]);
1024             }
1025             ast::TyKind::Array(ref ty, ref length) => {
1026                 self.s.word("[");
1027                 self.print_type(ty);
1028                 self.s.word("; ");
1029                 self.print_expr(&length.value);
1030                 self.s.word("]");
1031             }
1032             ast::TyKind::Typeof(ref e) => {
1033                 self.s.word("typeof(");
1034                 self.print_expr(&e.value);
1035                 self.s.word(")");
1036             }
1037             ast::TyKind::Infer => {
1038                 self.s.word("_");
1039             }
1040             ast::TyKind::Err => {
1041                 self.popen();
1042                 self.s.word("/*ERROR*/");
1043                 self.pclose();
1044             }
1045             ast::TyKind::ImplicitSelf => {
1046                 self.s.word("Self");
1047             }
1048             ast::TyKind::Mac(ref m) => {
1049                 self.print_mac(m);
1050             }
1051             ast::TyKind::CVarArgs => {
1052                 self.s.word("...");
1053             }
1054         }
1055         self.end();
1056     }
1057
1058     crate fn print_foreign_item(&mut self,
1059                               item: &ast::ForeignItem) {
1060         self.hardbreak_if_not_bol();
1061         self.maybe_print_comment(item.span.lo());
1062         self.print_outer_attributes(&item.attrs);
1063         match item.node {
1064             ast::ForeignItemKind::Fn(ref decl, ref generics) => {
1065                 self.head("");
1066                 self.print_fn(decl, ast::FnHeader::default(),
1067                               Some(item.ident),
1068                               generics, &item.vis);
1069                 self.end(); // end head-ibox
1070                 self.s.word(";");
1071                 self.end(); // end the outer fn box
1072             }
1073             ast::ForeignItemKind::Static(ref t, m) => {
1074                 self.head(visibility_qualified(&item.vis, "static"));
1075                 if m == ast::Mutability::Mutable {
1076                     self.word_space("mut");
1077                 }
1078                 self.print_ident(item.ident);
1079                 self.word_space(":");
1080                 self.print_type(t);
1081                 self.s.word(";");
1082                 self.end(); // end the head-ibox
1083                 self.end(); // end the outer cbox
1084             }
1085             ast::ForeignItemKind::Ty => {
1086                 self.head(visibility_qualified(&item.vis, "type"));
1087                 self.print_ident(item.ident);
1088                 self.s.word(";");
1089                 self.end(); // end the head-ibox
1090                 self.end(); // end the outer cbox
1091             }
1092             ast::ForeignItemKind::Macro(ref m) => {
1093                 self.print_mac(m);
1094                 match m.delim {
1095                     MacDelimiter::Brace => {},
1096                     _ => self.s.word(";")
1097                 }
1098             }
1099         }
1100     }
1101
1102     fn print_associated_const(&mut self,
1103                               ident: ast::Ident,
1104                               ty: &ast::Ty,
1105                               default: Option<&ast::Expr>,
1106                               vis: &ast::Visibility)
1107     {
1108         self.s.word(visibility_qualified(vis, ""));
1109         self.word_space("const");
1110         self.print_ident(ident);
1111         self.word_space(":");
1112         self.print_type(ty);
1113         if let Some(expr) = default {
1114             self.s.space();
1115             self.word_space("=");
1116             self.print_expr(expr);
1117         }
1118         self.s.word(";")
1119     }
1120
1121     fn print_associated_type(&mut self,
1122                              ident: ast::Ident,
1123                              bounds: Option<&ast::GenericBounds>,
1124                              ty: Option<&ast::Ty>)
1125                              {
1126         self.word_space("type");
1127         self.print_ident(ident);
1128         if let Some(bounds) = bounds {
1129             self.print_type_bounds(":", bounds);
1130         }
1131         if let Some(ty) = ty {
1132             self.s.space();
1133             self.word_space("=");
1134             self.print_type(ty);
1135         }
1136         self.s.word(";")
1137     }
1138
1139     /// Pretty-prints an item.
1140     crate fn print_item(&mut self, item: &ast::Item) {
1141         self.hardbreak_if_not_bol();
1142         self.maybe_print_comment(item.span.lo());
1143         self.print_outer_attributes(&item.attrs);
1144         self.ann.pre(self, AnnNode::Item(item));
1145         match item.kind {
1146             ast::ItemKind::ExternCrate(orig_name) => {
1147                 self.head(visibility_qualified(&item.vis, "extern crate"));
1148                 if let Some(orig_name) = orig_name {
1149                     self.print_name(orig_name);
1150                     self.s.space();
1151                     self.s.word("as");
1152                     self.s.space();
1153                 }
1154                 self.print_ident(item.ident);
1155                 self.s.word(";");
1156                 self.end(); // end inner head-block
1157                 self.end(); // end outer head-block
1158             }
1159             ast::ItemKind::Use(ref tree) => {
1160                 self.head(visibility_qualified(&item.vis, "use"));
1161                 self.print_use_tree(tree);
1162                 self.s.word(";");
1163                 self.end(); // end inner head-block
1164                 self.end(); // end outer head-block
1165             }
1166             ast::ItemKind::Static(ref ty, m, ref expr) => {
1167                 self.head(visibility_qualified(&item.vis, "static"));
1168                 if m == ast::Mutability::Mutable {
1169                     self.word_space("mut");
1170                 }
1171                 self.print_ident(item.ident);
1172                 self.word_space(":");
1173                 self.print_type(ty);
1174                 self.s.space();
1175                 self.end(); // end the head-ibox
1176
1177                 self.word_space("=");
1178                 self.print_expr(expr);
1179                 self.s.word(";");
1180                 self.end(); // end the outer cbox
1181             }
1182             ast::ItemKind::Const(ref ty, ref expr) => {
1183                 self.head(visibility_qualified(&item.vis, "const"));
1184                 self.print_ident(item.ident);
1185                 self.word_space(":");
1186                 self.print_type(ty);
1187                 self.s.space();
1188                 self.end(); // end the head-ibox
1189
1190                 self.word_space("=");
1191                 self.print_expr(expr);
1192                 self.s.word(";");
1193                 self.end(); // end the outer cbox
1194             }
1195             ast::ItemKind::Fn(ref decl, header, ref param_names, ref body) => {
1196                 self.head("");
1197                 self.print_fn(
1198                     decl,
1199                     header,
1200                     Some(item.ident),
1201                     param_names,
1202                     &item.vis
1203                 );
1204                 self.s.word(" ");
1205                 self.print_block_with_attrs(body, &item.attrs);
1206             }
1207             ast::ItemKind::Mod(ref _mod) => {
1208                 self.head(visibility_qualified(&item.vis, "mod"));
1209                 self.print_ident(item.ident);
1210
1211                 if _mod.inline || self.is_expanded {
1212                     self.nbsp();
1213                     self.bopen();
1214                     self.print_mod(_mod, &item.attrs);
1215                     self.bclose(item.span);
1216                 } else {
1217                     self.s.word(";");
1218                     self.end(); // end inner head-block
1219                     self.end(); // end outer head-block
1220                 }
1221
1222             }
1223             ast::ItemKind::ForeignMod(ref nmod) => {
1224                 self.head("extern");
1225                 self.word_nbsp(nmod.abi.to_string());
1226                 self.bopen();
1227                 self.print_foreign_mod(nmod, &item.attrs);
1228                 self.bclose(item.span);
1229             }
1230             ast::ItemKind::GlobalAsm(ref ga) => {
1231                 self.head(visibility_qualified(&item.vis, "global_asm!"));
1232                 self.s.word(ga.asm.as_str().to_string());
1233                 self.end();
1234             }
1235             ast::ItemKind::TyAlias(ref ty, ref generics) => {
1236                 self.head(visibility_qualified(&item.vis, "type"));
1237                 self.print_ident(item.ident);
1238                 self.print_generic_params(&generics.params);
1239                 self.end(); // end the inner ibox
1240
1241                 self.print_where_clause(&generics.where_clause);
1242                 self.s.space();
1243                 self.word_space("=");
1244                 self.print_type(ty);
1245                 self.s.word(";");
1246                 self.end(); // end the outer ibox
1247             }
1248             ast::ItemKind::OpaqueTy(ref bounds, ref generics) => {
1249                 self.head(visibility_qualified(&item.vis, "type"));
1250                 self.print_ident(item.ident);
1251                 self.word_space("= impl");
1252                 self.print_generic_params(&generics.params);
1253                 self.end(); // end the inner ibox
1254
1255                 self.print_where_clause(&generics.where_clause);
1256                 self.s.space();
1257                 self.print_type_bounds(":", bounds);
1258                 self.s.word(";");
1259                 self.end(); // end the outer ibox
1260             }
1261             ast::ItemKind::Enum(ref enum_definition, ref params) => {
1262                 self.print_enum_def(
1263                     enum_definition,
1264                     params,
1265                     item.ident,
1266                     item.span,
1267                     &item.vis
1268                 );
1269             }
1270             ast::ItemKind::Struct(ref struct_def, ref generics) => {
1271                 self.head(visibility_qualified(&item.vis, "struct"));
1272                 self.print_struct(struct_def, generics, item.ident, item.span, true);
1273             }
1274             ast::ItemKind::Union(ref struct_def, ref generics) => {
1275                 self.head(visibility_qualified(&item.vis, "union"));
1276                 self.print_struct(struct_def, generics, item.ident, item.span, true);
1277             }
1278             ast::ItemKind::Impl(unsafety,
1279                           polarity,
1280                           defaultness,
1281                           ref generics,
1282                           ref opt_trait,
1283                           ref ty,
1284                           ref impl_items) => {
1285                 self.head("");
1286                 self.print_visibility(&item.vis);
1287                 self.print_defaultness(defaultness);
1288                 self.print_unsafety(unsafety);
1289                 self.word_nbsp("impl");
1290
1291                 if !generics.params.is_empty() {
1292                     self.print_generic_params(&generics.params);
1293                     self.s.space();
1294                 }
1295
1296                 if polarity == ast::ImplPolarity::Negative {
1297                     self.s.word("!");
1298                 }
1299
1300                 if let Some(ref t) = *opt_trait {
1301                     self.print_trait_ref(t);
1302                     self.s.space();
1303                     self.word_space("for");
1304                 }
1305
1306                 self.print_type(ty);
1307                 self.print_where_clause(&generics.where_clause);
1308
1309                 self.s.space();
1310                 self.bopen();
1311                 self.print_inner_attributes(&item.attrs);
1312                 for impl_item in impl_items {
1313                     self.print_impl_item(impl_item);
1314                 }
1315                 self.bclose(item.span);
1316             }
1317             ast::ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref trait_items) => {
1318                 self.head("");
1319                 self.print_visibility(&item.vis);
1320                 self.print_unsafety(unsafety);
1321                 self.print_is_auto(is_auto);
1322                 self.word_nbsp("trait");
1323                 self.print_ident(item.ident);
1324                 self.print_generic_params(&generics.params);
1325                 let mut real_bounds = Vec::with_capacity(bounds.len());
1326                 for b in bounds.iter() {
1327                     if let GenericBound::Trait(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
1328                         self.s.space();
1329                         self.word_space("for ?");
1330                         self.print_trait_ref(&ptr.trait_ref);
1331                     } else {
1332                         real_bounds.push(b.clone());
1333                     }
1334                 }
1335                 self.print_type_bounds(":", &real_bounds[..]);
1336                 self.print_where_clause(&generics.where_clause);
1337                 self.s.word(" ");
1338                 self.bopen();
1339                 for trait_item in trait_items {
1340                     self.print_trait_item(trait_item);
1341                 }
1342                 self.bclose(item.span);
1343             }
1344             ast::ItemKind::TraitAlias(ref generics, ref bounds) => {
1345                 self.head("");
1346                 self.print_visibility(&item.vis);
1347                 self.word_nbsp("trait");
1348                 self.print_ident(item.ident);
1349                 self.print_generic_params(&generics.params);
1350                 let mut real_bounds = Vec::with_capacity(bounds.len());
1351                 // FIXME(durka) this seems to be some quite outdated syntax
1352                 for b in bounds.iter() {
1353                     if let GenericBound::Trait(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
1354                         self.s.space();
1355                         self.word_space("for ?");
1356                         self.print_trait_ref(&ptr.trait_ref);
1357                     } else {
1358                         real_bounds.push(b.clone());
1359                     }
1360                 }
1361                 self.nbsp();
1362                 self.print_type_bounds("=", &real_bounds[..]);
1363                 self.print_where_clause(&generics.where_clause);
1364                 self.s.word(";");
1365             }
1366             ast::ItemKind::Mac(ref mac) => {
1367                 self.print_mac(mac);
1368                 match mac.delim {
1369                     MacDelimiter::Brace => {}
1370                     _ => self.s.word(";"),
1371                 }
1372             }
1373             ast::ItemKind::MacroDef(ref macro_def) => {
1374                 let (kw, has_bang) = if macro_def.legacy {
1375                     ("macro_rules", true)
1376                 } else {
1377                     self.print_visibility(&item.vis);
1378                     ("macro", false)
1379                 };
1380                 self.print_mac_common(
1381                     Some(MacHeader::Keyword(kw)),
1382                     has_bang,
1383                     Some(item.ident),
1384                     DelimToken::Brace,
1385                     macro_def.stream(),
1386                     true,
1387                     item.span,
1388                 );
1389             }
1390         }
1391         self.ann.post(self, AnnNode::Item(item))
1392     }
1393
1394     fn print_trait_ref(&mut self, t: &ast::TraitRef) {
1395         self.print_path(&t.path, false, 0)
1396     }
1397
1398     fn print_formal_generic_params(
1399         &mut self,
1400         generic_params: &[ast::GenericParam]
1401     ) {
1402         if !generic_params.is_empty() {
1403             self.s.word("for");
1404             self.print_generic_params(generic_params);
1405             self.nbsp();
1406         }
1407     }
1408
1409     fn print_poly_trait_ref(&mut self, t: &ast::PolyTraitRef) {
1410         self.print_formal_generic_params(&t.bound_generic_params);
1411         self.print_trait_ref(&t.trait_ref)
1412     }
1413
1414     crate fn print_enum_def(&mut self, enum_definition: &ast::EnumDef,
1415                           generics: &ast::Generics, ident: ast::Ident,
1416                           span: syntax_pos::Span,
1417                           visibility: &ast::Visibility) {
1418         self.head(visibility_qualified(visibility, "enum"));
1419         self.print_ident(ident);
1420         self.print_generic_params(&generics.params);
1421         self.print_where_clause(&generics.where_clause);
1422         self.s.space();
1423         self.print_variants(&enum_definition.variants, span)
1424     }
1425
1426     crate fn print_variants(&mut self,
1427                           variants: &[ast::Variant],
1428                           span: syntax_pos::Span) {
1429         self.bopen();
1430         for v in variants {
1431             self.space_if_not_bol();
1432             self.maybe_print_comment(v.span.lo());
1433             self.print_outer_attributes(&v.attrs);
1434             self.ibox(INDENT_UNIT);
1435             self.print_variant(v);
1436             self.s.word(",");
1437             self.end();
1438             self.maybe_print_trailing_comment(v.span, None);
1439         }
1440         self.bclose(span)
1441     }
1442
1443     crate fn print_visibility(&mut self, vis: &ast::Visibility) {
1444         match vis.node {
1445             ast::VisibilityKind::Public => self.word_nbsp("pub"),
1446             ast::VisibilityKind::Crate(sugar) => match sugar {
1447                 ast::CrateSugar::PubCrate => self.word_nbsp("pub(crate)"),
1448                 ast::CrateSugar::JustCrate => self.word_nbsp("crate")
1449             }
1450             ast::VisibilityKind::Restricted { ref path, .. } => {
1451                 let path = to_string(|s| s.print_path(path, false, 0));
1452                 if path == "self" || path == "super" {
1453                     self.word_nbsp(format!("pub({})", path))
1454                 } else {
1455                     self.word_nbsp(format!("pub(in {})", path))
1456                 }
1457             }
1458             ast::VisibilityKind::Inherited => {}
1459         }
1460     }
1461
1462     crate fn print_defaultness(&mut self, defaultness: ast::Defaultness) {
1463         if let ast::Defaultness::Default = defaultness {
1464             self.word_nbsp("default");
1465         }
1466     }
1467
1468     crate fn print_struct(&mut self,
1469                         struct_def: &ast::VariantData,
1470                         generics: &ast::Generics,
1471                         ident: ast::Ident,
1472                         span: syntax_pos::Span,
1473                         print_finalizer: bool) {
1474         self.print_ident(ident);
1475         self.print_generic_params(&generics.params);
1476         match struct_def {
1477             ast::VariantData::Tuple(..) | ast::VariantData::Unit(..) => {
1478                 if let ast::VariantData::Tuple(..) = struct_def {
1479                     self.popen();
1480                     self.commasep(
1481                         Inconsistent, struct_def.fields(),
1482                         |s, field| {
1483                             s.maybe_print_comment(field.span.lo());
1484                             s.print_outer_attributes(&field.attrs);
1485                             s.print_visibility(&field.vis);
1486                             s.print_type(&field.ty)
1487                         }
1488                     );
1489                     self.pclose();
1490                 }
1491                 self.print_where_clause(&generics.where_clause);
1492                 if print_finalizer {
1493                     self.s.word(";");
1494                 }
1495                 self.end();
1496                 self.end(); // Close the outer-box.
1497             }
1498             ast::VariantData::Struct(..) => {
1499                 self.print_where_clause(&generics.where_clause);
1500                 self.nbsp();
1501                 self.bopen();
1502                 self.hardbreak_if_not_bol();
1503
1504                 for field in struct_def.fields() {
1505                     self.hardbreak_if_not_bol();
1506                     self.maybe_print_comment(field.span.lo());
1507                     self.print_outer_attributes(&field.attrs);
1508                     self.print_visibility(&field.vis);
1509                     self.print_ident(field.ident.unwrap());
1510                     self.word_nbsp(":");
1511                     self.print_type(&field.ty);
1512                     self.s.word(",");
1513                 }
1514
1515                 self.bclose(span)
1516             }
1517         }
1518     }
1519
1520     crate fn print_variant(&mut self, v: &ast::Variant) {
1521         self.head("");
1522         let generics = ast::Generics::default();
1523         self.print_struct(&v.data, &generics, v.ident, v.span, false);
1524         match v.disr_expr {
1525             Some(ref d) => {
1526                 self.s.space();
1527                 self.word_space("=");
1528                 self.print_expr(&d.value)
1529             }
1530             _ => {}
1531         }
1532     }
1533
1534     crate fn print_method_sig(&mut self,
1535                             ident: ast::Ident,
1536                             generics: &ast::Generics,
1537                             m: &ast::MethodSig,
1538                             vis: &ast::Visibility)
1539                             {
1540         self.print_fn(&m.decl,
1541                       m.header,
1542                       Some(ident),
1543                       &generics,
1544                       vis)
1545     }
1546
1547     crate fn print_trait_item(&mut self, ti: &ast::TraitItem)
1548                             {
1549         self.ann.pre(self, AnnNode::SubItem(ti.id));
1550         self.hardbreak_if_not_bol();
1551         self.maybe_print_comment(ti.span.lo());
1552         self.print_outer_attributes(&ti.attrs);
1553         match ti.kind {
1554             ast::TraitItemKind::Const(ref ty, ref default) => {
1555                 self.print_associated_const(
1556                     ti.ident,
1557                     ty,
1558                     default.as_ref().map(|expr| &**expr),
1559                     &source_map::respan(ti.span.shrink_to_lo(), ast::VisibilityKind::Inherited),
1560                 );
1561             }
1562             ast::TraitItemKind::Method(ref sig, ref body) => {
1563                 if body.is_some() {
1564                     self.head("");
1565                 }
1566                 self.print_method_sig(
1567                     ti.ident,
1568                     &ti.generics,
1569                     sig,
1570                     &source_map::respan(ti.span.shrink_to_lo(), ast::VisibilityKind::Inherited),
1571                 );
1572                 if let Some(ref body) = *body {
1573                     self.nbsp();
1574                     self.print_block_with_attrs(body, &ti.attrs);
1575                 } else {
1576                     self.s.word(";");
1577                 }
1578             }
1579             ast::TraitItemKind::Type(ref bounds, ref default) => {
1580                 self.print_associated_type(ti.ident, Some(bounds),
1581                                            default.as_ref().map(|ty| &**ty));
1582             }
1583             ast::TraitItemKind::Macro(ref mac) => {
1584                 self.print_mac(mac);
1585                 match mac.delim {
1586                     MacDelimiter::Brace => {}
1587                     _ => self.s.word(";"),
1588                 }
1589             }
1590         }
1591         self.ann.post(self, AnnNode::SubItem(ti.id))
1592     }
1593
1594     crate fn print_impl_item(&mut self, ii: &ast::ImplItem) {
1595         self.ann.pre(self, AnnNode::SubItem(ii.id));
1596         self.hardbreak_if_not_bol();
1597         self.maybe_print_comment(ii.span.lo());
1598         self.print_outer_attributes(&ii.attrs);
1599         self.print_defaultness(ii.defaultness);
1600         match ii.kind {
1601             ast::ImplItemKind::Const(ref ty, ref expr) => {
1602                 self.print_associated_const(ii.ident, ty, Some(expr), &ii.vis);
1603             }
1604             ast::ImplItemKind::Method(ref sig, ref body) => {
1605                 self.head("");
1606                 self.print_method_sig(ii.ident, &ii.generics, sig, &ii.vis);
1607                 self.nbsp();
1608                 self.print_block_with_attrs(body, &ii.attrs);
1609             }
1610             ast::ImplItemKind::TyAlias(ref ty) => {
1611                 self.print_associated_type(ii.ident, None, Some(ty));
1612             }
1613             ast::ImplItemKind::OpaqueTy(ref bounds) => {
1614                 self.word_space("type");
1615                 self.print_ident(ii.ident);
1616                 self.word_space("= impl");
1617                 self.print_type_bounds(":", bounds);
1618                 self.s.word(";");
1619             }
1620             ast::ImplItemKind::Macro(ref mac) => {
1621                 self.print_mac(mac);
1622                 match mac.delim {
1623                     MacDelimiter::Brace => {}
1624                     _ => self.s.word(";"),
1625                 }
1626             }
1627         }
1628         self.ann.post(self, AnnNode::SubItem(ii.id))
1629     }
1630
1631     crate fn print_stmt(&mut self, st: &ast::Stmt) {
1632         self.maybe_print_comment(st.span.lo());
1633         match st.kind {
1634             ast::StmtKind::Local(ref loc) => {
1635                 self.print_outer_attributes(&loc.attrs);
1636                 self.space_if_not_bol();
1637                 self.ibox(INDENT_UNIT);
1638                 self.word_nbsp("let");
1639
1640                 self.ibox(INDENT_UNIT);
1641                 self.print_local_decl(loc);
1642                 self.end();
1643                 if let Some(ref init) = loc.init {
1644                     self.nbsp();
1645                     self.word_space("=");
1646                     self.print_expr(init);
1647                 }
1648                 self.s.word(";");
1649                 self.end();
1650             }
1651             ast::StmtKind::Item(ref item) => self.print_item(item),
1652             ast::StmtKind::Expr(ref expr) => {
1653                 self.space_if_not_bol();
1654                 self.print_expr_outer_attr_style(expr, false);
1655                 if parse::classify::expr_requires_semi_to_be_stmt(expr) {
1656                     self.s.word(";");
1657                 }
1658             }
1659             ast::StmtKind::Semi(ref expr) => {
1660                 self.space_if_not_bol();
1661                 self.print_expr_outer_attr_style(expr, false);
1662                 self.s.word(";");
1663             }
1664             ast::StmtKind::Mac(ref mac) => {
1665                 let (ref mac, style, ref attrs) = **mac;
1666                 self.space_if_not_bol();
1667                 self.print_outer_attributes(attrs);
1668                 self.print_mac(mac);
1669                 if style == ast::MacStmtStyle::Semicolon {
1670                     self.s.word(";");
1671                 }
1672             }
1673         }
1674         self.maybe_print_trailing_comment(st.span, None)
1675     }
1676
1677     crate fn print_block(&mut self, blk: &ast::Block) {
1678         self.print_block_with_attrs(blk, &[])
1679     }
1680
1681     crate fn print_block_unclosed_indent(&mut self, blk: &ast::Block) {
1682         self.print_block_maybe_unclosed(blk, &[], false)
1683     }
1684
1685     crate fn print_block_with_attrs(&mut self,
1686                                   blk: &ast::Block,
1687                                   attrs: &[ast::Attribute]) {
1688         self.print_block_maybe_unclosed(blk, attrs, true)
1689     }
1690
1691     crate fn print_block_maybe_unclosed(&mut self,
1692                                       blk: &ast::Block,
1693                                       attrs: &[ast::Attribute],
1694                                       close_box: bool) {
1695         match blk.rules {
1696             BlockCheckMode::Unsafe(..) => self.word_space("unsafe"),
1697             BlockCheckMode::Default => ()
1698         }
1699         self.maybe_print_comment(blk.span.lo());
1700         self.ann.pre(self, AnnNode::Block(blk));
1701         self.bopen();
1702
1703         self.print_inner_attributes(attrs);
1704
1705         for (i, st) in blk.stmts.iter().enumerate() {
1706             match st.kind {
1707                 ast::StmtKind::Expr(ref expr) if i == blk.stmts.len() - 1 => {
1708                     self.maybe_print_comment(st.span.lo());
1709                     self.space_if_not_bol();
1710                     self.print_expr_outer_attr_style(expr, false);
1711                     self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi()));
1712                 }
1713                 _ => self.print_stmt(st),
1714             }
1715         }
1716
1717         self.bclose_maybe_open(blk.span, close_box);
1718         self.ann.post(self, AnnNode::Block(blk))
1719     }
1720
1721     /// Print a `let pat = scrutinee` expression.
1722     crate fn print_let(&mut self, pat: &ast::Pat, scrutinee: &ast::Expr) {
1723         self.s.word("let ");
1724
1725         self.print_pat(pat);
1726         self.s.space();
1727
1728         self.word_space("=");
1729         self.print_expr_cond_paren(
1730             scrutinee,
1731             Self::cond_needs_par(scrutinee)
1732             || parser::needs_par_as_let_scrutinee(scrutinee.precedence().order())
1733         )
1734     }
1735
1736     fn print_else(&mut self, els: Option<&ast::Expr>) {
1737         if let Some(_else) = els {
1738             match _else.kind {
1739                 // Another `else if` block.
1740                 ast::ExprKind::If(ref i, ref then, ref e) => {
1741                     self.cbox(INDENT_UNIT - 1);
1742                     self.ibox(0);
1743                     self.s.word(" else if ");
1744                     self.print_expr_as_cond(i);
1745                     self.s.space();
1746                     self.print_block(then);
1747                     self.print_else(e.as_ref().map(|e| &**e))
1748                 }
1749                 // Final `else` block.
1750                 ast::ExprKind::Block(ref b, _) => {
1751                     self.cbox(INDENT_UNIT - 1);
1752                     self.ibox(0);
1753                     self.s.word(" else ");
1754                     self.print_block(b)
1755                 }
1756                 // Constraints would be great here!
1757                 _ => {
1758                     panic!("print_if saw if with weird alternative");
1759                 }
1760             }
1761         }
1762     }
1763
1764     crate fn print_if(&mut self, test: &ast::Expr, blk: &ast::Block,
1765                     elseopt: Option<&ast::Expr>) {
1766         self.head("if");
1767
1768         self.print_expr_as_cond(test);
1769         self.s.space();
1770
1771         self.print_block(blk);
1772         self.print_else(elseopt)
1773     }
1774
1775     crate fn print_mac(&mut self, m: &ast::Mac) {
1776         self.print_mac_common(
1777             Some(MacHeader::Path(&m.path)),
1778             true,
1779             None,
1780             m.delim.to_token(),
1781             m.stream(),
1782             true,
1783             m.span,
1784         );
1785     }
1786
1787     fn print_call_post(&mut self, args: &[P<ast::Expr>]) {
1788         self.popen();
1789         self.commasep_exprs(Inconsistent, args);
1790         self.pclose()
1791     }
1792
1793     crate fn print_expr_maybe_paren(&mut self, expr: &ast::Expr, prec: i8) {
1794         self.print_expr_cond_paren(expr, expr.precedence().order() < prec)
1795     }
1796
1797     /// Prints an expr using syntax that's acceptable in a condition position, such as the `cond` in
1798     /// `if cond { ... }`.
1799     crate fn print_expr_as_cond(&mut self, expr: &ast::Expr) {
1800         self.print_expr_cond_paren(expr, Self::cond_needs_par(expr))
1801     }
1802
1803     /// Does `expr` need parenthesis when printed in a condition position?
1804     fn cond_needs_par(expr: &ast::Expr) -> bool {
1805         match expr.kind {
1806             // These cases need parens due to the parse error observed in #26461: `if return {}`
1807             // parses as the erroneous construct `if (return {})`, not `if (return) {}`.
1808             ast::ExprKind::Closure(..) |
1809             ast::ExprKind::Ret(..) |
1810             ast::ExprKind::Break(..) => true,
1811
1812             _ => parser::contains_exterior_struct_lit(expr),
1813         }
1814     }
1815
1816     /// Prints `expr` or `(expr)` when `needs_par` holds.
1817     fn print_expr_cond_paren(&mut self, expr: &ast::Expr, needs_par: bool) {
1818         if needs_par {
1819             self.popen();
1820         }
1821         self.print_expr(expr);
1822         if needs_par {
1823             self.pclose();
1824         }
1825     }
1826
1827     fn print_expr_vec(&mut self, exprs: &[P<ast::Expr>],
1828                       attrs: &[Attribute]) {
1829         self.ibox(INDENT_UNIT);
1830         self.s.word("[");
1831         self.print_inner_attributes_inline(attrs);
1832         self.commasep_exprs(Inconsistent, &exprs[..]);
1833         self.s.word("]");
1834         self.end();
1835     }
1836
1837     fn print_expr_repeat(&mut self,
1838                          element: &ast::Expr,
1839                          count: &ast::AnonConst,
1840                          attrs: &[Attribute]) {
1841         self.ibox(INDENT_UNIT);
1842         self.s.word("[");
1843         self.print_inner_attributes_inline(attrs);
1844         self.print_expr(element);
1845         self.word_space(";");
1846         self.print_expr(&count.value);
1847         self.s.word("]");
1848         self.end();
1849     }
1850
1851     fn print_expr_struct(&mut self,
1852                          path: &ast::Path,
1853                          fields: &[ast::Field],
1854                          wth: &Option<P<ast::Expr>>,
1855                          attrs: &[Attribute]) {
1856         self.print_path(path, true, 0);
1857         self.s.word("{");
1858         self.print_inner_attributes_inline(attrs);
1859         self.commasep_cmnt(
1860             Consistent,
1861             &fields[..],
1862             |s, field| {
1863                 s.ibox(INDENT_UNIT);
1864                 if !field.is_shorthand {
1865                     s.print_ident(field.ident);
1866                     s.word_space(":");
1867                 }
1868                 s.print_expr(&field.expr);
1869                 s.end();
1870             },
1871             |f| f.span);
1872         match *wth {
1873             Some(ref expr) => {
1874                 self.ibox(INDENT_UNIT);
1875                 if !fields.is_empty() {
1876                     self.s.word(",");
1877                     self.s.space();
1878                 }
1879                 self.s.word("..");
1880                 self.print_expr(expr);
1881                 self.end();
1882             }
1883             _ => if !fields.is_empty() {
1884                 self.s.word(",")
1885             }
1886         }
1887         self.s.word("}");
1888     }
1889
1890     fn print_expr_tup(&mut self, exprs: &[P<ast::Expr>],
1891                       attrs: &[Attribute]) {
1892         self.popen();
1893         self.print_inner_attributes_inline(attrs);
1894         self.commasep_exprs(Inconsistent, &exprs[..]);
1895         if exprs.len() == 1 {
1896             self.s.word(",");
1897         }
1898         self.pclose()
1899     }
1900
1901     fn print_expr_call(&mut self,
1902                        func: &ast::Expr,
1903                        args: &[P<ast::Expr>]) {
1904         let prec =
1905             match func.kind {
1906                 ast::ExprKind::Field(..) => parser::PREC_FORCE_PAREN,
1907                 _ => parser::PREC_POSTFIX,
1908             };
1909
1910         self.print_expr_maybe_paren(func, prec);
1911         self.print_call_post(args)
1912     }
1913
1914     fn print_expr_method_call(&mut self,
1915                               segment: &ast::PathSegment,
1916                               args: &[P<ast::Expr>]) {
1917         let base_args = &args[1..];
1918         self.print_expr_maybe_paren(&args[0], parser::PREC_POSTFIX);
1919         self.s.word(".");
1920         self.print_ident(segment.ident);
1921         if let Some(ref args) = segment.args {
1922             self.print_generic_args(args, true);
1923         }
1924         self.print_call_post(base_args)
1925     }
1926
1927     fn print_expr_binary(&mut self,
1928                          op: ast::BinOp,
1929                          lhs: &ast::Expr,
1930                          rhs: &ast::Expr) {
1931         let assoc_op = AssocOp::from_ast_binop(op.node);
1932         let prec = assoc_op.precedence() as i8;
1933         let fixity = assoc_op.fixity();
1934
1935         let (left_prec, right_prec) = match fixity {
1936             Fixity::Left => (prec, prec + 1),
1937             Fixity::Right => (prec + 1, prec),
1938             Fixity::None => (prec + 1, prec + 1),
1939         };
1940
1941         let left_prec = match (&lhs.kind, op.node) {
1942             // These cases need parens: `x as i32 < y` has the parser thinking that `i32 < y` is
1943             // the beginning of a path type. It starts trying to parse `x as (i32 < y ...` instead
1944             // of `(x as i32) < ...`. We need to convince it _not_ to do that.
1945             (&ast::ExprKind::Cast { .. }, ast::BinOpKind::Lt) |
1946             (&ast::ExprKind::Cast { .. }, ast::BinOpKind::Shl) => parser::PREC_FORCE_PAREN,
1947             // We are given `(let _ = a) OP b`.
1948             //
1949             // - When `OP <= LAnd` we should print `let _ = a OP b` to avoid redundant parens
1950             //   as the parser will interpret this as `(let _ = a) OP b`.
1951             //
1952             // - Otherwise, e.g. when we have `(let a = b) < c` in AST,
1953             //   parens are required since the parser would interpret `let a = b < c` as
1954             //   `let a = (b < c)`. To achieve this, we force parens.
1955             (&ast::ExprKind::Let { .. }, _) if !parser::needs_par_as_let_scrutinee(prec) => {
1956                 parser::PREC_FORCE_PAREN
1957             }
1958             _ => left_prec,
1959         };
1960
1961         self.print_expr_maybe_paren(lhs, left_prec);
1962         self.s.space();
1963         self.word_space(op.node.to_string());
1964         self.print_expr_maybe_paren(rhs, right_prec)
1965     }
1966
1967     fn print_expr_unary(&mut self,
1968                         op: ast::UnOp,
1969                         expr: &ast::Expr) {
1970         self.s.word(ast::UnOp::to_string(op));
1971         self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1972     }
1973
1974     fn print_expr_addr_of(&mut self,
1975                           mutability: ast::Mutability,
1976                           expr: &ast::Expr) {
1977         self.s.word("&");
1978         self.print_mutability(mutability);
1979         self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1980     }
1981
1982     crate fn print_expr(&mut self, expr: &ast::Expr) {
1983         self.print_expr_outer_attr_style(expr, true)
1984     }
1985
1986     fn print_expr_outer_attr_style(&mut self,
1987                                   expr: &ast::Expr,
1988                                   is_inline: bool) {
1989         self.maybe_print_comment(expr.span.lo());
1990
1991         let attrs = &expr.attrs;
1992         if is_inline {
1993             self.print_outer_attributes_inline(attrs);
1994         } else {
1995             self.print_outer_attributes(attrs);
1996         }
1997
1998         self.ibox(INDENT_UNIT);
1999         self.ann.pre(self, AnnNode::Expr(expr));
2000         match expr.kind {
2001             ast::ExprKind::Box(ref expr) => {
2002                 self.word_space("box");
2003                 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX);
2004             }
2005             ast::ExprKind::Array(ref exprs) => {
2006                 self.print_expr_vec(&exprs[..], attrs);
2007             }
2008             ast::ExprKind::Repeat(ref element, ref count) => {
2009                 self.print_expr_repeat(element, count, attrs);
2010             }
2011             ast::ExprKind::Struct(ref path, ref fields, ref wth) => {
2012                 self.print_expr_struct(path, &fields[..], wth, attrs);
2013             }
2014             ast::ExprKind::Tup(ref exprs) => {
2015                 self.print_expr_tup(&exprs[..], attrs);
2016             }
2017             ast::ExprKind::Call(ref func, ref args) => {
2018                 self.print_expr_call(func, &args[..]);
2019             }
2020             ast::ExprKind::MethodCall(ref segment, ref args) => {
2021                 self.print_expr_method_call(segment, &args[..]);
2022             }
2023             ast::ExprKind::Binary(op, ref lhs, ref rhs) => {
2024                 self.print_expr_binary(op, lhs, rhs);
2025             }
2026             ast::ExprKind::Unary(op, ref expr) => {
2027                 self.print_expr_unary(op, expr);
2028             }
2029             ast::ExprKind::AddrOf(m, ref expr) => {
2030                 self.print_expr_addr_of(m, expr);
2031             }
2032             ast::ExprKind::Lit(ref lit) => {
2033                 self.print_literal(lit);
2034             }
2035             ast::ExprKind::Cast(ref expr, ref ty) => {
2036                 let prec = AssocOp::As.precedence() as i8;
2037                 self.print_expr_maybe_paren(expr, prec);
2038                 self.s.space();
2039                 self.word_space("as");
2040                 self.print_type(ty);
2041             }
2042             ast::ExprKind::Type(ref expr, ref ty) => {
2043                 let prec = AssocOp::Colon.precedence() as i8;
2044                 self.print_expr_maybe_paren(expr, prec);
2045                 self.word_space(":");
2046                 self.print_type(ty);
2047             }
2048             ast::ExprKind::Let(ref pat, ref scrutinee) => {
2049                 self.print_let(pat, scrutinee);
2050             }
2051             ast::ExprKind::If(ref test, ref blk, ref elseopt) => {
2052                 self.print_if(test, blk, elseopt.as_ref().map(|e| &**e));
2053             }
2054             ast::ExprKind::While(ref test, ref blk, opt_label) => {
2055                 if let Some(label) = opt_label {
2056                     self.print_ident(label.ident);
2057                     self.word_space(":");
2058                 }
2059                 self.head("while");
2060                 self.print_expr_as_cond(test);
2061                 self.s.space();
2062                 self.print_block_with_attrs(blk, attrs);
2063             }
2064             ast::ExprKind::ForLoop(ref pat, ref iter, ref blk, opt_label) => {
2065                 if let Some(label) = opt_label {
2066                     self.print_ident(label.ident);
2067                     self.word_space(":");
2068                 }
2069                 self.head("for");
2070                 self.print_pat(pat);
2071                 self.s.space();
2072                 self.word_space("in");
2073                 self.print_expr_as_cond(iter);
2074                 self.s.space();
2075                 self.print_block_with_attrs(blk, attrs);
2076             }
2077             ast::ExprKind::Loop(ref blk, opt_label) => {
2078                 if let Some(label) = opt_label {
2079                     self.print_ident(label.ident);
2080                     self.word_space(":");
2081                 }
2082                 self.head("loop");
2083                 self.s.space();
2084                 self.print_block_with_attrs(blk, attrs);
2085             }
2086             ast::ExprKind::Match(ref expr, ref arms) => {
2087                 self.cbox(INDENT_UNIT);
2088                 self.ibox(INDENT_UNIT);
2089                 self.word_nbsp("match");
2090                 self.print_expr_as_cond(expr);
2091                 self.s.space();
2092                 self.bopen();
2093                 self.print_inner_attributes_no_trailing_hardbreak(attrs);
2094                 for arm in arms {
2095                     self.print_arm(arm);
2096                 }
2097                 self.bclose(expr.span);
2098             }
2099             ast::ExprKind::Closure(
2100                 capture_clause, asyncness, movability, ref decl, ref body, _) => {
2101                 self.print_movability(movability);
2102                 self.print_asyncness(asyncness);
2103                 self.print_capture_clause(capture_clause);
2104
2105                 self.print_fn_block_params(decl);
2106                 self.s.space();
2107                 self.print_expr(body);
2108                 self.end(); // need to close a box
2109
2110                 // a box will be closed by print_expr, but we didn't want an overall
2111                 // wrapper so we closed the corresponding opening. so create an
2112                 // empty box to satisfy the close.
2113                 self.ibox(0);
2114             }
2115             ast::ExprKind::Block(ref blk, opt_label) => {
2116                 if let Some(label) = opt_label {
2117                     self.print_ident(label.ident);
2118                     self.word_space(":");
2119                 }
2120                 // containing cbox, will be closed by print-block at }
2121                 self.cbox(INDENT_UNIT);
2122                 // head-box, will be closed by print-block after {
2123                 self.ibox(0);
2124                 self.print_block_with_attrs(blk, attrs);
2125             }
2126             ast::ExprKind::Async(capture_clause, _, ref blk) => {
2127                 self.word_nbsp("async");
2128                 self.print_capture_clause(capture_clause);
2129                 self.s.space();
2130                 // cbox/ibox in analogy to the `ExprKind::Block` arm above
2131                 self.cbox(INDENT_UNIT);
2132                 self.ibox(0);
2133                 self.print_block_with_attrs(blk, attrs);
2134             }
2135             ast::ExprKind::Await(ref expr) => {
2136                 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
2137                 self.s.word(".await");
2138             }
2139             ast::ExprKind::Assign(ref lhs, ref rhs) => {
2140                 let prec = AssocOp::Assign.precedence() as i8;
2141                 self.print_expr_maybe_paren(lhs, prec + 1);
2142                 self.s.space();
2143                 self.word_space("=");
2144                 self.print_expr_maybe_paren(rhs, prec);
2145             }
2146             ast::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
2147                 let prec = AssocOp::Assign.precedence() as i8;
2148                 self.print_expr_maybe_paren(lhs, prec + 1);
2149                 self.s.space();
2150                 self.s.word(op.node.to_string());
2151                 self.word_space("=");
2152                 self.print_expr_maybe_paren(rhs, prec);
2153             }
2154             ast::ExprKind::Field(ref expr, ident) => {
2155                 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
2156                 self.s.word(".");
2157                 self.print_ident(ident);
2158             }
2159             ast::ExprKind::Index(ref expr, ref index) => {
2160                 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
2161                 self.s.word("[");
2162                 self.print_expr(index);
2163                 self.s.word("]");
2164             }
2165             ast::ExprKind::Range(ref start, ref end, limits) => {
2166                 // Special case for `Range`.  `AssocOp` claims that `Range` has higher precedence
2167                 // than `Assign`, but `x .. x = x` gives a parse error instead of `x .. (x = x)`.
2168                 // Here we use a fake precedence value so that any child with lower precedence than
2169                 // a "normal" binop gets parenthesized.  (`LOr` is the lowest-precedence binop.)
2170                 let fake_prec = AssocOp::LOr.precedence() as i8;
2171                 if let Some(ref e) = *start {
2172                     self.print_expr_maybe_paren(e, fake_prec);
2173                 }
2174                 if limits == ast::RangeLimits::HalfOpen {
2175                     self.s.word("..");
2176                 } else {
2177                     self.s.word("..=");
2178                 }
2179                 if let Some(ref e) = *end {
2180                     self.print_expr_maybe_paren(e, fake_prec);
2181                 }
2182             }
2183             ast::ExprKind::Path(None, ref path) => {
2184                 self.print_path(path, true, 0)
2185             }
2186             ast::ExprKind::Path(Some(ref qself), ref path) => {
2187                 self.print_qpath(path, qself, true)
2188             }
2189             ast::ExprKind::Break(opt_label, ref opt_expr) => {
2190                 self.s.word("break");
2191                 self.s.space();
2192                 if let Some(label) = opt_label {
2193                     self.print_ident(label.ident);
2194                     self.s.space();
2195                 }
2196                 if let Some(ref expr) = *opt_expr {
2197                     self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
2198                     self.s.space();
2199                 }
2200             }
2201             ast::ExprKind::Continue(opt_label) => {
2202                 self.s.word("continue");
2203                 self.s.space();
2204                 if let Some(label) = opt_label {
2205                     self.print_ident(label.ident);
2206                     self.s.space()
2207                 }
2208             }
2209             ast::ExprKind::Ret(ref result) => {
2210                 self.s.word("return");
2211                 if let Some(ref expr) = *result {
2212                     self.s.word(" ");
2213                     self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
2214                 }
2215             }
2216             ast::ExprKind::InlineAsm(ref a) => {
2217                 self.s.word("asm!");
2218                 self.popen();
2219                 self.print_string(&a.asm.as_str(), a.asm_str_style);
2220                 self.word_space(":");
2221
2222                 self.commasep(Inconsistent, &a.outputs, |s, out| {
2223                     let constraint = out.constraint.as_str();
2224                     let mut ch = constraint.chars();
2225                     match ch.next() {
2226                         Some('=') if out.is_rw => {
2227                             s.print_string(&format!("+{}", ch.as_str()),
2228                                            ast::StrStyle::Cooked)
2229                         }
2230                         _ => s.print_string(&constraint, ast::StrStyle::Cooked)
2231                     }
2232                     s.popen();
2233                     s.print_expr(&out.expr);
2234                     s.pclose();
2235                 });
2236                 self.s.space();
2237                 self.word_space(":");
2238
2239                 self.commasep(Inconsistent, &a.inputs, |s, &(co, ref o)| {
2240                     s.print_string(&co.as_str(), ast::StrStyle::Cooked);
2241                     s.popen();
2242                     s.print_expr(o);
2243                     s.pclose();
2244                 });
2245                 self.s.space();
2246                 self.word_space(":");
2247
2248                 self.commasep(Inconsistent, &a.clobbers,
2249                                    |s, co| {
2250                     s.print_string(&co.as_str(), ast::StrStyle::Cooked);
2251                 });
2252
2253                 let mut options = vec![];
2254                 if a.volatile {
2255                     options.push("volatile");
2256                 }
2257                 if a.alignstack {
2258                     options.push("alignstack");
2259                 }
2260                 if a.dialect == ast::AsmDialect::Intel {
2261                     options.push("intel");
2262                 }
2263
2264                 if !options.is_empty() {
2265                     self.s.space();
2266                     self.word_space(":");
2267                     self.commasep(Inconsistent, &options,
2268                                   |s, &co| {
2269                                       s.print_string(co, ast::StrStyle::Cooked);
2270                                   });
2271                 }
2272
2273                 self.pclose();
2274             }
2275             ast::ExprKind::Mac(ref m) => self.print_mac(m),
2276             ast::ExprKind::Paren(ref e) => {
2277                 self.popen();
2278                 self.print_inner_attributes_inline(attrs);
2279                 self.print_expr(e);
2280                 self.pclose();
2281             },
2282             ast::ExprKind::Yield(ref e) => {
2283                 self.s.word("yield");
2284                 match *e {
2285                     Some(ref expr) => {
2286                         self.s.space();
2287                         self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
2288                     }
2289                     _ => ()
2290                 }
2291             }
2292             ast::ExprKind::Try(ref e) => {
2293                 self.print_expr_maybe_paren(e, parser::PREC_POSTFIX);
2294                 self.s.word("?")
2295             }
2296             ast::ExprKind::TryBlock(ref blk) => {
2297                 self.head("try");
2298                 self.s.space();
2299                 self.print_block_with_attrs(blk, attrs)
2300             }
2301             ast::ExprKind::Err => {
2302                 self.popen();
2303                 self.s.word("/*ERROR*/");
2304                 self.pclose()
2305             }
2306         }
2307         self.ann.post(self, AnnNode::Expr(expr));
2308         self.end();
2309     }
2310
2311     crate fn print_local_decl(&mut self, loc: &ast::Local) {
2312         self.print_pat(&loc.pat);
2313         if let Some(ref ty) = loc.ty {
2314             self.word_space(":");
2315             self.print_type(ty);
2316         }
2317     }
2318
2319     crate fn print_usize(&mut self, i: usize) {
2320         self.s.word(i.to_string())
2321     }
2322
2323     crate fn print_name(&mut self, name: ast::Name) {
2324         self.s.word(name.as_str().to_string());
2325         self.ann.post(self, AnnNode::Name(&name))
2326     }
2327
2328     fn print_qpath(&mut self,
2329                    path: &ast::Path,
2330                    qself: &ast::QSelf,
2331                    colons_before_params: bool)
2332     {
2333         self.s.word("<");
2334         self.print_type(&qself.ty);
2335         if qself.position > 0 {
2336             self.s.space();
2337             self.word_space("as");
2338             let depth = path.segments.len() - qself.position;
2339             self.print_path(path, false, depth);
2340         }
2341         self.s.word(">");
2342         self.s.word("::");
2343         let item_segment = path.segments.last().unwrap();
2344         self.print_ident(item_segment.ident);
2345         match item_segment.args {
2346             Some(ref args) => self.print_generic_args(args, colons_before_params),
2347             None => {},
2348         }
2349     }
2350
2351     crate fn print_pat(&mut self, pat: &ast::Pat) {
2352         self.maybe_print_comment(pat.span.lo());
2353         self.ann.pre(self, AnnNode::Pat(pat));
2354         /* Pat isn't normalized, but the beauty of it
2355          is that it doesn't matter */
2356         match pat.kind {
2357             PatKind::Wild => self.s.word("_"),
2358             PatKind::Ident(binding_mode, ident, ref sub) => {
2359                 match binding_mode {
2360                     ast::BindingMode::ByRef(mutbl) => {
2361                         self.word_nbsp("ref");
2362                         self.print_mutability(mutbl);
2363                     }
2364                     ast::BindingMode::ByValue(ast::Mutability::Immutable) => {}
2365                     ast::BindingMode::ByValue(ast::Mutability::Mutable) => {
2366                         self.word_nbsp("mut");
2367                     }
2368                 }
2369                 self.print_ident(ident);
2370                 if let Some(ref p) = *sub {
2371                     self.s.word("@");
2372                     self.print_pat(p);
2373                 }
2374             }
2375             PatKind::TupleStruct(ref path, ref elts) => {
2376                 self.print_path(path, true, 0);
2377                 self.popen();
2378                 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(p));
2379                 self.pclose();
2380             }
2381             PatKind::Or(ref pats) => {
2382                 self.strsep("|", true, Inconsistent, &pats[..], |s, p| s.print_pat(p));
2383             }
2384             PatKind::Path(None, ref path) => {
2385                 self.print_path(path, true, 0);
2386             }
2387             PatKind::Path(Some(ref qself), ref path) => {
2388                 self.print_qpath(path, qself, false);
2389             }
2390             PatKind::Struct(ref path, ref fields, etc) => {
2391                 self.print_path(path, true, 0);
2392                 self.nbsp();
2393                 self.word_space("{");
2394                 self.commasep_cmnt(
2395                     Consistent, &fields[..],
2396                     |s, f| {
2397                         s.cbox(INDENT_UNIT);
2398                         if !f.is_shorthand {
2399                             s.print_ident(f.ident);
2400                             s.word_nbsp(":");
2401                         }
2402                         s.print_pat(&f.pat);
2403                         s.end();
2404                     },
2405                     |f| f.pat.span);
2406                 if etc {
2407                     if !fields.is_empty() { self.word_space(","); }
2408                     self.s.word("..");
2409                 }
2410                 self.s.space();
2411                 self.s.word("}");
2412             }
2413             PatKind::Tuple(ref elts) => {
2414                 self.popen();
2415                 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(p));
2416                 if elts.len() == 1 {
2417                     self.s.word(",");
2418                 }
2419                 self.pclose();
2420             }
2421             PatKind::Box(ref inner) => {
2422                 self.s.word("box ");
2423                 self.print_pat(inner);
2424             }
2425             PatKind::Ref(ref inner, mutbl) => {
2426                 self.s.word("&");
2427                 if mutbl == ast::Mutability::Mutable {
2428                     self.s.word("mut ");
2429                 }
2430                 self.print_pat(inner);
2431             }
2432             PatKind::Lit(ref e) => self.print_expr(&**e),
2433             PatKind::Range(ref begin, ref end, Spanned { node: ref end_kind, .. }) => {
2434                 self.print_expr(begin);
2435                 self.s.space();
2436                 match *end_kind {
2437                     RangeEnd::Included(RangeSyntax::DotDotDot) => self.s.word("..."),
2438                     RangeEnd::Included(RangeSyntax::DotDotEq) => self.s.word("..="),
2439                     RangeEnd::Excluded => self.s.word(".."),
2440                 }
2441                 self.print_expr(end);
2442             }
2443             PatKind::Slice(ref elts) => {
2444                 self.s.word("[");
2445                 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(p));
2446                 self.s.word("]");
2447             }
2448             PatKind::Rest => self.s.word(".."),
2449             PatKind::Paren(ref inner) => {
2450                 self.popen();
2451                 self.print_pat(inner);
2452                 self.pclose();
2453             }
2454             PatKind::Mac(ref m) => self.print_mac(m),
2455         }
2456         self.ann.post(self, AnnNode::Pat(pat))
2457     }
2458
2459     fn print_arm(&mut self, arm: &ast::Arm) {
2460         // Note, I have no idea why this check is necessary, but here it is.
2461         if arm.attrs.is_empty() {
2462             self.s.space();
2463         }
2464         self.cbox(INDENT_UNIT);
2465         self.ibox(0);
2466         self.maybe_print_comment(arm.pat.span.lo());
2467         self.print_outer_attributes(&arm.attrs);
2468         self.print_pat(&arm.pat);
2469         self.s.space();
2470         if let Some(ref e) = arm.guard {
2471             self.word_space("if");
2472             self.print_expr(e);
2473             self.s.space();
2474         }
2475         self.word_space("=>");
2476
2477         match arm.body.kind {
2478             ast::ExprKind::Block(ref blk, opt_label) => {
2479                 if let Some(label) = opt_label {
2480                     self.print_ident(label.ident);
2481                     self.word_space(":");
2482                 }
2483
2484                 // The block will close the pattern's ibox.
2485                 self.print_block_unclosed_indent(blk);
2486
2487                 // If it is a user-provided unsafe block, print a comma after it.
2488                 if let BlockCheckMode::Unsafe(ast::UserProvided) = blk.rules {
2489                     self.s.word(",");
2490                 }
2491             }
2492             _ => {
2493                 self.end(); // Close the ibox for the pattern.
2494                 self.print_expr(&arm.body);
2495                 self.s.word(",");
2496             }
2497         }
2498         self.end(); // Close enclosing cbox.
2499     }
2500
2501     fn print_explicit_self(&mut self, explicit_self: &ast::ExplicitSelf) {
2502         match explicit_self.node {
2503             SelfKind::Value(m) => {
2504                 self.print_mutability(m);
2505                 self.s.word("self")
2506             }
2507             SelfKind::Region(ref lt, m) => {
2508                 self.s.word("&");
2509                 self.print_opt_lifetime(lt);
2510                 self.print_mutability(m);
2511                 self.s.word("self")
2512             }
2513             SelfKind::Explicit(ref typ, m) => {
2514                 self.print_mutability(m);
2515                 self.s.word("self");
2516                 self.word_space(":");
2517                 self.print_type(typ)
2518             }
2519         }
2520     }
2521
2522     crate fn print_fn(&mut self,
2523                     decl: &ast::FnDecl,
2524                     header: ast::FnHeader,
2525                     name: Option<ast::Ident>,
2526                     generics: &ast::Generics,
2527                     vis: &ast::Visibility) {
2528         self.print_fn_header_info(header, vis);
2529
2530         if let Some(name) = name {
2531             self.nbsp();
2532             self.print_ident(name);
2533         }
2534         self.print_generic_params(&generics.params);
2535         self.print_fn_params_and_ret(decl);
2536         self.print_where_clause(&generics.where_clause)
2537     }
2538
2539     crate fn print_fn_params_and_ret(&mut self, decl: &ast::FnDecl) {
2540         self.popen();
2541         self.commasep(Inconsistent, &decl.inputs, |s, param| s.print_param(param, false));
2542         self.pclose();
2543
2544         self.print_fn_output(decl)
2545     }
2546
2547     crate fn print_fn_block_params(&mut self, decl: &ast::FnDecl) {
2548         self.s.word("|");
2549         self.commasep(Inconsistent, &decl.inputs, |s, param| s.print_param(param, true));
2550         self.s.word("|");
2551
2552         if let ast::FunctionRetTy::Default(..) = decl.output {
2553             return;
2554         }
2555
2556         self.space_if_not_bol();
2557         self.word_space("->");
2558         match decl.output {
2559             ast::FunctionRetTy::Ty(ref ty) => {
2560                 self.print_type(ty);
2561                 self.maybe_print_comment(ty.span.lo())
2562             }
2563             ast::FunctionRetTy::Default(..) => unreachable!(),
2564         }
2565     }
2566
2567     crate fn print_movability(&mut self, movability: ast::Movability) {
2568         match movability {
2569             ast::Movability::Static => self.word_space("static"),
2570             ast::Movability::Movable => {},
2571         }
2572     }
2573
2574     crate fn print_asyncness(&mut self, asyncness: ast::IsAsync) {
2575         if asyncness.is_async() {
2576             self.word_nbsp("async");
2577         }
2578     }
2579
2580     crate fn print_capture_clause(&mut self, capture_clause: ast::CaptureBy) {
2581         match capture_clause {
2582             ast::CaptureBy::Value => self.word_space("move"),
2583             ast::CaptureBy::Ref => {},
2584         }
2585     }
2586
2587     crate fn print_type_bounds(&mut self, prefix: &'static str, bounds: &[ast::GenericBound]) {
2588         if !bounds.is_empty() {
2589             self.s.word(prefix);
2590             let mut first = true;
2591             for bound in bounds {
2592                 if !(first && prefix.is_empty()) {
2593                     self.nbsp();
2594                 }
2595                 if first {
2596                     first = false;
2597                 } else {
2598                     self.word_space("+");
2599                 }
2600
2601                 match bound {
2602                     GenericBound::Trait(tref, modifier) => {
2603                         if modifier == &TraitBoundModifier::Maybe {
2604                             self.s.word("?");
2605                         }
2606                         self.print_poly_trait_ref(tref);
2607                     }
2608                     GenericBound::Outlives(lt) => self.print_lifetime(*lt),
2609                 }
2610             }
2611         }
2612     }
2613
2614     crate fn print_lifetime(&mut self, lifetime: ast::Lifetime) {
2615         self.print_name(lifetime.ident.name)
2616     }
2617
2618     crate fn print_lifetime_bounds(
2619         &mut self, lifetime: ast::Lifetime, bounds: &ast::GenericBounds) {
2620         self.print_lifetime(lifetime);
2621         if !bounds.is_empty() {
2622             self.s.word(": ");
2623             for (i, bound) in bounds.iter().enumerate() {
2624                 if i != 0 {
2625                     self.s.word(" + ");
2626                 }
2627                 match bound {
2628                     ast::GenericBound::Outlives(lt) => self.print_lifetime(*lt),
2629                     _ => panic!(),
2630                 }
2631             }
2632         }
2633     }
2634
2635     crate fn print_generic_params(&mut self, generic_params: &[ast::GenericParam]) {
2636         if generic_params.is_empty() {
2637             return;
2638         }
2639
2640         self.s.word("<");
2641
2642         self.commasep(Inconsistent, &generic_params, |s, param| {
2643             s.print_outer_attributes_inline(&param.attrs);
2644
2645             match param.kind {
2646                 ast::GenericParamKind::Lifetime => {
2647                     let lt = ast::Lifetime { id: param.id, ident: param.ident };
2648                     s.print_lifetime_bounds(lt, &param.bounds)
2649                 }
2650                 ast::GenericParamKind::Type { ref default } => {
2651                     s.print_ident(param.ident);
2652                     s.print_type_bounds(":", &param.bounds);
2653                     if let Some(ref default) = default {
2654                         s.s.space();
2655                         s.word_space("=");
2656                         s.print_type(default)
2657                     }
2658                 }
2659                 ast::GenericParamKind::Const { ref ty } => {
2660                     s.word_space("const");
2661                     s.print_ident(param.ident);
2662                     s.s.space();
2663                     s.word_space(":");
2664                     s.print_type(ty);
2665                     s.print_type_bounds(":", &param.bounds)
2666                 }
2667             }
2668         });
2669
2670         self.s.word(">");
2671     }
2672
2673     crate fn print_where_clause(&mut self, where_clause: &ast::WhereClause) {
2674         if where_clause.predicates.is_empty() {
2675             return;
2676         }
2677
2678         self.s.space();
2679         self.word_space("where");
2680
2681         for (i, predicate) in where_clause.predicates.iter().enumerate() {
2682             if i != 0 {
2683                 self.word_space(",");
2684             }
2685
2686             match *predicate {
2687                 ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
2688                     ref bound_generic_params,
2689                     ref bounded_ty,
2690                     ref bounds,
2691                     ..
2692                 }) => {
2693                     self.print_formal_generic_params(bound_generic_params);
2694                     self.print_type(bounded_ty);
2695                     self.print_type_bounds(":", bounds);
2696                 }
2697                 ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate{ref lifetime,
2698                                                                                ref bounds,
2699                                                                                ..}) => {
2700                     self.print_lifetime_bounds(*lifetime, bounds);
2701                 }
2702                 ast::WherePredicate::EqPredicate(ast::WhereEqPredicate{ref lhs_ty,
2703                                                                        ref rhs_ty,
2704                                                                        ..}) => {
2705                     self.print_type(lhs_ty);
2706                     self.s.space();
2707                     self.word_space("=");
2708                     self.print_type(rhs_ty);
2709                 }
2710             }
2711         }
2712     }
2713
2714     crate fn print_use_tree(&mut self, tree: &ast::UseTree) {
2715         match tree.kind {
2716             ast::UseTreeKind::Simple(rename, ..) => {
2717                 self.print_path(&tree.prefix, false, 0);
2718                 if let Some(rename) = rename {
2719                     self.s.space();
2720                     self.word_space("as");
2721                     self.print_ident(rename);
2722                 }
2723             }
2724             ast::UseTreeKind::Glob => {
2725                 if !tree.prefix.segments.is_empty() {
2726                     self.print_path(&tree.prefix, false, 0);
2727                     self.s.word("::");
2728                 }
2729                 self.s.word("*");
2730             }
2731             ast::UseTreeKind::Nested(ref items) => {
2732                 if tree.prefix.segments.is_empty() {
2733                     self.s.word("{");
2734                 } else {
2735                     self.print_path(&tree.prefix, false, 0);
2736                     self.s.word("::{");
2737                 }
2738                 self.commasep(Inconsistent, &items[..], |this, &(ref tree, _)| {
2739                     this.print_use_tree(tree)
2740                 });
2741                 self.s.word("}");
2742             }
2743         }
2744     }
2745
2746     crate fn print_mutability(&mut self, mutbl: ast::Mutability) {
2747         match mutbl {
2748             ast::Mutability::Mutable => self.word_nbsp("mut"),
2749             ast::Mutability::Immutable => {},
2750         }
2751     }
2752
2753     crate fn print_mt(&mut self, mt: &ast::MutTy) {
2754         self.print_mutability(mt.mutbl);
2755         self.print_type(&mt.ty)
2756     }
2757
2758     crate fn print_param(&mut self, input: &ast::Param, is_closure: bool) {
2759         self.ibox(INDENT_UNIT);
2760
2761         self.print_outer_attributes_inline(&input.attrs);
2762
2763         match input.ty.kind {
2764             ast::TyKind::Infer if is_closure => self.print_pat(&input.pat),
2765             _ => {
2766                 if let Some(eself) = input.to_self() {
2767                     self.print_explicit_self(&eself);
2768                 } else {
2769                     let invalid = if let PatKind::Ident(_, ident, _) = input.pat.kind {
2770                         ident.name == kw::Invalid
2771                     } else {
2772                         false
2773                     };
2774                     if !invalid {
2775                         self.print_pat(&input.pat);
2776                         self.s.word(":");
2777                         self.s.space();
2778                     }
2779                     self.print_type(&input.ty);
2780                 }
2781             }
2782         }
2783         self.end();
2784     }
2785
2786     crate fn print_fn_output(&mut self, decl: &ast::FnDecl) {
2787         if let ast::FunctionRetTy::Default(..) = decl.output {
2788             return;
2789         }
2790
2791         self.space_if_not_bol();
2792         self.ibox(INDENT_UNIT);
2793         self.word_space("->");
2794         match decl.output {
2795             ast::FunctionRetTy::Default(..) => unreachable!(),
2796             ast::FunctionRetTy::Ty(ref ty) =>
2797                 self.print_type(ty),
2798         }
2799         self.end();
2800
2801         match decl.output {
2802             ast::FunctionRetTy::Ty(ref output) => self.maybe_print_comment(output.span.lo()),
2803             _ => {}
2804         }
2805     }
2806
2807     crate fn print_ty_fn(&mut self,
2808                        abi: abi::Abi,
2809                        unsafety: ast::Unsafety,
2810                        decl: &ast::FnDecl,
2811                        name: Option<ast::Ident>,
2812                        generic_params: &[ast::GenericParam])
2813                        {
2814         self.ibox(INDENT_UNIT);
2815         if !generic_params.is_empty() {
2816             self.s.word("for");
2817             self.print_generic_params(generic_params);
2818         }
2819         let generics = ast::Generics {
2820             params: Vec::new(),
2821             where_clause: ast::WhereClause {
2822                 predicates: Vec::new(),
2823                 span: syntax_pos::DUMMY_SP,
2824             },
2825             span: syntax_pos::DUMMY_SP,
2826         };
2827         self.print_fn(decl,
2828                       ast::FnHeader { unsafety, abi, ..ast::FnHeader::default() },
2829                       name,
2830                       &generics,
2831                       &source_map::dummy_spanned(ast::VisibilityKind::Inherited));
2832         self.end();
2833     }
2834
2835     crate fn maybe_print_trailing_comment(&mut self, span: syntax_pos::Span,
2836                                         next_pos: Option<BytePos>)
2837     {
2838         if let Some(cmnts) = self.comments() {
2839             if let Some(cmnt) = cmnts.trailing_comment(span, next_pos) {
2840                 self.print_comment(&cmnt);
2841             }
2842         }
2843     }
2844
2845     crate fn print_remaining_comments(&mut self) {
2846         // If there aren't any remaining comments, then we need to manually
2847         // make sure there is a line break at the end.
2848         if self.next_comment().is_none() {
2849             self.s.hardbreak();
2850         }
2851         while let Some(ref cmnt) = self.next_comment() {
2852             self.print_comment(cmnt);
2853         }
2854     }
2855
2856     crate fn print_fn_header_info(&mut self,
2857                                 header: ast::FnHeader,
2858                                 vis: &ast::Visibility) {
2859         self.s.word(visibility_qualified(vis, ""));
2860
2861         match header.constness.node {
2862             ast::Constness::NotConst => {}
2863             ast::Constness::Const => self.word_nbsp("const")
2864         }
2865
2866         self.print_asyncness(header.asyncness.node);
2867         self.print_unsafety(header.unsafety);
2868
2869         if header.abi != Abi::Rust {
2870             self.word_nbsp("extern");
2871             self.word_nbsp(header.abi.to_string());
2872         }
2873
2874         self.s.word("fn")
2875     }
2876
2877     crate fn print_unsafety(&mut self, s: ast::Unsafety) {
2878         match s {
2879             ast::Unsafety::Normal => {},
2880             ast::Unsafety::Unsafe => self.word_nbsp("unsafe"),
2881         }
2882     }
2883
2884     crate fn print_is_auto(&mut self, s: ast::IsAuto) {
2885         match s {
2886             ast::IsAuto::Yes => self.word_nbsp("auto"),
2887             ast::IsAuto::No => {}
2888         }
2889     }
2890 }