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