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