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