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