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