]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_hir_pretty/src/lib.rs
Rollup merge of #100669 - nnethercote:attribute-cleanups, r=spastorino
[rust.git] / compiler / rustc_hir_pretty / src / lib.rs
1 #![recursion_limit = "256"]
2
3 use rustc_ast as ast;
4 use rustc_ast::util::parser::{self, AssocOp, Fixity};
5 use rustc_ast_pretty::pp::Breaks::{Consistent, Inconsistent};
6 use rustc_ast_pretty::pp::{self, Breaks};
7 use rustc_ast_pretty::pprust::{Comments, PrintState};
8 use rustc_hir as hir;
9 use rustc_hir::LifetimeParamKind;
10 use rustc_hir::{GenericArg, GenericParam, GenericParamKind, Node, Term};
11 use rustc_hir::{GenericBound, PatKind, RangeEnd, TraitBoundModifier};
12 use rustc_span::source_map::SourceMap;
13 use rustc_span::symbol::{kw, Ident, IdentPrinter, Symbol};
14 use rustc_span::{self, FileName};
15 use rustc_target::spec::abi::Abi;
16
17 use std::cell::Cell;
18 use std::vec;
19
20 pub fn id_to_string(map: &dyn rustc_hir::intravisit::Map<'_>, hir_id: hir::HirId) -> String {
21     to_string(&map, |s| s.print_node(map.find(hir_id).unwrap()))
22 }
23
24 pub enum AnnNode<'a> {
25     Name(&'a Symbol),
26     Block(&'a hir::Block<'a>),
27     Item(&'a hir::Item<'a>),
28     SubItem(hir::HirId),
29     Expr(&'a hir::Expr<'a>),
30     Pat(&'a hir::Pat<'a>),
31     Arm(&'a hir::Arm<'a>),
32 }
33
34 pub enum Nested {
35     Item(hir::ItemId),
36     TraitItem(hir::TraitItemId),
37     ImplItem(hir::ImplItemId),
38     ForeignItem(hir::ForeignItemId),
39     Body(hir::BodyId),
40     BodyParamPat(hir::BodyId, usize),
41 }
42
43 pub trait PpAnn {
44     fn nested(&self, _state: &mut State<'_>, _nested: Nested) {}
45     fn pre(&self, _state: &mut State<'_>, _node: AnnNode<'_>) {}
46     fn post(&self, _state: &mut State<'_>, _node: AnnNode<'_>) {}
47 }
48
49 pub struct NoAnn;
50 impl PpAnn for NoAnn {}
51 pub const NO_ANN: &dyn PpAnn = &NoAnn;
52
53 /// Identical to the `PpAnn` implementation for `hir::Crate`,
54 /// except it avoids creating a dependency on the whole crate.
55 impl PpAnn for &dyn rustc_hir::intravisit::Map<'_> {
56     fn nested(&self, state: &mut State<'_>, nested: Nested) {
57         match nested {
58             Nested::Item(id) => state.print_item(self.item(id)),
59             Nested::TraitItem(id) => state.print_trait_item(self.trait_item(id)),
60             Nested::ImplItem(id) => state.print_impl_item(self.impl_item(id)),
61             Nested::ForeignItem(id) => state.print_foreign_item(self.foreign_item(id)),
62             Nested::Body(id) => state.print_expr(&self.body(id).value),
63             Nested::BodyParamPat(id, i) => state.print_pat(self.body(id).params[i].pat),
64         }
65     }
66 }
67
68 pub struct State<'a> {
69     pub s: pp::Printer,
70     comments: Option<Comments<'a>>,
71     attrs: &'a dyn Fn(hir::HirId) -> &'a [ast::Attribute],
72     ann: &'a (dyn PpAnn + 'a),
73 }
74
75 impl<'a> State<'a> {
76     pub fn print_node(&mut self, node: Node<'_>) {
77         match node {
78             Node::Param(a) => self.print_param(a),
79             Node::Item(a) => self.print_item(a),
80             Node::ForeignItem(a) => self.print_foreign_item(a),
81             Node::TraitItem(a) => self.print_trait_item(a),
82             Node::ImplItem(a) => self.print_impl_item(a),
83             Node::Variant(a) => self.print_variant(a),
84             Node::AnonConst(a) => self.print_anon_const(a),
85             Node::Expr(a) => self.print_expr(a),
86             Node::ExprField(a) => self.print_expr_field(&a),
87             Node::Stmt(a) => self.print_stmt(a),
88             Node::PathSegment(a) => self.print_path_segment(a),
89             Node::Ty(a) => self.print_type(a),
90             Node::TypeBinding(a) => self.print_type_binding(a),
91             Node::TraitRef(a) => self.print_trait_ref(a),
92             Node::Pat(a) => self.print_pat(a),
93             Node::PatField(a) => self.print_patfield(&a),
94             Node::Arm(a) => self.print_arm(a),
95             Node::Infer(_) => self.word("_"),
96             Node::Block(a) => {
97                 // Containing cbox, will be closed by print-block at `}`.
98                 self.cbox(INDENT_UNIT);
99                 // Head-ibox, will be closed by print-block after `{`.
100                 self.ibox(0);
101                 self.print_block(a);
102             }
103             Node::Lifetime(a) => self.print_lifetime(a),
104             Node::GenericParam(_) => panic!("cannot print Node::GenericParam"),
105             Node::Field(_) => panic!("cannot print Node::Field"),
106             // These cases do not carry enough information in the
107             // `hir_map` to reconstruct their full structure for pretty
108             // printing.
109             Node::Ctor(..) => panic!("cannot print isolated Ctor"),
110             Node::Local(a) => self.print_local_decl(a),
111             Node::Crate(..) => panic!("cannot print Crate"),
112         }
113     }
114 }
115
116 impl std::ops::Deref for State<'_> {
117     type Target = pp::Printer;
118     fn deref(&self) -> &Self::Target {
119         &self.s
120     }
121 }
122
123 impl std::ops::DerefMut for State<'_> {
124     fn deref_mut(&mut self) -> &mut Self::Target {
125         &mut self.s
126     }
127 }
128
129 impl<'a> PrintState<'a> for State<'a> {
130     fn comments(&mut self) -> &mut Option<Comments<'a>> {
131         &mut self.comments
132     }
133
134     fn print_ident(&mut self, ident: Ident) {
135         self.word(IdentPrinter::for_ast_ident(ident, ident.is_raw_guess()).to_string());
136         self.ann.post(self, AnnNode::Name(&ident.name))
137     }
138
139     fn print_generic_args(&mut self, _: &ast::GenericArgs, _colons_before_params: bool) {
140         panic!("AST generic args printed by HIR pretty-printer");
141     }
142 }
143
144 pub const INDENT_UNIT: isize = 4;
145
146 /// Requires you to pass an input filename and reader so that
147 /// it can scan the input text for comments to copy forward.
148 pub fn print_crate<'a>(
149     sm: &'a SourceMap,
150     krate: &hir::Mod<'_>,
151     filename: FileName,
152     input: String,
153     attrs: &'a dyn Fn(hir::HirId) -> &'a [ast::Attribute],
154     ann: &'a dyn PpAnn,
155 ) -> String {
156     let mut s = State::new_from_input(sm, filename, input, attrs, ann);
157
158     // When printing the AST, we sometimes need to inject `#[no_std]` here.
159     // Since you can't compile the HIR, it's not necessary.
160
161     s.print_mod(krate, (*attrs)(hir::CRATE_HIR_ID));
162     s.print_remaining_comments();
163     s.s.eof()
164 }
165
166 impl<'a> State<'a> {
167     pub fn new_from_input(
168         sm: &'a SourceMap,
169         filename: FileName,
170         input: String,
171         attrs: &'a dyn Fn(hir::HirId) -> &'a [ast::Attribute],
172         ann: &'a dyn PpAnn,
173     ) -> State<'a> {
174         State {
175             s: pp::Printer::new(),
176             comments: Some(Comments::new(sm, filename, input)),
177             attrs,
178             ann,
179         }
180     }
181
182     fn attrs(&self, id: hir::HirId) -> &'a [ast::Attribute] {
183         (self.attrs)(id)
184     }
185 }
186
187 pub fn to_string<F>(ann: &dyn PpAnn, f: F) -> String
188 where
189     F: FnOnce(&mut State<'_>),
190 {
191     let mut printer = State { s: pp::Printer::new(), comments: None, attrs: &|_| &[], ann };
192     f(&mut printer);
193     printer.s.eof()
194 }
195
196 pub fn generic_params_to_string(generic_params: &[GenericParam<'_>]) -> String {
197     to_string(NO_ANN, |s| s.print_generic_params(generic_params))
198 }
199
200 pub fn bounds_to_string<'b>(bounds: impl IntoIterator<Item = &'b hir::GenericBound<'b>>) -> String {
201     to_string(NO_ANN, |s| s.print_bounds("", bounds))
202 }
203
204 pub fn ty_to_string(ty: &hir::Ty<'_>) -> String {
205     to_string(NO_ANN, |s| s.print_type(ty))
206 }
207
208 pub fn path_segment_to_string(segment: &hir::PathSegment<'_>) -> String {
209     to_string(NO_ANN, |s| s.print_path_segment(segment))
210 }
211
212 pub fn path_to_string(segment: &hir::Path<'_>) -> String {
213     to_string(NO_ANN, |s| s.print_path(segment, false))
214 }
215
216 pub fn qpath_to_string(segment: &hir::QPath<'_>) -> String {
217     to_string(NO_ANN, |s| s.print_qpath(segment, false))
218 }
219
220 pub fn fn_to_string(
221     decl: &hir::FnDecl<'_>,
222     header: hir::FnHeader,
223     name: Option<Symbol>,
224     generics: &hir::Generics<'_>,
225     arg_names: &[Ident],
226     body_id: Option<hir::BodyId>,
227 ) -> String {
228     to_string(NO_ANN, |s| s.print_fn(decl, header, name, generics, arg_names, body_id))
229 }
230
231 pub fn enum_def_to_string(
232     enum_definition: &hir::EnumDef<'_>,
233     generics: &hir::Generics<'_>,
234     name: Symbol,
235     span: rustc_span::Span,
236 ) -> String {
237     to_string(NO_ANN, |s| s.print_enum_def(enum_definition, generics, name, span))
238 }
239
240 impl<'a> State<'a> {
241     pub fn bclose_maybe_open(&mut self, span: rustc_span::Span, close_box: bool) {
242         self.maybe_print_comment(span.hi());
243         self.break_offset_if_not_bol(1, -(INDENT_UNIT as isize));
244         self.word("}");
245         if close_box {
246             self.end(); // close the outer-box
247         }
248     }
249
250     pub fn bclose(&mut self, span: rustc_span::Span) {
251         self.bclose_maybe_open(span, true)
252     }
253
254     pub fn commasep_cmnt<T, F, G>(&mut self, b: Breaks, elts: &[T], mut op: F, mut get_span: G)
255     where
256         F: FnMut(&mut State<'_>, &T),
257         G: FnMut(&T) -> rustc_span::Span,
258     {
259         self.rbox(0, b);
260         let len = elts.len();
261         let mut i = 0;
262         for elt in elts {
263             self.maybe_print_comment(get_span(elt).hi());
264             op(self, elt);
265             i += 1;
266             if i < len {
267                 self.word(",");
268                 self.maybe_print_trailing_comment(get_span(elt), Some(get_span(&elts[i]).hi()));
269                 self.space_if_not_bol();
270             }
271         }
272         self.end();
273     }
274
275     pub fn commasep_exprs(&mut self, b: Breaks, exprs: &[hir::Expr<'_>]) {
276         self.commasep_cmnt(b, exprs, |s, e| s.print_expr(e), |e| e.span);
277     }
278
279     pub fn print_mod(&mut self, _mod: &hir::Mod<'_>, attrs: &[ast::Attribute]) {
280         self.print_inner_attributes(attrs);
281         for &item_id in _mod.item_ids {
282             self.ann.nested(self, Nested::Item(item_id));
283         }
284     }
285
286     pub fn print_opt_lifetime(&mut self, lifetime: &hir::Lifetime) {
287         if !lifetime.is_elided() {
288             self.print_lifetime(lifetime);
289             self.nbsp();
290         }
291     }
292
293     pub fn print_type(&mut self, ty: &hir::Ty<'_>) {
294         self.maybe_print_comment(ty.span.lo());
295         self.ibox(0);
296         match ty.kind {
297             hir::TyKind::Slice(ty) => {
298                 self.word("[");
299                 self.print_type(ty);
300                 self.word("]");
301             }
302             hir::TyKind::Ptr(ref mt) => {
303                 self.word("*");
304                 self.print_mt(mt, true);
305             }
306             hir::TyKind::Rptr(ref lifetime, ref mt) => {
307                 self.word("&");
308                 self.print_opt_lifetime(lifetime);
309                 self.print_mt(mt, false);
310             }
311             hir::TyKind::Never => {
312                 self.word("!");
313             }
314             hir::TyKind::Tup(elts) => {
315                 self.popen();
316                 self.commasep(Inconsistent, elts, |s, ty| s.print_type(ty));
317                 if elts.len() == 1 {
318                     self.word(",");
319                 }
320                 self.pclose();
321             }
322             hir::TyKind::BareFn(f) => {
323                 self.print_ty_fn(f.abi, f.unsafety, f.decl, None, f.generic_params, f.param_names);
324             }
325             hir::TyKind::OpaqueDef(..) => self.word("/*impl Trait*/"),
326             hir::TyKind::Path(ref qpath) => self.print_qpath(qpath, false),
327             hir::TyKind::TraitObject(bounds, ref lifetime, syntax) => {
328                 if syntax == ast::TraitObjectSyntax::Dyn {
329                     self.word_space("dyn");
330                 }
331                 let mut first = true;
332                 for bound in bounds {
333                     if first {
334                         first = false;
335                     } else {
336                         self.nbsp();
337                         self.word_space("+");
338                     }
339                     self.print_poly_trait_ref(bound);
340                 }
341                 if !lifetime.is_elided() {
342                     self.nbsp();
343                     self.word_space("+");
344                     self.print_lifetime(lifetime);
345                 }
346             }
347             hir::TyKind::Array(ty, ref length) => {
348                 self.word("[");
349                 self.print_type(ty);
350                 self.word("; ");
351                 self.print_array_length(length);
352                 self.word("]");
353             }
354             hir::TyKind::Typeof(ref e) => {
355                 self.word("typeof(");
356                 self.print_anon_const(e);
357                 self.word(")");
358             }
359             hir::TyKind::Err => {
360                 self.popen();
361                 self.word("/*ERROR*/");
362                 self.pclose();
363             }
364             hir::TyKind::Infer => {
365                 self.word("_");
366             }
367         }
368         self.end()
369     }
370
371     pub fn print_foreign_item(&mut self, item: &hir::ForeignItem<'_>) {
372         self.hardbreak_if_not_bol();
373         self.maybe_print_comment(item.span.lo());
374         self.print_outer_attributes(self.attrs(item.hir_id()));
375         match item.kind {
376             hir::ForeignItemKind::Fn(decl, arg_names, generics) => {
377                 self.head("");
378                 self.print_fn(
379                     decl,
380                     hir::FnHeader {
381                         unsafety: hir::Unsafety::Normal,
382                         constness: hir::Constness::NotConst,
383                         abi: Abi::Rust,
384                         asyncness: hir::IsAsync::NotAsync,
385                     },
386                     Some(item.ident.name),
387                     generics,
388                     arg_names,
389                     None,
390                 );
391                 self.end(); // end head-ibox
392                 self.word(";");
393                 self.end() // end the outer fn box
394             }
395             hir::ForeignItemKind::Static(t, m) => {
396                 self.head("static");
397                 if m == hir::Mutability::Mut {
398                     self.word_space("mut");
399                 }
400                 self.print_ident(item.ident);
401                 self.word_space(":");
402                 self.print_type(t);
403                 self.word(";");
404                 self.end(); // end the head-ibox
405                 self.end() // end the outer cbox
406             }
407             hir::ForeignItemKind::Type => {
408                 self.head("type");
409                 self.print_ident(item.ident);
410                 self.word(";");
411                 self.end(); // end the head-ibox
412                 self.end() // end the outer cbox
413             }
414         }
415     }
416
417     fn print_associated_const(
418         &mut self,
419         ident: Ident,
420         ty: &hir::Ty<'_>,
421         default: Option<hir::BodyId>,
422     ) {
423         self.head("");
424         self.word_space("const");
425         self.print_ident(ident);
426         self.word_space(":");
427         self.print_type(ty);
428         if let Some(expr) = default {
429             self.space();
430             self.word_space("=");
431             self.ann.nested(self, Nested::Body(expr));
432         }
433         self.word(";")
434     }
435
436     fn print_associated_type(
437         &mut self,
438         ident: Ident,
439         generics: &hir::Generics<'_>,
440         bounds: Option<hir::GenericBounds<'_>>,
441         ty: Option<&hir::Ty<'_>>,
442     ) {
443         self.word_space("type");
444         self.print_ident(ident);
445         self.print_generic_params(generics.params);
446         if let Some(bounds) = bounds {
447             self.print_bounds(":", bounds);
448         }
449         self.print_where_clause(generics);
450         if let Some(ty) = ty {
451             self.space();
452             self.word_space("=");
453             self.print_type(ty);
454         }
455         self.word(";")
456     }
457
458     fn print_item_type(
459         &mut self,
460         item: &hir::Item<'_>,
461         generics: &hir::Generics<'_>,
462         inner: impl Fn(&mut Self),
463     ) {
464         self.head("type");
465         self.print_ident(item.ident);
466         self.print_generic_params(generics.params);
467         self.end(); // end the inner ibox
468
469         self.print_where_clause(generics);
470         self.space();
471         inner(self);
472         self.word(";");
473         self.end(); // end the outer ibox
474     }
475
476     /// Pretty-print an item
477     pub fn print_item(&mut self, item: &hir::Item<'_>) {
478         self.hardbreak_if_not_bol();
479         self.maybe_print_comment(item.span.lo());
480         let attrs = self.attrs(item.hir_id());
481         self.print_outer_attributes(attrs);
482         self.ann.pre(self, AnnNode::Item(item));
483         match item.kind {
484             hir::ItemKind::ExternCrate(orig_name) => {
485                 self.head("extern crate");
486                 if let Some(orig_name) = orig_name {
487                     self.print_name(orig_name);
488                     self.space();
489                     self.word("as");
490                     self.space();
491                 }
492                 self.print_ident(item.ident);
493                 self.word(";");
494                 self.end(); // end inner head-block
495                 self.end(); // end outer head-block
496             }
497             hir::ItemKind::Use(path, kind) => {
498                 self.head("use");
499                 self.print_path(path, false);
500
501                 match kind {
502                     hir::UseKind::Single => {
503                         if path.segments.last().unwrap().ident != item.ident {
504                             self.space();
505                             self.word_space("as");
506                             self.print_ident(item.ident);
507                         }
508                         self.word(";");
509                     }
510                     hir::UseKind::Glob => self.word("::*;"),
511                     hir::UseKind::ListStem => self.word("::{};"),
512                 }
513                 self.end(); // end inner head-block
514                 self.end(); // end outer head-block
515             }
516             hir::ItemKind::Static(ty, m, expr) => {
517                 self.head("static");
518                 if m == hir::Mutability::Mut {
519                     self.word_space("mut");
520                 }
521                 self.print_ident(item.ident);
522                 self.word_space(":");
523                 self.print_type(ty);
524                 self.space();
525                 self.end(); // end the head-ibox
526
527                 self.word_space("=");
528                 self.ann.nested(self, Nested::Body(expr));
529                 self.word(";");
530                 self.end(); // end the outer cbox
531             }
532             hir::ItemKind::Const(ty, expr) => {
533                 self.head("const");
534                 self.print_ident(item.ident);
535                 self.word_space(":");
536                 self.print_type(ty);
537                 self.space();
538                 self.end(); // end the head-ibox
539
540                 self.word_space("=");
541                 self.ann.nested(self, Nested::Body(expr));
542                 self.word(";");
543                 self.end(); // end the outer cbox
544             }
545             hir::ItemKind::Fn(ref sig, param_names, body) => {
546                 self.head("");
547                 self.print_fn(
548                     sig.decl,
549                     sig.header,
550                     Some(item.ident.name),
551                     param_names,
552                     &[],
553                     Some(body),
554                 );
555                 self.word(" ");
556                 self.end(); // need to close a box
557                 self.end(); // need to close a box
558                 self.ann.nested(self, Nested::Body(body));
559             }
560             hir::ItemKind::Macro(ref macro_def, _) => {
561                 self.print_mac_def(macro_def, &item.ident, item.span, |_| {});
562             }
563             hir::ItemKind::Mod(ref _mod) => {
564                 self.head("mod");
565                 self.print_ident(item.ident);
566                 self.nbsp();
567                 self.bopen();
568                 self.print_mod(_mod, attrs);
569                 self.bclose(item.span);
570             }
571             hir::ItemKind::ForeignMod { abi, items } => {
572                 self.head("extern");
573                 self.word_nbsp(abi.to_string());
574                 self.bopen();
575                 self.print_inner_attributes(self.attrs(item.hir_id()));
576                 for item in items {
577                     self.ann.nested(self, Nested::ForeignItem(item.id));
578                 }
579                 self.bclose(item.span);
580             }
581             hir::ItemKind::GlobalAsm(asm) => {
582                 self.head("global_asm!");
583                 self.print_inline_asm(asm);
584                 self.end()
585             }
586             hir::ItemKind::TyAlias(ty, generics) => {
587                 self.print_item_type(item, generics, |state| {
588                     state.word_space("=");
589                     state.print_type(ty);
590                 });
591             }
592             hir::ItemKind::OpaqueTy(ref opaque_ty) => {
593                 self.print_item_type(item, opaque_ty.generics, |state| {
594                     let mut real_bounds = Vec::with_capacity(opaque_ty.bounds.len());
595                     for b in opaque_ty.bounds {
596                         if let GenericBound::Trait(ptr, hir::TraitBoundModifier::Maybe) = b {
597                             state.space();
598                             state.word_space("for ?");
599                             state.print_trait_ref(&ptr.trait_ref);
600                         } else {
601                             real_bounds.push(b);
602                         }
603                     }
604                     state.print_bounds("= impl", real_bounds);
605                 });
606             }
607             hir::ItemKind::Enum(ref enum_definition, params) => {
608                 self.print_enum_def(enum_definition, params, item.ident.name, item.span);
609             }
610             hir::ItemKind::Struct(ref struct_def, generics) => {
611                 self.head("struct");
612                 self.print_struct(struct_def, generics, item.ident.name, item.span, true);
613             }
614             hir::ItemKind::Union(ref struct_def, generics) => {
615                 self.head("union");
616                 self.print_struct(struct_def, generics, item.ident.name, item.span, true);
617             }
618             hir::ItemKind::Impl(&hir::Impl {
619                 unsafety,
620                 polarity,
621                 defaultness,
622                 constness,
623                 defaultness_span: _,
624                 generics,
625                 ref of_trait,
626                 self_ty,
627                 items,
628             }) => {
629                 self.head("");
630                 self.print_defaultness(defaultness);
631                 self.print_unsafety(unsafety);
632                 self.word_nbsp("impl");
633
634                 if !generics.params.is_empty() {
635                     self.print_generic_params(generics.params);
636                     self.space();
637                 }
638
639                 if constness == hir::Constness::Const {
640                     self.word_nbsp("const");
641                 }
642
643                 if let hir::ImplPolarity::Negative(_) = polarity {
644                     self.word("!");
645                 }
646
647                 if let Some(t) = of_trait {
648                     self.print_trait_ref(t);
649                     self.space();
650                     self.word_space("for");
651                 }
652
653                 self.print_type(self_ty);
654                 self.print_where_clause(generics);
655
656                 self.space();
657                 self.bopen();
658                 self.print_inner_attributes(attrs);
659                 for impl_item in items {
660                     self.ann.nested(self, Nested::ImplItem(impl_item.id));
661                 }
662                 self.bclose(item.span);
663             }
664             hir::ItemKind::Trait(is_auto, unsafety, generics, bounds, trait_items) => {
665                 self.head("");
666                 self.print_is_auto(is_auto);
667                 self.print_unsafety(unsafety);
668                 self.word_nbsp("trait");
669                 self.print_ident(item.ident);
670                 self.print_generic_params(generics.params);
671                 let mut real_bounds = Vec::with_capacity(bounds.len());
672                 for b in bounds {
673                     if let GenericBound::Trait(ptr, hir::TraitBoundModifier::Maybe) = b {
674                         self.space();
675                         self.word_space("for ?");
676                         self.print_trait_ref(&ptr.trait_ref);
677                     } else {
678                         real_bounds.push(b);
679                     }
680                 }
681                 self.print_bounds(":", real_bounds);
682                 self.print_where_clause(generics);
683                 self.word(" ");
684                 self.bopen();
685                 for trait_item in trait_items {
686                     self.ann.nested(self, Nested::TraitItem(trait_item.id));
687                 }
688                 self.bclose(item.span);
689             }
690             hir::ItemKind::TraitAlias(generics, bounds) => {
691                 self.head("trait");
692                 self.print_ident(item.ident);
693                 self.print_generic_params(generics.params);
694                 let mut real_bounds = Vec::with_capacity(bounds.len());
695                 // FIXME(durka) this seems to be some quite outdated syntax
696                 for b in bounds {
697                     if let GenericBound::Trait(ptr, hir::TraitBoundModifier::Maybe) = b {
698                         self.space();
699                         self.word_space("for ?");
700                         self.print_trait_ref(&ptr.trait_ref);
701                     } else {
702                         real_bounds.push(b);
703                     }
704                 }
705                 self.nbsp();
706                 self.print_bounds("=", real_bounds);
707                 self.print_where_clause(generics);
708                 self.word(";");
709                 self.end(); // end inner head-block
710                 self.end(); // end outer head-block
711             }
712         }
713         self.ann.post(self, AnnNode::Item(item))
714     }
715
716     pub fn print_trait_ref(&mut self, t: &hir::TraitRef<'_>) {
717         self.print_path(t.path, false);
718     }
719
720     fn print_formal_generic_params(&mut self, generic_params: &[hir::GenericParam<'_>]) {
721         if !generic_params.is_empty() {
722             self.word("for");
723             self.print_generic_params(generic_params);
724             self.nbsp();
725         }
726     }
727
728     fn print_poly_trait_ref(&mut self, t: &hir::PolyTraitRef<'_>) {
729         self.print_formal_generic_params(t.bound_generic_params);
730         self.print_trait_ref(&t.trait_ref);
731     }
732
733     pub fn print_enum_def(
734         &mut self,
735         enum_definition: &hir::EnumDef<'_>,
736         generics: &hir::Generics<'_>,
737         name: Symbol,
738         span: rustc_span::Span,
739     ) {
740         self.head("enum");
741         self.print_name(name);
742         self.print_generic_params(generics.params);
743         self.print_where_clause(generics);
744         self.space();
745         self.print_variants(enum_definition.variants, span);
746     }
747
748     pub fn print_variants(&mut self, variants: &[hir::Variant<'_>], span: rustc_span::Span) {
749         self.bopen();
750         for v in variants {
751             self.space_if_not_bol();
752             self.maybe_print_comment(v.span.lo());
753             self.print_outer_attributes(self.attrs(v.id));
754             self.ibox(INDENT_UNIT);
755             self.print_variant(v);
756             self.word(",");
757             self.end();
758             self.maybe_print_trailing_comment(v.span, None);
759         }
760         self.bclose(span)
761     }
762
763     pub fn print_defaultness(&mut self, defaultness: hir::Defaultness) {
764         match defaultness {
765             hir::Defaultness::Default { .. } => self.word_nbsp("default"),
766             hir::Defaultness::Final => (),
767         }
768     }
769
770     pub fn print_struct(
771         &mut self,
772         struct_def: &hir::VariantData<'_>,
773         generics: &hir::Generics<'_>,
774         name: Symbol,
775         span: rustc_span::Span,
776         print_finalizer: bool,
777     ) {
778         self.print_name(name);
779         self.print_generic_params(generics.params);
780         match struct_def {
781             hir::VariantData::Tuple(..) | hir::VariantData::Unit(..) => {
782                 if let hir::VariantData::Tuple(..) = struct_def {
783                     self.popen();
784                     self.commasep(Inconsistent, struct_def.fields(), |s, field| {
785                         s.maybe_print_comment(field.span.lo());
786                         s.print_outer_attributes(s.attrs(field.hir_id));
787                         s.print_type(field.ty);
788                     });
789                     self.pclose();
790                 }
791                 self.print_where_clause(generics);
792                 if print_finalizer {
793                     self.word(";");
794                 }
795                 self.end();
796                 self.end() // close the outer-box
797             }
798             hir::VariantData::Struct(..) => {
799                 self.print_where_clause(generics);
800                 self.nbsp();
801                 self.bopen();
802                 self.hardbreak_if_not_bol();
803
804                 for field in struct_def.fields() {
805                     self.hardbreak_if_not_bol();
806                     self.maybe_print_comment(field.span.lo());
807                     self.print_outer_attributes(self.attrs(field.hir_id));
808                     self.print_ident(field.ident);
809                     self.word_nbsp(":");
810                     self.print_type(field.ty);
811                     self.word(",");
812                 }
813
814                 self.bclose(span)
815             }
816         }
817     }
818
819     pub fn print_variant(&mut self, v: &hir::Variant<'_>) {
820         self.head("");
821         let generics = hir::Generics::empty();
822         self.print_struct(&v.data, generics, v.ident.name, v.span, false);
823         if let Some(ref d) = v.disr_expr {
824             self.space();
825             self.word_space("=");
826             self.print_anon_const(d);
827         }
828     }
829     pub fn print_method_sig(
830         &mut self,
831         ident: Ident,
832         m: &hir::FnSig<'_>,
833         generics: &hir::Generics<'_>,
834         arg_names: &[Ident],
835         body_id: Option<hir::BodyId>,
836     ) {
837         self.print_fn(m.decl, m.header, Some(ident.name), generics, arg_names, body_id);
838     }
839
840     pub fn print_trait_item(&mut self, ti: &hir::TraitItem<'_>) {
841         self.ann.pre(self, AnnNode::SubItem(ti.hir_id()));
842         self.hardbreak_if_not_bol();
843         self.maybe_print_comment(ti.span.lo());
844         self.print_outer_attributes(self.attrs(ti.hir_id()));
845         match ti.kind {
846             hir::TraitItemKind::Const(ty, default) => {
847                 self.print_associated_const(ti.ident, ty, default);
848             }
849             hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Required(arg_names)) => {
850                 self.print_method_sig(ti.ident, sig, ti.generics, arg_names, None);
851                 self.word(";");
852             }
853             hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Provided(body)) => {
854                 self.head("");
855                 self.print_method_sig(ti.ident, sig, ti.generics, &[], Some(body));
856                 self.nbsp();
857                 self.end(); // need to close a box
858                 self.end(); // need to close a box
859                 self.ann.nested(self, Nested::Body(body));
860             }
861             hir::TraitItemKind::Type(bounds, default) => {
862                 self.print_associated_type(ti.ident, ti.generics, Some(bounds), default);
863             }
864         }
865         self.ann.post(self, AnnNode::SubItem(ti.hir_id()))
866     }
867
868     pub fn print_impl_item(&mut self, ii: &hir::ImplItem<'_>) {
869         self.ann.pre(self, AnnNode::SubItem(ii.hir_id()));
870         self.hardbreak_if_not_bol();
871         self.maybe_print_comment(ii.span.lo());
872         self.print_outer_attributes(self.attrs(ii.hir_id()));
873
874         match ii.kind {
875             hir::ImplItemKind::Const(ty, expr) => {
876                 self.print_associated_const(ii.ident, ty, Some(expr));
877             }
878             hir::ImplItemKind::Fn(ref sig, body) => {
879                 self.head("");
880                 self.print_method_sig(ii.ident, sig, ii.generics, &[], Some(body));
881                 self.nbsp();
882                 self.end(); // need to close a box
883                 self.end(); // need to close a box
884                 self.ann.nested(self, Nested::Body(body));
885             }
886             hir::ImplItemKind::TyAlias(ty) => {
887                 self.print_associated_type(ii.ident, ii.generics, None, Some(ty));
888             }
889         }
890         self.ann.post(self, AnnNode::SubItem(ii.hir_id()))
891     }
892
893     pub fn print_local(
894         &mut self,
895         init: Option<&hir::Expr<'_>>,
896         els: Option<&hir::Block<'_>>,
897         decl: impl Fn(&mut Self),
898     ) {
899         self.space_if_not_bol();
900         self.ibox(INDENT_UNIT);
901         self.word_nbsp("let");
902
903         self.ibox(INDENT_UNIT);
904         decl(self);
905         self.end();
906
907         if let Some(init) = init {
908             self.nbsp();
909             self.word_space("=");
910             self.print_expr(init);
911         }
912
913         if let Some(els) = els {
914             self.nbsp();
915             self.word_space("else");
916             // containing cbox, will be closed by print-block at `}`
917             self.cbox(0);
918             // head-box, will be closed by print-block after `{`
919             self.ibox(0);
920             self.print_block(els);
921         }
922
923         self.end()
924     }
925
926     pub fn print_stmt(&mut self, st: &hir::Stmt<'_>) {
927         self.maybe_print_comment(st.span.lo());
928         match st.kind {
929             hir::StmtKind::Local(loc) => {
930                 self.print_local(loc.init, loc.els, |this| this.print_local_decl(loc));
931             }
932             hir::StmtKind::Item(item) => self.ann.nested(self, Nested::Item(item)),
933             hir::StmtKind::Expr(expr) => {
934                 self.space_if_not_bol();
935                 self.print_expr(expr);
936             }
937             hir::StmtKind::Semi(expr) => {
938                 self.space_if_not_bol();
939                 self.print_expr(expr);
940                 self.word(";");
941             }
942         }
943         if stmt_ends_with_semi(&st.kind) {
944             self.word(";");
945         }
946         self.maybe_print_trailing_comment(st.span, None)
947     }
948
949     pub fn print_block(&mut self, blk: &hir::Block<'_>) {
950         self.print_block_with_attrs(blk, &[])
951     }
952
953     pub fn print_block_unclosed(&mut self, blk: &hir::Block<'_>) {
954         self.print_block_maybe_unclosed(blk, &[], false)
955     }
956
957     pub fn print_block_with_attrs(&mut self, blk: &hir::Block<'_>, attrs: &[ast::Attribute]) {
958         self.print_block_maybe_unclosed(blk, attrs, true)
959     }
960
961     pub fn print_block_maybe_unclosed(
962         &mut self,
963         blk: &hir::Block<'_>,
964         attrs: &[ast::Attribute],
965         close_box: bool,
966     ) {
967         match blk.rules {
968             hir::BlockCheckMode::UnsafeBlock(..) => self.word_space("unsafe"),
969             hir::BlockCheckMode::DefaultBlock => (),
970         }
971         self.maybe_print_comment(blk.span.lo());
972         self.ann.pre(self, AnnNode::Block(blk));
973         self.bopen();
974
975         self.print_inner_attributes(attrs);
976
977         for st in blk.stmts {
978             self.print_stmt(st);
979         }
980         if let Some(expr) = blk.expr {
981             self.space_if_not_bol();
982             self.print_expr(expr);
983             self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi()));
984         }
985         self.bclose_maybe_open(blk.span, close_box);
986         self.ann.post(self, AnnNode::Block(blk))
987     }
988
989     fn print_else(&mut self, els: Option<&hir::Expr<'_>>) {
990         if let Some(els_inner) = els {
991             match els_inner.kind {
992                 // Another `else if` block.
993                 hir::ExprKind::If(i, then, e) => {
994                     self.cbox(INDENT_UNIT - 1);
995                     self.ibox(0);
996                     self.word(" else if ");
997                     self.print_expr_as_cond(i);
998                     self.space();
999                     self.print_expr(then);
1000                     self.print_else(e);
1001                 }
1002                 // Final `else` block.
1003                 hir::ExprKind::Block(b, _) => {
1004                     self.cbox(INDENT_UNIT - 1);
1005                     self.ibox(0);
1006                     self.word(" else ");
1007                     self.print_block(b);
1008                 }
1009                 // Constraints would be great here!
1010                 _ => {
1011                     panic!("print_if saw if with weird alternative");
1012                 }
1013             }
1014         }
1015     }
1016
1017     pub fn print_if(
1018         &mut self,
1019         test: &hir::Expr<'_>,
1020         blk: &hir::Expr<'_>,
1021         elseopt: Option<&hir::Expr<'_>>,
1022     ) {
1023         self.head("if");
1024         self.print_expr_as_cond(test);
1025         self.space();
1026         self.print_expr(blk);
1027         self.print_else(elseopt)
1028     }
1029
1030     pub fn print_array_length(&mut self, len: &hir::ArrayLen) {
1031         match len {
1032             hir::ArrayLen::Infer(_, _) => self.word("_"),
1033             hir::ArrayLen::Body(ct) => self.print_anon_const(ct),
1034         }
1035     }
1036
1037     pub fn print_anon_const(&mut self, constant: &hir::AnonConst) {
1038         self.ann.nested(self, Nested::Body(constant.body))
1039     }
1040
1041     fn print_call_post(&mut self, args: &[hir::Expr<'_>]) {
1042         self.popen();
1043         self.commasep_exprs(Inconsistent, args);
1044         self.pclose()
1045     }
1046
1047     fn print_expr_maybe_paren(&mut self, expr: &hir::Expr<'_>, prec: i8) {
1048         self.print_expr_cond_paren(expr, expr.precedence().order() < prec)
1049     }
1050
1051     /// Prints an expr using syntax that's acceptable in a condition position, such as the `cond` in
1052     /// `if cond { ... }`.
1053     pub fn print_expr_as_cond(&mut self, expr: &hir::Expr<'_>) {
1054         self.print_expr_cond_paren(expr, Self::cond_needs_par(expr))
1055     }
1056
1057     /// Prints `expr` or `(expr)` when `needs_par` holds.
1058     fn print_expr_cond_paren(&mut self, expr: &hir::Expr<'_>, needs_par: bool) {
1059         if needs_par {
1060             self.popen();
1061         }
1062         if let hir::ExprKind::DropTemps(actual_expr) = expr.kind {
1063             self.print_expr(actual_expr);
1064         } else {
1065             self.print_expr(expr);
1066         }
1067         if needs_par {
1068             self.pclose();
1069         }
1070     }
1071
1072     /// Print a `let pat = expr` expression.
1073     fn print_let(&mut self, pat: &hir::Pat<'_>, ty: Option<&hir::Ty<'_>>, init: &hir::Expr<'_>) {
1074         self.word_space("let");
1075         self.print_pat(pat);
1076         if let Some(ty) = ty {
1077             self.word_space(":");
1078             self.print_type(ty);
1079         }
1080         self.space();
1081         self.word_space("=");
1082         let npals = || parser::needs_par_as_let_scrutinee(init.precedence().order());
1083         self.print_expr_cond_paren(init, Self::cond_needs_par(init) || npals())
1084     }
1085
1086     // Does `expr` need parentheses when printed in a condition position?
1087     //
1088     // These cases need parens due to the parse error observed in #26461: `if return {}`
1089     // parses as the erroneous construct `if (return {})`, not `if (return) {}`.
1090     fn cond_needs_par(expr: &hir::Expr<'_>) -> bool {
1091         match expr.kind {
1092             hir::ExprKind::Break(..) | hir::ExprKind::Closure { .. } | hir::ExprKind::Ret(..) => {
1093                 true
1094             }
1095             _ => contains_exterior_struct_lit(expr),
1096         }
1097     }
1098
1099     fn print_expr_vec(&mut self, exprs: &[hir::Expr<'_>]) {
1100         self.ibox(INDENT_UNIT);
1101         self.word("[");
1102         self.commasep_exprs(Inconsistent, exprs);
1103         self.word("]");
1104         self.end()
1105     }
1106
1107     fn print_expr_anon_const(&mut self, anon_const: &hir::AnonConst) {
1108         self.ibox(INDENT_UNIT);
1109         self.word_space("const");
1110         self.print_anon_const(anon_const);
1111         self.end()
1112     }
1113
1114     fn print_expr_repeat(&mut self, element: &hir::Expr<'_>, count: &hir::ArrayLen) {
1115         self.ibox(INDENT_UNIT);
1116         self.word("[");
1117         self.print_expr(element);
1118         self.word_space(";");
1119         self.print_array_length(count);
1120         self.word("]");
1121         self.end()
1122     }
1123
1124     fn print_expr_struct(
1125         &mut self,
1126         qpath: &hir::QPath<'_>,
1127         fields: &[hir::ExprField<'_>],
1128         wth: Option<&hir::Expr<'_>>,
1129     ) {
1130         self.print_qpath(qpath, true);
1131         self.word("{");
1132         self.commasep_cmnt(Consistent, fields, |s, field| s.print_expr_field(field), |f| f.span);
1133         if let Some(expr) = wth {
1134             self.ibox(INDENT_UNIT);
1135             if !fields.is_empty() {
1136                 self.word(",");
1137                 self.space();
1138             }
1139             self.word("..");
1140             self.print_expr(expr);
1141             self.end();
1142         } else if !fields.is_empty() {
1143             self.word(",");
1144         }
1145
1146         self.word("}");
1147     }
1148
1149     fn print_expr_field(&mut self, field: &hir::ExprField<'_>) {
1150         if self.attrs(field.hir_id).is_empty() {
1151             self.space();
1152         }
1153         self.cbox(INDENT_UNIT);
1154         self.print_outer_attributes(&self.attrs(field.hir_id));
1155         if !field.is_shorthand {
1156             self.print_ident(field.ident);
1157             self.word_space(":");
1158         }
1159         self.print_expr(&field.expr);
1160         self.end()
1161     }
1162
1163     fn print_expr_tup(&mut self, exprs: &[hir::Expr<'_>]) {
1164         self.popen();
1165         self.commasep_exprs(Inconsistent, exprs);
1166         if exprs.len() == 1 {
1167             self.word(",");
1168         }
1169         self.pclose()
1170     }
1171
1172     fn print_expr_call(&mut self, func: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
1173         let prec = match func.kind {
1174             hir::ExprKind::Field(..) => parser::PREC_FORCE_PAREN,
1175             _ => parser::PREC_POSTFIX,
1176         };
1177
1178         self.print_expr_maybe_paren(func, prec);
1179         self.print_call_post(args)
1180     }
1181
1182     fn print_expr_method_call(&mut self, segment: &hir::PathSegment<'_>, args: &[hir::Expr<'_>]) {
1183         let base_args = &args[1..];
1184         self.print_expr_maybe_paren(&args[0], parser::PREC_POSTFIX);
1185         self.word(".");
1186         self.print_ident(segment.ident);
1187
1188         let generic_args = segment.args();
1189         if !generic_args.args.is_empty() || !generic_args.bindings.is_empty() {
1190             self.print_generic_args(generic_args, segment.infer_args, true);
1191         }
1192
1193         self.print_call_post(base_args)
1194     }
1195
1196     fn print_expr_binary(&mut self, op: hir::BinOp, lhs: &hir::Expr<'_>, rhs: &hir::Expr<'_>) {
1197         let assoc_op = bin_op_to_assoc_op(op.node);
1198         let prec = assoc_op.precedence() as i8;
1199         let fixity = assoc_op.fixity();
1200
1201         let (left_prec, right_prec) = match fixity {
1202             Fixity::Left => (prec, prec + 1),
1203             Fixity::Right => (prec + 1, prec),
1204             Fixity::None => (prec + 1, prec + 1),
1205         };
1206
1207         let left_prec = match (&lhs.kind, op.node) {
1208             // These cases need parens: `x as i32 < y` has the parser thinking that `i32 < y` is
1209             // the beginning of a path type. It starts trying to parse `x as (i32 < y ...` instead
1210             // of `(x as i32) < ...`. We need to convince it _not_ to do that.
1211             (&hir::ExprKind::Cast { .. }, hir::BinOpKind::Lt | hir::BinOpKind::Shl) => {
1212                 parser::PREC_FORCE_PAREN
1213             }
1214             (&hir::ExprKind::Let { .. }, _) if !parser::needs_par_as_let_scrutinee(prec) => {
1215                 parser::PREC_FORCE_PAREN
1216             }
1217             _ => left_prec,
1218         };
1219
1220         self.print_expr_maybe_paren(lhs, left_prec);
1221         self.space();
1222         self.word_space(op.node.as_str());
1223         self.print_expr_maybe_paren(rhs, right_prec)
1224     }
1225
1226     fn print_expr_unary(&mut self, op: hir::UnOp, expr: &hir::Expr<'_>) {
1227         self.word(op.as_str());
1228         self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1229     }
1230
1231     fn print_expr_addr_of(
1232         &mut self,
1233         kind: hir::BorrowKind,
1234         mutability: hir::Mutability,
1235         expr: &hir::Expr<'_>,
1236     ) {
1237         self.word("&");
1238         match kind {
1239             hir::BorrowKind::Ref => self.print_mutability(mutability, false),
1240             hir::BorrowKind::Raw => {
1241                 self.word_nbsp("raw");
1242                 self.print_mutability(mutability, true);
1243             }
1244         }
1245         self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1246     }
1247
1248     fn print_literal(&mut self, lit: &hir::Lit) {
1249         self.maybe_print_comment(lit.span.lo());
1250         self.word(lit.node.to_token_lit().to_string())
1251     }
1252
1253     fn print_inline_asm(&mut self, asm: &hir::InlineAsm<'_>) {
1254         enum AsmArg<'a> {
1255             Template(String),
1256             Operand(&'a hir::InlineAsmOperand<'a>),
1257             Options(ast::InlineAsmOptions),
1258         }
1259
1260         let mut args = vec![AsmArg::Template(ast::InlineAsmTemplatePiece::to_string(asm.template))];
1261         args.extend(asm.operands.iter().map(|(o, _)| AsmArg::Operand(o)));
1262         if !asm.options.is_empty() {
1263             args.push(AsmArg::Options(asm.options));
1264         }
1265
1266         self.popen();
1267         self.commasep(Consistent, &args, |s, arg| match *arg {
1268             AsmArg::Template(ref template) => s.print_string(template, ast::StrStyle::Cooked),
1269             AsmArg::Operand(op) => match *op {
1270                 hir::InlineAsmOperand::In { reg, ref expr } => {
1271                     s.word("in");
1272                     s.popen();
1273                     s.word(format!("{}", reg));
1274                     s.pclose();
1275                     s.space();
1276                     s.print_expr(expr);
1277                 }
1278                 hir::InlineAsmOperand::Out { reg, late, ref expr } => {
1279                     s.word(if late { "lateout" } else { "out" });
1280                     s.popen();
1281                     s.word(format!("{}", reg));
1282                     s.pclose();
1283                     s.space();
1284                     match expr {
1285                         Some(expr) => s.print_expr(expr),
1286                         None => s.word("_"),
1287                     }
1288                 }
1289                 hir::InlineAsmOperand::InOut { reg, late, ref expr } => {
1290                     s.word(if late { "inlateout" } else { "inout" });
1291                     s.popen();
1292                     s.word(format!("{}", reg));
1293                     s.pclose();
1294                     s.space();
1295                     s.print_expr(expr);
1296                 }
1297                 hir::InlineAsmOperand::SplitInOut { reg, late, ref in_expr, ref out_expr } => {
1298                     s.word(if late { "inlateout" } else { "inout" });
1299                     s.popen();
1300                     s.word(format!("{}", reg));
1301                     s.pclose();
1302                     s.space();
1303                     s.print_expr(in_expr);
1304                     s.space();
1305                     s.word_space("=>");
1306                     match out_expr {
1307                         Some(out_expr) => s.print_expr(out_expr),
1308                         None => s.word("_"),
1309                     }
1310                 }
1311                 hir::InlineAsmOperand::Const { ref anon_const } => {
1312                     s.word("const");
1313                     s.space();
1314                     s.print_anon_const(anon_const);
1315                 }
1316                 hir::InlineAsmOperand::SymFn { ref anon_const } => {
1317                     s.word("sym_fn");
1318                     s.space();
1319                     s.print_anon_const(anon_const);
1320                 }
1321                 hir::InlineAsmOperand::SymStatic { ref path, def_id: _ } => {
1322                     s.word("sym_static");
1323                     s.space();
1324                     s.print_qpath(path, true);
1325                 }
1326             },
1327             AsmArg::Options(opts) => {
1328                 s.word("options");
1329                 s.popen();
1330                 let mut options = vec![];
1331                 if opts.contains(ast::InlineAsmOptions::PURE) {
1332                     options.push("pure");
1333                 }
1334                 if opts.contains(ast::InlineAsmOptions::NOMEM) {
1335                     options.push("nomem");
1336                 }
1337                 if opts.contains(ast::InlineAsmOptions::READONLY) {
1338                     options.push("readonly");
1339                 }
1340                 if opts.contains(ast::InlineAsmOptions::PRESERVES_FLAGS) {
1341                     options.push("preserves_flags");
1342                 }
1343                 if opts.contains(ast::InlineAsmOptions::NORETURN) {
1344                     options.push("noreturn");
1345                 }
1346                 if opts.contains(ast::InlineAsmOptions::NOSTACK) {
1347                     options.push("nostack");
1348                 }
1349                 if opts.contains(ast::InlineAsmOptions::ATT_SYNTAX) {
1350                     options.push("att_syntax");
1351                 }
1352                 if opts.contains(ast::InlineAsmOptions::RAW) {
1353                     options.push("raw");
1354                 }
1355                 if opts.contains(ast::InlineAsmOptions::MAY_UNWIND) {
1356                     options.push("may_unwind");
1357                 }
1358                 s.commasep(Inconsistent, &options, |s, &opt| {
1359                     s.word(opt);
1360                 });
1361                 s.pclose();
1362             }
1363         });
1364         self.pclose();
1365     }
1366
1367     pub fn print_expr(&mut self, expr: &hir::Expr<'_>) {
1368         self.maybe_print_comment(expr.span.lo());
1369         self.print_outer_attributes(self.attrs(expr.hir_id));
1370         self.ibox(INDENT_UNIT);
1371         self.ann.pre(self, AnnNode::Expr(expr));
1372         match expr.kind {
1373             hir::ExprKind::Box(expr) => {
1374                 self.word_space("box");
1375                 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX);
1376             }
1377             hir::ExprKind::Array(exprs) => {
1378                 self.print_expr_vec(exprs);
1379             }
1380             hir::ExprKind::ConstBlock(ref anon_const) => {
1381                 self.print_expr_anon_const(anon_const);
1382             }
1383             hir::ExprKind::Repeat(element, ref count) => {
1384                 self.print_expr_repeat(element, count);
1385             }
1386             hir::ExprKind::Struct(qpath, fields, wth) => {
1387                 self.print_expr_struct(qpath, fields, wth);
1388             }
1389             hir::ExprKind::Tup(exprs) => {
1390                 self.print_expr_tup(exprs);
1391             }
1392             hir::ExprKind::Call(func, args) => {
1393                 self.print_expr_call(func, args);
1394             }
1395             hir::ExprKind::MethodCall(segment, args, _) => {
1396                 self.print_expr_method_call(segment, args);
1397             }
1398             hir::ExprKind::Binary(op, lhs, rhs) => {
1399                 self.print_expr_binary(op, lhs, rhs);
1400             }
1401             hir::ExprKind::Unary(op, expr) => {
1402                 self.print_expr_unary(op, expr);
1403             }
1404             hir::ExprKind::AddrOf(k, m, expr) => {
1405                 self.print_expr_addr_of(k, m, expr);
1406             }
1407             hir::ExprKind::Lit(ref lit) => {
1408                 self.print_literal(lit);
1409             }
1410             hir::ExprKind::Cast(expr, ty) => {
1411                 let prec = AssocOp::As.precedence() as i8;
1412                 self.print_expr_maybe_paren(expr, prec);
1413                 self.space();
1414                 self.word_space("as");
1415                 self.print_type(ty);
1416             }
1417             hir::ExprKind::Type(expr, ty) => {
1418                 let prec = AssocOp::Colon.precedence() as i8;
1419                 self.print_expr_maybe_paren(expr, prec);
1420                 self.word_space(":");
1421                 self.print_type(ty);
1422             }
1423             hir::ExprKind::DropTemps(init) => {
1424                 // Print `{`:
1425                 self.cbox(INDENT_UNIT);
1426                 self.ibox(0);
1427                 self.bopen();
1428
1429                 // Print `let _t = $init;`:
1430                 let temp = Ident::from_str("_t");
1431                 self.print_local(Some(init), None, |this| this.print_ident(temp));
1432                 self.word(";");
1433
1434                 // Print `_t`:
1435                 self.space_if_not_bol();
1436                 self.print_ident(temp);
1437
1438                 // Print `}`:
1439                 self.bclose_maybe_open(expr.span, true);
1440             }
1441             hir::ExprKind::Let(&hir::Let { pat, ty, init, .. }) => {
1442                 self.print_let(pat, ty, init);
1443             }
1444             hir::ExprKind::If(test, blk, elseopt) => {
1445                 self.print_if(test, blk, elseopt);
1446             }
1447             hir::ExprKind::Loop(blk, opt_label, _, _) => {
1448                 if let Some(label) = opt_label {
1449                     self.print_ident(label.ident);
1450                     self.word_space(":");
1451                 }
1452                 self.head("loop");
1453                 self.print_block(blk);
1454             }
1455             hir::ExprKind::Match(expr, arms, _) => {
1456                 self.cbox(INDENT_UNIT);
1457                 self.ibox(INDENT_UNIT);
1458                 self.word_nbsp("match");
1459                 self.print_expr_as_cond(expr);
1460                 self.space();
1461                 self.bopen();
1462                 for arm in arms {
1463                     self.print_arm(arm);
1464                 }
1465                 self.bclose(expr.span);
1466             }
1467             hir::ExprKind::Closure(&hir::Closure {
1468                 binder,
1469                 capture_clause,
1470                 bound_generic_params,
1471                 fn_decl,
1472                 body,
1473                 fn_decl_span: _,
1474                 movability: _,
1475             }) => {
1476                 self.print_closure_binder(binder, bound_generic_params);
1477                 self.print_capture_clause(capture_clause);
1478
1479                 self.print_closure_params(fn_decl, body);
1480                 self.space();
1481
1482                 // This is a bare expression.
1483                 self.ann.nested(self, Nested::Body(body));
1484                 self.end(); // need to close a box
1485
1486                 // A box will be closed by `print_expr`, but we didn't want an overall
1487                 // wrapper so we closed the corresponding opening. so create an
1488                 // empty box to satisfy the close.
1489                 self.ibox(0);
1490             }
1491             hir::ExprKind::Block(blk, opt_label) => {
1492                 if let Some(label) = opt_label {
1493                     self.print_ident(label.ident);
1494                     self.word_space(":");
1495                 }
1496                 // containing cbox, will be closed by print-block at `}`
1497                 self.cbox(INDENT_UNIT);
1498                 // head-box, will be closed by print-block after `{`
1499                 self.ibox(0);
1500                 self.print_block(blk);
1501             }
1502             hir::ExprKind::Assign(lhs, rhs, _) => {
1503                 let prec = AssocOp::Assign.precedence() as i8;
1504                 self.print_expr_maybe_paren(lhs, prec + 1);
1505                 self.space();
1506                 self.word_space("=");
1507                 self.print_expr_maybe_paren(rhs, prec);
1508             }
1509             hir::ExprKind::AssignOp(op, lhs, rhs) => {
1510                 let prec = AssocOp::Assign.precedence() as i8;
1511                 self.print_expr_maybe_paren(lhs, prec + 1);
1512                 self.space();
1513                 self.word(op.node.as_str());
1514                 self.word_space("=");
1515                 self.print_expr_maybe_paren(rhs, prec);
1516             }
1517             hir::ExprKind::Field(expr, ident) => {
1518                 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
1519                 self.word(".");
1520                 self.print_ident(ident);
1521             }
1522             hir::ExprKind::Index(expr, index) => {
1523                 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
1524                 self.word("[");
1525                 self.print_expr(index);
1526                 self.word("]");
1527             }
1528             hir::ExprKind::Path(ref qpath) => self.print_qpath(qpath, true),
1529             hir::ExprKind::Break(destination, opt_expr) => {
1530                 self.word("break");
1531                 if let Some(label) = destination.label {
1532                     self.space();
1533                     self.print_ident(label.ident);
1534                 }
1535                 if let Some(expr) = opt_expr {
1536                     self.space();
1537                     self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
1538                 }
1539             }
1540             hir::ExprKind::Continue(destination) => {
1541                 self.word("continue");
1542                 if let Some(label) = destination.label {
1543                     self.space();
1544                     self.print_ident(label.ident);
1545                 }
1546             }
1547             hir::ExprKind::Ret(result) => {
1548                 self.word("return");
1549                 if let Some(expr) = result {
1550                     self.word(" ");
1551                     self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
1552                 }
1553             }
1554             hir::ExprKind::InlineAsm(asm) => {
1555                 self.word("asm!");
1556                 self.print_inline_asm(asm);
1557             }
1558             hir::ExprKind::Yield(expr, _) => {
1559                 self.word_space("yield");
1560                 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
1561             }
1562             hir::ExprKind::Err => {
1563                 self.popen();
1564                 self.word("/*ERROR*/");
1565                 self.pclose();
1566             }
1567         }
1568         self.ann.post(self, AnnNode::Expr(expr));
1569         self.end()
1570     }
1571
1572     pub fn print_local_decl(&mut self, loc: &hir::Local<'_>) {
1573         self.print_pat(loc.pat);
1574         if let Some(ty) = loc.ty {
1575             self.word_space(":");
1576             self.print_type(ty);
1577         }
1578     }
1579
1580     pub fn print_name(&mut self, name: Symbol) {
1581         self.print_ident(Ident::with_dummy_span(name))
1582     }
1583
1584     pub fn print_path(&mut self, path: &hir::Path<'_>, colons_before_params: bool) {
1585         self.maybe_print_comment(path.span.lo());
1586
1587         for (i, segment) in path.segments.iter().enumerate() {
1588             if i > 0 {
1589                 self.word("::")
1590             }
1591             if segment.ident.name != kw::PathRoot {
1592                 self.print_ident(segment.ident);
1593                 self.print_generic_args(segment.args(), segment.infer_args, colons_before_params);
1594             }
1595         }
1596     }
1597
1598     pub fn print_path_segment(&mut self, segment: &hir::PathSegment<'_>) {
1599         if segment.ident.name != kw::PathRoot {
1600             self.print_ident(segment.ident);
1601             self.print_generic_args(segment.args(), segment.infer_args, false);
1602         }
1603     }
1604
1605     pub fn print_qpath(&mut self, qpath: &hir::QPath<'_>, colons_before_params: bool) {
1606         match *qpath {
1607             hir::QPath::Resolved(None, path) => self.print_path(path, colons_before_params),
1608             hir::QPath::Resolved(Some(qself), path) => {
1609                 self.word("<");
1610                 self.print_type(qself);
1611                 self.space();
1612                 self.word_space("as");
1613
1614                 for (i, segment) in path.segments[..path.segments.len() - 1].iter().enumerate() {
1615                     if i > 0 {
1616                         self.word("::")
1617                     }
1618                     if segment.ident.name != kw::PathRoot {
1619                         self.print_ident(segment.ident);
1620                         self.print_generic_args(
1621                             segment.args(),
1622                             segment.infer_args,
1623                             colons_before_params,
1624                         );
1625                     }
1626                 }
1627
1628                 self.word(">");
1629                 self.word("::");
1630                 let item_segment = path.segments.last().unwrap();
1631                 self.print_ident(item_segment.ident);
1632                 self.print_generic_args(
1633                     item_segment.args(),
1634                     item_segment.infer_args,
1635                     colons_before_params,
1636                 )
1637             }
1638             hir::QPath::TypeRelative(qself, item_segment) => {
1639                 // If we've got a compound-qualified-path, let's push an additional pair of angle
1640                 // brackets, so that we pretty-print `<<A::B>::C>` as `<A::B>::C`, instead of just
1641                 // `A::B::C` (since the latter could be ambiguous to the user)
1642                 if let hir::TyKind::Path(hir::QPath::Resolved(None, _)) = qself.kind {
1643                     self.print_type(qself);
1644                 } else {
1645                     self.word("<");
1646                     self.print_type(qself);
1647                     self.word(">");
1648                 }
1649
1650                 self.word("::");
1651                 self.print_ident(item_segment.ident);
1652                 self.print_generic_args(
1653                     item_segment.args(),
1654                     item_segment.infer_args,
1655                     colons_before_params,
1656                 )
1657             }
1658             hir::QPath::LangItem(lang_item, span, _) => {
1659                 self.word("#[lang = \"");
1660                 self.print_ident(Ident::new(lang_item.name(), span));
1661                 self.word("\"]");
1662             }
1663         }
1664     }
1665
1666     fn print_generic_args(
1667         &mut self,
1668         generic_args: &hir::GenericArgs<'_>,
1669         infer_args: bool,
1670         colons_before_params: bool,
1671     ) {
1672         if generic_args.parenthesized {
1673             self.word("(");
1674             self.commasep(Inconsistent, generic_args.inputs(), |s, ty| s.print_type(ty));
1675             self.word(")");
1676
1677             self.space_if_not_bol();
1678             self.word_space("->");
1679             self.print_type(generic_args.bindings[0].ty());
1680         } else {
1681             let start = if colons_before_params { "::<" } else { "<" };
1682             let empty = Cell::new(true);
1683             let start_or_comma = |this: &mut Self| {
1684                 if empty.get() {
1685                     empty.set(false);
1686                     this.word(start)
1687                 } else {
1688                     this.word_space(",")
1689                 }
1690             };
1691
1692             let mut nonelided_generic_args: bool = false;
1693             let elide_lifetimes = generic_args.args.iter().all(|arg| match arg {
1694                 GenericArg::Lifetime(lt) => lt.is_elided(),
1695                 _ => {
1696                     nonelided_generic_args = true;
1697                     true
1698                 }
1699             });
1700
1701             if nonelided_generic_args {
1702                 start_or_comma(self);
1703                 self.commasep(
1704                     Inconsistent,
1705                     generic_args.args,
1706                     |s, generic_arg| match generic_arg {
1707                         GenericArg::Lifetime(lt) if !elide_lifetimes => s.print_lifetime(lt),
1708                         GenericArg::Lifetime(_) => {}
1709                         GenericArg::Type(ty) => s.print_type(ty),
1710                         GenericArg::Const(ct) => s.print_anon_const(&ct.value),
1711                         GenericArg::Infer(_inf) => s.word("_"),
1712                     },
1713                 );
1714             }
1715
1716             // FIXME(eddyb): this would leak into error messages (e.g.,
1717             // "non-exhaustive patterns: `Some::<..>(_)` not covered").
1718             if infer_args && false {
1719                 start_or_comma(self);
1720                 self.word("..");
1721             }
1722
1723             for binding in generic_args.bindings {
1724                 start_or_comma(self);
1725                 self.print_type_binding(binding);
1726             }
1727
1728             if !empty.get() {
1729                 self.word(">")
1730             }
1731         }
1732     }
1733
1734     pub fn print_type_binding(&mut self, binding: &hir::TypeBinding<'_>) {
1735         self.print_ident(binding.ident);
1736         self.print_generic_args(binding.gen_args, false, false);
1737         self.space();
1738         match binding.kind {
1739             hir::TypeBindingKind::Equality { ref term } => {
1740                 self.word_space("=");
1741                 match term {
1742                     Term::Ty(ty) => self.print_type(ty),
1743                     Term::Const(ref c) => self.print_anon_const(c),
1744                 }
1745             }
1746             hir::TypeBindingKind::Constraint { bounds } => {
1747                 self.print_bounds(":", bounds);
1748             }
1749         }
1750     }
1751
1752     pub fn print_pat(&mut self, pat: &hir::Pat<'_>) {
1753         self.maybe_print_comment(pat.span.lo());
1754         self.ann.pre(self, AnnNode::Pat(pat));
1755         // Pat isn't normalized, but the beauty of it
1756         // is that it doesn't matter
1757         match pat.kind {
1758             PatKind::Wild => self.word("_"),
1759             PatKind::Binding(binding_mode, _, ident, sub) => {
1760                 match binding_mode {
1761                     hir::BindingAnnotation::Ref => {
1762                         self.word_nbsp("ref");
1763                         self.print_mutability(hir::Mutability::Not, false);
1764                     }
1765                     hir::BindingAnnotation::RefMut => {
1766                         self.word_nbsp("ref");
1767                         self.print_mutability(hir::Mutability::Mut, false);
1768                     }
1769                     hir::BindingAnnotation::Unannotated => {}
1770                     hir::BindingAnnotation::Mutable => {
1771                         self.word_nbsp("mut");
1772                     }
1773                 }
1774                 self.print_ident(ident);
1775                 if let Some(p) = sub {
1776                     self.word("@");
1777                     self.print_pat(p);
1778                 }
1779             }
1780             PatKind::TupleStruct(ref qpath, elts, ddpos) => {
1781                 self.print_qpath(qpath, true);
1782                 self.popen();
1783                 if let Some(ddpos) = ddpos {
1784                     self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(p));
1785                     if ddpos != 0 {
1786                         self.word_space(",");
1787                     }
1788                     self.word("..");
1789                     if ddpos != elts.len() {
1790                         self.word(",");
1791                         self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(p));
1792                     }
1793                 } else {
1794                     self.commasep(Inconsistent, elts, |s, p| s.print_pat(p));
1795                 }
1796                 self.pclose();
1797             }
1798             PatKind::Path(ref qpath) => {
1799                 self.print_qpath(qpath, true);
1800             }
1801             PatKind::Struct(ref qpath, fields, etc) => {
1802                 self.print_qpath(qpath, true);
1803                 self.nbsp();
1804                 self.word("{");
1805                 let empty = fields.is_empty() && !etc;
1806                 if !empty {
1807                     self.space();
1808                 }
1809                 self.commasep_cmnt(Consistent, &fields, |s, f| s.print_patfield(f), |f| f.pat.span);
1810                 if etc {
1811                     if !fields.is_empty() {
1812                         self.word_space(",");
1813                     }
1814                     self.word("..");
1815                 }
1816                 if !empty {
1817                     self.space();
1818                 }
1819                 self.word("}");
1820             }
1821             PatKind::Or(pats) => {
1822                 self.strsep("|", true, Inconsistent, pats, |s, p| s.print_pat(p));
1823             }
1824             PatKind::Tuple(elts, ddpos) => {
1825                 self.popen();
1826                 if let Some(ddpos) = ddpos {
1827                     self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(p));
1828                     if ddpos != 0 {
1829                         self.word_space(",");
1830                     }
1831                     self.word("..");
1832                     if ddpos != elts.len() {
1833                         self.word(",");
1834                         self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(p));
1835                     }
1836                 } else {
1837                     self.commasep(Inconsistent, elts, |s, p| s.print_pat(p));
1838                     if elts.len() == 1 {
1839                         self.word(",");
1840                     }
1841                 }
1842                 self.pclose();
1843             }
1844             PatKind::Box(inner) => {
1845                 let is_range_inner = matches!(inner.kind, PatKind::Range(..));
1846                 self.word("box ");
1847                 if is_range_inner {
1848                     self.popen();
1849                 }
1850                 self.print_pat(inner);
1851                 if is_range_inner {
1852                     self.pclose();
1853                 }
1854             }
1855             PatKind::Ref(inner, mutbl) => {
1856                 let is_range_inner = matches!(inner.kind, PatKind::Range(..));
1857                 self.word("&");
1858                 self.word(mutbl.prefix_str());
1859                 if is_range_inner {
1860                     self.popen();
1861                 }
1862                 self.print_pat(inner);
1863                 if is_range_inner {
1864                     self.pclose();
1865                 }
1866             }
1867             PatKind::Lit(e) => self.print_expr(e),
1868             PatKind::Range(begin, end, end_kind) => {
1869                 if let Some(expr) = begin {
1870                     self.print_expr(expr);
1871                 }
1872                 match end_kind {
1873                     RangeEnd::Included => self.word("..."),
1874                     RangeEnd::Excluded => self.word(".."),
1875                 }
1876                 if let Some(expr) = end {
1877                     self.print_expr(expr);
1878                 }
1879             }
1880             PatKind::Slice(before, slice, after) => {
1881                 self.word("[");
1882                 self.commasep(Inconsistent, before, |s, p| s.print_pat(p));
1883                 if let Some(p) = slice {
1884                     if !before.is_empty() {
1885                         self.word_space(",");
1886                     }
1887                     if let PatKind::Wild = p.kind {
1888                         // Print nothing.
1889                     } else {
1890                         self.print_pat(p);
1891                     }
1892                     self.word("..");
1893                     if !after.is_empty() {
1894                         self.word_space(",");
1895                     }
1896                 }
1897                 self.commasep(Inconsistent, after, |s, p| s.print_pat(p));
1898                 self.word("]");
1899             }
1900         }
1901         self.ann.post(self, AnnNode::Pat(pat))
1902     }
1903
1904     pub fn print_patfield(&mut self, field: &hir::PatField<'_>) {
1905         if self.attrs(field.hir_id).is_empty() {
1906             self.space();
1907         }
1908         self.cbox(INDENT_UNIT);
1909         self.print_outer_attributes(&self.attrs(field.hir_id));
1910         if !field.is_shorthand {
1911             self.print_ident(field.ident);
1912             self.word_nbsp(":");
1913         }
1914         self.print_pat(field.pat);
1915         self.end();
1916     }
1917
1918     pub fn print_param(&mut self, arg: &hir::Param<'_>) {
1919         self.print_outer_attributes(self.attrs(arg.hir_id));
1920         self.print_pat(arg.pat);
1921     }
1922
1923     pub fn print_arm(&mut self, arm: &hir::Arm<'_>) {
1924         // I have no idea why this check is necessary, but here it
1925         // is :(
1926         if self.attrs(arm.hir_id).is_empty() {
1927             self.space();
1928         }
1929         self.cbox(INDENT_UNIT);
1930         self.ann.pre(self, AnnNode::Arm(arm));
1931         self.ibox(0);
1932         self.print_outer_attributes(self.attrs(arm.hir_id));
1933         self.print_pat(arm.pat);
1934         self.space();
1935         if let Some(ref g) = arm.guard {
1936             match *g {
1937                 hir::Guard::If(e) => {
1938                     self.word_space("if");
1939                     self.print_expr(e);
1940                     self.space();
1941                 }
1942                 hir::Guard::IfLet(&hir::Let { pat, ty, init, .. }) => {
1943                     self.word_nbsp("if");
1944                     self.print_let(pat, ty, init);
1945                 }
1946             }
1947         }
1948         self.word_space("=>");
1949
1950         match arm.body.kind {
1951             hir::ExprKind::Block(blk, opt_label) => {
1952                 if let Some(label) = opt_label {
1953                     self.print_ident(label.ident);
1954                     self.word_space(":");
1955                 }
1956                 // the block will close the pattern's ibox
1957                 self.print_block_unclosed(blk);
1958
1959                 // If it is a user-provided unsafe block, print a comma after it
1960                 if let hir::BlockCheckMode::UnsafeBlock(hir::UnsafeSource::UserProvided) = blk.rules
1961                 {
1962                     self.word(",");
1963                 }
1964             }
1965             _ => {
1966                 self.end(); // close the ibox for the pattern
1967                 self.print_expr(arm.body);
1968                 self.word(",");
1969             }
1970         }
1971         self.ann.post(self, AnnNode::Arm(arm));
1972         self.end() // close enclosing cbox
1973     }
1974
1975     pub fn print_fn(
1976         &mut self,
1977         decl: &hir::FnDecl<'_>,
1978         header: hir::FnHeader,
1979         name: Option<Symbol>,
1980         generics: &hir::Generics<'_>,
1981         arg_names: &[Ident],
1982         body_id: Option<hir::BodyId>,
1983     ) {
1984         self.print_fn_header_info(header);
1985
1986         if let Some(name) = name {
1987             self.nbsp();
1988             self.print_name(name);
1989         }
1990         self.print_generic_params(generics.params);
1991
1992         self.popen();
1993         let mut i = 0;
1994         // Make sure we aren't supplied *both* `arg_names` and `body_id`.
1995         assert!(arg_names.is_empty() || body_id.is_none());
1996         self.commasep(Inconsistent, decl.inputs, |s, ty| {
1997             s.ibox(INDENT_UNIT);
1998             if let Some(arg_name) = arg_names.get(i) {
1999                 s.word(arg_name.to_string());
2000                 s.word(":");
2001                 s.space();
2002             } else if let Some(body_id) = body_id {
2003                 s.ann.nested(s, Nested::BodyParamPat(body_id, i));
2004                 s.word(":");
2005                 s.space();
2006             }
2007             i += 1;
2008             s.print_type(ty);
2009             s.end()
2010         });
2011         if decl.c_variadic {
2012             self.word(", ...");
2013         }
2014         self.pclose();
2015
2016         self.print_fn_output(decl);
2017         self.print_where_clause(generics)
2018     }
2019
2020     fn print_closure_params(&mut self, decl: &hir::FnDecl<'_>, body_id: hir::BodyId) {
2021         self.word("|");
2022         let mut i = 0;
2023         self.commasep(Inconsistent, decl.inputs, |s, ty| {
2024             s.ibox(INDENT_UNIT);
2025
2026             s.ann.nested(s, Nested::BodyParamPat(body_id, i));
2027             i += 1;
2028
2029             if let hir::TyKind::Infer = ty.kind {
2030                 // Print nothing.
2031             } else {
2032                 s.word(":");
2033                 s.space();
2034                 s.print_type(ty);
2035             }
2036             s.end();
2037         });
2038         self.word("|");
2039
2040         if let hir::FnRetTy::DefaultReturn(..) = decl.output {
2041             return;
2042         }
2043
2044         self.space_if_not_bol();
2045         self.word_space("->");
2046         match decl.output {
2047             hir::FnRetTy::Return(ty) => {
2048                 self.print_type(ty);
2049                 self.maybe_print_comment(ty.span.lo());
2050             }
2051             hir::FnRetTy::DefaultReturn(..) => unreachable!(),
2052         }
2053     }
2054
2055     pub fn print_capture_clause(&mut self, capture_clause: hir::CaptureBy) {
2056         match capture_clause {
2057             hir::CaptureBy::Value => self.word_space("move"),
2058             hir::CaptureBy::Ref => {}
2059         }
2060     }
2061
2062     pub fn print_closure_binder(
2063         &mut self,
2064         binder: hir::ClosureBinder,
2065         generic_params: &[GenericParam<'_>],
2066     ) {
2067         let generic_params = generic_params
2068             .iter()
2069             .filter(|p| {
2070                 matches!(
2071                     p,
2072                     GenericParam {
2073                         kind: GenericParamKind::Lifetime { kind: LifetimeParamKind::Explicit },
2074                         ..
2075                     }
2076                 )
2077             })
2078             .collect::<Vec<_>>();
2079
2080         match binder {
2081             hir::ClosureBinder::Default => {}
2082             // we need to distinguish `|...| {}` from `for<> |...| {}` as `for<>` adds additional restrictions
2083             hir::ClosureBinder::For { .. } if generic_params.is_empty() => self.word("for<>"),
2084             hir::ClosureBinder::For { .. } => {
2085                 self.word("for");
2086                 self.word("<");
2087
2088                 self.commasep(Inconsistent, &generic_params, |s, param| {
2089                     s.print_generic_param(param)
2090                 });
2091
2092                 self.word(">");
2093                 self.nbsp();
2094             }
2095         }
2096     }
2097
2098     pub fn print_bounds<'b>(
2099         &mut self,
2100         prefix: &'static str,
2101         bounds: impl IntoIterator<Item = &'b hir::GenericBound<'b>>,
2102     ) {
2103         let mut first = true;
2104         for bound in bounds {
2105             if first {
2106                 self.word(prefix);
2107             }
2108             if !(first && prefix.is_empty()) {
2109                 self.nbsp();
2110             }
2111             if first {
2112                 first = false;
2113             } else {
2114                 self.word_space("+");
2115             }
2116
2117             match bound {
2118                 GenericBound::Trait(tref, modifier) => {
2119                     if modifier == &TraitBoundModifier::Maybe {
2120                         self.word("?");
2121                     }
2122                     self.print_poly_trait_ref(tref);
2123                 }
2124                 GenericBound::LangItemTrait(lang_item, span, ..) => {
2125                     self.word("#[lang = \"");
2126                     self.print_ident(Ident::new(lang_item.name(), *span));
2127                     self.word("\"]");
2128                 }
2129                 GenericBound::Outlives(lt) => {
2130                     self.print_lifetime(lt);
2131                 }
2132             }
2133         }
2134     }
2135
2136     pub fn print_generic_params(&mut self, generic_params: &[GenericParam<'_>]) {
2137         if !generic_params.is_empty() {
2138             self.word("<");
2139
2140             self.commasep(Inconsistent, generic_params, |s, param| s.print_generic_param(param));
2141
2142             self.word(">");
2143         }
2144     }
2145
2146     pub fn print_generic_param(&mut self, param: &GenericParam<'_>) {
2147         if let GenericParamKind::Const { .. } = param.kind {
2148             self.word_space("const");
2149         }
2150
2151         self.print_ident(param.name.ident());
2152
2153         match param.kind {
2154             GenericParamKind::Lifetime { .. } => {}
2155             GenericParamKind::Type { default, .. } => {
2156                 if let Some(default) = default {
2157                     self.space();
2158                     self.word_space("=");
2159                     self.print_type(default);
2160                 }
2161             }
2162             GenericParamKind::Const { ty, ref default } => {
2163                 self.word_space(":");
2164                 self.print_type(ty);
2165                 if let Some(default) = default {
2166                     self.space();
2167                     self.word_space("=");
2168                     self.print_anon_const(default);
2169                 }
2170             }
2171         }
2172     }
2173
2174     pub fn print_lifetime(&mut self, lifetime: &hir::Lifetime) {
2175         self.print_ident(lifetime.name.ident())
2176     }
2177
2178     pub fn print_where_clause(&mut self, generics: &hir::Generics<'_>) {
2179         if generics.predicates.is_empty() {
2180             return;
2181         }
2182
2183         self.space();
2184         self.word_space("where");
2185
2186         for (i, predicate) in generics.predicates.iter().enumerate() {
2187             if i != 0 {
2188                 self.word_space(",");
2189             }
2190
2191             match *predicate {
2192                 hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
2193                     bound_generic_params,
2194                     bounded_ty,
2195                     bounds,
2196                     ..
2197                 }) => {
2198                     self.print_formal_generic_params(bound_generic_params);
2199                     self.print_type(bounded_ty);
2200                     self.print_bounds(":", bounds);
2201                 }
2202                 hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
2203                     ref lifetime,
2204                     bounds,
2205                     ..
2206                 }) => {
2207                     self.print_lifetime(lifetime);
2208                     self.word(":");
2209
2210                     for (i, bound) in bounds.iter().enumerate() {
2211                         match bound {
2212                             GenericBound::Outlives(lt) => {
2213                                 self.print_lifetime(lt);
2214                             }
2215                             _ => panic!(),
2216                         }
2217
2218                         if i != 0 {
2219                             self.word(":");
2220                         }
2221                     }
2222                 }
2223                 hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
2224                     lhs_ty, rhs_ty, ..
2225                 }) => {
2226                     self.print_type(lhs_ty);
2227                     self.space();
2228                     self.word_space("=");
2229                     self.print_type(rhs_ty);
2230                 }
2231             }
2232         }
2233     }
2234
2235     pub fn print_mutability(&mut self, mutbl: hir::Mutability, print_const: bool) {
2236         match mutbl {
2237             hir::Mutability::Mut => self.word_nbsp("mut"),
2238             hir::Mutability::Not => {
2239                 if print_const {
2240                     self.word_nbsp("const")
2241                 }
2242             }
2243         }
2244     }
2245
2246     pub fn print_mt(&mut self, mt: &hir::MutTy<'_>, print_const: bool) {
2247         self.print_mutability(mt.mutbl, print_const);
2248         self.print_type(mt.ty);
2249     }
2250
2251     pub fn print_fn_output(&mut self, decl: &hir::FnDecl<'_>) {
2252         if let hir::FnRetTy::DefaultReturn(..) = decl.output {
2253             return;
2254         }
2255
2256         self.space_if_not_bol();
2257         self.ibox(INDENT_UNIT);
2258         self.word_space("->");
2259         match decl.output {
2260             hir::FnRetTy::DefaultReturn(..) => unreachable!(),
2261             hir::FnRetTy::Return(ty) => self.print_type(ty),
2262         }
2263         self.end();
2264
2265         if let hir::FnRetTy::Return(output) = decl.output {
2266             self.maybe_print_comment(output.span.lo());
2267         }
2268     }
2269
2270     pub fn print_ty_fn(
2271         &mut self,
2272         abi: Abi,
2273         unsafety: hir::Unsafety,
2274         decl: &hir::FnDecl<'_>,
2275         name: Option<Symbol>,
2276         generic_params: &[hir::GenericParam<'_>],
2277         arg_names: &[Ident],
2278     ) {
2279         self.ibox(INDENT_UNIT);
2280         self.print_formal_generic_params(generic_params);
2281         let generics = hir::Generics::empty();
2282         self.print_fn(
2283             decl,
2284             hir::FnHeader {
2285                 unsafety,
2286                 abi,
2287                 constness: hir::Constness::NotConst,
2288                 asyncness: hir::IsAsync::NotAsync,
2289             },
2290             name,
2291             generics,
2292             arg_names,
2293             None,
2294         );
2295         self.end();
2296     }
2297
2298     pub fn print_fn_header_info(&mut self, header: hir::FnHeader) {
2299         match header.constness {
2300             hir::Constness::NotConst => {}
2301             hir::Constness::Const => self.word_nbsp("const"),
2302         }
2303
2304         match header.asyncness {
2305             hir::IsAsync::NotAsync => {}
2306             hir::IsAsync::Async => self.word_nbsp("async"),
2307         }
2308
2309         self.print_unsafety(header.unsafety);
2310
2311         if header.abi != Abi::Rust {
2312             self.word_nbsp("extern");
2313             self.word_nbsp(header.abi.to_string());
2314         }
2315
2316         self.word("fn")
2317     }
2318
2319     pub fn print_unsafety(&mut self, s: hir::Unsafety) {
2320         match s {
2321             hir::Unsafety::Normal => {}
2322             hir::Unsafety::Unsafe => self.word_nbsp("unsafe"),
2323         }
2324     }
2325
2326     pub fn print_is_auto(&mut self, s: hir::IsAuto) {
2327         match s {
2328             hir::IsAuto::Yes => self.word_nbsp("auto"),
2329             hir::IsAuto::No => {}
2330         }
2331     }
2332 }
2333
2334 /// Does this expression require a semicolon to be treated
2335 /// as a statement? The negation of this: 'can this expression
2336 /// be used as a statement without a semicolon' -- is used
2337 /// as an early-bail-out in the parser so that, for instance,
2338 ///     if true {...} else {...}
2339 ///      |x| 5
2340 /// isn't parsed as (if true {...} else {...} | x) | 5
2341 //
2342 // Duplicated from `parse::classify`, but adapted for the HIR.
2343 fn expr_requires_semi_to_be_stmt(e: &hir::Expr<'_>) -> bool {
2344     !matches!(
2345         e.kind,
2346         hir::ExprKind::If(..)
2347             | hir::ExprKind::Match(..)
2348             | hir::ExprKind::Block(..)
2349             | hir::ExprKind::Loop(..)
2350     )
2351 }
2352
2353 /// This statement requires a semicolon after it.
2354 /// note that in one case (stmt_semi), we've already
2355 /// seen the semicolon, and thus don't need another.
2356 fn stmt_ends_with_semi(stmt: &hir::StmtKind<'_>) -> bool {
2357     match *stmt {
2358         hir::StmtKind::Local(_) => true,
2359         hir::StmtKind::Item(_) => false,
2360         hir::StmtKind::Expr(e) => expr_requires_semi_to_be_stmt(e),
2361         hir::StmtKind::Semi(..) => false,
2362     }
2363 }
2364
2365 fn bin_op_to_assoc_op(op: hir::BinOpKind) -> AssocOp {
2366     use crate::hir::BinOpKind::*;
2367     match op {
2368         Add => AssocOp::Add,
2369         Sub => AssocOp::Subtract,
2370         Mul => AssocOp::Multiply,
2371         Div => AssocOp::Divide,
2372         Rem => AssocOp::Modulus,
2373
2374         And => AssocOp::LAnd,
2375         Or => AssocOp::LOr,
2376
2377         BitXor => AssocOp::BitXor,
2378         BitAnd => AssocOp::BitAnd,
2379         BitOr => AssocOp::BitOr,
2380         Shl => AssocOp::ShiftLeft,
2381         Shr => AssocOp::ShiftRight,
2382
2383         Eq => AssocOp::Equal,
2384         Lt => AssocOp::Less,
2385         Le => AssocOp::LessEqual,
2386         Ne => AssocOp::NotEqual,
2387         Ge => AssocOp::GreaterEqual,
2388         Gt => AssocOp::Greater,
2389     }
2390 }
2391
2392 /// Expressions that syntactically contain an "exterior" struct literal, i.e., not surrounded by any
2393 /// parens or other delimiters, e.g., `X { y: 1 }`, `X { y: 1 }.method()`, `foo == X { y: 1 }` and
2394 /// `X { y: 1 } == foo` all do, but `(X { y: 1 }) == foo` does not.
2395 fn contains_exterior_struct_lit(value: &hir::Expr<'_>) -> bool {
2396     match value.kind {
2397         hir::ExprKind::Struct(..) => true,
2398
2399         hir::ExprKind::Assign(lhs, rhs, _)
2400         | hir::ExprKind::AssignOp(_, lhs, rhs)
2401         | hir::ExprKind::Binary(_, lhs, rhs) => {
2402             // `X { y: 1 } + X { y: 2 }`
2403             contains_exterior_struct_lit(lhs) || contains_exterior_struct_lit(rhs)
2404         }
2405         hir::ExprKind::Unary(_, x)
2406         | hir::ExprKind::Cast(x, _)
2407         | hir::ExprKind::Type(x, _)
2408         | hir::ExprKind::Field(x, _)
2409         | hir::ExprKind::Index(x, _) => {
2410             // `&X { y: 1 }, X { y: 1 }.y`
2411             contains_exterior_struct_lit(x)
2412         }
2413
2414         hir::ExprKind::MethodCall(.., exprs, _) => {
2415             // `X { y: 1 }.bar(...)`
2416             contains_exterior_struct_lit(&exprs[0])
2417         }
2418
2419         _ => false,
2420     }
2421 }