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