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