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