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