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