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