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