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