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