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