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