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