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