]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_ast_pretty/src/pprust/state.rs
Rollup merge of #92487 - dtolnay:traitalias, r=matthewjasper
[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::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(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("impl");
1291
1292                 if generics.params.is_empty() {
1293                     self.nbsp();
1294                 } else {
1295                     self.print_generic_params(&generics.params);
1296                     self.space();
1297                 }
1298
1299                 self.print_constness(constness);
1300
1301                 if let ast::ImplPolarity::Negative(_) = polarity {
1302                     self.word("!");
1303                 }
1304
1305                 if let Some(ref t) = *of_trait {
1306                     self.print_trait_ref(t);
1307                     self.space();
1308                     self.word_space("for");
1309                 }
1310
1311                 self.print_type(self_ty);
1312                 self.print_where_clause(&generics.where_clause);
1313
1314                 self.space();
1315                 self.bopen();
1316                 self.print_inner_attributes(&item.attrs);
1317                 for impl_item in items {
1318                     self.print_assoc_item(impl_item);
1319                 }
1320                 let empty = item.attrs.is_empty() && items.is_empty();
1321                 self.bclose(item.span, empty);
1322             }
1323             ast::ItemKind::Trait(box ast::Trait {
1324                 is_auto,
1325                 unsafety,
1326                 ref generics,
1327                 ref bounds,
1328                 ref items,
1329                 ..
1330             }) => {
1331                 self.head("");
1332                 self.print_visibility(&item.vis);
1333                 self.print_unsafety(unsafety);
1334                 self.print_is_auto(is_auto);
1335                 self.word_nbsp("trait");
1336                 self.print_ident(item.ident);
1337                 self.print_generic_params(&generics.params);
1338                 let mut real_bounds = Vec::with_capacity(bounds.len());
1339                 for b in bounds.iter() {
1340                     if let GenericBound::Trait(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
1341                         self.space();
1342                         self.word_space("for ?");
1343                         self.print_trait_ref(&ptr.trait_ref);
1344                     } else {
1345                         real_bounds.push(b.clone());
1346                     }
1347                 }
1348                 self.print_type_bounds(":", &real_bounds);
1349                 self.print_where_clause(&generics.where_clause);
1350                 self.word(" ");
1351                 self.bopen();
1352                 self.print_inner_attributes(&item.attrs);
1353                 for trait_item in items {
1354                     self.print_assoc_item(trait_item);
1355                 }
1356                 let empty = item.attrs.is_empty() && items.is_empty();
1357                 self.bclose(item.span, empty);
1358             }
1359             ast::ItemKind::TraitAlias(ref generics, ref bounds) => {
1360                 self.head(visibility_qualified(&item.vis, "trait"));
1361                 self.print_ident(item.ident);
1362                 self.print_generic_params(&generics.params);
1363                 let mut real_bounds = Vec::with_capacity(bounds.len());
1364                 // FIXME(durka) this seems to be some quite outdated syntax
1365                 for b in bounds.iter() {
1366                     if let GenericBound::Trait(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
1367                         self.space();
1368                         self.word_space("for ?");
1369                         self.print_trait_ref(&ptr.trait_ref);
1370                     } else {
1371                         real_bounds.push(b.clone());
1372                     }
1373                 }
1374                 self.nbsp();
1375                 self.print_type_bounds("=", &real_bounds);
1376                 self.print_where_clause(&generics.where_clause);
1377                 self.word(";");
1378                 self.end(); // end inner head-block
1379                 self.end(); // end outer head-block
1380             }
1381             ast::ItemKind::MacCall(ref mac) => {
1382                 self.print_mac(mac);
1383                 if mac.args.need_semicolon() {
1384                     self.word(";");
1385                 }
1386             }
1387             ast::ItemKind::MacroDef(ref macro_def) => {
1388                 self.print_mac_def(macro_def, &item.ident, &item.span, |state| {
1389                     state.print_visibility(&item.vis)
1390                 });
1391             }
1392         }
1393         self.ann.post(self, AnnNode::Item(item))
1394     }
1395
1396     fn print_trait_ref(&mut self, t: &ast::TraitRef) {
1397         self.print_path(&t.path, false, 0)
1398     }
1399
1400     fn print_formal_generic_params(&mut self, generic_params: &[ast::GenericParam]) {
1401         if !generic_params.is_empty() {
1402             self.word("for");
1403             self.print_generic_params(generic_params);
1404             self.nbsp();
1405         }
1406     }
1407
1408     fn print_poly_trait_ref(&mut self, t: &ast::PolyTraitRef) {
1409         self.print_formal_generic_params(&t.bound_generic_params);
1410         self.print_trait_ref(&t.trait_ref)
1411     }
1412
1413     crate fn print_enum_def(
1414         &mut self,
1415         enum_definition: &ast::EnumDef,
1416         generics: &ast::Generics,
1417         ident: Ident,
1418         span: rustc_span::Span,
1419         visibility: &ast::Visibility,
1420     ) {
1421         self.head(visibility_qualified(visibility, "enum"));
1422         self.print_ident(ident);
1423         self.print_generic_params(&generics.params);
1424         self.print_where_clause(&generics.where_clause);
1425         self.space();
1426         self.print_variants(&enum_definition.variants, span)
1427     }
1428
1429     crate fn print_variants(&mut self, variants: &[ast::Variant], span: rustc_span::Span) {
1430         self.bopen();
1431         for v in variants {
1432             self.space_if_not_bol();
1433             self.maybe_print_comment(v.span.lo());
1434             self.print_outer_attributes(&v.attrs);
1435             self.ibox(INDENT_UNIT);
1436             self.print_variant(v);
1437             self.word(",");
1438             self.end();
1439             self.maybe_print_trailing_comment(v.span, None);
1440         }
1441         let empty = variants.is_empty();
1442         self.bclose(span, empty)
1443     }
1444
1445     crate fn print_visibility(&mut self, vis: &ast::Visibility) {
1446         match vis.kind {
1447             ast::VisibilityKind::Public => self.word_nbsp("pub"),
1448             ast::VisibilityKind::Crate(sugar) => match sugar {
1449                 ast::CrateSugar::PubCrate => self.word_nbsp("pub(crate)"),
1450                 ast::CrateSugar::JustCrate => self.word_nbsp("crate"),
1451             },
1452             ast::VisibilityKind::Restricted { ref path, .. } => {
1453                 let path = Self::to_string(|s| s.print_path(path, false, 0));
1454                 if path == "self" || path == "super" {
1455                     self.word_nbsp(format!("pub({})", path))
1456                 } else {
1457                     self.word_nbsp(format!("pub(in {})", path))
1458                 }
1459             }
1460             ast::VisibilityKind::Inherited => {}
1461         }
1462     }
1463
1464     crate fn print_defaultness(&mut self, defaultness: ast::Defaultness) {
1465         if let ast::Defaultness::Default(_) = defaultness {
1466             self.word_nbsp("default");
1467         }
1468     }
1469
1470     crate fn print_record_struct_body(&mut self, fields: &[ast::FieldDef], span: rustc_span::Span) {
1471         self.nbsp();
1472         self.bopen();
1473
1474         let empty = fields.is_empty();
1475         if !empty {
1476             self.hardbreak_if_not_bol();
1477
1478             for field in fields {
1479                 self.hardbreak_if_not_bol();
1480                 self.maybe_print_comment(field.span.lo());
1481                 self.print_outer_attributes(&field.attrs);
1482                 self.print_visibility(&field.vis);
1483                 self.print_ident(field.ident.unwrap());
1484                 self.word_nbsp(":");
1485                 self.print_type(&field.ty);
1486                 self.word(",");
1487             }
1488         }
1489
1490         self.bclose(span, empty);
1491     }
1492
1493     crate fn print_struct(
1494         &mut self,
1495         struct_def: &ast::VariantData,
1496         generics: &ast::Generics,
1497         ident: Ident,
1498         span: rustc_span::Span,
1499         print_finalizer: bool,
1500     ) {
1501         self.print_ident(ident);
1502         self.print_generic_params(&generics.params);
1503         match struct_def {
1504             ast::VariantData::Tuple(..) | ast::VariantData::Unit(..) => {
1505                 if let ast::VariantData::Tuple(..) = struct_def {
1506                     self.popen();
1507                     self.commasep(Inconsistent, struct_def.fields(), |s, field| {
1508                         s.maybe_print_comment(field.span.lo());
1509                         s.print_outer_attributes(&field.attrs);
1510                         s.print_visibility(&field.vis);
1511                         s.print_type(&field.ty)
1512                     });
1513                     self.pclose();
1514                 }
1515                 self.print_where_clause(&generics.where_clause);
1516                 if print_finalizer {
1517                     self.word(";");
1518                 }
1519                 self.end();
1520                 self.end(); // Close the outer-box.
1521             }
1522             ast::VariantData::Struct(ref fields, ..) => {
1523                 self.print_where_clause(&generics.where_clause);
1524                 self.print_record_struct_body(fields, span);
1525             }
1526         }
1527     }
1528
1529     crate fn print_variant(&mut self, v: &ast::Variant) {
1530         self.head("");
1531         self.print_visibility(&v.vis);
1532         let generics = ast::Generics::default();
1533         self.print_struct(&v.data, &generics, v.ident, v.span, false);
1534         if let Some(ref d) = v.disr_expr {
1535             self.space();
1536             self.word_space("=");
1537             self.print_expr(&d.value)
1538         }
1539     }
1540
1541     crate fn print_assoc_item(&mut self, item: &ast::AssocItem) {
1542         let ast::Item { id, span, ident, ref attrs, ref kind, ref vis, tokens: _ } = *item;
1543         self.ann.pre(self, AnnNode::SubItem(id));
1544         self.hardbreak_if_not_bol();
1545         self.maybe_print_comment(span.lo());
1546         self.print_outer_attributes(attrs);
1547         match kind {
1548             ast::AssocItemKind::Fn(box ast::Fn { defaultness, sig, generics, body }) => {
1549                 self.print_fn_full(sig, ident, generics, vis, *defaultness, body.as_deref(), attrs);
1550             }
1551             ast::AssocItemKind::Const(def, ty, body) => {
1552                 self.print_item_const(ident, None, ty, body.as_deref(), vis, *def);
1553             }
1554             ast::AssocItemKind::TyAlias(box ast::TyAlias { defaultness, generics, bounds, ty }) => {
1555                 self.print_associated_type(
1556                     ident,
1557                     generics,
1558                     bounds,
1559                     ty.as_deref(),
1560                     vis,
1561                     *defaultness,
1562                 );
1563             }
1564             ast::AssocItemKind::MacCall(m) => {
1565                 self.print_mac(m);
1566                 if m.args.need_semicolon() {
1567                     self.word(";");
1568                 }
1569             }
1570         }
1571         self.ann.post(self, AnnNode::SubItem(id))
1572     }
1573
1574     crate fn print_stmt(&mut self, st: &ast::Stmt) {
1575         self.maybe_print_comment(st.span.lo());
1576         match st.kind {
1577             ast::StmtKind::Local(ref loc) => {
1578                 self.print_outer_attributes(&loc.attrs);
1579                 self.space_if_not_bol();
1580                 self.ibox(INDENT_UNIT);
1581                 self.word_nbsp("let");
1582
1583                 self.ibox(INDENT_UNIT);
1584                 self.print_local_decl(loc);
1585                 self.end();
1586                 if let Some((init, els)) = loc.kind.init_else_opt() {
1587                     self.nbsp();
1588                     self.word_space("=");
1589                     self.print_expr(init);
1590                     if let Some(els) = els {
1591                         self.cbox(INDENT_UNIT);
1592                         self.ibox(INDENT_UNIT);
1593                         self.word(" else ");
1594                         self.print_block(els);
1595                     }
1596                 }
1597                 self.word(";");
1598                 self.end(); // `let` ibox
1599             }
1600             ast::StmtKind::Item(ref item) => self.print_item(item),
1601             ast::StmtKind::Expr(ref expr) => {
1602                 self.space_if_not_bol();
1603                 self.print_expr_outer_attr_style(expr, false);
1604                 if classify::expr_requires_semi_to_be_stmt(expr) {
1605                     self.word(";");
1606                 }
1607             }
1608             ast::StmtKind::Semi(ref expr) => {
1609                 self.space_if_not_bol();
1610                 self.print_expr_outer_attr_style(expr, false);
1611                 self.word(";");
1612             }
1613             ast::StmtKind::Empty => {
1614                 self.space_if_not_bol();
1615                 self.word(";");
1616             }
1617             ast::StmtKind::MacCall(ref mac) => {
1618                 self.space_if_not_bol();
1619                 self.print_outer_attributes(&mac.attrs);
1620                 self.print_mac(&mac.mac);
1621                 if mac.style == ast::MacStmtStyle::Semicolon {
1622                     self.word(";");
1623                 }
1624             }
1625         }
1626         self.maybe_print_trailing_comment(st.span, None)
1627     }
1628
1629     crate fn print_block(&mut self, blk: &ast::Block) {
1630         self.print_block_with_attrs(blk, &[])
1631     }
1632
1633     crate fn print_block_unclosed_indent(&mut self, blk: &ast::Block) {
1634         self.print_block_maybe_unclosed(blk, &[], false)
1635     }
1636
1637     crate fn print_block_with_attrs(&mut self, blk: &ast::Block, attrs: &[ast::Attribute]) {
1638         self.print_block_maybe_unclosed(blk, attrs, true)
1639     }
1640
1641     crate fn print_block_maybe_unclosed(
1642         &mut self,
1643         blk: &ast::Block,
1644         attrs: &[ast::Attribute],
1645         close_box: bool,
1646     ) {
1647         match blk.rules {
1648             BlockCheckMode::Unsafe(..) => self.word_space("unsafe"),
1649             BlockCheckMode::Default => (),
1650         }
1651         self.maybe_print_comment(blk.span.lo());
1652         self.ann.pre(self, AnnNode::Block(blk));
1653         self.bopen();
1654
1655         let has_attrs = self.print_inner_attributes(attrs);
1656
1657         for (i, st) in blk.stmts.iter().enumerate() {
1658             match st.kind {
1659                 ast::StmtKind::Expr(ref expr) if i == blk.stmts.len() - 1 => {
1660                     self.maybe_print_comment(st.span.lo());
1661                     self.space_if_not_bol();
1662                     self.print_expr_outer_attr_style(expr, false);
1663                     self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi()));
1664                 }
1665                 _ => self.print_stmt(st),
1666             }
1667         }
1668
1669         let empty = !has_attrs && blk.stmts.is_empty();
1670         self.bclose_maybe_open(blk.span, empty, close_box);
1671         self.ann.post(self, AnnNode::Block(blk))
1672     }
1673
1674     /// Print a `let pat = expr` expression.
1675     crate fn print_let(&mut self, pat: &ast::Pat, expr: &ast::Expr) {
1676         self.word("let ");
1677         self.print_pat(pat);
1678         self.space();
1679         self.word_space("=");
1680         let npals = || parser::needs_par_as_let_scrutinee(expr.precedence().order());
1681         self.print_expr_cond_paren(expr, Self::cond_needs_par(expr) || npals())
1682     }
1683
1684     fn print_else(&mut self, els: Option<&ast::Expr>) {
1685         if let Some(_else) = els {
1686             match _else.kind {
1687                 // Another `else if` block.
1688                 ast::ExprKind::If(ref i, ref then, ref e) => {
1689                     self.cbox(INDENT_UNIT - 1);
1690                     self.ibox(0);
1691                     self.word(" else if ");
1692                     self.print_expr_as_cond(i);
1693                     self.space();
1694                     self.print_block(then);
1695                     self.print_else(e.as_deref())
1696                 }
1697                 // Final `else` block.
1698                 ast::ExprKind::Block(ref b, _) => {
1699                     self.cbox(INDENT_UNIT - 1);
1700                     self.ibox(0);
1701                     self.word(" else ");
1702                     self.print_block(b)
1703                 }
1704                 // Constraints would be great here!
1705                 _ => {
1706                     panic!("print_if saw if with weird alternative");
1707                 }
1708             }
1709         }
1710     }
1711
1712     crate fn print_if(&mut self, test: &ast::Expr, blk: &ast::Block, elseopt: Option<&ast::Expr>) {
1713         self.head("if");
1714         self.print_expr_as_cond(test);
1715         self.space();
1716         self.print_block(blk);
1717         self.print_else(elseopt)
1718     }
1719
1720     crate fn print_mac(&mut self, m: &ast::MacCall) {
1721         self.print_mac_common(
1722             Some(MacHeader::Path(&m.path)),
1723             true,
1724             None,
1725             m.args.delim(),
1726             &m.args.inner_tokens(),
1727             true,
1728             m.span(),
1729         );
1730     }
1731
1732     fn print_call_post(&mut self, args: &[P<ast::Expr>]) {
1733         self.popen();
1734         self.commasep_exprs(Inconsistent, args);
1735         self.pclose()
1736     }
1737
1738     crate fn print_expr_maybe_paren(&mut self, expr: &ast::Expr, prec: i8) {
1739         self.print_expr_cond_paren(expr, expr.precedence().order() < prec)
1740     }
1741
1742     /// Prints an expr using syntax that's acceptable in a condition position, such as the `cond` in
1743     /// `if cond { ... }`.
1744     crate fn print_expr_as_cond(&mut self, expr: &ast::Expr) {
1745         self.print_expr_cond_paren(expr, Self::cond_needs_par(expr))
1746     }
1747
1748     // Does `expr` need parentheses when printed in a condition position?
1749     //
1750     // These cases need parens due to the parse error observed in #26461: `if return {}`
1751     // parses as the erroneous construct `if (return {})`, not `if (return) {}`.
1752     fn cond_needs_par(expr: &ast::Expr) -> bool {
1753         match expr.kind {
1754             ast::ExprKind::Break(..) | ast::ExprKind::Closure(..) | ast::ExprKind::Ret(..) => true,
1755             _ => parser::contains_exterior_struct_lit(expr),
1756         }
1757     }
1758
1759     /// Prints `expr` or `(expr)` when `needs_par` holds.
1760     fn print_expr_cond_paren(&mut self, expr: &ast::Expr, needs_par: bool) {
1761         if needs_par {
1762             self.popen();
1763         }
1764         self.print_expr(expr);
1765         if needs_par {
1766             self.pclose();
1767         }
1768     }
1769
1770     fn print_expr_vec(&mut self, exprs: &[P<ast::Expr>]) {
1771         self.ibox(INDENT_UNIT);
1772         self.word("[");
1773         self.commasep_exprs(Inconsistent, exprs);
1774         self.word("]");
1775         self.end();
1776     }
1777
1778     fn print_expr_anon_const(&mut self, expr: &ast::AnonConst) {
1779         self.ibox(INDENT_UNIT);
1780         self.word("const");
1781         self.print_expr(&expr.value);
1782         self.end();
1783     }
1784
1785     fn print_expr_repeat(&mut self, element: &ast::Expr, count: &ast::AnonConst) {
1786         self.ibox(INDENT_UNIT);
1787         self.word("[");
1788         self.print_expr(element);
1789         self.word_space(";");
1790         self.print_expr(&count.value);
1791         self.word("]");
1792         self.end();
1793     }
1794
1795     fn print_expr_struct(
1796         &mut self,
1797         qself: &Option<ast::QSelf>,
1798         path: &ast::Path,
1799         fields: &[ast::ExprField],
1800         rest: &ast::StructRest,
1801     ) {
1802         if let Some(qself) = qself {
1803             self.print_qpath(path, qself, true);
1804         } else {
1805             self.print_path(path, true, 0);
1806         }
1807         self.word("{");
1808         self.commasep_cmnt(
1809             Consistent,
1810             fields,
1811             |s, field| {
1812                 s.print_outer_attributes(&field.attrs);
1813                 s.ibox(INDENT_UNIT);
1814                 if !field.is_shorthand {
1815                     s.print_ident(field.ident);
1816                     s.word_space(":");
1817                 }
1818                 s.print_expr(&field.expr);
1819                 s.end();
1820             },
1821             |f| f.span,
1822         );
1823         match rest {
1824             ast::StructRest::Base(_) | ast::StructRest::Rest(_) => {
1825                 self.ibox(INDENT_UNIT);
1826                 if !fields.is_empty() {
1827                     self.word(",");
1828                     self.space();
1829                 }
1830                 self.word("..");
1831                 if let ast::StructRest::Base(ref expr) = *rest {
1832                     self.print_expr(expr);
1833                 }
1834                 self.end();
1835             }
1836             ast::StructRest::None if !fields.is_empty() => self.word(","),
1837             _ => {}
1838         }
1839         self.word("}");
1840     }
1841
1842     fn print_expr_tup(&mut self, exprs: &[P<ast::Expr>]) {
1843         self.popen();
1844         self.commasep_exprs(Inconsistent, exprs);
1845         if exprs.len() == 1 {
1846             self.word(",");
1847         }
1848         self.pclose()
1849     }
1850
1851     fn print_expr_call(&mut self, func: &ast::Expr, args: &[P<ast::Expr>]) {
1852         let prec = match func.kind {
1853             ast::ExprKind::Field(..) => parser::PREC_FORCE_PAREN,
1854             _ => parser::PREC_POSTFIX,
1855         };
1856
1857         self.print_expr_maybe_paren(func, prec);
1858         self.print_call_post(args)
1859     }
1860
1861     fn print_expr_method_call(&mut self, segment: &ast::PathSegment, args: &[P<ast::Expr>]) {
1862         let base_args = &args[1..];
1863         self.print_expr_maybe_paren(&args[0], parser::PREC_POSTFIX);
1864         self.word(".");
1865         self.print_ident(segment.ident);
1866         if let Some(ref args) = segment.args {
1867             self.print_generic_args(args, true);
1868         }
1869         self.print_call_post(base_args)
1870     }
1871
1872     fn print_expr_binary(&mut self, op: ast::BinOp, lhs: &ast::Expr, rhs: &ast::Expr) {
1873         let assoc_op = AssocOp::from_ast_binop(op.node);
1874         let prec = assoc_op.precedence() as i8;
1875         let fixity = assoc_op.fixity();
1876
1877         let (left_prec, right_prec) = match fixity {
1878             Fixity::Left => (prec, prec + 1),
1879             Fixity::Right => (prec + 1, prec),
1880             Fixity::None => (prec + 1, prec + 1),
1881         };
1882
1883         let left_prec = match (&lhs.kind, op.node) {
1884             // These cases need parens: `x as i32 < y` has the parser thinking that `i32 < y` is
1885             // the beginning of a path type. It starts trying to parse `x as (i32 < y ...` instead
1886             // of `(x as i32) < ...`. We need to convince it _not_ to do that.
1887             (&ast::ExprKind::Cast { .. }, ast::BinOpKind::Lt | ast::BinOpKind::Shl) => {
1888                 parser::PREC_FORCE_PAREN
1889             }
1890             // We are given `(let _ = a) OP b`.
1891             //
1892             // - When `OP <= LAnd` we should print `let _ = a OP b` to avoid redundant parens
1893             //   as the parser will interpret this as `(let _ = a) OP b`.
1894             //
1895             // - Otherwise, e.g. when we have `(let a = b) < c` in AST,
1896             //   parens are required since the parser would interpret `let a = b < c` as
1897             //   `let a = (b < c)`. To achieve this, we force parens.
1898             (&ast::ExprKind::Let { .. }, _) if !parser::needs_par_as_let_scrutinee(prec) => {
1899                 parser::PREC_FORCE_PAREN
1900             }
1901             _ => left_prec,
1902         };
1903
1904         self.print_expr_maybe_paren(lhs, left_prec);
1905         self.space();
1906         self.word_space(op.node.to_string());
1907         self.print_expr_maybe_paren(rhs, right_prec)
1908     }
1909
1910     fn print_expr_unary(&mut self, op: ast::UnOp, expr: &ast::Expr) {
1911         self.word(ast::UnOp::to_string(op));
1912         self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1913     }
1914
1915     fn print_expr_addr_of(
1916         &mut self,
1917         kind: ast::BorrowKind,
1918         mutability: ast::Mutability,
1919         expr: &ast::Expr,
1920     ) {
1921         self.word("&");
1922         match kind {
1923             ast::BorrowKind::Ref => self.print_mutability(mutability, false),
1924             ast::BorrowKind::Raw => {
1925                 self.word_nbsp("raw");
1926                 self.print_mutability(mutability, true);
1927             }
1928         }
1929         self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1930     }
1931
1932     pub fn print_expr(&mut self, expr: &ast::Expr) {
1933         self.print_expr_outer_attr_style(expr, true)
1934     }
1935
1936     fn print_expr_outer_attr_style(&mut self, expr: &ast::Expr, is_inline: bool) {
1937         self.maybe_print_comment(expr.span.lo());
1938
1939         let attrs = &expr.attrs;
1940         if is_inline {
1941             self.print_outer_attributes_inline(attrs);
1942         } else {
1943             self.print_outer_attributes(attrs);
1944         }
1945
1946         self.ibox(INDENT_UNIT);
1947         self.ann.pre(self, AnnNode::Expr(expr));
1948         match expr.kind {
1949             ast::ExprKind::Box(ref expr) => {
1950                 self.word_space("box");
1951                 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX);
1952             }
1953             ast::ExprKind::Array(ref exprs) => {
1954                 self.print_expr_vec(exprs);
1955             }
1956             ast::ExprKind::ConstBlock(ref anon_const) => {
1957                 self.print_expr_anon_const(anon_const);
1958             }
1959             ast::ExprKind::Repeat(ref element, ref count) => {
1960                 self.print_expr_repeat(element, count);
1961             }
1962             ast::ExprKind::Struct(ref se) => {
1963                 self.print_expr_struct(&se.qself, &se.path, &se.fields, &se.rest);
1964             }
1965             ast::ExprKind::Tup(ref exprs) => {
1966                 self.print_expr_tup(exprs);
1967             }
1968             ast::ExprKind::Call(ref func, ref args) => {
1969                 self.print_expr_call(func, &args);
1970             }
1971             ast::ExprKind::MethodCall(ref segment, ref args, _) => {
1972                 self.print_expr_method_call(segment, &args);
1973             }
1974             ast::ExprKind::Binary(op, ref lhs, ref rhs) => {
1975                 self.print_expr_binary(op, lhs, rhs);
1976             }
1977             ast::ExprKind::Unary(op, ref expr) => {
1978                 self.print_expr_unary(op, expr);
1979             }
1980             ast::ExprKind::AddrOf(k, m, ref expr) => {
1981                 self.print_expr_addr_of(k, m, expr);
1982             }
1983             ast::ExprKind::Lit(ref lit) => {
1984                 self.print_literal(lit);
1985             }
1986             ast::ExprKind::Cast(ref expr, ref ty) => {
1987                 let prec = AssocOp::As.precedence() as i8;
1988                 self.print_expr_maybe_paren(expr, prec);
1989                 self.space();
1990                 self.word_space("as");
1991                 self.print_type(ty);
1992             }
1993             ast::ExprKind::Type(ref expr, ref ty) => {
1994                 let prec = AssocOp::Colon.precedence() as i8;
1995                 self.print_expr_maybe_paren(expr, prec);
1996                 self.word_space(":");
1997                 self.print_type(ty);
1998             }
1999             ast::ExprKind::Let(ref pat, ref scrutinee, _) => {
2000                 self.print_let(pat, scrutinee);
2001             }
2002             ast::ExprKind::If(ref test, ref blk, ref elseopt) => {
2003                 self.print_if(test, blk, elseopt.as_deref())
2004             }
2005             ast::ExprKind::While(ref test, ref blk, opt_label) => {
2006                 if let Some(label) = opt_label {
2007                     self.print_ident(label.ident);
2008                     self.word_space(":");
2009                 }
2010                 self.head("while");
2011                 self.print_expr_as_cond(test);
2012                 self.space();
2013                 self.print_block_with_attrs(blk, attrs);
2014             }
2015             ast::ExprKind::ForLoop(ref pat, ref iter, ref blk, opt_label) => {
2016                 if let Some(label) = opt_label {
2017                     self.print_ident(label.ident);
2018                     self.word_space(":");
2019                 }
2020                 self.head("for");
2021                 self.print_pat(pat);
2022                 self.space();
2023                 self.word_space("in");
2024                 self.print_expr_as_cond(iter);
2025                 self.space();
2026                 self.print_block_with_attrs(blk, attrs);
2027             }
2028             ast::ExprKind::Loop(ref blk, opt_label) => {
2029                 if let Some(label) = opt_label {
2030                     self.print_ident(label.ident);
2031                     self.word_space(":");
2032                 }
2033                 self.head("loop");
2034                 self.print_block_with_attrs(blk, attrs);
2035             }
2036             ast::ExprKind::Match(ref expr, ref arms) => {
2037                 self.cbox(INDENT_UNIT);
2038                 self.ibox(INDENT_UNIT);
2039                 self.word_nbsp("match");
2040                 self.print_expr_as_cond(expr);
2041                 self.space();
2042                 self.bopen();
2043                 self.print_inner_attributes_no_trailing_hardbreak(attrs);
2044                 for arm in arms {
2045                     self.print_arm(arm);
2046                 }
2047                 let empty = attrs.is_empty() && arms.is_empty();
2048                 self.bclose(expr.span, empty);
2049             }
2050             ast::ExprKind::Closure(
2051                 capture_clause,
2052                 asyncness,
2053                 movability,
2054                 ref decl,
2055                 ref body,
2056                 _,
2057             ) => {
2058                 self.print_movability(movability);
2059                 self.print_asyncness(asyncness);
2060                 self.print_capture_clause(capture_clause);
2061
2062                 self.print_fn_params_and_ret(decl, true);
2063                 self.space();
2064                 self.print_expr(body);
2065                 self.end(); // need to close a box
2066
2067                 // a box will be closed by print_expr, but we didn't want an overall
2068                 // wrapper so we closed the corresponding opening. so create an
2069                 // empty box to satisfy the close.
2070                 self.ibox(0);
2071             }
2072             ast::ExprKind::Block(ref blk, opt_label) => {
2073                 if let Some(label) = opt_label {
2074                     self.print_ident(label.ident);
2075                     self.word_space(":");
2076                 }
2077                 // containing cbox, will be closed by print-block at }
2078                 self.cbox(INDENT_UNIT);
2079                 // head-box, will be closed by print-block after {
2080                 self.ibox(0);
2081                 self.print_block_with_attrs(blk, attrs);
2082             }
2083             ast::ExprKind::Async(capture_clause, _, ref blk) => {
2084                 self.word_nbsp("async");
2085                 self.print_capture_clause(capture_clause);
2086                 // cbox/ibox in analogy to the `ExprKind::Block` arm above
2087                 self.cbox(INDENT_UNIT);
2088                 self.ibox(0);
2089                 self.print_block_with_attrs(blk, attrs);
2090             }
2091             ast::ExprKind::Await(ref expr) => {
2092                 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
2093                 self.word(".await");
2094             }
2095             ast::ExprKind::Assign(ref lhs, ref rhs, _) => {
2096                 let prec = AssocOp::Assign.precedence() as i8;
2097                 self.print_expr_maybe_paren(lhs, prec + 1);
2098                 self.space();
2099                 self.word_space("=");
2100                 self.print_expr_maybe_paren(rhs, prec);
2101             }
2102             ast::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
2103                 let prec = AssocOp::Assign.precedence() as i8;
2104                 self.print_expr_maybe_paren(lhs, prec + 1);
2105                 self.space();
2106                 self.word(op.node.to_string());
2107                 self.word_space("=");
2108                 self.print_expr_maybe_paren(rhs, prec);
2109             }
2110             ast::ExprKind::Field(ref expr, ident) => {
2111                 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
2112                 self.word(".");
2113                 self.print_ident(ident);
2114             }
2115             ast::ExprKind::Index(ref expr, ref index) => {
2116                 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
2117                 self.word("[");
2118                 self.print_expr(index);
2119                 self.word("]");
2120             }
2121             ast::ExprKind::Range(ref start, ref end, limits) => {
2122                 // Special case for `Range`.  `AssocOp` claims that `Range` has higher precedence
2123                 // than `Assign`, but `x .. x = x` gives a parse error instead of `x .. (x = x)`.
2124                 // Here we use a fake precedence value so that any child with lower precedence than
2125                 // a "normal" binop gets parenthesized.  (`LOr` is the lowest-precedence binop.)
2126                 let fake_prec = AssocOp::LOr.precedence() as i8;
2127                 if let Some(ref e) = *start {
2128                     self.print_expr_maybe_paren(e, fake_prec);
2129                 }
2130                 if limits == ast::RangeLimits::HalfOpen {
2131                     self.word("..");
2132                 } else {
2133                     self.word("..=");
2134                 }
2135                 if let Some(ref e) = *end {
2136                     self.print_expr_maybe_paren(e, fake_prec);
2137                 }
2138             }
2139             ast::ExprKind::Underscore => self.word("_"),
2140             ast::ExprKind::Path(None, ref path) => self.print_path(path, true, 0),
2141             ast::ExprKind::Path(Some(ref qself), ref path) => self.print_qpath(path, qself, true),
2142             ast::ExprKind::Break(opt_label, ref opt_expr) => {
2143                 self.word("break");
2144                 if let Some(label) = opt_label {
2145                     self.space();
2146                     self.print_ident(label.ident);
2147                 }
2148                 if let Some(ref expr) = *opt_expr {
2149                     self.space();
2150                     self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
2151                 }
2152             }
2153             ast::ExprKind::Continue(opt_label) => {
2154                 self.word("continue");
2155                 if let Some(label) = opt_label {
2156                     self.space();
2157                     self.print_ident(label.ident);
2158                 }
2159             }
2160             ast::ExprKind::Ret(ref result) => {
2161                 self.word("return");
2162                 if let Some(ref expr) = *result {
2163                     self.word(" ");
2164                     self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
2165                 }
2166             }
2167             ast::ExprKind::InlineAsm(ref a) => {
2168                 self.word("asm!");
2169                 self.print_inline_asm(a);
2170             }
2171             ast::ExprKind::LlvmInlineAsm(ref a) => {
2172                 self.word("llvm_asm!");
2173                 self.popen();
2174                 self.print_symbol(a.asm, a.asm_str_style);
2175                 self.word_space(":");
2176
2177                 self.commasep(Inconsistent, &a.outputs, |s, out| {
2178                     let constraint = out.constraint.as_str();
2179                     let mut ch = constraint.chars();
2180                     match ch.next() {
2181                         Some('=') if out.is_rw => {
2182                             s.print_string(&format!("+{}", ch.as_str()), ast::StrStyle::Cooked)
2183                         }
2184                         _ => s.print_string(&constraint, ast::StrStyle::Cooked),
2185                     }
2186                     s.popen();
2187                     s.print_expr(&out.expr);
2188                     s.pclose();
2189                 });
2190                 self.space();
2191                 self.word_space(":");
2192
2193                 self.commasep(Inconsistent, &a.inputs, |s, &(co, ref o)| {
2194                     s.print_symbol(co, ast::StrStyle::Cooked);
2195                     s.popen();
2196                     s.print_expr(o);
2197                     s.pclose();
2198                 });
2199                 self.space();
2200                 self.word_space(":");
2201
2202                 self.commasep(Inconsistent, &a.clobbers, |s, &co| {
2203                     s.print_symbol(co, ast::StrStyle::Cooked);
2204                 });
2205
2206                 let mut options = vec![];
2207                 if a.volatile {
2208                     options.push("volatile");
2209                 }
2210                 if a.alignstack {
2211                     options.push("alignstack");
2212                 }
2213                 if a.dialect == ast::LlvmAsmDialect::Intel {
2214                     options.push("intel");
2215                 }
2216
2217                 if !options.is_empty() {
2218                     self.space();
2219                     self.word_space(":");
2220                     self.commasep(Inconsistent, &options, |s, &co| {
2221                         s.print_string(co, ast::StrStyle::Cooked);
2222                     });
2223                 }
2224
2225                 self.pclose();
2226             }
2227             ast::ExprKind::MacCall(ref m) => self.print_mac(m),
2228             ast::ExprKind::Paren(ref e) => {
2229                 self.popen();
2230                 self.print_expr(e);
2231                 self.pclose();
2232             }
2233             ast::ExprKind::Yield(ref e) => {
2234                 self.word("yield");
2235
2236                 if let Some(ref expr) = *e {
2237                     self.space();
2238                     self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
2239                 }
2240             }
2241             ast::ExprKind::Try(ref e) => {
2242                 self.print_expr_maybe_paren(e, parser::PREC_POSTFIX);
2243                 self.word("?")
2244             }
2245             ast::ExprKind::TryBlock(ref blk) => {
2246                 self.head("try");
2247                 self.print_block_with_attrs(blk, attrs)
2248             }
2249             ast::ExprKind::Err => {
2250                 self.popen();
2251                 self.word("/*ERROR*/");
2252                 self.pclose()
2253             }
2254         }
2255         self.ann.post(self, AnnNode::Expr(expr));
2256         self.end();
2257     }
2258
2259     fn print_inline_asm(&mut self, asm: &ast::InlineAsm) {
2260         enum AsmArg<'a> {
2261             Template(String),
2262             Operand(&'a InlineAsmOperand),
2263             ClobberAbi(Symbol),
2264             Options(InlineAsmOptions),
2265         }
2266
2267         let mut args = vec![AsmArg::Template(InlineAsmTemplatePiece::to_string(&asm.template))];
2268         args.extend(asm.operands.iter().map(|(o, _)| AsmArg::Operand(o)));
2269         for (abi, _) in &asm.clobber_abis {
2270             args.push(AsmArg::ClobberAbi(*abi));
2271         }
2272         if !asm.options.is_empty() {
2273             args.push(AsmArg::Options(asm.options));
2274         }
2275
2276         self.popen();
2277         self.commasep(Consistent, &args, |s, arg| match arg {
2278             AsmArg::Template(template) => s.print_string(&template, ast::StrStyle::Cooked),
2279             AsmArg::Operand(op) => {
2280                 let print_reg_or_class = |s: &mut Self, r: &InlineAsmRegOrRegClass| match r {
2281                     InlineAsmRegOrRegClass::Reg(r) => s.print_symbol(*r, ast::StrStyle::Cooked),
2282                     InlineAsmRegOrRegClass::RegClass(r) => s.word(r.to_string()),
2283                 };
2284                 match op {
2285                     InlineAsmOperand::In { reg, expr } => {
2286                         s.word("in");
2287                         s.popen();
2288                         print_reg_or_class(s, reg);
2289                         s.pclose();
2290                         s.space();
2291                         s.print_expr(expr);
2292                     }
2293                     InlineAsmOperand::Out { reg, late, expr } => {
2294                         s.word(if *late { "lateout" } else { "out" });
2295                         s.popen();
2296                         print_reg_or_class(s, reg);
2297                         s.pclose();
2298                         s.space();
2299                         match expr {
2300                             Some(expr) => s.print_expr(expr),
2301                             None => s.word("_"),
2302                         }
2303                     }
2304                     InlineAsmOperand::InOut { reg, late, expr } => {
2305                         s.word(if *late { "inlateout" } else { "inout" });
2306                         s.popen();
2307                         print_reg_or_class(s, reg);
2308                         s.pclose();
2309                         s.space();
2310                         s.print_expr(expr);
2311                     }
2312                     InlineAsmOperand::SplitInOut { reg, late, in_expr, out_expr } => {
2313                         s.word(if *late { "inlateout" } else { "inout" });
2314                         s.popen();
2315                         print_reg_or_class(s, reg);
2316                         s.pclose();
2317                         s.space();
2318                         s.print_expr(in_expr);
2319                         s.space();
2320                         s.word_space("=>");
2321                         match out_expr {
2322                             Some(out_expr) => s.print_expr(out_expr),
2323                             None => s.word("_"),
2324                         }
2325                     }
2326                     InlineAsmOperand::Const { anon_const } => {
2327                         s.word("const");
2328                         s.space();
2329                         s.print_expr(&anon_const.value);
2330                     }
2331                     InlineAsmOperand::Sym { expr } => {
2332                         s.word("sym");
2333                         s.space();
2334                         s.print_expr(expr);
2335                     }
2336                 }
2337             }
2338             AsmArg::ClobberAbi(abi) => {
2339                 s.word("clobber_abi");
2340                 s.popen();
2341                 s.print_symbol(*abi, ast::StrStyle::Cooked);
2342                 s.pclose();
2343             }
2344             AsmArg::Options(opts) => {
2345                 s.word("options");
2346                 s.popen();
2347                 let mut options = vec![];
2348                 if opts.contains(InlineAsmOptions::PURE) {
2349                     options.push("pure");
2350                 }
2351                 if opts.contains(InlineAsmOptions::NOMEM) {
2352                     options.push("nomem");
2353                 }
2354                 if opts.contains(InlineAsmOptions::READONLY) {
2355                     options.push("readonly");
2356                 }
2357                 if opts.contains(InlineAsmOptions::PRESERVES_FLAGS) {
2358                     options.push("preserves_flags");
2359                 }
2360                 if opts.contains(InlineAsmOptions::NORETURN) {
2361                     options.push("noreturn");
2362                 }
2363                 if opts.contains(InlineAsmOptions::NOSTACK) {
2364                     options.push("nostack");
2365                 }
2366                 if opts.contains(InlineAsmOptions::ATT_SYNTAX) {
2367                     options.push("att_syntax");
2368                 }
2369                 if opts.contains(InlineAsmOptions::RAW) {
2370                     options.push("raw");
2371                 }
2372                 if opts.contains(InlineAsmOptions::MAY_UNWIND) {
2373                     options.push("may_unwind");
2374                 }
2375                 s.commasep(Inconsistent, &options, |s, &opt| {
2376                     s.word(opt);
2377                 });
2378                 s.pclose();
2379             }
2380         });
2381         self.pclose();
2382     }
2383
2384     crate fn print_local_decl(&mut self, loc: &ast::Local) {
2385         self.print_pat(&loc.pat);
2386         if let Some(ref ty) = loc.ty {
2387             self.word_space(":");
2388             self.print_type(ty);
2389         }
2390     }
2391
2392     crate fn print_name(&mut self, name: Symbol) {
2393         self.word(name.to_string());
2394         self.ann.post(self, AnnNode::Name(&name))
2395     }
2396
2397     fn print_qpath(&mut self, path: &ast::Path, qself: &ast::QSelf, colons_before_params: bool) {
2398         self.word("<");
2399         self.print_type(&qself.ty);
2400         if qself.position > 0 {
2401             self.space();
2402             self.word_space("as");
2403             let depth = path.segments.len() - qself.position;
2404             self.print_path(path, false, depth);
2405         }
2406         self.word(">");
2407         for item_segment in &path.segments[qself.position..] {
2408             self.word("::");
2409             self.print_ident(item_segment.ident);
2410             if let Some(ref args) = item_segment.args {
2411                 self.print_generic_args(args, colons_before_params)
2412             }
2413         }
2414     }
2415
2416     crate fn print_pat(&mut self, pat: &ast::Pat) {
2417         self.maybe_print_comment(pat.span.lo());
2418         self.ann.pre(self, AnnNode::Pat(pat));
2419         /* Pat isn't normalized, but the beauty of it
2420         is that it doesn't matter */
2421         match pat.kind {
2422             PatKind::Wild => self.word("_"),
2423             PatKind::Ident(binding_mode, ident, ref sub) => {
2424                 match binding_mode {
2425                     ast::BindingMode::ByRef(mutbl) => {
2426                         self.word_nbsp("ref");
2427                         self.print_mutability(mutbl, false);
2428                     }
2429                     ast::BindingMode::ByValue(ast::Mutability::Not) => {}
2430                     ast::BindingMode::ByValue(ast::Mutability::Mut) => {
2431                         self.word_nbsp("mut");
2432                     }
2433                 }
2434                 self.print_ident(ident);
2435                 if let Some(ref p) = *sub {
2436                     self.space();
2437                     self.word_space("@");
2438                     self.print_pat(p);
2439                 }
2440             }
2441             PatKind::TupleStruct(ref qself, ref path, ref elts) => {
2442                 if let Some(qself) = qself {
2443                     self.print_qpath(path, qself, true);
2444                 } else {
2445                     self.print_path(path, true, 0);
2446                 }
2447                 self.popen();
2448                 self.commasep(Inconsistent, &elts, |s, p| s.print_pat(p));
2449                 self.pclose();
2450             }
2451             PatKind::Or(ref pats) => {
2452                 self.strsep("|", true, Inconsistent, &pats, |s, p| s.print_pat(p));
2453             }
2454             PatKind::Path(None, ref path) => {
2455                 self.print_path(path, true, 0);
2456             }
2457             PatKind::Path(Some(ref qself), ref path) => {
2458                 self.print_qpath(path, qself, false);
2459             }
2460             PatKind::Struct(ref qself, ref path, ref fields, etc) => {
2461                 if let Some(qself) = qself {
2462                     self.print_qpath(path, qself, true);
2463                 } else {
2464                     self.print_path(path, true, 0);
2465                 }
2466                 self.nbsp();
2467                 self.word("{");
2468                 let empty = fields.is_empty() && !etc;
2469                 if !empty {
2470                     self.space();
2471                 }
2472                 self.commasep_cmnt(
2473                     Consistent,
2474                     &fields,
2475                     |s, f| {
2476                         s.cbox(INDENT_UNIT);
2477                         if !f.is_shorthand {
2478                             s.print_ident(f.ident);
2479                             s.word_nbsp(":");
2480                         }
2481                         s.print_pat(&f.pat);
2482                         s.end();
2483                     },
2484                     |f| f.pat.span,
2485                 );
2486                 if etc {
2487                     if !fields.is_empty() {
2488                         self.word_space(",");
2489                     }
2490                     self.word("..");
2491                 }
2492                 if !empty {
2493                     self.space();
2494                 }
2495                 self.word("}");
2496             }
2497             PatKind::Tuple(ref elts) => {
2498                 self.popen();
2499                 self.commasep(Inconsistent, &elts, |s, p| s.print_pat(p));
2500                 if elts.len() == 1 {
2501                     self.word(",");
2502                 }
2503                 self.pclose();
2504             }
2505             PatKind::Box(ref inner) => {
2506                 self.word("box ");
2507                 self.print_pat(inner);
2508             }
2509             PatKind::Ref(ref inner, mutbl) => {
2510                 self.word("&");
2511                 if mutbl == ast::Mutability::Mut {
2512                     self.word("mut ");
2513                 }
2514                 if let PatKind::Ident(ast::BindingMode::ByValue(ast::Mutability::Mut), ..) =
2515                     inner.kind
2516                 {
2517                     self.popen();
2518                     self.print_pat(inner);
2519                     self.pclose();
2520                 } else {
2521                     self.print_pat(inner);
2522                 }
2523             }
2524             PatKind::Lit(ref e) => self.print_expr(&**e),
2525             PatKind::Range(ref begin, ref end, Spanned { node: ref end_kind, .. }) => {
2526                 if let Some(e) = begin {
2527                     self.print_expr(e);
2528                 }
2529                 match *end_kind {
2530                     RangeEnd::Included(RangeSyntax::DotDotDot) => self.word("..."),
2531                     RangeEnd::Included(RangeSyntax::DotDotEq) => self.word("..="),
2532                     RangeEnd::Excluded => self.word(".."),
2533                 }
2534                 if let Some(e) = end {
2535                     self.print_expr(e);
2536                 }
2537             }
2538             PatKind::Slice(ref elts) => {
2539                 self.word("[");
2540                 self.commasep(Inconsistent, &elts, |s, p| s.print_pat(p));
2541                 self.word("]");
2542             }
2543             PatKind::Rest => self.word(".."),
2544             PatKind::Paren(ref inner) => {
2545                 self.popen();
2546                 self.print_pat(inner);
2547                 self.pclose();
2548             }
2549             PatKind::MacCall(ref m) => self.print_mac(m),
2550         }
2551         self.ann.post(self, AnnNode::Pat(pat))
2552     }
2553
2554     fn print_arm(&mut self, arm: &ast::Arm) {
2555         // Note, I have no idea why this check is necessary, but here it is.
2556         if arm.attrs.is_empty() {
2557             self.space();
2558         }
2559         self.cbox(INDENT_UNIT);
2560         self.ibox(0);
2561         self.maybe_print_comment(arm.pat.span.lo());
2562         self.print_outer_attributes(&arm.attrs);
2563         self.print_pat(&arm.pat);
2564         self.space();
2565         if let Some(ref e) = arm.guard {
2566             self.word_space("if");
2567             self.print_expr(e);
2568             self.space();
2569         }
2570         self.word_space("=>");
2571
2572         match arm.body.kind {
2573             ast::ExprKind::Block(ref blk, opt_label) => {
2574                 if let Some(label) = opt_label {
2575                     self.print_ident(label.ident);
2576                     self.word_space(":");
2577                 }
2578
2579                 // The block will close the pattern's ibox.
2580                 self.print_block_unclosed_indent(blk);
2581
2582                 // If it is a user-provided unsafe block, print a comma after it.
2583                 if let BlockCheckMode::Unsafe(ast::UserProvided) = blk.rules {
2584                     self.word(",");
2585                 }
2586             }
2587             _ => {
2588                 self.end(); // Close the ibox for the pattern.
2589                 self.print_expr(&arm.body);
2590                 self.word(",");
2591             }
2592         }
2593         self.end(); // Close enclosing cbox.
2594     }
2595
2596     fn print_explicit_self(&mut self, explicit_self: &ast::ExplicitSelf) {
2597         match explicit_self.node {
2598             SelfKind::Value(m) => {
2599                 self.print_mutability(m, false);
2600                 self.word("self")
2601             }
2602             SelfKind::Region(ref lt, m) => {
2603                 self.word("&");
2604                 self.print_opt_lifetime(lt);
2605                 self.print_mutability(m, false);
2606                 self.word("self")
2607             }
2608             SelfKind::Explicit(ref typ, m) => {
2609                 self.print_mutability(m, false);
2610                 self.word("self");
2611                 self.word_space(":");
2612                 self.print_type(typ)
2613             }
2614         }
2615     }
2616
2617     fn print_fn_full(
2618         &mut self,
2619         sig: &ast::FnSig,
2620         name: Ident,
2621         generics: &ast::Generics,
2622         vis: &ast::Visibility,
2623         defaultness: ast::Defaultness,
2624         body: Option<&ast::Block>,
2625         attrs: &[ast::Attribute],
2626     ) {
2627         if body.is_some() {
2628             self.head("");
2629         }
2630         self.print_visibility(vis);
2631         self.print_defaultness(defaultness);
2632         self.print_fn(&sig.decl, sig.header, Some(name), generics);
2633         if let Some(body) = body {
2634             self.nbsp();
2635             self.print_block_with_attrs(body, attrs);
2636         } else {
2637             self.word(";");
2638         }
2639     }
2640
2641     crate fn print_fn(
2642         &mut self,
2643         decl: &ast::FnDecl,
2644         header: ast::FnHeader,
2645         name: Option<Ident>,
2646         generics: &ast::Generics,
2647     ) {
2648         self.print_fn_header_info(header);
2649         if let Some(name) = name {
2650             self.nbsp();
2651             self.print_ident(name);
2652         }
2653         self.print_generic_params(&generics.params);
2654         self.print_fn_params_and_ret(decl, false);
2655         self.print_where_clause(&generics.where_clause)
2656     }
2657
2658     crate fn print_fn_params_and_ret(&mut self, decl: &ast::FnDecl, is_closure: bool) {
2659         let (open, close) = if is_closure { ("|", "|") } else { ("(", ")") };
2660         self.word(open);
2661         self.commasep(Inconsistent, &decl.inputs, |s, param| s.print_param(param, is_closure));
2662         self.word(close);
2663         self.print_fn_ret_ty(&decl.output)
2664     }
2665
2666     crate fn print_movability(&mut self, movability: ast::Movability) {
2667         match movability {
2668             ast::Movability::Static => self.word_space("static"),
2669             ast::Movability::Movable => {}
2670         }
2671     }
2672
2673     crate fn print_asyncness(&mut self, asyncness: ast::Async) {
2674         if asyncness.is_async() {
2675             self.word_nbsp("async");
2676         }
2677     }
2678
2679     crate fn print_capture_clause(&mut self, capture_clause: ast::CaptureBy) {
2680         match capture_clause {
2681             ast::CaptureBy::Value => self.word_space("move"),
2682             ast::CaptureBy::Ref => {}
2683         }
2684     }
2685
2686     pub fn print_type_bounds(&mut self, prefix: &'static str, bounds: &[ast::GenericBound]) {
2687         if !bounds.is_empty() {
2688             self.word(prefix);
2689             let mut first = true;
2690             for bound in bounds {
2691                 if !(first && prefix.is_empty()) {
2692                     self.nbsp();
2693                 }
2694                 if first {
2695                     first = false;
2696                 } else {
2697                     self.word_space("+");
2698                 }
2699
2700                 match bound {
2701                     GenericBound::Trait(tref, modifier) => {
2702                         if modifier == &TraitBoundModifier::Maybe {
2703                             self.word("?");
2704                         }
2705                         self.print_poly_trait_ref(tref);
2706                     }
2707                     GenericBound::Outlives(lt) => self.print_lifetime(*lt),
2708                 }
2709             }
2710         }
2711     }
2712
2713     crate fn print_lifetime(&mut self, lifetime: ast::Lifetime) {
2714         self.print_name(lifetime.ident.name)
2715     }
2716
2717     crate fn print_lifetime_bounds(
2718         &mut self,
2719         lifetime: ast::Lifetime,
2720         bounds: &ast::GenericBounds,
2721     ) {
2722         self.print_lifetime(lifetime);
2723         if !bounds.is_empty() {
2724             self.word(": ");
2725             for (i, bound) in bounds.iter().enumerate() {
2726                 if i != 0 {
2727                     self.word(" + ");
2728                 }
2729                 match bound {
2730                     ast::GenericBound::Outlives(lt) => self.print_lifetime(*lt),
2731                     _ => panic!(),
2732                 }
2733             }
2734         }
2735     }
2736
2737     crate fn print_generic_params(&mut self, generic_params: &[ast::GenericParam]) {
2738         if generic_params.is_empty() {
2739             return;
2740         }
2741
2742         self.word("<");
2743
2744         self.commasep(Inconsistent, &generic_params, |s, param| {
2745             s.print_outer_attributes_inline(&param.attrs);
2746
2747             match param.kind {
2748                 ast::GenericParamKind::Lifetime => {
2749                     let lt = ast::Lifetime { id: param.id, ident: param.ident };
2750                     s.print_lifetime_bounds(lt, &param.bounds)
2751                 }
2752                 ast::GenericParamKind::Type { ref default } => {
2753                     s.print_ident(param.ident);
2754                     s.print_type_bounds(":", &param.bounds);
2755                     if let Some(ref default) = default {
2756                         s.space();
2757                         s.word_space("=");
2758                         s.print_type(default)
2759                     }
2760                 }
2761                 ast::GenericParamKind::Const { ref ty, kw_span: _, ref default } => {
2762                     s.word_space("const");
2763                     s.print_ident(param.ident);
2764                     s.space();
2765                     s.word_space(":");
2766                     s.print_type(ty);
2767                     s.print_type_bounds(":", &param.bounds);
2768                     if let Some(ref default) = default {
2769                         s.space();
2770                         s.word_space("=");
2771                         s.print_expr(&default.value);
2772                     }
2773                 }
2774             }
2775         });
2776
2777         self.word(">");
2778     }
2779
2780     crate fn print_where_clause(&mut self, where_clause: &ast::WhereClause) {
2781         if where_clause.predicates.is_empty() && !where_clause.has_where_token {
2782             return;
2783         }
2784
2785         self.space();
2786         self.word_space("where");
2787
2788         for (i, predicate) in where_clause.predicates.iter().enumerate() {
2789             if i != 0 {
2790                 self.word_space(",");
2791             }
2792
2793             self.print_where_predicate(predicate);
2794         }
2795     }
2796
2797     pub fn print_where_predicate(&mut self, predicate: &ast::WherePredicate) {
2798         match predicate {
2799             ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
2800                 bound_generic_params,
2801                 bounded_ty,
2802                 bounds,
2803                 ..
2804             }) => {
2805                 self.print_formal_generic_params(bound_generic_params);
2806                 self.print_type(bounded_ty);
2807                 self.print_type_bounds(":", bounds);
2808             }
2809             ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate {
2810                 lifetime,
2811                 bounds,
2812                 ..
2813             }) => {
2814                 self.print_lifetime_bounds(*lifetime, bounds);
2815             }
2816             ast::WherePredicate::EqPredicate(ast::WhereEqPredicate { lhs_ty, rhs_ty, .. }) => {
2817                 self.print_type(lhs_ty);
2818                 self.space();
2819                 self.word_space("=");
2820                 self.print_type(rhs_ty);
2821             }
2822         }
2823     }
2824
2825     crate fn print_use_tree(&mut self, tree: &ast::UseTree) {
2826         match tree.kind {
2827             ast::UseTreeKind::Simple(rename, ..) => {
2828                 self.print_path(&tree.prefix, false, 0);
2829                 if let Some(rename) = rename {
2830                     self.space();
2831                     self.word_space("as");
2832                     self.print_ident(rename);
2833                 }
2834             }
2835             ast::UseTreeKind::Glob => {
2836                 if !tree.prefix.segments.is_empty() {
2837                     self.print_path(&tree.prefix, false, 0);
2838                     self.word("::");
2839                 }
2840                 self.word("*");
2841             }
2842             ast::UseTreeKind::Nested(ref items) => {
2843                 if tree.prefix.segments.is_empty() {
2844                     self.word("{");
2845                 } else {
2846                     self.print_path(&tree.prefix, false, 0);
2847                     self.word("::{");
2848                 }
2849                 self.commasep(Inconsistent, &items, |this, &(ref tree, _)| {
2850                     this.print_use_tree(tree)
2851                 });
2852                 self.word("}");
2853             }
2854         }
2855     }
2856
2857     pub fn print_mutability(&mut self, mutbl: ast::Mutability, print_const: bool) {
2858         match mutbl {
2859             ast::Mutability::Mut => self.word_nbsp("mut"),
2860             ast::Mutability::Not => {
2861                 if print_const {
2862                     self.word_nbsp("const");
2863                 }
2864             }
2865         }
2866     }
2867
2868     crate fn print_mt(&mut self, mt: &ast::MutTy, print_const: bool) {
2869         self.print_mutability(mt.mutbl, print_const);
2870         self.print_type(&mt.ty)
2871     }
2872
2873     crate fn print_param(&mut self, input: &ast::Param, is_closure: bool) {
2874         self.ibox(INDENT_UNIT);
2875
2876         self.print_outer_attributes_inline(&input.attrs);
2877
2878         match input.ty.kind {
2879             ast::TyKind::Infer if is_closure => self.print_pat(&input.pat),
2880             _ => {
2881                 if let Some(eself) = input.to_self() {
2882                     self.print_explicit_self(&eself);
2883                 } else {
2884                     let invalid = if let PatKind::Ident(_, ident, _) = input.pat.kind {
2885                         ident.name == kw::Empty
2886                     } else {
2887                         false
2888                     };
2889                     if !invalid {
2890                         self.print_pat(&input.pat);
2891                         self.word(":");
2892                         self.space();
2893                     }
2894                     self.print_type(&input.ty);
2895                 }
2896             }
2897         }
2898         self.end();
2899     }
2900
2901     crate fn print_fn_ret_ty(&mut self, fn_ret_ty: &ast::FnRetTy) {
2902         if let ast::FnRetTy::Ty(ty) = fn_ret_ty {
2903             self.space_if_not_bol();
2904             self.ibox(INDENT_UNIT);
2905             self.word_space("->");
2906             self.print_type(ty);
2907             self.end();
2908             self.maybe_print_comment(ty.span.lo());
2909         }
2910     }
2911
2912     crate fn print_ty_fn(
2913         &mut self,
2914         ext: ast::Extern,
2915         unsafety: ast::Unsafe,
2916         decl: &ast::FnDecl,
2917         name: Option<Ident>,
2918         generic_params: &[ast::GenericParam],
2919     ) {
2920         self.ibox(INDENT_UNIT);
2921         self.print_formal_generic_params(generic_params);
2922         let generics = ast::Generics {
2923             params: Vec::new(),
2924             where_clause: ast::WhereClause {
2925                 has_where_token: false,
2926                 predicates: Vec::new(),
2927                 span: rustc_span::DUMMY_SP,
2928             },
2929             span: rustc_span::DUMMY_SP,
2930         };
2931         let header = ast::FnHeader { unsafety, ext, ..ast::FnHeader::default() };
2932         self.print_fn(decl, header, name, &generics);
2933         self.end();
2934     }
2935
2936     crate fn print_fn_header_info(&mut self, header: ast::FnHeader) {
2937         self.print_constness(header.constness);
2938         self.print_asyncness(header.asyncness);
2939         self.print_unsafety(header.unsafety);
2940
2941         match header.ext {
2942             ast::Extern::None => {}
2943             ast::Extern::Implicit => {
2944                 self.word_nbsp("extern");
2945             }
2946             ast::Extern::Explicit(abi) => {
2947                 self.word_nbsp("extern");
2948                 self.print_literal(&abi.as_lit());
2949                 self.nbsp();
2950             }
2951         }
2952
2953         self.word("fn")
2954     }
2955
2956     crate fn print_unsafety(&mut self, s: ast::Unsafe) {
2957         match s {
2958             ast::Unsafe::No => {}
2959             ast::Unsafe::Yes(_) => self.word_nbsp("unsafe"),
2960         }
2961     }
2962
2963     crate fn print_constness(&mut self, s: ast::Const) {
2964         match s {
2965             ast::Const::No => {}
2966             ast::Const::Yes(_) => self.word_nbsp("const"),
2967         }
2968     }
2969
2970     crate fn print_is_auto(&mut self, s: ast::IsAuto) {
2971         match s {
2972             ast::IsAuto::Yes => self.word_nbsp("auto"),
2973             ast::IsAuto::No => {}
2974         }
2975     }
2976 }