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