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