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