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