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