1 #![recursion_limit = "256"]
4 use rustc_ast::util::parser::{self, AssocOp, Fixity};
5 use rustc_ast_pretty::pp::Breaks::{Consistent, Inconsistent};
6 use rustc_ast_pretty::pp::{self, Breaks};
7 use rustc_ast_pretty::pprust::{Comments, PrintState};
9 use rustc_hir::LifetimeParamKind;
10 use rustc_hir::{GenericArg, GenericParam, GenericParamKind, Node, Term};
11 use rustc_hir::{GenericBound, PatKind, RangeEnd, TraitBoundModifier};
12 use rustc_span::source_map::SourceMap;
13 use rustc_span::symbol::{kw, Ident, IdentPrinter, Symbol};
14 use rustc_span::{self, FileName};
15 use rustc_target::spec::abi::Abi;
20 pub fn id_to_string(map: &dyn rustc_hir::intravisit::Map<'_>, hir_id: hir::HirId) -> String {
21 to_string(&map, |s| s.print_node(map.find(hir_id).unwrap()))
24 pub enum AnnNode<'a> {
26 Block(&'a hir::Block<'a>),
27 Item(&'a hir::Item<'a>),
29 Expr(&'a hir::Expr<'a>),
30 Pat(&'a hir::Pat<'a>),
31 Arm(&'a hir::Arm<'a>),
36 TraitItem(hir::TraitItemId),
37 ImplItem(hir::ImplItemId),
38 ForeignItem(hir::ForeignItemId),
40 BodyParamPat(hir::BodyId, usize),
44 fn nested(&self, _state: &mut State<'_>, _nested: Nested) {}
45 fn pre(&self, _state: &mut State<'_>, _node: AnnNode<'_>) {}
46 fn post(&self, _state: &mut State<'_>, _node: AnnNode<'_>) {}
50 impl PpAnn for NoAnn {}
51 pub const NO_ANN: &dyn PpAnn = &NoAnn;
53 /// Identical to the `PpAnn` implementation for `hir::Crate`,
54 /// except it avoids creating a dependency on the whole crate.
55 impl PpAnn for &dyn rustc_hir::intravisit::Map<'_> {
56 fn nested(&self, state: &mut State<'_>, nested: Nested) {
58 Nested::Item(id) => state.print_item(self.item(id)),
59 Nested::TraitItem(id) => state.print_trait_item(self.trait_item(id)),
60 Nested::ImplItem(id) => state.print_impl_item(self.impl_item(id)),
61 Nested::ForeignItem(id) => state.print_foreign_item(self.foreign_item(id)),
62 Nested::Body(id) => state.print_expr(&self.body(id).value),
63 Nested::BodyParamPat(id, i) => state.print_pat(self.body(id).params[i].pat),
68 pub struct State<'a> {
70 comments: Option<Comments<'a>>,
71 attrs: &'a dyn Fn(hir::HirId) -> &'a [ast::Attribute],
72 ann: &'a (dyn PpAnn + 'a),
76 pub fn print_node(&mut self, node: Node<'_>) {
78 Node::Param(a) => self.print_param(a),
79 Node::Item(a) => self.print_item(a),
80 Node::ForeignItem(a) => self.print_foreign_item(a),
81 Node::TraitItem(a) => self.print_trait_item(a),
82 Node::ImplItem(a) => self.print_impl_item(a),
83 Node::Variant(a) => self.print_variant(a),
84 Node::AnonConst(a) => self.print_anon_const(a),
85 Node::Expr(a) => self.print_expr(a),
86 Node::ExprField(a) => self.print_expr_field(&a),
87 Node::Stmt(a) => self.print_stmt(a),
88 Node::PathSegment(a) => self.print_path_segment(a),
89 Node::Ty(a) => self.print_type(a),
90 Node::TypeBinding(a) => self.print_type_binding(a),
91 Node::TraitRef(a) => self.print_trait_ref(a),
92 Node::Pat(a) => self.print_pat(a),
93 Node::PatField(a) => self.print_patfield(&a),
94 Node::Arm(a) => self.print_arm(a),
95 Node::Infer(_) => self.word("_"),
97 // Containing cbox, will be closed by print-block at `}`.
98 self.cbox(INDENT_UNIT);
99 // Head-ibox, will be closed by print-block after `{`.
103 Node::Lifetime(a) => self.print_lifetime(a),
104 Node::GenericParam(_) => panic!("cannot print Node::GenericParam"),
105 Node::Field(_) => panic!("cannot print Node::Field"),
106 // These cases do not carry enough information in the
107 // `hir_map` to reconstruct their full structure for pretty
109 Node::Ctor(..) => panic!("cannot print isolated Ctor"),
110 Node::Local(a) => self.print_local_decl(a),
111 Node::Crate(..) => panic!("cannot print Crate"),
116 impl std::ops::Deref for State<'_> {
117 type Target = pp::Printer;
118 fn deref(&self) -> &Self::Target {
123 impl std::ops::DerefMut for State<'_> {
124 fn deref_mut(&mut self) -> &mut Self::Target {
129 impl<'a> PrintState<'a> for State<'a> {
130 fn comments(&mut self) -> &mut Option<Comments<'a>> {
134 fn print_ident(&mut self, ident: Ident) {
135 self.word(IdentPrinter::for_ast_ident(ident, ident.is_raw_guess()).to_string());
136 self.ann.post(self, AnnNode::Name(&ident.name))
139 fn print_generic_args(&mut self, _: &ast::GenericArgs, _colons_before_params: bool) {
140 panic!("AST generic args printed by HIR pretty-printer");
144 pub const INDENT_UNIT: isize = 4;
146 /// Requires you to pass an input filename and reader so that
147 /// it can scan the input text for comments to copy forward.
148 pub fn print_crate<'a>(
150 krate: &hir::Mod<'_>,
153 attrs: &'a dyn Fn(hir::HirId) -> &'a [ast::Attribute],
156 let mut s = State::new_from_input(sm, filename, input, attrs, ann);
158 // When printing the AST, we sometimes need to inject `#[no_std]` here.
159 // Since you can't compile the HIR, it's not necessary.
161 s.print_mod(krate, (*attrs)(hir::CRATE_HIR_ID));
162 s.print_remaining_comments();
167 pub fn new_from_input(
171 attrs: &'a dyn Fn(hir::HirId) -> &'a [ast::Attribute],
175 s: pp::Printer::new(),
176 comments: Some(Comments::new(sm, filename, input)),
182 fn attrs(&self, id: hir::HirId) -> &'a [ast::Attribute] {
187 pub fn to_string<F>(ann: &dyn PpAnn, f: F) -> String
189 F: FnOnce(&mut State<'_>),
191 let mut printer = State { s: pp::Printer::new(), comments: None, attrs: &|_| &[], ann };
196 pub fn generic_params_to_string(generic_params: &[GenericParam<'_>]) -> String {
197 to_string(NO_ANN, |s| s.print_generic_params(generic_params))
200 pub fn bounds_to_string<'b>(bounds: impl IntoIterator<Item = &'b hir::GenericBound<'b>>) -> String {
201 to_string(NO_ANN, |s| s.print_bounds("", bounds))
204 pub fn ty_to_string(ty: &hir::Ty<'_>) -> String {
205 to_string(NO_ANN, |s| s.print_type(ty))
208 pub fn path_segment_to_string(segment: &hir::PathSegment<'_>) -> String {
209 to_string(NO_ANN, |s| s.print_path_segment(segment))
212 pub fn path_to_string(segment: &hir::Path<'_>) -> String {
213 to_string(NO_ANN, |s| s.print_path(segment, false))
216 pub fn qpath_to_string(segment: &hir::QPath<'_>) -> String {
217 to_string(NO_ANN, |s| s.print_qpath(segment, false))
221 decl: &hir::FnDecl<'_>,
222 header: hir::FnHeader,
223 name: Option<Symbol>,
224 generics: &hir::Generics<'_>,
226 body_id: Option<hir::BodyId>,
228 to_string(NO_ANN, |s| s.print_fn(decl, header, name, generics, arg_names, body_id))
231 pub fn enum_def_to_string(
232 enum_definition: &hir::EnumDef<'_>,
233 generics: &hir::Generics<'_>,
235 span: rustc_span::Span,
237 to_string(NO_ANN, |s| s.print_enum_def(enum_definition, generics, name, span))
241 pub fn bclose_maybe_open(&mut self, span: rustc_span::Span, close_box: bool) {
242 self.maybe_print_comment(span.hi());
243 self.break_offset_if_not_bol(1, -(INDENT_UNIT as isize));
246 self.end(); // close the outer-box
250 pub fn bclose(&mut self, span: rustc_span::Span) {
251 self.bclose_maybe_open(span, true)
254 pub fn commasep_cmnt<T, F, G>(&mut self, b: Breaks, elts: &[T], mut op: F, mut get_span: G)
256 F: FnMut(&mut State<'_>, &T),
257 G: FnMut(&T) -> rustc_span::Span,
260 let len = elts.len();
263 self.maybe_print_comment(get_span(elt).hi());
268 self.maybe_print_trailing_comment(get_span(elt), Some(get_span(&elts[i]).hi()));
269 self.space_if_not_bol();
275 pub fn commasep_exprs(&mut self, b: Breaks, exprs: &[hir::Expr<'_>]) {
276 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(e), |e| e.span);
279 pub fn print_mod(&mut self, _mod: &hir::Mod<'_>, attrs: &[ast::Attribute]) {
280 self.print_inner_attributes(attrs);
281 for &item_id in _mod.item_ids {
282 self.ann.nested(self, Nested::Item(item_id));
286 pub fn print_opt_lifetime(&mut self, lifetime: &hir::Lifetime) {
287 if !lifetime.is_elided() {
288 self.print_lifetime(lifetime);
293 pub fn print_type(&mut self, ty: &hir::Ty<'_>) {
294 self.maybe_print_comment(ty.span.lo());
297 hir::TyKind::Slice(ty) => {
302 hir::TyKind::Ptr(ref mt) => {
304 self.print_mt(mt, true);
306 hir::TyKind::Rptr(ref lifetime, ref mt) => {
308 self.print_opt_lifetime(lifetime);
309 self.print_mt(mt, false);
311 hir::TyKind::Never => {
314 hir::TyKind::Tup(elts) => {
316 self.commasep(Inconsistent, elts, |s, ty| s.print_type(ty));
322 hir::TyKind::BareFn(f) => {
323 self.print_ty_fn(f.abi, f.unsafety, f.decl, None, f.generic_params, f.param_names);
325 hir::TyKind::OpaqueDef(..) => self.word("/*impl Trait*/"),
326 hir::TyKind::Path(ref qpath) => self.print_qpath(qpath, false),
327 hir::TyKind::TraitObject(bounds, ref lifetime, syntax) => {
328 if syntax == ast::TraitObjectSyntax::Dyn {
329 self.word_space("dyn");
331 let mut first = true;
332 for bound in bounds {
337 self.word_space("+");
339 self.print_poly_trait_ref(bound);
341 if !lifetime.is_elided() {
343 self.word_space("+");
344 self.print_lifetime(lifetime);
347 hir::TyKind::Array(ty, ref length) => {
351 self.print_array_length(length);
354 hir::TyKind::Typeof(ref e) => {
355 self.word("typeof(");
356 self.print_anon_const(e);
359 hir::TyKind::Err => {
361 self.word("/*ERROR*/");
364 hir::TyKind::Infer => {
371 pub fn print_foreign_item(&mut self, item: &hir::ForeignItem<'_>) {
372 self.hardbreak_if_not_bol();
373 self.maybe_print_comment(item.span.lo());
374 self.print_outer_attributes(self.attrs(item.hir_id()));
376 hir::ForeignItemKind::Fn(decl, arg_names, generics) => {
381 unsafety: hir::Unsafety::Normal,
382 constness: hir::Constness::NotConst,
384 asyncness: hir::IsAsync::NotAsync,
386 Some(item.ident.name),
391 self.end(); // end head-ibox
393 self.end() // end the outer fn box
395 hir::ForeignItemKind::Static(t, m) => {
397 if m == hir::Mutability::Mut {
398 self.word_space("mut");
400 self.print_ident(item.ident);
401 self.word_space(":");
404 self.end(); // end the head-ibox
405 self.end() // end the outer cbox
407 hir::ForeignItemKind::Type => {
409 self.print_ident(item.ident);
411 self.end(); // end the head-ibox
412 self.end() // end the outer cbox
417 fn print_associated_const(
421 default: Option<hir::BodyId>,
424 self.word_space("const");
425 self.print_ident(ident);
426 self.word_space(":");
428 if let Some(expr) = default {
430 self.word_space("=");
431 self.ann.nested(self, Nested::Body(expr));
436 fn print_associated_type(
439 generics: &hir::Generics<'_>,
440 bounds: Option<hir::GenericBounds<'_>>,
441 ty: Option<&hir::Ty<'_>>,
443 self.word_space("type");
444 self.print_ident(ident);
445 self.print_generic_params(generics.params);
446 if let Some(bounds) = bounds {
447 self.print_bounds(":", bounds);
449 self.print_where_clause(generics);
450 if let Some(ty) = ty {
452 self.word_space("=");
460 item: &hir::Item<'_>,
461 generics: &hir::Generics<'_>,
462 inner: impl Fn(&mut Self),
465 self.print_ident(item.ident);
466 self.print_generic_params(generics.params);
467 self.end(); // end the inner ibox
469 self.print_where_clause(generics);
473 self.end(); // end the outer ibox
476 /// Pretty-print an item
477 pub fn print_item(&mut self, item: &hir::Item<'_>) {
478 self.hardbreak_if_not_bol();
479 self.maybe_print_comment(item.span.lo());
480 let attrs = self.attrs(item.hir_id());
481 self.print_outer_attributes(attrs);
482 self.ann.pre(self, AnnNode::Item(item));
484 hir::ItemKind::ExternCrate(orig_name) => {
485 self.head("extern crate");
486 if let Some(orig_name) = orig_name {
487 self.print_name(orig_name);
492 self.print_ident(item.ident);
494 self.end(); // end inner head-block
495 self.end(); // end outer head-block
497 hir::ItemKind::Use(path, kind) => {
499 self.print_path(path, false);
502 hir::UseKind::Single => {
503 if path.segments.last().unwrap().ident != item.ident {
505 self.word_space("as");
506 self.print_ident(item.ident);
510 hir::UseKind::Glob => self.word("::*;"),
511 hir::UseKind::ListStem => self.word("::{};"),
513 self.end(); // end inner head-block
514 self.end(); // end outer head-block
516 hir::ItemKind::Static(ty, m, expr) => {
518 if m == hir::Mutability::Mut {
519 self.word_space("mut");
521 self.print_ident(item.ident);
522 self.word_space(":");
525 self.end(); // end the head-ibox
527 self.word_space("=");
528 self.ann.nested(self, Nested::Body(expr));
530 self.end(); // end the outer cbox
532 hir::ItemKind::Const(ty, expr) => {
534 self.print_ident(item.ident);
535 self.word_space(":");
538 self.end(); // end the head-ibox
540 self.word_space("=");
541 self.ann.nested(self, Nested::Body(expr));
543 self.end(); // end the outer cbox
545 hir::ItemKind::Fn(ref sig, param_names, body) => {
550 Some(item.ident.name),
556 self.end(); // need to close a box
557 self.end(); // need to close a box
558 self.ann.nested(self, Nested::Body(body));
560 hir::ItemKind::Macro(ref macro_def, _) => {
561 self.print_mac_def(macro_def, &item.ident, item.span, |_| {});
563 hir::ItemKind::Mod(ref _mod) => {
565 self.print_ident(item.ident);
568 self.print_mod(_mod, attrs);
569 self.bclose(item.span);
571 hir::ItemKind::ForeignMod { abi, items } => {
573 self.word_nbsp(abi.to_string());
575 self.print_inner_attributes(self.attrs(item.hir_id()));
577 self.ann.nested(self, Nested::ForeignItem(item.id));
579 self.bclose(item.span);
581 hir::ItemKind::GlobalAsm(asm) => {
582 self.head("global_asm!");
583 self.print_inline_asm(asm);
586 hir::ItemKind::TyAlias(ty, generics) => {
587 self.print_item_type(item, generics, |state| {
588 state.word_space("=");
589 state.print_type(ty);
592 hir::ItemKind::OpaqueTy(ref opaque_ty) => {
593 self.print_item_type(item, opaque_ty.generics, |state| {
594 let mut real_bounds = Vec::with_capacity(opaque_ty.bounds.len());
595 for b in opaque_ty.bounds {
596 if let GenericBound::Trait(ptr, hir::TraitBoundModifier::Maybe) = b {
598 state.word_space("for ?");
599 state.print_trait_ref(&ptr.trait_ref);
604 state.print_bounds("= impl", real_bounds);
607 hir::ItemKind::Enum(ref enum_definition, params) => {
608 self.print_enum_def(enum_definition, params, item.ident.name, item.span);
610 hir::ItemKind::Struct(ref struct_def, generics) => {
612 self.print_struct(struct_def, generics, item.ident.name, item.span, true);
614 hir::ItemKind::Union(ref struct_def, generics) => {
616 self.print_struct(struct_def, generics, item.ident.name, item.span, true);
618 hir::ItemKind::Impl(&hir::Impl {
630 self.print_defaultness(defaultness);
631 self.print_unsafety(unsafety);
632 self.word_nbsp("impl");
634 if !generics.params.is_empty() {
635 self.print_generic_params(generics.params);
639 if constness == hir::Constness::Const {
640 self.word_nbsp("const");
643 if let hir::ImplPolarity::Negative(_) = polarity {
647 if let Some(t) = of_trait {
648 self.print_trait_ref(t);
650 self.word_space("for");
653 self.print_type(self_ty);
654 self.print_where_clause(generics);
658 self.print_inner_attributes(attrs);
659 for impl_item in items {
660 self.ann.nested(self, Nested::ImplItem(impl_item.id));
662 self.bclose(item.span);
664 hir::ItemKind::Trait(is_auto, unsafety, generics, bounds, trait_items) => {
666 self.print_is_auto(is_auto);
667 self.print_unsafety(unsafety);
668 self.word_nbsp("trait");
669 self.print_ident(item.ident);
670 self.print_generic_params(generics.params);
671 let mut real_bounds = Vec::with_capacity(bounds.len());
673 if let GenericBound::Trait(ptr, hir::TraitBoundModifier::Maybe) = b {
675 self.word_space("for ?");
676 self.print_trait_ref(&ptr.trait_ref);
681 self.print_bounds(":", real_bounds);
682 self.print_where_clause(generics);
685 for trait_item in trait_items {
686 self.ann.nested(self, Nested::TraitItem(trait_item.id));
688 self.bclose(item.span);
690 hir::ItemKind::TraitAlias(generics, bounds) => {
692 self.print_ident(item.ident);
693 self.print_generic_params(generics.params);
694 let mut real_bounds = Vec::with_capacity(bounds.len());
695 // FIXME(durka) this seems to be some quite outdated syntax
697 if let GenericBound::Trait(ptr, hir::TraitBoundModifier::Maybe) = b {
699 self.word_space("for ?");
700 self.print_trait_ref(&ptr.trait_ref);
706 self.print_bounds("=", real_bounds);
707 self.print_where_clause(generics);
709 self.end(); // end inner head-block
710 self.end(); // end outer head-block
713 self.ann.post(self, AnnNode::Item(item))
716 pub fn print_trait_ref(&mut self, t: &hir::TraitRef<'_>) {
717 self.print_path(t.path, false);
720 fn print_formal_generic_params(&mut self, generic_params: &[hir::GenericParam<'_>]) {
721 if !generic_params.is_empty() {
723 self.print_generic_params(generic_params);
728 fn print_poly_trait_ref(&mut self, t: &hir::PolyTraitRef<'_>) {
729 self.print_formal_generic_params(t.bound_generic_params);
730 self.print_trait_ref(&t.trait_ref);
733 pub fn print_enum_def(
735 enum_definition: &hir::EnumDef<'_>,
736 generics: &hir::Generics<'_>,
738 span: rustc_span::Span,
741 self.print_name(name);
742 self.print_generic_params(generics.params);
743 self.print_where_clause(generics);
745 self.print_variants(enum_definition.variants, span);
748 pub fn print_variants(&mut self, variants: &[hir::Variant<'_>], span: rustc_span::Span) {
751 self.space_if_not_bol();
752 self.maybe_print_comment(v.span.lo());
753 self.print_outer_attributes(self.attrs(v.id));
754 self.ibox(INDENT_UNIT);
755 self.print_variant(v);
758 self.maybe_print_trailing_comment(v.span, None);
763 pub fn print_defaultness(&mut self, defaultness: hir::Defaultness) {
765 hir::Defaultness::Default { .. } => self.word_nbsp("default"),
766 hir::Defaultness::Final => (),
772 struct_def: &hir::VariantData<'_>,
773 generics: &hir::Generics<'_>,
775 span: rustc_span::Span,
776 print_finalizer: bool,
778 self.print_name(name);
779 self.print_generic_params(generics.params);
781 hir::VariantData::Tuple(..) | hir::VariantData::Unit(..) => {
782 if let hir::VariantData::Tuple(..) = struct_def {
784 self.commasep(Inconsistent, struct_def.fields(), |s, field| {
785 s.maybe_print_comment(field.span.lo());
786 s.print_outer_attributes(s.attrs(field.hir_id));
787 s.print_type(field.ty);
791 self.print_where_clause(generics);
796 self.end() // close the outer-box
798 hir::VariantData::Struct(..) => {
799 self.print_where_clause(generics);
802 self.hardbreak_if_not_bol();
804 for field in struct_def.fields() {
805 self.hardbreak_if_not_bol();
806 self.maybe_print_comment(field.span.lo());
807 self.print_outer_attributes(self.attrs(field.hir_id));
808 self.print_ident(field.ident);
810 self.print_type(field.ty);
819 pub fn print_variant(&mut self, v: &hir::Variant<'_>) {
821 let generics = hir::Generics::empty();
822 self.print_struct(&v.data, generics, v.ident.name, v.span, false);
823 if let Some(ref d) = v.disr_expr {
825 self.word_space("=");
826 self.print_anon_const(d);
829 pub fn print_method_sig(
833 generics: &hir::Generics<'_>,
835 body_id: Option<hir::BodyId>,
837 self.print_fn(m.decl, m.header, Some(ident.name), generics, arg_names, body_id);
840 pub fn print_trait_item(&mut self, ti: &hir::TraitItem<'_>) {
841 self.ann.pre(self, AnnNode::SubItem(ti.hir_id()));
842 self.hardbreak_if_not_bol();
843 self.maybe_print_comment(ti.span.lo());
844 self.print_outer_attributes(self.attrs(ti.hir_id()));
846 hir::TraitItemKind::Const(ty, default) => {
847 self.print_associated_const(ti.ident, ty, default);
849 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Required(arg_names)) => {
850 self.print_method_sig(ti.ident, sig, ti.generics, arg_names, None);
853 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Provided(body)) => {
855 self.print_method_sig(ti.ident, sig, ti.generics, &[], Some(body));
857 self.end(); // need to close a box
858 self.end(); // need to close a box
859 self.ann.nested(self, Nested::Body(body));
861 hir::TraitItemKind::Type(bounds, default) => {
862 self.print_associated_type(ti.ident, ti.generics, Some(bounds), default);
865 self.ann.post(self, AnnNode::SubItem(ti.hir_id()))
868 pub fn print_impl_item(&mut self, ii: &hir::ImplItem<'_>) {
869 self.ann.pre(self, AnnNode::SubItem(ii.hir_id()));
870 self.hardbreak_if_not_bol();
871 self.maybe_print_comment(ii.span.lo());
872 self.print_outer_attributes(self.attrs(ii.hir_id()));
875 hir::ImplItemKind::Const(ty, expr) => {
876 self.print_associated_const(ii.ident, ty, Some(expr));
878 hir::ImplItemKind::Fn(ref sig, body) => {
880 self.print_method_sig(ii.ident, sig, ii.generics, &[], Some(body));
882 self.end(); // need to close a box
883 self.end(); // need to close a box
884 self.ann.nested(self, Nested::Body(body));
886 hir::ImplItemKind::TyAlias(ty) => {
887 self.print_associated_type(ii.ident, ii.generics, None, Some(ty));
890 self.ann.post(self, AnnNode::SubItem(ii.hir_id()))
895 init: Option<&hir::Expr<'_>>,
896 els: Option<&hir::Block<'_>>,
897 decl: impl Fn(&mut Self),
899 self.space_if_not_bol();
900 self.ibox(INDENT_UNIT);
901 self.word_nbsp("let");
903 self.ibox(INDENT_UNIT);
907 if let Some(init) = init {
909 self.word_space("=");
910 self.print_expr(init);
913 if let Some(els) = els {
915 self.word_space("else");
916 // containing cbox, will be closed by print-block at `}`
918 // head-box, will be closed by print-block after `{`
920 self.print_block(els);
926 pub fn print_stmt(&mut self, st: &hir::Stmt<'_>) {
927 self.maybe_print_comment(st.span.lo());
929 hir::StmtKind::Local(loc) => {
930 self.print_local(loc.init, loc.els, |this| this.print_local_decl(loc));
932 hir::StmtKind::Item(item) => self.ann.nested(self, Nested::Item(item)),
933 hir::StmtKind::Expr(expr) => {
934 self.space_if_not_bol();
935 self.print_expr(expr);
937 hir::StmtKind::Semi(expr) => {
938 self.space_if_not_bol();
939 self.print_expr(expr);
943 if stmt_ends_with_semi(&st.kind) {
946 self.maybe_print_trailing_comment(st.span, None)
949 pub fn print_block(&mut self, blk: &hir::Block<'_>) {
950 self.print_block_with_attrs(blk, &[])
953 pub fn print_block_unclosed(&mut self, blk: &hir::Block<'_>) {
954 self.print_block_maybe_unclosed(blk, &[], false)
957 pub fn print_block_with_attrs(&mut self, blk: &hir::Block<'_>, attrs: &[ast::Attribute]) {
958 self.print_block_maybe_unclosed(blk, attrs, true)
961 pub fn print_block_maybe_unclosed(
963 blk: &hir::Block<'_>,
964 attrs: &[ast::Attribute],
968 hir::BlockCheckMode::UnsafeBlock(..) => self.word_space("unsafe"),
969 hir::BlockCheckMode::DefaultBlock => (),
971 self.maybe_print_comment(blk.span.lo());
972 self.ann.pre(self, AnnNode::Block(blk));
975 self.print_inner_attributes(attrs);
977 for st in blk.stmts {
980 if let Some(expr) = blk.expr {
981 self.space_if_not_bol();
982 self.print_expr(expr);
983 self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi()));
985 self.bclose_maybe_open(blk.span, close_box);
986 self.ann.post(self, AnnNode::Block(blk))
989 fn print_else(&mut self, els: Option<&hir::Expr<'_>>) {
990 if let Some(els_inner) = els {
991 match els_inner.kind {
992 // Another `else if` block.
993 hir::ExprKind::If(i, then, e) => {
994 self.cbox(INDENT_UNIT - 1);
996 self.word(" else if ");
997 self.print_expr_as_cond(i);
999 self.print_expr(then);
1002 // Final `else` block.
1003 hir::ExprKind::Block(b, _) => {
1004 self.cbox(INDENT_UNIT - 1);
1006 self.word(" else ");
1007 self.print_block(b);
1009 // Constraints would be great here!
1011 panic!("print_if saw if with weird alternative");
1019 test: &hir::Expr<'_>,
1020 blk: &hir::Expr<'_>,
1021 elseopt: Option<&hir::Expr<'_>>,
1024 self.print_expr_as_cond(test);
1026 self.print_expr(blk);
1027 self.print_else(elseopt)
1030 pub fn print_array_length(&mut self, len: &hir::ArrayLen) {
1032 hir::ArrayLen::Infer(_, _) => self.word("_"),
1033 hir::ArrayLen::Body(ct) => self.print_anon_const(ct),
1037 pub fn print_anon_const(&mut self, constant: &hir::AnonConst) {
1038 self.ann.nested(self, Nested::Body(constant.body))
1041 fn print_call_post(&mut self, args: &[hir::Expr<'_>]) {
1043 self.commasep_exprs(Inconsistent, args);
1047 fn print_expr_maybe_paren(&mut self, expr: &hir::Expr<'_>, prec: i8) {
1048 self.print_expr_cond_paren(expr, expr.precedence().order() < prec)
1051 /// Prints an expr using syntax that's acceptable in a condition position, such as the `cond` in
1052 /// `if cond { ... }`.
1053 pub fn print_expr_as_cond(&mut self, expr: &hir::Expr<'_>) {
1054 self.print_expr_cond_paren(expr, Self::cond_needs_par(expr))
1057 /// Prints `expr` or `(expr)` when `needs_par` holds.
1058 fn print_expr_cond_paren(&mut self, expr: &hir::Expr<'_>, needs_par: bool) {
1062 if let hir::ExprKind::DropTemps(actual_expr) = expr.kind {
1063 self.print_expr(actual_expr);
1065 self.print_expr(expr);
1072 /// Print a `let pat = expr` expression.
1073 fn print_let(&mut self, pat: &hir::Pat<'_>, ty: Option<&hir::Ty<'_>>, init: &hir::Expr<'_>) {
1074 self.word_space("let");
1075 self.print_pat(pat);
1076 if let Some(ty) = ty {
1077 self.word_space(":");
1078 self.print_type(ty);
1081 self.word_space("=");
1082 let npals = || parser::needs_par_as_let_scrutinee(init.precedence().order());
1083 self.print_expr_cond_paren(init, Self::cond_needs_par(init) || npals())
1086 // Does `expr` need parentheses when printed in a condition position?
1088 // These cases need parens due to the parse error observed in #26461: `if return {}`
1089 // parses as the erroneous construct `if (return {})`, not `if (return) {}`.
1090 fn cond_needs_par(expr: &hir::Expr<'_>) -> bool {
1092 hir::ExprKind::Break(..) | hir::ExprKind::Closure { .. } | hir::ExprKind::Ret(..) => {
1095 _ => contains_exterior_struct_lit(expr),
1099 fn print_expr_vec(&mut self, exprs: &[hir::Expr<'_>]) {
1100 self.ibox(INDENT_UNIT);
1102 self.commasep_exprs(Inconsistent, exprs);
1107 fn print_expr_anon_const(&mut self, anon_const: &hir::AnonConst) {
1108 self.ibox(INDENT_UNIT);
1109 self.word_space("const");
1110 self.print_anon_const(anon_const);
1114 fn print_expr_repeat(&mut self, element: &hir::Expr<'_>, count: &hir::ArrayLen) {
1115 self.ibox(INDENT_UNIT);
1117 self.print_expr(element);
1118 self.word_space(";");
1119 self.print_array_length(count);
1124 fn print_expr_struct(
1126 qpath: &hir::QPath<'_>,
1127 fields: &[hir::ExprField<'_>],
1128 wth: Option<&hir::Expr<'_>>,
1130 self.print_qpath(qpath, true);
1132 self.commasep_cmnt(Consistent, fields, |s, field| s.print_expr_field(field), |f| f.span);
1133 if let Some(expr) = wth {
1134 self.ibox(INDENT_UNIT);
1135 if !fields.is_empty() {
1140 self.print_expr(expr);
1142 } else if !fields.is_empty() {
1149 fn print_expr_field(&mut self, field: &hir::ExprField<'_>) {
1150 if self.attrs(field.hir_id).is_empty() {
1153 self.cbox(INDENT_UNIT);
1154 self.print_outer_attributes(&self.attrs(field.hir_id));
1155 if !field.is_shorthand {
1156 self.print_ident(field.ident);
1157 self.word_space(":");
1159 self.print_expr(&field.expr);
1163 fn print_expr_tup(&mut self, exprs: &[hir::Expr<'_>]) {
1165 self.commasep_exprs(Inconsistent, exprs);
1166 if exprs.len() == 1 {
1172 fn print_expr_call(&mut self, func: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
1173 let prec = match func.kind {
1174 hir::ExprKind::Field(..) => parser::PREC_FORCE_PAREN,
1175 _ => parser::PREC_POSTFIX,
1178 self.print_expr_maybe_paren(func, prec);
1179 self.print_call_post(args)
1182 fn print_expr_method_call(&mut self, segment: &hir::PathSegment<'_>, args: &[hir::Expr<'_>]) {
1183 let base_args = &args[1..];
1184 self.print_expr_maybe_paren(&args[0], parser::PREC_POSTFIX);
1186 self.print_ident(segment.ident);
1188 let generic_args = segment.args();
1189 if !generic_args.args.is_empty() || !generic_args.bindings.is_empty() {
1190 self.print_generic_args(generic_args, segment.infer_args, true);
1193 self.print_call_post(base_args)
1196 fn print_expr_binary(&mut self, op: hir::BinOp, lhs: &hir::Expr<'_>, rhs: &hir::Expr<'_>) {
1197 let assoc_op = bin_op_to_assoc_op(op.node);
1198 let prec = assoc_op.precedence() as i8;
1199 let fixity = assoc_op.fixity();
1201 let (left_prec, right_prec) = match fixity {
1202 Fixity::Left => (prec, prec + 1),
1203 Fixity::Right => (prec + 1, prec),
1204 Fixity::None => (prec + 1, prec + 1),
1207 let left_prec = match (&lhs.kind, op.node) {
1208 // These cases need parens: `x as i32 < y` has the parser thinking that `i32 < y` is
1209 // the beginning of a path type. It starts trying to parse `x as (i32 < y ...` instead
1210 // of `(x as i32) < ...`. We need to convince it _not_ to do that.
1211 (&hir::ExprKind::Cast { .. }, hir::BinOpKind::Lt | hir::BinOpKind::Shl) => {
1212 parser::PREC_FORCE_PAREN
1214 (&hir::ExprKind::Let { .. }, _) if !parser::needs_par_as_let_scrutinee(prec) => {
1215 parser::PREC_FORCE_PAREN
1220 self.print_expr_maybe_paren(lhs, left_prec);
1222 self.word_space(op.node.as_str());
1223 self.print_expr_maybe_paren(rhs, right_prec)
1226 fn print_expr_unary(&mut self, op: hir::UnOp, expr: &hir::Expr<'_>) {
1227 self.word(op.as_str());
1228 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1231 fn print_expr_addr_of(
1233 kind: hir::BorrowKind,
1234 mutability: hir::Mutability,
1235 expr: &hir::Expr<'_>,
1239 hir::BorrowKind::Ref => self.print_mutability(mutability, false),
1240 hir::BorrowKind::Raw => {
1241 self.word_nbsp("raw");
1242 self.print_mutability(mutability, true);
1245 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1248 fn print_literal(&mut self, lit: &hir::Lit) {
1249 self.maybe_print_comment(lit.span.lo());
1250 self.word(lit.node.to_token_lit().to_string())
1253 fn print_inline_asm(&mut self, asm: &hir::InlineAsm<'_>) {
1256 Operand(&'a hir::InlineAsmOperand<'a>),
1257 Options(ast::InlineAsmOptions),
1260 let mut args = vec![AsmArg::Template(ast::InlineAsmTemplatePiece::to_string(asm.template))];
1261 args.extend(asm.operands.iter().map(|(o, _)| AsmArg::Operand(o)));
1262 if !asm.options.is_empty() {
1263 args.push(AsmArg::Options(asm.options));
1267 self.commasep(Consistent, &args, |s, arg| match *arg {
1268 AsmArg::Template(ref template) => s.print_string(template, ast::StrStyle::Cooked),
1269 AsmArg::Operand(op) => match *op {
1270 hir::InlineAsmOperand::In { reg, ref expr } => {
1273 s.word(format!("{}", reg));
1278 hir::InlineAsmOperand::Out { reg, late, ref expr } => {
1279 s.word(if late { "lateout" } else { "out" });
1281 s.word(format!("{}", reg));
1285 Some(expr) => s.print_expr(expr),
1286 None => s.word("_"),
1289 hir::InlineAsmOperand::InOut { reg, late, ref expr } => {
1290 s.word(if late { "inlateout" } else { "inout" });
1292 s.word(format!("{}", reg));
1297 hir::InlineAsmOperand::SplitInOut { reg, late, ref in_expr, ref out_expr } => {
1298 s.word(if late { "inlateout" } else { "inout" });
1300 s.word(format!("{}", reg));
1303 s.print_expr(in_expr);
1307 Some(out_expr) => s.print_expr(out_expr),
1308 None => s.word("_"),
1311 hir::InlineAsmOperand::Const { ref anon_const } => {
1314 s.print_anon_const(anon_const);
1316 hir::InlineAsmOperand::SymFn { ref anon_const } => {
1319 s.print_anon_const(anon_const);
1321 hir::InlineAsmOperand::SymStatic { ref path, def_id: _ } => {
1322 s.word("sym_static");
1324 s.print_qpath(path, true);
1327 AsmArg::Options(opts) => {
1330 let mut options = vec![];
1331 if opts.contains(ast::InlineAsmOptions::PURE) {
1332 options.push("pure");
1334 if opts.contains(ast::InlineAsmOptions::NOMEM) {
1335 options.push("nomem");
1337 if opts.contains(ast::InlineAsmOptions::READONLY) {
1338 options.push("readonly");
1340 if opts.contains(ast::InlineAsmOptions::PRESERVES_FLAGS) {
1341 options.push("preserves_flags");
1343 if opts.contains(ast::InlineAsmOptions::NORETURN) {
1344 options.push("noreturn");
1346 if opts.contains(ast::InlineAsmOptions::NOSTACK) {
1347 options.push("nostack");
1349 if opts.contains(ast::InlineAsmOptions::ATT_SYNTAX) {
1350 options.push("att_syntax");
1352 if opts.contains(ast::InlineAsmOptions::RAW) {
1353 options.push("raw");
1355 if opts.contains(ast::InlineAsmOptions::MAY_UNWIND) {
1356 options.push("may_unwind");
1358 s.commasep(Inconsistent, &options, |s, &opt| {
1367 pub fn print_expr(&mut self, expr: &hir::Expr<'_>) {
1368 self.maybe_print_comment(expr.span.lo());
1369 self.print_outer_attributes(self.attrs(expr.hir_id));
1370 self.ibox(INDENT_UNIT);
1371 self.ann.pre(self, AnnNode::Expr(expr));
1373 hir::ExprKind::Box(expr) => {
1374 self.word_space("box");
1375 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX);
1377 hir::ExprKind::Array(exprs) => {
1378 self.print_expr_vec(exprs);
1380 hir::ExprKind::ConstBlock(ref anon_const) => {
1381 self.print_expr_anon_const(anon_const);
1383 hir::ExprKind::Repeat(element, ref count) => {
1384 self.print_expr_repeat(element, count);
1386 hir::ExprKind::Struct(qpath, fields, wth) => {
1387 self.print_expr_struct(qpath, fields, wth);
1389 hir::ExprKind::Tup(exprs) => {
1390 self.print_expr_tup(exprs);
1392 hir::ExprKind::Call(func, args) => {
1393 self.print_expr_call(func, args);
1395 hir::ExprKind::MethodCall(segment, args, _) => {
1396 self.print_expr_method_call(segment, args);
1398 hir::ExprKind::Binary(op, lhs, rhs) => {
1399 self.print_expr_binary(op, lhs, rhs);
1401 hir::ExprKind::Unary(op, expr) => {
1402 self.print_expr_unary(op, expr);
1404 hir::ExprKind::AddrOf(k, m, expr) => {
1405 self.print_expr_addr_of(k, m, expr);
1407 hir::ExprKind::Lit(ref lit) => {
1408 self.print_literal(lit);
1410 hir::ExprKind::Cast(expr, ty) => {
1411 let prec = AssocOp::As.precedence() as i8;
1412 self.print_expr_maybe_paren(expr, prec);
1414 self.word_space("as");
1415 self.print_type(ty);
1417 hir::ExprKind::Type(expr, ty) => {
1418 let prec = AssocOp::Colon.precedence() as i8;
1419 self.print_expr_maybe_paren(expr, prec);
1420 self.word_space(":");
1421 self.print_type(ty);
1423 hir::ExprKind::DropTemps(init) => {
1425 self.cbox(INDENT_UNIT);
1429 // Print `let _t = $init;`:
1430 let temp = Ident::from_str("_t");
1431 self.print_local(Some(init), None, |this| this.print_ident(temp));
1435 self.space_if_not_bol();
1436 self.print_ident(temp);
1439 self.bclose_maybe_open(expr.span, true);
1441 hir::ExprKind::Let(&hir::Let { pat, ty, init, .. }) => {
1442 self.print_let(pat, ty, init);
1444 hir::ExprKind::If(test, blk, elseopt) => {
1445 self.print_if(test, blk, elseopt);
1447 hir::ExprKind::Loop(blk, opt_label, _, _) => {
1448 if let Some(label) = opt_label {
1449 self.print_ident(label.ident);
1450 self.word_space(":");
1453 self.print_block(blk);
1455 hir::ExprKind::Match(expr, arms, _) => {
1456 self.cbox(INDENT_UNIT);
1457 self.ibox(INDENT_UNIT);
1458 self.word_nbsp("match");
1459 self.print_expr_as_cond(expr);
1463 self.print_arm(arm);
1465 self.bclose(expr.span);
1467 hir::ExprKind::Closure(&hir::Closure {
1470 bound_generic_params,
1476 self.print_closure_binder(binder, bound_generic_params);
1477 self.print_capture_clause(capture_clause);
1479 self.print_closure_params(fn_decl, body);
1482 // This is a bare expression.
1483 self.ann.nested(self, Nested::Body(body));
1484 self.end(); // need to close a box
1486 // A box will be closed by `print_expr`, but we didn't want an overall
1487 // wrapper so we closed the corresponding opening. so create an
1488 // empty box to satisfy the close.
1491 hir::ExprKind::Block(blk, opt_label) => {
1492 if let Some(label) = opt_label {
1493 self.print_ident(label.ident);
1494 self.word_space(":");
1496 // containing cbox, will be closed by print-block at `}`
1497 self.cbox(INDENT_UNIT);
1498 // head-box, will be closed by print-block after `{`
1500 self.print_block(blk);
1502 hir::ExprKind::Assign(lhs, rhs, _) => {
1503 let prec = AssocOp::Assign.precedence() as i8;
1504 self.print_expr_maybe_paren(lhs, prec + 1);
1506 self.word_space("=");
1507 self.print_expr_maybe_paren(rhs, prec);
1509 hir::ExprKind::AssignOp(op, lhs, rhs) => {
1510 let prec = AssocOp::Assign.precedence() as i8;
1511 self.print_expr_maybe_paren(lhs, prec + 1);
1513 self.word(op.node.as_str());
1514 self.word_space("=");
1515 self.print_expr_maybe_paren(rhs, prec);
1517 hir::ExprKind::Field(expr, ident) => {
1518 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
1520 self.print_ident(ident);
1522 hir::ExprKind::Index(expr, index) => {
1523 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
1525 self.print_expr(index);
1528 hir::ExprKind::Path(ref qpath) => self.print_qpath(qpath, true),
1529 hir::ExprKind::Break(destination, opt_expr) => {
1531 if let Some(label) = destination.label {
1533 self.print_ident(label.ident);
1535 if let Some(expr) = opt_expr {
1537 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
1540 hir::ExprKind::Continue(destination) => {
1541 self.word("continue");
1542 if let Some(label) = destination.label {
1544 self.print_ident(label.ident);
1547 hir::ExprKind::Ret(result) => {
1548 self.word("return");
1549 if let Some(expr) = result {
1551 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
1554 hir::ExprKind::InlineAsm(asm) => {
1556 self.print_inline_asm(asm);
1558 hir::ExprKind::Yield(expr, _) => {
1559 self.word_space("yield");
1560 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
1562 hir::ExprKind::Err => {
1564 self.word("/*ERROR*/");
1568 self.ann.post(self, AnnNode::Expr(expr));
1572 pub fn print_local_decl(&mut self, loc: &hir::Local<'_>) {
1573 self.print_pat(loc.pat);
1574 if let Some(ty) = loc.ty {
1575 self.word_space(":");
1576 self.print_type(ty);
1580 pub fn print_name(&mut self, name: Symbol) {
1581 self.print_ident(Ident::with_dummy_span(name))
1584 pub fn print_path(&mut self, path: &hir::Path<'_>, colons_before_params: bool) {
1585 self.maybe_print_comment(path.span.lo());
1587 for (i, segment) in path.segments.iter().enumerate() {
1591 if segment.ident.name != kw::PathRoot {
1592 self.print_ident(segment.ident);
1593 self.print_generic_args(segment.args(), segment.infer_args, colons_before_params);
1598 pub fn print_path_segment(&mut self, segment: &hir::PathSegment<'_>) {
1599 if segment.ident.name != kw::PathRoot {
1600 self.print_ident(segment.ident);
1601 self.print_generic_args(segment.args(), segment.infer_args, false);
1605 pub fn print_qpath(&mut self, qpath: &hir::QPath<'_>, colons_before_params: bool) {
1607 hir::QPath::Resolved(None, path) => self.print_path(path, colons_before_params),
1608 hir::QPath::Resolved(Some(qself), path) => {
1610 self.print_type(qself);
1612 self.word_space("as");
1614 for (i, segment) in path.segments[..path.segments.len() - 1].iter().enumerate() {
1618 if segment.ident.name != kw::PathRoot {
1619 self.print_ident(segment.ident);
1620 self.print_generic_args(
1623 colons_before_params,
1630 let item_segment = path.segments.last().unwrap();
1631 self.print_ident(item_segment.ident);
1632 self.print_generic_args(
1633 item_segment.args(),
1634 item_segment.infer_args,
1635 colons_before_params,
1638 hir::QPath::TypeRelative(qself, item_segment) => {
1639 // If we've got a compound-qualified-path, let's push an additional pair of angle
1640 // brackets, so that we pretty-print `<<A::B>::C>` as `<A::B>::C`, instead of just
1641 // `A::B::C` (since the latter could be ambiguous to the user)
1642 if let hir::TyKind::Path(hir::QPath::Resolved(None, _)) = qself.kind {
1643 self.print_type(qself);
1646 self.print_type(qself);
1651 self.print_ident(item_segment.ident);
1652 self.print_generic_args(
1653 item_segment.args(),
1654 item_segment.infer_args,
1655 colons_before_params,
1658 hir::QPath::LangItem(lang_item, span, _) => {
1659 self.word("#[lang = \"");
1660 self.print_ident(Ident::new(lang_item.name(), span));
1666 fn print_generic_args(
1668 generic_args: &hir::GenericArgs<'_>,
1670 colons_before_params: bool,
1672 if generic_args.parenthesized {
1674 self.commasep(Inconsistent, generic_args.inputs(), |s, ty| s.print_type(ty));
1677 self.space_if_not_bol();
1678 self.word_space("->");
1679 self.print_type(generic_args.bindings[0].ty());
1681 let start = if colons_before_params { "::<" } else { "<" };
1682 let empty = Cell::new(true);
1683 let start_or_comma = |this: &mut Self| {
1688 this.word_space(",")
1692 let mut nonelided_generic_args: bool = false;
1693 let elide_lifetimes = generic_args.args.iter().all(|arg| match arg {
1694 GenericArg::Lifetime(lt) => lt.is_elided(),
1696 nonelided_generic_args = true;
1701 if nonelided_generic_args {
1702 start_or_comma(self);
1706 |s, generic_arg| match generic_arg {
1707 GenericArg::Lifetime(lt) if !elide_lifetimes => s.print_lifetime(lt),
1708 GenericArg::Lifetime(_) => {}
1709 GenericArg::Type(ty) => s.print_type(ty),
1710 GenericArg::Const(ct) => s.print_anon_const(&ct.value),
1711 GenericArg::Infer(_inf) => s.word("_"),
1716 // FIXME(eddyb): this would leak into error messages (e.g.,
1717 // "non-exhaustive patterns: `Some::<..>(_)` not covered").
1718 if infer_args && false {
1719 start_or_comma(self);
1723 for binding in generic_args.bindings {
1724 start_or_comma(self);
1725 self.print_type_binding(binding);
1734 pub fn print_type_binding(&mut self, binding: &hir::TypeBinding<'_>) {
1735 self.print_ident(binding.ident);
1736 self.print_generic_args(binding.gen_args, false, false);
1738 match binding.kind {
1739 hir::TypeBindingKind::Equality { ref term } => {
1740 self.word_space("=");
1742 Term::Ty(ty) => self.print_type(ty),
1743 Term::Const(ref c) => self.print_anon_const(c),
1746 hir::TypeBindingKind::Constraint { bounds } => {
1747 self.print_bounds(":", bounds);
1752 pub fn print_pat(&mut self, pat: &hir::Pat<'_>) {
1753 self.maybe_print_comment(pat.span.lo());
1754 self.ann.pre(self, AnnNode::Pat(pat));
1755 // Pat isn't normalized, but the beauty of it
1756 // is that it doesn't matter
1758 PatKind::Wild => self.word("_"),
1759 PatKind::Binding(binding_mode, _, ident, sub) => {
1760 match binding_mode {
1761 hir::BindingAnnotation::Ref => {
1762 self.word_nbsp("ref");
1763 self.print_mutability(hir::Mutability::Not, false);
1765 hir::BindingAnnotation::RefMut => {
1766 self.word_nbsp("ref");
1767 self.print_mutability(hir::Mutability::Mut, false);
1769 hir::BindingAnnotation::Unannotated => {}
1770 hir::BindingAnnotation::Mutable => {
1771 self.word_nbsp("mut");
1774 self.print_ident(ident);
1775 if let Some(p) = sub {
1780 PatKind::TupleStruct(ref qpath, elts, ddpos) => {
1781 self.print_qpath(qpath, true);
1783 if let Some(ddpos) = ddpos {
1784 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(p));
1786 self.word_space(",");
1789 if ddpos != elts.len() {
1791 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(p));
1794 self.commasep(Inconsistent, elts, |s, p| s.print_pat(p));
1798 PatKind::Path(ref qpath) => {
1799 self.print_qpath(qpath, true);
1801 PatKind::Struct(ref qpath, fields, etc) => {
1802 self.print_qpath(qpath, true);
1805 let empty = fields.is_empty() && !etc;
1809 self.commasep_cmnt(Consistent, &fields, |s, f| s.print_patfield(f), |f| f.pat.span);
1811 if !fields.is_empty() {
1812 self.word_space(",");
1821 PatKind::Or(pats) => {
1822 self.strsep("|", true, Inconsistent, pats, |s, p| s.print_pat(p));
1824 PatKind::Tuple(elts, ddpos) => {
1826 if let Some(ddpos) = ddpos {
1827 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(p));
1829 self.word_space(",");
1832 if ddpos != elts.len() {
1834 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(p));
1837 self.commasep(Inconsistent, elts, |s, p| s.print_pat(p));
1838 if elts.len() == 1 {
1844 PatKind::Box(inner) => {
1845 let is_range_inner = matches!(inner.kind, PatKind::Range(..));
1850 self.print_pat(inner);
1855 PatKind::Ref(inner, mutbl) => {
1856 let is_range_inner = matches!(inner.kind, PatKind::Range(..));
1858 self.word(mutbl.prefix_str());
1862 self.print_pat(inner);
1867 PatKind::Lit(e) => self.print_expr(e),
1868 PatKind::Range(begin, end, end_kind) => {
1869 if let Some(expr) = begin {
1870 self.print_expr(expr);
1873 RangeEnd::Included => self.word("..."),
1874 RangeEnd::Excluded => self.word(".."),
1876 if let Some(expr) = end {
1877 self.print_expr(expr);
1880 PatKind::Slice(before, slice, after) => {
1882 self.commasep(Inconsistent, before, |s, p| s.print_pat(p));
1883 if let Some(p) = slice {
1884 if !before.is_empty() {
1885 self.word_space(",");
1887 if let PatKind::Wild = p.kind {
1893 if !after.is_empty() {
1894 self.word_space(",");
1897 self.commasep(Inconsistent, after, |s, p| s.print_pat(p));
1901 self.ann.post(self, AnnNode::Pat(pat))
1904 pub fn print_patfield(&mut self, field: &hir::PatField<'_>) {
1905 if self.attrs(field.hir_id).is_empty() {
1908 self.cbox(INDENT_UNIT);
1909 self.print_outer_attributes(&self.attrs(field.hir_id));
1910 if !field.is_shorthand {
1911 self.print_ident(field.ident);
1912 self.word_nbsp(":");
1914 self.print_pat(field.pat);
1918 pub fn print_param(&mut self, arg: &hir::Param<'_>) {
1919 self.print_outer_attributes(self.attrs(arg.hir_id));
1920 self.print_pat(arg.pat);
1923 pub fn print_arm(&mut self, arm: &hir::Arm<'_>) {
1924 // I have no idea why this check is necessary, but here it
1926 if self.attrs(arm.hir_id).is_empty() {
1929 self.cbox(INDENT_UNIT);
1930 self.ann.pre(self, AnnNode::Arm(arm));
1932 self.print_outer_attributes(self.attrs(arm.hir_id));
1933 self.print_pat(arm.pat);
1935 if let Some(ref g) = arm.guard {
1937 hir::Guard::If(e) => {
1938 self.word_space("if");
1942 hir::Guard::IfLet(&hir::Let { pat, ty, init, .. }) => {
1943 self.word_nbsp("if");
1944 self.print_let(pat, ty, init);
1948 self.word_space("=>");
1950 match arm.body.kind {
1951 hir::ExprKind::Block(blk, opt_label) => {
1952 if let Some(label) = opt_label {
1953 self.print_ident(label.ident);
1954 self.word_space(":");
1956 // the block will close the pattern's ibox
1957 self.print_block_unclosed(blk);
1959 // If it is a user-provided unsafe block, print a comma after it
1960 if let hir::BlockCheckMode::UnsafeBlock(hir::UnsafeSource::UserProvided) = blk.rules
1966 self.end(); // close the ibox for the pattern
1967 self.print_expr(arm.body);
1971 self.ann.post(self, AnnNode::Arm(arm));
1972 self.end() // close enclosing cbox
1977 decl: &hir::FnDecl<'_>,
1978 header: hir::FnHeader,
1979 name: Option<Symbol>,
1980 generics: &hir::Generics<'_>,
1981 arg_names: &[Ident],
1982 body_id: Option<hir::BodyId>,
1984 self.print_fn_header_info(header);
1986 if let Some(name) = name {
1988 self.print_name(name);
1990 self.print_generic_params(generics.params);
1994 // Make sure we aren't supplied *both* `arg_names` and `body_id`.
1995 assert!(arg_names.is_empty() || body_id.is_none());
1996 self.commasep(Inconsistent, decl.inputs, |s, ty| {
1997 s.ibox(INDENT_UNIT);
1998 if let Some(arg_name) = arg_names.get(i) {
1999 s.word(arg_name.to_string());
2002 } else if let Some(body_id) = body_id {
2003 s.ann.nested(s, Nested::BodyParamPat(body_id, i));
2011 if decl.c_variadic {
2016 self.print_fn_output(decl);
2017 self.print_where_clause(generics)
2020 fn print_closure_params(&mut self, decl: &hir::FnDecl<'_>, body_id: hir::BodyId) {
2023 self.commasep(Inconsistent, decl.inputs, |s, ty| {
2024 s.ibox(INDENT_UNIT);
2026 s.ann.nested(s, Nested::BodyParamPat(body_id, i));
2029 if let hir::TyKind::Infer = ty.kind {
2040 if let hir::FnRetTy::DefaultReturn(..) = decl.output {
2044 self.space_if_not_bol();
2045 self.word_space("->");
2047 hir::FnRetTy::Return(ty) => {
2048 self.print_type(ty);
2049 self.maybe_print_comment(ty.span.lo());
2051 hir::FnRetTy::DefaultReturn(..) => unreachable!(),
2055 pub fn print_capture_clause(&mut self, capture_clause: hir::CaptureBy) {
2056 match capture_clause {
2057 hir::CaptureBy::Value => self.word_space("move"),
2058 hir::CaptureBy::Ref => {}
2062 pub fn print_closure_binder(
2064 binder: hir::ClosureBinder,
2065 generic_params: &[GenericParam<'_>],
2067 let generic_params = generic_params
2073 kind: GenericParamKind::Lifetime { kind: LifetimeParamKind::Explicit },
2078 .collect::<Vec<_>>();
2081 hir::ClosureBinder::Default => {}
2082 // we need to distinguish `|...| {}` from `for<> |...| {}` as `for<>` adds additional restrictions
2083 hir::ClosureBinder::For { .. } if generic_params.is_empty() => self.word("for<>"),
2084 hir::ClosureBinder::For { .. } => {
2088 self.commasep(Inconsistent, &generic_params, |s, param| {
2089 s.print_generic_param(param)
2098 pub fn print_bounds<'b>(
2100 prefix: &'static str,
2101 bounds: impl IntoIterator<Item = &'b hir::GenericBound<'b>>,
2103 let mut first = true;
2104 for bound in bounds {
2108 if !(first && prefix.is_empty()) {
2114 self.word_space("+");
2118 GenericBound::Trait(tref, modifier) => {
2119 if modifier == &TraitBoundModifier::Maybe {
2122 self.print_poly_trait_ref(tref);
2124 GenericBound::LangItemTrait(lang_item, span, ..) => {
2125 self.word("#[lang = \"");
2126 self.print_ident(Ident::new(lang_item.name(), *span));
2129 GenericBound::Outlives(lt) => {
2130 self.print_lifetime(lt);
2136 pub fn print_generic_params(&mut self, generic_params: &[GenericParam<'_>]) {
2137 if !generic_params.is_empty() {
2140 self.commasep(Inconsistent, generic_params, |s, param| s.print_generic_param(param));
2146 pub fn print_generic_param(&mut self, param: &GenericParam<'_>) {
2147 if let GenericParamKind::Const { .. } = param.kind {
2148 self.word_space("const");
2151 self.print_ident(param.name.ident());
2154 GenericParamKind::Lifetime { .. } => {}
2155 GenericParamKind::Type { default, .. } => {
2156 if let Some(default) = default {
2158 self.word_space("=");
2159 self.print_type(default);
2162 GenericParamKind::Const { ty, ref default } => {
2163 self.word_space(":");
2164 self.print_type(ty);
2165 if let Some(default) = default {
2167 self.word_space("=");
2168 self.print_anon_const(default);
2174 pub fn print_lifetime(&mut self, lifetime: &hir::Lifetime) {
2175 self.print_ident(lifetime.name.ident())
2178 pub fn print_where_clause(&mut self, generics: &hir::Generics<'_>) {
2179 if generics.predicates.is_empty() {
2184 self.word_space("where");
2186 for (i, predicate) in generics.predicates.iter().enumerate() {
2188 self.word_space(",");
2192 hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
2193 bound_generic_params,
2198 self.print_formal_generic_params(bound_generic_params);
2199 self.print_type(bounded_ty);
2200 self.print_bounds(":", bounds);
2202 hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
2207 self.print_lifetime(lifetime);
2210 for (i, bound) in bounds.iter().enumerate() {
2212 GenericBound::Outlives(lt) => {
2213 self.print_lifetime(lt);
2223 hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
2226 self.print_type(lhs_ty);
2228 self.word_space("=");
2229 self.print_type(rhs_ty);
2235 pub fn print_mutability(&mut self, mutbl: hir::Mutability, print_const: bool) {
2237 hir::Mutability::Mut => self.word_nbsp("mut"),
2238 hir::Mutability::Not => {
2240 self.word_nbsp("const")
2246 pub fn print_mt(&mut self, mt: &hir::MutTy<'_>, print_const: bool) {
2247 self.print_mutability(mt.mutbl, print_const);
2248 self.print_type(mt.ty);
2251 pub fn print_fn_output(&mut self, decl: &hir::FnDecl<'_>) {
2252 if let hir::FnRetTy::DefaultReturn(..) = decl.output {
2256 self.space_if_not_bol();
2257 self.ibox(INDENT_UNIT);
2258 self.word_space("->");
2260 hir::FnRetTy::DefaultReturn(..) => unreachable!(),
2261 hir::FnRetTy::Return(ty) => self.print_type(ty),
2265 if let hir::FnRetTy::Return(output) = decl.output {
2266 self.maybe_print_comment(output.span.lo());
2273 unsafety: hir::Unsafety,
2274 decl: &hir::FnDecl<'_>,
2275 name: Option<Symbol>,
2276 generic_params: &[hir::GenericParam<'_>],
2277 arg_names: &[Ident],
2279 self.ibox(INDENT_UNIT);
2280 self.print_formal_generic_params(generic_params);
2281 let generics = hir::Generics::empty();
2287 constness: hir::Constness::NotConst,
2288 asyncness: hir::IsAsync::NotAsync,
2298 pub fn print_fn_header_info(&mut self, header: hir::FnHeader) {
2299 match header.constness {
2300 hir::Constness::NotConst => {}
2301 hir::Constness::Const => self.word_nbsp("const"),
2304 match header.asyncness {
2305 hir::IsAsync::NotAsync => {}
2306 hir::IsAsync::Async => self.word_nbsp("async"),
2309 self.print_unsafety(header.unsafety);
2311 if header.abi != Abi::Rust {
2312 self.word_nbsp("extern");
2313 self.word_nbsp(header.abi.to_string());
2319 pub fn print_unsafety(&mut self, s: hir::Unsafety) {
2321 hir::Unsafety::Normal => {}
2322 hir::Unsafety::Unsafe => self.word_nbsp("unsafe"),
2326 pub fn print_is_auto(&mut self, s: hir::IsAuto) {
2328 hir::IsAuto::Yes => self.word_nbsp("auto"),
2329 hir::IsAuto::No => {}
2334 /// Does this expression require a semicolon to be treated
2335 /// as a statement? The negation of this: 'can this expression
2336 /// be used as a statement without a semicolon' -- is used
2337 /// as an early-bail-out in the parser so that, for instance,
2338 /// if true {...} else {...}
2340 /// isn't parsed as (if true {...} else {...} | x) | 5
2342 // Duplicated from `parse::classify`, but adapted for the HIR.
2343 fn expr_requires_semi_to_be_stmt(e: &hir::Expr<'_>) -> bool {
2346 hir::ExprKind::If(..)
2347 | hir::ExprKind::Match(..)
2348 | hir::ExprKind::Block(..)
2349 | hir::ExprKind::Loop(..)
2353 /// This statement requires a semicolon after it.
2354 /// note that in one case (stmt_semi), we've already
2355 /// seen the semicolon, and thus don't need another.
2356 fn stmt_ends_with_semi(stmt: &hir::StmtKind<'_>) -> bool {
2358 hir::StmtKind::Local(_) => true,
2359 hir::StmtKind::Item(_) => false,
2360 hir::StmtKind::Expr(e) => expr_requires_semi_to_be_stmt(e),
2361 hir::StmtKind::Semi(..) => false,
2365 fn bin_op_to_assoc_op(op: hir::BinOpKind) -> AssocOp {
2366 use crate::hir::BinOpKind::*;
2368 Add => AssocOp::Add,
2369 Sub => AssocOp::Subtract,
2370 Mul => AssocOp::Multiply,
2371 Div => AssocOp::Divide,
2372 Rem => AssocOp::Modulus,
2374 And => AssocOp::LAnd,
2377 BitXor => AssocOp::BitXor,
2378 BitAnd => AssocOp::BitAnd,
2379 BitOr => AssocOp::BitOr,
2380 Shl => AssocOp::ShiftLeft,
2381 Shr => AssocOp::ShiftRight,
2383 Eq => AssocOp::Equal,
2384 Lt => AssocOp::Less,
2385 Le => AssocOp::LessEqual,
2386 Ne => AssocOp::NotEqual,
2387 Ge => AssocOp::GreaterEqual,
2388 Gt => AssocOp::Greater,
2392 /// Expressions that syntactically contain an "exterior" struct literal, i.e., not surrounded by any
2393 /// parens or other delimiters, e.g., `X { y: 1 }`, `X { y: 1 }.method()`, `foo == X { y: 1 }` and
2394 /// `X { y: 1 } == foo` all do, but `(X { y: 1 }) == foo` does not.
2395 fn contains_exterior_struct_lit(value: &hir::Expr<'_>) -> bool {
2397 hir::ExprKind::Struct(..) => true,
2399 hir::ExprKind::Assign(lhs, rhs, _)
2400 | hir::ExprKind::AssignOp(_, lhs, rhs)
2401 | hir::ExprKind::Binary(_, lhs, rhs) => {
2402 // `X { y: 1 } + X { y: 2 }`
2403 contains_exterior_struct_lit(lhs) || contains_exterior_struct_lit(rhs)
2405 hir::ExprKind::Unary(_, x)
2406 | hir::ExprKind::Cast(x, _)
2407 | hir::ExprKind::Type(x, _)
2408 | hir::ExprKind::Field(x, _)
2409 | hir::ExprKind::Index(x, _) => {
2410 // `&X { y: 1 }, X { y: 1 }.y`
2411 contains_exterior_struct_lit(x)
2414 hir::ExprKind::MethodCall(.., exprs, _) => {
2415 // `X { y: 1 }.bar(...)`
2416 contains_exterior_struct_lit(&exprs[0])