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