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