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