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