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