1#![recursion_limit = "256"]
6use std::cell::Cell;
9use std::vec;
10
11use rustc_abi::ExternAbi;
12use rustc_ast::util::parser::{self, ExprPrecedence, Fixity};
13use rustc_ast::{DUMMY_NODE_ID, DelimArgs};
14use rustc_ast_pretty::pp::Breaks::{Consistent, Inconsistent};
15use rustc_ast_pretty::pp::{self, BoxMarker, Breaks};
16use rustc_ast_pretty::pprust::state::MacHeader;
17use rustc_ast_pretty::pprust::{Comments, PrintState};
18use rustc_hir::attrs::{AttributeKind, PrintAttribute};
19use rustc_hir::{
20 BindingMode, ByRef, ConstArgKind, GenericArg, GenericBound, GenericParam, GenericParamKind,
21 HirId, ImplicitSelfKind, LifetimeParamKind, Node, PatKind, PreciseCapturingArg, RangeEnd, Term,
22 TyPatKind,
23};
24use rustc_span::source_map::SourceMap;
25use rustc_span::{FileName, Ident, Span, Symbol, kw, sym};
26use {rustc_ast as ast, rustc_hir as hir};
27
28pub fn id_to_string(cx: &dyn rustc_hir::intravisit::HirTyCtxt<'_>, hir_id: HirId) -> String {
29 to_string(&cx, |s| s.print_node(cx.hir_node(hir_id)))
30}
31
32pub enum AnnNode<'a> {
33 Name(&'a Symbol),
34 Block(&'a hir::Block<'a>),
35 Item(&'a hir::Item<'a>),
36 SubItem(HirId),
37 Expr(&'a hir::Expr<'a>),
38 Pat(&'a hir::Pat<'a>),
39 TyPat(&'a hir::TyPat<'a>),
40 Arm(&'a hir::Arm<'a>),
41}
42
43pub enum Nested {
44 Item(hir::ItemId),
45 TraitItem(hir::TraitItemId),
46 ImplItem(hir::ImplItemId),
47 ForeignItem(hir::ForeignItemId),
48 Body(hir::BodyId),
49 BodyParamPat(hir::BodyId, usize),
50}
51
52pub trait PpAnn {
53 fn nested(&self, _state: &mut State<'_>, _nested: Nested) {}
54 fn pre(&self, _state: &mut State<'_>, _node: AnnNode<'_>) {}
55 fn post(&self, _state: &mut State<'_>, _node: AnnNode<'_>) {}
56}
57
58impl PpAnn for &dyn rustc_hir::intravisit::HirTyCtxt<'_> {
59 fn nested(&self, state: &mut State<'_>, nested: Nested) {
60 match nested {
61 Nested::Item(id) => state.print_item(self.hir_item(id)),
62 Nested::TraitItem(id) => state.print_trait_item(self.hir_trait_item(id)),
63 Nested::ImplItem(id) => state.print_impl_item(self.hir_impl_item(id)),
64 Nested::ForeignItem(id) => state.print_foreign_item(self.hir_foreign_item(id)),
65 Nested::Body(id) => state.print_expr(self.hir_body(id).value),
66 Nested::BodyParamPat(id, i) => state.print_pat(self.hir_body(id).params[i].pat),
67 }
68 }
69}
70
71pub struct State<'a> {
72 pub s: pp::Printer,
73 comments: Option<Comments<'a>>,
74 attrs: &'a dyn Fn(HirId) -> &'a [hir::Attribute],
75 ann: &'a (dyn PpAnn + 'a),
76}
77
78impl<'a> State<'a> {
79 fn attrs(&self, id: HirId) -> &'a [hir::Attribute] {
80 (self.attrs)(id)
81 }
82
83 fn precedence(&self, expr: &hir::Expr<'_>) -> ExprPrecedence {
84 let has_attr = |id: HirId| !self.attrs(id).is_empty();
85 expr.precedence(&has_attr)
86 }
87
88 fn print_attrs(&mut self, attrs: &[hir::Attribute]) {
89 if attrs.is_empty() {
90 return;
91 }
92
93 for attr in attrs {
94 self.print_attribute_as_style(attr, ast::AttrStyle::Outer);
95 }
96 self.hardbreak_if_not_bol();
97 }
98
99 fn print_attribute_as_style(&mut self, attr: &hir::Attribute, style: ast::AttrStyle) {
102 match &attr {
103 hir::Attribute::Unparsed(unparsed) => {
104 self.maybe_print_comment(unparsed.span.lo());
105 match style {
106 ast::AttrStyle::Inner => self.word("#!["),
107 ast::AttrStyle::Outer => self.word("#["),
108 }
109 self.print_attr_item(&unparsed, unparsed.span);
110 self.word("]");
111 self.hardbreak()
112 }
113 hir::Attribute::Parsed(AttributeKind::DocComment { kind, comment, .. }) => {
114 self.word(rustc_ast_pretty::pprust::state::doc_comment_to_string(
115 *kind, style, *comment,
116 ));
117 self.hardbreak()
118 }
119 hir::Attribute::Parsed(pa) => {
120 match style {
121 ast::AttrStyle::Inner => self.word("#![attr = "),
122 ast::AttrStyle::Outer => self.word("#[attr = "),
123 }
124 pa.print_attribute(self);
125 self.word("]");
126 self.hardbreak()
127 }
128 }
129 }
130
131 fn print_attr_item(&mut self, item: &hir::AttrItem, span: Span) {
132 let ib = self.ibox(0);
133 let path = ast::Path {
134 span,
135 segments: item
136 .path
137 .segments
138 .iter()
139 .map(|i| ast::PathSegment { ident: *i, args: None, id: DUMMY_NODE_ID })
140 .collect(),
141 tokens: None,
142 };
143
144 match &item.args {
145 hir::AttrArgs::Delimited(DelimArgs { dspan: _, delim, tokens }) => self
146 .print_mac_common(
147 Some(MacHeader::Path(&path)),
148 false,
149 None,
150 *delim,
151 None,
152 &tokens,
153 true,
154 span,
155 ),
156 hir::AttrArgs::Empty => {
157 PrintState::print_path(self, &path, false, 0);
158 }
159 hir::AttrArgs::Eq { eq_span: _, expr } => {
160 PrintState::print_path(self, &path, false, 0);
161 self.space();
162 self.word_space("=");
163 let token_str = self.meta_item_lit_to_string(expr);
164 self.word(token_str);
165 }
166 }
167 self.end(ib);
168 }
169
170 fn print_node(&mut self, node: Node<'_>) {
171 match node {
172 Node::Param(a) => self.print_param(a),
173 Node::Item(a) => self.print_item(a),
174 Node::ForeignItem(a) => self.print_foreign_item(a),
175 Node::TraitItem(a) => self.print_trait_item(a),
176 Node::ImplItem(a) => self.print_impl_item(a),
177 Node::Variant(a) => self.print_variant(a),
178 Node::AnonConst(a) => self.print_anon_const(a),
179 Node::ConstBlock(a) => self.print_inline_const(a),
180 Node::ConstArg(a) => self.print_const_arg(a),
181 Node::Expr(a) => self.print_expr(a),
182 Node::ExprField(a) => self.print_expr_field(a),
183 Node::Stmt(a) => self.print_stmt(a),
184 Node::PathSegment(a) => self.print_path_segment(a),
185 Node::Ty(a) => self.print_type(a),
186 Node::AssocItemConstraint(a) => self.print_assoc_item_constraint(a),
187 Node::TraitRef(a) => self.print_trait_ref(a),
188 Node::OpaqueTy(_) => panic!("cannot print Node::OpaqueTy"),
189 Node::Pat(a) => self.print_pat(a),
190 Node::TyPat(a) => self.print_ty_pat(a),
191 Node::PatField(a) => self.print_patfield(a),
192 Node::PatExpr(a) => self.print_pat_expr(a),
193 Node::Arm(a) => self.print_arm(a),
194 Node::Infer(_) => self.word("_"),
195 Node::PreciseCapturingNonLifetimeArg(param) => self.print_ident(param.ident),
196 Node::Block(a) => {
197 let cb = self.cbox(INDENT_UNIT);
199 let ib = self.ibox(0);
201 self.print_block(a, cb, ib);
202 }
203 Node::Lifetime(a) => self.print_lifetime(a),
204 Node::GenericParam(_) => panic!("cannot print Node::GenericParam"),
205 Node::Field(_) => panic!("cannot print Node::Field"),
206 Node::Ctor(..) => panic!("cannot print isolated Ctor"),
210 Node::LetStmt(a) => self.print_local_decl(a),
211 Node::Crate(..) => panic!("cannot print Crate"),
212 Node::WherePredicate(pred) => self.print_where_predicate(pred),
213 Node::Synthetic => unreachable!(),
214 Node::Err(_) => self.word("/*ERROR*/"),
215 }
216 }
217
218 fn print_generic_arg(&mut self, generic_arg: &GenericArg<'_>, elide_lifetimes: bool) {
219 match generic_arg {
220 GenericArg::Lifetime(lt) if !elide_lifetimes => self.print_lifetime(lt),
221 GenericArg::Lifetime(_) => {}
222 GenericArg::Type(ty) => self.print_type(ty.as_unambig_ty()),
223 GenericArg::Const(ct) => self.print_const_arg(ct.as_unambig_ct()),
224 GenericArg::Infer(_inf) => self.word("_"),
225 }
226 }
227}
228
229impl std::ops::Deref for State<'_> {
230 type Target = pp::Printer;
231 fn deref(&self) -> &Self::Target {
232 &self.s
233 }
234}
235
236impl std::ops::DerefMut for State<'_> {
237 fn deref_mut(&mut self) -> &mut Self::Target {
238 &mut self.s
239 }
240}
241
242impl<'a> PrintState<'a> for State<'a> {
243 fn comments(&self) -> Option<&Comments<'a>> {
244 self.comments.as_ref()
245 }
246
247 fn comments_mut(&mut self) -> Option<&mut Comments<'a>> {
248 self.comments.as_mut()
249 }
250
251 fn ann_post(&mut self, ident: Ident) {
252 self.ann.post(self, AnnNode::Name(&ident.name));
253 }
254
255 fn print_generic_args(&mut self, _: &ast::GenericArgs, _colons_before_params: bool) {
256 panic!("AST generic args printed by HIR pretty-printer");
257 }
258}
259
260const INDENT_UNIT: isize = 4;
261
262pub fn print_crate<'a>(
265 sm: &'a SourceMap,
266 krate: &hir::Mod<'_>,
267 filename: FileName,
268 input: String,
269 attrs: &'a dyn Fn(HirId) -> &'a [hir::Attribute],
270 ann: &'a dyn PpAnn,
271) -> String {
272 let mut s = State {
273 s: pp::Printer::new(),
274 comments: Some(Comments::new(sm, filename, input)),
275 attrs,
276 ann,
277 };
278
279 for attr in s.attrs(hir::CRATE_HIR_ID) {
283 s.print_attribute_as_style(attr, ast::AttrStyle::Inner);
284 }
285
286 s.print_mod(krate);
290 s.print_remaining_comments();
291 s.s.eof()
292}
293
294fn to_string<F>(ann: &dyn PpAnn, f: F) -> String
295where
296 F: FnOnce(&mut State<'_>),
297{
298 let mut printer = State { s: pp::Printer::new(), comments: None, attrs: &|_| &[], ann };
299 f(&mut printer);
300 printer.s.eof()
301}
302
303pub fn attribute_to_string(ann: &dyn PpAnn, attr: &hir::Attribute) -> String {
304 to_string(ann, |s| s.print_attribute_as_style(attr, ast::AttrStyle::Outer))
305}
306
307pub fn ty_to_string(ann: &dyn PpAnn, ty: &hir::Ty<'_>) -> String {
308 to_string(ann, |s| s.print_type(ty))
309}
310
311pub fn qpath_to_string(ann: &dyn PpAnn, segment: &hir::QPath<'_>) -> String {
312 to_string(ann, |s| s.print_qpath(segment, false))
313}
314
315pub fn pat_to_string(ann: &dyn PpAnn, pat: &hir::Pat<'_>) -> String {
316 to_string(ann, |s| s.print_pat(pat))
317}
318
319pub fn expr_to_string(ann: &dyn PpAnn, pat: &hir::Expr<'_>) -> String {
320 to_string(ann, |s| s.print_expr(pat))
321}
322
323pub fn item_to_string(ann: &dyn PpAnn, pat: &hir::Item<'_>) -> String {
324 to_string(ann, |s| s.print_item(pat))
325}
326
327impl<'a> State<'a> {
328 fn bclose_maybe_open(&mut self, span: rustc_span::Span, cb: Option<BoxMarker>) {
329 self.maybe_print_comment(span.hi());
330 self.break_offset_if_not_bol(1, -INDENT_UNIT);
331 self.word("}");
332 if let Some(cb) = cb {
333 self.end(cb);
334 }
335 }
336
337 fn bclose(&mut self, span: rustc_span::Span, cb: BoxMarker) {
338 self.bclose_maybe_open(span, Some(cb))
339 }
340
341 fn commasep_cmnt<T, F, G>(&mut self, b: Breaks, elts: &[T], mut op: F, mut get_span: G)
342 where
343 F: FnMut(&mut State<'_>, &T),
344 G: FnMut(&T) -> rustc_span::Span,
345 {
346 let rb = self.rbox(0, b);
347 let len = elts.len();
348 let mut i = 0;
349 for elt in elts {
350 self.maybe_print_comment(get_span(elt).hi());
351 op(self, elt);
352 i += 1;
353 if i < len {
354 self.word(",");
355 self.maybe_print_trailing_comment(get_span(elt), Some(get_span(&elts[i]).hi()));
356 self.space_if_not_bol();
357 }
358 }
359 self.end(rb);
360 }
361
362 fn commasep_exprs(&mut self, b: Breaks, exprs: &[hir::Expr<'_>]) {
363 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(e), |e| e.span);
364 }
365
366 fn print_mod(&mut self, _mod: &hir::Mod<'_>) {
367 for &item_id in _mod.item_ids {
368 self.ann.nested(self, Nested::Item(item_id));
369 }
370 }
371
372 fn print_opt_lifetime(&mut self, lifetime: &hir::Lifetime) {
373 if !lifetime.is_elided() {
374 self.print_lifetime(lifetime);
375 self.nbsp();
376 }
377 }
378
379 fn print_type(&mut self, ty: &hir::Ty<'_>) {
380 self.maybe_print_comment(ty.span.lo());
381 let ib = self.ibox(0);
382 match ty.kind {
383 hir::TyKind::Slice(ty) => {
384 self.word("[");
385 self.print_type(ty);
386 self.word("]");
387 }
388 hir::TyKind::Ptr(ref mt) => {
389 self.word("*");
390 self.print_mt(mt, true);
391 }
392 hir::TyKind::Ref(lifetime, ref mt) => {
393 self.word("&");
394 self.print_opt_lifetime(lifetime);
395 self.print_mt(mt, false);
396 }
397 hir::TyKind::Never => {
398 self.word("!");
399 }
400 hir::TyKind::Tup(elts) => {
401 self.popen();
402 self.commasep(Inconsistent, elts, |s, ty| s.print_type(ty));
403 if elts.len() == 1 {
404 self.word(",");
405 }
406 self.pclose();
407 }
408 hir::TyKind::FnPtr(f) => {
409 self.print_ty_fn(f.abi, f.safety, f.decl, None, f.generic_params, f.param_idents);
410 }
411 hir::TyKind::UnsafeBinder(unsafe_binder) => {
412 self.print_unsafe_binder(unsafe_binder);
413 }
414 hir::TyKind::OpaqueDef(..) => self.word("/*impl Trait*/"),
415 hir::TyKind::TraitAscription(bounds) => {
416 self.print_bounds("impl", bounds);
417 }
418 hir::TyKind::Path(ref qpath) => self.print_qpath(qpath, false),
419 hir::TyKind::TraitObject(bounds, lifetime) => {
420 let syntax = lifetime.tag();
421 match syntax {
422 ast::TraitObjectSyntax::Dyn => self.word_nbsp("dyn"),
423 ast::TraitObjectSyntax::None => {}
424 }
425 let mut first = true;
426 for bound in bounds {
427 if first {
428 first = false;
429 } else {
430 self.nbsp();
431 self.word_space("+");
432 }
433 self.print_poly_trait_ref(bound);
434 }
435 if !lifetime.is_elided() {
436 self.nbsp();
437 self.word_space("+");
438 self.print_lifetime(lifetime.pointer());
439 }
440 }
441 hir::TyKind::Array(ty, ref length) => {
442 self.word("[");
443 self.print_type(ty);
444 self.word("; ");
445 self.print_const_arg(length);
446 self.word("]");
447 }
448 hir::TyKind::Typeof(ref e) => {
449 self.word("typeof(");
450 self.print_anon_const(e);
451 self.word(")");
452 }
453 hir::TyKind::Err(_) => {
454 self.popen();
455 self.word("/*ERROR*/");
456 self.pclose();
457 }
458 hir::TyKind::Infer(()) | hir::TyKind::InferDelegation(..) => {
459 self.word("_");
460 }
461 hir::TyKind::Pat(ty, pat) => {
462 self.print_type(ty);
463 self.word(" is ");
464 self.print_ty_pat(pat);
465 }
466 }
467 self.end(ib)
468 }
469
470 fn print_unsafe_binder(&mut self, unsafe_binder: &hir::UnsafeBinderTy<'_>) {
471 let ib = self.ibox(INDENT_UNIT);
472 self.word("unsafe");
473 self.print_generic_params(unsafe_binder.generic_params);
474 self.nbsp();
475 self.print_type(unsafe_binder.inner_ty);
476 self.end(ib);
477 }
478
479 fn print_foreign_item(&mut self, item: &hir::ForeignItem<'_>) {
480 self.hardbreak_if_not_bol();
481 self.maybe_print_comment(item.span.lo());
482 self.print_attrs(self.attrs(item.hir_id()));
483 match item.kind {
484 hir::ForeignItemKind::Fn(sig, arg_idents, generics) => {
485 let (cb, ib) = self.head("");
486 self.print_fn(
487 sig.header,
488 Some(item.ident.name),
489 generics,
490 sig.decl,
491 arg_idents,
492 None,
493 );
494 self.end(ib);
495 self.word(";");
496 self.end(cb)
497 }
498 hir::ForeignItemKind::Static(t, m, safety) => {
499 self.print_safety(safety);
500 let (cb, ib) = self.head("static");
501 if m.is_mut() {
502 self.word_space("mut");
503 }
504 self.print_ident(item.ident);
505 self.word_space(":");
506 self.print_type(t);
507 self.word(";");
508 self.end(ib);
509 self.end(cb)
510 }
511 hir::ForeignItemKind::Type => {
512 let (cb, ib) = self.head("type");
513 self.print_ident(item.ident);
514 self.word(";");
515 self.end(ib);
516 self.end(cb)
517 }
518 }
519 }
520
521 fn print_associated_const(
522 &mut self,
523 ident: Ident,
524 generics: &hir::Generics<'_>,
525 ty: &hir::Ty<'_>,
526 default: Option<hir::ConstItemRhs<'_>>,
527 ) {
528 self.word_space("const");
529 self.print_ident(ident);
530 self.print_generic_params(generics.params);
531 self.word_space(":");
532 self.print_type(ty);
533 if let Some(ct_rhs) = default {
534 self.space();
535 self.word_space("=");
536 self.print_const_item_rhs(ct_rhs);
537 }
538 self.print_where_clause(generics);
539 self.word(";")
540 }
541
542 fn print_associated_type(
543 &mut self,
544 ident: Ident,
545 generics: &hir::Generics<'_>,
546 bounds: Option<hir::GenericBounds<'_>>,
547 ty: Option<&hir::Ty<'_>>,
548 ) {
549 self.word_space("type");
550 self.print_ident(ident);
551 self.print_generic_params(generics.params);
552 if let Some(bounds) = bounds {
553 self.print_bounds(":", bounds);
554 }
555 self.print_where_clause(generics);
556 if let Some(ty) = ty {
557 self.space();
558 self.word_space("=");
559 self.print_type(ty);
560 }
561 self.word(";")
562 }
563
564 fn print_item(&mut self, item: &hir::Item<'_>) {
565 self.hardbreak_if_not_bol();
566 self.maybe_print_comment(item.span.lo());
567 let attrs = self.attrs(item.hir_id());
568 self.print_attrs(attrs);
569 self.ann.pre(self, AnnNode::Item(item));
570 match item.kind {
571 hir::ItemKind::ExternCrate(orig_name, ident) => {
572 let (cb, ib) = self.head("extern crate");
573 if let Some(orig_name) = orig_name {
574 self.print_name(orig_name);
575 self.space();
576 self.word("as");
577 self.space();
578 }
579 self.print_ident(ident);
580 self.word(";");
581 self.end(ib);
582 self.end(cb);
583 }
584 hir::ItemKind::Use(path, kind) => {
585 let (cb, ib) = self.head("use");
586 self.print_path(path, false);
587
588 match kind {
589 hir::UseKind::Single(ident) => {
590 if path.segments.last().unwrap().ident != ident {
591 self.space();
592 self.word_space("as");
593 self.print_ident(ident);
594 }
595 self.word(";");
596 }
597 hir::UseKind::Glob => self.word("::*;"),
598 hir::UseKind::ListStem => self.word("::{};"),
599 }
600 self.end(ib);
601 self.end(cb);
602 }
603 hir::ItemKind::Static(m, ident, ty, expr) => {
604 let (cb, ib) = self.head("static");
605 if m.is_mut() {
606 self.word_space("mut");
607 }
608 self.print_ident(ident);
609 self.word_space(":");
610 self.print_type(ty);
611 self.space();
612 self.end(ib);
613
614 self.word_space("=");
615 self.ann.nested(self, Nested::Body(expr));
616 self.word(";");
617 self.end(cb);
618 }
619 hir::ItemKind::Const(ident, generics, ty, rhs) => {
620 let (cb, ib) = self.head("const");
621 self.print_ident(ident);
622 self.print_generic_params(generics.params);
623 self.word_space(":");
624 self.print_type(ty);
625 self.space();
626 self.end(ib);
627
628 self.word_space("=");
629 self.print_const_item_rhs(rhs);
630 self.print_where_clause(generics);
631 self.word(";");
632 self.end(cb);
633 }
634 hir::ItemKind::Fn { ident, sig, generics, body, .. } => {
635 let (cb, ib) = self.head("");
636 self.print_fn(sig.header, Some(ident.name), generics, sig.decl, &[], Some(body));
637 self.word(" ");
638 self.end(ib);
639 self.end(cb);
640 self.ann.nested(self, Nested::Body(body));
641 }
642 hir::ItemKind::Macro(ident, macro_def, _) => {
643 self.print_mac_def(macro_def, &ident, item.span, |_| {});
644 }
645 hir::ItemKind::Mod(ident, mod_) => {
646 let (cb, ib) = self.head("mod");
647 self.print_ident(ident);
648 self.nbsp();
649 self.bopen(ib);
650 self.print_mod(mod_);
651 self.bclose(item.span, cb);
652 }
653 hir::ItemKind::ForeignMod { abi, items } => {
654 let (cb, ib) = self.head("extern");
655 self.word_nbsp(abi.to_string());
656 self.bopen(ib);
657 for &foreign_item in items {
658 self.ann.nested(self, Nested::ForeignItem(foreign_item));
659 }
660 self.bclose(item.span, cb);
661 }
662 hir::ItemKind::GlobalAsm { asm, .. } => {
663 let (cb, ib) = self.head("global_asm!");
664 self.print_inline_asm(asm);
665 self.word(";");
666 self.end(cb);
667 self.end(ib);
668 }
669 hir::ItemKind::TyAlias(ident, generics, ty) => {
670 let (cb, ib) = self.head("type");
671 self.print_ident(ident);
672 self.print_generic_params(generics.params);
673 self.end(ib);
674
675 self.print_where_clause(generics);
676 self.space();
677 self.word_space("=");
678 self.print_type(ty);
679 self.word(";");
680 self.end(cb);
681 }
682 hir::ItemKind::Enum(ident, generics, ref enum_def) => {
683 self.print_enum_def(ident.name, generics, enum_def, item.span);
684 }
685 hir::ItemKind::Struct(ident, generics, ref struct_def) => {
686 let (cb, ib) = self.head("struct");
687 self.print_struct(ident.name, generics, struct_def, item.span, true, cb, ib);
688 }
689 hir::ItemKind::Union(ident, generics, ref struct_def) => {
690 let (cb, ib) = self.head("union");
691 self.print_struct(ident.name, generics, struct_def, item.span, true, cb, ib);
692 }
693 hir::ItemKind::Impl(hir::Impl { generics, of_trait, self_ty, items, constness }) => {
694 let (cb, ib) = self.head("");
695
696 let impl_generics = |this: &mut Self| {
697 this.word_nbsp("impl");
698 if !generics.params.is_empty() {
699 this.print_generic_params(generics.params);
700 this.space();
701 }
702 };
703
704 match of_trait {
705 None => {
706 if let hir::Constness::Const = constness {
707 self.word_nbsp("const");
708 }
709 impl_generics(self)
710 }
711 Some(&hir::TraitImplHeader {
712 safety,
713 polarity,
714 defaultness,
715 defaultness_span: _,
716 ref trait_ref,
717 }) => {
718 self.print_defaultness(defaultness);
719 self.print_safety(safety);
720
721 impl_generics(self);
722
723 if let hir::Constness::Const = constness {
724 self.word_nbsp("const");
725 }
726
727 if let hir::ImplPolarity::Negative(_) = polarity {
728 self.word("!");
729 }
730
731 self.print_trait_ref(trait_ref);
732 self.space();
733 self.word_space("for");
734 }
735 }
736
737 self.print_type(self_ty);
738 self.print_where_clause(generics);
739
740 self.space();
741 self.bopen(ib);
742 for &impl_item in items {
743 self.ann.nested(self, Nested::ImplItem(impl_item));
744 }
745 self.bclose(item.span, cb);
746 }
747 hir::ItemKind::Trait(
748 constness,
749 is_auto,
750 safety,
751 ident,
752 generics,
753 bounds,
754 trait_items,
755 ) => {
756 let (cb, ib) = self.head("");
757 self.print_constness(constness);
758 self.print_is_auto(is_auto);
759 self.print_safety(safety);
760 self.word_nbsp("trait");
761 self.print_ident(ident);
762 self.print_generic_params(generics.params);
763 self.print_bounds(":", bounds);
764 self.print_where_clause(generics);
765 self.word(" ");
766 self.bopen(ib);
767 for &trait_item in trait_items {
768 self.ann.nested(self, Nested::TraitItem(trait_item));
769 }
770 self.bclose(item.span, cb);
771 }
772 hir::ItemKind::TraitAlias(constness, ident, generics, bounds) => {
773 let (cb, ib) = self.head("");
774 self.print_constness(constness);
775 self.word_nbsp("trait");
776 self.print_ident(ident);
777 self.print_generic_params(generics.params);
778 self.nbsp();
779 self.print_bounds("=", bounds);
780 self.print_where_clause(generics);
781 self.word(";");
782 self.end(ib);
783 self.end(cb);
784 }
785 }
786 self.ann.post(self, AnnNode::Item(item))
787 }
788
789 fn print_trait_ref(&mut self, t: &hir::TraitRef<'_>) {
790 self.print_path(t.path, false);
791 }
792
793 fn print_formal_generic_params(&mut self, generic_params: &[hir::GenericParam<'_>]) {
794 if !generic_params.is_empty() {
795 self.word("for");
796 self.print_generic_params(generic_params);
797 self.nbsp();
798 }
799 }
800
801 fn print_poly_trait_ref(&mut self, t: &hir::PolyTraitRef<'_>) {
802 let hir::TraitBoundModifiers { constness, polarity } = t.modifiers;
803 match constness {
804 hir::BoundConstness::Never => {}
805 hir::BoundConstness::Always(_) => self.word("const"),
806 hir::BoundConstness::Maybe(_) => self.word("[const]"),
807 }
808 match polarity {
809 hir::BoundPolarity::Positive => {}
810 hir::BoundPolarity::Negative(_) => self.word("!"),
811 hir::BoundPolarity::Maybe(_) => self.word("?"),
812 }
813 self.print_formal_generic_params(t.bound_generic_params);
814 self.print_trait_ref(&t.trait_ref);
815 }
816
817 fn print_enum_def(
818 &mut self,
819 name: Symbol,
820 generics: &hir::Generics<'_>,
821 enum_def: &hir::EnumDef<'_>,
822 span: rustc_span::Span,
823 ) {
824 let (cb, ib) = self.head("enum");
825 self.print_name(name);
826 self.print_generic_params(generics.params);
827 self.print_where_clause(generics);
828 self.space();
829 self.print_variants(enum_def.variants, span, cb, ib);
830 }
831
832 fn print_variants(
833 &mut self,
834 variants: &[hir::Variant<'_>],
835 span: rustc_span::Span,
836 cb: BoxMarker,
837 ib: BoxMarker,
838 ) {
839 self.bopen(ib);
840 for v in variants {
841 self.space_if_not_bol();
842 self.maybe_print_comment(v.span.lo());
843 self.print_attrs(self.attrs(v.hir_id));
844 let ib = self.ibox(INDENT_UNIT);
845 self.print_variant(v);
846 self.word(",");
847 self.end(ib);
848 self.maybe_print_trailing_comment(v.span, None);
849 }
850 self.bclose(span, cb)
851 }
852
853 fn print_defaultness(&mut self, defaultness: hir::Defaultness) {
854 match defaultness {
855 hir::Defaultness::Default { .. } => self.word_nbsp("default"),
856 hir::Defaultness::Final => (),
857 }
858 }
859
860 fn print_struct(
861 &mut self,
862 name: Symbol,
863 generics: &hir::Generics<'_>,
864 struct_def: &hir::VariantData<'_>,
865 span: rustc_span::Span,
866 print_finalizer: bool,
867 cb: BoxMarker,
868 ib: BoxMarker,
869 ) {
870 self.print_name(name);
871 self.print_generic_params(generics.params);
872 match struct_def {
873 hir::VariantData::Tuple(..) | hir::VariantData::Unit(..) => {
874 if let hir::VariantData::Tuple(..) = struct_def {
875 self.popen();
876 self.commasep(Inconsistent, struct_def.fields(), |s, field| {
877 s.maybe_print_comment(field.span.lo());
878 s.print_attrs(s.attrs(field.hir_id));
879 s.print_type(field.ty);
880 });
881 self.pclose();
882 }
883 self.print_where_clause(generics);
884 if print_finalizer {
885 self.word(";");
886 }
887 self.end(ib);
888 self.end(cb);
889 }
890 hir::VariantData::Struct { .. } => {
891 self.print_where_clause(generics);
892 self.nbsp();
893 self.bopen(ib);
894 self.hardbreak_if_not_bol();
895
896 for field in struct_def.fields() {
897 self.hardbreak_if_not_bol();
898 self.maybe_print_comment(field.span.lo());
899 self.print_attrs(self.attrs(field.hir_id));
900 self.print_ident(field.ident);
901 self.word_nbsp(":");
902 self.print_type(field.ty);
903 self.word(",");
904 }
905
906 self.bclose(span, cb)
907 }
908 }
909 }
910
911 pub fn print_variant(&mut self, v: &hir::Variant<'_>) {
912 let (cb, ib) = self.head("");
913 let generics = hir::Generics::empty();
914 self.print_struct(v.ident.name, generics, &v.data, v.span, false, cb, ib);
915 if let Some(ref d) = v.disr_expr {
916 self.space();
917 self.word_space("=");
918 self.print_anon_const(d);
919 }
920 }
921
922 fn print_method_sig(
923 &mut self,
924 ident: Ident,
925 m: &hir::FnSig<'_>,
926 generics: &hir::Generics<'_>,
927 arg_idents: &[Option<Ident>],
928 body_id: Option<hir::BodyId>,
929 ) {
930 self.print_fn(m.header, Some(ident.name), generics, m.decl, arg_idents, body_id);
931 }
932
933 fn print_trait_item(&mut self, ti: &hir::TraitItem<'_>) {
934 self.ann.pre(self, AnnNode::SubItem(ti.hir_id()));
935 self.hardbreak_if_not_bol();
936 self.maybe_print_comment(ti.span.lo());
937 self.print_attrs(self.attrs(ti.hir_id()));
938 match ti.kind {
939 hir::TraitItemKind::Const(ty, default) => {
940 self.print_associated_const(ti.ident, ti.generics, ty, default);
941 }
942 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Required(arg_idents)) => {
943 self.print_method_sig(ti.ident, sig, ti.generics, arg_idents, None);
944 self.word(";");
945 }
946 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Provided(body)) => {
947 let (cb, ib) = self.head("");
948 self.print_method_sig(ti.ident, sig, ti.generics, &[], Some(body));
949 self.nbsp();
950 self.end(ib);
951 self.end(cb);
952 self.ann.nested(self, Nested::Body(body));
953 }
954 hir::TraitItemKind::Type(bounds, default) => {
955 self.print_associated_type(ti.ident, ti.generics, Some(bounds), default);
956 }
957 }
958 self.ann.post(self, AnnNode::SubItem(ti.hir_id()))
959 }
960
961 fn print_impl_item(&mut self, ii: &hir::ImplItem<'_>) {
962 self.ann.pre(self, AnnNode::SubItem(ii.hir_id()));
963 self.hardbreak_if_not_bol();
964 self.maybe_print_comment(ii.span.lo());
965 self.print_attrs(self.attrs(ii.hir_id()));
966
967 match ii.kind {
968 hir::ImplItemKind::Const(ty, expr) => {
969 self.print_associated_const(ii.ident, ii.generics, ty, Some(expr));
970 }
971 hir::ImplItemKind::Fn(ref sig, body) => {
972 let (cb, ib) = self.head("");
973 self.print_method_sig(ii.ident, sig, ii.generics, &[], Some(body));
974 self.nbsp();
975 self.end(ib);
976 self.end(cb);
977 self.ann.nested(self, Nested::Body(body));
978 }
979 hir::ImplItemKind::Type(ty) => {
980 self.print_associated_type(ii.ident, ii.generics, None, Some(ty));
981 }
982 }
983 self.ann.post(self, AnnNode::SubItem(ii.hir_id()))
984 }
985
986 fn print_local(
987 &mut self,
988 super_: bool,
989 init: Option<&hir::Expr<'_>>,
990 els: Option<&hir::Block<'_>>,
991 decl: impl Fn(&mut Self),
992 ) {
993 self.space_if_not_bol();
994 let ibm1 = self.ibox(INDENT_UNIT);
995 if super_ {
996 self.word_nbsp("super");
997 }
998 self.word_nbsp("let");
999
1000 let ibm2 = self.ibox(INDENT_UNIT);
1001 decl(self);
1002 self.end(ibm2);
1003
1004 if let Some(init) = init {
1005 self.nbsp();
1006 self.word_space("=");
1007 self.print_expr(init);
1008 }
1009
1010 if let Some(els) = els {
1011 self.nbsp();
1012 self.word_space("else");
1013 let cb = self.cbox(0);
1015 let ib = self.ibox(0);
1017 self.print_block(els, cb, ib);
1018 }
1019
1020 self.end(ibm1)
1021 }
1022
1023 fn print_stmt(&mut self, st: &hir::Stmt<'_>) {
1024 self.maybe_print_comment(st.span.lo());
1025 match st.kind {
1026 hir::StmtKind::Let(loc) => {
1027 self.print_local(loc.super_.is_some(), loc.init, loc.els, |this| {
1028 this.print_local_decl(loc)
1029 });
1030 }
1031 hir::StmtKind::Item(item) => self.ann.nested(self, Nested::Item(item)),
1032 hir::StmtKind::Expr(expr) => {
1033 self.space_if_not_bol();
1034 self.print_expr(expr);
1035 }
1036 hir::StmtKind::Semi(expr) => {
1037 self.space_if_not_bol();
1038 self.print_expr(expr);
1039 self.word(";");
1040 }
1041 }
1042 if stmt_ends_with_semi(&st.kind) {
1043 self.word(";");
1044 }
1045 self.maybe_print_trailing_comment(st.span, None)
1046 }
1047
1048 fn print_block(&mut self, blk: &hir::Block<'_>, cb: BoxMarker, ib: BoxMarker) {
1049 self.print_block_maybe_unclosed(blk, Some(cb), ib)
1050 }
1051
1052 fn print_block_unclosed(&mut self, blk: &hir::Block<'_>, ib: BoxMarker) {
1053 self.print_block_maybe_unclosed(blk, None, ib)
1054 }
1055
1056 fn print_block_maybe_unclosed(
1057 &mut self,
1058 blk: &hir::Block<'_>,
1059 cb: Option<BoxMarker>,
1060 ib: BoxMarker,
1061 ) {
1062 match blk.rules {
1063 hir::BlockCheckMode::UnsafeBlock(..) => self.word_space("unsafe"),
1064 hir::BlockCheckMode::DefaultBlock => (),
1065 }
1066 self.maybe_print_comment(blk.span.lo());
1067 self.ann.pre(self, AnnNode::Block(blk));
1068 self.bopen(ib);
1069
1070 for st in blk.stmts {
1071 self.print_stmt(st);
1072 }
1073 if let Some(expr) = blk.expr {
1074 self.space_if_not_bol();
1075 self.print_expr(expr);
1076 self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi()));
1077 }
1078 self.bclose_maybe_open(blk.span, cb);
1079 self.ann.post(self, AnnNode::Block(blk))
1080 }
1081
1082 fn print_else(&mut self, els: Option<&hir::Expr<'_>>) {
1083 if let Some(els_inner) = els {
1084 match els_inner.kind {
1085 hir::ExprKind::If(i, hir::Expr { kind: hir::ExprKind::Block(t, None), .. }, e) => {
1087 let cb = self.cbox(0);
1088 let ib = self.ibox(0);
1089 self.word(" else if ");
1090 self.print_expr_as_cond(i);
1091 self.space();
1092 self.print_block(t, cb, ib);
1093 self.print_else(e);
1094 }
1095 hir::ExprKind::Block(b, None) => {
1097 let cb = self.cbox(0);
1098 let ib = self.ibox(0);
1099 self.word(" else ");
1100 self.print_block(b, cb, ib);
1101 }
1102 _ => {
1104 panic!("print_if saw if with weird alternative");
1105 }
1106 }
1107 }
1108 }
1109
1110 fn print_if(
1111 &mut self,
1112 test: &hir::Expr<'_>,
1113 blk: &hir::Expr<'_>,
1114 elseopt: Option<&hir::Expr<'_>>,
1115 ) {
1116 match blk.kind {
1117 hir::ExprKind::Block(blk, None) => {
1118 let cb = self.cbox(0);
1119 let ib = self.ibox(0);
1120 self.word_nbsp("if");
1121 self.print_expr_as_cond(test);
1122 self.space();
1123 self.print_block(blk, cb, ib);
1124 self.print_else(elseopt)
1125 }
1126 _ => panic!("non-block then expr"),
1127 }
1128 }
1129
1130 fn print_anon_const(&mut self, constant: &hir::AnonConst) {
1131 self.ann.nested(self, Nested::Body(constant.body))
1132 }
1133
1134 fn print_const_item_rhs(&mut self, ct_rhs: hir::ConstItemRhs<'_>) {
1135 match ct_rhs {
1136 hir::ConstItemRhs::Body(body_id) => self.ann.nested(self, Nested::Body(body_id)),
1137 hir::ConstItemRhs::TypeConst(const_arg) => self.print_const_arg(const_arg),
1138 }
1139 }
1140
1141 fn print_const_arg(&mut self, const_arg: &hir::ConstArg<'_>) {
1142 match &const_arg.kind {
1143 ConstArgKind::Path(qpath) => self.print_qpath(qpath, true),
1144 ConstArgKind::Anon(anon) => self.print_anon_const(anon),
1145 ConstArgKind::Error(_, _) => self.word("/*ERROR*/"),
1146 ConstArgKind::Infer(..) => self.word("_"),
1147 }
1148 }
1149
1150 fn print_call_post(&mut self, args: &[hir::Expr<'_>]) {
1151 self.popen();
1152 self.commasep_exprs(Inconsistent, args);
1153 self.pclose()
1154 }
1155
1156 fn print_expr_as_cond(&mut self, expr: &hir::Expr<'_>) {
1159 self.print_expr_cond_paren(expr, Self::cond_needs_par(expr))
1160 }
1161
1162 fn print_expr_cond_paren(&mut self, expr: &hir::Expr<'_>, needs_par: bool) {
1164 if needs_par {
1165 self.popen();
1166 }
1167 if let hir::ExprKind::DropTemps(actual_expr) = expr.kind {
1168 self.print_expr(actual_expr);
1169 } else {
1170 self.print_expr(expr);
1171 }
1172 if needs_par {
1173 self.pclose();
1174 }
1175 }
1176
1177 fn print_let(&mut self, pat: &hir::Pat<'_>, ty: Option<&hir::Ty<'_>>, init: &hir::Expr<'_>) {
1179 self.word_space("let");
1180 self.print_pat(pat);
1181 if let Some(ty) = ty {
1182 self.word_space(":");
1183 self.print_type(ty);
1184 }
1185 self.space();
1186 self.word_space("=");
1187 let npals = || parser::needs_par_as_let_scrutinee(self.precedence(init));
1188 self.print_expr_cond_paren(init, Self::cond_needs_par(init) || npals())
1189 }
1190
1191 fn cond_needs_par(expr: &hir::Expr<'_>) -> bool {
1196 match expr.kind {
1197 hir::ExprKind::Break(..) | hir::ExprKind::Closure { .. } | hir::ExprKind::Ret(..) => {
1198 true
1199 }
1200 _ => contains_exterior_struct_lit(expr),
1201 }
1202 }
1203
1204 fn print_expr_vec(&mut self, exprs: &[hir::Expr<'_>]) {
1205 let ib = self.ibox(INDENT_UNIT);
1206 self.word("[");
1207 self.commasep_exprs(Inconsistent, exprs);
1208 self.word("]");
1209 self.end(ib)
1210 }
1211
1212 fn print_inline_const(&mut self, constant: &hir::ConstBlock) {
1213 let ib = self.ibox(INDENT_UNIT);
1214 self.word_space("const");
1215 self.ann.nested(self, Nested::Body(constant.body));
1216 self.end(ib)
1217 }
1218
1219 fn print_expr_repeat(&mut self, element: &hir::Expr<'_>, count: &hir::ConstArg<'_>) {
1220 let ib = self.ibox(INDENT_UNIT);
1221 self.word("[");
1222 self.print_expr(element);
1223 self.word_space(";");
1224 self.print_const_arg(count);
1225 self.word("]");
1226 self.end(ib)
1227 }
1228
1229 fn print_expr_struct(
1230 &mut self,
1231 qpath: &hir::QPath<'_>,
1232 fields: &[hir::ExprField<'_>],
1233 wth: hir::StructTailExpr<'_>,
1234 ) {
1235 self.print_qpath(qpath, true);
1236 self.nbsp();
1237 self.word_space("{");
1238 self.commasep_cmnt(Consistent, fields, |s, field| s.print_expr_field(field), |f| f.span);
1239 match wth {
1240 hir::StructTailExpr::Base(expr) => {
1241 let ib = self.ibox(INDENT_UNIT);
1242 if !fields.is_empty() {
1243 self.word(",");
1244 self.space();
1245 }
1246 self.word("..");
1247 self.print_expr(expr);
1248 self.end(ib);
1249 }
1250 hir::StructTailExpr::DefaultFields(_) => {
1251 let ib = self.ibox(INDENT_UNIT);
1252 if !fields.is_empty() {
1253 self.word(",");
1254 self.space();
1255 }
1256 self.word("..");
1257 self.end(ib);
1258 }
1259 hir::StructTailExpr::None => {}
1260 }
1261 self.space();
1262 self.word("}");
1263 }
1264
1265 fn print_expr_field(&mut self, field: &hir::ExprField<'_>) {
1266 let cb = self.cbox(INDENT_UNIT);
1267 self.print_attrs(self.attrs(field.hir_id));
1268 if !field.is_shorthand {
1269 self.print_ident(field.ident);
1270 self.word_space(":");
1271 }
1272 self.print_expr(field.expr);
1273 self.end(cb)
1274 }
1275
1276 fn print_expr_tup(&mut self, exprs: &[hir::Expr<'_>]) {
1277 self.popen();
1278 self.commasep_exprs(Inconsistent, exprs);
1279 if exprs.len() == 1 {
1280 self.word(",");
1281 }
1282 self.pclose()
1283 }
1284
1285 fn print_expr_call(&mut self, func: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
1286 let needs_paren = match func.kind {
1287 hir::ExprKind::Field(..) => true,
1288 _ => self.precedence(func) < ExprPrecedence::Unambiguous,
1289 };
1290
1291 self.print_expr_cond_paren(func, needs_paren);
1292 self.print_call_post(args)
1293 }
1294
1295 fn print_expr_method_call(
1296 &mut self,
1297 segment: &hir::PathSegment<'_>,
1298 receiver: &hir::Expr<'_>,
1299 args: &[hir::Expr<'_>],
1300 ) {
1301 let base_args = args;
1302 self.print_expr_cond_paren(
1303 receiver,
1304 self.precedence(receiver) < ExprPrecedence::Unambiguous,
1305 );
1306 self.word(".");
1307 self.print_ident(segment.ident);
1308
1309 let generic_args = segment.args();
1310 if !generic_args.args.is_empty() || !generic_args.constraints.is_empty() {
1311 self.print_generic_args(generic_args, true);
1312 }
1313
1314 self.print_call_post(base_args)
1315 }
1316
1317 fn print_expr_binary(&mut self, op: hir::BinOpKind, lhs: &hir::Expr<'_>, rhs: &hir::Expr<'_>) {
1318 let binop_prec = op.precedence();
1319 let left_prec = self.precedence(lhs);
1320 let right_prec = self.precedence(rhs);
1321
1322 let (mut left_needs_paren, right_needs_paren) = match op.fixity() {
1323 Fixity::Left => (left_prec < binop_prec, right_prec <= binop_prec),
1324 Fixity::Right => (left_prec <= binop_prec, right_prec < binop_prec),
1325 Fixity::None => (left_prec <= binop_prec, right_prec <= binop_prec),
1326 };
1327
1328 match (&lhs.kind, op) {
1329 (&hir::ExprKind::Cast { .. }, hir::BinOpKind::Lt | hir::BinOpKind::Shl) => {
1333 left_needs_paren = true;
1334 }
1335 (&hir::ExprKind::Let { .. }, _) if !parser::needs_par_as_let_scrutinee(binop_prec) => {
1336 left_needs_paren = true;
1337 }
1338 _ => {}
1339 }
1340
1341 self.print_expr_cond_paren(lhs, left_needs_paren);
1342 self.space();
1343 self.word_space(op.as_str());
1344 self.print_expr_cond_paren(rhs, right_needs_paren);
1345 }
1346
1347 fn print_expr_unary(&mut self, op: hir::UnOp, expr: &hir::Expr<'_>) {
1348 self.word(op.as_str());
1349 self.print_expr_cond_paren(expr, self.precedence(expr) < ExprPrecedence::Prefix);
1350 }
1351
1352 fn print_expr_addr_of(
1353 &mut self,
1354 kind: hir::BorrowKind,
1355 mutability: hir::Mutability,
1356 expr: &hir::Expr<'_>,
1357 ) {
1358 self.word("&");
1359 match kind {
1360 hir::BorrowKind::Ref => self.print_mutability(mutability, false),
1361 hir::BorrowKind::Raw => {
1362 self.word_nbsp("raw");
1363 self.print_mutability(mutability, true);
1364 }
1365 hir::BorrowKind::Pin => {
1366 self.word_nbsp("pin");
1367 self.print_mutability(mutability, true);
1368 }
1369 }
1370 self.print_expr_cond_paren(expr, self.precedence(expr) < ExprPrecedence::Prefix);
1371 }
1372
1373 fn print_literal(&mut self, lit: &hir::Lit) {
1374 self.maybe_print_comment(lit.span.lo());
1375 self.word(lit.node.to_string())
1376 }
1377
1378 fn print_inline_asm(&mut self, asm: &hir::InlineAsm<'_>) {
1379 enum AsmArg<'a> {
1380 Template(String),
1381 Operand(&'a hir::InlineAsmOperand<'a>),
1382 Options(ast::InlineAsmOptions),
1383 }
1384
1385 let mut args = vec![AsmArg::Template(ast::InlineAsmTemplatePiece::to_string(asm.template))];
1386 args.extend(asm.operands.iter().map(|(o, _)| AsmArg::Operand(o)));
1387 if !asm.options.is_empty() {
1388 args.push(AsmArg::Options(asm.options));
1389 }
1390
1391 self.popen();
1392 self.commasep(Consistent, &args, |s, arg| match *arg {
1393 AsmArg::Template(ref template) => s.print_string(template, ast::StrStyle::Cooked),
1394 AsmArg::Operand(op) => match *op {
1395 hir::InlineAsmOperand::In { reg, expr } => {
1396 s.word("in");
1397 s.popen();
1398 s.word(format!("{reg}"));
1399 s.pclose();
1400 s.space();
1401 s.print_expr(expr);
1402 }
1403 hir::InlineAsmOperand::Out { reg, late, ref expr } => {
1404 s.word(if late { "lateout" } else { "out" });
1405 s.popen();
1406 s.word(format!("{reg}"));
1407 s.pclose();
1408 s.space();
1409 match expr {
1410 Some(expr) => s.print_expr(expr),
1411 None => s.word("_"),
1412 }
1413 }
1414 hir::InlineAsmOperand::InOut { reg, late, expr } => {
1415 s.word(if late { "inlateout" } else { "inout" });
1416 s.popen();
1417 s.word(format!("{reg}"));
1418 s.pclose();
1419 s.space();
1420 s.print_expr(expr);
1421 }
1422 hir::InlineAsmOperand::SplitInOut { reg, late, in_expr, ref out_expr } => {
1423 s.word(if late { "inlateout" } else { "inout" });
1424 s.popen();
1425 s.word(format!("{reg}"));
1426 s.pclose();
1427 s.space();
1428 s.print_expr(in_expr);
1429 s.space();
1430 s.word_space("=>");
1431 match out_expr {
1432 Some(out_expr) => s.print_expr(out_expr),
1433 None => s.word("_"),
1434 }
1435 }
1436 hir::InlineAsmOperand::Const { ref anon_const } => {
1437 s.word("const");
1438 s.space();
1439 s.ann.nested(s, Nested::Body(anon_const.body))
1441 }
1442 hir::InlineAsmOperand::SymFn { ref expr } => {
1443 s.word("sym_fn");
1444 s.space();
1445 s.print_expr(expr);
1446 }
1447 hir::InlineAsmOperand::SymStatic { ref path, def_id: _ } => {
1448 s.word("sym_static");
1449 s.space();
1450 s.print_qpath(path, true);
1451 }
1452 hir::InlineAsmOperand::Label { block } => {
1453 let (cb, ib) = s.head("label");
1454 s.print_block(block, cb, ib);
1455 }
1456 },
1457 AsmArg::Options(opts) => {
1458 s.word("options");
1459 s.popen();
1460 s.commasep(Inconsistent, &opts.human_readable_names(), |s, &opt| {
1461 s.word(opt);
1462 });
1463 s.pclose();
1464 }
1465 });
1466 self.pclose();
1467 }
1468
1469 fn print_expr(&mut self, expr: &hir::Expr<'_>) {
1470 self.maybe_print_comment(expr.span.lo());
1471 self.print_attrs(self.attrs(expr.hir_id));
1472 let ib = self.ibox(INDENT_UNIT);
1473 self.ann.pre(self, AnnNode::Expr(expr));
1474 match expr.kind {
1475 hir::ExprKind::Array(exprs) => {
1476 self.print_expr_vec(exprs);
1477 }
1478 hir::ExprKind::ConstBlock(ref anon_const) => {
1479 self.print_inline_const(anon_const);
1480 }
1481 hir::ExprKind::Repeat(element, ref count) => {
1482 self.print_expr_repeat(element, count);
1483 }
1484 hir::ExprKind::Struct(qpath, fields, wth) => {
1485 self.print_expr_struct(qpath, fields, wth);
1486 }
1487 hir::ExprKind::Tup(exprs) => {
1488 self.print_expr_tup(exprs);
1489 }
1490 hir::ExprKind::Call(func, args) => {
1491 self.print_expr_call(func, args);
1492 }
1493 hir::ExprKind::MethodCall(segment, receiver, args, _) => {
1494 self.print_expr_method_call(segment, receiver, args);
1495 }
1496 hir::ExprKind::Use(expr, _) => {
1497 self.print_expr(expr);
1498 self.word(".use");
1499 }
1500 hir::ExprKind::Binary(op, lhs, rhs) => {
1501 self.print_expr_binary(op.node, lhs, rhs);
1502 }
1503 hir::ExprKind::Unary(op, expr) => {
1504 self.print_expr_unary(op, expr);
1505 }
1506 hir::ExprKind::AddrOf(k, m, expr) => {
1507 self.print_expr_addr_of(k, m, expr);
1508 }
1509 hir::ExprKind::Lit(lit) => {
1510 self.print_literal(&lit);
1511 }
1512 hir::ExprKind::Cast(expr, ty) => {
1513 self.print_expr_cond_paren(expr, self.precedence(expr) < ExprPrecedence::Cast);
1514 self.space();
1515 self.word_space("as");
1516 self.print_type(ty);
1517 }
1518 hir::ExprKind::Type(expr, ty) => {
1519 self.word("type_ascribe!(");
1520 let ib = self.ibox(0);
1521 self.print_expr(expr);
1522
1523 self.word(",");
1524 self.space_if_not_bol();
1525 self.print_type(ty);
1526
1527 self.end(ib);
1528 self.word(")");
1529 }
1530 hir::ExprKind::DropTemps(init) => {
1531 let cb = self.cbox(0);
1533 let ib = self.ibox(0);
1534 self.bopen(ib);
1535
1536 let temp = Ident::with_dummy_span(sym::_t);
1538 self.print_local(false, Some(init), None, |this| this.print_ident(temp));
1539 self.word(";");
1540
1541 self.space_if_not_bol();
1543 self.print_ident(temp);
1544
1545 self.bclose_maybe_open(expr.span, Some(cb));
1547 }
1548 hir::ExprKind::Let(&hir::LetExpr { pat, ty, init, .. }) => {
1549 self.print_let(pat, ty, init);
1550 }
1551 hir::ExprKind::If(test, blk, elseopt) => {
1552 self.print_if(test, blk, elseopt);
1553 }
1554 hir::ExprKind::Loop(blk, opt_label, _, _) => {
1555 let cb = self.cbox(0);
1556 let ib = self.ibox(0);
1557 if let Some(label) = opt_label {
1558 self.print_ident(label.ident);
1559 self.word_space(":");
1560 }
1561 self.word_nbsp("loop");
1562 self.print_block(blk, cb, ib);
1563 }
1564 hir::ExprKind::Match(expr, arms, _) => {
1565 let cb = self.cbox(0);
1566 let ib = self.ibox(0);
1567 self.word_nbsp("match");
1568 self.print_expr_as_cond(expr);
1569 self.space();
1570 self.bopen(ib);
1571 for arm in arms {
1572 self.print_arm(arm);
1573 }
1574 self.bclose(expr.span, cb);
1575 }
1576 hir::ExprKind::Closure(&hir::Closure {
1577 binder,
1578 constness,
1579 capture_clause,
1580 bound_generic_params,
1581 fn_decl,
1582 body,
1583 fn_decl_span: _,
1584 fn_arg_span: _,
1585 kind: _,
1586 def_id: _,
1587 }) => {
1588 self.print_closure_binder(binder, bound_generic_params);
1589 self.print_constness(constness);
1590 self.print_capture_clause(capture_clause);
1591
1592 self.print_closure_params(fn_decl, body);
1593 self.space();
1594
1595 self.ann.nested(self, Nested::Body(body));
1597 }
1598 hir::ExprKind::Block(blk, opt_label) => {
1599 if let Some(label) = opt_label {
1600 self.print_ident(label.ident);
1601 self.word_space(":");
1602 }
1603 let cb = self.cbox(0);
1605 let ib = self.ibox(0);
1607 self.print_block(blk, cb, ib);
1608 }
1609 hir::ExprKind::Assign(lhs, rhs, _) => {
1610 self.print_expr_cond_paren(lhs, self.precedence(lhs) <= ExprPrecedence::Assign);
1611 self.space();
1612 self.word_space("=");
1613 self.print_expr_cond_paren(rhs, self.precedence(rhs) < ExprPrecedence::Assign);
1614 }
1615 hir::ExprKind::AssignOp(op, lhs, rhs) => {
1616 self.print_expr_cond_paren(lhs, self.precedence(lhs) <= ExprPrecedence::Assign);
1617 self.space();
1618 self.word_space(op.node.as_str());
1619 self.print_expr_cond_paren(rhs, self.precedence(rhs) < ExprPrecedence::Assign);
1620 }
1621 hir::ExprKind::Field(expr, ident) => {
1622 self.print_expr_cond_paren(
1623 expr,
1624 self.precedence(expr) < ExprPrecedence::Unambiguous,
1625 );
1626 self.word(".");
1627 self.print_ident(ident);
1628 }
1629 hir::ExprKind::Index(expr, index, _) => {
1630 self.print_expr_cond_paren(
1631 expr,
1632 self.precedence(expr) < ExprPrecedence::Unambiguous,
1633 );
1634 self.word("[");
1635 self.print_expr(index);
1636 self.word("]");
1637 }
1638 hir::ExprKind::Path(ref qpath) => self.print_qpath(qpath, true),
1639 hir::ExprKind::Break(destination, opt_expr) => {
1640 self.word("break");
1641 if let Some(label) = destination.label {
1642 self.space();
1643 self.print_ident(label.ident);
1644 }
1645 if let Some(expr) = opt_expr {
1646 self.space();
1647 self.print_expr_cond_paren(expr, self.precedence(expr) < ExprPrecedence::Jump);
1648 }
1649 }
1650 hir::ExprKind::Continue(destination) => {
1651 self.word("continue");
1652 if let Some(label) = destination.label {
1653 self.space();
1654 self.print_ident(label.ident);
1655 }
1656 }
1657 hir::ExprKind::Ret(result) => {
1658 self.word("return");
1659 if let Some(expr) = result {
1660 self.word(" ");
1661 self.print_expr_cond_paren(expr, self.precedence(expr) < ExprPrecedence::Jump);
1662 }
1663 }
1664 hir::ExprKind::Become(result) => {
1665 self.word("become");
1666 self.word(" ");
1667 self.print_expr_cond_paren(result, self.precedence(result) < ExprPrecedence::Jump);
1668 }
1669 hir::ExprKind::InlineAsm(asm) => {
1670 self.word("asm!");
1671 self.print_inline_asm(asm);
1672 }
1673 hir::ExprKind::OffsetOf(container, fields) => {
1674 self.word("offset_of!(");
1675 self.print_type(container);
1676 self.word(",");
1677 self.space();
1678
1679 if let Some((&first, rest)) = fields.split_first() {
1680 self.print_ident(first);
1681
1682 for &field in rest {
1683 self.word(".");
1684 self.print_ident(field);
1685 }
1686 }
1687
1688 self.word(")");
1689 }
1690 hir::ExprKind::UnsafeBinderCast(kind, expr, ty) => {
1691 match kind {
1692 ast::UnsafeBinderCastKind::Wrap => self.word("wrap_binder!("),
1693 ast::UnsafeBinderCastKind::Unwrap => self.word("unwrap_binder!("),
1694 }
1695 self.print_expr(expr);
1696 if let Some(ty) = ty {
1697 self.word(",");
1698 self.space();
1699 self.print_type(ty);
1700 }
1701 self.word(")");
1702 }
1703 hir::ExprKind::Yield(expr, _) => {
1704 self.word_space("yield");
1705 self.print_expr_cond_paren(expr, self.precedence(expr) < ExprPrecedence::Jump);
1706 }
1707 hir::ExprKind::Err(_) => {
1708 self.popen();
1709 self.word("/*ERROR*/");
1710 self.pclose();
1711 }
1712 }
1713 self.ann.post(self, AnnNode::Expr(expr));
1714 self.end(ib)
1715 }
1716
1717 fn print_local_decl(&mut self, loc: &hir::LetStmt<'_>) {
1718 self.print_pat(loc.pat);
1719 if let Some(ty) = loc.ty {
1720 self.word_space(":");
1721 self.print_type(ty);
1722 }
1723 }
1724
1725 fn print_name(&mut self, name: Symbol) {
1726 self.print_ident(Ident::with_dummy_span(name))
1727 }
1728
1729 fn print_path<R>(&mut self, path: &hir::Path<'_, R>, colons_before_params: bool) {
1730 self.maybe_print_comment(path.span.lo());
1731
1732 for (i, segment) in path.segments.iter().enumerate() {
1733 if i > 0 {
1734 self.word("::")
1735 }
1736 if segment.ident.name != kw::PathRoot {
1737 self.print_ident(segment.ident);
1738 self.print_generic_args(segment.args(), colons_before_params);
1739 }
1740 }
1741 }
1742
1743 fn print_path_segment(&mut self, segment: &hir::PathSegment<'_>) {
1744 if segment.ident.name != kw::PathRoot {
1745 self.print_ident(segment.ident);
1746 self.print_generic_args(segment.args(), false);
1747 }
1748 }
1749
1750 fn print_qpath(&mut self, qpath: &hir::QPath<'_>, colons_before_params: bool) {
1751 match *qpath {
1752 hir::QPath::Resolved(None, path) => self.print_path(path, colons_before_params),
1753 hir::QPath::Resolved(Some(qself), path) => {
1754 self.word("<");
1755 self.print_type(qself);
1756 self.space();
1757 self.word_space("as");
1758
1759 for (i, segment) in path.segments[..path.segments.len() - 1].iter().enumerate() {
1760 if i > 0 {
1761 self.word("::")
1762 }
1763 if segment.ident.name != kw::PathRoot {
1764 self.print_ident(segment.ident);
1765 self.print_generic_args(segment.args(), colons_before_params);
1766 }
1767 }
1768
1769 self.word(">");
1770 self.word("::");
1771 let item_segment = path.segments.last().unwrap();
1772 self.print_ident(item_segment.ident);
1773 self.print_generic_args(item_segment.args(), colons_before_params)
1774 }
1775 hir::QPath::TypeRelative(qself, item_segment) => {
1776 if let hir::TyKind::Path(hir::QPath::Resolved(None, _)) = qself.kind {
1780 self.print_type(qself);
1781 } else {
1782 self.word("<");
1783 self.print_type(qself);
1784 self.word(">");
1785 }
1786
1787 self.word("::");
1788 self.print_ident(item_segment.ident);
1789 self.print_generic_args(item_segment.args(), colons_before_params)
1790 }
1791 }
1792 }
1793
1794 fn print_generic_args(
1795 &mut self,
1796 generic_args: &hir::GenericArgs<'_>,
1797 colons_before_params: bool,
1798 ) {
1799 match generic_args.parenthesized {
1800 hir::GenericArgsParentheses::No => {
1801 let start = if colons_before_params { "::<" } else { "<" };
1802 let empty = Cell::new(true);
1803 let start_or_comma = |this: &mut Self| {
1804 if empty.get() {
1805 empty.set(false);
1806 this.word(start)
1807 } else {
1808 this.word_space(",")
1809 }
1810 };
1811
1812 let mut nonelided_generic_args: bool = false;
1813 let elide_lifetimes = generic_args.args.iter().all(|arg| match arg {
1814 GenericArg::Lifetime(lt) if lt.is_elided() => true,
1815 GenericArg::Lifetime(_) => {
1816 nonelided_generic_args = true;
1817 false
1818 }
1819 _ => {
1820 nonelided_generic_args = true;
1821 true
1822 }
1823 });
1824
1825 if nonelided_generic_args {
1826 start_or_comma(self);
1827 self.commasep(Inconsistent, generic_args.args, |s, generic_arg| {
1828 s.print_generic_arg(generic_arg, elide_lifetimes)
1829 });
1830 }
1831
1832 for constraint in generic_args.constraints {
1833 start_or_comma(self);
1834 self.print_assoc_item_constraint(constraint);
1835 }
1836
1837 if !empty.get() {
1838 self.word(">")
1839 }
1840 }
1841 hir::GenericArgsParentheses::ParenSugar => {
1842 let (inputs, output) = generic_args.paren_sugar_inputs_output().unwrap();
1843
1844 self.word("(");
1845 self.commasep(Inconsistent, inputs, |s, ty| s.print_type(ty));
1846 self.word(")");
1847
1848 self.space_if_not_bol();
1849 self.word_space("->");
1850 self.print_type(output);
1851 }
1852 hir::GenericArgsParentheses::ReturnTypeNotation => {
1853 self.word("(..)");
1854 }
1855 }
1856 }
1857
1858 fn print_assoc_item_constraint(&mut self, constraint: &hir::AssocItemConstraint<'_>) {
1859 self.print_ident(constraint.ident);
1860 self.print_generic_args(constraint.gen_args, false);
1861 self.space();
1862 match constraint.kind {
1863 hir::AssocItemConstraintKind::Equality { ref term } => {
1864 self.word_space("=");
1865 match term {
1866 Term::Ty(ty) => self.print_type(ty),
1867 Term::Const(c) => self.print_const_arg(c),
1868 }
1869 }
1870 hir::AssocItemConstraintKind::Bound { bounds } => {
1871 self.print_bounds(":", bounds);
1872 }
1873 }
1874 }
1875
1876 fn print_pat_expr(&mut self, expr: &hir::PatExpr<'_>) {
1877 match &expr.kind {
1878 hir::PatExprKind::Lit { lit, negated } => {
1879 if *negated {
1880 self.word("-");
1881 }
1882 self.print_literal(lit);
1883 }
1884 hir::PatExprKind::ConstBlock(c) => self.print_inline_const(c),
1885 hir::PatExprKind::Path(qpath) => self.print_qpath(qpath, true),
1886 }
1887 }
1888
1889 fn print_ty_pat(&mut self, pat: &hir::TyPat<'_>) {
1890 self.maybe_print_comment(pat.span.lo());
1891 self.ann.pre(self, AnnNode::TyPat(pat));
1892 match pat.kind {
1895 TyPatKind::Range(begin, end) => {
1896 self.print_const_arg(begin);
1897 self.word("..=");
1898 self.print_const_arg(end);
1899 }
1900 TyPatKind::NotNull => {
1901 self.word_space("not");
1902 self.word("null");
1903 }
1904 TyPatKind::Or(patterns) => {
1905 self.popen();
1906 let mut first = true;
1907 for pat in patterns {
1908 if first {
1909 first = false;
1910 } else {
1911 self.word(" | ");
1912 }
1913 self.print_ty_pat(pat);
1914 }
1915 self.pclose();
1916 }
1917 TyPatKind::Err(_) => {
1918 self.popen();
1919 self.word("/*ERROR*/");
1920 self.pclose();
1921 }
1922 }
1923 self.ann.post(self, AnnNode::TyPat(pat))
1924 }
1925
1926 fn print_pat(&mut self, pat: &hir::Pat<'_>) {
1927 self.maybe_print_comment(pat.span.lo());
1928 self.ann.pre(self, AnnNode::Pat(pat));
1929 match pat.kind {
1931 PatKind::Missing => self.word("_"),
1934 PatKind::Wild => self.word("_"),
1935 PatKind::Never => self.word("!"),
1936 PatKind::Binding(BindingMode(by_ref, mutbl), _, ident, sub) => {
1937 if mutbl.is_mut() {
1938 self.word_nbsp("mut");
1939 }
1940 if let ByRef::Yes(pinnedness, rmutbl) = by_ref {
1941 self.word_nbsp("ref");
1942 if pinnedness.is_pinned() {
1943 self.word_nbsp("pin");
1944 }
1945 if rmutbl.is_mut() {
1946 self.word_nbsp("mut");
1947 } else if pinnedness.is_pinned() {
1948 self.word_nbsp("const");
1949 }
1950 }
1951 self.print_ident(ident);
1952 if let Some(p) = sub {
1953 self.word("@");
1954 self.print_pat(p);
1955 }
1956 }
1957 PatKind::TupleStruct(ref qpath, elts, ddpos) => {
1958 self.print_qpath(qpath, true);
1959 self.popen();
1960 if let Some(ddpos) = ddpos.as_opt_usize() {
1961 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(p));
1962 if ddpos != 0 {
1963 self.word_space(",");
1964 }
1965 self.word("..");
1966 if ddpos != elts.len() {
1967 self.word(",");
1968 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(p));
1969 }
1970 } else {
1971 self.commasep(Inconsistent, elts, |s, p| s.print_pat(p));
1972 }
1973 self.pclose();
1974 }
1975 PatKind::Struct(ref qpath, fields, etc) => {
1976 self.print_qpath(qpath, true);
1977 self.nbsp();
1978 self.word("{");
1979 let empty = fields.is_empty() && etc.is_none();
1980 if !empty {
1981 self.space();
1982 }
1983 self.commasep_cmnt(Consistent, fields, |s, f| s.print_patfield(f), |f| f.pat.span);
1984 if etc.is_some() {
1985 if !fields.is_empty() {
1986 self.word_space(",");
1987 }
1988 self.word("..");
1989 }
1990 if !empty {
1991 self.space();
1992 }
1993 self.word("}");
1994 }
1995 PatKind::Or(pats) => {
1996 self.strsep("|", true, Inconsistent, pats, |s, p| s.print_pat(p));
1997 }
1998 PatKind::Tuple(elts, ddpos) => {
1999 self.popen();
2000 if let Some(ddpos) = ddpos.as_opt_usize() {
2001 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(p));
2002 if ddpos != 0 {
2003 self.word_space(",");
2004 }
2005 self.word("..");
2006 if ddpos != elts.len() {
2007 self.word(",");
2008 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(p));
2009 }
2010 } else {
2011 self.commasep(Inconsistent, elts, |s, p| s.print_pat(p));
2012 if elts.len() == 1 {
2013 self.word(",");
2014 }
2015 }
2016 self.pclose();
2017 }
2018 PatKind::Box(inner) => {
2019 let is_range_inner = matches!(inner.kind, PatKind::Range(..));
2020 self.word("box ");
2021 if is_range_inner {
2022 self.popen();
2023 }
2024 self.print_pat(inner);
2025 if is_range_inner {
2026 self.pclose();
2027 }
2028 }
2029 PatKind::Deref(inner) => {
2030 self.word("deref!");
2031 self.popen();
2032 self.print_pat(inner);
2033 self.pclose();
2034 }
2035 PatKind::Ref(inner, pinned, mutbl) => {
2036 let is_range_inner = matches!(inner.kind, PatKind::Range(..));
2037 self.word("&");
2038 if pinned.is_pinned() {
2039 self.word("pin ");
2040 if mutbl.is_not() {
2041 self.word("const ");
2042 }
2043 }
2044 self.word(mutbl.prefix_str());
2045 if is_range_inner {
2046 self.popen();
2047 }
2048 self.print_pat(inner);
2049 if is_range_inner {
2050 self.pclose();
2051 }
2052 }
2053 PatKind::Expr(e) => self.print_pat_expr(e),
2054 PatKind::Range(begin, end, end_kind) => {
2055 if let Some(expr) = begin {
2056 self.print_pat_expr(expr);
2057 }
2058 match end_kind {
2059 RangeEnd::Included => self.word("..."),
2060 RangeEnd::Excluded => self.word(".."),
2061 }
2062 if let Some(expr) = end {
2063 self.print_pat_expr(expr);
2064 }
2065 }
2066 PatKind::Slice(before, slice, after) => {
2067 self.word("[");
2068 self.commasep(Inconsistent, before, |s, p| s.print_pat(p));
2069 if let Some(p) = slice {
2070 if !before.is_empty() {
2071 self.word_space(",");
2072 }
2073 if let PatKind::Wild = p.kind {
2074 } else {
2076 self.print_pat(p);
2077 }
2078 self.word("..");
2079 if !after.is_empty() {
2080 self.word_space(",");
2081 }
2082 }
2083 self.commasep(Inconsistent, after, |s, p| s.print_pat(p));
2084 self.word("]");
2085 }
2086 PatKind::Guard(inner, cond) => {
2087 self.print_pat(inner);
2088 self.space();
2089 self.word_space("if");
2090 self.print_expr(cond);
2091 }
2092 PatKind::Err(_) => {
2093 self.popen();
2094 self.word("/*ERROR*/");
2095 self.pclose();
2096 }
2097 }
2098 self.ann.post(self, AnnNode::Pat(pat))
2099 }
2100
2101 fn print_patfield(&mut self, field: &hir::PatField<'_>) {
2102 if self.attrs(field.hir_id).is_empty() {
2103 self.space();
2104 }
2105 let cb = self.cbox(INDENT_UNIT);
2106 self.print_attrs(self.attrs(field.hir_id));
2107 if !field.is_shorthand {
2108 self.print_ident(field.ident);
2109 self.word_nbsp(":");
2110 }
2111 self.print_pat(field.pat);
2112 self.end(cb);
2113 }
2114
2115 fn print_param(&mut self, arg: &hir::Param<'_>) {
2116 self.print_attrs(self.attrs(arg.hir_id));
2117 self.print_pat(arg.pat);
2118 }
2119
2120 fn print_implicit_self(&mut self, implicit_self_kind: &hir::ImplicitSelfKind) {
2121 match implicit_self_kind {
2122 ImplicitSelfKind::Imm => {
2123 self.word("self");
2124 }
2125 ImplicitSelfKind::Mut => {
2126 self.print_mutability(hir::Mutability::Mut, false);
2127 self.word("self");
2128 }
2129 ImplicitSelfKind::RefImm => {
2130 self.word("&");
2131 self.word("self");
2132 }
2133 ImplicitSelfKind::RefMut => {
2134 self.word("&");
2135 self.print_mutability(hir::Mutability::Mut, false);
2136 self.word("self");
2137 }
2138 ImplicitSelfKind::None => unreachable!(),
2139 }
2140 }
2141
2142 fn print_arm(&mut self, arm: &hir::Arm<'_>) {
2143 if self.attrs(arm.hir_id).is_empty() {
2146 self.space();
2147 }
2148 let cb = self.cbox(INDENT_UNIT);
2149 self.ann.pre(self, AnnNode::Arm(arm));
2150 let ib = self.ibox(0);
2151 self.print_attrs(self.attrs(arm.hir_id));
2152 self.print_pat(arm.pat);
2153 self.space();
2154 if let Some(ref g) = arm.guard {
2155 self.word_space("if");
2156 self.print_expr(g);
2157 self.space();
2158 }
2159 self.word_space("=>");
2160
2161 match arm.body.kind {
2162 hir::ExprKind::Block(blk, opt_label) => {
2163 if let Some(label) = opt_label {
2164 self.print_ident(label.ident);
2165 self.word_space(":");
2166 }
2167 self.print_block_unclosed(blk, ib);
2168
2169 if let hir::BlockCheckMode::UnsafeBlock(hir::UnsafeSource::UserProvided) = blk.rules
2171 {
2172 self.word(",");
2173 }
2174 }
2175 _ => {
2176 self.end(ib);
2177 self.print_expr(arm.body);
2178 self.word(",");
2179 }
2180 }
2181 self.ann.post(self, AnnNode::Arm(arm));
2182 self.end(cb)
2183 }
2184
2185 fn print_fn(
2186 &mut self,
2187 header: hir::FnHeader,
2188 name: Option<Symbol>,
2189 generics: &hir::Generics<'_>,
2190 decl: &hir::FnDecl<'_>,
2191 arg_idents: &[Option<Ident>],
2192 body_id: Option<hir::BodyId>,
2193 ) {
2194 self.print_fn_header_info(header);
2195
2196 if let Some(name) = name {
2197 self.nbsp();
2198 self.print_name(name);
2199 }
2200 self.print_generic_params(generics.params);
2201
2202 self.popen();
2203 assert!(arg_idents.is_empty() || body_id.is_none());
2205 let mut i = 0;
2206 let mut print_arg = |s: &mut Self, ty: Option<&hir::Ty<'_>>| {
2207 if i == 0 && decl.implicit_self.has_implicit_self() {
2208 s.print_implicit_self(&decl.implicit_self);
2209 } else {
2210 if let Some(arg_ident) = arg_idents.get(i) {
2211 if let Some(arg_ident) = arg_ident {
2212 s.word(arg_ident.to_string());
2213 s.word(":");
2214 s.space();
2215 }
2216 } else if let Some(body_id) = body_id {
2217 s.ann.nested(s, Nested::BodyParamPat(body_id, i));
2218 s.word(":");
2219 s.space();
2220 }
2221 if let Some(ty) = ty {
2222 s.print_type(ty);
2223 }
2224 }
2225 i += 1;
2226 };
2227 self.commasep(Inconsistent, decl.inputs, |s, ty| {
2228 let ib = s.ibox(INDENT_UNIT);
2229 print_arg(s, Some(ty));
2230 s.end(ib);
2231 });
2232 if decl.c_variadic {
2233 if !decl.inputs.is_empty() {
2234 self.word(", ");
2235 }
2236 print_arg(self, None);
2237 self.word("...");
2238 }
2239 self.pclose();
2240
2241 self.print_fn_output(decl);
2242 self.print_where_clause(generics)
2243 }
2244
2245 fn print_closure_params(&mut self, decl: &hir::FnDecl<'_>, body_id: hir::BodyId) {
2246 self.word("|");
2247 let mut i = 0;
2248 self.commasep(Inconsistent, decl.inputs, |s, ty| {
2249 let ib = s.ibox(INDENT_UNIT);
2250
2251 s.ann.nested(s, Nested::BodyParamPat(body_id, i));
2252 i += 1;
2253
2254 if let hir::TyKind::Infer(()) = ty.kind {
2255 } else {
2257 s.word(":");
2258 s.space();
2259 s.print_type(ty);
2260 }
2261 s.end(ib);
2262 });
2263 self.word("|");
2264
2265 match decl.output {
2266 hir::FnRetTy::Return(ty) => {
2267 self.space_if_not_bol();
2268 self.word_space("->");
2269 self.print_type(ty);
2270 self.maybe_print_comment(ty.span.lo());
2271 }
2272 hir::FnRetTy::DefaultReturn(..) => {}
2273 }
2274 }
2275
2276 fn print_capture_clause(&mut self, capture_clause: hir::CaptureBy) {
2277 match capture_clause {
2278 hir::CaptureBy::Value { .. } => self.word_space("move"),
2279 hir::CaptureBy::Use { .. } => self.word_space("use"),
2280 hir::CaptureBy::Ref => {}
2281 }
2282 }
2283
2284 fn print_closure_binder(
2285 &mut self,
2286 binder: hir::ClosureBinder,
2287 generic_params: &[GenericParam<'_>],
2288 ) {
2289 let generic_params = generic_params
2290 .iter()
2291 .filter(|p| {
2292 matches!(
2293 p,
2294 GenericParam {
2295 kind: GenericParamKind::Lifetime { kind: LifetimeParamKind::Explicit },
2296 ..
2297 }
2298 )
2299 })
2300 .collect::<Vec<_>>();
2301
2302 match binder {
2303 hir::ClosureBinder::Default => {}
2304 hir::ClosureBinder::For { .. } if generic_params.is_empty() => self.word("for<>"),
2307 hir::ClosureBinder::For { .. } => {
2308 self.word("for");
2309 self.word("<");
2310
2311 self.commasep(Inconsistent, &generic_params, |s, param| {
2312 s.print_generic_param(param)
2313 });
2314
2315 self.word(">");
2316 self.nbsp();
2317 }
2318 }
2319 }
2320
2321 fn print_bounds<'b>(
2322 &mut self,
2323 prefix: &'static str,
2324 bounds: impl IntoIterator<Item = &'b hir::GenericBound<'b>>,
2325 ) {
2326 let mut first = true;
2327 for bound in bounds {
2328 if first {
2329 self.word(prefix);
2330 }
2331 if !(first && prefix.is_empty()) {
2332 self.nbsp();
2333 }
2334 if first {
2335 first = false;
2336 } else {
2337 self.word_space("+");
2338 }
2339
2340 match bound {
2341 GenericBound::Trait(tref) => {
2342 self.print_poly_trait_ref(tref);
2343 }
2344 GenericBound::Outlives(lt) => {
2345 self.print_lifetime(lt);
2346 }
2347 GenericBound::Use(args, _) => {
2348 self.word("use <");
2349
2350 self.commasep(Inconsistent, *args, |s, arg| {
2351 s.print_precise_capturing_arg(*arg)
2352 });
2353
2354 self.word(">");
2355 }
2356 }
2357 }
2358 }
2359
2360 fn print_precise_capturing_arg(&mut self, arg: PreciseCapturingArg<'_>) {
2361 match arg {
2362 PreciseCapturingArg::Lifetime(lt) => self.print_lifetime(lt),
2363 PreciseCapturingArg::Param(arg) => self.print_ident(arg.ident),
2364 }
2365 }
2366
2367 fn print_generic_params(&mut self, generic_params: &[GenericParam<'_>]) {
2368 let is_lifetime_elided = |generic_param: &GenericParam<'_>| {
2369 matches!(
2370 generic_param.kind,
2371 GenericParamKind::Lifetime { kind: LifetimeParamKind::Elided(_) }
2372 )
2373 };
2374
2375 if !generic_params.is_empty() && !generic_params.iter().all(is_lifetime_elided) {
2378 self.word("<");
2379
2380 self.commasep(
2381 Inconsistent,
2382 generic_params.iter().filter(|gp| !is_lifetime_elided(gp)),
2383 |s, param| s.print_generic_param(param),
2384 );
2385
2386 self.word(">");
2387 }
2388 }
2389
2390 fn print_generic_param(&mut self, param: &GenericParam<'_>) {
2391 if let GenericParamKind::Const { .. } = param.kind {
2392 self.word_space("const");
2393 }
2394
2395 self.print_ident(param.name.ident());
2396
2397 match param.kind {
2398 GenericParamKind::Lifetime { .. } => {}
2399 GenericParamKind::Type { default, .. } => {
2400 if let Some(default) = default {
2401 self.space();
2402 self.word_space("=");
2403 self.print_type(default);
2404 }
2405 }
2406 GenericParamKind::Const { ty, ref default } => {
2407 self.word_space(":");
2408 self.print_type(ty);
2409 if let Some(default) = default {
2410 self.space();
2411 self.word_space("=");
2412 self.print_const_arg(default);
2413 }
2414 }
2415 }
2416 }
2417
2418 fn print_lifetime(&mut self, lifetime: &hir::Lifetime) {
2419 self.print_ident(lifetime.ident)
2420 }
2421
2422 fn print_where_clause(&mut self, generics: &hir::Generics<'_>) {
2423 if generics.predicates.is_empty() {
2424 return;
2425 }
2426
2427 self.space();
2428 self.word_space("where");
2429
2430 for (i, predicate) in generics.predicates.iter().enumerate() {
2431 if i != 0 {
2432 self.word_space(",");
2433 }
2434 self.print_where_predicate(predicate);
2435 }
2436 }
2437
2438 fn print_where_predicate(&mut self, predicate: &hir::WherePredicate<'_>) {
2439 self.print_attrs(self.attrs(predicate.hir_id));
2440 match *predicate.kind {
2441 hir::WherePredicateKind::BoundPredicate(hir::WhereBoundPredicate {
2442 bound_generic_params,
2443 bounded_ty,
2444 bounds,
2445 ..
2446 }) => {
2447 self.print_formal_generic_params(bound_generic_params);
2448 self.print_type(bounded_ty);
2449 self.print_bounds(":", bounds);
2450 }
2451 hir::WherePredicateKind::RegionPredicate(hir::WhereRegionPredicate {
2452 lifetime,
2453 bounds,
2454 ..
2455 }) => {
2456 self.print_lifetime(lifetime);
2457 self.word(":");
2458
2459 for (i, bound) in bounds.iter().enumerate() {
2460 match bound {
2461 GenericBound::Outlives(lt) => {
2462 self.print_lifetime(lt);
2463 }
2464 _ => panic!("unexpected bound on lifetime param: {bound:?}"),
2465 }
2466
2467 if i != 0 {
2468 self.word(":");
2469 }
2470 }
2471 }
2472 hir::WherePredicateKind::EqPredicate(hir::WhereEqPredicate {
2473 lhs_ty, rhs_ty, ..
2474 }) => {
2475 self.print_type(lhs_ty);
2476 self.space();
2477 self.word_space("=");
2478 self.print_type(rhs_ty);
2479 }
2480 }
2481 }
2482
2483 fn print_mutability(&mut self, mutbl: hir::Mutability, print_const: bool) {
2484 match mutbl {
2485 hir::Mutability::Mut => self.word_nbsp("mut"),
2486 hir::Mutability::Not => {
2487 if print_const {
2488 self.word_nbsp("const")
2489 }
2490 }
2491 }
2492 }
2493
2494 fn print_mt(&mut self, mt: &hir::MutTy<'_>, print_const: bool) {
2495 self.print_mutability(mt.mutbl, print_const);
2496 self.print_type(mt.ty);
2497 }
2498
2499 fn print_fn_output(&mut self, decl: &hir::FnDecl<'_>) {
2500 match decl.output {
2501 hir::FnRetTy::Return(ty) => {
2502 self.space_if_not_bol();
2503 let ib = self.ibox(INDENT_UNIT);
2504 self.word_space("->");
2505 self.print_type(ty);
2506 self.end(ib);
2507
2508 if let hir::FnRetTy::Return(output) = decl.output {
2509 self.maybe_print_comment(output.span.lo());
2510 }
2511 }
2512 hir::FnRetTy::DefaultReturn(..) => {}
2513 }
2514 }
2515
2516 fn print_ty_fn(
2517 &mut self,
2518 abi: ExternAbi,
2519 safety: hir::Safety,
2520 decl: &hir::FnDecl<'_>,
2521 name: Option<Symbol>,
2522 generic_params: &[hir::GenericParam<'_>],
2523 arg_idents: &[Option<Ident>],
2524 ) {
2525 let ib = self.ibox(INDENT_UNIT);
2526 self.print_formal_generic_params(generic_params);
2527 let generics = hir::Generics::empty();
2528 self.print_fn(
2529 hir::FnHeader {
2530 safety: safety.into(),
2531 abi,
2532 constness: hir::Constness::NotConst,
2533 asyncness: hir::IsAsync::NotAsync,
2534 },
2535 name,
2536 generics,
2537 decl,
2538 arg_idents,
2539 None,
2540 );
2541 self.end(ib);
2542 }
2543
2544 fn print_fn_header_info(&mut self, header: hir::FnHeader) {
2545 self.print_constness(header.constness);
2546
2547 let safety = match header.safety {
2548 hir::HeaderSafety::SafeTargetFeatures => {
2549 self.word_nbsp("#[target_feature]");
2550 hir::Safety::Safe
2551 }
2552 hir::HeaderSafety::Normal(safety) => safety,
2553 };
2554
2555 match header.asyncness {
2556 hir::IsAsync::NotAsync => {}
2557 hir::IsAsync::Async(_) => self.word_nbsp("async"),
2558 }
2559
2560 self.print_safety(safety);
2561
2562 if header.abi != ExternAbi::Rust {
2563 self.word_nbsp("extern");
2564 self.word_nbsp(header.abi.to_string());
2565 }
2566
2567 self.word("fn")
2568 }
2569
2570 fn print_constness(&mut self, s: hir::Constness) {
2571 match s {
2572 hir::Constness::NotConst => {}
2573 hir::Constness::Const => self.word_nbsp("const"),
2574 }
2575 }
2576
2577 fn print_safety(&mut self, s: hir::Safety) {
2578 match s {
2579 hir::Safety::Safe => {}
2580 hir::Safety::Unsafe => self.word_nbsp("unsafe"),
2581 }
2582 }
2583
2584 fn print_is_auto(&mut self, s: hir::IsAuto) {
2585 match s {
2586 hir::IsAuto::Yes => self.word_nbsp("auto"),
2587 hir::IsAuto::No => {}
2588 }
2589 }
2590}
2591
2592fn expr_requires_semi_to_be_stmt(e: &hir::Expr<'_>) -> bool {
2602 !matches!(
2603 e.kind,
2604 hir::ExprKind::If(..)
2605 | hir::ExprKind::Match(..)
2606 | hir::ExprKind::Block(..)
2607 | hir::ExprKind::Loop(..)
2608 )
2609}
2610
2611fn stmt_ends_with_semi(stmt: &hir::StmtKind<'_>) -> bool {
2615 match *stmt {
2616 hir::StmtKind::Let(_) => true,
2617 hir::StmtKind::Item(_) => false,
2618 hir::StmtKind::Expr(e) => expr_requires_semi_to_be_stmt(e),
2619 hir::StmtKind::Semi(..) => false,
2620 }
2621}
2622
2623fn contains_exterior_struct_lit(value: &hir::Expr<'_>) -> bool {
2627 match value.kind {
2628 hir::ExprKind::Struct(..) => true,
2629
2630 hir::ExprKind::Assign(lhs, rhs, _)
2631 | hir::ExprKind::AssignOp(_, lhs, rhs)
2632 | hir::ExprKind::Binary(_, lhs, rhs) => {
2633 contains_exterior_struct_lit(lhs) || contains_exterior_struct_lit(rhs)
2635 }
2636 hir::ExprKind::Unary(_, x)
2637 | hir::ExprKind::Cast(x, _)
2638 | hir::ExprKind::Type(x, _)
2639 | hir::ExprKind::Field(x, _)
2640 | hir::ExprKind::Index(x, _, _) => {
2641 contains_exterior_struct_lit(x)
2643 }
2644
2645 hir::ExprKind::MethodCall(_, receiver, ..) => {
2646 contains_exterior_struct_lit(receiver)
2648 }
2649
2650 _ => false,
2651 }
2652}