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