1 #![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 StructField"),
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 param_to_string(arg: &hir::Param<'_>) -> String {
225 to_string(NO_ANN, |s| s.print_param(arg))
228 pub fn ty_to_string(ty: &hir::Ty<'_>) -> String {
229 to_string(NO_ANN, |s| s.print_type(ty))
232 pub fn path_segment_to_string(segment: &hir::PathSegment<'_>) -> String {
233 to_string(NO_ANN, |s| s.print_path_segment(segment))
236 pub fn path_to_string(segment: &hir::Path<'_>) -> String {
237 to_string(NO_ANN, |s| s.print_path(segment, false))
241 decl: &hir::FnDecl<'_>,
242 header: hir::FnHeader,
243 name: Option<Symbol>,
244 generics: &hir::Generics<'_>,
245 vis: &hir::Visibility<'_>,
247 body_id: Option<hir::BodyId>,
249 to_string(NO_ANN, |s| s.print_fn(decl, header, name, generics, vis, arg_names, body_id))
252 pub fn enum_def_to_string(
253 enum_definition: &hir::EnumDef<'_>,
254 generics: &hir::Generics<'_>,
256 span: rustc_span::Span,
257 visibility: &hir::Visibility<'_>,
259 to_string(NO_ANN, |s| s.print_enum_def(enum_definition, generics, name, span, visibility))
263 pub fn cbox(&mut self, u: usize) {
267 pub fn nbsp(&mut self) {
271 pub fn word_nbsp<S: Into<Cow<'static, str>>>(&mut self, w: S) {
276 pub fn head<S: Into<Cow<'static, str>>>(&mut self, w: S) {
278 // outer-box is consistent
279 self.cbox(INDENT_UNIT);
280 // head-box is inconsistent
281 self.ibox(w.len() + 1);
282 // keyword that starts the head
288 pub fn bopen(&mut self) {
290 self.end(); // close the head-box
293 pub fn bclose_maybe_open(&mut self, span: rustc_span::Span, close_box: bool) {
294 self.maybe_print_comment(span.hi());
295 self.break_offset_if_not_bol(1, -(INDENT_UNIT as isize));
298 self.end(); // close the outer-box
302 pub fn bclose(&mut self, span: rustc_span::Span) {
303 self.bclose_maybe_open(span, true)
306 pub fn space_if_not_bol(&mut self) {
307 if !self.s.is_beginning_of_line() {
312 pub fn break_offset_if_not_bol(&mut self, n: usize, off: isize) {
313 if !self.s.is_beginning_of_line() {
314 self.s.break_offset(n, off)
315 } else if off != 0 && self.s.last_token().is_hardbreak_tok() {
316 // We do something pretty sketchy here: tuck the nonzero
317 // offset-adjustment we were going to deposit along with the
318 // break into the previous hardbreak.
319 self.s.replace_last_token(pp::Printer::hardbreak_tok_offset(off));
323 // Synthesizes a comment that was not textually present in the original source
325 pub fn synth_comment(&mut self, text: String) {
333 pub fn commasep_cmnt<T, F, G>(&mut self, b: Breaks, elts: &[T], mut op: F, mut get_span: G)
335 F: FnMut(&mut State<'_>, &T),
336 G: FnMut(&T) -> rustc_span::Span,
339 let len = elts.len();
342 self.maybe_print_comment(get_span(elt).hi());
347 self.maybe_print_trailing_comment(get_span(elt), Some(get_span(&elts[i]).hi()));
348 self.space_if_not_bol();
354 pub fn commasep_exprs(&mut self, b: Breaks, exprs: &[hir::Expr<'_>]) {
355 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(&e), |e| e.span)
358 pub fn print_mod(&mut self, _mod: &hir::Mod<'_>, attrs: &[ast::Attribute]) {
359 self.print_inner_attributes(attrs);
360 for &item_id in _mod.item_ids {
361 self.ann.nested(self, Nested::Item(item_id));
365 pub fn print_opt_lifetime(&mut self, lifetime: &hir::Lifetime) {
366 if !lifetime.is_elided() {
367 self.print_lifetime(lifetime);
372 pub fn print_type(&mut self, ty: &hir::Ty<'_>) {
373 self.maybe_print_comment(ty.span.lo());
376 hir::TyKind::Slice(ref ty) => {
378 self.print_type(&ty);
381 hir::TyKind::Ptr(ref mt) => {
383 self.print_mt(mt, true);
385 hir::TyKind::Rptr(ref lifetime, ref mt) => {
387 self.print_opt_lifetime(lifetime);
388 self.print_mt(mt, false);
390 hir::TyKind::Never => {
393 hir::TyKind::Tup(ref elts) => {
395 self.commasep(Inconsistent, &elts[..], |s, ty| s.print_type(&ty));
401 hir::TyKind::BareFn(ref f) => {
411 hir::TyKind::OpaqueDef(..) => self.s.word("/*impl Trait*/"),
412 hir::TyKind::Path(ref qpath) => self.print_qpath(qpath, false),
413 hir::TyKind::TraitObject(bounds, ref lifetime) => {
414 let mut first = true;
415 for bound in bounds {
420 self.word_space("+");
422 self.print_poly_trait_ref(bound);
424 if !lifetime.is_elided() {
426 self.word_space("+");
427 self.print_lifetime(lifetime);
430 hir::TyKind::Array(ref ty, ref length) => {
432 self.print_type(&ty);
434 self.print_anon_const(length);
437 hir::TyKind::Typeof(ref e) => {
438 self.s.word("typeof(");
439 self.print_anon_const(e);
442 hir::TyKind::Infer => {
445 hir::TyKind::Err => {
447 self.s.word("/*ERROR*/");
454 pub fn print_foreign_item(&mut self, item: &hir::ForeignItem<'_>) {
455 self.hardbreak_if_not_bol();
456 self.maybe_print_comment(item.span.lo());
457 self.print_outer_attributes(self.attrs(item.hir_id()));
459 hir::ForeignItemKind::Fn(ref decl, ref arg_names, ref generics) => {
464 unsafety: hir::Unsafety::Normal,
465 constness: hir::Constness::NotConst,
467 asyncness: hir::IsAsync::NotAsync,
469 Some(item.ident.name),
475 self.end(); // end head-ibox
477 self.end() // end the outer fn box
479 hir::ForeignItemKind::Static(ref t, m) => {
480 self.head(visibility_qualified(&item.vis, "static"));
481 if m == hir::Mutability::Mut {
482 self.word_space("mut");
484 self.print_ident(item.ident);
485 self.word_space(":");
488 self.end(); // end the head-ibox
489 self.end() // end the outer cbox
491 hir::ForeignItemKind::Type => {
492 self.head(visibility_qualified(&item.vis, "type"));
493 self.print_ident(item.ident);
495 self.end(); // end the head-ibox
496 self.end() // end the outer cbox
501 fn print_associated_const(
505 default: Option<hir::BodyId>,
506 vis: &hir::Visibility<'_>,
508 self.s.word(visibility_qualified(vis, ""));
509 self.word_space("const");
510 self.print_ident(ident);
511 self.word_space(":");
513 if let Some(expr) = default {
515 self.word_space("=");
516 self.ann.nested(self, Nested::Body(expr));
521 fn print_associated_type(
524 generics: &hir::Generics<'_>,
525 bounds: Option<hir::GenericBounds<'_>>,
526 ty: Option<&hir::Ty<'_>>,
528 self.word_space("type");
529 self.print_ident(ident);
530 self.print_generic_params(&generics.params);
531 if let Some(bounds) = bounds {
532 self.print_bounds(":", bounds);
534 self.print_where_clause(&generics.where_clause);
535 if let Some(ty) = ty {
537 self.word_space("=");
545 item: &hir::Item<'_>,
546 generics: &hir::Generics<'_>,
547 inner: impl Fn(&mut Self),
549 self.head(visibility_qualified(&item.vis, "type"));
550 self.print_ident(item.ident);
551 self.print_generic_params(&generics.params);
552 self.end(); // end the inner ibox
554 self.print_where_clause(&generics.where_clause);
558 self.end(); // end the outer ibox
561 /// Pretty-print an item
562 pub fn print_item(&mut self, item: &hir::Item<'_>) {
563 self.hardbreak_if_not_bol();
564 self.maybe_print_comment(item.span.lo());
565 let attrs = self.attrs(item.hir_id());
566 self.print_outer_attributes(attrs);
567 self.ann.pre(self, AnnNode::Item(item));
569 hir::ItemKind::ExternCrate(orig_name) => {
570 self.head(visibility_qualified(&item.vis, "extern crate"));
571 if let Some(orig_name) = orig_name {
572 self.print_name(orig_name);
577 self.print_ident(item.ident);
579 self.end(); // end inner head-block
580 self.end(); // end outer head-block
582 hir::ItemKind::Use(ref path, kind) => {
583 self.head(visibility_qualified(&item.vis, "use"));
584 self.print_path(path, false);
587 hir::UseKind::Single => {
588 if path.segments.last().unwrap().ident != item.ident {
590 self.word_space("as");
591 self.print_ident(item.ident);
595 hir::UseKind::Glob => self.s.word("::*;"),
596 hir::UseKind::ListStem => self.s.word("::{};"),
598 self.end(); // end inner head-block
599 self.end(); // end outer head-block
601 hir::ItemKind::Static(ref ty, m, expr) => {
602 self.head(visibility_qualified(&item.vis, "static"));
603 if m == hir::Mutability::Mut {
604 self.word_space("mut");
606 self.print_ident(item.ident);
607 self.word_space(":");
608 self.print_type(&ty);
610 self.end(); // end the head-ibox
612 self.word_space("=");
613 self.ann.nested(self, Nested::Body(expr));
615 self.end(); // end the outer cbox
617 hir::ItemKind::Const(ref ty, expr) => {
618 self.head(visibility_qualified(&item.vis, "const"));
619 self.print_ident(item.ident);
620 self.word_space(":");
621 self.print_type(&ty);
623 self.end(); // end the head-ibox
625 self.word_space("=");
626 self.ann.nested(self, Nested::Body(expr));
628 self.end(); // end the outer cbox
630 hir::ItemKind::Fn(ref sig, ref param_names, body) => {
635 Some(item.ident.name),
642 self.end(); // need to close a box
643 self.end(); // need to close a box
644 self.ann.nested(self, Nested::Body(body));
646 hir::ItemKind::Mod(ref _mod) => {
647 self.head(visibility_qualified(&item.vis, "mod"));
648 self.print_ident(item.ident);
651 self.print_mod(_mod, attrs);
652 self.bclose(item.span);
654 hir::ItemKind::ForeignMod { abi, items } => {
656 self.word_nbsp(abi.to_string());
658 self.print_inner_attributes(self.attrs(item.hir_id()));
660 self.ann.nested(self, Nested::ForeignItem(item.id));
662 self.bclose(item.span);
664 hir::ItemKind::GlobalAsm(ref ga) => {
665 self.head(visibility_qualified(&item.vis, "global asm"));
666 self.s.word(ga.asm.to_string());
669 hir::ItemKind::TyAlias(ref ty, ref generics) => {
670 self.print_item_type(item, &generics, |state| {
671 state.word_space("=");
672 state.print_type(&ty);
675 hir::ItemKind::OpaqueTy(ref opaque_ty) => {
676 self.print_item_type(item, &opaque_ty.generics, |state| {
677 let mut real_bounds = Vec::with_capacity(opaque_ty.bounds.len());
678 for b in opaque_ty.bounds.iter() {
679 if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
681 state.word_space("for ?");
682 state.print_trait_ref(&ptr.trait_ref);
687 state.print_bounds("= impl", real_bounds);
690 hir::ItemKind::Enum(ref enum_definition, ref params) => {
691 self.print_enum_def(enum_definition, params, item.ident.name, item.span, &item.vis);
693 hir::ItemKind::Struct(ref struct_def, ref generics) => {
694 self.head(visibility_qualified(&item.vis, "struct"));
695 self.print_struct(struct_def, generics, item.ident.name, item.span, true);
697 hir::ItemKind::Union(ref struct_def, ref generics) => {
698 self.head(visibility_qualified(&item.vis, "union"));
699 self.print_struct(struct_def, generics, item.ident.name, item.span, true);
701 hir::ItemKind::Impl(hir::Impl {
713 self.print_visibility(&item.vis);
714 self.print_defaultness(defaultness);
715 self.print_unsafety(unsafety);
716 self.word_nbsp("impl");
718 if !generics.params.is_empty() {
719 self.print_generic_params(&generics.params);
723 if constness == hir::Constness::Const {
724 self.word_nbsp("const");
727 if let hir::ImplPolarity::Negative(_) = polarity {
731 if let Some(ref t) = of_trait {
732 self.print_trait_ref(t);
734 self.word_space("for");
737 self.print_type(&self_ty);
738 self.print_where_clause(&generics.where_clause);
742 self.print_inner_attributes(attrs);
743 for impl_item in items {
744 self.ann.nested(self, Nested::ImplItem(impl_item.id));
746 self.bclose(item.span);
748 hir::ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, trait_items) => {
750 self.print_visibility(&item.vis);
751 self.print_is_auto(is_auto);
752 self.print_unsafety(unsafety);
753 self.word_nbsp("trait");
754 self.print_ident(item.ident);
755 self.print_generic_params(&generics.params);
756 let mut real_bounds = Vec::with_capacity(bounds.len());
757 for b in bounds.iter() {
758 if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
760 self.word_space("for ?");
761 self.print_trait_ref(&ptr.trait_ref);
766 self.print_bounds(":", real_bounds);
767 self.print_where_clause(&generics.where_clause);
770 for trait_item in trait_items {
771 self.ann.nested(self, Nested::TraitItem(trait_item.id));
773 self.bclose(item.span);
775 hir::ItemKind::TraitAlias(ref generics, ref bounds) => {
777 self.print_visibility(&item.vis);
778 self.word_nbsp("trait");
779 self.print_ident(item.ident);
780 self.print_generic_params(&generics.params);
781 let mut real_bounds = Vec::with_capacity(bounds.len());
782 // FIXME(durka) this seems to be some quite outdated syntax
783 for b in bounds.iter() {
784 if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
786 self.word_space("for ?");
787 self.print_trait_ref(&ptr.trait_ref);
793 self.print_bounds("=", real_bounds);
794 self.print_where_clause(&generics.where_clause);
798 self.ann.post(self, AnnNode::Item(item))
801 pub fn print_trait_ref(&mut self, t: &hir::TraitRef<'_>) {
802 self.print_path(&t.path, false)
805 fn print_formal_generic_params(&mut self, generic_params: &[hir::GenericParam<'_>]) {
806 if !generic_params.is_empty() {
808 self.print_generic_params(generic_params);
813 fn print_poly_trait_ref(&mut self, t: &hir::PolyTraitRef<'_>) {
814 self.print_formal_generic_params(&t.bound_generic_params);
815 self.print_trait_ref(&t.trait_ref)
818 pub fn print_enum_def(
820 enum_definition: &hir::EnumDef<'_>,
821 generics: &hir::Generics<'_>,
823 span: rustc_span::Span,
824 visibility: &hir::Visibility<'_>,
826 self.head(visibility_qualified(visibility, "enum"));
827 self.print_name(name);
828 self.print_generic_params(&generics.params);
829 self.print_where_clause(&generics.where_clause);
831 self.print_variants(&enum_definition.variants, span)
834 pub fn print_variants(&mut self, variants: &[hir::Variant<'_>], span: rustc_span::Span) {
837 self.space_if_not_bol();
838 self.maybe_print_comment(v.span.lo());
839 self.print_outer_attributes(self.attrs(v.id));
840 self.ibox(INDENT_UNIT);
841 self.print_variant(v);
844 self.maybe_print_trailing_comment(v.span, None);
849 pub fn print_visibility(&mut self, vis: &hir::Visibility<'_>) {
851 hir::VisibilityKind::Public => self.word_nbsp("pub"),
852 hir::VisibilityKind::Crate(ast::CrateSugar::JustCrate) => self.word_nbsp("crate"),
853 hir::VisibilityKind::Crate(ast::CrateSugar::PubCrate) => self.word_nbsp("pub(crate)"),
854 hir::VisibilityKind::Restricted { ref path, .. } => {
856 if path.segments.len() == 1 && path.segments[0].ident.name == kw::Super {
857 // Special case: `super` can print like `pub(super)`.
858 self.s.word("super");
860 // Everything else requires `in` at present.
861 self.word_nbsp("in");
862 self.print_path(path, false);
866 hir::VisibilityKind::Inherited => (),
870 pub fn print_defaultness(&mut self, defaultness: hir::Defaultness) {
872 hir::Defaultness::Default { .. } => self.word_nbsp("default"),
873 hir::Defaultness::Final => (),
879 struct_def: &hir::VariantData<'_>,
880 generics: &hir::Generics<'_>,
882 span: rustc_span::Span,
883 print_finalizer: bool,
885 self.print_name(name);
886 self.print_generic_params(&generics.params);
888 hir::VariantData::Tuple(..) | hir::VariantData::Unit(..) => {
889 if let hir::VariantData::Tuple(..) = struct_def {
891 self.commasep(Inconsistent, struct_def.fields(), |s, field| {
892 s.maybe_print_comment(field.span.lo());
893 s.print_outer_attributes(s.attrs(field.hir_id));
894 s.print_visibility(&field.vis);
895 s.print_type(&field.ty)
899 self.print_where_clause(&generics.where_clause);
904 self.end() // close the outer-box
906 hir::VariantData::Struct(..) => {
907 self.print_where_clause(&generics.where_clause);
910 self.hardbreak_if_not_bol();
912 for field in struct_def.fields() {
913 self.hardbreak_if_not_bol();
914 self.maybe_print_comment(field.span.lo());
915 self.print_outer_attributes(self.attrs(field.hir_id));
916 self.print_visibility(&field.vis);
917 self.print_ident(field.ident);
919 self.print_type(&field.ty);
928 pub fn print_variant(&mut self, v: &hir::Variant<'_>) {
930 let generics = hir::Generics::empty();
931 self.print_struct(&v.data, &generics, v.ident.name, v.span, false);
932 if let Some(ref d) = v.disr_expr {
934 self.word_space("=");
935 self.print_anon_const(d);
938 pub fn print_method_sig(
942 generics: &hir::Generics<'_>,
943 vis: &hir::Visibility<'_>,
945 body_id: Option<hir::BodyId>,
947 self.print_fn(&m.decl, m.header, Some(ident.name), generics, vis, arg_names, body_id)
950 pub fn print_trait_item(&mut self, ti: &hir::TraitItem<'_>) {
951 self.ann.pre(self, AnnNode::SubItem(ti.hir_id()));
952 self.hardbreak_if_not_bol();
953 self.maybe_print_comment(ti.span.lo());
954 self.print_outer_attributes(self.attrs(ti.hir_id()));
956 hir::TraitItemKind::Const(ref ty, default) => {
958 Spanned { span: rustc_span::DUMMY_SP, node: hir::VisibilityKind::Inherited };
959 self.print_associated_const(ti.ident, &ty, default, &vis);
961 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Required(ref arg_names)) => {
963 Spanned { span: rustc_span::DUMMY_SP, node: hir::VisibilityKind::Inherited };
964 self.print_method_sig(ti.ident, sig, &ti.generics, &vis, arg_names, None);
967 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Provided(body)) => {
969 Spanned { span: rustc_span::DUMMY_SP, node: hir::VisibilityKind::Inherited };
971 self.print_method_sig(ti.ident, sig, &ti.generics, &vis, &[], Some(body));
973 self.end(); // need to close a box
974 self.end(); // need to close a box
975 self.ann.nested(self, Nested::Body(body));
977 hir::TraitItemKind::Type(ref bounds, ref default) => {
978 self.print_associated_type(
982 default.as_ref().map(|ty| &**ty),
986 self.ann.post(self, AnnNode::SubItem(ti.hir_id()))
989 pub fn print_impl_item(&mut self, ii: &hir::ImplItem<'_>) {
990 self.ann.pre(self, AnnNode::SubItem(ii.hir_id()));
991 self.hardbreak_if_not_bol();
992 self.maybe_print_comment(ii.span.lo());
993 self.print_outer_attributes(self.attrs(ii.hir_id()));
994 self.print_defaultness(ii.defaultness);
997 hir::ImplItemKind::Const(ref ty, expr) => {
998 self.print_associated_const(ii.ident, &ty, Some(expr), &ii.vis);
1000 hir::ImplItemKind::Fn(ref sig, body) => {
1002 self.print_method_sig(ii.ident, sig, &ii.generics, &ii.vis, &[], Some(body));
1004 self.end(); // need to close a box
1005 self.end(); // need to close a box
1006 self.ann.nested(self, Nested::Body(body));
1008 hir::ImplItemKind::TyAlias(ref ty) => {
1009 self.print_associated_type(ii.ident, &ii.generics, None, Some(ty));
1012 self.ann.post(self, AnnNode::SubItem(ii.hir_id()))
1015 pub fn print_local(&mut self, init: Option<&hir::Expr<'_>>, decl: impl Fn(&mut Self)) {
1016 self.space_if_not_bol();
1017 self.ibox(INDENT_UNIT);
1018 self.word_nbsp("let");
1020 self.ibox(INDENT_UNIT);
1024 if let Some(ref init) = init {
1026 self.word_space("=");
1027 self.print_expr(&init);
1032 pub fn print_stmt(&mut self, st: &hir::Stmt<'_>) {
1033 self.maybe_print_comment(st.span.lo());
1035 hir::StmtKind::Local(ref loc) => {
1036 self.print_local(loc.init.as_deref(), |this| this.print_local_decl(&loc));
1038 hir::StmtKind::Item(item) => self.ann.nested(self, Nested::Item(item)),
1039 hir::StmtKind::Expr(ref expr) => {
1040 self.space_if_not_bol();
1041 self.print_expr(&expr);
1043 hir::StmtKind::Semi(ref expr) => {
1044 self.space_if_not_bol();
1045 self.print_expr(&expr);
1049 if stmt_ends_with_semi(&st.kind) {
1052 self.maybe_print_trailing_comment(st.span, None)
1055 pub fn print_block(&mut self, blk: &hir::Block<'_>) {
1056 self.print_block_with_attrs(blk, &[])
1059 pub fn print_block_unclosed(&mut self, blk: &hir::Block<'_>) {
1060 self.print_block_maybe_unclosed(blk, &[], false)
1063 pub fn print_block_with_attrs(&mut self, blk: &hir::Block<'_>, attrs: &[ast::Attribute]) {
1064 self.print_block_maybe_unclosed(blk, attrs, true)
1067 pub fn print_block_maybe_unclosed(
1069 blk: &hir::Block<'_>,
1070 attrs: &[ast::Attribute],
1074 hir::BlockCheckMode::UnsafeBlock(..) => self.word_space("unsafe"),
1075 hir::BlockCheckMode::PushUnsafeBlock(..) => self.word_space("push_unsafe"),
1076 hir::BlockCheckMode::PopUnsafeBlock(..) => self.word_space("pop_unsafe"),
1077 hir::BlockCheckMode::DefaultBlock => (),
1079 self.maybe_print_comment(blk.span.lo());
1080 self.ann.pre(self, AnnNode::Block(blk));
1083 self.print_inner_attributes(attrs);
1085 for st in blk.stmts {
1086 self.print_stmt(st);
1088 if let Some(ref expr) = blk.expr {
1089 self.space_if_not_bol();
1090 self.print_expr(&expr);
1091 self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi()));
1093 self.bclose_maybe_open(blk.span, close_box);
1094 self.ann.post(self, AnnNode::Block(blk))
1097 fn print_else(&mut self, els: Option<&hir::Expr<'_>>) {
1101 // "another else-if"
1102 hir::ExprKind::If(ref i, ref then, ref e) => {
1103 self.cbox(INDENT_UNIT - 1);
1105 self.s.word(" else if ");
1106 self.print_expr_as_cond(&i);
1108 self.print_expr(&then);
1109 self.print_else(e.as_ref().map(|e| &**e))
1112 hir::ExprKind::Block(ref b, _) => {
1113 self.cbox(INDENT_UNIT - 1);
1115 self.s.word(" else ");
1116 self.print_block(&b)
1118 // BLEAH, constraints would be great here
1120 panic!("print_if saw if with weird alternative");
1130 test: &hir::Expr<'_>,
1131 blk: &hir::Expr<'_>,
1132 elseopt: Option<&hir::Expr<'_>>,
1135 self.print_expr_as_cond(test);
1137 self.print_expr(blk);
1138 self.print_else(elseopt)
1141 pub fn print_anon_const(&mut self, constant: &hir::AnonConst) {
1142 self.ann.nested(self, Nested::Body(constant.body))
1145 fn print_call_post(&mut self, args: &[hir::Expr<'_>]) {
1147 self.commasep_exprs(Inconsistent, args);
1151 pub fn print_expr_maybe_paren(&mut self, expr: &hir::Expr<'_>, prec: i8) {
1152 let needs_par = expr.precedence().order() < prec;
1156 self.print_expr(expr);
1162 /// Print an expr using syntax that's acceptable in a condition position, such as the `cond` in
1163 /// `if cond { ... }`.
1164 pub fn print_expr_as_cond(&mut self, expr: &hir::Expr<'_>) {
1165 let needs_par = match expr.kind {
1166 // These cases need parens due to the parse error observed in #26461: `if return {}`
1167 // parses as the erroneous construct `if (return {})`, not `if (return) {}`.
1168 hir::ExprKind::Closure(..) | hir::ExprKind::Ret(..) | hir::ExprKind::Break(..) => true,
1170 _ => contains_exterior_struct_lit(expr),
1176 self.print_expr(expr);
1182 fn print_expr_vec(&mut self, exprs: &[hir::Expr<'_>]) {
1183 self.ibox(INDENT_UNIT);
1185 self.commasep_exprs(Inconsistent, exprs);
1190 fn print_expr_anon_const(&mut self, anon_const: &hir::AnonConst) {
1191 self.ibox(INDENT_UNIT);
1192 self.s.word_space("const");
1193 self.print_anon_const(anon_const);
1197 fn print_expr_repeat(&mut self, element: &hir::Expr<'_>, count: &hir::AnonConst) {
1198 self.ibox(INDENT_UNIT);
1200 self.print_expr(element);
1201 self.word_space(";");
1202 self.print_anon_const(count);
1207 fn print_expr_struct(
1209 qpath: &hir::QPath<'_>,
1210 fields: &[hir::Field<'_>],
1211 wth: &Option<&hir::Expr<'_>>,
1213 self.print_qpath(qpath, true);
1219 s.ibox(INDENT_UNIT);
1220 if !field.is_shorthand {
1221 s.print_ident(field.ident);
1224 s.print_expr(&field.expr);
1231 self.ibox(INDENT_UNIT);
1232 if !fields.is_empty() {
1237 self.print_expr(&expr);
1241 if !fields.is_empty() {
1249 fn print_expr_tup(&mut self, exprs: &[hir::Expr<'_>]) {
1251 self.commasep_exprs(Inconsistent, exprs);
1252 if exprs.len() == 1 {
1258 fn print_expr_call(&mut self, func: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
1259 let prec = match func.kind {
1260 hir::ExprKind::Field(..) => parser::PREC_FORCE_PAREN,
1261 _ => parser::PREC_POSTFIX,
1264 self.print_expr_maybe_paren(func, prec);
1265 self.print_call_post(args)
1268 fn print_expr_method_call(&mut self, segment: &hir::PathSegment<'_>, args: &[hir::Expr<'_>]) {
1269 let base_args = &args[1..];
1270 self.print_expr_maybe_paren(&args[0], parser::PREC_POSTFIX);
1272 self.print_ident(segment.ident);
1274 let generic_args = segment.args();
1275 if !generic_args.args.is_empty() || !generic_args.bindings.is_empty() {
1276 self.print_generic_args(generic_args, segment.infer_args, true);
1279 self.print_call_post(base_args)
1282 fn print_expr_binary(&mut self, op: hir::BinOp, lhs: &hir::Expr<'_>, rhs: &hir::Expr<'_>) {
1283 let assoc_op = bin_op_to_assoc_op(op.node);
1284 let prec = assoc_op.precedence() as i8;
1285 let fixity = assoc_op.fixity();
1287 let (left_prec, right_prec) = match fixity {
1288 Fixity::Left => (prec, prec + 1),
1289 Fixity::Right => (prec + 1, prec),
1290 Fixity::None => (prec + 1, prec + 1),
1293 let left_prec = match (&lhs.kind, op.node) {
1294 // These cases need parens: `x as i32 < y` has the parser thinking that `i32 < y` is
1295 // the beginning of a path type. It starts trying to parse `x as (i32 < y ...` instead
1296 // of `(x as i32) < ...`. We need to convince it _not_ to do that.
1297 (&hir::ExprKind::Cast { .. }, hir::BinOpKind::Lt | hir::BinOpKind::Shl) => {
1298 parser::PREC_FORCE_PAREN
1303 self.print_expr_maybe_paren(lhs, left_prec);
1305 self.word_space(op.node.as_str());
1306 self.print_expr_maybe_paren(rhs, right_prec)
1309 fn print_expr_unary(&mut self, op: hir::UnOp, expr: &hir::Expr<'_>) {
1310 self.s.word(op.as_str());
1311 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1314 fn print_expr_addr_of(
1316 kind: hir::BorrowKind,
1317 mutability: hir::Mutability,
1318 expr: &hir::Expr<'_>,
1322 hir::BorrowKind::Ref => self.print_mutability(mutability, false),
1323 hir::BorrowKind::Raw => {
1324 self.word_nbsp("raw");
1325 self.print_mutability(mutability, true);
1328 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1331 fn print_literal(&mut self, lit: &hir::Lit) {
1332 self.maybe_print_comment(lit.span.lo());
1333 self.word(lit.node.to_lit_token().to_string())
1336 pub fn print_expr(&mut self, expr: &hir::Expr<'_>) {
1337 self.maybe_print_comment(expr.span.lo());
1338 self.print_outer_attributes(self.attrs(expr.hir_id));
1339 self.ibox(INDENT_UNIT);
1340 self.ann.pre(self, AnnNode::Expr(expr));
1342 hir::ExprKind::Box(ref expr) => {
1343 self.word_space("box");
1344 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX);
1346 hir::ExprKind::Array(ref exprs) => {
1347 self.print_expr_vec(exprs);
1349 hir::ExprKind::ConstBlock(ref anon_const) => {
1350 self.print_expr_anon_const(anon_const);
1352 hir::ExprKind::Repeat(ref element, ref count) => {
1353 self.print_expr_repeat(&element, count);
1355 hir::ExprKind::Struct(ref qpath, fields, ref wth) => {
1356 self.print_expr_struct(qpath, fields, wth);
1358 hir::ExprKind::Tup(ref exprs) => {
1359 self.print_expr_tup(exprs);
1361 hir::ExprKind::Call(ref func, ref args) => {
1362 self.print_expr_call(&func, args);
1364 hir::ExprKind::MethodCall(ref segment, _, ref args, _) => {
1365 self.print_expr_method_call(segment, args);
1367 hir::ExprKind::Binary(op, ref lhs, ref rhs) => {
1368 self.print_expr_binary(op, &lhs, &rhs);
1370 hir::ExprKind::Unary(op, ref expr) => {
1371 self.print_expr_unary(op, &expr);
1373 hir::ExprKind::AddrOf(k, m, ref expr) => {
1374 self.print_expr_addr_of(k, m, &expr);
1376 hir::ExprKind::Lit(ref lit) => {
1377 self.print_literal(&lit);
1379 hir::ExprKind::Cast(ref expr, ref ty) => {
1380 let prec = AssocOp::As.precedence() as i8;
1381 self.print_expr_maybe_paren(&expr, prec);
1383 self.word_space("as");
1384 self.print_type(&ty);
1386 hir::ExprKind::Type(ref expr, ref ty) => {
1387 let prec = AssocOp::Colon.precedence() as i8;
1388 self.print_expr_maybe_paren(&expr, prec);
1389 self.word_space(":");
1390 self.print_type(&ty);
1392 hir::ExprKind::DropTemps(ref init) => {
1394 self.cbox(INDENT_UNIT);
1398 // Print `let _t = $init;`:
1399 let temp = Ident::from_str("_t");
1400 self.print_local(Some(init), |this| this.print_ident(temp));
1404 self.space_if_not_bol();
1405 self.print_ident(temp);
1408 self.bclose_maybe_open(expr.span, true);
1410 hir::ExprKind::If(ref test, ref blk, ref elseopt) => {
1411 self.print_if(&test, &blk, elseopt.as_ref().map(|e| &**e));
1413 hir::ExprKind::Loop(ref blk, opt_label, _, _) => {
1414 if let Some(label) = opt_label {
1415 self.print_ident(label.ident);
1416 self.word_space(":");
1420 self.print_block(&blk);
1422 hir::ExprKind::Match(ref expr, arms, _) => {
1423 self.cbox(INDENT_UNIT);
1424 self.ibox(INDENT_UNIT);
1425 self.word_nbsp("match");
1426 self.print_expr_as_cond(&expr);
1430 self.print_arm(arm);
1432 self.bclose(expr.span);
1434 hir::ExprKind::Closure(capture_clause, ref decl, body, _fn_decl_span, _gen) => {
1435 self.print_capture_clause(capture_clause);
1437 self.print_closure_params(&decl, body);
1440 // This is a bare expression.
1441 self.ann.nested(self, Nested::Body(body));
1442 self.end(); // need to close a box
1444 // A box will be closed by `print_expr`, but we didn't want an overall
1445 // wrapper so we closed the corresponding opening. so create an
1446 // empty box to satisfy the close.
1449 hir::ExprKind::Block(ref blk, opt_label) => {
1450 if let Some(label) = opt_label {
1451 self.print_ident(label.ident);
1452 self.word_space(":");
1454 // containing cbox, will be closed by print-block at `}`
1455 self.cbox(INDENT_UNIT);
1456 // head-box, will be closed by print-block after `{`
1458 self.print_block(&blk);
1460 hir::ExprKind::Assign(ref lhs, ref rhs, _) => {
1461 let prec = AssocOp::Assign.precedence() as i8;
1462 self.print_expr_maybe_paren(&lhs, prec + 1);
1464 self.word_space("=");
1465 self.print_expr_maybe_paren(&rhs, prec);
1467 hir::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
1468 let prec = AssocOp::Assign.precedence() as i8;
1469 self.print_expr_maybe_paren(&lhs, prec + 1);
1471 self.s.word(op.node.as_str());
1472 self.word_space("=");
1473 self.print_expr_maybe_paren(&rhs, prec);
1475 hir::ExprKind::Field(ref expr, ident) => {
1476 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
1478 self.print_ident(ident);
1480 hir::ExprKind::Index(ref expr, ref index) => {
1481 self.print_expr_maybe_paren(&expr, parser::PREC_POSTFIX);
1483 self.print_expr(&index);
1486 hir::ExprKind::Path(ref qpath) => self.print_qpath(qpath, true),
1487 hir::ExprKind::Break(destination, ref opt_expr) => {
1488 self.s.word("break");
1490 if let Some(label) = destination.label {
1491 self.print_ident(label.ident);
1494 if let Some(ref expr) = *opt_expr {
1495 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
1499 hir::ExprKind::Continue(destination) => {
1500 self.s.word("continue");
1502 if let Some(label) = destination.label {
1503 self.print_ident(label.ident);
1507 hir::ExprKind::Ret(ref result) => {
1508 self.s.word("return");
1509 if let Some(ref expr) = *result {
1511 self.print_expr_maybe_paren(&expr, parser::PREC_JUMP);
1514 hir::ExprKind::InlineAsm(ref a) => {
1517 Operand(&'a hir::InlineAsmOperand<'a>),
1518 Options(ast::InlineAsmOptions),
1521 let mut args = vec![];
1522 args.push(AsmArg::Template(ast::InlineAsmTemplatePiece::to_string(&a.template)));
1523 args.extend(a.operands.iter().map(|(o, _)| AsmArg::Operand(o)));
1524 if !a.options.is_empty() {
1525 args.push(AsmArg::Options(a.options));
1530 self.commasep(Consistent, &args, |s, arg| match arg {
1531 AsmArg::Template(template) => s.print_string(&template, ast::StrStyle::Cooked),
1532 AsmArg::Operand(op) => match op {
1533 hir::InlineAsmOperand::In { reg, expr } => {
1536 s.word(format!("{}", reg));
1541 hir::InlineAsmOperand::Out { reg, late, expr } => {
1542 s.word(if *late { "lateout" } else { "out" });
1544 s.word(format!("{}", reg));
1548 Some(expr) => s.print_expr(expr),
1549 None => s.word("_"),
1552 hir::InlineAsmOperand::InOut { reg, late, expr } => {
1553 s.word(if *late { "inlateout" } else { "inout" });
1555 s.word(format!("{}", reg));
1560 hir::InlineAsmOperand::SplitInOut { reg, late, in_expr, out_expr } => {
1561 s.word(if *late { "inlateout" } else { "inout" });
1563 s.word(format!("{}", reg));
1566 s.print_expr(in_expr);
1570 Some(out_expr) => s.print_expr(out_expr),
1571 None => s.word("_"),
1574 hir::InlineAsmOperand::Const { expr } => {
1579 hir::InlineAsmOperand::Sym { expr } => {
1585 AsmArg::Options(opts) => {
1588 let mut options = vec![];
1589 if opts.contains(ast::InlineAsmOptions::PURE) {
1590 options.push("pure");
1592 if opts.contains(ast::InlineAsmOptions::NOMEM) {
1593 options.push("nomem");
1595 if opts.contains(ast::InlineAsmOptions::READONLY) {
1596 options.push("readonly");
1598 if opts.contains(ast::InlineAsmOptions::PRESERVES_FLAGS) {
1599 options.push("preserves_flags");
1601 if opts.contains(ast::InlineAsmOptions::NORETURN) {
1602 options.push("noreturn");
1604 if opts.contains(ast::InlineAsmOptions::NOSTACK) {
1605 options.push("nostack");
1607 if opts.contains(ast::InlineAsmOptions::ATT_SYNTAX) {
1608 options.push("att_syntax");
1610 s.commasep(Inconsistent, &options, |s, &opt| {
1618 hir::ExprKind::LlvmInlineAsm(ref a) => {
1620 self.s.word("llvm_asm!");
1622 self.print_symbol(i.asm, i.asm_str_style);
1623 self.word_space(":");
1625 let mut out_idx = 0;
1626 self.commasep(Inconsistent, &i.outputs, |s, out| {
1627 let constraint = out.constraint.as_str();
1628 let mut ch = constraint.chars();
1630 Some('=') if out.is_rw => {
1631 s.print_string(&format!("+{}", ch.as_str()), ast::StrStyle::Cooked)
1633 _ => s.print_string(&constraint, ast::StrStyle::Cooked),
1636 s.print_expr(&a.outputs_exprs[out_idx]);
1641 self.word_space(":");
1644 self.commasep(Inconsistent, &i.inputs, |s, &co| {
1645 s.print_symbol(co, ast::StrStyle::Cooked);
1647 s.print_expr(&a.inputs_exprs[in_idx]);
1652 self.word_space(":");
1654 self.commasep(Inconsistent, &i.clobbers, |s, &co| {
1655 s.print_symbol(co, ast::StrStyle::Cooked);
1658 let mut options = vec![];
1660 options.push("volatile");
1663 options.push("alignstack");
1665 if i.dialect == ast::LlvmAsmDialect::Intel {
1666 options.push("intel");
1669 if !options.is_empty() {
1671 self.word_space(":");
1672 self.commasep(Inconsistent, &options, |s, &co| {
1673 s.print_string(co, ast::StrStyle::Cooked);
1679 hir::ExprKind::Yield(ref expr, _) => {
1680 self.word_space("yield");
1681 self.print_expr_maybe_paren(&expr, parser::PREC_JUMP);
1683 hir::ExprKind::Err => {
1685 self.s.word("/*ERROR*/");
1689 self.ann.post(self, AnnNode::Expr(expr));
1693 pub fn print_local_decl(&mut self, loc: &hir::Local<'_>) {
1694 self.print_pat(&loc.pat);
1695 if let Some(ref ty) = loc.ty {
1696 self.word_space(":");
1697 self.print_type(&ty);
1701 pub fn print_usize(&mut self, i: usize) {
1702 self.s.word(i.to_string())
1705 pub fn print_name(&mut self, name: Symbol) {
1706 self.print_ident(Ident::with_dummy_span(name))
1709 pub fn print_for_decl(&mut self, loc: &hir::Local<'_>, coll: &hir::Expr<'_>) {
1710 self.print_local_decl(loc);
1712 self.word_space("in");
1713 self.print_expr(coll)
1716 pub fn print_path(&mut self, path: &hir::Path<'_>, colons_before_params: bool) {
1717 self.maybe_print_comment(path.span.lo());
1719 for (i, segment) in path.segments.iter().enumerate() {
1723 if segment.ident.name != kw::PathRoot {
1724 self.print_ident(segment.ident);
1725 self.print_generic_args(segment.args(), segment.infer_args, colons_before_params);
1730 pub fn print_path_segment(&mut self, segment: &hir::PathSegment<'_>) {
1731 if segment.ident.name != kw::PathRoot {
1732 self.print_ident(segment.ident);
1733 self.print_generic_args(segment.args(), segment.infer_args, false);
1737 pub fn print_qpath(&mut self, qpath: &hir::QPath<'_>, colons_before_params: bool) {
1739 hir::QPath::Resolved(None, ref path) => self.print_path(path, colons_before_params),
1740 hir::QPath::Resolved(Some(ref qself), ref path) => {
1742 self.print_type(qself);
1744 self.word_space("as");
1746 for (i, segment) in path.segments[..path.segments.len() - 1].iter().enumerate() {
1750 if segment.ident.name != kw::PathRoot {
1751 self.print_ident(segment.ident);
1752 self.print_generic_args(
1755 colons_before_params,
1762 let item_segment = path.segments.last().unwrap();
1763 self.print_ident(item_segment.ident);
1764 self.print_generic_args(
1765 item_segment.args(),
1766 item_segment.infer_args,
1767 colons_before_params,
1770 hir::QPath::TypeRelative(ref qself, ref item_segment) => {
1771 // If we've got a compound-qualified-path, let's push an additional pair of angle
1772 // brackets, so that we pretty-print `<<A::B>::C>` as `<A::B>::C`, instead of just
1773 // `A::B::C` (since the latter could be ambiguous to the user)
1774 if let hir::TyKind::Path(hir::QPath::Resolved(None, _)) = &qself.kind {
1775 self.print_type(qself);
1778 self.print_type(qself);
1783 self.print_ident(item_segment.ident);
1784 self.print_generic_args(
1785 item_segment.args(),
1786 item_segment.infer_args,
1787 colons_before_params,
1790 hir::QPath::LangItem(lang_item, span) => {
1791 self.s.word("#[lang = \"");
1792 self.print_ident(Ident::new(lang_item.name(), span));
1798 fn print_generic_args(
1800 generic_args: &hir::GenericArgs<'_>,
1802 colons_before_params: bool,
1804 if generic_args.parenthesized {
1806 self.commasep(Inconsistent, generic_args.inputs(), |s, ty| s.print_type(&ty));
1809 self.space_if_not_bol();
1810 self.word_space("->");
1811 self.print_type(generic_args.bindings[0].ty());
1813 let start = if colons_before_params { "::<" } else { "<" };
1814 let empty = Cell::new(true);
1815 let start_or_comma = |this: &mut Self| {
1820 this.word_space(",")
1824 let mut nonelided_generic_args: bool = false;
1825 let elide_lifetimes = generic_args.args.iter().all(|arg| match arg {
1826 GenericArg::Lifetime(lt) => lt.is_elided(),
1828 nonelided_generic_args = true;
1833 if nonelided_generic_args {
1834 start_or_comma(self);
1838 |s, generic_arg| match generic_arg {
1839 GenericArg::Lifetime(lt) if !elide_lifetimes => s.print_lifetime(lt),
1840 GenericArg::Lifetime(_) => {}
1841 GenericArg::Type(ty) => s.print_type(ty),
1842 GenericArg::Const(ct) => s.print_anon_const(&ct.value),
1847 // FIXME(eddyb): this would leak into error messages (e.g.,
1848 // "non-exhaustive patterns: `Some::<..>(_)` not covered").
1849 if infer_args && false {
1850 start_or_comma(self);
1854 for binding in generic_args.bindings.iter() {
1855 start_or_comma(self);
1856 self.print_ident(binding.ident);
1857 self.print_generic_args(binding.gen_args, false, false);
1859 match generic_args.bindings[0].kind {
1860 hir::TypeBindingKind::Equality { ref ty } => {
1861 self.word_space("=");
1862 self.print_type(ty);
1864 hir::TypeBindingKind::Constraint { bounds } => {
1865 self.print_bounds(":", bounds);
1876 pub fn print_pat(&mut self, pat: &hir::Pat<'_>) {
1877 self.maybe_print_comment(pat.span.lo());
1878 self.ann.pre(self, AnnNode::Pat(pat));
1879 // Pat isn't normalized, but the beauty of it
1880 // is that it doesn't matter
1882 PatKind::Wild => self.s.word("_"),
1883 PatKind::Binding(binding_mode, _, ident, ref sub) => {
1884 match binding_mode {
1885 hir::BindingAnnotation::Ref => {
1886 self.word_nbsp("ref");
1887 self.print_mutability(hir::Mutability::Not, false);
1889 hir::BindingAnnotation::RefMut => {
1890 self.word_nbsp("ref");
1891 self.print_mutability(hir::Mutability::Mut, false);
1893 hir::BindingAnnotation::Unannotated => {}
1894 hir::BindingAnnotation::Mutable => {
1895 self.word_nbsp("mut");
1898 self.print_ident(ident);
1899 if let Some(ref p) = *sub {
1904 PatKind::TupleStruct(ref qpath, ref elts, ddpos) => {
1905 self.print_qpath(qpath, true);
1907 if let Some(ddpos) = ddpos {
1908 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p));
1910 self.word_space(",");
1913 if ddpos != elts.len() {
1915 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p));
1918 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p));
1922 PatKind::Path(ref qpath) => {
1923 self.print_qpath(qpath, true);
1925 PatKind::Struct(ref qpath, ref fields, etc) => {
1926 self.print_qpath(qpath, true);
1928 self.word_space("{");
1933 s.cbox(INDENT_UNIT);
1934 if !f.is_shorthand {
1935 s.print_ident(f.ident);
1938 s.print_pat(&f.pat);
1944 if !fields.is_empty() {
1945 self.word_space(",");
1952 PatKind::Or(ref pats) => {
1953 self.strsep("|", true, Inconsistent, &pats[..], |s, p| s.print_pat(&p));
1955 PatKind::Tuple(ref elts, ddpos) => {
1957 if let Some(ddpos) = ddpos {
1958 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p));
1960 self.word_space(",");
1963 if ddpos != elts.len() {
1965 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p));
1968 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p));
1969 if elts.len() == 1 {
1975 PatKind::Box(ref inner) => {
1976 let is_range_inner = matches!(inner.kind, PatKind::Range(..));
1977 self.s.word("box ");
1981 self.print_pat(&inner);
1986 PatKind::Ref(ref inner, mutbl) => {
1987 let is_range_inner = matches!(inner.kind, PatKind::Range(..));
1989 self.s.word(mutbl.prefix_str());
1993 self.print_pat(&inner);
1998 PatKind::Lit(ref e) => self.print_expr(&e),
1999 PatKind::Range(ref begin, ref end, ref end_kind) => {
2000 if let Some(expr) = begin {
2001 self.print_expr(expr);
2005 RangeEnd::Included => self.s.word("..."),
2006 RangeEnd::Excluded => self.s.word(".."),
2008 if let Some(expr) = end {
2009 self.print_expr(expr);
2012 PatKind::Slice(ref before, ref slice, ref after) => {
2014 self.commasep(Inconsistent, &before[..], |s, p| s.print_pat(&p));
2015 if let Some(ref p) = *slice {
2016 if !before.is_empty() {
2017 self.word_space(",");
2019 if let PatKind::Wild = p.kind {
2025 if !after.is_empty() {
2026 self.word_space(",");
2029 self.commasep(Inconsistent, &after[..], |s, p| s.print_pat(&p));
2033 self.ann.post(self, AnnNode::Pat(pat))
2036 pub fn print_param(&mut self, arg: &hir::Param<'_>) {
2037 self.print_outer_attributes(self.attrs(arg.hir_id));
2038 self.print_pat(&arg.pat);
2041 pub fn print_arm(&mut self, arm: &hir::Arm<'_>) {
2042 // I have no idea why this check is necessary, but here it
2044 if self.attrs(arm.hir_id).is_empty() {
2047 self.cbox(INDENT_UNIT);
2048 self.ann.pre(self, AnnNode::Arm(arm));
2050 self.print_outer_attributes(&self.attrs(arm.hir_id));
2051 self.print_pat(&arm.pat);
2053 if let Some(ref g) = arm.guard {
2055 hir::Guard::If(e) => {
2056 self.word_space("if");
2057 self.print_expr(&e);
2060 hir::Guard::IfLet(pat, e) => {
2061 self.word_nbsp("if");
2062 self.word_nbsp("let");
2063 self.print_pat(&pat);
2065 self.word_space("=");
2066 self.print_expr(&e);
2071 self.word_space("=>");
2073 match arm.body.kind {
2074 hir::ExprKind::Block(ref blk, opt_label) => {
2075 if let Some(label) = opt_label {
2076 self.print_ident(label.ident);
2077 self.word_space(":");
2079 // the block will close the pattern's ibox
2080 self.print_block_unclosed(&blk);
2082 // If it is a user-provided unsafe block, print a comma after it
2083 if let hir::BlockCheckMode::UnsafeBlock(hir::UnsafeSource::UserProvided) = blk.rules
2089 self.end(); // close the ibox for the pattern
2090 self.print_expr(&arm.body);
2094 self.ann.post(self, AnnNode::Arm(arm));
2095 self.end() // close enclosing cbox
2100 decl: &hir::FnDecl<'_>,
2101 header: hir::FnHeader,
2102 name: Option<Symbol>,
2103 generics: &hir::Generics<'_>,
2104 vis: &hir::Visibility<'_>,
2105 arg_names: &[Ident],
2106 body_id: Option<hir::BodyId>,
2108 self.print_fn_header_info(header, vis);
2110 if let Some(name) = name {
2112 self.print_name(name);
2114 self.print_generic_params(&generics.params);
2118 // Make sure we aren't supplied *both* `arg_names` and `body_id`.
2119 assert!(arg_names.is_empty() || body_id.is_none());
2120 self.commasep(Inconsistent, &decl.inputs, |s, ty| {
2121 s.ibox(INDENT_UNIT);
2122 if let Some(arg_name) = arg_names.get(i) {
2123 s.s.word(arg_name.to_string());
2126 } else if let Some(body_id) = body_id {
2127 s.ann.nested(s, Nested::BodyParamPat(body_id, i));
2135 if decl.c_variadic {
2136 self.s.word(", ...");
2140 self.print_fn_output(decl);
2141 self.print_where_clause(&generics.where_clause)
2144 fn print_closure_params(&mut self, decl: &hir::FnDecl<'_>, body_id: hir::BodyId) {
2147 self.commasep(Inconsistent, &decl.inputs, |s, ty| {
2148 s.ibox(INDENT_UNIT);
2150 s.ann.nested(s, Nested::BodyParamPat(body_id, i));
2153 if let hir::TyKind::Infer = ty.kind {
2164 if let hir::FnRetTy::DefaultReturn(..) = decl.output {
2168 self.space_if_not_bol();
2169 self.word_space("->");
2171 hir::FnRetTy::Return(ref ty) => {
2172 self.print_type(&ty);
2173 self.maybe_print_comment(ty.span.lo())
2175 hir::FnRetTy::DefaultReturn(..) => unreachable!(),
2179 pub fn print_capture_clause(&mut self, capture_clause: hir::CaptureBy) {
2180 match capture_clause {
2181 hir::CaptureBy::Value => self.word_space("move"),
2182 hir::CaptureBy::Ref => {}
2186 pub fn print_bounds<'b>(
2188 prefix: &'static str,
2189 bounds: impl IntoIterator<Item = &'b hir::GenericBound<'b>>,
2191 let mut first = true;
2192 for bound in bounds {
2194 self.s.word(prefix);
2196 if !(first && prefix.is_empty()) {
2202 self.word_space("+");
2206 GenericBound::Trait(tref, modifier) => {
2207 if modifier == &TraitBoundModifier::Maybe {
2210 self.print_poly_trait_ref(tref);
2212 GenericBound::LangItemTrait(lang_item, span, ..) => {
2213 self.s.word("#[lang = \"");
2214 self.print_ident(Ident::new(lang_item.name(), *span));
2217 GenericBound::Outlives(lt) => {
2218 self.print_lifetime(lt);
2224 pub fn print_generic_params(&mut self, generic_params: &[GenericParam<'_>]) {
2225 if !generic_params.is_empty() {
2228 self.commasep(Inconsistent, generic_params, |s, param| s.print_generic_param(param));
2234 pub fn print_generic_param(&mut self, param: &GenericParam<'_>) {
2235 if let GenericParamKind::Const { .. } = param.kind {
2236 self.word_space("const");
2239 self.print_ident(param.name.ident());
2242 GenericParamKind::Lifetime { .. } => {
2244 for bound in param.bounds {
2246 GenericBound::Outlives(ref lt) => {
2248 self.print_lifetime(lt);
2255 GenericParamKind::Type { ref default, .. } => {
2256 self.print_bounds(":", param.bounds);
2257 if let Some(default) = default {
2259 self.word_space("=");
2260 self.print_type(&default)
2263 GenericParamKind::Const { ref ty, ref default } => {
2264 self.word_space(":");
2265 self.print_type(ty);
2266 if let Some(ref _default) = default {
2267 // FIXME(const_generics_defaults): print the `default` value here
2273 pub fn print_lifetime(&mut self, lifetime: &hir::Lifetime) {
2274 self.print_ident(lifetime.name.ident())
2277 pub fn print_where_clause(&mut self, where_clause: &hir::WhereClause<'_>) {
2278 if where_clause.predicates.is_empty() {
2283 self.word_space("where");
2285 for (i, predicate) in where_clause.predicates.iter().enumerate() {
2287 self.word_space(",");
2291 hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
2292 bound_generic_params,
2297 self.print_formal_generic_params(bound_generic_params);
2298 self.print_type(&bounded_ty);
2299 self.print_bounds(":", *bounds);
2301 hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
2306 self.print_lifetime(lifetime);
2309 for (i, bound) in bounds.iter().enumerate() {
2311 GenericBound::Outlives(lt) => {
2312 self.print_lifetime(lt);
2322 hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
2325 self.print_type(lhs_ty);
2327 self.word_space("=");
2328 self.print_type(rhs_ty);
2334 pub fn print_mutability(&mut self, mutbl: hir::Mutability, print_const: bool) {
2336 hir::Mutability::Mut => self.word_nbsp("mut"),
2337 hir::Mutability::Not => {
2339 self.word_nbsp("const")
2345 pub fn print_mt(&mut self, mt: &hir::MutTy<'_>, print_const: bool) {
2346 self.print_mutability(mt.mutbl, print_const);
2347 self.print_type(&mt.ty)
2350 pub fn print_fn_output(&mut self, decl: &hir::FnDecl<'_>) {
2351 if let hir::FnRetTy::DefaultReturn(..) = decl.output {
2355 self.space_if_not_bol();
2356 self.ibox(INDENT_UNIT);
2357 self.word_space("->");
2359 hir::FnRetTy::DefaultReturn(..) => unreachable!(),
2360 hir::FnRetTy::Return(ref ty) => self.print_type(&ty),
2364 if let hir::FnRetTy::Return(ref output) = decl.output {
2365 self.maybe_print_comment(output.span.lo())
2372 unsafety: hir::Unsafety,
2373 decl: &hir::FnDecl<'_>,
2374 name: Option<Symbol>,
2375 generic_params: &[hir::GenericParam<'_>],
2376 arg_names: &[Ident],
2378 self.ibox(INDENT_UNIT);
2379 if !generic_params.is_empty() {
2381 self.print_generic_params(generic_params);
2383 let generics = hir::Generics {
2385 where_clause: hir::WhereClause { predicates: &[], span: rustc_span::DUMMY_SP },
2386 span: rustc_span::DUMMY_SP,
2393 constness: hir::Constness::NotConst,
2394 asyncness: hir::IsAsync::NotAsync,
2398 &Spanned { span: rustc_span::DUMMY_SP, node: hir::VisibilityKind::Inherited },
2405 pub fn maybe_print_trailing_comment(
2407 span: rustc_span::Span,
2408 next_pos: Option<BytePos>,
2410 if let Some(cmnts) = self.comments() {
2411 if let Some(cmnt) = cmnts.trailing_comment(span, next_pos) {
2412 self.print_comment(&cmnt);
2417 pub fn print_remaining_comments(&mut self) {
2418 // If there aren't any remaining comments, then we need to manually
2419 // make sure there is a line break at the end.
2420 if self.next_comment().is_none() {
2423 while let Some(ref cmnt) = self.next_comment() {
2424 self.print_comment(cmnt)
2428 pub fn print_opt_abi_and_extern_if_nondefault(&mut self, opt_abi: Option<Abi>) {
2430 Some(Abi::Rust) => {}
2432 self.word_nbsp("extern");
2433 self.word_nbsp(abi.to_string())
2439 pub fn print_extern_opt_abi(&mut self, opt_abi: Option<Abi>) {
2440 if let Some(abi) = opt_abi {
2441 self.word_nbsp("extern");
2442 self.word_nbsp(abi.to_string())
2446 pub fn print_fn_header_info(&mut self, header: hir::FnHeader, vis: &hir::Visibility<'_>) {
2447 self.s.word(visibility_qualified(vis, ""));
2449 match header.constness {
2450 hir::Constness::NotConst => {}
2451 hir::Constness::Const => self.word_nbsp("const"),
2454 match header.asyncness {
2455 hir::IsAsync::NotAsync => {}
2456 hir::IsAsync::Async => self.word_nbsp("async"),
2459 self.print_unsafety(header.unsafety);
2461 if header.abi != Abi::Rust {
2462 self.word_nbsp("extern");
2463 self.word_nbsp(header.abi.to_string());
2469 pub fn print_unsafety(&mut self, s: hir::Unsafety) {
2471 hir::Unsafety::Normal => {}
2472 hir::Unsafety::Unsafe => self.word_nbsp("unsafe"),
2476 pub fn print_is_auto(&mut self, s: hir::IsAuto) {
2478 hir::IsAuto::Yes => self.word_nbsp("auto"),
2479 hir::IsAuto::No => {}
2484 /// Does this expression require a semicolon to be treated
2485 /// as a statement? The negation of this: 'can this expression
2486 /// be used as a statement without a semicolon' -- is used
2487 /// as an early-bail-out in the parser so that, for instance,
2488 /// if true {...} else {...}
2490 /// isn't parsed as (if true {...} else {...} | x) | 5
2492 // Duplicated from `parse::classify`, but adapted for the HIR.
2493 fn expr_requires_semi_to_be_stmt(e: &hir::Expr<'_>) -> bool {
2496 hir::ExprKind::If(..)
2497 | hir::ExprKind::Match(..)
2498 | hir::ExprKind::Block(..)
2499 | hir::ExprKind::Loop(..)
2503 /// This statement requires a semicolon after it.
2504 /// note that in one case (stmt_semi), we've already
2505 /// seen the semicolon, and thus don't need another.
2506 fn stmt_ends_with_semi(stmt: &hir::StmtKind<'_>) -> bool {
2508 hir::StmtKind::Local(_) => true,
2509 hir::StmtKind::Item(_) => false,
2510 hir::StmtKind::Expr(ref e) => expr_requires_semi_to_be_stmt(&e),
2511 hir::StmtKind::Semi(..) => false,
2515 fn bin_op_to_assoc_op(op: hir::BinOpKind) -> AssocOp {
2516 use crate::hir::BinOpKind::*;
2518 Add => AssocOp::Add,
2519 Sub => AssocOp::Subtract,
2520 Mul => AssocOp::Multiply,
2521 Div => AssocOp::Divide,
2522 Rem => AssocOp::Modulus,
2524 And => AssocOp::LAnd,
2527 BitXor => AssocOp::BitXor,
2528 BitAnd => AssocOp::BitAnd,
2529 BitOr => AssocOp::BitOr,
2530 Shl => AssocOp::ShiftLeft,
2531 Shr => AssocOp::ShiftRight,
2533 Eq => AssocOp::Equal,
2534 Lt => AssocOp::Less,
2535 Le => AssocOp::LessEqual,
2536 Ne => AssocOp::NotEqual,
2537 Ge => AssocOp::GreaterEqual,
2538 Gt => AssocOp::Greater,
2542 /// Expressions that syntactically contain an "exterior" struct literal, i.e., not surrounded by any
2543 /// parens or other delimiters, e.g., `X { y: 1 }`, `X { y: 1 }.method()`, `foo == X { y: 1 }` and
2544 /// `X { y: 1 } == foo` all do, but `(X { y: 1 }) == foo` does not.
2545 fn contains_exterior_struct_lit(value: &hir::Expr<'_>) -> bool {
2547 hir::ExprKind::Struct(..) => true,
2549 hir::ExprKind::Assign(ref lhs, ref rhs, _)
2550 | hir::ExprKind::AssignOp(_, ref lhs, ref rhs)
2551 | hir::ExprKind::Binary(_, ref lhs, ref rhs) => {
2552 // `X { y: 1 } + X { y: 2 }`
2553 contains_exterior_struct_lit(&lhs) || contains_exterior_struct_lit(&rhs)
2555 hir::ExprKind::Unary(_, ref x)
2556 | hir::ExprKind::Cast(ref x, _)
2557 | hir::ExprKind::Type(ref x, _)
2558 | hir::ExprKind::Field(ref x, _)
2559 | hir::ExprKind::Index(ref x, _) => {
2560 // `&X { y: 1 }, X { y: 1 }.y`
2561 contains_exterior_struct_lit(&x)
2564 hir::ExprKind::MethodCall(.., ref exprs, _) => {
2565 // `X { y: 1 }.bar(...)`
2566 contains_exterior_struct_lit(&exprs[0])