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