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