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