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