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