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