1 #![cfg_attr(bootstrap, feature(or_patterns))]
2 #![recursion_limit = "256"]
5 use rustc_ast::util::parser::{self, AssocOp, Fixity};
6 use rustc_ast_pretty::pp::Breaks::{Consistent, Inconsistent};
7 use rustc_ast_pretty::pp::{self, Breaks};
8 use rustc_ast_pretty::pprust::{Comments, PrintState};
10 use rustc_hir::{GenericArg, GenericParam, GenericParamKind, Node};
11 use rustc_hir::{GenericBound, PatKind, RangeEnd, TraitBoundModifier};
12 use rustc_span::source_map::{SourceMap, Spanned};
13 use rustc_span::symbol::{kw, Ident, IdentPrinter, Symbol};
14 use rustc_span::{self, BytePos, FileName};
15 use rustc_target::spec::abi::Abi;
19 use std::collections::BTreeMap;
22 pub fn id_to_string(map: &dyn rustc_hir::intravisit::Map<'_>, hir_id: hir::HirId) -> String {
23 to_string(&map, |s| s.print_node(map.find(hir_id).unwrap()))
26 pub enum AnnNode<'a> {
28 Block(&'a hir::Block<'a>),
29 Item(&'a hir::Item<'a>),
31 Expr(&'a hir::Expr<'a>),
32 Pat(&'a hir::Pat<'a>),
33 Arm(&'a hir::Arm<'a>),
38 TraitItem(hir::TraitItemId),
39 ImplItem(hir::ImplItemId),
40 ForeignItem(hir::ForeignItemId),
42 BodyParamPat(hir::BodyId, usize),
46 fn nested(&self, _state: &mut State<'_>, _nested: Nested) {}
47 fn pre(&self, _state: &mut State<'_>, _node: AnnNode<'_>) {}
48 fn post(&self, _state: &mut State<'_>, _node: AnnNode<'_>) {}
52 impl PpAnn for NoAnn {}
53 pub const NO_ANN: &dyn PpAnn = &NoAnn;
55 impl PpAnn for hir::Crate<'_> {
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 /// Identical to the `PpAnn` implementation for `hir::Crate`,
69 /// except it avoids creating a dependency on the whole crate.
70 impl PpAnn for &dyn rustc_hir::intravisit::Map<'_> {
71 fn nested(&self, state: &mut State<'_>, nested: Nested) {
73 Nested::Item(id) => state.print_item(self.item(id)),
74 Nested::TraitItem(id) => state.print_trait_item(self.trait_item(id)),
75 Nested::ImplItem(id) => state.print_impl_item(self.impl_item(id)),
76 Nested::ForeignItem(id) => state.print_foreign_item(self.foreign_item(id)),
77 Nested::Body(id) => state.print_expr(&self.body(id).value),
78 Nested::BodyParamPat(id, i) => state.print_pat(&self.body(id).params[i].pat),
83 pub struct State<'a> {
85 comments: Option<Comments<'a>>,
86 attrs: &'a BTreeMap<hir::HirId, &'a [ast::Attribute]>,
87 ann: &'a (dyn PpAnn + 'a),
91 pub fn print_node(&mut self, node: Node<'_>) {
93 Node::Param(a) => self.print_param(&a),
94 Node::Item(a) => self.print_item(&a),
95 Node::ForeignItem(a) => self.print_foreign_item(&a),
96 Node::TraitItem(a) => self.print_trait_item(a),
97 Node::ImplItem(a) => self.print_impl_item(a),
98 Node::Variant(a) => self.print_variant(&a),
99 Node::AnonConst(a) => self.print_anon_const(&a),
100 Node::Expr(a) => self.print_expr(&a),
101 Node::Stmt(a) => self.print_stmt(&a),
102 Node::PathSegment(a) => self.print_path_segment(&a),
103 Node::Ty(a) => self.print_type(&a),
104 Node::TraitRef(a) => self.print_trait_ref(&a),
105 Node::Binding(a) | Node::Pat(a) => self.print_pat(&a),
106 Node::Arm(a) => self.print_arm(&a),
108 // Containing cbox, will be closed by print-block at `}`.
109 self.cbox(INDENT_UNIT);
110 // Head-ibox, will be closed by print-block after `{`.
114 Node::Lifetime(a) => self.print_lifetime(&a),
115 Node::Visibility(a) => self.print_visibility(&a),
116 Node::GenericParam(_) => panic!("cannot print Node::GenericParam"),
117 Node::Field(_) => panic!("cannot print Node::Field"),
118 // These cases do not carry enough information in the
119 // `hir_map` to reconstruct their full structure for pretty
121 Node::Ctor(..) => panic!("cannot print isolated Ctor"),
122 Node::Local(a) => self.print_local_decl(&a),
123 Node::MacroDef(_) => panic!("cannot print MacroDef"),
124 Node::Crate(..) => panic!("cannot print Crate"),
129 impl std::ops::Deref for State<'_> {
130 type Target = pp::Printer;
131 fn deref(&self) -> &Self::Target {
136 impl std::ops::DerefMut for State<'_> {
137 fn deref_mut(&mut self) -> &mut Self::Target {
142 impl<'a> PrintState<'a> for State<'a> {
143 fn comments(&mut self) -> &mut Option<Comments<'a>> {
147 fn print_ident(&mut self, ident: Ident) {
148 self.s.word(IdentPrinter::for_ast_ident(ident, ident.is_raw_guess()).to_string());
149 self.ann.post(self, AnnNode::Name(&ident.name))
152 fn print_generic_args(&mut self, _: &ast::GenericArgs, _colons_before_params: bool) {
153 panic!("AST generic args printed by HIR pretty-printer");
157 pub const INDENT_UNIT: usize = 4;
159 /// Requires you to pass an input filename and reader so that
160 /// it can scan the input text for comments to copy forward.
161 pub fn print_crate<'a>(
163 krate: &hir::Crate<'_>,
168 let mut s = State::new_from_input(sm, filename, input, &krate.attrs, ann);
170 // When printing the AST, we sometimes need to inject `#[no_std]` here.
171 // Since you can't compile the HIR, it's not necessary.
173 s.print_mod(&krate.item.module, s.attrs(hir::CRATE_HIR_ID));
174 s.print_remaining_comments();
179 pub fn new_from_input(
183 attrs: &'a BTreeMap<hir::HirId, &[ast::Attribute]>,
188 comments: Some(Comments::new(sm, filename, input)),
194 fn attrs(&self, id: hir::HirId) -> &'a [ast::Attribute] {
195 self.attrs.get(&id).map_or(&[], |la| *la)
199 pub fn to_string<F>(ann: &dyn PpAnn, f: F) -> String
201 F: FnOnce(&mut State<'_>),
204 State { s: pp::mk_printer(), comments: None, attrs: &BTreeMap::default(), ann };
209 pub fn visibility_qualified<S: Into<Cow<'static, str>>>(vis: &hir::Visibility<'_>, w: S) -> String {
210 to_string(NO_ANN, |s| {
211 s.print_visibility(vis);
216 pub fn generic_params_to_string(generic_params: &[GenericParam<'_>]) -> String {
217 to_string(NO_ANN, |s| s.print_generic_params(generic_params))
220 pub fn bounds_to_string<'b>(bounds: impl IntoIterator<Item = &'b hir::GenericBound<'b>>) -> String {
221 to_string(NO_ANN, |s| s.print_bounds("", bounds))
224 pub fn ty_to_string(ty: &hir::Ty<'_>) -> String {
225 to_string(NO_ANN, |s| s.print_type(ty))
228 pub fn path_segment_to_string(segment: &hir::PathSegment<'_>) -> String {
229 to_string(NO_ANN, |s| s.print_path_segment(segment))
232 pub fn path_to_string(segment: &hir::Path<'_>) -> String {
233 to_string(NO_ANN, |s| s.print_path(segment, false))
237 decl: &hir::FnDecl<'_>,
238 header: hir::FnHeader,
239 name: Option<Symbol>,
240 generics: &hir::Generics<'_>,
241 vis: &hir::Visibility<'_>,
243 body_id: Option<hir::BodyId>,
245 to_string(NO_ANN, |s| s.print_fn(decl, header, name, generics, vis, arg_names, body_id))
248 pub fn enum_def_to_string(
249 enum_definition: &hir::EnumDef<'_>,
250 generics: &hir::Generics<'_>,
252 span: rustc_span::Span,
253 visibility: &hir::Visibility<'_>,
255 to_string(NO_ANN, |s| s.print_enum_def(enum_definition, generics, name, span, visibility))
259 pub fn cbox(&mut self, u: usize) {
263 pub fn nbsp(&mut self) {
267 pub fn word_nbsp<S: Into<Cow<'static, str>>>(&mut self, w: S) {
272 pub fn head<S: Into<Cow<'static, str>>>(&mut self, w: S) {
274 // outer-box is consistent
275 self.cbox(INDENT_UNIT);
276 // head-box is inconsistent
277 self.ibox(w.len() + 1);
278 // keyword that starts the head
284 pub fn bopen(&mut self) {
286 self.end(); // close the head-box
289 pub fn bclose_maybe_open(&mut self, span: rustc_span::Span, close_box: bool) {
290 self.maybe_print_comment(span.hi());
291 self.break_offset_if_not_bol(1, -(INDENT_UNIT as isize));
294 self.end(); // close the outer-box
298 pub fn bclose(&mut self, span: rustc_span::Span) {
299 self.bclose_maybe_open(span, true)
302 pub fn space_if_not_bol(&mut self) {
303 if !self.s.is_beginning_of_line() {
308 pub fn break_offset_if_not_bol(&mut self, n: usize, off: isize) {
309 if !self.s.is_beginning_of_line() {
310 self.s.break_offset(n, off)
311 } else if off != 0 && self.s.last_token().is_hardbreak_tok() {
312 // We do something pretty sketchy here: tuck the nonzero
313 // offset-adjustment we were going to deposit along with the
314 // break into the previous hardbreak.
315 self.s.replace_last_token(pp::Printer::hardbreak_tok_offset(off));
319 // Synthesizes a comment that was not textually present in the original source
321 pub fn synth_comment(&mut self, text: String) {
329 pub fn commasep_cmnt<T, F, G>(&mut self, b: Breaks, elts: &[T], mut op: F, mut get_span: G)
331 F: FnMut(&mut State<'_>, &T),
332 G: FnMut(&T) -> rustc_span::Span,
335 let len = elts.len();
338 self.maybe_print_comment(get_span(elt).hi());
343 self.maybe_print_trailing_comment(get_span(elt), Some(get_span(&elts[i]).hi()));
344 self.space_if_not_bol();
350 pub fn commasep_exprs(&mut self, b: Breaks, exprs: &[hir::Expr<'_>]) {
351 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(&e), |e| e.span)
354 pub fn print_mod(&mut self, _mod: &hir::Mod<'_>, attrs: &[ast::Attribute]) {
355 self.print_inner_attributes(attrs);
356 for &item_id in _mod.item_ids {
357 self.ann.nested(self, Nested::Item(item_id));
361 pub fn print_opt_lifetime(&mut self, lifetime: &hir::Lifetime) {
362 if !lifetime.is_elided() {
363 self.print_lifetime(lifetime);
368 pub fn print_type(&mut self, ty: &hir::Ty<'_>) {
369 self.maybe_print_comment(ty.span.lo());
372 hir::TyKind::Slice(ref ty) => {
374 self.print_type(&ty);
377 hir::TyKind::Ptr(ref mt) => {
379 self.print_mt(mt, true);
381 hir::TyKind::Rptr(ref lifetime, ref mt) => {
383 self.print_opt_lifetime(lifetime);
384 self.print_mt(mt, false);
386 hir::TyKind::Never => {
389 hir::TyKind::Tup(ref elts) => {
391 self.commasep(Inconsistent, &elts[..], |s, ty| s.print_type(&ty));
397 hir::TyKind::BareFn(ref f) => {
407 hir::TyKind::OpaqueDef(..) => self.s.word("/*impl Trait*/"),
408 hir::TyKind::Path(ref qpath) => self.print_qpath(qpath, false),
409 hir::TyKind::TraitObject(bounds, ref lifetime, syntax) => {
410 if syntax == ast::TraitObjectSyntax::Dyn {
411 self.word_space("dyn");
413 let mut first = true;
414 for bound in bounds {
419 self.word_space("+");
421 self.print_poly_trait_ref(bound);
423 if !lifetime.is_elided() {
425 self.word_space("+");
426 self.print_lifetime(lifetime);
429 hir::TyKind::Array(ref ty, ref length) => {
431 self.print_type(&ty);
433 self.print_anon_const(length);
436 hir::TyKind::Typeof(ref e) => {
437 self.s.word("typeof(");
438 self.print_anon_const(e);
441 hir::TyKind::Infer => {
444 hir::TyKind::Err => {
446 self.s.word("/*ERROR*/");
453 pub fn print_foreign_item(&mut self, item: &hir::ForeignItem<'_>) {
454 self.hardbreak_if_not_bol();
455 self.maybe_print_comment(item.span.lo());
456 self.print_outer_attributes(self.attrs(item.hir_id()));
458 hir::ForeignItemKind::Fn(ref decl, ref arg_names, ref generics) => {
463 unsafety: hir::Unsafety::Normal,
464 constness: hir::Constness::NotConst,
466 asyncness: hir::IsAsync::NotAsync,
468 Some(item.ident.name),
474 self.end(); // end head-ibox
476 self.end() // end the outer fn box
478 hir::ForeignItemKind::Static(ref t, m) => {
479 self.head(visibility_qualified(&item.vis, "static"));
480 if m == hir::Mutability::Mut {
481 self.word_space("mut");
483 self.print_ident(item.ident);
484 self.word_space(":");
487 self.end(); // end the head-ibox
488 self.end() // end the outer cbox
490 hir::ForeignItemKind::Type => {
491 self.head(visibility_qualified(&item.vis, "type"));
492 self.print_ident(item.ident);
494 self.end(); // end the head-ibox
495 self.end() // end the outer cbox
500 fn print_associated_const(
504 default: Option<hir::BodyId>,
505 vis: &hir::Visibility<'_>,
507 self.s.word(visibility_qualified(vis, ""));
508 self.word_space("const");
509 self.print_ident(ident);
510 self.word_space(":");
512 if let Some(expr) = default {
514 self.word_space("=");
515 self.ann.nested(self, Nested::Body(expr));
520 fn print_associated_type(
523 generics: &hir::Generics<'_>,
524 bounds: Option<hir::GenericBounds<'_>>,
525 ty: Option<&hir::Ty<'_>>,
527 self.word_space("type");
528 self.print_ident(ident);
529 self.print_generic_params(&generics.params);
530 if let Some(bounds) = bounds {
531 self.print_bounds(":", bounds);
533 self.print_where_clause(&generics.where_clause);
534 if let Some(ty) = ty {
536 self.word_space("=");
544 item: &hir::Item<'_>,
545 generics: &hir::Generics<'_>,
546 inner: impl Fn(&mut Self),
548 self.head(visibility_qualified(&item.vis, "type"));
549 self.print_ident(item.ident);
550 self.print_generic_params(&generics.params);
551 self.end(); // end the inner ibox
553 self.print_where_clause(&generics.where_clause);
557 self.end(); // end the outer ibox
560 /// Pretty-print an item
561 pub fn print_item(&mut self, item: &hir::Item<'_>) {
562 self.hardbreak_if_not_bol();
563 self.maybe_print_comment(item.span.lo());
564 let attrs = self.attrs(item.hir_id());
565 self.print_outer_attributes(attrs);
566 self.ann.pre(self, AnnNode::Item(item));
568 hir::ItemKind::ExternCrate(orig_name) => {
569 self.head(visibility_qualified(&item.vis, "extern crate"));
570 if let Some(orig_name) = orig_name {
571 self.print_name(orig_name);
576 self.print_ident(item.ident);
578 self.end(); // end inner head-block
579 self.end(); // end outer head-block
581 hir::ItemKind::Use(ref path, kind) => {
582 self.head(visibility_qualified(&item.vis, "use"));
583 self.print_path(path, false);
586 hir::UseKind::Single => {
587 if path.segments.last().unwrap().ident != item.ident {
589 self.word_space("as");
590 self.print_ident(item.ident);
594 hir::UseKind::Glob => self.s.word("::*;"),
595 hir::UseKind::ListStem => self.s.word("::{};"),
597 self.end(); // end inner head-block
598 self.end(); // end outer head-block
600 hir::ItemKind::Static(ref ty, m, expr) => {
601 self.head(visibility_qualified(&item.vis, "static"));
602 if m == hir::Mutability::Mut {
603 self.word_space("mut");
605 self.print_ident(item.ident);
606 self.word_space(":");
607 self.print_type(&ty);
609 self.end(); // end the head-ibox
611 self.word_space("=");
612 self.ann.nested(self, Nested::Body(expr));
614 self.end(); // end the outer cbox
616 hir::ItemKind::Const(ref ty, expr) => {
617 self.head(visibility_qualified(&item.vis, "const"));
618 self.print_ident(item.ident);
619 self.word_space(":");
620 self.print_type(&ty);
622 self.end(); // end the head-ibox
624 self.word_space("=");
625 self.ann.nested(self, Nested::Body(expr));
627 self.end(); // end the outer cbox
629 hir::ItemKind::Fn(ref sig, ref param_names, body) => {
634 Some(item.ident.name),
641 self.end(); // need to close a box
642 self.end(); // need to close a box
643 self.ann.nested(self, Nested::Body(body));
645 hir::ItemKind::Mod(ref _mod) => {
646 self.head(visibility_qualified(&item.vis, "mod"));
647 self.print_ident(item.ident);
650 self.print_mod(_mod, attrs);
651 self.bclose(item.span);
653 hir::ItemKind::ForeignMod { abi, items } => {
655 self.word_nbsp(abi.to_string());
657 self.print_inner_attributes(self.attrs(item.hir_id()));
659 self.ann.nested(self, Nested::ForeignItem(item.id));
661 self.bclose(item.span);
663 hir::ItemKind::GlobalAsm(ref ga) => {
664 self.head(visibility_qualified(&item.vis, "global asm"));
665 self.s.word(ga.asm.to_string());
668 hir::ItemKind::TyAlias(ref ty, ref generics) => {
669 self.print_item_type(item, &generics, |state| {
670 state.word_space("=");
671 state.print_type(&ty);
674 hir::ItemKind::OpaqueTy(ref opaque_ty) => {
675 self.print_item_type(item, &opaque_ty.generics, |state| {
676 let mut real_bounds = Vec::with_capacity(opaque_ty.bounds.len());
677 for b in opaque_ty.bounds.iter() {
678 if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
680 state.word_space("for ?");
681 state.print_trait_ref(&ptr.trait_ref);
686 state.print_bounds("= impl", real_bounds);
689 hir::ItemKind::Enum(ref enum_definition, ref params) => {
690 self.print_enum_def(enum_definition, params, item.ident.name, item.span, &item.vis);
692 hir::ItemKind::Struct(ref struct_def, ref generics) => {
693 self.head(visibility_qualified(&item.vis, "struct"));
694 self.print_struct(struct_def, generics, item.ident.name, item.span, true);
696 hir::ItemKind::Union(ref struct_def, ref generics) => {
697 self.head(visibility_qualified(&item.vis, "union"));
698 self.print_struct(struct_def, generics, item.ident.name, item.span, true);
700 hir::ItemKind::Impl(hir::Impl {
712 self.print_visibility(&item.vis);
713 self.print_defaultness(defaultness);
714 self.print_unsafety(unsafety);
715 self.word_nbsp("impl");
717 if !generics.params.is_empty() {
718 self.print_generic_params(&generics.params);
722 if constness == hir::Constness::Const {
723 self.word_nbsp("const");
726 if let hir::ImplPolarity::Negative(_) = polarity {
730 if let Some(ref t) = of_trait {
731 self.print_trait_ref(t);
733 self.word_space("for");
736 self.print_type(&self_ty);
737 self.print_where_clause(&generics.where_clause);
741 self.print_inner_attributes(attrs);
742 for impl_item in items {
743 self.ann.nested(self, Nested::ImplItem(impl_item.id));
745 self.bclose(item.span);
747 hir::ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, trait_items) => {
749 self.print_visibility(&item.vis);
750 self.print_is_auto(is_auto);
751 self.print_unsafety(unsafety);
752 self.word_nbsp("trait");
753 self.print_ident(item.ident);
754 self.print_generic_params(&generics.params);
755 let mut real_bounds = Vec::with_capacity(bounds.len());
756 for b in bounds.iter() {
757 if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
759 self.word_space("for ?");
760 self.print_trait_ref(&ptr.trait_ref);
765 self.print_bounds(":", real_bounds);
766 self.print_where_clause(&generics.where_clause);
769 for trait_item in trait_items {
770 self.ann.nested(self, Nested::TraitItem(trait_item.id));
772 self.bclose(item.span);
774 hir::ItemKind::TraitAlias(ref generics, ref bounds) => {
776 self.print_visibility(&item.vis);
777 self.word_nbsp("trait");
778 self.print_ident(item.ident);
779 self.print_generic_params(&generics.params);
780 let mut real_bounds = Vec::with_capacity(bounds.len());
781 // FIXME(durka) this seems to be some quite outdated syntax
782 for b in bounds.iter() {
783 if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
785 self.word_space("for ?");
786 self.print_trait_ref(&ptr.trait_ref);
792 self.print_bounds("=", real_bounds);
793 self.print_where_clause(&generics.where_clause);
797 self.ann.post(self, AnnNode::Item(item))
800 pub fn print_trait_ref(&mut self, t: &hir::TraitRef<'_>) {
801 self.print_path(&t.path, false)
804 fn print_formal_generic_params(&mut self, generic_params: &[hir::GenericParam<'_>]) {
805 if !generic_params.is_empty() {
807 self.print_generic_params(generic_params);
812 fn print_poly_trait_ref(&mut self, t: &hir::PolyTraitRef<'_>) {
813 self.print_formal_generic_params(&t.bound_generic_params);
814 self.print_trait_ref(&t.trait_ref)
817 pub fn print_enum_def(
819 enum_definition: &hir::EnumDef<'_>,
820 generics: &hir::Generics<'_>,
822 span: rustc_span::Span,
823 visibility: &hir::Visibility<'_>,
825 self.head(visibility_qualified(visibility, "enum"));
826 self.print_name(name);
827 self.print_generic_params(&generics.params);
828 self.print_where_clause(&generics.where_clause);
830 self.print_variants(&enum_definition.variants, span)
833 pub fn print_variants(&mut self, variants: &[hir::Variant<'_>], span: rustc_span::Span) {
836 self.space_if_not_bol();
837 self.maybe_print_comment(v.span.lo());
838 self.print_outer_attributes(self.attrs(v.id));
839 self.ibox(INDENT_UNIT);
840 self.print_variant(v);
843 self.maybe_print_trailing_comment(v.span, None);
848 pub fn print_visibility(&mut self, vis: &hir::Visibility<'_>) {
850 hir::VisibilityKind::Public => self.word_nbsp("pub"),
851 hir::VisibilityKind::Crate(ast::CrateSugar::JustCrate) => self.word_nbsp("crate"),
852 hir::VisibilityKind::Crate(ast::CrateSugar::PubCrate) => self.word_nbsp("pub(crate)"),
853 hir::VisibilityKind::Restricted { ref path, .. } => {
855 if path.segments.len() == 1 && path.segments[0].ident.name == kw::Super {
856 // Special case: `super` can print like `pub(super)`.
857 self.s.word("super");
859 // Everything else requires `in` at present.
860 self.word_nbsp("in");
861 self.print_path(path, false);
865 hir::VisibilityKind::Inherited => (),
869 pub fn print_defaultness(&mut self, defaultness: hir::Defaultness) {
871 hir::Defaultness::Default { .. } => self.word_nbsp("default"),
872 hir::Defaultness::Final => (),
878 struct_def: &hir::VariantData<'_>,
879 generics: &hir::Generics<'_>,
881 span: rustc_span::Span,
882 print_finalizer: bool,
884 self.print_name(name);
885 self.print_generic_params(&generics.params);
887 hir::VariantData::Tuple(..) | hir::VariantData::Unit(..) => {
888 if let hir::VariantData::Tuple(..) = struct_def {
890 self.commasep(Inconsistent, struct_def.fields(), |s, field| {
891 s.maybe_print_comment(field.span.lo());
892 s.print_outer_attributes(s.attrs(field.hir_id));
893 s.print_visibility(&field.vis);
894 s.print_type(&field.ty)
898 self.print_where_clause(&generics.where_clause);
903 self.end() // close the outer-box
905 hir::VariantData::Struct(..) => {
906 self.print_where_clause(&generics.where_clause);
909 self.hardbreak_if_not_bol();
911 for field in struct_def.fields() {
912 self.hardbreak_if_not_bol();
913 self.maybe_print_comment(field.span.lo());
914 self.print_outer_attributes(self.attrs(field.hir_id));
915 self.print_visibility(&field.vis);
916 self.print_ident(field.ident);
918 self.print_type(&field.ty);
927 pub fn print_variant(&mut self, v: &hir::Variant<'_>) {
929 let generics = hir::Generics::empty();
930 self.print_struct(&v.data, &generics, v.ident.name, v.span, false);
931 if let Some(ref d) = v.disr_expr {
933 self.word_space("=");
934 self.print_anon_const(d);
937 pub fn print_method_sig(
941 generics: &hir::Generics<'_>,
942 vis: &hir::Visibility<'_>,
944 body_id: Option<hir::BodyId>,
946 self.print_fn(&m.decl, m.header, Some(ident.name), generics, vis, arg_names, body_id)
949 pub fn print_trait_item(&mut self, ti: &hir::TraitItem<'_>) {
950 self.ann.pre(self, AnnNode::SubItem(ti.hir_id()));
951 self.hardbreak_if_not_bol();
952 self.maybe_print_comment(ti.span.lo());
953 self.print_outer_attributes(self.attrs(ti.hir_id()));
955 hir::TraitItemKind::Const(ref ty, default) => {
957 Spanned { span: rustc_span::DUMMY_SP, node: hir::VisibilityKind::Inherited };
958 self.print_associated_const(ti.ident, &ty, default, &vis);
960 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Required(ref arg_names)) => {
962 Spanned { span: rustc_span::DUMMY_SP, node: hir::VisibilityKind::Inherited };
963 self.print_method_sig(ti.ident, sig, &ti.generics, &vis, arg_names, None);
966 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Provided(body)) => {
968 Spanned { span: rustc_span::DUMMY_SP, node: hir::VisibilityKind::Inherited };
970 self.print_method_sig(ti.ident, sig, &ti.generics, &vis, &[], Some(body));
972 self.end(); // need to close a box
973 self.end(); // need to close a box
974 self.ann.nested(self, Nested::Body(body));
976 hir::TraitItemKind::Type(ref bounds, ref default) => {
977 self.print_associated_type(
981 default.as_ref().map(|ty| &**ty),
985 self.ann.post(self, AnnNode::SubItem(ti.hir_id()))
988 pub fn print_impl_item(&mut self, ii: &hir::ImplItem<'_>) {
989 self.ann.pre(self, AnnNode::SubItem(ii.hir_id()));
990 self.hardbreak_if_not_bol();
991 self.maybe_print_comment(ii.span.lo());
992 self.print_outer_attributes(self.attrs(ii.hir_id()));
993 self.print_defaultness(ii.defaultness);
996 hir::ImplItemKind::Const(ref ty, expr) => {
997 self.print_associated_const(ii.ident, &ty, Some(expr), &ii.vis);
999 hir::ImplItemKind::Fn(ref sig, body) => {
1001 self.print_method_sig(ii.ident, sig, &ii.generics, &ii.vis, &[], Some(body));
1003 self.end(); // need to close a box
1004 self.end(); // need to close a box
1005 self.ann.nested(self, Nested::Body(body));
1007 hir::ImplItemKind::TyAlias(ref ty) => {
1008 self.print_associated_type(ii.ident, &ii.generics, None, Some(ty));
1011 self.ann.post(self, AnnNode::SubItem(ii.hir_id()))
1014 pub fn print_local(&mut self, init: Option<&hir::Expr<'_>>, decl: impl Fn(&mut Self)) {
1015 self.space_if_not_bol();
1016 self.ibox(INDENT_UNIT);
1017 self.word_nbsp("let");
1019 self.ibox(INDENT_UNIT);
1023 if let Some(ref init) = init {
1025 self.word_space("=");
1026 self.print_expr(&init);
1031 pub fn print_stmt(&mut self, st: &hir::Stmt<'_>) {
1032 self.maybe_print_comment(st.span.lo());
1034 hir::StmtKind::Local(ref loc) => {
1035 self.print_local(loc.init.as_deref(), |this| this.print_local_decl(&loc));
1037 hir::StmtKind::Item(item) => self.ann.nested(self, Nested::Item(item)),
1038 hir::StmtKind::Expr(ref expr) => {
1039 self.space_if_not_bol();
1040 self.print_expr(&expr);
1042 hir::StmtKind::Semi(ref expr) => {
1043 self.space_if_not_bol();
1044 self.print_expr(&expr);
1048 if stmt_ends_with_semi(&st.kind) {
1051 self.maybe_print_trailing_comment(st.span, None)
1054 pub fn print_block(&mut self, blk: &hir::Block<'_>) {
1055 self.print_block_with_attrs(blk, &[])
1058 pub fn print_block_unclosed(&mut self, blk: &hir::Block<'_>) {
1059 self.print_block_maybe_unclosed(blk, &[], false)
1062 pub fn print_block_with_attrs(&mut self, blk: &hir::Block<'_>, attrs: &[ast::Attribute]) {
1063 self.print_block_maybe_unclosed(blk, attrs, true)
1066 pub fn print_block_maybe_unclosed(
1068 blk: &hir::Block<'_>,
1069 attrs: &[ast::Attribute],
1073 hir::BlockCheckMode::UnsafeBlock(..) => self.word_space("unsafe"),
1074 hir::BlockCheckMode::PushUnsafeBlock(..) => self.word_space("push_unsafe"),
1075 hir::BlockCheckMode::PopUnsafeBlock(..) => self.word_space("pop_unsafe"),
1076 hir::BlockCheckMode::DefaultBlock => (),
1078 self.maybe_print_comment(blk.span.lo());
1079 self.ann.pre(self, AnnNode::Block(blk));
1082 self.print_inner_attributes(attrs);
1084 for st in blk.stmts {
1085 self.print_stmt(st);
1087 if let Some(ref expr) = blk.expr {
1088 self.space_if_not_bol();
1089 self.print_expr(&expr);
1090 self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi()));
1092 self.bclose_maybe_open(blk.span, close_box);
1093 self.ann.post(self, AnnNode::Block(blk))
1096 fn print_else(&mut self, els: Option<&hir::Expr<'_>>) {
1100 // "another else-if"
1101 hir::ExprKind::If(ref i, ref then, ref e) => {
1102 self.cbox(INDENT_UNIT - 1);
1104 self.s.word(" else if ");
1105 self.print_expr_as_cond(&i);
1107 self.print_expr(&then);
1108 self.print_else(e.as_ref().map(|e| &**e))
1111 hir::ExprKind::Block(ref b, _) => {
1112 self.cbox(INDENT_UNIT - 1);
1114 self.s.word(" else ");
1115 self.print_block(&b)
1117 // BLEAH, constraints would be great here
1119 panic!("print_if saw if with weird alternative");
1129 test: &hir::Expr<'_>,
1130 blk: &hir::Expr<'_>,
1131 elseopt: Option<&hir::Expr<'_>>,
1134 self.print_expr_as_cond(test);
1136 self.print_expr(blk);
1137 self.print_else(elseopt)
1140 pub fn print_anon_const(&mut self, constant: &hir::AnonConst) {
1141 self.ann.nested(self, Nested::Body(constant.body))
1144 fn print_call_post(&mut self, args: &[hir::Expr<'_>]) {
1146 self.commasep_exprs(Inconsistent, args);
1150 pub fn print_expr_maybe_paren(&mut self, expr: &hir::Expr<'_>, prec: i8) {
1151 let needs_par = expr.precedence().order() < prec;
1155 self.print_expr(expr);
1161 /// Print an expr using syntax that's acceptable in a condition position, such as the `cond` in
1162 /// `if cond { ... }`.
1163 pub fn print_expr_as_cond(&mut self, expr: &hir::Expr<'_>) {
1164 let needs_par = match expr.kind {
1165 // These cases need parens due to the parse error observed in #26461: `if return {}`
1166 // parses as the erroneous construct `if (return {})`, not `if (return) {}`.
1167 hir::ExprKind::Closure(..) | hir::ExprKind::Ret(..) | hir::ExprKind::Break(..) => true,
1169 _ => contains_exterior_struct_lit(expr),
1175 self.print_expr(expr);
1181 fn print_expr_vec(&mut self, exprs: &[hir::Expr<'_>]) {
1182 self.ibox(INDENT_UNIT);
1184 self.commasep_exprs(Inconsistent, exprs);
1189 fn print_expr_anon_const(&mut self, anon_const: &hir::AnonConst) {
1190 self.ibox(INDENT_UNIT);
1191 self.s.word_space("const");
1192 self.print_anon_const(anon_const);
1196 fn print_expr_repeat(&mut self, element: &hir::Expr<'_>, count: &hir::AnonConst) {
1197 self.ibox(INDENT_UNIT);
1199 self.print_expr(element);
1200 self.word_space(";");
1201 self.print_anon_const(count);
1206 fn print_expr_struct(
1208 qpath: &hir::QPath<'_>,
1209 fields: &[hir::ExprField<'_>],
1210 wth: &Option<&hir::Expr<'_>>,
1212 self.print_qpath(qpath, true);
1218 s.ibox(INDENT_UNIT);
1219 if !field.is_shorthand {
1220 s.print_ident(field.ident);
1223 s.print_expr(&field.expr);
1230 self.ibox(INDENT_UNIT);
1231 if !fields.is_empty() {
1236 self.print_expr(&expr);
1240 if !fields.is_empty() {
1248 fn print_expr_tup(&mut self, exprs: &[hir::Expr<'_>]) {
1250 self.commasep_exprs(Inconsistent, exprs);
1251 if exprs.len() == 1 {
1257 fn print_expr_call(&mut self, func: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
1258 let prec = match func.kind {
1259 hir::ExprKind::Field(..) => parser::PREC_FORCE_PAREN,
1260 _ => parser::PREC_POSTFIX,
1263 self.print_expr_maybe_paren(func, prec);
1264 self.print_call_post(args)
1267 fn print_expr_method_call(&mut self, segment: &hir::PathSegment<'_>, args: &[hir::Expr<'_>]) {
1268 let base_args = &args[1..];
1269 self.print_expr_maybe_paren(&args[0], parser::PREC_POSTFIX);
1271 self.print_ident(segment.ident);
1273 let generic_args = segment.args();
1274 if !generic_args.args.is_empty() || !generic_args.bindings.is_empty() {
1275 self.print_generic_args(generic_args, segment.infer_args, true);
1278 self.print_call_post(base_args)
1281 fn print_expr_binary(&mut self, op: hir::BinOp, lhs: &hir::Expr<'_>, rhs: &hir::Expr<'_>) {
1282 let assoc_op = bin_op_to_assoc_op(op.node);
1283 let prec = assoc_op.precedence() as i8;
1284 let fixity = assoc_op.fixity();
1286 let (left_prec, right_prec) = match fixity {
1287 Fixity::Left => (prec, prec + 1),
1288 Fixity::Right => (prec + 1, prec),
1289 Fixity::None => (prec + 1, prec + 1),
1292 let left_prec = match (&lhs.kind, op.node) {
1293 // These cases need parens: `x as i32 < y` has the parser thinking that `i32 < y` is
1294 // the beginning of a path type. It starts trying to parse `x as (i32 < y ...` instead
1295 // of `(x as i32) < ...`. We need to convince it _not_ to do that.
1296 (&hir::ExprKind::Cast { .. }, hir::BinOpKind::Lt | hir::BinOpKind::Shl) => {
1297 parser::PREC_FORCE_PAREN
1302 self.print_expr_maybe_paren(lhs, left_prec);
1304 self.word_space(op.node.as_str());
1305 self.print_expr_maybe_paren(rhs, right_prec)
1308 fn print_expr_unary(&mut self, op: hir::UnOp, expr: &hir::Expr<'_>) {
1309 self.s.word(op.as_str());
1310 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1313 fn print_expr_addr_of(
1315 kind: hir::BorrowKind,
1316 mutability: hir::Mutability,
1317 expr: &hir::Expr<'_>,
1321 hir::BorrowKind::Ref => self.print_mutability(mutability, false),
1322 hir::BorrowKind::Raw => {
1323 self.word_nbsp("raw");
1324 self.print_mutability(mutability, true);
1327 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1330 fn print_literal(&mut self, lit: &hir::Lit) {
1331 self.maybe_print_comment(lit.span.lo());
1332 self.word(lit.node.to_lit_token().to_string())
1335 pub fn print_expr(&mut self, expr: &hir::Expr<'_>) {
1336 self.maybe_print_comment(expr.span.lo());
1337 self.print_outer_attributes(self.attrs(expr.hir_id));
1338 self.ibox(INDENT_UNIT);
1339 self.ann.pre(self, AnnNode::Expr(expr));
1341 hir::ExprKind::Box(ref expr) => {
1342 self.word_space("box");
1343 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX);
1345 hir::ExprKind::Array(ref exprs) => {
1346 self.print_expr_vec(exprs);
1348 hir::ExprKind::ConstBlock(ref anon_const) => {
1349 self.print_expr_anon_const(anon_const);
1351 hir::ExprKind::Repeat(ref element, ref count) => {
1352 self.print_expr_repeat(&element, count);
1354 hir::ExprKind::Struct(ref qpath, fields, ref wth) => {
1355 self.print_expr_struct(qpath, fields, wth);
1357 hir::ExprKind::Tup(ref exprs) => {
1358 self.print_expr_tup(exprs);
1360 hir::ExprKind::Call(ref func, ref args) => {
1361 self.print_expr_call(&func, args);
1363 hir::ExprKind::MethodCall(ref segment, _, ref args, _) => {
1364 self.print_expr_method_call(segment, args);
1366 hir::ExprKind::Binary(op, ref lhs, ref rhs) => {
1367 self.print_expr_binary(op, &lhs, &rhs);
1369 hir::ExprKind::Unary(op, ref expr) => {
1370 self.print_expr_unary(op, &expr);
1372 hir::ExprKind::AddrOf(k, m, ref expr) => {
1373 self.print_expr_addr_of(k, m, &expr);
1375 hir::ExprKind::Lit(ref lit) => {
1376 self.print_literal(&lit);
1378 hir::ExprKind::Cast(ref expr, ref ty) => {
1379 let prec = AssocOp::As.precedence() as i8;
1380 self.print_expr_maybe_paren(&expr, prec);
1382 self.word_space("as");
1383 self.print_type(&ty);
1385 hir::ExprKind::Type(ref expr, ref ty) => {
1386 let prec = AssocOp::Colon.precedence() as i8;
1387 self.print_expr_maybe_paren(&expr, prec);
1388 self.word_space(":");
1389 self.print_type(&ty);
1391 hir::ExprKind::DropTemps(ref init) => {
1393 self.cbox(INDENT_UNIT);
1397 // Print `let _t = $init;`:
1398 let temp = Ident::from_str("_t");
1399 self.print_local(Some(init), |this| this.print_ident(temp));
1403 self.space_if_not_bol();
1404 self.print_ident(temp);
1407 self.bclose_maybe_open(expr.span, true);
1409 hir::ExprKind::If(ref test, ref blk, ref elseopt) => {
1410 self.print_if(&test, &blk, elseopt.as_ref().map(|e| &**e));
1412 hir::ExprKind::Loop(ref blk, opt_label, _, _) => {
1413 if let Some(label) = opt_label {
1414 self.print_ident(label.ident);
1415 self.word_space(":");
1419 self.print_block(&blk);
1421 hir::ExprKind::Match(ref expr, arms, _) => {
1422 self.cbox(INDENT_UNIT);
1423 self.ibox(INDENT_UNIT);
1424 self.word_nbsp("match");
1425 self.print_expr_as_cond(&expr);
1429 self.print_arm(arm);
1431 self.bclose(expr.span);
1433 hir::ExprKind::Closure(capture_clause, ref decl, body, _fn_decl_span, _gen) => {
1434 self.print_capture_clause(capture_clause);
1436 self.print_closure_params(&decl, body);
1439 // This is a bare expression.
1440 self.ann.nested(self, Nested::Body(body));
1441 self.end(); // need to close a box
1443 // A box will be closed by `print_expr`, but we didn't want an overall
1444 // wrapper so we closed the corresponding opening. so create an
1445 // empty box to satisfy the close.
1448 hir::ExprKind::Block(ref blk, opt_label) => {
1449 if let Some(label) = opt_label {
1450 self.print_ident(label.ident);
1451 self.word_space(":");
1453 // containing cbox, will be closed by print-block at `}`
1454 self.cbox(INDENT_UNIT);
1455 // head-box, will be closed by print-block after `{`
1457 self.print_block(&blk);
1459 hir::ExprKind::Assign(ref lhs, ref rhs, _) => {
1460 let prec = AssocOp::Assign.precedence() as i8;
1461 self.print_expr_maybe_paren(&lhs, prec + 1);
1463 self.word_space("=");
1464 self.print_expr_maybe_paren(&rhs, prec);
1466 hir::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
1467 let prec = AssocOp::Assign.precedence() as i8;
1468 self.print_expr_maybe_paren(&lhs, prec + 1);
1470 self.s.word(op.node.as_str());
1471 self.word_space("=");
1472 self.print_expr_maybe_paren(&rhs, prec);
1474 hir::ExprKind::Field(ref expr, ident) => {
1475 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
1477 self.print_ident(ident);
1479 hir::ExprKind::Index(ref expr, ref index) => {
1480 self.print_expr_maybe_paren(&expr, parser::PREC_POSTFIX);
1482 self.print_expr(&index);
1485 hir::ExprKind::Path(ref qpath) => self.print_qpath(qpath, true),
1486 hir::ExprKind::Break(destination, ref opt_expr) => {
1487 self.s.word("break");
1489 if let Some(label) = destination.label {
1490 self.print_ident(label.ident);
1493 if let Some(ref expr) = *opt_expr {
1494 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
1498 hir::ExprKind::Continue(destination) => {
1499 self.s.word("continue");
1501 if let Some(label) = destination.label {
1502 self.print_ident(label.ident);
1506 hir::ExprKind::Ret(ref result) => {
1507 self.s.word("return");
1508 if let Some(ref expr) = *result {
1510 self.print_expr_maybe_paren(&expr, parser::PREC_JUMP);
1513 hir::ExprKind::InlineAsm(ref a) => {
1516 Operand(&'a hir::InlineAsmOperand<'a>),
1517 Options(ast::InlineAsmOptions),
1520 let mut args = vec![];
1521 args.push(AsmArg::Template(ast::InlineAsmTemplatePiece::to_string(&a.template)));
1522 args.extend(a.operands.iter().map(|(o, _)| AsmArg::Operand(o)));
1523 if !a.options.is_empty() {
1524 args.push(AsmArg::Options(a.options));
1529 self.commasep(Consistent, &args, |s, arg| match arg {
1530 AsmArg::Template(template) => s.print_string(&template, ast::StrStyle::Cooked),
1531 AsmArg::Operand(op) => match op {
1532 hir::InlineAsmOperand::In { reg, expr } => {
1535 s.word(format!("{}", reg));
1540 hir::InlineAsmOperand::Out { reg, late, expr } => {
1541 s.word(if *late { "lateout" } else { "out" });
1543 s.word(format!("{}", reg));
1547 Some(expr) => s.print_expr(expr),
1548 None => s.word("_"),
1551 hir::InlineAsmOperand::InOut { reg, late, expr } => {
1552 s.word(if *late { "inlateout" } else { "inout" });
1554 s.word(format!("{}", reg));
1559 hir::InlineAsmOperand::SplitInOut { reg, late, in_expr, out_expr } => {
1560 s.word(if *late { "inlateout" } else { "inout" });
1562 s.word(format!("{}", reg));
1565 s.print_expr(in_expr);
1569 Some(out_expr) => s.print_expr(out_expr),
1570 None => s.word("_"),
1573 hir::InlineAsmOperand::Const { expr } => {
1578 hir::InlineAsmOperand::Sym { expr } => {
1584 AsmArg::Options(opts) => {
1587 let mut options = vec![];
1588 if opts.contains(ast::InlineAsmOptions::PURE) {
1589 options.push("pure");
1591 if opts.contains(ast::InlineAsmOptions::NOMEM) {
1592 options.push("nomem");
1594 if opts.contains(ast::InlineAsmOptions::READONLY) {
1595 options.push("readonly");
1597 if opts.contains(ast::InlineAsmOptions::PRESERVES_FLAGS) {
1598 options.push("preserves_flags");
1600 if opts.contains(ast::InlineAsmOptions::NORETURN) {
1601 options.push("noreturn");
1603 if opts.contains(ast::InlineAsmOptions::NOSTACK) {
1604 options.push("nostack");
1606 if opts.contains(ast::InlineAsmOptions::ATT_SYNTAX) {
1607 options.push("att_syntax");
1609 s.commasep(Inconsistent, &options, |s, &opt| {
1617 hir::ExprKind::LlvmInlineAsm(ref a) => {
1619 self.s.word("llvm_asm!");
1621 self.print_symbol(i.asm, i.asm_str_style);
1622 self.word_space(":");
1624 let mut out_idx = 0;
1625 self.commasep(Inconsistent, &i.outputs, |s, out| {
1626 let constraint = out.constraint.as_str();
1627 let mut ch = constraint.chars();
1629 Some('=') if out.is_rw => {
1630 s.print_string(&format!("+{}", ch.as_str()), ast::StrStyle::Cooked)
1632 _ => s.print_string(&constraint, ast::StrStyle::Cooked),
1635 s.print_expr(&a.outputs_exprs[out_idx]);
1640 self.word_space(":");
1643 self.commasep(Inconsistent, &i.inputs, |s, &co| {
1644 s.print_symbol(co, ast::StrStyle::Cooked);
1646 s.print_expr(&a.inputs_exprs[in_idx]);
1651 self.word_space(":");
1653 self.commasep(Inconsistent, &i.clobbers, |s, &co| {
1654 s.print_symbol(co, ast::StrStyle::Cooked);
1657 let mut options = vec![];
1659 options.push("volatile");
1662 options.push("alignstack");
1664 if i.dialect == ast::LlvmAsmDialect::Intel {
1665 options.push("intel");
1668 if !options.is_empty() {
1670 self.word_space(":");
1671 self.commasep(Inconsistent, &options, |s, &co| {
1672 s.print_string(co, ast::StrStyle::Cooked);
1678 hir::ExprKind::Yield(ref expr, _) => {
1679 self.word_space("yield");
1680 self.print_expr_maybe_paren(&expr, parser::PREC_JUMP);
1682 hir::ExprKind::Err => {
1684 self.s.word("/*ERROR*/");
1688 self.ann.post(self, AnnNode::Expr(expr));
1692 pub fn print_local_decl(&mut self, loc: &hir::Local<'_>) {
1693 self.print_pat(&loc.pat);
1694 if let Some(ref ty) = loc.ty {
1695 self.word_space(":");
1696 self.print_type(&ty);
1700 pub fn print_name(&mut self, name: Symbol) {
1701 self.print_ident(Ident::with_dummy_span(name))
1704 pub fn print_path(&mut self, path: &hir::Path<'_>, colons_before_params: bool) {
1705 self.maybe_print_comment(path.span.lo());
1707 for (i, segment) in path.segments.iter().enumerate() {
1711 if segment.ident.name != kw::PathRoot {
1712 self.print_ident(segment.ident);
1713 self.print_generic_args(segment.args(), segment.infer_args, colons_before_params);
1718 pub fn print_path_segment(&mut self, segment: &hir::PathSegment<'_>) {
1719 if segment.ident.name != kw::PathRoot {
1720 self.print_ident(segment.ident);
1721 self.print_generic_args(segment.args(), segment.infer_args, false);
1725 pub fn print_qpath(&mut self, qpath: &hir::QPath<'_>, colons_before_params: bool) {
1727 hir::QPath::Resolved(None, ref path) => self.print_path(path, colons_before_params),
1728 hir::QPath::Resolved(Some(ref qself), ref path) => {
1730 self.print_type(qself);
1732 self.word_space("as");
1734 for (i, segment) in path.segments[..path.segments.len() - 1].iter().enumerate() {
1738 if segment.ident.name != kw::PathRoot {
1739 self.print_ident(segment.ident);
1740 self.print_generic_args(
1743 colons_before_params,
1750 let item_segment = path.segments.last().unwrap();
1751 self.print_ident(item_segment.ident);
1752 self.print_generic_args(
1753 item_segment.args(),
1754 item_segment.infer_args,
1755 colons_before_params,
1758 hir::QPath::TypeRelative(ref qself, ref item_segment) => {
1759 // If we've got a compound-qualified-path, let's push an additional pair of angle
1760 // brackets, so that we pretty-print `<<A::B>::C>` as `<A::B>::C`, instead of just
1761 // `A::B::C` (since the latter could be ambiguous to the user)
1762 if let hir::TyKind::Path(hir::QPath::Resolved(None, _)) = &qself.kind {
1763 self.print_type(qself);
1766 self.print_type(qself);
1771 self.print_ident(item_segment.ident);
1772 self.print_generic_args(
1773 item_segment.args(),
1774 item_segment.infer_args,
1775 colons_before_params,
1778 hir::QPath::LangItem(lang_item, span) => {
1779 self.s.word("#[lang = \"");
1780 self.print_ident(Ident::new(lang_item.name(), span));
1786 fn print_generic_args(
1788 generic_args: &hir::GenericArgs<'_>,
1790 colons_before_params: bool,
1792 if generic_args.parenthesized {
1794 self.commasep(Inconsistent, generic_args.inputs(), |s, ty| s.print_type(&ty));
1797 self.space_if_not_bol();
1798 self.word_space("->");
1799 self.print_type(generic_args.bindings[0].ty());
1801 let start = if colons_before_params { "::<" } else { "<" };
1802 let empty = Cell::new(true);
1803 let start_or_comma = |this: &mut Self| {
1808 this.word_space(",")
1812 let mut nonelided_generic_args: bool = false;
1813 let elide_lifetimes = generic_args.args.iter().all(|arg| match arg {
1814 GenericArg::Lifetime(lt) => lt.is_elided(),
1816 nonelided_generic_args = true;
1821 if nonelided_generic_args {
1822 start_or_comma(self);
1826 |s, generic_arg| match generic_arg {
1827 GenericArg::Lifetime(lt) if !elide_lifetimes => s.print_lifetime(lt),
1828 GenericArg::Lifetime(_) => {}
1829 GenericArg::Type(ty) => s.print_type(ty),
1830 GenericArg::Const(ct) => s.print_anon_const(&ct.value),
1835 // FIXME(eddyb): this would leak into error messages (e.g.,
1836 // "non-exhaustive patterns: `Some::<..>(_)` not covered").
1837 if infer_args && false {
1838 start_or_comma(self);
1842 for binding in generic_args.bindings.iter() {
1843 start_or_comma(self);
1844 self.print_ident(binding.ident);
1845 self.print_generic_args(binding.gen_args, false, false);
1847 match generic_args.bindings[0].kind {
1848 hir::TypeBindingKind::Equality { ref ty } => {
1849 self.word_space("=");
1850 self.print_type(ty);
1852 hir::TypeBindingKind::Constraint { bounds } => {
1853 self.print_bounds(":", bounds);
1864 pub fn print_pat(&mut self, pat: &hir::Pat<'_>) {
1865 self.maybe_print_comment(pat.span.lo());
1866 self.ann.pre(self, AnnNode::Pat(pat));
1867 // Pat isn't normalized, but the beauty of it
1868 // is that it doesn't matter
1870 PatKind::Wild => self.s.word("_"),
1871 PatKind::Binding(binding_mode, _, ident, ref sub) => {
1872 match binding_mode {
1873 hir::BindingAnnotation::Ref => {
1874 self.word_nbsp("ref");
1875 self.print_mutability(hir::Mutability::Not, false);
1877 hir::BindingAnnotation::RefMut => {
1878 self.word_nbsp("ref");
1879 self.print_mutability(hir::Mutability::Mut, false);
1881 hir::BindingAnnotation::Unannotated => {}
1882 hir::BindingAnnotation::Mutable => {
1883 self.word_nbsp("mut");
1886 self.print_ident(ident);
1887 if let Some(ref p) = *sub {
1892 PatKind::TupleStruct(ref qpath, ref elts, ddpos) => {
1893 self.print_qpath(qpath, true);
1895 if let Some(ddpos) = ddpos {
1896 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p));
1898 self.word_space(",");
1901 if ddpos != elts.len() {
1903 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p));
1906 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p));
1910 PatKind::Path(ref qpath) => {
1911 self.print_qpath(qpath, true);
1913 PatKind::Struct(ref qpath, ref fields, etc) => {
1914 self.print_qpath(qpath, true);
1916 self.word_space("{");
1921 s.cbox(INDENT_UNIT);
1922 if !f.is_shorthand {
1923 s.print_ident(f.ident);
1926 s.print_pat(&f.pat);
1932 if !fields.is_empty() {
1933 self.word_space(",");
1940 PatKind::Or(ref pats) => {
1941 self.strsep("|", true, Inconsistent, &pats[..], |s, p| s.print_pat(&p));
1943 PatKind::Tuple(ref elts, ddpos) => {
1945 if let Some(ddpos) = ddpos {
1946 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p));
1948 self.word_space(",");
1951 if ddpos != elts.len() {
1953 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p));
1956 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p));
1957 if elts.len() == 1 {
1963 PatKind::Box(ref inner) => {
1964 let is_range_inner = matches!(inner.kind, PatKind::Range(..));
1965 self.s.word("box ");
1969 self.print_pat(&inner);
1974 PatKind::Ref(ref inner, mutbl) => {
1975 let is_range_inner = matches!(inner.kind, PatKind::Range(..));
1977 self.s.word(mutbl.prefix_str());
1981 self.print_pat(&inner);
1986 PatKind::Lit(ref e) => self.print_expr(&e),
1987 PatKind::Range(ref begin, ref end, ref end_kind) => {
1988 if let Some(expr) = begin {
1989 self.print_expr(expr);
1993 RangeEnd::Included => self.s.word("..."),
1994 RangeEnd::Excluded => self.s.word(".."),
1996 if let Some(expr) = end {
1997 self.print_expr(expr);
2000 PatKind::Slice(ref before, ref slice, ref after) => {
2002 self.commasep(Inconsistent, &before[..], |s, p| s.print_pat(&p));
2003 if let Some(ref p) = *slice {
2004 if !before.is_empty() {
2005 self.word_space(",");
2007 if let PatKind::Wild = p.kind {
2013 if !after.is_empty() {
2014 self.word_space(",");
2017 self.commasep(Inconsistent, &after[..], |s, p| s.print_pat(&p));
2021 self.ann.post(self, AnnNode::Pat(pat))
2024 pub fn print_param(&mut self, arg: &hir::Param<'_>) {
2025 self.print_outer_attributes(self.attrs(arg.hir_id));
2026 self.print_pat(&arg.pat);
2029 pub fn print_arm(&mut self, arm: &hir::Arm<'_>) {
2030 // I have no idea why this check is necessary, but here it
2032 if self.attrs(arm.hir_id).is_empty() {
2035 self.cbox(INDENT_UNIT);
2036 self.ann.pre(self, AnnNode::Arm(arm));
2038 self.print_outer_attributes(&self.attrs(arm.hir_id));
2039 self.print_pat(&arm.pat);
2041 if let Some(ref g) = arm.guard {
2043 hir::Guard::If(e) => {
2044 self.word_space("if");
2045 self.print_expr(&e);
2048 hir::Guard::IfLet(pat, e) => {
2049 self.word_nbsp("if");
2050 self.word_nbsp("let");
2051 self.print_pat(&pat);
2053 self.word_space("=");
2054 self.print_expr(&e);
2059 self.word_space("=>");
2061 match arm.body.kind {
2062 hir::ExprKind::Block(ref blk, opt_label) => {
2063 if let Some(label) = opt_label {
2064 self.print_ident(label.ident);
2065 self.word_space(":");
2067 // the block will close the pattern's ibox
2068 self.print_block_unclosed(&blk);
2070 // If it is a user-provided unsafe block, print a comma after it
2071 if let hir::BlockCheckMode::UnsafeBlock(hir::UnsafeSource::UserProvided) = blk.rules
2077 self.end(); // close the ibox for the pattern
2078 self.print_expr(&arm.body);
2082 self.ann.post(self, AnnNode::Arm(arm));
2083 self.end() // close enclosing cbox
2088 decl: &hir::FnDecl<'_>,
2089 header: hir::FnHeader,
2090 name: Option<Symbol>,
2091 generics: &hir::Generics<'_>,
2092 vis: &hir::Visibility<'_>,
2093 arg_names: &[Ident],
2094 body_id: Option<hir::BodyId>,
2096 self.print_fn_header_info(header, vis);
2098 if let Some(name) = name {
2100 self.print_name(name);
2102 self.print_generic_params(&generics.params);
2106 // Make sure we aren't supplied *both* `arg_names` and `body_id`.
2107 assert!(arg_names.is_empty() || body_id.is_none());
2108 self.commasep(Inconsistent, &decl.inputs, |s, ty| {
2109 s.ibox(INDENT_UNIT);
2110 if let Some(arg_name) = arg_names.get(i) {
2111 s.s.word(arg_name.to_string());
2114 } else if let Some(body_id) = body_id {
2115 s.ann.nested(s, Nested::BodyParamPat(body_id, i));
2123 if decl.c_variadic {
2124 self.s.word(", ...");
2128 self.print_fn_output(decl);
2129 self.print_where_clause(&generics.where_clause)
2132 fn print_closure_params(&mut self, decl: &hir::FnDecl<'_>, body_id: hir::BodyId) {
2135 self.commasep(Inconsistent, &decl.inputs, |s, ty| {
2136 s.ibox(INDENT_UNIT);
2138 s.ann.nested(s, Nested::BodyParamPat(body_id, i));
2141 if let hir::TyKind::Infer = ty.kind {
2152 if let hir::FnRetTy::DefaultReturn(..) = decl.output {
2156 self.space_if_not_bol();
2157 self.word_space("->");
2159 hir::FnRetTy::Return(ref ty) => {
2160 self.print_type(&ty);
2161 self.maybe_print_comment(ty.span.lo())
2163 hir::FnRetTy::DefaultReturn(..) => unreachable!(),
2167 pub fn print_capture_clause(&mut self, capture_clause: hir::CaptureBy) {
2168 match capture_clause {
2169 hir::CaptureBy::Value => self.word_space("move"),
2170 hir::CaptureBy::Ref => {}
2174 pub fn print_bounds<'b>(
2176 prefix: &'static str,
2177 bounds: impl IntoIterator<Item = &'b hir::GenericBound<'b>>,
2179 let mut first = true;
2180 for bound in bounds {
2182 self.s.word(prefix);
2184 if !(first && prefix.is_empty()) {
2190 self.word_space("+");
2194 GenericBound::Trait(tref, modifier) => {
2195 if modifier == &TraitBoundModifier::Maybe {
2198 self.print_poly_trait_ref(tref);
2200 GenericBound::LangItemTrait(lang_item, span, ..) => {
2201 self.s.word("#[lang = \"");
2202 self.print_ident(Ident::new(lang_item.name(), *span));
2205 GenericBound::Outlives(lt) => {
2206 self.print_lifetime(lt);
2212 pub fn print_generic_params(&mut self, generic_params: &[GenericParam<'_>]) {
2213 if !generic_params.is_empty() {
2216 self.commasep(Inconsistent, generic_params, |s, param| s.print_generic_param(param));
2222 pub fn print_generic_param(&mut self, param: &GenericParam<'_>) {
2223 if let GenericParamKind::Const { .. } = param.kind {
2224 self.word_space("const");
2227 self.print_ident(param.name.ident());
2230 GenericParamKind::Lifetime { .. } => {
2232 for bound in param.bounds {
2234 GenericBound::Outlives(ref lt) => {
2236 self.print_lifetime(lt);
2243 GenericParamKind::Type { ref default, .. } => {
2244 self.print_bounds(":", param.bounds);
2245 if let Some(default) = default {
2247 self.word_space("=");
2248 self.print_type(&default)
2251 GenericParamKind::Const { ref ty, ref default } => {
2252 self.word_space(":");
2253 self.print_type(ty);
2254 if let Some(ref default) = default {
2256 self.word_space("=");
2257 self.print_anon_const(&default)
2263 pub fn print_lifetime(&mut self, lifetime: &hir::Lifetime) {
2264 self.print_ident(lifetime.name.ident())
2267 pub fn print_where_clause(&mut self, where_clause: &hir::WhereClause<'_>) {
2268 if where_clause.predicates.is_empty() {
2273 self.word_space("where");
2275 for (i, predicate) in where_clause.predicates.iter().enumerate() {
2277 self.word_space(",");
2281 hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
2282 bound_generic_params,
2287 self.print_formal_generic_params(bound_generic_params);
2288 self.print_type(&bounded_ty);
2289 self.print_bounds(":", *bounds);
2291 hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
2296 self.print_lifetime(lifetime);
2299 for (i, bound) in bounds.iter().enumerate() {
2301 GenericBound::Outlives(lt) => {
2302 self.print_lifetime(lt);
2312 hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
2315 self.print_type(lhs_ty);
2317 self.word_space("=");
2318 self.print_type(rhs_ty);
2324 pub fn print_mutability(&mut self, mutbl: hir::Mutability, print_const: bool) {
2326 hir::Mutability::Mut => self.word_nbsp("mut"),
2327 hir::Mutability::Not => {
2329 self.word_nbsp("const")
2335 pub fn print_mt(&mut self, mt: &hir::MutTy<'_>, print_const: bool) {
2336 self.print_mutability(mt.mutbl, print_const);
2337 self.print_type(&mt.ty)
2340 pub fn print_fn_output(&mut self, decl: &hir::FnDecl<'_>) {
2341 if let hir::FnRetTy::DefaultReturn(..) = decl.output {
2345 self.space_if_not_bol();
2346 self.ibox(INDENT_UNIT);
2347 self.word_space("->");
2349 hir::FnRetTy::DefaultReturn(..) => unreachable!(),
2350 hir::FnRetTy::Return(ref ty) => self.print_type(&ty),
2354 if let hir::FnRetTy::Return(ref output) = decl.output {
2355 self.maybe_print_comment(output.span.lo())
2362 unsafety: hir::Unsafety,
2363 decl: &hir::FnDecl<'_>,
2364 name: Option<Symbol>,
2365 generic_params: &[hir::GenericParam<'_>],
2366 arg_names: &[Ident],
2368 self.ibox(INDENT_UNIT);
2369 if !generic_params.is_empty() {
2371 self.print_generic_params(generic_params);
2373 let generics = hir::Generics {
2375 where_clause: hir::WhereClause { predicates: &[], span: rustc_span::DUMMY_SP },
2376 span: rustc_span::DUMMY_SP,
2383 constness: hir::Constness::NotConst,
2384 asyncness: hir::IsAsync::NotAsync,
2388 &Spanned { span: rustc_span::DUMMY_SP, node: hir::VisibilityKind::Inherited },
2395 pub fn maybe_print_trailing_comment(
2397 span: rustc_span::Span,
2398 next_pos: Option<BytePos>,
2400 if let Some(cmnts) = self.comments() {
2401 if let Some(cmnt) = cmnts.trailing_comment(span, next_pos) {
2402 self.print_comment(&cmnt);
2407 pub fn print_remaining_comments(&mut self) {
2408 // If there aren't any remaining comments, then we need to manually
2409 // make sure there is a line break at the end.
2410 if self.next_comment().is_none() {
2413 while let Some(ref cmnt) = self.next_comment() {
2414 self.print_comment(cmnt)
2418 pub fn print_fn_header_info(&mut self, header: hir::FnHeader, vis: &hir::Visibility<'_>) {
2419 self.s.word(visibility_qualified(vis, ""));
2421 match header.constness {
2422 hir::Constness::NotConst => {}
2423 hir::Constness::Const => self.word_nbsp("const"),
2426 match header.asyncness {
2427 hir::IsAsync::NotAsync => {}
2428 hir::IsAsync::Async => self.word_nbsp("async"),
2431 self.print_unsafety(header.unsafety);
2433 if header.abi != Abi::Rust {
2434 self.word_nbsp("extern");
2435 self.word_nbsp(header.abi.to_string());
2441 pub fn print_unsafety(&mut self, s: hir::Unsafety) {
2443 hir::Unsafety::Normal => {}
2444 hir::Unsafety::Unsafe => self.word_nbsp("unsafe"),
2448 pub fn print_is_auto(&mut self, s: hir::IsAuto) {
2450 hir::IsAuto::Yes => self.word_nbsp("auto"),
2451 hir::IsAuto::No => {}
2456 /// Does this expression require a semicolon to be treated
2457 /// as a statement? The negation of this: 'can this expression
2458 /// be used as a statement without a semicolon' -- is used
2459 /// as an early-bail-out in the parser so that, for instance,
2460 /// if true {...} else {...}
2462 /// isn't parsed as (if true {...} else {...} | x) | 5
2464 // Duplicated from `parse::classify`, but adapted for the HIR.
2465 fn expr_requires_semi_to_be_stmt(e: &hir::Expr<'_>) -> bool {
2468 hir::ExprKind::If(..)
2469 | hir::ExprKind::Match(..)
2470 | hir::ExprKind::Block(..)
2471 | hir::ExprKind::Loop(..)
2475 /// This statement requires a semicolon after it.
2476 /// note that in one case (stmt_semi), we've already
2477 /// seen the semicolon, and thus don't need another.
2478 fn stmt_ends_with_semi(stmt: &hir::StmtKind<'_>) -> bool {
2480 hir::StmtKind::Local(_) => true,
2481 hir::StmtKind::Item(_) => false,
2482 hir::StmtKind::Expr(ref e) => expr_requires_semi_to_be_stmt(&e),
2483 hir::StmtKind::Semi(..) => false,
2487 fn bin_op_to_assoc_op(op: hir::BinOpKind) -> AssocOp {
2488 use crate::hir::BinOpKind::*;
2490 Add => AssocOp::Add,
2491 Sub => AssocOp::Subtract,
2492 Mul => AssocOp::Multiply,
2493 Div => AssocOp::Divide,
2494 Rem => AssocOp::Modulus,
2496 And => AssocOp::LAnd,
2499 BitXor => AssocOp::BitXor,
2500 BitAnd => AssocOp::BitAnd,
2501 BitOr => AssocOp::BitOr,
2502 Shl => AssocOp::ShiftLeft,
2503 Shr => AssocOp::ShiftRight,
2505 Eq => AssocOp::Equal,
2506 Lt => AssocOp::Less,
2507 Le => AssocOp::LessEqual,
2508 Ne => AssocOp::NotEqual,
2509 Ge => AssocOp::GreaterEqual,
2510 Gt => AssocOp::Greater,
2514 /// Expressions that syntactically contain an "exterior" struct literal, i.e., not surrounded by any
2515 /// parens or other delimiters, e.g., `X { y: 1 }`, `X { y: 1 }.method()`, `foo == X { y: 1 }` and
2516 /// `X { y: 1 } == foo` all do, but `(X { y: 1 }) == foo` does not.
2517 fn contains_exterior_struct_lit(value: &hir::Expr<'_>) -> bool {
2519 hir::ExprKind::Struct(..) => true,
2521 hir::ExprKind::Assign(ref lhs, ref rhs, _)
2522 | hir::ExprKind::AssignOp(_, ref lhs, ref rhs)
2523 | hir::ExprKind::Binary(_, ref lhs, ref rhs) => {
2524 // `X { y: 1 } + X { y: 2 }`
2525 contains_exterior_struct_lit(&lhs) || contains_exterior_struct_lit(&rhs)
2527 hir::ExprKind::Unary(_, ref x)
2528 | hir::ExprKind::Cast(ref x, _)
2529 | hir::ExprKind::Type(ref x, _)
2530 | hir::ExprKind::Field(ref x, _)
2531 | hir::ExprKind::Index(ref x, _) => {
2532 // `&X { y: 1 }, X { y: 1 }.y`
2533 contains_exterior_struct_lit(&x)
2536 hir::ExprKind::MethodCall(.., ref exprs, _) => {
2537 // `X { y: 1 }.bar(...)`
2538 contains_exterior_struct_lit(&exprs[0])