1 #![recursion_limit = "256"]
4 use rustc_ast::util::parser::{self, AssocOp, Fixity};
5 use rustc_ast_pretty::pp::Breaks::{Consistent, Inconsistent};
6 use rustc_ast_pretty::pp::{self, Breaks};
7 use rustc_ast_pretty::pprust::{Comments, PrintState};
9 use rustc_hir::{GenericArg, GenericParam, GenericParamKind, Node};
10 use rustc_hir::{GenericBound, PatKind, RangeEnd, TraitBoundModifier};
11 use rustc_span::source_map::{SourceMap, Spanned};
12 use rustc_span::symbol::{kw, Ident, IdentPrinter, Symbol};
13 use rustc_span::{self, BytePos, FileName};
14 use rustc_target::spec::abi::Abi;
18 use std::collections::BTreeMap;
21 pub fn id_to_string(map: &dyn rustc_hir::intravisit::Map<'_>, hir_id: hir::HirId) -> String {
22 to_string(&map, |s| s.print_node(map.find(hir_id).unwrap()))
25 pub enum AnnNode<'a> {
27 Block(&'a hir::Block<'a>),
28 Item(&'a hir::Item<'a>),
30 Expr(&'a hir::Expr<'a>),
31 Pat(&'a hir::Pat<'a>),
32 Arm(&'a hir::Arm<'a>),
37 TraitItem(hir::TraitItemId),
38 ImplItem(hir::ImplItemId),
39 ForeignItem(hir::ForeignItemId),
41 BodyParamPat(hir::BodyId, usize),
45 fn nested(&self, _state: &mut State<'_>, _nested: Nested) {}
46 fn pre(&self, _state: &mut State<'_>, _node: AnnNode<'_>) {}
47 fn post(&self, _state: &mut State<'_>, _node: AnnNode<'_>) {}
51 impl PpAnn for NoAnn {}
52 pub const NO_ANN: &dyn PpAnn = &NoAnn;
54 impl PpAnn for hir::Crate<'_> {
55 fn nested(&self, state: &mut State<'_>, nested: Nested) {
57 Nested::Item(id) => state.print_item(self.item(id)),
58 Nested::TraitItem(id) => state.print_trait_item(self.trait_item(id)),
59 Nested::ImplItem(id) => state.print_impl_item(self.impl_item(id)),
60 Nested::ForeignItem(id) => state.print_foreign_item(self.foreign_item(id)),
61 Nested::Body(id) => state.print_expr(&self.body(id).value),
62 Nested::BodyParamPat(id, i) => state.print_pat(&self.body(id).params[i].pat),
67 /// Identical to the `PpAnn` implementation for `hir::Crate`,
68 /// except it avoids creating a dependency on the whole crate.
69 impl PpAnn for &dyn rustc_hir::intravisit::Map<'_> {
70 fn nested(&self, state: &mut State<'_>, nested: Nested) {
72 Nested::Item(id) => state.print_item(self.item(id)),
73 Nested::TraitItem(id) => state.print_trait_item(self.trait_item(id)),
74 Nested::ImplItem(id) => state.print_impl_item(self.impl_item(id)),
75 Nested::ForeignItem(id) => state.print_foreign_item(self.foreign_item(id)),
76 Nested::Body(id) => state.print_expr(&self.body(id).value),
77 Nested::BodyParamPat(id, i) => state.print_pat(&self.body(id).params[i].pat),
82 pub struct State<'a> {
84 comments: Option<Comments<'a>>,
85 attrs: &'a BTreeMap<hir::HirId, &'a [ast::Attribute]>,
86 ann: &'a (dyn PpAnn + 'a),
90 pub fn print_node(&mut self, node: Node<'_>) {
92 Node::Param(a) => self.print_param(&a),
93 Node::Item(a) => self.print_item(&a),
94 Node::ForeignItem(a) => self.print_foreign_item(&a),
95 Node::TraitItem(a) => self.print_trait_item(a),
96 Node::ImplItem(a) => self.print_impl_item(a),
97 Node::Variant(a) => self.print_variant(&a),
98 Node::AnonConst(a) => self.print_anon_const(&a),
99 Node::Expr(a) => self.print_expr(&a),
100 Node::Stmt(a) => self.print_stmt(&a),
101 Node::PathSegment(a) => self.print_path_segment(&a),
102 Node::Ty(a) => self.print_type(&a),
103 Node::TraitRef(a) => self.print_trait_ref(&a),
104 Node::Binding(a) | Node::Pat(a) => self.print_pat(&a),
105 Node::Arm(a) => self.print_arm(&a),
107 // Containing cbox, will be closed by print-block at `}`.
108 self.cbox(INDENT_UNIT);
109 // Head-ibox, will be closed by print-block after `{`.
113 Node::Lifetime(a) => self.print_lifetime(&a),
114 Node::Visibility(a) => self.print_visibility(&a),
115 Node::GenericParam(_) => panic!("cannot print Node::GenericParam"),
116 Node::Field(_) => panic!("cannot print Node::Field"),
117 // These cases do not carry enough information in the
118 // `hir_map` to reconstruct their full structure for pretty
120 Node::Ctor(..) => panic!("cannot print isolated Ctor"),
121 Node::Local(a) => self.print_local_decl(&a),
122 Node::MacroDef(_) => panic!("cannot print MacroDef"),
123 Node::Crate(..) => panic!("cannot print Crate"),
128 impl std::ops::Deref for State<'_> {
129 type Target = pp::Printer;
130 fn deref(&self) -> &Self::Target {
135 impl std::ops::DerefMut for State<'_> {
136 fn deref_mut(&mut self) -> &mut Self::Target {
141 impl<'a> PrintState<'a> for State<'a> {
142 fn comments(&mut self) -> &mut Option<Comments<'a>> {
146 fn print_ident(&mut self, ident: Ident) {
147 self.s.word(IdentPrinter::for_ast_ident(ident, ident.is_raw_guess()).to_string());
148 self.ann.post(self, AnnNode::Name(&ident.name))
151 fn print_generic_args(&mut self, _: &ast::GenericArgs, _colons_before_params: bool) {
152 panic!("AST generic args printed by HIR pretty-printer");
156 pub const INDENT_UNIT: usize = 4;
158 /// Requires you to pass an input filename and reader so that
159 /// it can scan the input text for comments to copy forward.
160 pub fn print_crate<'a>(
162 krate: &hir::Crate<'_>,
167 let mut s = State::new_from_input(sm, filename, input, &krate.attrs, ann);
169 // When printing the AST, we sometimes need to inject `#[no_std]` here.
170 // Since you can't compile the HIR, it's not necessary.
172 s.print_mod(&krate.item, s.attrs(hir::CRATE_HIR_ID));
173 s.print_remaining_comments();
178 pub fn new_from_input(
182 attrs: &'a BTreeMap<hir::HirId, &[ast::Attribute]>,
187 comments: Some(Comments::new(sm, filename, input)),
193 fn attrs(&self, id: hir::HirId) -> &'a [ast::Attribute] {
194 self.attrs.get(&id).map_or(&[], |la| *la)
198 pub fn to_string<F>(ann: &dyn PpAnn, f: F) -> String
200 F: FnOnce(&mut State<'_>),
203 State { s: pp::mk_printer(), comments: None, attrs: &BTreeMap::default(), ann };
208 pub fn visibility_qualified<S: Into<Cow<'static, str>>>(vis: &hir::Visibility<'_>, w: S) -> String {
209 to_string(NO_ANN, |s| {
210 s.print_visibility(vis);
215 pub fn generic_params_to_string(generic_params: &[GenericParam<'_>]) -> String {
216 to_string(NO_ANN, |s| s.print_generic_params(generic_params))
219 pub fn bounds_to_string<'b>(bounds: impl IntoIterator<Item = &'b hir::GenericBound<'b>>) -> String {
220 to_string(NO_ANN, |s| s.print_bounds("", bounds))
223 pub fn ty_to_string(ty: &hir::Ty<'_>) -> String {
224 to_string(NO_ANN, |s| s.print_type(ty))
227 pub fn path_segment_to_string(segment: &hir::PathSegment<'_>) -> String {
228 to_string(NO_ANN, |s| s.print_path_segment(segment))
231 pub fn path_to_string(segment: &hir::Path<'_>) -> String {
232 to_string(NO_ANN, |s| s.print_path(segment, false))
236 decl: &hir::FnDecl<'_>,
237 header: hir::FnHeader,
238 name: Option<Symbol>,
239 generics: &hir::Generics<'_>,
240 vis: &hir::Visibility<'_>,
242 body_id: Option<hir::BodyId>,
244 to_string(NO_ANN, |s| s.print_fn(decl, header, name, generics, vis, arg_names, body_id))
247 pub fn enum_def_to_string(
248 enum_definition: &hir::EnumDef<'_>,
249 generics: &hir::Generics<'_>,
251 span: rustc_span::Span,
252 visibility: &hir::Visibility<'_>,
254 to_string(NO_ANN, |s| s.print_enum_def(enum_definition, generics, name, span, visibility))
258 pub fn cbox(&mut self, u: usize) {
262 pub fn nbsp(&mut self) {
266 pub fn word_nbsp<S: Into<Cow<'static, str>>>(&mut self, w: S) {
271 pub fn head<S: Into<Cow<'static, str>>>(&mut self, w: S) {
273 // outer-box is consistent
274 self.cbox(INDENT_UNIT);
275 // head-box is inconsistent
276 self.ibox(w.len() + 1);
277 // keyword that starts the head
283 pub fn bopen(&mut self) {
285 self.end(); // close the head-box
288 pub fn bclose_maybe_open(&mut self, span: rustc_span::Span, close_box: bool) {
289 self.maybe_print_comment(span.hi());
290 self.break_offset_if_not_bol(1, -(INDENT_UNIT as isize));
293 self.end(); // close the outer-box
297 pub fn bclose(&mut self, span: rustc_span::Span) {
298 self.bclose_maybe_open(span, true)
301 pub fn space_if_not_bol(&mut self) {
302 if !self.s.is_beginning_of_line() {
307 pub fn break_offset_if_not_bol(&mut self, n: usize, off: isize) {
308 if !self.s.is_beginning_of_line() {
309 self.s.break_offset(n, off)
310 } else if off != 0 && self.s.last_token().is_hardbreak_tok() {
311 // We do something pretty sketchy here: tuck the nonzero
312 // offset-adjustment we were going to deposit along with the
313 // break into the previous hardbreak.
314 self.s.replace_last_token(pp::Printer::hardbreak_tok_offset(off));
318 // Synthesizes a comment that was not textually present in the original source
320 pub fn synth_comment(&mut self, text: String) {
328 pub fn commasep_cmnt<T, F, G>(&mut self, b: Breaks, elts: &[T], mut op: F, mut get_span: G)
330 F: FnMut(&mut State<'_>, &T),
331 G: FnMut(&T) -> rustc_span::Span,
334 let len = elts.len();
337 self.maybe_print_comment(get_span(elt).hi());
342 self.maybe_print_trailing_comment(get_span(elt), Some(get_span(&elts[i]).hi()));
343 self.space_if_not_bol();
349 pub fn commasep_exprs(&mut self, b: Breaks, exprs: &[hir::Expr<'_>]) {
350 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(&e), |e| e.span)
353 pub fn print_mod(&mut self, _mod: &hir::Mod<'_>, attrs: &[ast::Attribute]) {
354 self.print_inner_attributes(attrs);
355 for &item_id in _mod.item_ids {
356 self.ann.nested(self, Nested::Item(item_id));
360 pub fn print_opt_lifetime(&mut self, lifetime: &hir::Lifetime) {
361 if !lifetime.is_elided() {
362 self.print_lifetime(lifetime);
367 pub fn print_type(&mut self, ty: &hir::Ty<'_>) {
368 self.maybe_print_comment(ty.span.lo());
371 hir::TyKind::Slice(ref ty) => {
373 self.print_type(&ty);
376 hir::TyKind::Ptr(ref mt) => {
378 self.print_mt(mt, true);
380 hir::TyKind::Rptr(ref lifetime, ref mt) => {
382 self.print_opt_lifetime(lifetime);
383 self.print_mt(mt, false);
385 hir::TyKind::Never => {
388 hir::TyKind::Tup(ref elts) => {
390 self.commasep(Inconsistent, &elts[..], |s, ty| s.print_type(&ty));
396 hir::TyKind::BareFn(ref f) => {
406 hir::TyKind::OpaqueDef(..) => self.s.word("/*impl Trait*/"),
407 hir::TyKind::Path(ref qpath) => self.print_qpath(qpath, false),
408 hir::TyKind::TraitObject(bounds, ref lifetime, syntax) => {
409 if syntax == ast::TraitObjectSyntax::Dyn {
410 self.word_space("dyn");
412 let mut first = true;
413 for bound in bounds {
418 self.word_space("+");
420 self.print_poly_trait_ref(bound);
422 if !lifetime.is_elided() {
424 self.word_space("+");
425 self.print_lifetime(lifetime);
428 hir::TyKind::Array(ref ty, ref length) => {
430 self.print_type(&ty);
432 self.print_anon_const(length);
435 hir::TyKind::Typeof(ref e) => {
436 self.s.word("typeof(");
437 self.print_anon_const(e);
440 hir::TyKind::Infer => {
443 hir::TyKind::Err => {
445 self.s.word("/*ERROR*/");
452 pub fn print_foreign_item(&mut self, item: &hir::ForeignItem<'_>) {
453 self.hardbreak_if_not_bol();
454 self.maybe_print_comment(item.span.lo());
455 self.print_outer_attributes(self.attrs(item.hir_id()));
457 hir::ForeignItemKind::Fn(ref decl, ref arg_names, ref generics) => {
462 unsafety: hir::Unsafety::Normal,
463 constness: hir::Constness::NotConst,
465 asyncness: hir::IsAsync::NotAsync,
467 Some(item.ident.name),
473 self.end(); // end head-ibox
475 self.end() // end the outer fn box
477 hir::ForeignItemKind::Static(ref t, m) => {
478 self.head(visibility_qualified(&item.vis, "static"));
479 if m == hir::Mutability::Mut {
480 self.word_space("mut");
482 self.print_ident(item.ident);
483 self.word_space(":");
486 self.end(); // end the head-ibox
487 self.end() // end the outer cbox
489 hir::ForeignItemKind::Type => {
490 self.head(visibility_qualified(&item.vis, "type"));
491 self.print_ident(item.ident);
493 self.end(); // end the head-ibox
494 self.end() // end the outer cbox
499 fn print_associated_const(
503 default: Option<hir::BodyId>,
504 vis: &hir::Visibility<'_>,
506 self.s.word(visibility_qualified(vis, ""));
507 self.word_space("const");
508 self.print_ident(ident);
509 self.word_space(":");
511 if let Some(expr) = default {
513 self.word_space("=");
514 self.ann.nested(self, Nested::Body(expr));
519 fn print_associated_type(
522 generics: &hir::Generics<'_>,
523 bounds: Option<hir::GenericBounds<'_>>,
524 ty: Option<&hir::Ty<'_>>,
526 self.word_space("type");
527 self.print_ident(ident);
528 self.print_generic_params(&generics.params);
529 if let Some(bounds) = bounds {
530 self.print_bounds(":", bounds);
532 self.print_where_clause(&generics.where_clause);
533 if let Some(ty) = ty {
535 self.word_space("=");
543 item: &hir::Item<'_>,
544 generics: &hir::Generics<'_>,
545 inner: impl Fn(&mut Self),
547 self.head(visibility_qualified(&item.vis, "type"));
548 self.print_ident(item.ident);
549 self.print_generic_params(&generics.params);
550 self.end(); // end the inner ibox
552 self.print_where_clause(&generics.where_clause);
556 self.end(); // end the outer ibox
559 /// Pretty-print an item
560 pub fn print_item(&mut self, item: &hir::Item<'_>) {
561 self.hardbreak_if_not_bol();
562 self.maybe_print_comment(item.span.lo());
563 let attrs = self.attrs(item.hir_id());
564 self.print_outer_attributes(attrs);
565 self.ann.pre(self, AnnNode::Item(item));
567 hir::ItemKind::ExternCrate(orig_name) => {
568 self.head(visibility_qualified(&item.vis, "extern crate"));
569 if let Some(orig_name) = orig_name {
570 self.print_name(orig_name);
575 self.print_ident(item.ident);
577 self.end(); // end inner head-block
578 self.end(); // end outer head-block
580 hir::ItemKind::Use(ref path, kind) => {
581 self.head(visibility_qualified(&item.vis, "use"));
582 self.print_path(path, false);
585 hir::UseKind::Single => {
586 if path.segments.last().unwrap().ident != item.ident {
588 self.word_space("as");
589 self.print_ident(item.ident);
593 hir::UseKind::Glob => self.s.word("::*;"),
594 hir::UseKind::ListStem => self.s.word("::{};"),
596 self.end(); // end inner head-block
597 self.end(); // end outer head-block
599 hir::ItemKind::Static(ref ty, m, expr) => {
600 self.head(visibility_qualified(&item.vis, "static"));
601 if m == hir::Mutability::Mut {
602 self.word_space("mut");
604 self.print_ident(item.ident);
605 self.word_space(":");
606 self.print_type(&ty);
608 self.end(); // end the head-ibox
610 self.word_space("=");
611 self.ann.nested(self, Nested::Body(expr));
613 self.end(); // end the outer cbox
615 hir::ItemKind::Const(ref ty, expr) => {
616 self.head(visibility_qualified(&item.vis, "const"));
617 self.print_ident(item.ident);
618 self.word_space(":");
619 self.print_type(&ty);
621 self.end(); // end the head-ibox
623 self.word_space("=");
624 self.ann.nested(self, Nested::Body(expr));
626 self.end(); // end the outer cbox
628 hir::ItemKind::Fn(ref sig, ref param_names, body) => {
633 Some(item.ident.name),
640 self.end(); // need to close a box
641 self.end(); // need to close a box
642 self.ann.nested(self, Nested::Body(body));
644 hir::ItemKind::Mod(ref _mod) => {
645 self.head(visibility_qualified(&item.vis, "mod"));
646 self.print_ident(item.ident);
649 self.print_mod(_mod, attrs);
650 self.bclose(item.span);
652 hir::ItemKind::ForeignMod { abi, items } => {
654 self.word_nbsp(abi.to_string());
656 self.print_inner_attributes(self.attrs(item.hir_id()));
658 self.ann.nested(self, Nested::ForeignItem(item.id));
660 self.bclose(item.span);
662 hir::ItemKind::GlobalAsm(ref asm) => {
663 self.head(visibility_qualified(&item.vis, "global_asm!"));
664 self.print_inline_asm(asm);
667 hir::ItemKind::TyAlias(ref ty, ref generics) => {
668 self.print_item_type(item, &generics, |state| {
669 state.word_space("=");
670 state.print_type(&ty);
673 hir::ItemKind::OpaqueTy(ref opaque_ty) => {
674 self.print_item_type(item, &opaque_ty.generics, |state| {
675 let mut real_bounds = Vec::with_capacity(opaque_ty.bounds.len());
676 for b in opaque_ty.bounds.iter() {
677 if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
679 state.word_space("for ?");
680 state.print_trait_ref(&ptr.trait_ref);
685 state.print_bounds("= impl", real_bounds);
688 hir::ItemKind::Enum(ref enum_definition, ref params) => {
689 self.print_enum_def(enum_definition, params, item.ident.name, item.span, &item.vis);
691 hir::ItemKind::Struct(ref struct_def, ref generics) => {
692 self.head(visibility_qualified(&item.vis, "struct"));
693 self.print_struct(struct_def, generics, item.ident.name, item.span, true);
695 hir::ItemKind::Union(ref struct_def, ref generics) => {
696 self.head(visibility_qualified(&item.vis, "union"));
697 self.print_struct(struct_def, generics, item.ident.name, item.span, true);
699 hir::ItemKind::Impl(hir::Impl {
711 self.print_visibility(&item.vis);
712 self.print_defaultness(defaultness);
713 self.print_unsafety(unsafety);
714 self.word_nbsp("impl");
716 if !generics.params.is_empty() {
717 self.print_generic_params(&generics.params);
721 if constness == hir::Constness::Const {
722 self.word_nbsp("const");
725 if let hir::ImplPolarity::Negative(_) = polarity {
729 if let Some(ref t) = of_trait {
730 self.print_trait_ref(t);
732 self.word_space("for");
735 self.print_type(&self_ty);
736 self.print_where_clause(&generics.where_clause);
740 self.print_inner_attributes(attrs);
741 for impl_item in items {
742 self.ann.nested(self, Nested::ImplItem(impl_item.id));
744 self.bclose(item.span);
746 hir::ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, trait_items) => {
748 self.print_visibility(&item.vis);
749 self.print_is_auto(is_auto);
750 self.print_unsafety(unsafety);
751 self.word_nbsp("trait");
752 self.print_ident(item.ident);
753 self.print_generic_params(&generics.params);
754 let mut real_bounds = Vec::with_capacity(bounds.len());
755 for b in bounds.iter() {
756 if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
758 self.word_space("for ?");
759 self.print_trait_ref(&ptr.trait_ref);
764 self.print_bounds(":", real_bounds);
765 self.print_where_clause(&generics.where_clause);
768 for trait_item in trait_items {
769 self.ann.nested(self, Nested::TraitItem(trait_item.id));
771 self.bclose(item.span);
773 hir::ItemKind::TraitAlias(ref generics, ref bounds) => {
775 self.print_visibility(&item.vis);
776 self.word_nbsp("trait");
777 self.print_ident(item.ident);
778 self.print_generic_params(&generics.params);
779 let mut real_bounds = Vec::with_capacity(bounds.len());
780 // FIXME(durka) this seems to be some quite outdated syntax
781 for b in bounds.iter() {
782 if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
784 self.word_space("for ?");
785 self.print_trait_ref(&ptr.trait_ref);
791 self.print_bounds("=", real_bounds);
792 self.print_where_clause(&generics.where_clause);
796 self.ann.post(self, AnnNode::Item(item))
799 pub fn print_trait_ref(&mut self, t: &hir::TraitRef<'_>) {
800 self.print_path(&t.path, false)
803 fn print_formal_generic_params(&mut self, generic_params: &[hir::GenericParam<'_>]) {
804 if !generic_params.is_empty() {
806 self.print_generic_params(generic_params);
811 fn print_poly_trait_ref(&mut self, t: &hir::PolyTraitRef<'_>) {
812 self.print_formal_generic_params(&t.bound_generic_params);
813 self.print_trait_ref(&t.trait_ref)
816 pub fn print_enum_def(
818 enum_definition: &hir::EnumDef<'_>,
819 generics: &hir::Generics<'_>,
821 span: rustc_span::Span,
822 visibility: &hir::Visibility<'_>,
824 self.head(visibility_qualified(visibility, "enum"));
825 self.print_name(name);
826 self.print_generic_params(&generics.params);
827 self.print_where_clause(&generics.where_clause);
829 self.print_variants(&enum_definition.variants, span)
832 pub fn print_variants(&mut self, variants: &[hir::Variant<'_>], span: rustc_span::Span) {
835 self.space_if_not_bol();
836 self.maybe_print_comment(v.span.lo());
837 self.print_outer_attributes(self.attrs(v.id));
838 self.ibox(INDENT_UNIT);
839 self.print_variant(v);
842 self.maybe_print_trailing_comment(v.span, None);
847 pub fn print_visibility(&mut self, vis: &hir::Visibility<'_>) {
849 hir::VisibilityKind::Public => self.word_nbsp("pub"),
850 hir::VisibilityKind::Crate(ast::CrateSugar::JustCrate) => self.word_nbsp("crate"),
851 hir::VisibilityKind::Crate(ast::CrateSugar::PubCrate) => self.word_nbsp("pub(crate)"),
852 hir::VisibilityKind::Restricted { ref path, .. } => {
854 if path.segments.len() == 1 && path.segments[0].ident.name == kw::Super {
855 // Special case: `super` can print like `pub(super)`.
856 self.s.word("super");
858 // Everything else requires `in` at present.
859 self.word_nbsp("in");
860 self.print_path(path, false);
864 hir::VisibilityKind::Inherited => (),
868 pub fn print_defaultness(&mut self, defaultness: hir::Defaultness) {
870 hir::Defaultness::Default { .. } => self.word_nbsp("default"),
871 hir::Defaultness::Final => (),
877 struct_def: &hir::VariantData<'_>,
878 generics: &hir::Generics<'_>,
880 span: rustc_span::Span,
881 print_finalizer: bool,
883 self.print_name(name);
884 self.print_generic_params(&generics.params);
886 hir::VariantData::Tuple(..) | hir::VariantData::Unit(..) => {
887 if let hir::VariantData::Tuple(..) = struct_def {
889 self.commasep(Inconsistent, struct_def.fields(), |s, field| {
890 s.maybe_print_comment(field.span.lo());
891 s.print_outer_attributes(s.attrs(field.hir_id));
892 s.print_visibility(&field.vis);
893 s.print_type(&field.ty)
897 self.print_where_clause(&generics.where_clause);
902 self.end() // close the outer-box
904 hir::VariantData::Struct(..) => {
905 self.print_where_clause(&generics.where_clause);
908 self.hardbreak_if_not_bol();
910 for field in struct_def.fields() {
911 self.hardbreak_if_not_bol();
912 self.maybe_print_comment(field.span.lo());
913 self.print_outer_attributes(self.attrs(field.hir_id));
914 self.print_visibility(&field.vis);
915 self.print_ident(field.ident);
917 self.print_type(&field.ty);
926 pub fn print_variant(&mut self, v: &hir::Variant<'_>) {
928 let generics = hir::Generics::empty();
929 self.print_struct(&v.data, &generics, v.ident.name, v.span, false);
930 if let Some(ref d) = v.disr_expr {
932 self.word_space("=");
933 self.print_anon_const(d);
936 pub fn print_method_sig(
940 generics: &hir::Generics<'_>,
941 vis: &hir::Visibility<'_>,
943 body_id: Option<hir::BodyId>,
945 self.print_fn(&m.decl, m.header, Some(ident.name), generics, vis, arg_names, body_id)
948 pub fn print_trait_item(&mut self, ti: &hir::TraitItem<'_>) {
949 self.ann.pre(self, AnnNode::SubItem(ti.hir_id()));
950 self.hardbreak_if_not_bol();
951 self.maybe_print_comment(ti.span.lo());
952 self.print_outer_attributes(self.attrs(ti.hir_id()));
954 hir::TraitItemKind::Const(ref ty, default) => {
956 Spanned { span: rustc_span::DUMMY_SP, node: hir::VisibilityKind::Inherited };
957 self.print_associated_const(ti.ident, &ty, default, &vis);
959 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Required(ref arg_names)) => {
961 Spanned { span: rustc_span::DUMMY_SP, node: hir::VisibilityKind::Inherited };
962 self.print_method_sig(ti.ident, sig, &ti.generics, &vis, arg_names, None);
965 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Provided(body)) => {
967 Spanned { span: rustc_span::DUMMY_SP, node: hir::VisibilityKind::Inherited };
969 self.print_method_sig(ti.ident, sig, &ti.generics, &vis, &[], Some(body));
971 self.end(); // need to close a box
972 self.end(); // need to close a box
973 self.ann.nested(self, Nested::Body(body));
975 hir::TraitItemKind::Type(ref bounds, ref default) => {
976 self.print_associated_type(
980 default.as_ref().map(|ty| &**ty),
984 self.ann.post(self, AnnNode::SubItem(ti.hir_id()))
987 pub fn print_impl_item(&mut self, ii: &hir::ImplItem<'_>) {
988 self.ann.pre(self, AnnNode::SubItem(ii.hir_id()));
989 self.hardbreak_if_not_bol();
990 self.maybe_print_comment(ii.span.lo());
991 self.print_outer_attributes(self.attrs(ii.hir_id()));
992 self.print_defaultness(ii.defaultness);
995 hir::ImplItemKind::Const(ref ty, expr) => {
996 self.print_associated_const(ii.ident, &ty, Some(expr), &ii.vis);
998 hir::ImplItemKind::Fn(ref sig, body) => {
1000 self.print_method_sig(ii.ident, sig, &ii.generics, &ii.vis, &[], Some(body));
1002 self.end(); // need to close a box
1003 self.end(); // need to close a box
1004 self.ann.nested(self, Nested::Body(body));
1006 hir::ImplItemKind::TyAlias(ref ty) => {
1007 self.print_associated_type(ii.ident, &ii.generics, None, Some(ty));
1010 self.ann.post(self, AnnNode::SubItem(ii.hir_id()))
1013 pub fn print_local(&mut self, init: Option<&hir::Expr<'_>>, decl: impl Fn(&mut Self)) {
1014 self.space_if_not_bol();
1015 self.ibox(INDENT_UNIT);
1016 self.word_nbsp("let");
1018 self.ibox(INDENT_UNIT);
1022 if let Some(ref init) = init {
1024 self.word_space("=");
1025 self.print_expr(&init);
1030 pub fn print_stmt(&mut self, st: &hir::Stmt<'_>) {
1031 self.maybe_print_comment(st.span.lo());
1033 hir::StmtKind::Local(ref loc) => {
1034 self.print_local(loc.init.as_deref(), |this| this.print_local_decl(&loc));
1036 hir::StmtKind::Item(item) => self.ann.nested(self, Nested::Item(item)),
1037 hir::StmtKind::Expr(ref expr) => {
1038 self.space_if_not_bol();
1039 self.print_expr(&expr);
1041 hir::StmtKind::Semi(ref expr) => {
1042 self.space_if_not_bol();
1043 self.print_expr(&expr);
1047 if stmt_ends_with_semi(&st.kind) {
1050 self.maybe_print_trailing_comment(st.span, None)
1053 pub fn print_block(&mut self, blk: &hir::Block<'_>) {
1054 self.print_block_with_attrs(blk, &[])
1057 pub fn print_block_unclosed(&mut self, blk: &hir::Block<'_>) {
1058 self.print_block_maybe_unclosed(blk, &[], false)
1061 pub fn print_block_with_attrs(&mut self, blk: &hir::Block<'_>, attrs: &[ast::Attribute]) {
1062 self.print_block_maybe_unclosed(blk, attrs, true)
1065 pub fn print_block_maybe_unclosed(
1067 blk: &hir::Block<'_>,
1068 attrs: &[ast::Attribute],
1072 hir::BlockCheckMode::UnsafeBlock(..) => self.word_space("unsafe"),
1073 hir::BlockCheckMode::DefaultBlock => (),
1075 self.maybe_print_comment(blk.span.lo());
1076 self.ann.pre(self, AnnNode::Block(blk));
1079 self.print_inner_attributes(attrs);
1081 for st in blk.stmts {
1082 self.print_stmt(st);
1084 if let Some(ref expr) = blk.expr {
1085 self.space_if_not_bol();
1086 self.print_expr(&expr);
1087 self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi()));
1089 self.bclose_maybe_open(blk.span, close_box);
1090 self.ann.post(self, AnnNode::Block(blk))
1093 fn print_else(&mut self, els: Option<&hir::Expr<'_>>) {
1097 // "another else-if"
1098 hir::ExprKind::If(ref i, ref then, ref e) => {
1099 self.cbox(INDENT_UNIT - 1);
1101 self.s.word(" else if ");
1102 self.print_expr_as_cond(&i);
1104 self.print_expr(&then);
1105 self.print_else(e.as_ref().map(|e| &**e))
1108 hir::ExprKind::Block(ref b, _) => {
1109 self.cbox(INDENT_UNIT - 1);
1111 self.s.word(" else ");
1112 self.print_block(&b)
1114 hir::ExprKind::Match(ref expr, arms, _) => {
1115 // else if let desugared to match
1116 assert!(arms.len() == 2, "if let desugars to match with two arms");
1118 self.s.word(" else ");
1121 self.cbox(INDENT_UNIT);
1122 self.ibox(INDENT_UNIT);
1123 self.word_nbsp("match");
1124 self.print_expr_as_cond(&expr);
1128 self.print_arm(arm);
1130 self.bclose(expr.span);
1134 // BLEAH, constraints would be great here
1136 panic!("print_if saw if with weird alternative");
1146 test: &hir::Expr<'_>,
1147 blk: &hir::Expr<'_>,
1148 elseopt: Option<&hir::Expr<'_>>,
1151 self.print_expr_as_cond(test);
1153 self.print_expr(blk);
1154 self.print_else(elseopt)
1157 pub fn print_anon_const(&mut self, constant: &hir::AnonConst) {
1158 self.ann.nested(self, Nested::Body(constant.body))
1161 fn print_call_post(&mut self, args: &[hir::Expr<'_>]) {
1163 self.commasep_exprs(Inconsistent, args);
1167 pub fn print_expr_maybe_paren(&mut self, expr: &hir::Expr<'_>, prec: i8) {
1168 let needs_par = expr.precedence().order() < prec;
1172 self.print_expr(expr);
1178 /// Print an expr using syntax that's acceptable in a condition position, such as the `cond` in
1179 /// `if cond { ... }`.
1180 pub fn print_expr_as_cond(&mut self, expr: &hir::Expr<'_>) {
1181 let needs_par = match expr.kind {
1182 // These cases need parens due to the parse error observed in #26461: `if return {}`
1183 // parses as the erroneous construct `if (return {})`, not `if (return) {}`.
1184 hir::ExprKind::Closure(..) | hir::ExprKind::Ret(..) | hir::ExprKind::Break(..) => true,
1186 _ => contains_exterior_struct_lit(expr),
1192 self.print_expr(expr);
1198 fn print_expr_vec(&mut self, exprs: &[hir::Expr<'_>]) {
1199 self.ibox(INDENT_UNIT);
1201 self.commasep_exprs(Inconsistent, exprs);
1206 fn print_expr_anon_const(&mut self, anon_const: &hir::AnonConst) {
1207 self.ibox(INDENT_UNIT);
1208 self.s.word_space("const");
1209 self.print_anon_const(anon_const);
1213 fn print_expr_repeat(&mut self, element: &hir::Expr<'_>, count: &hir::AnonConst) {
1214 self.ibox(INDENT_UNIT);
1216 self.print_expr(element);
1217 self.word_space(";");
1218 self.print_anon_const(count);
1223 fn print_expr_struct(
1225 qpath: &hir::QPath<'_>,
1226 fields: &[hir::ExprField<'_>],
1227 wth: &Option<&hir::Expr<'_>>,
1229 self.print_qpath(qpath, true);
1235 s.ibox(INDENT_UNIT);
1236 if !field.is_shorthand {
1237 s.print_ident(field.ident);
1240 s.print_expr(&field.expr);
1247 self.ibox(INDENT_UNIT);
1248 if !fields.is_empty() {
1253 self.print_expr(&expr);
1257 if !fields.is_empty() {
1265 fn print_expr_tup(&mut self, exprs: &[hir::Expr<'_>]) {
1267 self.commasep_exprs(Inconsistent, exprs);
1268 if exprs.len() == 1 {
1274 fn print_expr_call(&mut self, func: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
1275 let prec = match func.kind {
1276 hir::ExprKind::Field(..) => parser::PREC_FORCE_PAREN,
1277 _ => parser::PREC_POSTFIX,
1280 self.print_expr_maybe_paren(func, prec);
1281 self.print_call_post(args)
1284 fn print_expr_method_call(&mut self, segment: &hir::PathSegment<'_>, args: &[hir::Expr<'_>]) {
1285 let base_args = &args[1..];
1286 self.print_expr_maybe_paren(&args[0], parser::PREC_POSTFIX);
1288 self.print_ident(segment.ident);
1290 let generic_args = segment.args();
1291 if !generic_args.args.is_empty() || !generic_args.bindings.is_empty() {
1292 self.print_generic_args(generic_args, segment.infer_args, true);
1295 self.print_call_post(base_args)
1298 fn print_expr_binary(&mut self, op: hir::BinOp, lhs: &hir::Expr<'_>, rhs: &hir::Expr<'_>) {
1299 let assoc_op = bin_op_to_assoc_op(op.node);
1300 let prec = assoc_op.precedence() as i8;
1301 let fixity = assoc_op.fixity();
1303 let (left_prec, right_prec) = match fixity {
1304 Fixity::Left => (prec, prec + 1),
1305 Fixity::Right => (prec + 1, prec),
1306 Fixity::None => (prec + 1, prec + 1),
1309 let left_prec = match (&lhs.kind, op.node) {
1310 // These cases need parens: `x as i32 < y` has the parser thinking that `i32 < y` is
1311 // the beginning of a path type. It starts trying to parse `x as (i32 < y ...` instead
1312 // of `(x as i32) < ...`. We need to convince it _not_ to do that.
1313 (&hir::ExprKind::Cast { .. }, hir::BinOpKind::Lt | hir::BinOpKind::Shl) => {
1314 parser::PREC_FORCE_PAREN
1319 self.print_expr_maybe_paren(lhs, left_prec);
1321 self.word_space(op.node.as_str());
1322 self.print_expr_maybe_paren(rhs, right_prec)
1325 fn print_expr_unary(&mut self, op: hir::UnOp, expr: &hir::Expr<'_>) {
1326 self.s.word(op.as_str());
1327 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1330 fn print_expr_addr_of(
1332 kind: hir::BorrowKind,
1333 mutability: hir::Mutability,
1334 expr: &hir::Expr<'_>,
1338 hir::BorrowKind::Ref => self.print_mutability(mutability, false),
1339 hir::BorrowKind::Raw => {
1340 self.word_nbsp("raw");
1341 self.print_mutability(mutability, true);
1344 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1347 fn print_literal(&mut self, lit: &hir::Lit) {
1348 self.maybe_print_comment(lit.span.lo());
1349 self.word(lit.node.to_lit_token().to_string())
1352 fn print_inline_asm(&mut self, asm: &hir::InlineAsm<'_>) {
1355 Operand(&'a hir::InlineAsmOperand<'a>),
1356 Options(ast::InlineAsmOptions),
1359 let mut args = vec![];
1360 args.push(AsmArg::Template(ast::InlineAsmTemplatePiece::to_string(&asm.template)));
1361 args.extend(asm.operands.iter().map(|(o, _)| AsmArg::Operand(o)));
1362 if !asm.options.is_empty() {
1363 args.push(AsmArg::Options(asm.options));
1367 self.commasep(Consistent, &args, |s, arg| match arg {
1368 AsmArg::Template(template) => s.print_string(&template, ast::StrStyle::Cooked),
1369 AsmArg::Operand(op) => match op {
1370 hir::InlineAsmOperand::In { reg, expr } => {
1373 s.word(format!("{}", reg));
1378 hir::InlineAsmOperand::Out { reg, late, expr } => {
1379 s.word(if *late { "lateout" } else { "out" });
1381 s.word(format!("{}", reg));
1385 Some(expr) => s.print_expr(expr),
1386 None => s.word("_"),
1389 hir::InlineAsmOperand::InOut { reg, late, expr } => {
1390 s.word(if *late { "inlateout" } else { "inout" });
1392 s.word(format!("{}", reg));
1397 hir::InlineAsmOperand::SplitInOut { reg, late, in_expr, out_expr } => {
1398 s.word(if *late { "inlateout" } else { "inout" });
1400 s.word(format!("{}", reg));
1403 s.print_expr(in_expr);
1407 Some(out_expr) => s.print_expr(out_expr),
1408 None => s.word("_"),
1411 hir::InlineAsmOperand::Const { anon_const } => {
1414 s.print_anon_const(anon_const);
1416 hir::InlineAsmOperand::Sym { expr } => {
1422 AsmArg::Options(opts) => {
1425 let mut options = vec![];
1426 if opts.contains(ast::InlineAsmOptions::PURE) {
1427 options.push("pure");
1429 if opts.contains(ast::InlineAsmOptions::NOMEM) {
1430 options.push("nomem");
1432 if opts.contains(ast::InlineAsmOptions::READONLY) {
1433 options.push("readonly");
1435 if opts.contains(ast::InlineAsmOptions::PRESERVES_FLAGS) {
1436 options.push("preserves_flags");
1438 if opts.contains(ast::InlineAsmOptions::NORETURN) {
1439 options.push("noreturn");
1441 if opts.contains(ast::InlineAsmOptions::NOSTACK) {
1442 options.push("nostack");
1444 if opts.contains(ast::InlineAsmOptions::ATT_SYNTAX) {
1445 options.push("att_syntax");
1447 s.commasep(Inconsistent, &options, |s, &opt| {
1456 pub fn print_expr(&mut self, expr: &hir::Expr<'_>) {
1457 self.maybe_print_comment(expr.span.lo());
1458 self.print_outer_attributes(self.attrs(expr.hir_id));
1459 self.ibox(INDENT_UNIT);
1460 self.ann.pre(self, AnnNode::Expr(expr));
1462 hir::ExprKind::Box(ref expr) => {
1463 self.word_space("box");
1464 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX);
1466 hir::ExprKind::Array(ref exprs) => {
1467 self.print_expr_vec(exprs);
1469 hir::ExprKind::ConstBlock(ref anon_const) => {
1470 self.print_expr_anon_const(anon_const);
1472 hir::ExprKind::Repeat(ref element, ref count) => {
1473 self.print_expr_repeat(&element, count);
1475 hir::ExprKind::Struct(ref qpath, fields, ref wth) => {
1476 self.print_expr_struct(qpath, fields, wth);
1478 hir::ExprKind::Tup(ref exprs) => {
1479 self.print_expr_tup(exprs);
1481 hir::ExprKind::Call(ref func, ref args) => {
1482 self.print_expr_call(&func, args);
1484 hir::ExprKind::MethodCall(ref segment, _, ref args, _) => {
1485 self.print_expr_method_call(segment, args);
1487 hir::ExprKind::Binary(op, ref lhs, ref rhs) => {
1488 self.print_expr_binary(op, &lhs, &rhs);
1490 hir::ExprKind::Unary(op, ref expr) => {
1491 self.print_expr_unary(op, &expr);
1493 hir::ExprKind::AddrOf(k, m, ref expr) => {
1494 self.print_expr_addr_of(k, m, &expr);
1496 hir::ExprKind::Lit(ref lit) => {
1497 self.print_literal(&lit);
1499 hir::ExprKind::Cast(ref expr, ref ty) => {
1500 let prec = AssocOp::As.precedence() as i8;
1501 self.print_expr_maybe_paren(&expr, prec);
1503 self.word_space("as");
1504 self.print_type(&ty);
1506 hir::ExprKind::Type(ref expr, ref ty) => {
1507 let prec = AssocOp::Colon.precedence() as i8;
1508 self.print_expr_maybe_paren(&expr, prec);
1509 self.word_space(":");
1510 self.print_type(&ty);
1512 hir::ExprKind::DropTemps(ref init) => {
1514 self.cbox(INDENT_UNIT);
1518 // Print `let _t = $init;`:
1519 let temp = Ident::from_str("_t");
1520 self.print_local(Some(init), |this| this.print_ident(temp));
1524 self.space_if_not_bol();
1525 self.print_ident(temp);
1528 self.bclose_maybe_open(expr.span, true);
1530 hir::ExprKind::If(ref test, ref blk, ref elseopt) => {
1531 self.print_if(&test, &blk, elseopt.as_ref().map(|e| &**e));
1533 hir::ExprKind::Loop(ref blk, opt_label, _, _) => {
1534 if let Some(label) = opt_label {
1535 self.print_ident(label.ident);
1536 self.word_space(":");
1540 self.print_block(&blk);
1542 hir::ExprKind::Match(ref expr, arms, _) => {
1543 self.cbox(INDENT_UNIT);
1544 self.ibox(INDENT_UNIT);
1545 self.word_nbsp("match");
1546 self.print_expr_as_cond(&expr);
1550 self.print_arm(arm);
1552 self.bclose(expr.span);
1554 hir::ExprKind::Closure(capture_clause, ref decl, body, _fn_decl_span, _gen) => {
1555 self.print_capture_clause(capture_clause);
1557 self.print_closure_params(&decl, body);
1560 // This is a bare expression.
1561 self.ann.nested(self, Nested::Body(body));
1562 self.end(); // need to close a box
1564 // A box will be closed by `print_expr`, but we didn't want an overall
1565 // wrapper so we closed the corresponding opening. so create an
1566 // empty box to satisfy the close.
1569 hir::ExprKind::Block(ref blk, opt_label) => {
1570 if let Some(label) = opt_label {
1571 self.print_ident(label.ident);
1572 self.word_space(":");
1574 // containing cbox, will be closed by print-block at `}`
1575 self.cbox(INDENT_UNIT);
1576 // head-box, will be closed by print-block after `{`
1578 self.print_block(&blk);
1580 hir::ExprKind::Assign(ref lhs, ref rhs, _) => {
1581 let prec = AssocOp::Assign.precedence() as i8;
1582 self.print_expr_maybe_paren(&lhs, prec + 1);
1584 self.word_space("=");
1585 self.print_expr_maybe_paren(&rhs, prec);
1587 hir::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
1588 let prec = AssocOp::Assign.precedence() as i8;
1589 self.print_expr_maybe_paren(&lhs, prec + 1);
1591 self.s.word(op.node.as_str());
1592 self.word_space("=");
1593 self.print_expr_maybe_paren(&rhs, prec);
1595 hir::ExprKind::Field(ref expr, ident) => {
1596 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
1598 self.print_ident(ident);
1600 hir::ExprKind::Index(ref expr, ref index) => {
1601 self.print_expr_maybe_paren(&expr, parser::PREC_POSTFIX);
1603 self.print_expr(&index);
1606 hir::ExprKind::Path(ref qpath) => self.print_qpath(qpath, true),
1607 hir::ExprKind::Break(destination, ref opt_expr) => {
1608 self.s.word("break");
1610 if let Some(label) = destination.label {
1611 self.print_ident(label.ident);
1614 if let Some(ref expr) = *opt_expr {
1615 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
1619 hir::ExprKind::Continue(destination) => {
1620 self.s.word("continue");
1622 if let Some(label) = destination.label {
1623 self.print_ident(label.ident);
1627 hir::ExprKind::Ret(ref result) => {
1628 self.s.word("return");
1629 if let Some(ref expr) = *result {
1631 self.print_expr_maybe_paren(&expr, parser::PREC_JUMP);
1634 hir::ExprKind::InlineAsm(ref asm) => {
1636 self.print_inline_asm(asm);
1638 hir::ExprKind::LlvmInlineAsm(ref a) => {
1640 self.s.word("llvm_asm!");
1642 self.print_symbol(i.asm, i.asm_str_style);
1643 self.word_space(":");
1645 let mut out_idx = 0;
1646 self.commasep(Inconsistent, &i.outputs, |s, out| {
1647 let constraint = out.constraint.as_str();
1648 let mut ch = constraint.chars();
1650 Some('=') if out.is_rw => {
1651 s.print_string(&format!("+{}", ch.as_str()), ast::StrStyle::Cooked)
1653 _ => s.print_string(&constraint, ast::StrStyle::Cooked),
1656 s.print_expr(&a.outputs_exprs[out_idx]);
1661 self.word_space(":");
1664 self.commasep(Inconsistent, &i.inputs, |s, &co| {
1665 s.print_symbol(co, ast::StrStyle::Cooked);
1667 s.print_expr(&a.inputs_exprs[in_idx]);
1672 self.word_space(":");
1674 self.commasep(Inconsistent, &i.clobbers, |s, &co| {
1675 s.print_symbol(co, ast::StrStyle::Cooked);
1678 let mut options = vec![];
1680 options.push("volatile");
1683 options.push("alignstack");
1685 if i.dialect == ast::LlvmAsmDialect::Intel {
1686 options.push("intel");
1689 if !options.is_empty() {
1691 self.word_space(":");
1692 self.commasep(Inconsistent, &options, |s, &co| {
1693 s.print_string(co, ast::StrStyle::Cooked);
1699 hir::ExprKind::Yield(ref expr, _) => {
1700 self.word_space("yield");
1701 self.print_expr_maybe_paren(&expr, parser::PREC_JUMP);
1703 hir::ExprKind::Err => {
1705 self.s.word("/*ERROR*/");
1709 self.ann.post(self, AnnNode::Expr(expr));
1713 pub fn print_local_decl(&mut self, loc: &hir::Local<'_>) {
1714 self.print_pat(&loc.pat);
1715 if let Some(ref ty) = loc.ty {
1716 self.word_space(":");
1717 self.print_type(&ty);
1721 pub fn print_name(&mut self, name: Symbol) {
1722 self.print_ident(Ident::with_dummy_span(name))
1725 pub fn print_path(&mut self, path: &hir::Path<'_>, colons_before_params: bool) {
1726 self.maybe_print_comment(path.span.lo());
1728 for (i, segment) in path.segments.iter().enumerate() {
1732 if segment.ident.name != kw::PathRoot {
1733 self.print_ident(segment.ident);
1734 self.print_generic_args(segment.args(), segment.infer_args, colons_before_params);
1739 pub fn print_path_segment(&mut self, segment: &hir::PathSegment<'_>) {
1740 if segment.ident.name != kw::PathRoot {
1741 self.print_ident(segment.ident);
1742 self.print_generic_args(segment.args(), segment.infer_args, false);
1746 pub fn print_qpath(&mut self, qpath: &hir::QPath<'_>, colons_before_params: bool) {
1748 hir::QPath::Resolved(None, ref path) => self.print_path(path, colons_before_params),
1749 hir::QPath::Resolved(Some(ref qself), ref path) => {
1751 self.print_type(qself);
1753 self.word_space("as");
1755 for (i, segment) in path.segments[..path.segments.len() - 1].iter().enumerate() {
1759 if segment.ident.name != kw::PathRoot {
1760 self.print_ident(segment.ident);
1761 self.print_generic_args(
1764 colons_before_params,
1771 let item_segment = path.segments.last().unwrap();
1772 self.print_ident(item_segment.ident);
1773 self.print_generic_args(
1774 item_segment.args(),
1775 item_segment.infer_args,
1776 colons_before_params,
1779 hir::QPath::TypeRelative(ref qself, ref item_segment) => {
1780 // If we've got a compound-qualified-path, let's push an additional pair of angle
1781 // brackets, so that we pretty-print `<<A::B>::C>` as `<A::B>::C`, instead of just
1782 // `A::B::C` (since the latter could be ambiguous to the user)
1783 if let hir::TyKind::Path(hir::QPath::Resolved(None, _)) = &qself.kind {
1784 self.print_type(qself);
1787 self.print_type(qself);
1792 self.print_ident(item_segment.ident);
1793 self.print_generic_args(
1794 item_segment.args(),
1795 item_segment.infer_args,
1796 colons_before_params,
1799 hir::QPath::LangItem(lang_item, span) => {
1800 self.s.word("#[lang = \"");
1801 self.print_ident(Ident::new(lang_item.name(), span));
1807 fn print_generic_args(
1809 generic_args: &hir::GenericArgs<'_>,
1811 colons_before_params: bool,
1813 if generic_args.parenthesized {
1815 self.commasep(Inconsistent, generic_args.inputs(), |s, ty| s.print_type(&ty));
1818 self.space_if_not_bol();
1819 self.word_space("->");
1820 self.print_type(generic_args.bindings[0].ty());
1822 let start = if colons_before_params { "::<" } else { "<" };
1823 let empty = Cell::new(true);
1824 let start_or_comma = |this: &mut Self| {
1829 this.word_space(",")
1833 let mut nonelided_generic_args: bool = false;
1834 let elide_lifetimes = generic_args.args.iter().all(|arg| match arg {
1835 GenericArg::Lifetime(lt) => lt.is_elided(),
1837 nonelided_generic_args = true;
1842 if nonelided_generic_args {
1843 start_or_comma(self);
1847 |s, generic_arg| match generic_arg {
1848 GenericArg::Lifetime(lt) if !elide_lifetimes => s.print_lifetime(lt),
1849 GenericArg::Lifetime(_) => {}
1850 GenericArg::Type(ty) => s.print_type(ty),
1851 GenericArg::Const(ct) => s.print_anon_const(&ct.value),
1856 // FIXME(eddyb): this would leak into error messages (e.g.,
1857 // "non-exhaustive patterns: `Some::<..>(_)` not covered").
1858 if infer_args && false {
1859 start_or_comma(self);
1863 for binding in generic_args.bindings.iter() {
1864 start_or_comma(self);
1865 self.print_ident(binding.ident);
1866 self.print_generic_args(binding.gen_args, false, false);
1868 match generic_args.bindings[0].kind {
1869 hir::TypeBindingKind::Equality { ref ty } => {
1870 self.word_space("=");
1871 self.print_type(ty);
1873 hir::TypeBindingKind::Constraint { bounds } => {
1874 self.print_bounds(":", bounds);
1885 pub fn print_pat(&mut self, pat: &hir::Pat<'_>) {
1886 self.maybe_print_comment(pat.span.lo());
1887 self.ann.pre(self, AnnNode::Pat(pat));
1888 // Pat isn't normalized, but the beauty of it
1889 // is that it doesn't matter
1891 PatKind::Wild => self.s.word("_"),
1892 PatKind::Binding(binding_mode, _, ident, ref sub) => {
1893 match binding_mode {
1894 hir::BindingAnnotation::Ref => {
1895 self.word_nbsp("ref");
1896 self.print_mutability(hir::Mutability::Not, false);
1898 hir::BindingAnnotation::RefMut => {
1899 self.word_nbsp("ref");
1900 self.print_mutability(hir::Mutability::Mut, false);
1902 hir::BindingAnnotation::Unannotated => {}
1903 hir::BindingAnnotation::Mutable => {
1904 self.word_nbsp("mut");
1907 self.print_ident(ident);
1908 if let Some(ref p) = *sub {
1913 PatKind::TupleStruct(ref qpath, ref elts, ddpos) => {
1914 self.print_qpath(qpath, true);
1916 if let Some(ddpos) = ddpos {
1917 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p));
1919 self.word_space(",");
1922 if ddpos != elts.len() {
1924 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p));
1927 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p));
1931 PatKind::Path(ref qpath) => {
1932 self.print_qpath(qpath, true);
1934 PatKind::Struct(ref qpath, ref fields, etc) => {
1935 self.print_qpath(qpath, true);
1937 self.word_space("{");
1942 s.cbox(INDENT_UNIT);
1943 if !f.is_shorthand {
1944 s.print_ident(f.ident);
1947 s.print_pat(&f.pat);
1953 if !fields.is_empty() {
1954 self.word_space(",");
1961 PatKind::Or(ref pats) => {
1962 self.strsep("|", true, Inconsistent, &pats[..], |s, p| s.print_pat(&p));
1964 PatKind::Tuple(ref elts, ddpos) => {
1966 if let Some(ddpos) = ddpos {
1967 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p));
1969 self.word_space(",");
1972 if ddpos != elts.len() {
1974 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p));
1977 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p));
1978 if elts.len() == 1 {
1984 PatKind::Box(ref inner) => {
1985 let is_range_inner = matches!(inner.kind, PatKind::Range(..));
1986 self.s.word("box ");
1990 self.print_pat(&inner);
1995 PatKind::Ref(ref inner, mutbl) => {
1996 let is_range_inner = matches!(inner.kind, PatKind::Range(..));
1998 self.s.word(mutbl.prefix_str());
2002 self.print_pat(&inner);
2007 PatKind::Lit(ref e) => self.print_expr(&e),
2008 PatKind::Range(ref begin, ref end, ref end_kind) => {
2009 if let Some(expr) = begin {
2010 self.print_expr(expr);
2014 RangeEnd::Included => self.s.word("..."),
2015 RangeEnd::Excluded => self.s.word(".."),
2017 if let Some(expr) = end {
2018 self.print_expr(expr);
2021 PatKind::Slice(ref before, ref slice, ref after) => {
2023 self.commasep(Inconsistent, &before[..], |s, p| s.print_pat(&p));
2024 if let Some(ref p) = *slice {
2025 if !before.is_empty() {
2026 self.word_space(",");
2028 if let PatKind::Wild = p.kind {
2034 if !after.is_empty() {
2035 self.word_space(",");
2038 self.commasep(Inconsistent, &after[..], |s, p| s.print_pat(&p));
2042 self.ann.post(self, AnnNode::Pat(pat))
2045 pub fn print_param(&mut self, arg: &hir::Param<'_>) {
2046 self.print_outer_attributes(self.attrs(arg.hir_id));
2047 self.print_pat(&arg.pat);
2050 pub fn print_arm(&mut self, arm: &hir::Arm<'_>) {
2051 // I have no idea why this check is necessary, but here it
2053 if self.attrs(arm.hir_id).is_empty() {
2056 self.cbox(INDENT_UNIT);
2057 self.ann.pre(self, AnnNode::Arm(arm));
2059 self.print_outer_attributes(&self.attrs(arm.hir_id));
2060 self.print_pat(&arm.pat);
2062 if let Some(ref g) = arm.guard {
2064 hir::Guard::If(e) => {
2065 self.word_space("if");
2066 self.print_expr(&e);
2069 hir::Guard::IfLet(pat, e) => {
2070 self.word_nbsp("if");
2071 self.word_nbsp("let");
2072 self.print_pat(&pat);
2074 self.word_space("=");
2075 self.print_expr(&e);
2080 self.word_space("=>");
2082 match arm.body.kind {
2083 hir::ExprKind::Block(ref blk, opt_label) => {
2084 if let Some(label) = opt_label {
2085 self.print_ident(label.ident);
2086 self.word_space(":");
2088 // the block will close the pattern's ibox
2089 self.print_block_unclosed(&blk);
2091 // If it is a user-provided unsafe block, print a comma after it
2092 if let hir::BlockCheckMode::UnsafeBlock(hir::UnsafeSource::UserProvided) = blk.rules
2098 self.end(); // close the ibox for the pattern
2099 self.print_expr(&arm.body);
2103 self.ann.post(self, AnnNode::Arm(arm));
2104 self.end() // close enclosing cbox
2109 decl: &hir::FnDecl<'_>,
2110 header: hir::FnHeader,
2111 name: Option<Symbol>,
2112 generics: &hir::Generics<'_>,
2113 vis: &hir::Visibility<'_>,
2114 arg_names: &[Ident],
2115 body_id: Option<hir::BodyId>,
2117 self.print_fn_header_info(header, vis);
2119 if let Some(name) = name {
2121 self.print_name(name);
2123 self.print_generic_params(&generics.params);
2127 // Make sure we aren't supplied *both* `arg_names` and `body_id`.
2128 assert!(arg_names.is_empty() || body_id.is_none());
2129 self.commasep(Inconsistent, &decl.inputs, |s, ty| {
2130 s.ibox(INDENT_UNIT);
2131 if let Some(arg_name) = arg_names.get(i) {
2132 s.s.word(arg_name.to_string());
2135 } else if let Some(body_id) = body_id {
2136 s.ann.nested(s, Nested::BodyParamPat(body_id, i));
2144 if decl.c_variadic {
2145 self.s.word(", ...");
2149 self.print_fn_output(decl);
2150 self.print_where_clause(&generics.where_clause)
2153 fn print_closure_params(&mut self, decl: &hir::FnDecl<'_>, body_id: hir::BodyId) {
2156 self.commasep(Inconsistent, &decl.inputs, |s, ty| {
2157 s.ibox(INDENT_UNIT);
2159 s.ann.nested(s, Nested::BodyParamPat(body_id, i));
2162 if let hir::TyKind::Infer = ty.kind {
2173 if let hir::FnRetTy::DefaultReturn(..) = decl.output {
2177 self.space_if_not_bol();
2178 self.word_space("->");
2180 hir::FnRetTy::Return(ref ty) => {
2181 self.print_type(&ty);
2182 self.maybe_print_comment(ty.span.lo())
2184 hir::FnRetTy::DefaultReturn(..) => unreachable!(),
2188 pub fn print_capture_clause(&mut self, capture_clause: hir::CaptureBy) {
2189 match capture_clause {
2190 hir::CaptureBy::Value => self.word_space("move"),
2191 hir::CaptureBy::Ref => {}
2195 pub fn print_bounds<'b>(
2197 prefix: &'static str,
2198 bounds: impl IntoIterator<Item = &'b hir::GenericBound<'b>>,
2200 let mut first = true;
2201 for bound in bounds {
2203 self.s.word(prefix);
2205 if !(first && prefix.is_empty()) {
2211 self.word_space("+");
2215 GenericBound::Trait(tref, modifier) => {
2216 if modifier == &TraitBoundModifier::Maybe {
2219 self.print_poly_trait_ref(tref);
2221 GenericBound::LangItemTrait(lang_item, span, ..) => {
2222 self.s.word("#[lang = \"");
2223 self.print_ident(Ident::new(lang_item.name(), *span));
2226 GenericBound::Outlives(lt) => {
2227 self.print_lifetime(lt);
2233 pub fn print_generic_params(&mut self, generic_params: &[GenericParam<'_>]) {
2234 if !generic_params.is_empty() {
2237 self.commasep(Inconsistent, generic_params, |s, param| s.print_generic_param(param));
2243 pub fn print_generic_param(&mut self, param: &GenericParam<'_>) {
2244 if let GenericParamKind::Const { .. } = param.kind {
2245 self.word_space("const");
2248 self.print_ident(param.name.ident());
2251 GenericParamKind::Lifetime { .. } => {
2253 for bound in param.bounds {
2255 GenericBound::Outlives(ref lt) => {
2257 self.print_lifetime(lt);
2264 GenericParamKind::Type { ref default, .. } => {
2265 self.print_bounds(":", param.bounds);
2266 if let Some(default) = default {
2268 self.word_space("=");
2269 self.print_type(&default)
2272 GenericParamKind::Const { ref ty, ref default } => {
2273 self.word_space(":");
2274 self.print_type(ty);
2275 if let Some(ref default) = default {
2277 self.word_space("=");
2278 self.print_anon_const(&default)
2284 pub fn print_lifetime(&mut self, lifetime: &hir::Lifetime) {
2285 self.print_ident(lifetime.name.ident())
2288 pub fn print_where_clause(&mut self, where_clause: &hir::WhereClause<'_>) {
2289 if where_clause.predicates.is_empty() {
2294 self.word_space("where");
2296 for (i, predicate) in where_clause.predicates.iter().enumerate() {
2298 self.word_space(",");
2302 hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
2303 bound_generic_params,
2308 self.print_formal_generic_params(bound_generic_params);
2309 self.print_type(&bounded_ty);
2310 self.print_bounds(":", *bounds);
2312 hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
2317 self.print_lifetime(lifetime);
2320 for (i, bound) in bounds.iter().enumerate() {
2322 GenericBound::Outlives(lt) => {
2323 self.print_lifetime(lt);
2333 hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
2336 self.print_type(lhs_ty);
2338 self.word_space("=");
2339 self.print_type(rhs_ty);
2345 pub fn print_mutability(&mut self, mutbl: hir::Mutability, print_const: bool) {
2347 hir::Mutability::Mut => self.word_nbsp("mut"),
2348 hir::Mutability::Not => {
2350 self.word_nbsp("const")
2356 pub fn print_mt(&mut self, mt: &hir::MutTy<'_>, print_const: bool) {
2357 self.print_mutability(mt.mutbl, print_const);
2358 self.print_type(&mt.ty)
2361 pub fn print_fn_output(&mut self, decl: &hir::FnDecl<'_>) {
2362 if let hir::FnRetTy::DefaultReturn(..) = decl.output {
2366 self.space_if_not_bol();
2367 self.ibox(INDENT_UNIT);
2368 self.word_space("->");
2370 hir::FnRetTy::DefaultReturn(..) => unreachable!(),
2371 hir::FnRetTy::Return(ref ty) => self.print_type(&ty),
2375 if let hir::FnRetTy::Return(ref output) = decl.output {
2376 self.maybe_print_comment(output.span.lo())
2383 unsafety: hir::Unsafety,
2384 decl: &hir::FnDecl<'_>,
2385 name: Option<Symbol>,
2386 generic_params: &[hir::GenericParam<'_>],
2387 arg_names: &[Ident],
2389 self.ibox(INDENT_UNIT);
2390 if !generic_params.is_empty() {
2392 self.print_generic_params(generic_params);
2394 let generics = hir::Generics {
2396 where_clause: hir::WhereClause { predicates: &[], span: rustc_span::DUMMY_SP },
2397 span: rustc_span::DUMMY_SP,
2404 constness: hir::Constness::NotConst,
2405 asyncness: hir::IsAsync::NotAsync,
2409 &Spanned { span: rustc_span::DUMMY_SP, node: hir::VisibilityKind::Inherited },
2416 pub fn maybe_print_trailing_comment(
2418 span: rustc_span::Span,
2419 next_pos: Option<BytePos>,
2421 if let Some(cmnts) = self.comments() {
2422 if let Some(cmnt) = cmnts.trailing_comment(span, next_pos) {
2423 self.print_comment(&cmnt);
2428 pub fn print_remaining_comments(&mut self) {
2429 // If there aren't any remaining comments, then we need to manually
2430 // make sure there is a line break at the end.
2431 if self.next_comment().is_none() {
2434 while let Some(ref cmnt) = self.next_comment() {
2435 self.print_comment(cmnt)
2439 pub fn print_fn_header_info(&mut self, header: hir::FnHeader, vis: &hir::Visibility<'_>) {
2440 self.s.word(visibility_qualified(vis, ""));
2442 match header.constness {
2443 hir::Constness::NotConst => {}
2444 hir::Constness::Const => self.word_nbsp("const"),
2447 match header.asyncness {
2448 hir::IsAsync::NotAsync => {}
2449 hir::IsAsync::Async => self.word_nbsp("async"),
2452 self.print_unsafety(header.unsafety);
2454 if header.abi != Abi::Rust {
2455 self.word_nbsp("extern");
2456 self.word_nbsp(header.abi.to_string());
2462 pub fn print_unsafety(&mut self, s: hir::Unsafety) {
2464 hir::Unsafety::Normal => {}
2465 hir::Unsafety::Unsafe => self.word_nbsp("unsafe"),
2469 pub fn print_is_auto(&mut self, s: hir::IsAuto) {
2471 hir::IsAuto::Yes => self.word_nbsp("auto"),
2472 hir::IsAuto::No => {}
2477 /// Does this expression require a semicolon to be treated
2478 /// as a statement? The negation of this: 'can this expression
2479 /// be used as a statement without a semicolon' -- is used
2480 /// as an early-bail-out in the parser so that, for instance,
2481 /// if true {...} else {...}
2483 /// isn't parsed as (if true {...} else {...} | x) | 5
2485 // Duplicated from `parse::classify`, but adapted for the HIR.
2486 fn expr_requires_semi_to_be_stmt(e: &hir::Expr<'_>) -> bool {
2489 hir::ExprKind::If(..)
2490 | hir::ExprKind::Match(..)
2491 | hir::ExprKind::Block(..)
2492 | hir::ExprKind::Loop(..)
2496 /// This statement requires a semicolon after it.
2497 /// note that in one case (stmt_semi), we've already
2498 /// seen the semicolon, and thus don't need another.
2499 fn stmt_ends_with_semi(stmt: &hir::StmtKind<'_>) -> bool {
2501 hir::StmtKind::Local(_) => true,
2502 hir::StmtKind::Item(_) => false,
2503 hir::StmtKind::Expr(ref e) => expr_requires_semi_to_be_stmt(&e),
2504 hir::StmtKind::Semi(..) => false,
2508 fn bin_op_to_assoc_op(op: hir::BinOpKind) -> AssocOp {
2509 use crate::hir::BinOpKind::*;
2511 Add => AssocOp::Add,
2512 Sub => AssocOp::Subtract,
2513 Mul => AssocOp::Multiply,
2514 Div => AssocOp::Divide,
2515 Rem => AssocOp::Modulus,
2517 And => AssocOp::LAnd,
2520 BitXor => AssocOp::BitXor,
2521 BitAnd => AssocOp::BitAnd,
2522 BitOr => AssocOp::BitOr,
2523 Shl => AssocOp::ShiftLeft,
2524 Shr => AssocOp::ShiftRight,
2526 Eq => AssocOp::Equal,
2527 Lt => AssocOp::Less,
2528 Le => AssocOp::LessEqual,
2529 Ne => AssocOp::NotEqual,
2530 Ge => AssocOp::GreaterEqual,
2531 Gt => AssocOp::Greater,
2535 /// Expressions that syntactically contain an "exterior" struct literal, i.e., not surrounded by any
2536 /// parens or other delimiters, e.g., `X { y: 1 }`, `X { y: 1 }.method()`, `foo == X { y: 1 }` and
2537 /// `X { y: 1 } == foo` all do, but `(X { y: 1 }) == foo` does not.
2538 fn contains_exterior_struct_lit(value: &hir::Expr<'_>) -> bool {
2540 hir::ExprKind::Struct(..) => true,
2542 hir::ExprKind::Assign(ref lhs, ref rhs, _)
2543 | hir::ExprKind::AssignOp(_, ref lhs, ref rhs)
2544 | hir::ExprKind::Binary(_, ref lhs, ref rhs) => {
2545 // `X { y: 1 } + X { y: 2 }`
2546 contains_exterior_struct_lit(&lhs) || contains_exterior_struct_lit(&rhs)
2548 hir::ExprKind::Unary(_, ref x)
2549 | hir::ExprKind::Cast(ref x, _)
2550 | hir::ExprKind::Type(ref x, _)
2551 | hir::ExprKind::Field(ref x, _)
2552 | hir::ExprKind::Index(ref x, _) => {
2553 // `&X { y: 1 }, X { y: 1 }.y`
2554 contains_exterior_struct_lit(&x)
2557 hir::ExprKind::MethodCall(.., ref exprs, _) => {
2558 // `X { y: 1 }.bar(...)`
2559 contains_exterior_struct_lit(&exprs[0])