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