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