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