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