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