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