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::BodyId>,
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(expr) = default {
534 self.space();
535 self.word_space("=");
536 self.ann.nested(self, Nested::Body(expr));
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, expr) => {
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.ann.nested(self, Nested::Body(expr));
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_arg(&mut self, const_arg: &hir::ConstArg<'_>) {
1131 match &const_arg.kind {
1132 ConstArgKind::Path(qpath) => self.print_qpath(qpath, true),
1133 ConstArgKind::Anon(anon) => self.print_anon_const(anon),
1134 ConstArgKind::Infer(..) => self.word("_"),
1135 }
1136 }
1137
1138 fn print_call_post(&mut self, args: &[hir::Expr<'_>]) {
1139 self.popen();
1140 self.commasep_exprs(Inconsistent, args);
1141 self.pclose()
1142 }
1143
1144 fn print_expr_as_cond(&mut self, expr: &hir::Expr<'_>) {
1147 self.print_expr_cond_paren(expr, Self::cond_needs_par(expr))
1148 }
1149
1150 fn print_expr_cond_paren(&mut self, expr: &hir::Expr<'_>, needs_par: bool) {
1152 if needs_par {
1153 self.popen();
1154 }
1155 if let hir::ExprKind::DropTemps(actual_expr) = expr.kind {
1156 self.print_expr(actual_expr);
1157 } else {
1158 self.print_expr(expr);
1159 }
1160 if needs_par {
1161 self.pclose();
1162 }
1163 }
1164
1165 fn print_let(&mut self, pat: &hir::Pat<'_>, ty: Option<&hir::Ty<'_>>, init: &hir::Expr<'_>) {
1167 self.word_space("let");
1168 self.print_pat(pat);
1169 if let Some(ty) = ty {
1170 self.word_space(":");
1171 self.print_type(ty);
1172 }
1173 self.space();
1174 self.word_space("=");
1175 let npals = || parser::needs_par_as_let_scrutinee(self.precedence(init));
1176 self.print_expr_cond_paren(init, Self::cond_needs_par(init) || npals())
1177 }
1178
1179 fn cond_needs_par(expr: &hir::Expr<'_>) -> bool {
1184 match expr.kind {
1185 hir::ExprKind::Break(..) | hir::ExprKind::Closure { .. } | hir::ExprKind::Ret(..) => {
1186 true
1187 }
1188 _ => contains_exterior_struct_lit(expr),
1189 }
1190 }
1191
1192 fn print_expr_vec(&mut self, exprs: &[hir::Expr<'_>]) {
1193 let ib = self.ibox(INDENT_UNIT);
1194 self.word("[");
1195 self.commasep_exprs(Inconsistent, exprs);
1196 self.word("]");
1197 self.end(ib)
1198 }
1199
1200 fn print_inline_const(&mut self, constant: &hir::ConstBlock) {
1201 let ib = self.ibox(INDENT_UNIT);
1202 self.word_space("const");
1203 self.ann.nested(self, Nested::Body(constant.body));
1204 self.end(ib)
1205 }
1206
1207 fn print_expr_repeat(&mut self, element: &hir::Expr<'_>, count: &hir::ConstArg<'_>) {
1208 let ib = self.ibox(INDENT_UNIT);
1209 self.word("[");
1210 self.print_expr(element);
1211 self.word_space(";");
1212 self.print_const_arg(count);
1213 self.word("]");
1214 self.end(ib)
1215 }
1216
1217 fn print_expr_struct(
1218 &mut self,
1219 qpath: &hir::QPath<'_>,
1220 fields: &[hir::ExprField<'_>],
1221 wth: hir::StructTailExpr<'_>,
1222 ) {
1223 self.print_qpath(qpath, true);
1224 self.nbsp();
1225 self.word_space("{");
1226 self.commasep_cmnt(Consistent, fields, |s, field| s.print_expr_field(field), |f| f.span);
1227 match wth {
1228 hir::StructTailExpr::Base(expr) => {
1229 let ib = self.ibox(INDENT_UNIT);
1230 if !fields.is_empty() {
1231 self.word(",");
1232 self.space();
1233 }
1234 self.word("..");
1235 self.print_expr(expr);
1236 self.end(ib);
1237 }
1238 hir::StructTailExpr::DefaultFields(_) => {
1239 let ib = self.ibox(INDENT_UNIT);
1240 if !fields.is_empty() {
1241 self.word(",");
1242 self.space();
1243 }
1244 self.word("..");
1245 self.end(ib);
1246 }
1247 hir::StructTailExpr::None => {}
1248 }
1249 self.space();
1250 self.word("}");
1251 }
1252
1253 fn print_expr_field(&mut self, field: &hir::ExprField<'_>) {
1254 let cb = self.cbox(INDENT_UNIT);
1255 self.print_attrs(self.attrs(field.hir_id));
1256 if !field.is_shorthand {
1257 self.print_ident(field.ident);
1258 self.word_space(":");
1259 }
1260 self.print_expr(field.expr);
1261 self.end(cb)
1262 }
1263
1264 fn print_expr_tup(&mut self, exprs: &[hir::Expr<'_>]) {
1265 self.popen();
1266 self.commasep_exprs(Inconsistent, exprs);
1267 if exprs.len() == 1 {
1268 self.word(",");
1269 }
1270 self.pclose()
1271 }
1272
1273 fn print_expr_call(&mut self, func: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
1274 let needs_paren = match func.kind {
1275 hir::ExprKind::Field(..) => true,
1276 _ => self.precedence(func) < ExprPrecedence::Unambiguous,
1277 };
1278
1279 self.print_expr_cond_paren(func, needs_paren);
1280 self.print_call_post(args)
1281 }
1282
1283 fn print_expr_method_call(
1284 &mut self,
1285 segment: &hir::PathSegment<'_>,
1286 receiver: &hir::Expr<'_>,
1287 args: &[hir::Expr<'_>],
1288 ) {
1289 let base_args = args;
1290 self.print_expr_cond_paren(
1291 receiver,
1292 self.precedence(receiver) < ExprPrecedence::Unambiguous,
1293 );
1294 self.word(".");
1295 self.print_ident(segment.ident);
1296
1297 let generic_args = segment.args();
1298 if !generic_args.args.is_empty() || !generic_args.constraints.is_empty() {
1299 self.print_generic_args(generic_args, true);
1300 }
1301
1302 self.print_call_post(base_args)
1303 }
1304
1305 fn print_expr_binary(&mut self, op: hir::BinOpKind, lhs: &hir::Expr<'_>, rhs: &hir::Expr<'_>) {
1306 let binop_prec = op.precedence();
1307 let left_prec = self.precedence(lhs);
1308 let right_prec = self.precedence(rhs);
1309
1310 let (mut left_needs_paren, right_needs_paren) = match op.fixity() {
1311 Fixity::Left => (left_prec < binop_prec, right_prec <= binop_prec),
1312 Fixity::Right => (left_prec <= binop_prec, right_prec < binop_prec),
1313 Fixity::None => (left_prec <= binop_prec, right_prec <= binop_prec),
1314 };
1315
1316 match (&lhs.kind, op) {
1317 (&hir::ExprKind::Cast { .. }, hir::BinOpKind::Lt | hir::BinOpKind::Shl) => {
1321 left_needs_paren = true;
1322 }
1323 (&hir::ExprKind::Let { .. }, _) if !parser::needs_par_as_let_scrutinee(binop_prec) => {
1324 left_needs_paren = true;
1325 }
1326 _ => {}
1327 }
1328
1329 self.print_expr_cond_paren(lhs, left_needs_paren);
1330 self.space();
1331 self.word_space(op.as_str());
1332 self.print_expr_cond_paren(rhs, right_needs_paren);
1333 }
1334
1335 fn print_expr_unary(&mut self, op: hir::UnOp, expr: &hir::Expr<'_>) {
1336 self.word(op.as_str());
1337 self.print_expr_cond_paren(expr, self.precedence(expr) < ExprPrecedence::Prefix);
1338 }
1339
1340 fn print_expr_addr_of(
1341 &mut self,
1342 kind: hir::BorrowKind,
1343 mutability: hir::Mutability,
1344 expr: &hir::Expr<'_>,
1345 ) {
1346 self.word("&");
1347 match kind {
1348 hir::BorrowKind::Ref => self.print_mutability(mutability, false),
1349 hir::BorrowKind::Raw => {
1350 self.word_nbsp("raw");
1351 self.print_mutability(mutability, true);
1352 }
1353 hir::BorrowKind::Pin => {
1354 self.word_nbsp("pin");
1355 self.print_mutability(mutability, true);
1356 }
1357 }
1358 self.print_expr_cond_paren(expr, self.precedence(expr) < ExprPrecedence::Prefix);
1359 }
1360
1361 fn print_literal(&mut self, lit: &hir::Lit) {
1362 self.maybe_print_comment(lit.span.lo());
1363 self.word(lit.node.to_string())
1364 }
1365
1366 fn print_inline_asm(&mut self, asm: &hir::InlineAsm<'_>) {
1367 enum AsmArg<'a> {
1368 Template(String),
1369 Operand(&'a hir::InlineAsmOperand<'a>),
1370 Options(ast::InlineAsmOptions),
1371 }
1372
1373 let mut args = vec![AsmArg::Template(ast::InlineAsmTemplatePiece::to_string(asm.template))];
1374 args.extend(asm.operands.iter().map(|(o, _)| AsmArg::Operand(o)));
1375 if !asm.options.is_empty() {
1376 args.push(AsmArg::Options(asm.options));
1377 }
1378
1379 self.popen();
1380 self.commasep(Consistent, &args, |s, arg| match *arg {
1381 AsmArg::Template(ref template) => s.print_string(template, ast::StrStyle::Cooked),
1382 AsmArg::Operand(op) => match *op {
1383 hir::InlineAsmOperand::In { reg, expr } => {
1384 s.word("in");
1385 s.popen();
1386 s.word(format!("{reg}"));
1387 s.pclose();
1388 s.space();
1389 s.print_expr(expr);
1390 }
1391 hir::InlineAsmOperand::Out { reg, late, ref expr } => {
1392 s.word(if late { "lateout" } else { "out" });
1393 s.popen();
1394 s.word(format!("{reg}"));
1395 s.pclose();
1396 s.space();
1397 match expr {
1398 Some(expr) => s.print_expr(expr),
1399 None => s.word("_"),
1400 }
1401 }
1402 hir::InlineAsmOperand::InOut { reg, late, expr } => {
1403 s.word(if late { "inlateout" } else { "inout" });
1404 s.popen();
1405 s.word(format!("{reg}"));
1406 s.pclose();
1407 s.space();
1408 s.print_expr(expr);
1409 }
1410 hir::InlineAsmOperand::SplitInOut { reg, late, in_expr, ref out_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(in_expr);
1417 s.space();
1418 s.word_space("=>");
1419 match out_expr {
1420 Some(out_expr) => s.print_expr(out_expr),
1421 None => s.word("_"),
1422 }
1423 }
1424 hir::InlineAsmOperand::Const { ref anon_const } => {
1425 s.word("const");
1426 s.space();
1427 s.ann.nested(s, Nested::Body(anon_const.body))
1429 }
1430 hir::InlineAsmOperand::SymFn { ref expr } => {
1431 s.word("sym_fn");
1432 s.space();
1433 s.print_expr(expr);
1434 }
1435 hir::InlineAsmOperand::SymStatic { ref path, def_id: _ } => {
1436 s.word("sym_static");
1437 s.space();
1438 s.print_qpath(path, true);
1439 }
1440 hir::InlineAsmOperand::Label { block } => {
1441 let (cb, ib) = s.head("label");
1442 s.print_block(block, cb, ib);
1443 }
1444 },
1445 AsmArg::Options(opts) => {
1446 s.word("options");
1447 s.popen();
1448 s.commasep(Inconsistent, &opts.human_readable_names(), |s, &opt| {
1449 s.word(opt);
1450 });
1451 s.pclose();
1452 }
1453 });
1454 self.pclose();
1455 }
1456
1457 fn print_expr(&mut self, expr: &hir::Expr<'_>) {
1458 self.maybe_print_comment(expr.span.lo());
1459 self.print_attrs(self.attrs(expr.hir_id));
1460 let ib = self.ibox(INDENT_UNIT);
1461 self.ann.pre(self, AnnNode::Expr(expr));
1462 match expr.kind {
1463 hir::ExprKind::Array(exprs) => {
1464 self.print_expr_vec(exprs);
1465 }
1466 hir::ExprKind::ConstBlock(ref anon_const) => {
1467 self.print_inline_const(anon_const);
1468 }
1469 hir::ExprKind::Repeat(element, ref count) => {
1470 self.print_expr_repeat(element, count);
1471 }
1472 hir::ExprKind::Struct(qpath, fields, wth) => {
1473 self.print_expr_struct(qpath, fields, wth);
1474 }
1475 hir::ExprKind::Tup(exprs) => {
1476 self.print_expr_tup(exprs);
1477 }
1478 hir::ExprKind::Call(func, args) => {
1479 self.print_expr_call(func, args);
1480 }
1481 hir::ExprKind::MethodCall(segment, receiver, args, _) => {
1482 self.print_expr_method_call(segment, receiver, args);
1483 }
1484 hir::ExprKind::Use(expr, _) => {
1485 self.print_expr(expr);
1486 self.word(".use");
1487 }
1488 hir::ExprKind::Binary(op, lhs, rhs) => {
1489 self.print_expr_binary(op.node, lhs, rhs);
1490 }
1491 hir::ExprKind::Unary(op, expr) => {
1492 self.print_expr_unary(op, expr);
1493 }
1494 hir::ExprKind::AddrOf(k, m, expr) => {
1495 self.print_expr_addr_of(k, m, expr);
1496 }
1497 hir::ExprKind::Lit(lit) => {
1498 self.print_literal(&lit);
1499 }
1500 hir::ExprKind::Cast(expr, ty) => {
1501 self.print_expr_cond_paren(expr, self.precedence(expr) < ExprPrecedence::Cast);
1502 self.space();
1503 self.word_space("as");
1504 self.print_type(ty);
1505 }
1506 hir::ExprKind::Type(expr, ty) => {
1507 self.word("type_ascribe!(");
1508 let ib = self.ibox(0);
1509 self.print_expr(expr);
1510
1511 self.word(",");
1512 self.space_if_not_bol();
1513 self.print_type(ty);
1514
1515 self.end(ib);
1516 self.word(")");
1517 }
1518 hir::ExprKind::DropTemps(init) => {
1519 let cb = self.cbox(0);
1521 let ib = self.ibox(0);
1522 self.bopen(ib);
1523
1524 let temp = Ident::with_dummy_span(sym::_t);
1526 self.print_local(false, Some(init), None, |this| this.print_ident(temp));
1527 self.word(";");
1528
1529 self.space_if_not_bol();
1531 self.print_ident(temp);
1532
1533 self.bclose_maybe_open(expr.span, Some(cb));
1535 }
1536 hir::ExprKind::Let(&hir::LetExpr { pat, ty, init, .. }) => {
1537 self.print_let(pat, ty, init);
1538 }
1539 hir::ExprKind::If(test, blk, elseopt) => {
1540 self.print_if(test, blk, elseopt);
1541 }
1542 hir::ExprKind::Loop(blk, opt_label, _, _) => {
1543 let cb = self.cbox(0);
1544 let ib = self.ibox(0);
1545 if let Some(label) = opt_label {
1546 self.print_ident(label.ident);
1547 self.word_space(":");
1548 }
1549 self.word_nbsp("loop");
1550 self.print_block(blk, cb, ib);
1551 }
1552 hir::ExprKind::Match(expr, arms, _) => {
1553 let cb = self.cbox(0);
1554 let ib = self.ibox(0);
1555 self.word_nbsp("match");
1556 self.print_expr_as_cond(expr);
1557 self.space();
1558 self.bopen(ib);
1559 for arm in arms {
1560 self.print_arm(arm);
1561 }
1562 self.bclose(expr.span, cb);
1563 }
1564 hir::ExprKind::Closure(&hir::Closure {
1565 binder,
1566 constness,
1567 capture_clause,
1568 bound_generic_params,
1569 fn_decl,
1570 body,
1571 fn_decl_span: _,
1572 fn_arg_span: _,
1573 kind: _,
1574 def_id: _,
1575 }) => {
1576 self.print_closure_binder(binder, bound_generic_params);
1577 self.print_constness(constness);
1578 self.print_capture_clause(capture_clause);
1579
1580 self.print_closure_params(fn_decl, body);
1581 self.space();
1582
1583 self.ann.nested(self, Nested::Body(body));
1585 }
1586 hir::ExprKind::Block(blk, opt_label) => {
1587 if let Some(label) = opt_label {
1588 self.print_ident(label.ident);
1589 self.word_space(":");
1590 }
1591 let cb = self.cbox(0);
1593 let ib = self.ibox(0);
1595 self.print_block(blk, cb, ib);
1596 }
1597 hir::ExprKind::Assign(lhs, rhs, _) => {
1598 self.print_expr_cond_paren(lhs, self.precedence(lhs) <= ExprPrecedence::Assign);
1599 self.space();
1600 self.word_space("=");
1601 self.print_expr_cond_paren(rhs, self.precedence(rhs) < ExprPrecedence::Assign);
1602 }
1603 hir::ExprKind::AssignOp(op, lhs, rhs) => {
1604 self.print_expr_cond_paren(lhs, self.precedence(lhs) <= ExprPrecedence::Assign);
1605 self.space();
1606 self.word_space(op.node.as_str());
1607 self.print_expr_cond_paren(rhs, self.precedence(rhs) < ExprPrecedence::Assign);
1608 }
1609 hir::ExprKind::Field(expr, ident) => {
1610 self.print_expr_cond_paren(
1611 expr,
1612 self.precedence(expr) < ExprPrecedence::Unambiguous,
1613 );
1614 self.word(".");
1615 self.print_ident(ident);
1616 }
1617 hir::ExprKind::Index(expr, index, _) => {
1618 self.print_expr_cond_paren(
1619 expr,
1620 self.precedence(expr) < ExprPrecedence::Unambiguous,
1621 );
1622 self.word("[");
1623 self.print_expr(index);
1624 self.word("]");
1625 }
1626 hir::ExprKind::Path(ref qpath) => self.print_qpath(qpath, true),
1627 hir::ExprKind::Break(destination, opt_expr) => {
1628 self.word("break");
1629 if let Some(label) = destination.label {
1630 self.space();
1631 self.print_ident(label.ident);
1632 }
1633 if let Some(expr) = opt_expr {
1634 self.space();
1635 self.print_expr_cond_paren(expr, self.precedence(expr) < ExprPrecedence::Jump);
1636 }
1637 }
1638 hir::ExprKind::Continue(destination) => {
1639 self.word("continue");
1640 if let Some(label) = destination.label {
1641 self.space();
1642 self.print_ident(label.ident);
1643 }
1644 }
1645 hir::ExprKind::Ret(result) => {
1646 self.word("return");
1647 if let Some(expr) = result {
1648 self.word(" ");
1649 self.print_expr_cond_paren(expr, self.precedence(expr) < ExprPrecedence::Jump);
1650 }
1651 }
1652 hir::ExprKind::Become(result) => {
1653 self.word("become");
1654 self.word(" ");
1655 self.print_expr_cond_paren(result, self.precedence(result) < ExprPrecedence::Jump);
1656 }
1657 hir::ExprKind::InlineAsm(asm) => {
1658 self.word("asm!");
1659 self.print_inline_asm(asm);
1660 }
1661 hir::ExprKind::OffsetOf(container, fields) => {
1662 self.word("offset_of!(");
1663 self.print_type(container);
1664 self.word(",");
1665 self.space();
1666
1667 if let Some((&first, rest)) = fields.split_first() {
1668 self.print_ident(first);
1669
1670 for &field in rest {
1671 self.word(".");
1672 self.print_ident(field);
1673 }
1674 }
1675
1676 self.word(")");
1677 }
1678 hir::ExprKind::UnsafeBinderCast(kind, expr, ty) => {
1679 match kind {
1680 ast::UnsafeBinderCastKind::Wrap => self.word("wrap_binder!("),
1681 ast::UnsafeBinderCastKind::Unwrap => self.word("unwrap_binder!("),
1682 }
1683 self.print_expr(expr);
1684 if let Some(ty) = ty {
1685 self.word(",");
1686 self.space();
1687 self.print_type(ty);
1688 }
1689 self.word(")");
1690 }
1691 hir::ExprKind::Yield(expr, _) => {
1692 self.word_space("yield");
1693 self.print_expr_cond_paren(expr, self.precedence(expr) < ExprPrecedence::Jump);
1694 }
1695 hir::ExprKind::Err(_) => {
1696 self.popen();
1697 self.word("/*ERROR*/");
1698 self.pclose();
1699 }
1700 }
1701 self.ann.post(self, AnnNode::Expr(expr));
1702 self.end(ib)
1703 }
1704
1705 fn print_local_decl(&mut self, loc: &hir::LetStmt<'_>) {
1706 self.print_pat(loc.pat);
1707 if let Some(ty) = loc.ty {
1708 self.word_space(":");
1709 self.print_type(ty);
1710 }
1711 }
1712
1713 fn print_name(&mut self, name: Symbol) {
1714 self.print_ident(Ident::with_dummy_span(name))
1715 }
1716
1717 fn print_path<R>(&mut self, path: &hir::Path<'_, R>, colons_before_params: bool) {
1718 self.maybe_print_comment(path.span.lo());
1719
1720 for (i, segment) in path.segments.iter().enumerate() {
1721 if i > 0 {
1722 self.word("::")
1723 }
1724 if segment.ident.name != kw::PathRoot {
1725 self.print_ident(segment.ident);
1726 self.print_generic_args(segment.args(), colons_before_params);
1727 }
1728 }
1729 }
1730
1731 fn print_path_segment(&mut self, segment: &hir::PathSegment<'_>) {
1732 if segment.ident.name != kw::PathRoot {
1733 self.print_ident(segment.ident);
1734 self.print_generic_args(segment.args(), false);
1735 }
1736 }
1737
1738 fn print_qpath(&mut self, qpath: &hir::QPath<'_>, colons_before_params: bool) {
1739 match *qpath {
1740 hir::QPath::Resolved(None, path) => self.print_path(path, colons_before_params),
1741 hir::QPath::Resolved(Some(qself), path) => {
1742 self.word("<");
1743 self.print_type(qself);
1744 self.space();
1745 self.word_space("as");
1746
1747 for (i, segment) in path.segments[..path.segments.len() - 1].iter().enumerate() {
1748 if i > 0 {
1749 self.word("::")
1750 }
1751 if segment.ident.name != kw::PathRoot {
1752 self.print_ident(segment.ident);
1753 self.print_generic_args(segment.args(), colons_before_params);
1754 }
1755 }
1756
1757 self.word(">");
1758 self.word("::");
1759 let item_segment = path.segments.last().unwrap();
1760 self.print_ident(item_segment.ident);
1761 self.print_generic_args(item_segment.args(), colons_before_params)
1762 }
1763 hir::QPath::TypeRelative(qself, item_segment) => {
1764 if let hir::TyKind::Path(hir::QPath::Resolved(None, _)) = qself.kind {
1768 self.print_type(qself);
1769 } else {
1770 self.word("<");
1771 self.print_type(qself);
1772 self.word(">");
1773 }
1774
1775 self.word("::");
1776 self.print_ident(item_segment.ident);
1777 self.print_generic_args(item_segment.args(), colons_before_params)
1778 }
1779 }
1780 }
1781
1782 fn print_generic_args(
1783 &mut self,
1784 generic_args: &hir::GenericArgs<'_>,
1785 colons_before_params: bool,
1786 ) {
1787 match generic_args.parenthesized {
1788 hir::GenericArgsParentheses::No => {
1789 let start = if colons_before_params { "::<" } else { "<" };
1790 let empty = Cell::new(true);
1791 let start_or_comma = |this: &mut Self| {
1792 if empty.get() {
1793 empty.set(false);
1794 this.word(start)
1795 } else {
1796 this.word_space(",")
1797 }
1798 };
1799
1800 let mut nonelided_generic_args: bool = false;
1801 let elide_lifetimes = generic_args.args.iter().all(|arg| match arg {
1802 GenericArg::Lifetime(lt) if lt.is_elided() => true,
1803 GenericArg::Lifetime(_) => {
1804 nonelided_generic_args = true;
1805 false
1806 }
1807 _ => {
1808 nonelided_generic_args = true;
1809 true
1810 }
1811 });
1812
1813 if nonelided_generic_args {
1814 start_or_comma(self);
1815 self.commasep(Inconsistent, generic_args.args, |s, generic_arg| {
1816 s.print_generic_arg(generic_arg, elide_lifetimes)
1817 });
1818 }
1819
1820 for constraint in generic_args.constraints {
1821 start_or_comma(self);
1822 self.print_assoc_item_constraint(constraint);
1823 }
1824
1825 if !empty.get() {
1826 self.word(">")
1827 }
1828 }
1829 hir::GenericArgsParentheses::ParenSugar => {
1830 let (inputs, output) = generic_args.paren_sugar_inputs_output().unwrap();
1831
1832 self.word("(");
1833 self.commasep(Inconsistent, inputs, |s, ty| s.print_type(ty));
1834 self.word(")");
1835
1836 self.space_if_not_bol();
1837 self.word_space("->");
1838 self.print_type(output);
1839 }
1840 hir::GenericArgsParentheses::ReturnTypeNotation => {
1841 self.word("(..)");
1842 }
1843 }
1844 }
1845
1846 fn print_assoc_item_constraint(&mut self, constraint: &hir::AssocItemConstraint<'_>) {
1847 self.print_ident(constraint.ident);
1848 self.print_generic_args(constraint.gen_args, false);
1849 self.space();
1850 match constraint.kind {
1851 hir::AssocItemConstraintKind::Equality { ref term } => {
1852 self.word_space("=");
1853 match term {
1854 Term::Ty(ty) => self.print_type(ty),
1855 Term::Const(c) => self.print_const_arg(c),
1856 }
1857 }
1858 hir::AssocItemConstraintKind::Bound { bounds } => {
1859 self.print_bounds(":", bounds);
1860 }
1861 }
1862 }
1863
1864 fn print_pat_expr(&mut self, expr: &hir::PatExpr<'_>) {
1865 match &expr.kind {
1866 hir::PatExprKind::Lit { lit, negated } => {
1867 if *negated {
1868 self.word("-");
1869 }
1870 self.print_literal(lit);
1871 }
1872 hir::PatExprKind::ConstBlock(c) => self.print_inline_const(c),
1873 hir::PatExprKind::Path(qpath) => self.print_qpath(qpath, true),
1874 }
1875 }
1876
1877 fn print_ty_pat(&mut self, pat: &hir::TyPat<'_>) {
1878 self.maybe_print_comment(pat.span.lo());
1879 self.ann.pre(self, AnnNode::TyPat(pat));
1880 match pat.kind {
1883 TyPatKind::Range(begin, end) => {
1884 self.print_const_arg(begin);
1885 self.word("..=");
1886 self.print_const_arg(end);
1887 }
1888 TyPatKind::NotNull => {
1889 self.word_space("not");
1890 self.word("null");
1891 }
1892 TyPatKind::Or(patterns) => {
1893 self.popen();
1894 let mut first = true;
1895 for pat in patterns {
1896 if first {
1897 first = false;
1898 } else {
1899 self.word(" | ");
1900 }
1901 self.print_ty_pat(pat);
1902 }
1903 self.pclose();
1904 }
1905 TyPatKind::Err(_) => {
1906 self.popen();
1907 self.word("/*ERROR*/");
1908 self.pclose();
1909 }
1910 }
1911 self.ann.post(self, AnnNode::TyPat(pat))
1912 }
1913
1914 fn print_pat(&mut self, pat: &hir::Pat<'_>) {
1915 self.maybe_print_comment(pat.span.lo());
1916 self.ann.pre(self, AnnNode::Pat(pat));
1917 match pat.kind {
1919 PatKind::Missing => self.word("_"),
1922 PatKind::Wild => self.word("_"),
1923 PatKind::Never => self.word("!"),
1924 PatKind::Binding(BindingMode(by_ref, mutbl), _, ident, sub) => {
1925 if mutbl.is_mut() {
1926 self.word_nbsp("mut");
1927 }
1928 if let ByRef::Yes(pinnedness, rmutbl) = by_ref {
1929 self.word_nbsp("ref");
1930 if pinnedness.is_pinned() {
1931 self.word_nbsp("pin");
1932 }
1933 if rmutbl.is_mut() {
1934 self.word_nbsp("mut");
1935 } else if pinnedness.is_pinned() {
1936 self.word_nbsp("const");
1937 }
1938 }
1939 self.print_ident(ident);
1940 if let Some(p) = sub {
1941 self.word("@");
1942 self.print_pat(p);
1943 }
1944 }
1945 PatKind::TupleStruct(ref qpath, elts, ddpos) => {
1946 self.print_qpath(qpath, true);
1947 self.popen();
1948 if let Some(ddpos) = ddpos.as_opt_usize() {
1949 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(p));
1950 if ddpos != 0 {
1951 self.word_space(",");
1952 }
1953 self.word("..");
1954 if ddpos != elts.len() {
1955 self.word(",");
1956 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(p));
1957 }
1958 } else {
1959 self.commasep(Inconsistent, elts, |s, p| s.print_pat(p));
1960 }
1961 self.pclose();
1962 }
1963 PatKind::Struct(ref qpath, fields, etc) => {
1964 self.print_qpath(qpath, true);
1965 self.nbsp();
1966 self.word("{");
1967 let empty = fields.is_empty() && etc.is_none();
1968 if !empty {
1969 self.space();
1970 }
1971 self.commasep_cmnt(Consistent, fields, |s, f| s.print_patfield(f), |f| f.pat.span);
1972 if etc.is_some() {
1973 if !fields.is_empty() {
1974 self.word_space(",");
1975 }
1976 self.word("..");
1977 }
1978 if !empty {
1979 self.space();
1980 }
1981 self.word("}");
1982 }
1983 PatKind::Or(pats) => {
1984 self.strsep("|", true, Inconsistent, pats, |s, p| s.print_pat(p));
1985 }
1986 PatKind::Tuple(elts, ddpos) => {
1987 self.popen();
1988 if let Some(ddpos) = ddpos.as_opt_usize() {
1989 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(p));
1990 if ddpos != 0 {
1991 self.word_space(",");
1992 }
1993 self.word("..");
1994 if ddpos != elts.len() {
1995 self.word(",");
1996 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(p));
1997 }
1998 } else {
1999 self.commasep(Inconsistent, elts, |s, p| s.print_pat(p));
2000 if elts.len() == 1 {
2001 self.word(",");
2002 }
2003 }
2004 self.pclose();
2005 }
2006 PatKind::Box(inner) => {
2007 let is_range_inner = matches!(inner.kind, PatKind::Range(..));
2008 self.word("box ");
2009 if is_range_inner {
2010 self.popen();
2011 }
2012 self.print_pat(inner);
2013 if is_range_inner {
2014 self.pclose();
2015 }
2016 }
2017 PatKind::Deref(inner) => {
2018 self.word("deref!");
2019 self.popen();
2020 self.print_pat(inner);
2021 self.pclose();
2022 }
2023 PatKind::Ref(inner, mutbl) => {
2024 let is_range_inner = matches!(inner.kind, PatKind::Range(..));
2025 self.word("&");
2026 self.word(mutbl.prefix_str());
2027 if is_range_inner {
2028 self.popen();
2029 }
2030 self.print_pat(inner);
2031 if is_range_inner {
2032 self.pclose();
2033 }
2034 }
2035 PatKind::Expr(e) => self.print_pat_expr(e),
2036 PatKind::Range(begin, end, end_kind) => {
2037 if let Some(expr) = begin {
2038 self.print_pat_expr(expr);
2039 }
2040 match end_kind {
2041 RangeEnd::Included => self.word("..."),
2042 RangeEnd::Excluded => self.word(".."),
2043 }
2044 if let Some(expr) = end {
2045 self.print_pat_expr(expr);
2046 }
2047 }
2048 PatKind::Slice(before, slice, after) => {
2049 self.word("[");
2050 self.commasep(Inconsistent, before, |s, p| s.print_pat(p));
2051 if let Some(p) = slice {
2052 if !before.is_empty() {
2053 self.word_space(",");
2054 }
2055 if let PatKind::Wild = p.kind {
2056 } else {
2058 self.print_pat(p);
2059 }
2060 self.word("..");
2061 if !after.is_empty() {
2062 self.word_space(",");
2063 }
2064 }
2065 self.commasep(Inconsistent, after, |s, p| s.print_pat(p));
2066 self.word("]");
2067 }
2068 PatKind::Guard(inner, cond) => {
2069 self.print_pat(inner);
2070 self.space();
2071 self.word_space("if");
2072 self.print_expr(cond);
2073 }
2074 PatKind::Err(_) => {
2075 self.popen();
2076 self.word("/*ERROR*/");
2077 self.pclose();
2078 }
2079 }
2080 self.ann.post(self, AnnNode::Pat(pat))
2081 }
2082
2083 fn print_patfield(&mut self, field: &hir::PatField<'_>) {
2084 if self.attrs(field.hir_id).is_empty() {
2085 self.space();
2086 }
2087 let cb = self.cbox(INDENT_UNIT);
2088 self.print_attrs(self.attrs(field.hir_id));
2089 if !field.is_shorthand {
2090 self.print_ident(field.ident);
2091 self.word_nbsp(":");
2092 }
2093 self.print_pat(field.pat);
2094 self.end(cb);
2095 }
2096
2097 fn print_param(&mut self, arg: &hir::Param<'_>) {
2098 self.print_attrs(self.attrs(arg.hir_id));
2099 self.print_pat(arg.pat);
2100 }
2101
2102 fn print_implicit_self(&mut self, implicit_self_kind: &hir::ImplicitSelfKind) {
2103 match implicit_self_kind {
2104 ImplicitSelfKind::Imm => {
2105 self.word("self");
2106 }
2107 ImplicitSelfKind::Mut => {
2108 self.print_mutability(hir::Mutability::Mut, false);
2109 self.word("self");
2110 }
2111 ImplicitSelfKind::RefImm => {
2112 self.word("&");
2113 self.word("self");
2114 }
2115 ImplicitSelfKind::RefMut => {
2116 self.word("&");
2117 self.print_mutability(hir::Mutability::Mut, false);
2118 self.word("self");
2119 }
2120 ImplicitSelfKind::None => unreachable!(),
2121 }
2122 }
2123
2124 fn print_arm(&mut self, arm: &hir::Arm<'_>) {
2125 if self.attrs(arm.hir_id).is_empty() {
2128 self.space();
2129 }
2130 let cb = self.cbox(INDENT_UNIT);
2131 self.ann.pre(self, AnnNode::Arm(arm));
2132 let ib = self.ibox(0);
2133 self.print_attrs(self.attrs(arm.hir_id));
2134 self.print_pat(arm.pat);
2135 self.space();
2136 if let Some(ref g) = arm.guard {
2137 self.word_space("if");
2138 self.print_expr(g);
2139 self.space();
2140 }
2141 self.word_space("=>");
2142
2143 match arm.body.kind {
2144 hir::ExprKind::Block(blk, opt_label) => {
2145 if let Some(label) = opt_label {
2146 self.print_ident(label.ident);
2147 self.word_space(":");
2148 }
2149 self.print_block_unclosed(blk, ib);
2150
2151 if let hir::BlockCheckMode::UnsafeBlock(hir::UnsafeSource::UserProvided) = blk.rules
2153 {
2154 self.word(",");
2155 }
2156 }
2157 _ => {
2158 self.end(ib);
2159 self.print_expr(arm.body);
2160 self.word(",");
2161 }
2162 }
2163 self.ann.post(self, AnnNode::Arm(arm));
2164 self.end(cb)
2165 }
2166
2167 fn print_fn(
2168 &mut self,
2169 header: hir::FnHeader,
2170 name: Option<Symbol>,
2171 generics: &hir::Generics<'_>,
2172 decl: &hir::FnDecl<'_>,
2173 arg_idents: &[Option<Ident>],
2174 body_id: Option<hir::BodyId>,
2175 ) {
2176 self.print_fn_header_info(header);
2177
2178 if let Some(name) = name {
2179 self.nbsp();
2180 self.print_name(name);
2181 }
2182 self.print_generic_params(generics.params);
2183
2184 self.popen();
2185 assert!(arg_idents.is_empty() || body_id.is_none());
2187 let mut i = 0;
2188 let mut print_arg = |s: &mut Self, ty: Option<&hir::Ty<'_>>| {
2189 if i == 0 && decl.implicit_self.has_implicit_self() {
2190 s.print_implicit_self(&decl.implicit_self);
2191 } else {
2192 if let Some(arg_ident) = arg_idents.get(i) {
2193 if let Some(arg_ident) = arg_ident {
2194 s.word(arg_ident.to_string());
2195 s.word(":");
2196 s.space();
2197 }
2198 } else if let Some(body_id) = body_id {
2199 s.ann.nested(s, Nested::BodyParamPat(body_id, i));
2200 s.word(":");
2201 s.space();
2202 }
2203 if let Some(ty) = ty {
2204 s.print_type(ty);
2205 }
2206 }
2207 i += 1;
2208 };
2209 self.commasep(Inconsistent, decl.inputs, |s, ty| {
2210 let ib = s.ibox(INDENT_UNIT);
2211 print_arg(s, Some(ty));
2212 s.end(ib);
2213 });
2214 if decl.c_variadic {
2215 if !decl.inputs.is_empty() {
2216 self.word(", ");
2217 }
2218 print_arg(self, None);
2219 self.word("...");
2220 }
2221 self.pclose();
2222
2223 self.print_fn_output(decl);
2224 self.print_where_clause(generics)
2225 }
2226
2227 fn print_closure_params(&mut self, decl: &hir::FnDecl<'_>, body_id: hir::BodyId) {
2228 self.word("|");
2229 let mut i = 0;
2230 self.commasep(Inconsistent, decl.inputs, |s, ty| {
2231 let ib = s.ibox(INDENT_UNIT);
2232
2233 s.ann.nested(s, Nested::BodyParamPat(body_id, i));
2234 i += 1;
2235
2236 if let hir::TyKind::Infer(()) = ty.kind {
2237 } else {
2239 s.word(":");
2240 s.space();
2241 s.print_type(ty);
2242 }
2243 s.end(ib);
2244 });
2245 self.word("|");
2246
2247 match decl.output {
2248 hir::FnRetTy::Return(ty) => {
2249 self.space_if_not_bol();
2250 self.word_space("->");
2251 self.print_type(ty);
2252 self.maybe_print_comment(ty.span.lo());
2253 }
2254 hir::FnRetTy::DefaultReturn(..) => {}
2255 }
2256 }
2257
2258 fn print_capture_clause(&mut self, capture_clause: hir::CaptureBy) {
2259 match capture_clause {
2260 hir::CaptureBy::Value { .. } => self.word_space("move"),
2261 hir::CaptureBy::Use { .. } => self.word_space("use"),
2262 hir::CaptureBy::Ref => {}
2263 }
2264 }
2265
2266 fn print_closure_binder(
2267 &mut self,
2268 binder: hir::ClosureBinder,
2269 generic_params: &[GenericParam<'_>],
2270 ) {
2271 let generic_params = generic_params
2272 .iter()
2273 .filter(|p| {
2274 matches!(
2275 p,
2276 GenericParam {
2277 kind: GenericParamKind::Lifetime { kind: LifetimeParamKind::Explicit },
2278 ..
2279 }
2280 )
2281 })
2282 .collect::<Vec<_>>();
2283
2284 match binder {
2285 hir::ClosureBinder::Default => {}
2286 hir::ClosureBinder::For { .. } if generic_params.is_empty() => self.word("for<>"),
2289 hir::ClosureBinder::For { .. } => {
2290 self.word("for");
2291 self.word("<");
2292
2293 self.commasep(Inconsistent, &generic_params, |s, param| {
2294 s.print_generic_param(param)
2295 });
2296
2297 self.word(">");
2298 self.nbsp();
2299 }
2300 }
2301 }
2302
2303 fn print_bounds<'b>(
2304 &mut self,
2305 prefix: &'static str,
2306 bounds: impl IntoIterator<Item = &'b hir::GenericBound<'b>>,
2307 ) {
2308 let mut first = true;
2309 for bound in bounds {
2310 if first {
2311 self.word(prefix);
2312 }
2313 if !(first && prefix.is_empty()) {
2314 self.nbsp();
2315 }
2316 if first {
2317 first = false;
2318 } else {
2319 self.word_space("+");
2320 }
2321
2322 match bound {
2323 GenericBound::Trait(tref) => {
2324 self.print_poly_trait_ref(tref);
2325 }
2326 GenericBound::Outlives(lt) => {
2327 self.print_lifetime(lt);
2328 }
2329 GenericBound::Use(args, _) => {
2330 self.word("use <");
2331
2332 self.commasep(Inconsistent, *args, |s, arg| {
2333 s.print_precise_capturing_arg(*arg)
2334 });
2335
2336 self.word(">");
2337 }
2338 }
2339 }
2340 }
2341
2342 fn print_precise_capturing_arg(&mut self, arg: PreciseCapturingArg<'_>) {
2343 match arg {
2344 PreciseCapturingArg::Lifetime(lt) => self.print_lifetime(lt),
2345 PreciseCapturingArg::Param(arg) => self.print_ident(arg.ident),
2346 }
2347 }
2348
2349 fn print_generic_params(&mut self, generic_params: &[GenericParam<'_>]) {
2350 let is_lifetime_elided = |generic_param: &GenericParam<'_>| {
2351 matches!(
2352 generic_param.kind,
2353 GenericParamKind::Lifetime { kind: LifetimeParamKind::Elided(_) }
2354 )
2355 };
2356
2357 if !generic_params.is_empty() && !generic_params.iter().all(is_lifetime_elided) {
2360 self.word("<");
2361
2362 self.commasep(
2363 Inconsistent,
2364 generic_params.iter().filter(|gp| !is_lifetime_elided(gp)),
2365 |s, param| s.print_generic_param(param),
2366 );
2367
2368 self.word(">");
2369 }
2370 }
2371
2372 fn print_generic_param(&mut self, param: &GenericParam<'_>) {
2373 if let GenericParamKind::Const { .. } = param.kind {
2374 self.word_space("const");
2375 }
2376
2377 self.print_ident(param.name.ident());
2378
2379 match param.kind {
2380 GenericParamKind::Lifetime { .. } => {}
2381 GenericParamKind::Type { default, .. } => {
2382 if let Some(default) = default {
2383 self.space();
2384 self.word_space("=");
2385 self.print_type(default);
2386 }
2387 }
2388 GenericParamKind::Const { ty, ref default } => {
2389 self.word_space(":");
2390 self.print_type(ty);
2391 if let Some(default) = default {
2392 self.space();
2393 self.word_space("=");
2394 self.print_const_arg(default);
2395 }
2396 }
2397 }
2398 }
2399
2400 fn print_lifetime(&mut self, lifetime: &hir::Lifetime) {
2401 self.print_ident(lifetime.ident)
2402 }
2403
2404 fn print_where_clause(&mut self, generics: &hir::Generics<'_>) {
2405 if generics.predicates.is_empty() {
2406 return;
2407 }
2408
2409 self.space();
2410 self.word_space("where");
2411
2412 for (i, predicate) in generics.predicates.iter().enumerate() {
2413 if i != 0 {
2414 self.word_space(",");
2415 }
2416 self.print_where_predicate(predicate);
2417 }
2418 }
2419
2420 fn print_where_predicate(&mut self, predicate: &hir::WherePredicate<'_>) {
2421 self.print_attrs(self.attrs(predicate.hir_id));
2422 match *predicate.kind {
2423 hir::WherePredicateKind::BoundPredicate(hir::WhereBoundPredicate {
2424 bound_generic_params,
2425 bounded_ty,
2426 bounds,
2427 ..
2428 }) => {
2429 self.print_formal_generic_params(bound_generic_params);
2430 self.print_type(bounded_ty);
2431 self.print_bounds(":", bounds);
2432 }
2433 hir::WherePredicateKind::RegionPredicate(hir::WhereRegionPredicate {
2434 lifetime,
2435 bounds,
2436 ..
2437 }) => {
2438 self.print_lifetime(lifetime);
2439 self.word(":");
2440
2441 for (i, bound) in bounds.iter().enumerate() {
2442 match bound {
2443 GenericBound::Outlives(lt) => {
2444 self.print_lifetime(lt);
2445 }
2446 _ => panic!("unexpected bound on lifetime param: {bound:?}"),
2447 }
2448
2449 if i != 0 {
2450 self.word(":");
2451 }
2452 }
2453 }
2454 hir::WherePredicateKind::EqPredicate(hir::WhereEqPredicate {
2455 lhs_ty, rhs_ty, ..
2456 }) => {
2457 self.print_type(lhs_ty);
2458 self.space();
2459 self.word_space("=");
2460 self.print_type(rhs_ty);
2461 }
2462 }
2463 }
2464
2465 fn print_mutability(&mut self, mutbl: hir::Mutability, print_const: bool) {
2466 match mutbl {
2467 hir::Mutability::Mut => self.word_nbsp("mut"),
2468 hir::Mutability::Not => {
2469 if print_const {
2470 self.word_nbsp("const")
2471 }
2472 }
2473 }
2474 }
2475
2476 fn print_mt(&mut self, mt: &hir::MutTy<'_>, print_const: bool) {
2477 self.print_mutability(mt.mutbl, print_const);
2478 self.print_type(mt.ty);
2479 }
2480
2481 fn print_fn_output(&mut self, decl: &hir::FnDecl<'_>) {
2482 match decl.output {
2483 hir::FnRetTy::Return(ty) => {
2484 self.space_if_not_bol();
2485 let ib = self.ibox(INDENT_UNIT);
2486 self.word_space("->");
2487 self.print_type(ty);
2488 self.end(ib);
2489
2490 if let hir::FnRetTy::Return(output) = decl.output {
2491 self.maybe_print_comment(output.span.lo());
2492 }
2493 }
2494 hir::FnRetTy::DefaultReturn(..) => {}
2495 }
2496 }
2497
2498 fn print_ty_fn(
2499 &mut self,
2500 abi: ExternAbi,
2501 safety: hir::Safety,
2502 decl: &hir::FnDecl<'_>,
2503 name: Option<Symbol>,
2504 generic_params: &[hir::GenericParam<'_>],
2505 arg_idents: &[Option<Ident>],
2506 ) {
2507 let ib = self.ibox(INDENT_UNIT);
2508 self.print_formal_generic_params(generic_params);
2509 let generics = hir::Generics::empty();
2510 self.print_fn(
2511 hir::FnHeader {
2512 safety: safety.into(),
2513 abi,
2514 constness: hir::Constness::NotConst,
2515 asyncness: hir::IsAsync::NotAsync,
2516 },
2517 name,
2518 generics,
2519 decl,
2520 arg_idents,
2521 None,
2522 );
2523 self.end(ib);
2524 }
2525
2526 fn print_fn_header_info(&mut self, header: hir::FnHeader) {
2527 self.print_constness(header.constness);
2528
2529 let safety = match header.safety {
2530 hir::HeaderSafety::SafeTargetFeatures => {
2531 self.word_nbsp("#[target_feature]");
2532 hir::Safety::Safe
2533 }
2534 hir::HeaderSafety::Normal(safety) => safety,
2535 };
2536
2537 match header.asyncness {
2538 hir::IsAsync::NotAsync => {}
2539 hir::IsAsync::Async(_) => self.word_nbsp("async"),
2540 }
2541
2542 self.print_safety(safety);
2543
2544 if header.abi != ExternAbi::Rust {
2545 self.word_nbsp("extern");
2546 self.word_nbsp(header.abi.to_string());
2547 }
2548
2549 self.word("fn")
2550 }
2551
2552 fn print_constness(&mut self, s: hir::Constness) {
2553 match s {
2554 hir::Constness::NotConst => {}
2555 hir::Constness::Const => self.word_nbsp("const"),
2556 }
2557 }
2558
2559 fn print_safety(&mut self, s: hir::Safety) {
2560 match s {
2561 hir::Safety::Safe => {}
2562 hir::Safety::Unsafe => self.word_nbsp("unsafe"),
2563 }
2564 }
2565
2566 fn print_is_auto(&mut self, s: hir::IsAuto) {
2567 match s {
2568 hir::IsAuto::Yes => self.word_nbsp("auto"),
2569 hir::IsAuto::No => {}
2570 }
2571 }
2572}
2573
2574fn expr_requires_semi_to_be_stmt(e: &hir::Expr<'_>) -> bool {
2584 !matches!(
2585 e.kind,
2586 hir::ExprKind::If(..)
2587 | hir::ExprKind::Match(..)
2588 | hir::ExprKind::Block(..)
2589 | hir::ExprKind::Loop(..)
2590 )
2591}
2592
2593fn stmt_ends_with_semi(stmt: &hir::StmtKind<'_>) -> bool {
2597 match *stmt {
2598 hir::StmtKind::Let(_) => true,
2599 hir::StmtKind::Item(_) => false,
2600 hir::StmtKind::Expr(e) => expr_requires_semi_to_be_stmt(e),
2601 hir::StmtKind::Semi(..) => false,
2602 }
2603}
2604
2605fn contains_exterior_struct_lit(value: &hir::Expr<'_>) -> bool {
2609 match value.kind {
2610 hir::ExprKind::Struct(..) => true,
2611
2612 hir::ExprKind::Assign(lhs, rhs, _)
2613 | hir::ExprKind::AssignOp(_, lhs, rhs)
2614 | hir::ExprKind::Binary(_, lhs, rhs) => {
2615 contains_exterior_struct_lit(lhs) || contains_exterior_struct_lit(rhs)
2617 }
2618 hir::ExprKind::Unary(_, x)
2619 | hir::ExprKind::Cast(x, _)
2620 | hir::ExprKind::Type(x, _)
2621 | hir::ExprKind::Field(x, _)
2622 | hir::ExprKind::Index(x, _, _) => {
2623 contains_exterior_struct_lit(x)
2625 }
2626
2627 hir::ExprKind::MethodCall(_, receiver, ..) => {
2628 contains_exterior_struct_lit(receiver)
2630 }
2631
2632 _ => false,
2633 }
2634}