]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_hir_pretty/src/lib.rs
Rollup merge of #101447 - cjgillot:no-remap-resolver, r=spastorino
[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(
1185         &mut self,
1186         segment: &hir::PathSegment<'_>,
1187         receiver: &hir::Expr<'_>,
1188         args: &[hir::Expr<'_>],
1189     ) {
1190         let base_args = args;
1191         self.print_expr_maybe_paren(&receiver, parser::PREC_POSTFIX);
1192         self.word(".");
1193         self.print_ident(segment.ident);
1194
1195         let generic_args = segment.args();
1196         if !generic_args.args.is_empty() || !generic_args.bindings.is_empty() {
1197             self.print_generic_args(generic_args, true);
1198         }
1199
1200         self.print_call_post(base_args)
1201     }
1202
1203     fn print_expr_binary(&mut self, op: hir::BinOp, lhs: &hir::Expr<'_>, rhs: &hir::Expr<'_>) {
1204         let assoc_op = bin_op_to_assoc_op(op.node);
1205         let prec = assoc_op.precedence() as i8;
1206         let fixity = assoc_op.fixity();
1207
1208         let (left_prec, right_prec) = match fixity {
1209             Fixity::Left => (prec, prec + 1),
1210             Fixity::Right => (prec + 1, prec),
1211             Fixity::None => (prec + 1, prec + 1),
1212         };
1213
1214         let left_prec = match (&lhs.kind, op.node) {
1215             // These cases need parens: `x as i32 < y` has the parser thinking that `i32 < y` is
1216             // the beginning of a path type. It starts trying to parse `x as (i32 < y ...` instead
1217             // of `(x as i32) < ...`. We need to convince it _not_ to do that.
1218             (&hir::ExprKind::Cast { .. }, hir::BinOpKind::Lt | hir::BinOpKind::Shl) => {
1219                 parser::PREC_FORCE_PAREN
1220             }
1221             (&hir::ExprKind::Let { .. }, _) if !parser::needs_par_as_let_scrutinee(prec) => {
1222                 parser::PREC_FORCE_PAREN
1223             }
1224             _ => left_prec,
1225         };
1226
1227         self.print_expr_maybe_paren(lhs, left_prec);
1228         self.space();
1229         self.word_space(op.node.as_str());
1230         self.print_expr_maybe_paren(rhs, right_prec)
1231     }
1232
1233     fn print_expr_unary(&mut self, op: hir::UnOp, expr: &hir::Expr<'_>) {
1234         self.word(op.as_str());
1235         self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1236     }
1237
1238     fn print_expr_addr_of(
1239         &mut self,
1240         kind: hir::BorrowKind,
1241         mutability: hir::Mutability,
1242         expr: &hir::Expr<'_>,
1243     ) {
1244         self.word("&");
1245         match kind {
1246             hir::BorrowKind::Ref => self.print_mutability(mutability, false),
1247             hir::BorrowKind::Raw => {
1248                 self.word_nbsp("raw");
1249                 self.print_mutability(mutability, true);
1250             }
1251         }
1252         self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1253     }
1254
1255     fn print_literal(&mut self, lit: &hir::Lit) {
1256         self.maybe_print_comment(lit.span.lo());
1257         self.word(lit.node.to_token_lit().to_string())
1258     }
1259
1260     fn print_inline_asm(&mut self, asm: &hir::InlineAsm<'_>) {
1261         enum AsmArg<'a> {
1262             Template(String),
1263             Operand(&'a hir::InlineAsmOperand<'a>),
1264             Options(ast::InlineAsmOptions),
1265         }
1266
1267         let mut args = vec![AsmArg::Template(ast::InlineAsmTemplatePiece::to_string(asm.template))];
1268         args.extend(asm.operands.iter().map(|(o, _)| AsmArg::Operand(o)));
1269         if !asm.options.is_empty() {
1270             args.push(AsmArg::Options(asm.options));
1271         }
1272
1273         self.popen();
1274         self.commasep(Consistent, &args, |s, arg| match *arg {
1275             AsmArg::Template(ref template) => s.print_string(template, ast::StrStyle::Cooked),
1276             AsmArg::Operand(op) => match *op {
1277                 hir::InlineAsmOperand::In { reg, ref expr } => {
1278                     s.word("in");
1279                     s.popen();
1280                     s.word(format!("{}", reg));
1281                     s.pclose();
1282                     s.space();
1283                     s.print_expr(expr);
1284                 }
1285                 hir::InlineAsmOperand::Out { reg, late, ref expr } => {
1286                     s.word(if late { "lateout" } else { "out" });
1287                     s.popen();
1288                     s.word(format!("{}", reg));
1289                     s.pclose();
1290                     s.space();
1291                     match expr {
1292                         Some(expr) => s.print_expr(expr),
1293                         None => s.word("_"),
1294                     }
1295                 }
1296                 hir::InlineAsmOperand::InOut { reg, late, ref expr } => {
1297                     s.word(if late { "inlateout" } else { "inout" });
1298                     s.popen();
1299                     s.word(format!("{}", reg));
1300                     s.pclose();
1301                     s.space();
1302                     s.print_expr(expr);
1303                 }
1304                 hir::InlineAsmOperand::SplitInOut { reg, late, ref in_expr, ref out_expr } => {
1305                     s.word(if late { "inlateout" } else { "inout" });
1306                     s.popen();
1307                     s.word(format!("{}", reg));
1308                     s.pclose();
1309                     s.space();
1310                     s.print_expr(in_expr);
1311                     s.space();
1312                     s.word_space("=>");
1313                     match out_expr {
1314                         Some(out_expr) => s.print_expr(out_expr),
1315                         None => s.word("_"),
1316                     }
1317                 }
1318                 hir::InlineAsmOperand::Const { ref anon_const } => {
1319                     s.word("const");
1320                     s.space();
1321                     s.print_anon_const(anon_const);
1322                 }
1323                 hir::InlineAsmOperand::SymFn { ref anon_const } => {
1324                     s.word("sym_fn");
1325                     s.space();
1326                     s.print_anon_const(anon_const);
1327                 }
1328                 hir::InlineAsmOperand::SymStatic { ref path, def_id: _ } => {
1329                     s.word("sym_static");
1330                     s.space();
1331                     s.print_qpath(path, true);
1332                 }
1333             },
1334             AsmArg::Options(opts) => {
1335                 s.word("options");
1336                 s.popen();
1337                 let mut options = vec![];
1338                 if opts.contains(ast::InlineAsmOptions::PURE) {
1339                     options.push("pure");
1340                 }
1341                 if opts.contains(ast::InlineAsmOptions::NOMEM) {
1342                     options.push("nomem");
1343                 }
1344                 if opts.contains(ast::InlineAsmOptions::READONLY) {
1345                     options.push("readonly");
1346                 }
1347                 if opts.contains(ast::InlineAsmOptions::PRESERVES_FLAGS) {
1348                     options.push("preserves_flags");
1349                 }
1350                 if opts.contains(ast::InlineAsmOptions::NORETURN) {
1351                     options.push("noreturn");
1352                 }
1353                 if opts.contains(ast::InlineAsmOptions::NOSTACK) {
1354                     options.push("nostack");
1355                 }
1356                 if opts.contains(ast::InlineAsmOptions::ATT_SYNTAX) {
1357                     options.push("att_syntax");
1358                 }
1359                 if opts.contains(ast::InlineAsmOptions::RAW) {
1360                     options.push("raw");
1361                 }
1362                 if opts.contains(ast::InlineAsmOptions::MAY_UNWIND) {
1363                     options.push("may_unwind");
1364                 }
1365                 s.commasep(Inconsistent, &options, |s, &opt| {
1366                     s.word(opt);
1367                 });
1368                 s.pclose();
1369             }
1370         });
1371         self.pclose();
1372     }
1373
1374     pub fn print_expr(&mut self, expr: &hir::Expr<'_>) {
1375         self.maybe_print_comment(expr.span.lo());
1376         self.print_outer_attributes(self.attrs(expr.hir_id));
1377         self.ibox(INDENT_UNIT);
1378         self.ann.pre(self, AnnNode::Expr(expr));
1379         match expr.kind {
1380             hir::ExprKind::Box(expr) => {
1381                 self.word_space("box");
1382                 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX);
1383             }
1384             hir::ExprKind::Array(exprs) => {
1385                 self.print_expr_vec(exprs);
1386             }
1387             hir::ExprKind::ConstBlock(ref anon_const) => {
1388                 self.print_expr_anon_const(anon_const);
1389             }
1390             hir::ExprKind::Repeat(element, ref count) => {
1391                 self.print_expr_repeat(element, count);
1392             }
1393             hir::ExprKind::Struct(qpath, fields, wth) => {
1394                 self.print_expr_struct(qpath, fields, wth);
1395             }
1396             hir::ExprKind::Tup(exprs) => {
1397                 self.print_expr_tup(exprs);
1398             }
1399             hir::ExprKind::Call(func, args) => {
1400                 self.print_expr_call(func, args);
1401             }
1402             hir::ExprKind::MethodCall(segment, receiver, args, _) => {
1403                 self.print_expr_method_call(segment, receiver, args);
1404             }
1405             hir::ExprKind::Binary(op, lhs, rhs) => {
1406                 self.print_expr_binary(op, lhs, rhs);
1407             }
1408             hir::ExprKind::Unary(op, expr) => {
1409                 self.print_expr_unary(op, expr);
1410             }
1411             hir::ExprKind::AddrOf(k, m, expr) => {
1412                 self.print_expr_addr_of(k, m, expr);
1413             }
1414             hir::ExprKind::Lit(ref lit) => {
1415                 self.print_literal(lit);
1416             }
1417             hir::ExprKind::Cast(expr, ty) => {
1418                 let prec = AssocOp::As.precedence() as i8;
1419                 self.print_expr_maybe_paren(expr, prec);
1420                 self.space();
1421                 self.word_space("as");
1422                 self.print_type(ty);
1423             }
1424             hir::ExprKind::Type(expr, ty) => {
1425                 let prec = AssocOp::Colon.precedence() as i8;
1426                 self.print_expr_maybe_paren(expr, prec);
1427                 self.word_space(":");
1428                 self.print_type(ty);
1429             }
1430             hir::ExprKind::DropTemps(init) => {
1431                 // Print `{`:
1432                 self.cbox(INDENT_UNIT);
1433                 self.ibox(0);
1434                 self.bopen();
1435
1436                 // Print `let _t = $init;`:
1437                 let temp = Ident::from_str("_t");
1438                 self.print_local(Some(init), None, |this| this.print_ident(temp));
1439                 self.word(";");
1440
1441                 // Print `_t`:
1442                 self.space_if_not_bol();
1443                 self.print_ident(temp);
1444
1445                 // Print `}`:
1446                 self.bclose_maybe_open(expr.span, true);
1447             }
1448             hir::ExprKind::Let(&hir::Let { pat, ty, init, .. }) => {
1449                 self.print_let(pat, ty, init);
1450             }
1451             hir::ExprKind::If(test, blk, elseopt) => {
1452                 self.print_if(test, blk, elseopt);
1453             }
1454             hir::ExprKind::Loop(blk, opt_label, _, _) => {
1455                 if let Some(label) = opt_label {
1456                     self.print_ident(label.ident);
1457                     self.word_space(":");
1458                 }
1459                 self.head("loop");
1460                 self.print_block(blk);
1461             }
1462             hir::ExprKind::Match(expr, arms, _) => {
1463                 self.cbox(INDENT_UNIT);
1464                 self.ibox(INDENT_UNIT);
1465                 self.word_nbsp("match");
1466                 self.print_expr_as_cond(expr);
1467                 self.space();
1468                 self.bopen();
1469                 for arm in arms {
1470                     self.print_arm(arm);
1471                 }
1472                 self.bclose(expr.span);
1473             }
1474             hir::ExprKind::Closure(&hir::Closure {
1475                 binder,
1476                 capture_clause,
1477                 bound_generic_params,
1478                 fn_decl,
1479                 body,
1480                 fn_decl_span: _,
1481                 movability: _,
1482             }) => {
1483                 self.print_closure_binder(binder, bound_generic_params);
1484                 self.print_capture_clause(capture_clause);
1485
1486                 self.print_closure_params(fn_decl, body);
1487                 self.space();
1488
1489                 // This is a bare expression.
1490                 self.ann.nested(self, Nested::Body(body));
1491                 self.end(); // need to close a box
1492
1493                 // A box will be closed by `print_expr`, but we didn't want an overall
1494                 // wrapper so we closed the corresponding opening. so create an
1495                 // empty box to satisfy the close.
1496                 self.ibox(0);
1497             }
1498             hir::ExprKind::Block(blk, opt_label) => {
1499                 if let Some(label) = opt_label {
1500                     self.print_ident(label.ident);
1501                     self.word_space(":");
1502                 }
1503                 // containing cbox, will be closed by print-block at `}`
1504                 self.cbox(INDENT_UNIT);
1505                 // head-box, will be closed by print-block after `{`
1506                 self.ibox(0);
1507                 self.print_block(blk);
1508             }
1509             hir::ExprKind::Assign(lhs, rhs, _) => {
1510                 let prec = AssocOp::Assign.precedence() as i8;
1511                 self.print_expr_maybe_paren(lhs, prec + 1);
1512                 self.space();
1513                 self.word_space("=");
1514                 self.print_expr_maybe_paren(rhs, prec);
1515             }
1516             hir::ExprKind::AssignOp(op, lhs, rhs) => {
1517                 let prec = AssocOp::Assign.precedence() as i8;
1518                 self.print_expr_maybe_paren(lhs, prec + 1);
1519                 self.space();
1520                 self.word(op.node.as_str());
1521                 self.word_space("=");
1522                 self.print_expr_maybe_paren(rhs, prec);
1523             }
1524             hir::ExprKind::Field(expr, ident) => {
1525                 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
1526                 self.word(".");
1527                 self.print_ident(ident);
1528             }
1529             hir::ExprKind::Index(expr, index) => {
1530                 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
1531                 self.word("[");
1532                 self.print_expr(index);
1533                 self.word("]");
1534             }
1535             hir::ExprKind::Path(ref qpath) => self.print_qpath(qpath, true),
1536             hir::ExprKind::Break(destination, opt_expr) => {
1537                 self.word("break");
1538                 if let Some(label) = destination.label {
1539                     self.space();
1540                     self.print_ident(label.ident);
1541                 }
1542                 if let Some(expr) = opt_expr {
1543                     self.space();
1544                     self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
1545                 }
1546             }
1547             hir::ExprKind::Continue(destination) => {
1548                 self.word("continue");
1549                 if let Some(label) = destination.label {
1550                     self.space();
1551                     self.print_ident(label.ident);
1552                 }
1553             }
1554             hir::ExprKind::Ret(result) => {
1555                 self.word("return");
1556                 if let Some(expr) = result {
1557                     self.word(" ");
1558                     self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
1559                 }
1560             }
1561             hir::ExprKind::InlineAsm(asm) => {
1562                 self.word("asm!");
1563                 self.print_inline_asm(asm);
1564             }
1565             hir::ExprKind::Yield(expr, _) => {
1566                 self.word_space("yield");
1567                 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
1568             }
1569             hir::ExprKind::Err => {
1570                 self.popen();
1571                 self.word("/*ERROR*/");
1572                 self.pclose();
1573             }
1574         }
1575         self.ann.post(self, AnnNode::Expr(expr));
1576         self.end()
1577     }
1578
1579     pub fn print_local_decl(&mut self, loc: &hir::Local<'_>) {
1580         self.print_pat(loc.pat);
1581         if let Some(ty) = loc.ty {
1582             self.word_space(":");
1583             self.print_type(ty);
1584         }
1585     }
1586
1587     pub fn print_name(&mut self, name: Symbol) {
1588         self.print_ident(Ident::with_dummy_span(name))
1589     }
1590
1591     pub fn print_path(&mut self, path: &hir::Path<'_>, colons_before_params: bool) {
1592         self.maybe_print_comment(path.span.lo());
1593
1594         for (i, segment) in path.segments.iter().enumerate() {
1595             if i > 0 {
1596                 self.word("::")
1597             }
1598             if segment.ident.name != kw::PathRoot {
1599                 self.print_ident(segment.ident);
1600                 self.print_generic_args(segment.args(), colons_before_params);
1601             }
1602         }
1603     }
1604
1605     pub fn print_path_segment(&mut self, segment: &hir::PathSegment<'_>) {
1606         if segment.ident.name != kw::PathRoot {
1607             self.print_ident(segment.ident);
1608             self.print_generic_args(segment.args(), false);
1609         }
1610     }
1611
1612     pub fn print_qpath(&mut self, qpath: &hir::QPath<'_>, colons_before_params: bool) {
1613         match *qpath {
1614             hir::QPath::Resolved(None, path) => self.print_path(path, colons_before_params),
1615             hir::QPath::Resolved(Some(qself), path) => {
1616                 self.word("<");
1617                 self.print_type(qself);
1618                 self.space();
1619                 self.word_space("as");
1620
1621                 for (i, segment) in path.segments[..path.segments.len() - 1].iter().enumerate() {
1622                     if i > 0 {
1623                         self.word("::")
1624                     }
1625                     if segment.ident.name != kw::PathRoot {
1626                         self.print_ident(segment.ident);
1627                         self.print_generic_args(segment.args(), colons_before_params);
1628                     }
1629                 }
1630
1631                 self.word(">");
1632                 self.word("::");
1633                 let item_segment = path.segments.last().unwrap();
1634                 self.print_ident(item_segment.ident);
1635                 self.print_generic_args(item_segment.args(), colons_before_params)
1636             }
1637             hir::QPath::TypeRelative(qself, item_segment) => {
1638                 // If we've got a compound-qualified-path, let's push an additional pair of angle
1639                 // brackets, so that we pretty-print `<<A::B>::C>` as `<A::B>::C`, instead of just
1640                 // `A::B::C` (since the latter could be ambiguous to the user)
1641                 if let hir::TyKind::Path(hir::QPath::Resolved(None, _)) = qself.kind {
1642                     self.print_type(qself);
1643                 } else {
1644                     self.word("<");
1645                     self.print_type(qself);
1646                     self.word(">");
1647                 }
1648
1649                 self.word("::");
1650                 self.print_ident(item_segment.ident);
1651                 self.print_generic_args(item_segment.args(), colons_before_params)
1652             }
1653             hir::QPath::LangItem(lang_item, span, _) => {
1654                 self.word("#[lang = \"");
1655                 self.print_ident(Ident::new(lang_item.name(), span));
1656                 self.word("\"]");
1657             }
1658         }
1659     }
1660
1661     fn print_generic_args(
1662         &mut self,
1663         generic_args: &hir::GenericArgs<'_>,
1664         colons_before_params: bool,
1665     ) {
1666         if generic_args.parenthesized {
1667             self.word("(");
1668             self.commasep(Inconsistent, generic_args.inputs(), |s, ty| s.print_type(ty));
1669             self.word(")");
1670
1671             self.space_if_not_bol();
1672             self.word_space("->");
1673             self.print_type(generic_args.bindings[0].ty());
1674         } else {
1675             let start = if colons_before_params { "::<" } else { "<" };
1676             let empty = Cell::new(true);
1677             let start_or_comma = |this: &mut Self| {
1678                 if empty.get() {
1679                     empty.set(false);
1680                     this.word(start)
1681                 } else {
1682                     this.word_space(",")
1683                 }
1684             };
1685
1686             let mut nonelided_generic_args: bool = false;
1687             let elide_lifetimes = generic_args.args.iter().all(|arg| match arg {
1688                 GenericArg::Lifetime(lt) => lt.is_elided(),
1689                 _ => {
1690                     nonelided_generic_args = true;
1691                     true
1692                 }
1693             });
1694
1695             if nonelided_generic_args {
1696                 start_or_comma(self);
1697                 self.commasep(
1698                     Inconsistent,
1699                     generic_args.args,
1700                     |s, generic_arg| match generic_arg {
1701                         GenericArg::Lifetime(lt) if !elide_lifetimes => s.print_lifetime(lt),
1702                         GenericArg::Lifetime(_) => {}
1703                         GenericArg::Type(ty) => s.print_type(ty),
1704                         GenericArg::Const(ct) => s.print_anon_const(&ct.value),
1705                         GenericArg::Infer(_inf) => s.word("_"),
1706                     },
1707                 );
1708             }
1709
1710             for binding in generic_args.bindings {
1711                 start_or_comma(self);
1712                 self.print_type_binding(binding);
1713             }
1714
1715             if !empty.get() {
1716                 self.word(">")
1717             }
1718         }
1719     }
1720
1721     pub fn print_type_binding(&mut self, binding: &hir::TypeBinding<'_>) {
1722         self.print_ident(binding.ident);
1723         self.print_generic_args(binding.gen_args, false);
1724         self.space();
1725         match binding.kind {
1726             hir::TypeBindingKind::Equality { ref term } => {
1727                 self.word_space("=");
1728                 match term {
1729                     Term::Ty(ty) => self.print_type(ty),
1730                     Term::Const(ref c) => self.print_anon_const(c),
1731                 }
1732             }
1733             hir::TypeBindingKind::Constraint { bounds } => {
1734                 self.print_bounds(":", bounds);
1735             }
1736         }
1737     }
1738
1739     pub fn print_pat(&mut self, pat: &hir::Pat<'_>) {
1740         self.maybe_print_comment(pat.span.lo());
1741         self.ann.pre(self, AnnNode::Pat(pat));
1742         // Pat isn't normalized, but the beauty of it
1743         // is that it doesn't matter
1744         match pat.kind {
1745             PatKind::Wild => self.word("_"),
1746             PatKind::Binding(binding_mode, _, ident, sub) => {
1747                 match binding_mode {
1748                     hir::BindingAnnotation::Ref => {
1749                         self.word_nbsp("ref");
1750                         self.print_mutability(hir::Mutability::Not, false);
1751                     }
1752                     hir::BindingAnnotation::RefMut => {
1753                         self.word_nbsp("ref");
1754                         self.print_mutability(hir::Mutability::Mut, false);
1755                     }
1756                     hir::BindingAnnotation::Unannotated => {}
1757                     hir::BindingAnnotation::Mutable => {
1758                         self.word_nbsp("mut");
1759                     }
1760                 }
1761                 self.print_ident(ident);
1762                 if let Some(p) = sub {
1763                     self.word("@");
1764                     self.print_pat(p);
1765                 }
1766             }
1767             PatKind::TupleStruct(ref qpath, elts, ddpos) => {
1768                 self.print_qpath(qpath, true);
1769                 self.popen();
1770                 if let Some(ddpos) = ddpos {
1771                     self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(p));
1772                     if ddpos != 0 {
1773                         self.word_space(",");
1774                     }
1775                     self.word("..");
1776                     if ddpos != elts.len() {
1777                         self.word(",");
1778                         self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(p));
1779                     }
1780                 } else {
1781                     self.commasep(Inconsistent, elts, |s, p| s.print_pat(p));
1782                 }
1783                 self.pclose();
1784             }
1785             PatKind::Path(ref qpath) => {
1786                 self.print_qpath(qpath, true);
1787             }
1788             PatKind::Struct(ref qpath, fields, etc) => {
1789                 self.print_qpath(qpath, true);
1790                 self.nbsp();
1791                 self.word("{");
1792                 let empty = fields.is_empty() && !etc;
1793                 if !empty {
1794                     self.space();
1795                 }
1796                 self.commasep_cmnt(Consistent, &fields, |s, f| s.print_patfield(f), |f| f.pat.span);
1797                 if etc {
1798                     if !fields.is_empty() {
1799                         self.word_space(",");
1800                     }
1801                     self.word("..");
1802                 }
1803                 if !empty {
1804                     self.space();
1805                 }
1806                 self.word("}");
1807             }
1808             PatKind::Or(pats) => {
1809                 self.strsep("|", true, Inconsistent, pats, |s, p| s.print_pat(p));
1810             }
1811             PatKind::Tuple(elts, ddpos) => {
1812                 self.popen();
1813                 if let Some(ddpos) = ddpos {
1814                     self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(p));
1815                     if ddpos != 0 {
1816                         self.word_space(",");
1817                     }
1818                     self.word("..");
1819                     if ddpos != elts.len() {
1820                         self.word(",");
1821                         self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(p));
1822                     }
1823                 } else {
1824                     self.commasep(Inconsistent, elts, |s, p| s.print_pat(p));
1825                     if elts.len() == 1 {
1826                         self.word(",");
1827                     }
1828                 }
1829                 self.pclose();
1830             }
1831             PatKind::Box(inner) => {
1832                 let is_range_inner = matches!(inner.kind, PatKind::Range(..));
1833                 self.word("box ");
1834                 if is_range_inner {
1835                     self.popen();
1836                 }
1837                 self.print_pat(inner);
1838                 if is_range_inner {
1839                     self.pclose();
1840                 }
1841             }
1842             PatKind::Ref(inner, mutbl) => {
1843                 let is_range_inner = matches!(inner.kind, PatKind::Range(..));
1844                 self.word("&");
1845                 self.word(mutbl.prefix_str());
1846                 if is_range_inner {
1847                     self.popen();
1848                 }
1849                 self.print_pat(inner);
1850                 if is_range_inner {
1851                     self.pclose();
1852                 }
1853             }
1854             PatKind::Lit(e) => self.print_expr(e),
1855             PatKind::Range(begin, end, end_kind) => {
1856                 if let Some(expr) = begin {
1857                     self.print_expr(expr);
1858                 }
1859                 match end_kind {
1860                     RangeEnd::Included => self.word("..."),
1861                     RangeEnd::Excluded => self.word(".."),
1862                 }
1863                 if let Some(expr) = end {
1864                     self.print_expr(expr);
1865                 }
1866             }
1867             PatKind::Slice(before, slice, after) => {
1868                 self.word("[");
1869                 self.commasep(Inconsistent, before, |s, p| s.print_pat(p));
1870                 if let Some(p) = slice {
1871                     if !before.is_empty() {
1872                         self.word_space(",");
1873                     }
1874                     if let PatKind::Wild = p.kind {
1875                         // Print nothing.
1876                     } else {
1877                         self.print_pat(p);
1878                     }
1879                     self.word("..");
1880                     if !after.is_empty() {
1881                         self.word_space(",");
1882                     }
1883                 }
1884                 self.commasep(Inconsistent, after, |s, p| s.print_pat(p));
1885                 self.word("]");
1886             }
1887         }
1888         self.ann.post(self, AnnNode::Pat(pat))
1889     }
1890
1891     pub fn print_patfield(&mut self, field: &hir::PatField<'_>) {
1892         if self.attrs(field.hir_id).is_empty() {
1893             self.space();
1894         }
1895         self.cbox(INDENT_UNIT);
1896         self.print_outer_attributes(&self.attrs(field.hir_id));
1897         if !field.is_shorthand {
1898             self.print_ident(field.ident);
1899             self.word_nbsp(":");
1900         }
1901         self.print_pat(field.pat);
1902         self.end();
1903     }
1904
1905     pub fn print_param(&mut self, arg: &hir::Param<'_>) {
1906         self.print_outer_attributes(self.attrs(arg.hir_id));
1907         self.print_pat(arg.pat);
1908     }
1909
1910     pub fn print_arm(&mut self, arm: &hir::Arm<'_>) {
1911         // I have no idea why this check is necessary, but here it
1912         // is :(
1913         if self.attrs(arm.hir_id).is_empty() {
1914             self.space();
1915         }
1916         self.cbox(INDENT_UNIT);
1917         self.ann.pre(self, AnnNode::Arm(arm));
1918         self.ibox(0);
1919         self.print_outer_attributes(self.attrs(arm.hir_id));
1920         self.print_pat(arm.pat);
1921         self.space();
1922         if let Some(ref g) = arm.guard {
1923             match *g {
1924                 hir::Guard::If(e) => {
1925                     self.word_space("if");
1926                     self.print_expr(e);
1927                     self.space();
1928                 }
1929                 hir::Guard::IfLet(&hir::Let { pat, ty, init, .. }) => {
1930                     self.word_nbsp("if");
1931                     self.print_let(pat, ty, init);
1932                 }
1933             }
1934         }
1935         self.word_space("=>");
1936
1937         match arm.body.kind {
1938             hir::ExprKind::Block(blk, opt_label) => {
1939                 if let Some(label) = opt_label {
1940                     self.print_ident(label.ident);
1941                     self.word_space(":");
1942                 }
1943                 // the block will close the pattern's ibox
1944                 self.print_block_unclosed(blk);
1945
1946                 // If it is a user-provided unsafe block, print a comma after it
1947                 if let hir::BlockCheckMode::UnsafeBlock(hir::UnsafeSource::UserProvided) = blk.rules
1948                 {
1949                     self.word(",");
1950                 }
1951             }
1952             _ => {
1953                 self.end(); // close the ibox for the pattern
1954                 self.print_expr(arm.body);
1955                 self.word(",");
1956             }
1957         }
1958         self.ann.post(self, AnnNode::Arm(arm));
1959         self.end() // close enclosing cbox
1960     }
1961
1962     pub fn print_fn(
1963         &mut self,
1964         decl: &hir::FnDecl<'_>,
1965         header: hir::FnHeader,
1966         name: Option<Symbol>,
1967         generics: &hir::Generics<'_>,
1968         arg_names: &[Ident],
1969         body_id: Option<hir::BodyId>,
1970     ) {
1971         self.print_fn_header_info(header);
1972
1973         if let Some(name) = name {
1974             self.nbsp();
1975             self.print_name(name);
1976         }
1977         self.print_generic_params(generics.params);
1978
1979         self.popen();
1980         let mut i = 0;
1981         // Make sure we aren't supplied *both* `arg_names` and `body_id`.
1982         assert!(arg_names.is_empty() || body_id.is_none());
1983         self.commasep(Inconsistent, decl.inputs, |s, ty| {
1984             s.ibox(INDENT_UNIT);
1985             if let Some(arg_name) = arg_names.get(i) {
1986                 s.word(arg_name.to_string());
1987                 s.word(":");
1988                 s.space();
1989             } else if let Some(body_id) = body_id {
1990                 s.ann.nested(s, Nested::BodyParamPat(body_id, i));
1991                 s.word(":");
1992                 s.space();
1993             }
1994             i += 1;
1995             s.print_type(ty);
1996             s.end()
1997         });
1998         if decl.c_variadic {
1999             self.word(", ...");
2000         }
2001         self.pclose();
2002
2003         self.print_fn_output(decl);
2004         self.print_where_clause(generics)
2005     }
2006
2007     fn print_closure_params(&mut self, decl: &hir::FnDecl<'_>, body_id: hir::BodyId) {
2008         self.word("|");
2009         let mut i = 0;
2010         self.commasep(Inconsistent, decl.inputs, |s, ty| {
2011             s.ibox(INDENT_UNIT);
2012
2013             s.ann.nested(s, Nested::BodyParamPat(body_id, i));
2014             i += 1;
2015
2016             if let hir::TyKind::Infer = ty.kind {
2017                 // Print nothing.
2018             } else {
2019                 s.word(":");
2020                 s.space();
2021                 s.print_type(ty);
2022             }
2023             s.end();
2024         });
2025         self.word("|");
2026
2027         if let hir::FnRetTy::DefaultReturn(..) = decl.output {
2028             return;
2029         }
2030
2031         self.space_if_not_bol();
2032         self.word_space("->");
2033         match decl.output {
2034             hir::FnRetTy::Return(ty) => {
2035                 self.print_type(ty);
2036                 self.maybe_print_comment(ty.span.lo());
2037             }
2038             hir::FnRetTy::DefaultReturn(..) => unreachable!(),
2039         }
2040     }
2041
2042     pub fn print_capture_clause(&mut self, capture_clause: hir::CaptureBy) {
2043         match capture_clause {
2044             hir::CaptureBy::Value => self.word_space("move"),
2045             hir::CaptureBy::Ref => {}
2046         }
2047     }
2048
2049     pub fn print_closure_binder(
2050         &mut self,
2051         binder: hir::ClosureBinder,
2052         generic_params: &[GenericParam<'_>],
2053     ) {
2054         let generic_params = generic_params
2055             .iter()
2056             .filter(|p| {
2057                 matches!(
2058                     p,
2059                     GenericParam {
2060                         kind: GenericParamKind::Lifetime { kind: LifetimeParamKind::Explicit },
2061                         ..
2062                     }
2063                 )
2064             })
2065             .collect::<Vec<_>>();
2066
2067         match binder {
2068             hir::ClosureBinder::Default => {}
2069             // we need to distinguish `|...| {}` from `for<> |...| {}` as `for<>` adds additional restrictions
2070             hir::ClosureBinder::For { .. } if generic_params.is_empty() => self.word("for<>"),
2071             hir::ClosureBinder::For { .. } => {
2072                 self.word("for");
2073                 self.word("<");
2074
2075                 self.commasep(Inconsistent, &generic_params, |s, param| {
2076                     s.print_generic_param(param)
2077                 });
2078
2079                 self.word(">");
2080                 self.nbsp();
2081             }
2082         }
2083     }
2084
2085     pub fn print_bounds<'b>(
2086         &mut self,
2087         prefix: &'static str,
2088         bounds: impl IntoIterator<Item = &'b hir::GenericBound<'b>>,
2089     ) {
2090         let mut first = true;
2091         for bound in bounds {
2092             if first {
2093                 self.word(prefix);
2094             }
2095             if !(first && prefix.is_empty()) {
2096                 self.nbsp();
2097             }
2098             if first {
2099                 first = false;
2100             } else {
2101                 self.word_space("+");
2102             }
2103
2104             match bound {
2105                 GenericBound::Trait(tref, modifier) => {
2106                     if modifier == &TraitBoundModifier::Maybe {
2107                         self.word("?");
2108                     }
2109                     self.print_poly_trait_ref(tref);
2110                 }
2111                 GenericBound::LangItemTrait(lang_item, span, ..) => {
2112                     self.word("#[lang = \"");
2113                     self.print_ident(Ident::new(lang_item.name(), *span));
2114                     self.word("\"]");
2115                 }
2116                 GenericBound::Outlives(lt) => {
2117                     self.print_lifetime(lt);
2118                 }
2119             }
2120         }
2121     }
2122
2123     pub fn print_generic_params(&mut self, generic_params: &[GenericParam<'_>]) {
2124         if !generic_params.is_empty() {
2125             self.word("<");
2126
2127             self.commasep(Inconsistent, generic_params, |s, param| s.print_generic_param(param));
2128
2129             self.word(">");
2130         }
2131     }
2132
2133     pub fn print_generic_param(&mut self, param: &GenericParam<'_>) {
2134         if let GenericParamKind::Const { .. } = param.kind {
2135             self.word_space("const");
2136         }
2137
2138         self.print_ident(param.name.ident());
2139
2140         match param.kind {
2141             GenericParamKind::Lifetime { .. } => {}
2142             GenericParamKind::Type { default, .. } => {
2143                 if let Some(default) = default {
2144                     self.space();
2145                     self.word_space("=");
2146                     self.print_type(default);
2147                 }
2148             }
2149             GenericParamKind::Const { ty, ref default } => {
2150                 self.word_space(":");
2151                 self.print_type(ty);
2152                 if let Some(default) = default {
2153                     self.space();
2154                     self.word_space("=");
2155                     self.print_anon_const(default);
2156                 }
2157             }
2158         }
2159     }
2160
2161     pub fn print_lifetime(&mut self, lifetime: &hir::Lifetime) {
2162         self.print_ident(lifetime.name.ident())
2163     }
2164
2165     pub fn print_where_clause(&mut self, generics: &hir::Generics<'_>) {
2166         if generics.predicates.is_empty() {
2167             return;
2168         }
2169
2170         self.space();
2171         self.word_space("where");
2172
2173         for (i, predicate) in generics.predicates.iter().enumerate() {
2174             if i != 0 {
2175                 self.word_space(",");
2176             }
2177
2178             match *predicate {
2179                 hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
2180                     bound_generic_params,
2181                     bounded_ty,
2182                     bounds,
2183                     ..
2184                 }) => {
2185                     self.print_formal_generic_params(bound_generic_params);
2186                     self.print_type(bounded_ty);
2187                     self.print_bounds(":", bounds);
2188                 }
2189                 hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
2190                     ref lifetime,
2191                     bounds,
2192                     ..
2193                 }) => {
2194                     self.print_lifetime(lifetime);
2195                     self.word(":");
2196
2197                     for (i, bound) in bounds.iter().enumerate() {
2198                         match bound {
2199                             GenericBound::Outlives(lt) => {
2200                                 self.print_lifetime(lt);
2201                             }
2202                             _ => panic!(),
2203                         }
2204
2205                         if i != 0 {
2206                             self.word(":");
2207                         }
2208                     }
2209                 }
2210                 hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
2211                     lhs_ty, rhs_ty, ..
2212                 }) => {
2213                     self.print_type(lhs_ty);
2214                     self.space();
2215                     self.word_space("=");
2216                     self.print_type(rhs_ty);
2217                 }
2218             }
2219         }
2220     }
2221
2222     pub fn print_mutability(&mut self, mutbl: hir::Mutability, print_const: bool) {
2223         match mutbl {
2224             hir::Mutability::Mut => self.word_nbsp("mut"),
2225             hir::Mutability::Not => {
2226                 if print_const {
2227                     self.word_nbsp("const")
2228                 }
2229             }
2230         }
2231     }
2232
2233     pub fn print_mt(&mut self, mt: &hir::MutTy<'_>, print_const: bool) {
2234         self.print_mutability(mt.mutbl, print_const);
2235         self.print_type(mt.ty);
2236     }
2237
2238     pub fn print_fn_output(&mut self, decl: &hir::FnDecl<'_>) {
2239         if let hir::FnRetTy::DefaultReturn(..) = decl.output {
2240             return;
2241         }
2242
2243         self.space_if_not_bol();
2244         self.ibox(INDENT_UNIT);
2245         self.word_space("->");
2246         match decl.output {
2247             hir::FnRetTy::DefaultReturn(..) => unreachable!(),
2248             hir::FnRetTy::Return(ty) => self.print_type(ty),
2249         }
2250         self.end();
2251
2252         if let hir::FnRetTy::Return(output) = decl.output {
2253             self.maybe_print_comment(output.span.lo());
2254         }
2255     }
2256
2257     pub fn print_ty_fn(
2258         &mut self,
2259         abi: Abi,
2260         unsafety: hir::Unsafety,
2261         decl: &hir::FnDecl<'_>,
2262         name: Option<Symbol>,
2263         generic_params: &[hir::GenericParam<'_>],
2264         arg_names: &[Ident],
2265     ) {
2266         self.ibox(INDENT_UNIT);
2267         self.print_formal_generic_params(generic_params);
2268         let generics = hir::Generics::empty();
2269         self.print_fn(
2270             decl,
2271             hir::FnHeader {
2272                 unsafety,
2273                 abi,
2274                 constness: hir::Constness::NotConst,
2275                 asyncness: hir::IsAsync::NotAsync,
2276             },
2277             name,
2278             generics,
2279             arg_names,
2280             None,
2281         );
2282         self.end();
2283     }
2284
2285     pub fn print_fn_header_info(&mut self, header: hir::FnHeader) {
2286         match header.constness {
2287             hir::Constness::NotConst => {}
2288             hir::Constness::Const => self.word_nbsp("const"),
2289         }
2290
2291         match header.asyncness {
2292             hir::IsAsync::NotAsync => {}
2293             hir::IsAsync::Async => self.word_nbsp("async"),
2294         }
2295
2296         self.print_unsafety(header.unsafety);
2297
2298         if header.abi != Abi::Rust {
2299             self.word_nbsp("extern");
2300             self.word_nbsp(header.abi.to_string());
2301         }
2302
2303         self.word("fn")
2304     }
2305
2306     pub fn print_unsafety(&mut self, s: hir::Unsafety) {
2307         match s {
2308             hir::Unsafety::Normal => {}
2309             hir::Unsafety::Unsafe => self.word_nbsp("unsafe"),
2310         }
2311     }
2312
2313     pub fn print_is_auto(&mut self, s: hir::IsAuto) {
2314         match s {
2315             hir::IsAuto::Yes => self.word_nbsp("auto"),
2316             hir::IsAuto::No => {}
2317         }
2318     }
2319 }
2320
2321 /// Does this expression require a semicolon to be treated
2322 /// as a statement? The negation of this: 'can this expression
2323 /// be used as a statement without a semicolon' -- is used
2324 /// as an early-bail-out in the parser so that, for instance,
2325 ///     if true {...} else {...}
2326 ///      |x| 5
2327 /// isn't parsed as (if true {...} else {...} | x) | 5
2328 //
2329 // Duplicated from `parse::classify`, but adapted for the HIR.
2330 fn expr_requires_semi_to_be_stmt(e: &hir::Expr<'_>) -> bool {
2331     !matches!(
2332         e.kind,
2333         hir::ExprKind::If(..)
2334             | hir::ExprKind::Match(..)
2335             | hir::ExprKind::Block(..)
2336             | hir::ExprKind::Loop(..)
2337     )
2338 }
2339
2340 /// This statement requires a semicolon after it.
2341 /// note that in one case (stmt_semi), we've already
2342 /// seen the semicolon, and thus don't need another.
2343 fn stmt_ends_with_semi(stmt: &hir::StmtKind<'_>) -> bool {
2344     match *stmt {
2345         hir::StmtKind::Local(_) => true,
2346         hir::StmtKind::Item(_) => false,
2347         hir::StmtKind::Expr(e) => expr_requires_semi_to_be_stmt(e),
2348         hir::StmtKind::Semi(..) => false,
2349     }
2350 }
2351
2352 fn bin_op_to_assoc_op(op: hir::BinOpKind) -> AssocOp {
2353     use crate::hir::BinOpKind::*;
2354     match op {
2355         Add => AssocOp::Add,
2356         Sub => AssocOp::Subtract,
2357         Mul => AssocOp::Multiply,
2358         Div => AssocOp::Divide,
2359         Rem => AssocOp::Modulus,
2360
2361         And => AssocOp::LAnd,
2362         Or => AssocOp::LOr,
2363
2364         BitXor => AssocOp::BitXor,
2365         BitAnd => AssocOp::BitAnd,
2366         BitOr => AssocOp::BitOr,
2367         Shl => AssocOp::ShiftLeft,
2368         Shr => AssocOp::ShiftRight,
2369
2370         Eq => AssocOp::Equal,
2371         Lt => AssocOp::Less,
2372         Le => AssocOp::LessEqual,
2373         Ne => AssocOp::NotEqual,
2374         Ge => AssocOp::GreaterEqual,
2375         Gt => AssocOp::Greater,
2376     }
2377 }
2378
2379 /// Expressions that syntactically contain an "exterior" struct literal, i.e., not surrounded by any
2380 /// parens or other delimiters, e.g., `X { y: 1 }`, `X { y: 1 }.method()`, `foo == X { y: 1 }` and
2381 /// `X { y: 1 } == foo` all do, but `(X { y: 1 }) == foo` does not.
2382 fn contains_exterior_struct_lit(value: &hir::Expr<'_>) -> bool {
2383     match value.kind {
2384         hir::ExprKind::Struct(..) => true,
2385
2386         hir::ExprKind::Assign(lhs, rhs, _)
2387         | hir::ExprKind::AssignOp(_, lhs, rhs)
2388         | hir::ExprKind::Binary(_, lhs, rhs) => {
2389             // `X { y: 1 } + X { y: 2 }`
2390             contains_exterior_struct_lit(lhs) || contains_exterior_struct_lit(rhs)
2391         }
2392         hir::ExprKind::Unary(_, x)
2393         | hir::ExprKind::Cast(x, _)
2394         | hir::ExprKind::Type(x, _)
2395         | hir::ExprKind::Field(x, _)
2396         | hir::ExprKind::Index(x, _) => {
2397             // `&X { y: 1 }, X { y: 1 }.y`
2398             contains_exterior_struct_lit(x)
2399         }
2400
2401         hir::ExprKind::MethodCall(_, receiver, ..) => {
2402             // `X { y: 1 }.bar(...)`
2403             contains_exterior_struct_lit(receiver)
2404         }
2405
2406         _ => false,
2407     }
2408 }