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