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