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