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