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;
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),
40 BodyParamPat(hir::BodyId, usize),
44 fn nested(&self, _state: &mut State<'_>, _nested: Nested) {}
45 fn pre(&self, _state: &mut State<'_>, _node: AnnNode<'_>) {}
46 fn post(&self, _state: &mut State<'_>, _node: AnnNode<'_>) {}
50 impl PpAnn for NoAnn {}
51 pub const NO_ANN: &dyn PpAnn = &NoAnn;
53 impl PpAnn for hir::Crate<'_> {
54 fn nested(&self, state: &mut State<'_>, nested: Nested) {
56 Nested::Item(id) => state.print_item(self.item(id.id)),
57 Nested::TraitItem(id) => state.print_trait_item(self.trait_item(id)),
58 Nested::ImplItem(id) => state.print_impl_item(self.impl_item(id)),
59 Nested::Body(id) => state.print_expr(&self.body(id).value),
60 Nested::BodyParamPat(id, i) => state.print_pat(&self.body(id).params[i].pat),
65 /// Identical to the `PpAnn` implementation for `hir::Crate`,
66 /// except it avoids creating a dependency on the whole crate.
67 impl PpAnn for &dyn rustc_hir::intravisit::Map<'_> {
68 fn nested(&self, state: &mut State<'_>, nested: Nested) {
70 Nested::Item(id) => state.print_item(self.item(id.id)),
71 Nested::TraitItem(id) => state.print_trait_item(self.trait_item(id)),
72 Nested::ImplItem(id) => state.print_impl_item(self.impl_item(id)),
73 Nested::Body(id) => state.print_expr(&self.body(id).value),
74 Nested::BodyParamPat(id, i) => state.print_pat(&self.body(id).params[i].pat),
79 pub struct State<'a> {
81 comments: Option<Comments<'a>>,
82 ann: &'a (dyn PpAnn + 'a),
86 pub fn print_node(&mut self, node: Node<'_>) {
88 Node::Param(a) => self.print_param(&a),
89 Node::Item(a) => self.print_item(&a),
90 Node::ForeignItem(a) => self.print_foreign_item(&a),
91 Node::TraitItem(a) => self.print_trait_item(a),
92 Node::ImplItem(a) => self.print_impl_item(a),
93 Node::Variant(a) => self.print_variant(&a),
94 Node::AnonConst(a) => self.print_anon_const(&a),
95 Node::Expr(a) => self.print_expr(&a),
96 Node::Stmt(a) => self.print_stmt(&a),
97 Node::PathSegment(a) => self.print_path_segment(&a),
98 Node::Ty(a) => self.print_type(&a),
99 Node::TraitRef(a) => self.print_trait_ref(&a),
100 Node::Binding(a) | Node::Pat(a) => self.print_pat(&a),
101 Node::Arm(a) => self.print_arm(&a),
103 // Containing cbox, will be closed by print-block at `}`.
104 self.cbox(INDENT_UNIT);
105 // Head-ibox, will be closed by print-block after `{`.
109 Node::Lifetime(a) => self.print_lifetime(&a),
110 Node::Visibility(a) => self.print_visibility(&a),
111 Node::GenericParam(_) => panic!("cannot print Node::GenericParam"),
112 Node::Field(_) => panic!("cannot print StructField"),
113 // These cases do not carry enough information in the
114 // `hir_map` to reconstruct their full structure for pretty
116 Node::Ctor(..) => panic!("cannot print isolated Ctor"),
117 Node::Local(a) => self.print_local_decl(&a),
118 Node::MacroDef(_) => panic!("cannot print MacroDef"),
119 Node::Crate(..) => panic!("cannot print Crate"),
124 impl std::ops::Deref for State<'_> {
125 type Target = pp::Printer;
126 fn deref(&self) -> &Self::Target {
131 impl std::ops::DerefMut for State<'_> {
132 fn deref_mut(&mut self) -> &mut Self::Target {
137 impl<'a> PrintState<'a> for State<'a> {
138 fn insert_extra_parens(&self) -> bool {
141 fn comments(&mut self) -> &mut Option<Comments<'a>> {
145 fn print_ident(&mut self, ident: Ident) {
146 self.s.word(IdentPrinter::for_ast_ident(ident, ident.is_raw_guess()).to_string());
147 self.ann.post(self, AnnNode::Name(&ident.name))
150 fn print_generic_args(&mut self, _: &ast::GenericArgs, _colons_before_params: bool) {
151 panic!("AST generic args printed by HIR pretty-printer");
155 pub const INDENT_UNIT: usize = 4;
157 /// Requires you to pass an input filename and reader so that
158 /// it can scan the input text for comments to copy forward.
159 pub fn print_crate<'a>(
161 krate: &hir::Crate<'_>,
166 let mut s = State::new_from_input(sm, filename, input, ann);
168 // When printing the AST, we sometimes need to inject `#[no_std]` here.
169 // Since you can't compile the HIR, it's not necessary.
171 s.print_mod(&krate.item.module, &krate.item.attrs);
172 s.print_remaining_comments();
177 pub fn new_from_input(
183 State { s: pp::mk_printer(), comments: Some(Comments::new(sm, filename, input)), ann }
187 pub fn to_string<F>(ann: &dyn PpAnn, f: F) -> String
189 F: FnOnce(&mut State<'_>),
191 let mut printer = State { s: pp::mk_printer(), comments: None, ann };
196 pub fn visibility_qualified<S: Into<Cow<'static, str>>>(vis: &hir::Visibility<'_>, w: S) -> String {
197 to_string(NO_ANN, |s| {
198 s.print_visibility(vis);
203 pub fn generic_params_to_string(generic_params: &[GenericParam<'_>]) -> String {
204 to_string(NO_ANN, |s| s.print_generic_params(generic_params))
207 pub fn bounds_to_string<'b>(bounds: impl IntoIterator<Item = &'b hir::GenericBound<'b>>) -> String {
208 to_string(NO_ANN, |s| s.print_bounds("", bounds))
211 pub fn param_to_string(arg: &hir::Param<'_>) -> String {
212 to_string(NO_ANN, |s| s.print_param(arg))
215 pub fn ty_to_string(ty: &hir::Ty<'_>) -> String {
216 to_string(NO_ANN, |s| s.print_type(ty))
219 pub fn path_segment_to_string(segment: &hir::PathSegment<'_>) -> String {
220 to_string(NO_ANN, |s| s.print_path_segment(segment))
223 pub fn path_to_string(segment: &hir::Path<'_>) -> String {
224 to_string(NO_ANN, |s| s.print_path(segment, false))
228 decl: &hir::FnDecl<'_>,
229 header: hir::FnHeader,
230 name: Option<Symbol>,
231 generics: &hir::Generics<'_>,
232 vis: &hir::Visibility<'_>,
234 body_id: Option<hir::BodyId>,
236 to_string(NO_ANN, |s| s.print_fn(decl, header, name, generics, vis, arg_names, body_id))
239 pub fn enum_def_to_string(
240 enum_definition: &hir::EnumDef<'_>,
241 generics: &hir::Generics<'_>,
243 span: rustc_span::Span,
244 visibility: &hir::Visibility<'_>,
246 to_string(NO_ANN, |s| s.print_enum_def(enum_definition, generics, name, span, visibility))
250 pub fn cbox(&mut self, u: usize) {
254 pub fn nbsp(&mut self) {
258 pub fn word_nbsp<S: Into<Cow<'static, str>>>(&mut self, w: S) {
263 pub fn head<S: Into<Cow<'static, str>>>(&mut self, w: S) {
265 // outer-box is consistent
266 self.cbox(INDENT_UNIT);
267 // head-box is inconsistent
268 self.ibox(w.len() + 1);
269 // keyword that starts the head
275 pub fn bopen(&mut self) {
277 self.end(); // close the head-box
280 pub fn bclose_maybe_open(&mut self, span: rustc_span::Span, close_box: bool) {
281 self.maybe_print_comment(span.hi());
282 self.break_offset_if_not_bol(1, -(INDENT_UNIT as isize));
285 self.end(); // close the outer-box
289 pub fn bclose(&mut self, span: rustc_span::Span) {
290 self.bclose_maybe_open(span, true)
293 pub fn space_if_not_bol(&mut self) {
294 if !self.s.is_beginning_of_line() {
299 pub fn break_offset_if_not_bol(&mut self, n: usize, off: isize) {
300 if !self.s.is_beginning_of_line() {
301 self.s.break_offset(n, off)
302 } else if off != 0 && self.s.last_token().is_hardbreak_tok() {
303 // We do something pretty sketchy here: tuck the nonzero
304 // offset-adjustment we were going to deposit along with the
305 // break into the previous hardbreak.
306 self.s.replace_last_token(pp::Printer::hardbreak_tok_offset(off));
310 // Synthesizes a comment that was not textually present in the original source
312 pub fn synth_comment(&mut self, text: String) {
320 pub fn commasep_cmnt<T, F, G>(&mut self, b: Breaks, elts: &[T], mut op: F, mut get_span: G)
322 F: FnMut(&mut State<'_>, &T),
323 G: FnMut(&T) -> rustc_span::Span,
326 let len = elts.len();
329 self.maybe_print_comment(get_span(elt).hi());
334 self.maybe_print_trailing_comment(get_span(elt), Some(get_span(&elts[i]).hi()));
335 self.space_if_not_bol();
341 pub fn commasep_exprs(&mut self, b: Breaks, exprs: &[hir::Expr<'_>]) {
342 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(&e), |e| e.span)
345 pub fn print_mod(&mut self, _mod: &hir::Mod<'_>, attrs: &[ast::Attribute]) {
346 self.print_inner_attributes(attrs);
347 for &item_id in _mod.item_ids {
348 self.ann.nested(self, Nested::Item(item_id));
352 pub fn print_foreign_mod(&mut self, nmod: &hir::ForeignMod<'_>, attrs: &[ast::Attribute]) {
353 self.print_inner_attributes(attrs);
354 for item in nmod.items {
355 self.print_foreign_item(item);
359 pub fn print_opt_lifetime(&mut self, lifetime: &hir::Lifetime) {
360 if !lifetime.is_elided() {
361 self.print_lifetime(lifetime);
366 pub fn print_type(&mut self, ty: &hir::Ty<'_>) {
367 self.maybe_print_comment(ty.span.lo());
370 hir::TyKind::Slice(ref ty) => {
372 self.print_type(&ty);
375 hir::TyKind::Ptr(ref mt) => {
377 self.print_mt(mt, true);
379 hir::TyKind::Rptr(ref lifetime, ref mt) => {
381 self.print_opt_lifetime(lifetime);
382 self.print_mt(mt, false);
384 hir::TyKind::Never => {
387 hir::TyKind::Tup(ref elts) => {
389 self.commasep(Inconsistent, &elts[..], |s, ty| s.print_type(&ty));
395 hir::TyKind::BareFn(ref f) => {
405 hir::TyKind::OpaqueDef(..) => self.s.word("/*impl Trait*/"),
406 hir::TyKind::Path(ref qpath) => self.print_qpath(qpath, false),
407 hir::TyKind::TraitObject(bounds, ref lifetime) => {
408 let mut first = true;
409 for bound in bounds {
414 self.word_space("+");
416 self.print_poly_trait_ref(bound);
418 if !lifetime.is_elided() {
420 self.word_space("+");
421 self.print_lifetime(lifetime);
424 hir::TyKind::Array(ref ty, ref length) => {
426 self.print_type(&ty);
428 self.print_anon_const(length);
431 hir::TyKind::Typeof(ref e) => {
432 self.s.word("typeof(");
433 self.print_anon_const(e);
436 hir::TyKind::Infer => {
439 hir::TyKind::Err => {
441 self.s.word("/*ERROR*/");
448 pub fn print_foreign_item(&mut self, item: &hir::ForeignItem<'_>) {
449 self.hardbreak_if_not_bol();
450 self.maybe_print_comment(item.span.lo());
451 self.print_outer_attributes(&item.attrs);
453 hir::ForeignItemKind::Fn(ref decl, ref arg_names, ref generics) => {
458 unsafety: hir::Unsafety::Normal,
459 constness: hir::Constness::NotConst,
461 asyncness: hir::IsAsync::NotAsync,
463 Some(item.ident.name),
469 self.end(); // end head-ibox
471 self.end() // end the outer fn box
473 hir::ForeignItemKind::Static(ref t, m) => {
474 self.head(visibility_qualified(&item.vis, "static"));
475 if m == hir::Mutability::Mut {
476 self.word_space("mut");
478 self.print_ident(item.ident);
479 self.word_space(":");
482 self.end(); // end the head-ibox
483 self.end() // end the outer cbox
485 hir::ForeignItemKind::Type => {
486 self.head(visibility_qualified(&item.vis, "type"));
487 self.print_ident(item.ident);
489 self.end(); // end the head-ibox
490 self.end() // end the outer cbox
495 fn print_associated_const(
499 default: Option<hir::BodyId>,
500 vis: &hir::Visibility<'_>,
502 self.s.word(visibility_qualified(vis, ""));
503 self.word_space("const");
504 self.print_ident(ident);
505 self.word_space(":");
507 if let Some(expr) = default {
509 self.word_space("=");
510 self.ann.nested(self, Nested::Body(expr));
515 fn print_associated_type(
518 generics: &hir::Generics<'_>,
519 bounds: Option<hir::GenericBounds<'_>>,
520 ty: Option<&hir::Ty<'_>>,
522 self.word_space("type");
523 self.print_ident(ident);
524 self.print_generic_params(&generics.params);
525 if let Some(bounds) = bounds {
526 self.print_bounds(":", bounds);
528 self.print_where_clause(&generics.where_clause);
529 if let Some(ty) = ty {
531 self.word_space("=");
539 item: &hir::Item<'_>,
540 generics: &hir::Generics<'_>,
541 inner: impl Fn(&mut Self),
543 self.head(visibility_qualified(&item.vis, "type"));
544 self.print_ident(item.ident);
545 self.print_generic_params(&generics.params);
546 self.end(); // end the inner ibox
548 self.print_where_clause(&generics.where_clause);
552 self.end(); // end the outer ibox
555 /// Pretty-print an item
556 pub fn print_item(&mut self, item: &hir::Item<'_>) {
557 self.hardbreak_if_not_bol();
558 self.maybe_print_comment(item.span.lo());
559 self.print_outer_attributes(&item.attrs);
560 self.ann.pre(self, AnnNode::Item(item));
562 hir::ItemKind::ExternCrate(orig_name) => {
563 self.head(visibility_qualified(&item.vis, "extern crate"));
564 if let Some(orig_name) = orig_name {
565 self.print_name(orig_name);
570 self.print_ident(item.ident);
572 self.end(); // end inner head-block
573 self.end(); // end outer head-block
575 hir::ItemKind::Use(ref path, kind) => {
576 self.head(visibility_qualified(&item.vis, "use"));
577 self.print_path(path, false);
580 hir::UseKind::Single => {
581 if path.segments.last().unwrap().ident != item.ident {
583 self.word_space("as");
584 self.print_ident(item.ident);
588 hir::UseKind::Glob => self.s.word("::*;"),
589 hir::UseKind::ListStem => self.s.word("::{};"),
591 self.end(); // end inner head-block
592 self.end(); // end outer head-block
594 hir::ItemKind::Static(ref ty, m, expr) => {
595 self.head(visibility_qualified(&item.vis, "static"));
596 if m == hir::Mutability::Mut {
597 self.word_space("mut");
599 self.print_ident(item.ident);
600 self.word_space(":");
601 self.print_type(&ty);
603 self.end(); // end the head-ibox
605 self.word_space("=");
606 self.ann.nested(self, Nested::Body(expr));
608 self.end(); // end the outer cbox
610 hir::ItemKind::Const(ref ty, expr) => {
611 self.head(visibility_qualified(&item.vis, "const"));
612 self.print_ident(item.ident);
613 self.word_space(":");
614 self.print_type(&ty);
616 self.end(); // end the head-ibox
618 self.word_space("=");
619 self.ann.nested(self, Nested::Body(expr));
621 self.end(); // end the outer cbox
623 hir::ItemKind::Fn(ref sig, ref param_names, body) => {
628 Some(item.ident.name),
635 self.end(); // need to close a box
636 self.end(); // need to close a box
637 self.ann.nested(self, Nested::Body(body));
639 hir::ItemKind::Mod(ref _mod) => {
640 self.head(visibility_qualified(&item.vis, "mod"));
641 self.print_ident(item.ident);
644 self.print_mod(_mod, &item.attrs);
645 self.bclose(item.span);
647 hir::ItemKind::ForeignMod(ref nmod) => {
649 self.word_nbsp(nmod.abi.to_string());
651 self.print_foreign_mod(nmod, &item.attrs);
652 self.bclose(item.span);
654 hir::ItemKind::GlobalAsm(ref ga) => {
655 self.head(visibility_qualified(&item.vis, "global asm"));
656 self.s.word(ga.asm.to_string());
659 hir::ItemKind::TyAlias(ref ty, ref generics) => {
660 self.print_item_type(item, &generics, |state| {
661 state.word_space("=");
662 state.print_type(&ty);
665 hir::ItemKind::OpaqueTy(ref opaque_ty) => {
666 self.print_item_type(item, &opaque_ty.generics, |state| {
667 let mut real_bounds = Vec::with_capacity(opaque_ty.bounds.len());
668 for b in opaque_ty.bounds.iter() {
669 if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
671 state.word_space("for ?");
672 state.print_trait_ref(&ptr.trait_ref);
677 state.print_bounds("= impl", real_bounds);
680 hir::ItemKind::Enum(ref enum_definition, ref params) => {
681 self.print_enum_def(enum_definition, params, item.ident.name, item.span, &item.vis);
683 hir::ItemKind::Struct(ref struct_def, ref generics) => {
684 self.head(visibility_qualified(&item.vis, "struct"));
685 self.print_struct(struct_def, generics, item.ident.name, item.span, true);
687 hir::ItemKind::Union(ref struct_def, ref generics) => {
688 self.head(visibility_qualified(&item.vis, "union"));
689 self.print_struct(struct_def, generics, item.ident.name, item.span, true);
691 hir::ItemKind::Impl {
703 self.print_visibility(&item.vis);
704 self.print_defaultness(defaultness);
705 self.print_unsafety(unsafety);
706 self.word_nbsp("impl");
708 if !generics.params.is_empty() {
709 self.print_generic_params(&generics.params);
713 if constness == hir::Constness::Const {
714 self.word_nbsp("const");
717 if let hir::ImplPolarity::Negative(_) = polarity {
721 if let Some(ref t) = of_trait {
722 self.print_trait_ref(t);
724 self.word_space("for");
727 self.print_type(&self_ty);
728 self.print_where_clause(&generics.where_clause);
732 self.print_inner_attributes(&item.attrs);
733 for impl_item in items {
734 self.ann.nested(self, Nested::ImplItem(impl_item.id));
736 self.bclose(item.span);
738 hir::ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, trait_items) => {
740 self.print_visibility(&item.vis);
741 self.print_is_auto(is_auto);
742 self.print_unsafety(unsafety);
743 self.word_nbsp("trait");
744 self.print_ident(item.ident);
745 self.print_generic_params(&generics.params);
746 let mut real_bounds = Vec::with_capacity(bounds.len());
747 for b in bounds.iter() {
748 if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
750 self.word_space("for ?");
751 self.print_trait_ref(&ptr.trait_ref);
756 self.print_bounds(":", real_bounds);
757 self.print_where_clause(&generics.where_clause);
760 for trait_item in trait_items {
761 self.ann.nested(self, Nested::TraitItem(trait_item.id));
763 self.bclose(item.span);
765 hir::ItemKind::TraitAlias(ref generics, ref bounds) => {
767 self.print_visibility(&item.vis);
768 self.word_nbsp("trait");
769 self.print_ident(item.ident);
770 self.print_generic_params(&generics.params);
771 let mut real_bounds = Vec::with_capacity(bounds.len());
772 // FIXME(durka) this seems to be some quite outdated syntax
773 for b in bounds.iter() {
774 if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
776 self.word_space("for ?");
777 self.print_trait_ref(&ptr.trait_ref);
783 self.print_bounds("=", real_bounds);
784 self.print_where_clause(&generics.where_clause);
788 self.ann.post(self, AnnNode::Item(item))
791 pub fn print_trait_ref(&mut self, t: &hir::TraitRef<'_>) {
792 self.print_path(&t.path, false)
795 fn print_formal_generic_params(&mut self, generic_params: &[hir::GenericParam<'_>]) {
796 if !generic_params.is_empty() {
798 self.print_generic_params(generic_params);
803 fn print_poly_trait_ref(&mut self, t: &hir::PolyTraitRef<'_>) {
804 self.print_formal_generic_params(&t.bound_generic_params);
805 self.print_trait_ref(&t.trait_ref)
808 pub fn print_enum_def(
810 enum_definition: &hir::EnumDef<'_>,
811 generics: &hir::Generics<'_>,
813 span: rustc_span::Span,
814 visibility: &hir::Visibility<'_>,
816 self.head(visibility_qualified(visibility, "enum"));
817 self.print_name(name);
818 self.print_generic_params(&generics.params);
819 self.print_where_clause(&generics.where_clause);
821 self.print_variants(&enum_definition.variants, span)
824 pub fn print_variants(&mut self, variants: &[hir::Variant<'_>], span: rustc_span::Span) {
827 self.space_if_not_bol();
828 self.maybe_print_comment(v.span.lo());
829 self.print_outer_attributes(&v.attrs);
830 self.ibox(INDENT_UNIT);
831 self.print_variant(v);
834 self.maybe_print_trailing_comment(v.span, None);
839 pub fn print_visibility(&mut self, vis: &hir::Visibility<'_>) {
841 hir::VisibilityKind::Public => self.word_nbsp("pub"),
842 hir::VisibilityKind::Crate(ast::CrateSugar::JustCrate) => self.word_nbsp("crate"),
843 hir::VisibilityKind::Crate(ast::CrateSugar::PubCrate) => self.word_nbsp("pub(crate)"),
844 hir::VisibilityKind::Restricted { ref path, .. } => {
846 if path.segments.len() == 1 && path.segments[0].ident.name == kw::Super {
847 // Special case: `super` can print like `pub(super)`.
848 self.s.word("super");
850 // Everything else requires `in` at present.
851 self.word_nbsp("in");
852 self.print_path(path, false);
856 hir::VisibilityKind::Inherited => (),
860 pub fn print_defaultness(&mut self, defaultness: hir::Defaultness) {
862 hir::Defaultness::Default { .. } => self.word_nbsp("default"),
863 hir::Defaultness::Final => (),
869 struct_def: &hir::VariantData<'_>,
870 generics: &hir::Generics<'_>,
872 span: rustc_span::Span,
873 print_finalizer: bool,
875 self.print_name(name);
876 self.print_generic_params(&generics.params);
878 hir::VariantData::Tuple(..) | hir::VariantData::Unit(..) => {
879 if let hir::VariantData::Tuple(..) = struct_def {
881 self.commasep(Inconsistent, struct_def.fields(), |s, field| {
882 s.maybe_print_comment(field.span.lo());
883 s.print_outer_attributes(&field.attrs);
884 s.print_visibility(&field.vis);
885 s.print_type(&field.ty)
889 self.print_where_clause(&generics.where_clause);
894 self.end() // close the outer-box
896 hir::VariantData::Struct(..) => {
897 self.print_where_clause(&generics.where_clause);
900 self.hardbreak_if_not_bol();
902 for field in struct_def.fields() {
903 self.hardbreak_if_not_bol();
904 self.maybe_print_comment(field.span.lo());
905 self.print_outer_attributes(&field.attrs);
906 self.print_visibility(&field.vis);
907 self.print_ident(field.ident);
909 self.print_type(&field.ty);
918 pub fn print_variant(&mut self, v: &hir::Variant<'_>) {
920 let generics = hir::Generics::empty();
921 self.print_struct(&v.data, &generics, v.ident.name, v.span, false);
922 if let Some(ref d) = v.disr_expr {
924 self.word_space("=");
925 self.print_anon_const(d);
928 pub fn print_method_sig(
932 generics: &hir::Generics<'_>,
933 vis: &hir::Visibility<'_>,
935 body_id: Option<hir::BodyId>,
937 self.print_fn(&m.decl, m.header, Some(ident.name), generics, vis, arg_names, body_id)
940 pub fn print_trait_item(&mut self, ti: &hir::TraitItem<'_>) {
941 self.ann.pre(self, AnnNode::SubItem(ti.hir_id));
942 self.hardbreak_if_not_bol();
943 self.maybe_print_comment(ti.span.lo());
944 self.print_outer_attributes(&ti.attrs);
946 hir::TraitItemKind::Const(ref ty, default) => {
948 Spanned { span: rustc_span::DUMMY_SP, node: hir::VisibilityKind::Inherited };
949 self.print_associated_const(ti.ident, &ty, default, &vis);
951 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Required(ref arg_names)) => {
953 Spanned { span: rustc_span::DUMMY_SP, node: hir::VisibilityKind::Inherited };
954 self.print_method_sig(ti.ident, sig, &ti.generics, &vis, arg_names, None);
957 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Provided(body)) => {
959 Spanned { span: rustc_span::DUMMY_SP, node: hir::VisibilityKind::Inherited };
961 self.print_method_sig(ti.ident, sig, &ti.generics, &vis, &[], Some(body));
963 self.end(); // need to close a box
964 self.end(); // need to close a box
965 self.ann.nested(self, Nested::Body(body));
967 hir::TraitItemKind::Type(ref bounds, ref default) => {
968 self.print_associated_type(
972 default.as_ref().map(|ty| &**ty),
976 self.ann.post(self, AnnNode::SubItem(ti.hir_id))
979 pub fn print_impl_item(&mut self, ii: &hir::ImplItem<'_>) {
980 self.ann.pre(self, AnnNode::SubItem(ii.hir_id));
981 self.hardbreak_if_not_bol();
982 self.maybe_print_comment(ii.span.lo());
983 self.print_outer_attributes(&ii.attrs);
984 self.print_defaultness(ii.defaultness);
987 hir::ImplItemKind::Const(ref ty, expr) => {
988 self.print_associated_const(ii.ident, &ty, Some(expr), &ii.vis);
990 hir::ImplItemKind::Fn(ref sig, body) => {
992 self.print_method_sig(ii.ident, sig, &ii.generics, &ii.vis, &[], Some(body));
994 self.end(); // need to close a box
995 self.end(); // need to close a box
996 self.ann.nested(self, Nested::Body(body));
998 hir::ImplItemKind::TyAlias(ref ty) => {
999 self.print_associated_type(ii.ident, &ii.generics, None, Some(ty));
1002 self.ann.post(self, AnnNode::SubItem(ii.hir_id))
1005 pub fn print_local(&mut self, init: Option<&hir::Expr<'_>>, decl: impl Fn(&mut Self)) {
1006 self.space_if_not_bol();
1007 self.ibox(INDENT_UNIT);
1008 self.word_nbsp("let");
1010 self.ibox(INDENT_UNIT);
1014 if let Some(ref init) = init {
1016 self.word_space("=");
1017 self.print_expr(&init);
1022 pub fn print_stmt(&mut self, st: &hir::Stmt<'_>) {
1023 self.maybe_print_comment(st.span.lo());
1025 hir::StmtKind::Local(ref loc) => {
1026 self.print_local(loc.init.as_deref(), |this| this.print_local_decl(&loc));
1028 hir::StmtKind::Item(item) => self.ann.nested(self, Nested::Item(item)),
1029 hir::StmtKind::Expr(ref expr) => {
1030 self.space_if_not_bol();
1031 self.print_expr(&expr);
1033 hir::StmtKind::Semi(ref expr) => {
1034 self.space_if_not_bol();
1035 self.print_expr(&expr);
1039 if stmt_ends_with_semi(&st.kind) {
1042 self.maybe_print_trailing_comment(st.span, None)
1045 pub fn print_block(&mut self, blk: &hir::Block<'_>) {
1046 self.print_block_with_attrs(blk, &[])
1049 pub fn print_block_unclosed(&mut self, blk: &hir::Block<'_>) {
1050 self.print_block_maybe_unclosed(blk, &[], false)
1053 pub fn print_block_with_attrs(&mut self, blk: &hir::Block<'_>, attrs: &[ast::Attribute]) {
1054 self.print_block_maybe_unclosed(blk, attrs, true)
1057 pub fn print_block_maybe_unclosed(
1059 blk: &hir::Block<'_>,
1060 attrs: &[ast::Attribute],
1064 hir::BlockCheckMode::UnsafeBlock(..) => self.word_space("unsafe"),
1065 hir::BlockCheckMode::PushUnsafeBlock(..) => self.word_space("push_unsafe"),
1066 hir::BlockCheckMode::PopUnsafeBlock(..) => self.word_space("pop_unsafe"),
1067 hir::BlockCheckMode::DefaultBlock => (),
1069 self.maybe_print_comment(blk.span.lo());
1070 self.ann.pre(self, AnnNode::Block(blk));
1073 self.print_inner_attributes(attrs);
1075 for st in blk.stmts {
1076 self.print_stmt(st);
1078 if let Some(ref expr) = blk.expr {
1079 self.space_if_not_bol();
1080 self.print_expr(&expr);
1081 self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi()));
1083 self.bclose_maybe_open(blk.span, close_box);
1084 self.ann.post(self, AnnNode::Block(blk))
1087 pub fn print_anon_const(&mut self, constant: &hir::AnonConst) {
1088 self.ann.nested(self, Nested::Body(constant.body))
1091 fn print_call_post(&mut self, args: &[hir::Expr<'_>]) {
1093 self.commasep_exprs(Inconsistent, args);
1097 pub fn print_expr_maybe_paren(&mut self, expr: &hir::Expr<'_>, prec: i8) {
1098 let needs_par = expr.precedence().order() < prec;
1102 self.print_expr(expr);
1108 /// Print an expr using syntax that's acceptable in a condition position, such as the `cond` in
1109 /// `if cond { ... }`.
1110 pub fn print_expr_as_cond(&mut self, expr: &hir::Expr<'_>) {
1111 let needs_par = match expr.kind {
1112 // These cases need parens due to the parse error observed in #26461: `if return {}`
1113 // parses as the erroneous construct `if (return {})`, not `if (return) {}`.
1114 hir::ExprKind::Closure(..) | hir::ExprKind::Ret(..) | hir::ExprKind::Break(..) => true,
1116 _ => contains_exterior_struct_lit(expr),
1122 self.print_expr(expr);
1128 fn print_expr_vec(&mut self, exprs: &[hir::Expr<'_>]) {
1129 self.ibox(INDENT_UNIT);
1131 self.commasep_exprs(Inconsistent, exprs);
1136 fn print_expr_anon_const(&mut self, anon_const: &hir::AnonConst) {
1137 self.ibox(INDENT_UNIT);
1138 self.s.word_space("const");
1139 self.print_anon_const(anon_const);
1143 fn print_expr_repeat(&mut self, element: &hir::Expr<'_>, count: &hir::AnonConst) {
1144 self.ibox(INDENT_UNIT);
1146 self.print_expr(element);
1147 self.word_space(";");
1148 self.print_anon_const(count);
1153 fn print_expr_struct(
1155 qpath: &hir::QPath<'_>,
1156 fields: &[hir::Field<'_>],
1157 wth: &Option<&hir::Expr<'_>>,
1159 self.print_qpath(qpath, true);
1165 s.ibox(INDENT_UNIT);
1166 if !field.is_shorthand {
1167 s.print_ident(field.ident);
1170 s.print_expr(&field.expr);
1177 self.ibox(INDENT_UNIT);
1178 if !fields.is_empty() {
1183 self.print_expr(&expr);
1187 if !fields.is_empty() {
1195 fn print_expr_tup(&mut self, exprs: &[hir::Expr<'_>]) {
1197 self.commasep_exprs(Inconsistent, exprs);
1198 if exprs.len() == 1 {
1204 fn print_expr_call(&mut self, func: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
1205 let prec = match func.kind {
1206 hir::ExprKind::Field(..) => parser::PREC_FORCE_PAREN,
1207 _ => parser::PREC_POSTFIX,
1210 self.print_expr_maybe_paren(func, prec);
1211 self.print_call_post(args)
1214 fn print_expr_method_call(&mut self, segment: &hir::PathSegment<'_>, args: &[hir::Expr<'_>]) {
1215 let base_args = &args[1..];
1216 self.print_expr_maybe_paren(&args[0], parser::PREC_POSTFIX);
1218 self.print_ident(segment.ident);
1220 let generic_args = segment.generic_args();
1221 if !generic_args.args.is_empty() || !generic_args.bindings.is_empty() {
1222 self.print_generic_args(generic_args, segment.infer_args, true);
1225 self.print_call_post(base_args)
1228 fn print_expr_binary(&mut self, op: hir::BinOp, lhs: &hir::Expr<'_>, rhs: &hir::Expr<'_>) {
1229 let assoc_op = bin_op_to_assoc_op(op.node);
1230 let prec = assoc_op.precedence() as i8;
1231 let fixity = assoc_op.fixity();
1233 let (left_prec, right_prec) = match fixity {
1234 Fixity::Left => (prec, prec + 1),
1235 Fixity::Right => (prec + 1, prec),
1236 Fixity::None => (prec + 1, prec + 1),
1239 let left_prec = match (&lhs.kind, op.node) {
1240 // These cases need parens: `x as i32 < y` has the parser thinking that `i32 < y` is
1241 // the beginning of a path type. It starts trying to parse `x as (i32 < y ...` instead
1242 // of `(x as i32) < ...`. We need to convince it _not_ to do that.
1243 (&hir::ExprKind::Cast { .. }, hir::BinOpKind::Lt | hir::BinOpKind::Shl) => {
1244 parser::PREC_FORCE_PAREN
1249 self.print_expr_maybe_paren(lhs, left_prec);
1251 self.word_space(op.node.as_str());
1252 self.print_expr_maybe_paren(rhs, right_prec)
1255 fn print_expr_unary(&mut self, op: hir::UnOp, expr: &hir::Expr<'_>) {
1256 self.s.word(op.as_str());
1257 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1260 fn print_expr_addr_of(
1262 kind: hir::BorrowKind,
1263 mutability: hir::Mutability,
1264 expr: &hir::Expr<'_>,
1268 hir::BorrowKind::Ref => self.print_mutability(mutability, false),
1269 hir::BorrowKind::Raw => {
1270 self.word_nbsp("raw");
1271 self.print_mutability(mutability, true);
1274 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1277 fn print_literal(&mut self, lit: &hir::Lit) {
1278 self.maybe_print_comment(lit.span.lo());
1279 self.word(lit.node.to_lit_token().to_string())
1282 pub fn print_expr(&mut self, expr: &hir::Expr<'_>) {
1283 self.maybe_print_comment(expr.span.lo());
1284 self.print_outer_attributes(&expr.attrs);
1285 self.ibox(INDENT_UNIT);
1286 self.ann.pre(self, AnnNode::Expr(expr));
1288 hir::ExprKind::Box(ref expr) => {
1289 self.word_space("box");
1290 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX);
1292 hir::ExprKind::Array(ref exprs) => {
1293 self.print_expr_vec(exprs);
1295 hir::ExprKind::ConstBlock(ref anon_const) => {
1296 self.print_expr_anon_const(anon_const);
1298 hir::ExprKind::Repeat(ref element, ref count) => {
1299 self.print_expr_repeat(&element, count);
1301 hir::ExprKind::Struct(ref qpath, fields, ref wth) => {
1302 self.print_expr_struct(qpath, fields, wth);
1304 hir::ExprKind::Tup(ref exprs) => {
1305 self.print_expr_tup(exprs);
1307 hir::ExprKind::Call(ref func, ref args) => {
1308 self.print_expr_call(&func, args);
1310 hir::ExprKind::MethodCall(ref segment, _, ref args, _) => {
1311 self.print_expr_method_call(segment, args);
1313 hir::ExprKind::Binary(op, ref lhs, ref rhs) => {
1314 self.print_expr_binary(op, &lhs, &rhs);
1316 hir::ExprKind::Unary(op, ref expr) => {
1317 self.print_expr_unary(op, &expr);
1319 hir::ExprKind::AddrOf(k, m, ref expr) => {
1320 self.print_expr_addr_of(k, m, &expr);
1322 hir::ExprKind::Lit(ref lit) => {
1323 self.print_literal(&lit);
1325 hir::ExprKind::Cast(ref expr, ref ty) => {
1326 let prec = AssocOp::As.precedence() as i8;
1327 self.print_expr_maybe_paren(&expr, prec);
1329 self.word_space("as");
1330 self.print_type(&ty);
1332 hir::ExprKind::Type(ref expr, ref ty) => {
1333 let prec = AssocOp::Colon.precedence() as i8;
1334 self.print_expr_maybe_paren(&expr, prec);
1335 self.word_space(":");
1336 self.print_type(&ty);
1338 hir::ExprKind::DropTemps(ref init) => {
1340 self.cbox(INDENT_UNIT);
1344 // Print `let _t = $init;`:
1345 let temp = Ident::from_str("_t");
1346 self.print_local(Some(init), |this| this.print_ident(temp));
1350 self.space_if_not_bol();
1351 self.print_ident(temp);
1354 self.bclose_maybe_open(expr.span, true);
1356 hir::ExprKind::Loop(ref blk, opt_label, _) => {
1357 if let Some(label) = opt_label {
1358 self.print_ident(label.ident);
1359 self.word_space(":");
1363 self.print_block(&blk);
1365 hir::ExprKind::Match(ref expr, arms, _) => {
1366 self.cbox(INDENT_UNIT);
1367 self.ibox(INDENT_UNIT);
1368 self.word_nbsp("match");
1369 self.print_expr_as_cond(&expr);
1373 self.print_arm(arm);
1375 self.bclose(expr.span);
1377 hir::ExprKind::Closure(capture_clause, ref decl, body, _fn_decl_span, _gen) => {
1378 self.print_capture_clause(capture_clause);
1380 self.print_closure_params(&decl, body);
1383 // This is a bare expression.
1384 self.ann.nested(self, Nested::Body(body));
1385 self.end(); // need to close a box
1387 // A box will be closed by `print_expr`, but we didn't want an overall
1388 // wrapper so we closed the corresponding opening. so create an
1389 // empty box to satisfy the close.
1392 hir::ExprKind::Block(ref blk, opt_label) => {
1393 if let Some(label) = opt_label {
1394 self.print_ident(label.ident);
1395 self.word_space(":");
1397 // containing cbox, will be closed by print-block at `}`
1398 self.cbox(INDENT_UNIT);
1399 // head-box, will be closed by print-block after `{`
1401 self.print_block(&blk);
1403 hir::ExprKind::Assign(ref lhs, ref rhs, _) => {
1404 let prec = AssocOp::Assign.precedence() as i8;
1405 self.print_expr_maybe_paren(&lhs, prec + 1);
1407 self.word_space("=");
1408 self.print_expr_maybe_paren(&rhs, prec);
1410 hir::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
1411 let prec = AssocOp::Assign.precedence() as i8;
1412 self.print_expr_maybe_paren(&lhs, prec + 1);
1414 self.s.word(op.node.as_str());
1415 self.word_space("=");
1416 self.print_expr_maybe_paren(&rhs, prec);
1418 hir::ExprKind::Field(ref expr, ident) => {
1419 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
1421 self.print_ident(ident);
1423 hir::ExprKind::Index(ref expr, ref index) => {
1424 self.print_expr_maybe_paren(&expr, parser::PREC_POSTFIX);
1426 self.print_expr(&index);
1429 hir::ExprKind::Path(ref qpath) => self.print_qpath(qpath, true),
1430 hir::ExprKind::Break(destination, ref opt_expr) => {
1431 self.s.word("break");
1433 if let Some(label) = destination.label {
1434 self.print_ident(label.ident);
1437 if let Some(ref expr) = *opt_expr {
1438 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
1442 hir::ExprKind::Continue(destination) => {
1443 self.s.word("continue");
1445 if let Some(label) = destination.label {
1446 self.print_ident(label.ident);
1450 hir::ExprKind::Ret(ref result) => {
1451 self.s.word("return");
1452 if let Some(ref expr) = *result {
1454 self.print_expr_maybe_paren(&expr, parser::PREC_JUMP);
1457 hir::ExprKind::InlineAsm(ref a) => {
1460 Operand(&'a hir::InlineAsmOperand<'a>),
1461 Options(ast::InlineAsmOptions),
1464 let mut args = vec![];
1465 args.push(AsmArg::Template(ast::InlineAsmTemplatePiece::to_string(&a.template)));
1466 args.extend(a.operands.iter().map(|o| AsmArg::Operand(o)));
1467 if !a.options.is_empty() {
1468 args.push(AsmArg::Options(a.options));
1473 self.commasep(Consistent, &args, |s, arg| match arg {
1474 AsmArg::Template(template) => s.print_string(&template, ast::StrStyle::Cooked),
1475 AsmArg::Operand(op) => match op {
1476 hir::InlineAsmOperand::In { reg, expr } => {
1479 s.word(format!("{}", reg));
1484 hir::InlineAsmOperand::Out { reg, late, expr } => {
1485 s.word(if *late { "lateout" } else { "out" });
1487 s.word(format!("{}", reg));
1491 Some(expr) => s.print_expr(expr),
1492 None => s.word("_"),
1495 hir::InlineAsmOperand::InOut { reg, late, expr } => {
1496 s.word(if *late { "inlateout" } else { "inout" });
1498 s.word(format!("{}", reg));
1503 hir::InlineAsmOperand::SplitInOut { reg, late, in_expr, out_expr } => {
1504 s.word(if *late { "inlateout" } else { "inout" });
1506 s.word(format!("{}", reg));
1509 s.print_expr(in_expr);
1513 Some(out_expr) => s.print_expr(out_expr),
1514 None => s.word("_"),
1517 hir::InlineAsmOperand::Const { expr } => {
1522 hir::InlineAsmOperand::Sym { expr } => {
1528 AsmArg::Options(opts) => {
1531 let mut options = vec![];
1532 if opts.contains(ast::InlineAsmOptions::PURE) {
1533 options.push("pure");
1535 if opts.contains(ast::InlineAsmOptions::NOMEM) {
1536 options.push("nomem");
1538 if opts.contains(ast::InlineAsmOptions::READONLY) {
1539 options.push("readonly");
1541 if opts.contains(ast::InlineAsmOptions::PRESERVES_FLAGS) {
1542 options.push("preserves_flags");
1544 if opts.contains(ast::InlineAsmOptions::NORETURN) {
1545 options.push("noreturn");
1547 if opts.contains(ast::InlineAsmOptions::NOSTACK) {
1548 options.push("nostack");
1550 if opts.contains(ast::InlineAsmOptions::ATT_SYNTAX) {
1551 options.push("att_syntax");
1553 s.commasep(Inconsistent, &options, |s, &opt| {
1561 hir::ExprKind::LlvmInlineAsm(ref a) => {
1563 self.s.word("llvm_asm!");
1565 self.print_symbol(i.asm, i.asm_str_style);
1566 self.word_space(":");
1568 let mut out_idx = 0;
1569 self.commasep(Inconsistent, &i.outputs, |s, out| {
1570 let constraint = out.constraint.as_str();
1571 let mut ch = constraint.chars();
1573 Some('=') if out.is_rw => {
1574 s.print_string(&format!("+{}", ch.as_str()), ast::StrStyle::Cooked)
1576 _ => s.print_string(&constraint, ast::StrStyle::Cooked),
1579 s.print_expr(&a.outputs_exprs[out_idx]);
1584 self.word_space(":");
1587 self.commasep(Inconsistent, &i.inputs, |s, &co| {
1588 s.print_symbol(co, ast::StrStyle::Cooked);
1590 s.print_expr(&a.inputs_exprs[in_idx]);
1595 self.word_space(":");
1597 self.commasep(Inconsistent, &i.clobbers, |s, &co| {
1598 s.print_symbol(co, ast::StrStyle::Cooked);
1601 let mut options = vec![];
1603 options.push("volatile");
1606 options.push("alignstack");
1608 if i.dialect == ast::LlvmAsmDialect::Intel {
1609 options.push("intel");
1612 if !options.is_empty() {
1614 self.word_space(":");
1615 self.commasep(Inconsistent, &options, |s, &co| {
1616 s.print_string(co, ast::StrStyle::Cooked);
1622 hir::ExprKind::Yield(ref expr, _) => {
1623 self.word_space("yield");
1624 self.print_expr_maybe_paren(&expr, parser::PREC_JUMP);
1626 hir::ExprKind::Err => {
1628 self.s.word("/*ERROR*/");
1632 self.ann.post(self, AnnNode::Expr(expr));
1636 pub fn print_local_decl(&mut self, loc: &hir::Local<'_>) {
1637 self.print_pat(&loc.pat);
1638 if let Some(ref ty) = loc.ty {
1639 self.word_space(":");
1640 self.print_type(&ty);
1644 pub fn print_usize(&mut self, i: usize) {
1645 self.s.word(i.to_string())
1648 pub fn print_name(&mut self, name: Symbol) {
1649 self.print_ident(Ident::with_dummy_span(name))
1652 pub fn print_for_decl(&mut self, loc: &hir::Local<'_>, coll: &hir::Expr<'_>) {
1653 self.print_local_decl(loc);
1655 self.word_space("in");
1656 self.print_expr(coll)
1659 pub fn print_path(&mut self, path: &hir::Path<'_>, colons_before_params: bool) {
1660 self.maybe_print_comment(path.span.lo());
1662 for (i, segment) in path.segments.iter().enumerate() {
1666 if segment.ident.name != kw::PathRoot {
1667 self.print_ident(segment.ident);
1668 self.print_generic_args(
1669 segment.generic_args(),
1671 colons_before_params,
1677 pub fn print_path_segment(&mut self, segment: &hir::PathSegment<'_>) {
1678 if segment.ident.name != kw::PathRoot {
1679 self.print_ident(segment.ident);
1680 self.print_generic_args(segment.generic_args(), segment.infer_args, false);
1684 pub fn print_qpath(&mut self, qpath: &hir::QPath<'_>, colons_before_params: bool) {
1686 hir::QPath::Resolved(None, ref path) => self.print_path(path, colons_before_params),
1687 hir::QPath::Resolved(Some(ref qself), ref path) => {
1689 self.print_type(qself);
1691 self.word_space("as");
1693 for (i, segment) in path.segments[..path.segments.len() - 1].iter().enumerate() {
1697 if segment.ident.name != kw::PathRoot {
1698 self.print_ident(segment.ident);
1699 self.print_generic_args(
1700 segment.generic_args(),
1702 colons_before_params,
1709 let item_segment = path.segments.last().unwrap();
1710 self.print_ident(item_segment.ident);
1711 self.print_generic_args(
1712 item_segment.generic_args(),
1713 item_segment.infer_args,
1714 colons_before_params,
1717 hir::QPath::TypeRelative(ref qself, ref item_segment) => {
1718 // If we've got a compound-qualified-path, let's push an additional pair of angle
1719 // brackets, so that we pretty-print `<<A::B>::C>` as `<A::B>::C`, instead of just
1720 // `A::B::C` (since the latter could be ambiguous to the user)
1721 if let hir::TyKind::Path(hir::QPath::Resolved(None, _)) = &qself.kind {
1722 self.print_type(qself);
1725 self.print_type(qself);
1730 self.print_ident(item_segment.ident);
1731 self.print_generic_args(
1732 item_segment.generic_args(),
1733 item_segment.infer_args,
1734 colons_before_params,
1737 hir::QPath::LangItem(lang_item, span) => {
1738 self.s.word("#[lang = \"");
1739 self.print_ident(Ident::new(lang_item.name(), span));
1745 fn print_generic_args(
1747 generic_args: &hir::GenericArgs<'_>,
1749 colons_before_params: bool,
1751 if generic_args.parenthesized {
1753 self.commasep(Inconsistent, generic_args.inputs(), |s, ty| s.print_type(&ty));
1756 self.space_if_not_bol();
1757 self.word_space("->");
1758 self.print_type(generic_args.bindings[0].ty());
1760 let start = if colons_before_params { "::<" } else { "<" };
1761 let empty = Cell::new(true);
1762 let start_or_comma = |this: &mut Self| {
1767 this.word_space(",")
1771 let mut nonelided_generic_args: bool = false;
1772 let elide_lifetimes = generic_args.args.iter().all(|arg| match arg {
1773 GenericArg::Lifetime(lt) => lt.is_elided(),
1775 nonelided_generic_args = true;
1780 if nonelided_generic_args {
1781 start_or_comma(self);
1785 |s, generic_arg| match generic_arg {
1786 GenericArg::Lifetime(lt) if !elide_lifetimes => s.print_lifetime(lt),
1787 GenericArg::Lifetime(_) => {}
1788 GenericArg::Type(ty) => s.print_type(ty),
1789 GenericArg::Const(ct) => s.print_anon_const(&ct.value),
1794 // FIXME(eddyb): this would leak into error messages (e.g.,
1795 // "non-exhaustive patterns: `Some::<..>(_)` not covered").
1796 if infer_args && false {
1797 start_or_comma(self);
1801 for binding in generic_args.bindings.iter() {
1802 start_or_comma(self);
1803 self.print_ident(binding.ident);
1805 match generic_args.bindings[0].kind {
1806 hir::TypeBindingKind::Equality { ref ty } => {
1807 self.word_space("=");
1808 self.print_type(ty);
1810 hir::TypeBindingKind::Constraint { bounds } => {
1811 self.print_bounds(":", bounds);
1822 pub fn print_pat(&mut self, pat: &hir::Pat<'_>) {
1823 self.maybe_print_comment(pat.span.lo());
1824 self.ann.pre(self, AnnNode::Pat(pat));
1825 // Pat isn't normalized, but the beauty of it
1826 // is that it doesn't matter
1828 PatKind::Wild => self.s.word("_"),
1829 PatKind::Binding(binding_mode, _, ident, ref sub) => {
1830 match binding_mode {
1831 hir::BindingAnnotation::Ref => {
1832 self.word_nbsp("ref");
1833 self.print_mutability(hir::Mutability::Not, false);
1835 hir::BindingAnnotation::RefMut => {
1836 self.word_nbsp("ref");
1837 self.print_mutability(hir::Mutability::Mut, false);
1839 hir::BindingAnnotation::Unannotated => {}
1840 hir::BindingAnnotation::Mutable => {
1841 self.word_nbsp("mut");
1844 self.print_ident(ident);
1845 if let Some(ref p) = *sub {
1850 PatKind::TupleStruct(ref qpath, ref elts, ddpos) => {
1851 self.print_qpath(qpath, true);
1853 if let Some(ddpos) = ddpos {
1854 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p));
1856 self.word_space(",");
1859 if ddpos != elts.len() {
1861 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p));
1864 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p));
1868 PatKind::Path(ref qpath) => {
1869 self.print_qpath(qpath, true);
1871 PatKind::Struct(ref qpath, ref fields, etc) => {
1872 self.print_qpath(qpath, true);
1874 self.word_space("{");
1879 s.cbox(INDENT_UNIT);
1880 if !f.is_shorthand {
1881 s.print_ident(f.ident);
1884 s.print_pat(&f.pat);
1890 if !fields.is_empty() {
1891 self.word_space(",");
1898 PatKind::Or(ref pats) => {
1899 self.strsep("|", true, Inconsistent, &pats[..], |s, p| s.print_pat(&p));
1901 PatKind::Tuple(ref elts, ddpos) => {
1903 if let Some(ddpos) = ddpos {
1904 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p));
1906 self.word_space(",");
1909 if ddpos != elts.len() {
1911 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p));
1914 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p));
1915 if elts.len() == 1 {
1921 PatKind::Box(ref inner) => {
1922 let is_range_inner = matches!(inner.kind, PatKind::Range(..));
1923 self.s.word("box ");
1927 self.print_pat(&inner);
1932 PatKind::Ref(ref inner, mutbl) => {
1933 let is_range_inner = matches!(inner.kind, PatKind::Range(..));
1935 self.s.word(mutbl.prefix_str());
1939 self.print_pat(&inner);
1944 PatKind::Lit(ref e) => self.print_expr(&e),
1945 PatKind::Range(ref begin, ref end, ref end_kind) => {
1946 if let Some(expr) = begin {
1947 self.print_expr(expr);
1951 RangeEnd::Included => self.s.word("..."),
1952 RangeEnd::Excluded => self.s.word(".."),
1954 if let Some(expr) = end {
1955 self.print_expr(expr);
1958 PatKind::Slice(ref before, ref slice, ref after) => {
1960 self.commasep(Inconsistent, &before[..], |s, p| s.print_pat(&p));
1961 if let Some(ref p) = *slice {
1962 if !before.is_empty() {
1963 self.word_space(",");
1965 if let PatKind::Wild = p.kind {
1971 if !after.is_empty() {
1972 self.word_space(",");
1975 self.commasep(Inconsistent, &after[..], |s, p| s.print_pat(&p));
1979 self.ann.post(self, AnnNode::Pat(pat))
1982 pub fn print_param(&mut self, arg: &hir::Param<'_>) {
1983 self.print_outer_attributes(&arg.attrs);
1984 self.print_pat(&arg.pat);
1987 pub fn print_arm(&mut self, arm: &hir::Arm<'_>) {
1988 // I have no idea why this check is necessary, but here it
1990 if arm.attrs.is_empty() {
1993 self.cbox(INDENT_UNIT);
1994 self.ann.pre(self, AnnNode::Arm(arm));
1996 self.print_outer_attributes(&arm.attrs);
1997 self.print_pat(&arm.pat);
1999 if let Some(ref g) = arm.guard {
2001 hir::Guard::If(e) => {
2002 self.word_space("if");
2003 self.print_expr(&e);
2008 self.word_space("=>");
2010 match arm.body.kind {
2011 hir::ExprKind::Block(ref blk, opt_label) => {
2012 if let Some(label) = opt_label {
2013 self.print_ident(label.ident);
2014 self.word_space(":");
2016 // the block will close the pattern's ibox
2017 self.print_block_unclosed(&blk);
2019 // If it is a user-provided unsafe block, print a comma after it
2020 if let hir::BlockCheckMode::UnsafeBlock(hir::UnsafeSource::UserProvided) = blk.rules
2026 self.end(); // close the ibox for the pattern
2027 self.print_expr(&arm.body);
2031 self.ann.post(self, AnnNode::Arm(arm));
2032 self.end() // close enclosing cbox
2037 decl: &hir::FnDecl<'_>,
2038 header: hir::FnHeader,
2039 name: Option<Symbol>,
2040 generics: &hir::Generics<'_>,
2041 vis: &hir::Visibility<'_>,
2042 arg_names: &[Ident],
2043 body_id: Option<hir::BodyId>,
2045 self.print_fn_header_info(header, vis);
2047 if let Some(name) = name {
2049 self.print_name(name);
2051 self.print_generic_params(&generics.params);
2055 // Make sure we aren't supplied *both* `arg_names` and `body_id`.
2056 assert!(arg_names.is_empty() || body_id.is_none());
2057 self.commasep(Inconsistent, &decl.inputs, |s, ty| {
2058 s.ibox(INDENT_UNIT);
2059 if let Some(arg_name) = arg_names.get(i) {
2060 s.s.word(arg_name.to_string());
2063 } else if let Some(body_id) = body_id {
2064 s.ann.nested(s, Nested::BodyParamPat(body_id, i));
2072 if decl.c_variadic {
2073 self.s.word(", ...");
2077 self.print_fn_output(decl);
2078 self.print_where_clause(&generics.where_clause)
2081 fn print_closure_params(&mut self, decl: &hir::FnDecl<'_>, body_id: hir::BodyId) {
2084 self.commasep(Inconsistent, &decl.inputs, |s, ty| {
2085 s.ibox(INDENT_UNIT);
2087 s.ann.nested(s, Nested::BodyParamPat(body_id, i));
2090 if let hir::TyKind::Infer = ty.kind {
2101 if let hir::FnRetTy::DefaultReturn(..) = decl.output {
2105 self.space_if_not_bol();
2106 self.word_space("->");
2108 hir::FnRetTy::Return(ref ty) => {
2109 self.print_type(&ty);
2110 self.maybe_print_comment(ty.span.lo())
2112 hir::FnRetTy::DefaultReturn(..) => unreachable!(),
2116 pub fn print_capture_clause(&mut self, capture_clause: hir::CaptureBy) {
2117 match capture_clause {
2118 hir::CaptureBy::Value => self.word_space("move"),
2119 hir::CaptureBy::Ref => {}
2123 pub fn print_bounds<'b>(
2125 prefix: &'static str,
2126 bounds: impl IntoIterator<Item = &'b hir::GenericBound<'b>>,
2128 let mut first = true;
2129 for bound in bounds {
2131 self.s.word(prefix);
2133 if !(first && prefix.is_empty()) {
2139 self.word_space("+");
2143 GenericBound::Trait(tref, modifier) => {
2144 if modifier == &TraitBoundModifier::Maybe {
2147 self.print_poly_trait_ref(tref);
2149 GenericBound::LangItemTrait(lang_item, span, ..) => {
2150 self.s.word("#[lang = \"");
2151 self.print_ident(Ident::new(lang_item.name(), *span));
2154 GenericBound::Outlives(lt) => {
2155 self.print_lifetime(lt);
2161 pub fn print_generic_params(&mut self, generic_params: &[GenericParam<'_>]) {
2162 if !generic_params.is_empty() {
2165 self.commasep(Inconsistent, generic_params, |s, param| s.print_generic_param(param));
2171 pub fn print_generic_param(&mut self, param: &GenericParam<'_>) {
2172 if let GenericParamKind::Const { .. } = param.kind {
2173 self.word_space("const");
2176 self.print_ident(param.name.ident());
2179 GenericParamKind::Lifetime { .. } => {
2181 for bound in param.bounds {
2183 GenericBound::Outlives(ref lt) => {
2185 self.print_lifetime(lt);
2192 GenericParamKind::Type { ref default, .. } => {
2193 self.print_bounds(":", param.bounds);
2194 if let Some(default) = default {
2196 self.word_space("=");
2197 self.print_type(&default)
2200 GenericParamKind::Const { ref ty } => {
2201 self.word_space(":");
2207 pub fn print_lifetime(&mut self, lifetime: &hir::Lifetime) {
2208 self.print_ident(lifetime.name.ident())
2211 pub fn print_where_clause(&mut self, where_clause: &hir::WhereClause<'_>) {
2212 if where_clause.predicates.is_empty() {
2217 self.word_space("where");
2219 for (i, predicate) in where_clause.predicates.iter().enumerate() {
2221 self.word_space(",");
2225 &hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
2226 ref bound_generic_params,
2231 self.print_formal_generic_params(bound_generic_params);
2232 self.print_type(&bounded_ty);
2233 self.print_bounds(":", bounds);
2235 &hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
2240 self.print_lifetime(lifetime);
2243 for (i, bound) in bounds.iter().enumerate() {
2245 GenericBound::Outlives(lt) => {
2246 self.print_lifetime(lt);
2256 &hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
2261 self.print_type(lhs_ty);
2263 self.word_space("=");
2264 self.print_type(rhs_ty);
2270 pub fn print_mutability(&mut self, mutbl: hir::Mutability, print_const: bool) {
2272 hir::Mutability::Mut => self.word_nbsp("mut"),
2273 hir::Mutability::Not => {
2275 self.word_nbsp("const")
2281 pub fn print_mt(&mut self, mt: &hir::MutTy<'_>, print_const: bool) {
2282 self.print_mutability(mt.mutbl, print_const);
2283 self.print_type(&mt.ty)
2286 pub fn print_fn_output(&mut self, decl: &hir::FnDecl<'_>) {
2287 if let hir::FnRetTy::DefaultReturn(..) = decl.output {
2291 self.space_if_not_bol();
2292 self.ibox(INDENT_UNIT);
2293 self.word_space("->");
2295 hir::FnRetTy::DefaultReturn(..) => unreachable!(),
2296 hir::FnRetTy::Return(ref ty) => self.print_type(&ty),
2300 if let hir::FnRetTy::Return(ref output) = decl.output {
2301 self.maybe_print_comment(output.span.lo())
2308 unsafety: hir::Unsafety,
2309 decl: &hir::FnDecl<'_>,
2310 name: Option<Symbol>,
2311 generic_params: &[hir::GenericParam<'_>],
2312 arg_names: &[Ident],
2314 self.ibox(INDENT_UNIT);
2315 if !generic_params.is_empty() {
2317 self.print_generic_params(generic_params);
2319 let generics = hir::Generics {
2321 where_clause: hir::WhereClause { predicates: &[], span: rustc_span::DUMMY_SP },
2322 span: rustc_span::DUMMY_SP,
2329 constness: hir::Constness::NotConst,
2330 asyncness: hir::IsAsync::NotAsync,
2334 &Spanned { span: rustc_span::DUMMY_SP, node: hir::VisibilityKind::Inherited },
2341 pub fn maybe_print_trailing_comment(
2343 span: rustc_span::Span,
2344 next_pos: Option<BytePos>,
2346 if let Some(cmnts) = self.comments() {
2347 if let Some(cmnt) = cmnts.trailing_comment(span, next_pos) {
2348 self.print_comment(&cmnt);
2353 pub fn print_remaining_comments(&mut self) {
2354 // If there aren't any remaining comments, then we need to manually
2355 // make sure there is a line break at the end.
2356 if self.next_comment().is_none() {
2359 while let Some(ref cmnt) = self.next_comment() {
2360 self.print_comment(cmnt)
2364 pub fn print_opt_abi_and_extern_if_nondefault(&mut self, opt_abi: Option<Abi>) {
2366 Some(Abi::Rust) => {}
2368 self.word_nbsp("extern");
2369 self.word_nbsp(abi.to_string())
2375 pub fn print_extern_opt_abi(&mut self, opt_abi: Option<Abi>) {
2376 if let Some(abi) = opt_abi {
2377 self.word_nbsp("extern");
2378 self.word_nbsp(abi.to_string())
2382 pub fn print_fn_header_info(&mut self, header: hir::FnHeader, vis: &hir::Visibility<'_>) {
2383 self.s.word(visibility_qualified(vis, ""));
2385 match header.constness {
2386 hir::Constness::NotConst => {}
2387 hir::Constness::Const => self.word_nbsp("const"),
2390 match header.asyncness {
2391 hir::IsAsync::NotAsync => {}
2392 hir::IsAsync::Async => self.word_nbsp("async"),
2395 self.print_unsafety(header.unsafety);
2397 if header.abi != Abi::Rust {
2398 self.word_nbsp("extern");
2399 self.word_nbsp(header.abi.to_string());
2405 pub fn print_unsafety(&mut self, s: hir::Unsafety) {
2407 hir::Unsafety::Normal => {}
2408 hir::Unsafety::Unsafe => self.word_nbsp("unsafe"),
2412 pub fn print_is_auto(&mut self, s: hir::IsAuto) {
2414 hir::IsAuto::Yes => self.word_nbsp("auto"),
2415 hir::IsAuto::No => {}
2420 /// Does this expression require a semicolon to be treated
2421 /// as a statement? The negation of this: 'can this expression
2422 /// be used as a statement without a semicolon' -- is used
2423 /// as an early-bail-out in the parser so that, for instance,
2424 /// if true {...} else {...}
2426 /// isn't parsed as (if true {...} else {...} | x) | 5
2428 // Duplicated from `parse::classify`, but adapted for the HIR.
2429 fn expr_requires_semi_to_be_stmt(e: &hir::Expr<'_>) -> bool {
2430 !matches!(e.kind, hir::ExprKind::Match(..) | hir::ExprKind::Block(..) | hir::ExprKind::Loop(..))
2433 /// This statement requires a semicolon after it.
2434 /// note that in one case (stmt_semi), we've already
2435 /// seen the semicolon, and thus don't need another.
2436 fn stmt_ends_with_semi(stmt: &hir::StmtKind<'_>) -> bool {
2438 hir::StmtKind::Local(_) => true,
2439 hir::StmtKind::Item(_) => false,
2440 hir::StmtKind::Expr(ref e) => expr_requires_semi_to_be_stmt(&e),
2441 hir::StmtKind::Semi(..) => false,
2445 fn bin_op_to_assoc_op(op: hir::BinOpKind) -> AssocOp {
2446 use crate::hir::BinOpKind::*;
2448 Add => AssocOp::Add,
2449 Sub => AssocOp::Subtract,
2450 Mul => AssocOp::Multiply,
2451 Div => AssocOp::Divide,
2452 Rem => AssocOp::Modulus,
2454 And => AssocOp::LAnd,
2457 BitXor => AssocOp::BitXor,
2458 BitAnd => AssocOp::BitAnd,
2459 BitOr => AssocOp::BitOr,
2460 Shl => AssocOp::ShiftLeft,
2461 Shr => AssocOp::ShiftRight,
2463 Eq => AssocOp::Equal,
2464 Lt => AssocOp::Less,
2465 Le => AssocOp::LessEqual,
2466 Ne => AssocOp::NotEqual,
2467 Ge => AssocOp::GreaterEqual,
2468 Gt => AssocOp::Greater,
2472 /// Expressions that syntactically contain an "exterior" struct literal, i.e., not surrounded by any
2473 /// parens or other delimiters, e.g., `X { y: 1 }`, `X { y: 1 }.method()`, `foo == X { y: 1 }` and
2474 /// `X { y: 1 } == foo` all do, but `(X { y: 1 }) == foo` does not.
2475 fn contains_exterior_struct_lit(value: &hir::Expr<'_>) -> bool {
2477 hir::ExprKind::Struct(..) => true,
2479 hir::ExprKind::Assign(ref lhs, ref rhs, _)
2480 | hir::ExprKind::AssignOp(_, ref lhs, ref rhs)
2481 | hir::ExprKind::Binary(_, ref lhs, ref rhs) => {
2482 // `X { y: 1 } + X { y: 2 }`
2483 contains_exterior_struct_lit(&lhs) || contains_exterior_struct_lit(&rhs)
2485 hir::ExprKind::Unary(_, ref x)
2486 | hir::ExprKind::Cast(ref x, _)
2487 | hir::ExprKind::Type(ref x, _)
2488 | hir::ExprKind::Field(ref x, _)
2489 | hir::ExprKind::Index(ref x, _) => {
2490 // `&X { y: 1 }, X { y: 1 }.y`
2491 contains_exterior_struct_lit(&x)
2494 hir::ExprKind::MethodCall(.., ref exprs, _) => {
2495 // `X { y: 1 }.bar(...)`
2496 contains_exterior_struct_lit(&exprs[0])