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