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