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