1 use rustc_span::source_map::{SourceMap, Spanned};
2 use rustc_span::symbol::kw;
3 use rustc_span::{self, BytePos, FileName};
4 use rustc_target::spec::abi::Abi;
6 use syntax::print::pp::Breaks::{Consistent, Inconsistent};
7 use syntax::print::pp::{self, Breaks};
8 use syntax::print::pprust::{self, Comments, PrintState};
9 use syntax::sess::ParseSess;
10 use syntax::util::parser::{self, AssocOp, Fixity};
13 use crate::hir::{GenericArg, GenericParam, GenericParamKind, Node};
14 use crate::hir::{GenericBound, PatKind, RangeEnd, TraitBoundModifier};
20 pub enum AnnNode<'a> {
22 Block(&'a hir::Block<'a>),
23 Item(&'a hir::Item<'a>),
25 Expr(&'a hir::Expr<'a>),
26 Pat(&'a hir::Pat<'a>),
27 Arm(&'a hir::Arm<'a>),
32 TraitItem(hir::TraitItemId),
33 ImplItem(hir::ImplItemId),
35 BodyParamPat(hir::BodyId, usize),
39 fn nested(&self, _state: &mut State<'_>, _nested: Nested) {}
40 fn pre(&self, _state: &mut State<'_>, _node: AnnNode<'_>) {}
41 fn post(&self, _state: &mut State<'_>, _node: AnnNode<'_>) {}
42 fn try_fetch_item(&self, _: hir::HirId) -> Option<&hir::Item<'_>> {
48 impl PpAnn for NoAnn {}
49 pub const NO_ANN: &dyn PpAnn = &NoAnn;
51 impl PpAnn for hir::Crate<'a> {
52 fn try_fetch_item(&self, item: hir::HirId) -> Option<&hir::Item<'_>> {
55 fn nested(&self, state: &mut State<'_>, nested: Nested) {
57 Nested::Item(id) => state.print_item(self.item(id.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::Body(id) => state.print_expr(&self.body(id).value),
61 Nested::BodyParamPat(id, i) => state.print_pat(&self.body(id).params[i].pat),
66 pub struct State<'a> {
68 comments: Option<Comments<'a>>,
69 ann: &'a (dyn PpAnn + 'a),
73 pub fn print_node(&mut self, node: Node<'_>) {
75 Node::Param(a) => self.print_param(&a),
76 Node::Item(a) => self.print_item(&a),
77 Node::ForeignItem(a) => self.print_foreign_item(&a),
78 Node::TraitItem(a) => self.print_trait_item(a),
79 Node::ImplItem(a) => self.print_impl_item(a),
80 Node::Variant(a) => self.print_variant(&a),
81 Node::AnonConst(a) => self.print_anon_const(&a),
82 Node::Expr(a) => self.print_expr(&a),
83 Node::Stmt(a) => self.print_stmt(&a),
84 Node::PathSegment(a) => self.print_path_segment(&a),
85 Node::Ty(a) => self.print_type(&a),
86 Node::TraitRef(a) => self.print_trait_ref(&a),
87 Node::Binding(a) | Node::Pat(a) => self.print_pat(&a),
88 Node::Arm(a) => self.print_arm(&a),
90 // Containing cbox, will be closed by print-block at `}`.
91 self.cbox(INDENT_UNIT);
92 // Head-ibox, will be closed by print-block after `{`.
96 Node::Lifetime(a) => self.print_lifetime(&a),
97 Node::Visibility(a) => self.print_visibility(&a),
98 Node::GenericParam(_) => panic!("cannot print Node::GenericParam"),
99 Node::Field(_) => panic!("cannot print StructField"),
100 // These cases do not carry enough information in the
101 // `hir_map` to reconstruct their full structure for pretty
103 Node::Ctor(..) => panic!("cannot print isolated Ctor"),
104 Node::Local(a) => self.print_local_decl(&a),
105 Node::MacroDef(_) => panic!("cannot print MacroDef"),
106 Node::Crate => panic!("cannot print Crate"),
111 impl std::ops::Deref for State<'_> {
112 type Target = pp::Printer;
113 fn deref(&self) -> &Self::Target {
118 impl std::ops::DerefMut for State<'_> {
119 fn deref_mut(&mut self) -> &mut Self::Target {
124 impl<'a> PrintState<'a> for State<'a> {
125 fn comments(&mut self) -> &mut Option<Comments<'a>> {
129 fn print_ident(&mut self, ident: ast::Ident) {
130 self.s.word(pprust::ast_ident_to_string(ident, ident.is_raw_guess()));
131 self.ann.post(self, AnnNode::Name(&ident.name))
134 fn print_generic_args(&mut self, _: &ast::GenericArgs, _colons_before_params: bool) {
135 panic!("AST generic args printed by HIR pretty-printer");
139 pub const INDENT_UNIT: usize = 4;
141 /// Requires you to pass an input filename and reader so that
142 /// it can scan the input text for comments to copy forward.
143 pub fn print_crate<'a>(
146 krate: &hir::Crate<'_>,
151 let mut s = State::new_from_input(cm, sess, filename, input, ann);
153 // When printing the AST, we sometimes need to inject `#[no_std]` here.
154 // Since you can't compile the HIR, it's not necessary.
156 s.print_mod(&krate.module, &krate.attrs);
157 s.print_remaining_comments();
162 pub fn new_from_input(
169 State { s: pp::mk_printer(), comments: Some(Comments::new(cm, sess, filename, input)), ann }
173 pub fn to_string<F>(ann: &dyn PpAnn, f: F) -> String
175 F: FnOnce(&mut State<'_>),
177 let mut printer = State { s: pp::mk_printer(), comments: None, ann };
182 pub fn visibility_qualified<S: Into<Cow<'static, str>>>(vis: &hir::Visibility<'_>, w: S) -> String {
183 to_string(NO_ANN, |s| {
184 s.print_visibility(vis);
190 pub fn cbox(&mut self, u: usize) {
194 pub fn nbsp(&mut self) {
198 pub fn word_nbsp<S: Into<Cow<'static, str>>>(&mut self, w: S) {
203 pub fn head<S: Into<Cow<'static, str>>>(&mut self, w: S) {
205 // outer-box is consistent
206 self.cbox(INDENT_UNIT);
207 // head-box is inconsistent
208 self.ibox(w.len() + 1);
209 // keyword that starts the head
215 pub fn bopen(&mut self) {
217 self.end(); // close the head-box
220 pub fn bclose_maybe_open(&mut self, span: rustc_span::Span, close_box: bool) {
221 self.maybe_print_comment(span.hi());
222 self.break_offset_if_not_bol(1, -(INDENT_UNIT as isize));
225 self.end(); // close the outer-box
229 pub fn bclose(&mut self, span: rustc_span::Span) {
230 self.bclose_maybe_open(span, true)
233 pub fn space_if_not_bol(&mut self) {
234 if !self.s.is_beginning_of_line() {
239 pub fn break_offset_if_not_bol(&mut self, n: usize, off: isize) {
240 if !self.s.is_beginning_of_line() {
241 self.s.break_offset(n, off)
243 if off != 0 && self.s.last_token().is_hardbreak_tok() {
244 // We do something pretty sketchy here: tuck the nonzero
245 // offset-adjustment we were going to deposit along with the
246 // break into the previous hardbreak.
247 self.s.replace_last_token(pp::Printer::hardbreak_tok_offset(off));
252 // Synthesizes a comment that was not textually present in the original source
254 pub fn synth_comment(&mut self, text: String) {
262 pub fn commasep_cmnt<T, F, G>(&mut self, b: Breaks, elts: &[T], mut op: F, mut get_span: G)
264 F: FnMut(&mut State<'_>, &T),
265 G: FnMut(&T) -> rustc_span::Span,
268 let len = elts.len();
271 self.maybe_print_comment(get_span(elt).hi());
276 self.maybe_print_trailing_comment(get_span(elt), Some(get_span(&elts[i]).hi()));
277 self.space_if_not_bol();
283 pub fn commasep_exprs(&mut self, b: Breaks, exprs: &[hir::Expr<'_>]) {
284 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(&e), |e| e.span)
287 pub fn print_mod(&mut self, _mod: &hir::Mod<'_>, attrs: &[ast::Attribute]) {
288 self.print_inner_attributes(attrs);
289 for &item_id in _mod.item_ids {
290 self.ann.nested(self, Nested::Item(item_id));
294 pub fn print_foreign_mod(&mut self, nmod: &hir::ForeignMod<'_>, attrs: &[ast::Attribute]) {
295 self.print_inner_attributes(attrs);
296 for item in nmod.items {
297 self.print_foreign_item(item);
301 pub fn print_opt_lifetime(&mut self, lifetime: &hir::Lifetime) {
302 if !lifetime.is_elided() {
303 self.print_lifetime(lifetime);
308 pub fn print_type(&mut self, ty: &hir::Ty<'_>) {
309 self.maybe_print_comment(ty.span.lo());
312 hir::TyKind::Slice(ref ty) => {
314 self.print_type(&ty);
317 hir::TyKind::Ptr(ref mt) => {
319 self.print_mt(mt, true);
321 hir::TyKind::Rptr(ref lifetime, ref mt) => {
323 self.print_opt_lifetime(lifetime);
324 self.print_mt(mt, false);
326 hir::TyKind::Never => {
329 hir::TyKind::Tup(ref elts) => {
331 self.commasep(Inconsistent, &elts[..], |s, ty| s.print_type(&ty));
337 hir::TyKind::BareFn(ref f) => {
347 hir::TyKind::Def(..) => {}
348 hir::TyKind::Path(ref qpath) => self.print_qpath(qpath, false),
349 hir::TyKind::TraitObject(bounds, ref lifetime) => {
350 let mut first = true;
351 for bound in bounds {
356 self.word_space("+");
358 self.print_poly_trait_ref(bound);
360 if !lifetime.is_elided() {
362 self.word_space("+");
363 self.print_lifetime(lifetime);
366 hir::TyKind::Array(ref ty, ref length) => {
368 self.print_type(&ty);
370 self.print_anon_const(length);
373 hir::TyKind::Typeof(ref e) => {
374 self.s.word("typeof(");
375 self.print_anon_const(e);
378 hir::TyKind::Infer => {
381 hir::TyKind::Err => {
383 self.s.word("/*ERROR*/");
390 pub fn print_foreign_item(&mut self, item: &hir::ForeignItem<'_>) {
391 self.hardbreak_if_not_bol();
392 self.maybe_print_comment(item.span.lo());
393 self.print_outer_attributes(&item.attrs);
395 hir::ForeignItemKind::Fn(ref decl, ref arg_names, ref generics) => {
400 unsafety: hir::Unsafety::Normal,
401 constness: hir::Constness::NotConst,
403 asyncness: hir::IsAsync::NotAsync,
405 Some(item.ident.name),
411 self.end(); // end head-ibox
413 self.end() // end the outer fn box
415 hir::ForeignItemKind::Static(ref t, m) => {
416 self.head(visibility_qualified(&item.vis, "static"));
417 if m == hir::Mutability::Mut {
418 self.word_space("mut");
420 self.print_ident(item.ident);
421 self.word_space(":");
424 self.end(); // end the head-ibox
425 self.end() // end the outer cbox
427 hir::ForeignItemKind::Type => {
428 self.head(visibility_qualified(&item.vis, "type"));
429 self.print_ident(item.ident);
431 self.end(); // end the head-ibox
432 self.end() // end the outer cbox
437 fn print_associated_const(
441 default: Option<hir::BodyId>,
442 vis: &hir::Visibility<'_>,
444 self.s.word(visibility_qualified(vis, ""));
445 self.word_space("const");
446 self.print_ident(ident);
447 self.word_space(":");
449 if let Some(expr) = default {
451 self.word_space("=");
452 self.ann.nested(self, Nested::Body(expr));
457 fn print_associated_type(
460 bounds: Option<hir::GenericBounds<'_>>,
461 ty: Option<&hir::Ty<'_>>,
463 self.word_space("type");
464 self.print_ident(ident);
465 if let Some(bounds) = bounds {
466 self.print_bounds(":", bounds);
468 if let Some(ty) = ty {
470 self.word_space("=");
478 item: &hir::Item<'_>,
479 generics: &hir::Generics<'_>,
480 inner: impl Fn(&mut Self),
482 self.head(visibility_qualified(&item.vis, "type"));
483 self.print_ident(item.ident);
484 self.print_generic_params(&generics.params);
485 self.end(); // end the inner ibox
487 self.print_where_clause(&generics.where_clause);
491 self.end(); // end the outer ibox
494 /// Pretty-print an item
495 pub fn print_item(&mut self, item: &hir::Item<'_>) {
496 self.hardbreak_if_not_bol();
497 self.maybe_print_comment(item.span.lo());
498 self.print_outer_attributes(&item.attrs);
499 self.ann.pre(self, AnnNode::Item(item));
501 hir::ItemKind::ExternCrate(orig_name) => {
502 self.head(visibility_qualified(&item.vis, "extern crate"));
503 if let Some(orig_name) = orig_name {
504 self.print_name(orig_name);
509 self.print_ident(item.ident);
511 self.end(); // end inner head-block
512 self.end(); // end outer head-block
514 hir::ItemKind::Use(ref path, kind) => {
515 self.head(visibility_qualified(&item.vis, "use"));
516 self.print_path(path, false);
519 hir::UseKind::Single => {
520 if path.segments.last().unwrap().ident != item.ident {
522 self.word_space("as");
523 self.print_ident(item.ident);
527 hir::UseKind::Glob => self.s.word("::*;"),
528 hir::UseKind::ListStem => self.s.word("::{};"),
530 self.end(); // end inner head-block
531 self.end(); // end outer head-block
533 hir::ItemKind::Static(ref ty, m, expr) => {
534 self.head(visibility_qualified(&item.vis, "static"));
535 if m == hir::Mutability::Mut {
536 self.word_space("mut");
538 self.print_ident(item.ident);
539 self.word_space(":");
540 self.print_type(&ty);
542 self.end(); // end the head-ibox
544 self.word_space("=");
545 self.ann.nested(self, Nested::Body(expr));
547 self.end(); // end the outer cbox
549 hir::ItemKind::Const(ref ty, expr) => {
550 self.head(visibility_qualified(&item.vis, "const"));
551 self.print_ident(item.ident);
552 self.word_space(":");
553 self.print_type(&ty);
555 self.end(); // end the head-ibox
557 self.word_space("=");
558 self.ann.nested(self, Nested::Body(expr));
560 self.end(); // end the outer cbox
562 hir::ItemKind::Fn(ref sig, ref param_names, body) => {
567 Some(item.ident.name),
574 self.end(); // need to close a box
575 self.end(); // need to close a box
576 self.ann.nested(self, Nested::Body(body));
578 hir::ItemKind::Mod(ref _mod) => {
579 self.head(visibility_qualified(&item.vis, "mod"));
580 self.print_ident(item.ident);
583 self.print_mod(_mod, &item.attrs);
584 self.bclose(item.span);
586 hir::ItemKind::ForeignMod(ref nmod) => {
588 self.word_nbsp(nmod.abi.to_string());
590 self.print_foreign_mod(nmod, &item.attrs);
591 self.bclose(item.span);
593 hir::ItemKind::GlobalAsm(ref ga) => {
594 self.head(visibility_qualified(&item.vis, "global asm"));
595 self.s.word(ga.asm.to_string());
598 hir::ItemKind::TyAlias(ref ty, ref generics) => {
599 self.print_item_type(item, &generics, |state| {
600 state.word_space("=");
601 state.print_type(&ty);
604 hir::ItemKind::OpaqueTy(ref opaque_ty) => {
605 self.print_item_type(item, &opaque_ty.generics, |state| {
606 let mut real_bounds = Vec::with_capacity(opaque_ty.bounds.len());
607 for b in opaque_ty.bounds.iter() {
608 if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
610 state.word_space("for ?");
611 state.print_trait_ref(&ptr.trait_ref);
616 state.print_bounds("= impl", real_bounds);
619 hir::ItemKind::Enum(ref enum_definition, ref params) => {
620 self.print_enum_def(enum_definition, params, item.ident.name, item.span, &item.vis);
622 hir::ItemKind::Struct(ref struct_def, ref generics) => {
623 self.head(visibility_qualified(&item.vis, "struct"));
624 self.print_struct(struct_def, generics, item.ident.name, item.span, true);
626 hir::ItemKind::Union(ref struct_def, ref generics) => {
627 self.head(visibility_qualified(&item.vis, "union"));
628 self.print_struct(struct_def, generics, item.ident.name, item.span, true);
630 hir::ItemKind::Impl {
641 self.print_visibility(&item.vis);
642 self.print_defaultness(defaultness);
643 self.print_unsafety(unsafety);
644 self.word_nbsp("impl");
646 if !generics.params.is_empty() {
647 self.print_generic_params(&generics.params);
651 if constness == ast::Constness::Const {
652 self.word_nbsp("const");
655 if let hir::ImplPolarity::Negative = polarity {
659 if let Some(ref t) = of_trait {
660 self.print_trait_ref(t);
662 self.word_space("for");
665 self.print_type(&self_ty);
666 self.print_where_clause(&generics.where_clause);
670 self.print_inner_attributes(&item.attrs);
671 for impl_item in items {
672 self.ann.nested(self, Nested::ImplItem(impl_item.id));
674 self.bclose(item.span);
676 hir::ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, trait_items) => {
678 self.print_visibility(&item.vis);
679 self.print_is_auto(is_auto);
680 self.print_unsafety(unsafety);
681 self.word_nbsp("trait");
682 self.print_ident(item.ident);
683 self.print_generic_params(&generics.params);
684 let mut real_bounds = Vec::with_capacity(bounds.len());
685 for b in bounds.iter() {
686 if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
688 self.word_space("for ?");
689 self.print_trait_ref(&ptr.trait_ref);
694 self.print_bounds(":", real_bounds);
695 self.print_where_clause(&generics.where_clause);
698 for trait_item in trait_items {
699 self.ann.nested(self, Nested::TraitItem(trait_item.id));
701 self.bclose(item.span);
703 hir::ItemKind::TraitAlias(ref generics, ref bounds) => {
705 self.print_visibility(&item.vis);
706 self.word_nbsp("trait");
707 self.print_ident(item.ident);
708 self.print_generic_params(&generics.params);
709 let mut real_bounds = Vec::with_capacity(bounds.len());
710 // FIXME(durka) this seems to be some quite outdated syntax
711 for b in bounds.iter() {
712 if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
714 self.word_space("for ?");
715 self.print_trait_ref(&ptr.trait_ref);
721 self.print_bounds("=", real_bounds);
722 self.print_where_clause(&generics.where_clause);
726 self.ann.post(self, AnnNode::Item(item))
729 pub fn print_trait_ref(&mut self, t: &hir::TraitRef<'_>) {
730 self.print_path(&t.path, false)
733 fn print_formal_generic_params(&mut self, generic_params: &[hir::GenericParam<'_>]) {
734 if !generic_params.is_empty() {
736 self.print_generic_params(generic_params);
741 fn print_poly_trait_ref(&mut self, t: &hir::PolyTraitRef<'_>) {
742 self.print_formal_generic_params(&t.bound_generic_params);
743 self.print_trait_ref(&t.trait_ref)
746 pub fn print_enum_def(
748 enum_definition: &hir::EnumDef<'_>,
749 generics: &hir::Generics<'_>,
751 span: rustc_span::Span,
752 visibility: &hir::Visibility<'_>,
754 self.head(visibility_qualified(visibility, "enum"));
755 self.print_name(name);
756 self.print_generic_params(&generics.params);
757 self.print_where_clause(&generics.where_clause);
759 self.print_variants(&enum_definition.variants, span)
762 pub fn print_variants(&mut self, variants: &[hir::Variant<'_>], span: rustc_span::Span) {
765 self.space_if_not_bol();
766 self.maybe_print_comment(v.span.lo());
767 self.print_outer_attributes(&v.attrs);
768 self.ibox(INDENT_UNIT);
769 self.print_variant(v);
772 self.maybe_print_trailing_comment(v.span, None);
777 pub fn print_visibility(&mut self, vis: &hir::Visibility<'_>) {
779 hir::VisibilityKind::Public => self.word_nbsp("pub"),
780 hir::VisibilityKind::Crate(ast::CrateSugar::JustCrate) => self.word_nbsp("crate"),
781 hir::VisibilityKind::Crate(ast::CrateSugar::PubCrate) => self.word_nbsp("pub(crate)"),
782 hir::VisibilityKind::Restricted { ref path, .. } => {
784 if path.segments.len() == 1 && path.segments[0].ident.name == kw::Super {
785 // Special case: `super` can print like `pub(super)`.
786 self.s.word("super");
788 // Everything else requires `in` at present.
789 self.word_nbsp("in");
790 self.print_path(path, false);
794 hir::VisibilityKind::Inherited => (),
798 pub fn print_defaultness(&mut self, defaultness: hir::Defaultness) {
800 hir::Defaultness::Default { .. } => self.word_nbsp("default"),
801 hir::Defaultness::Final => (),
807 struct_def: &hir::VariantData<'_>,
808 generics: &hir::Generics<'_>,
810 span: rustc_span::Span,
811 print_finalizer: bool,
813 self.print_name(name);
814 self.print_generic_params(&generics.params);
816 hir::VariantData::Tuple(..) | hir::VariantData::Unit(..) => {
817 if let hir::VariantData::Tuple(..) = struct_def {
819 self.commasep(Inconsistent, struct_def.fields(), |s, field| {
820 s.maybe_print_comment(field.span.lo());
821 s.print_outer_attributes(&field.attrs);
822 s.print_visibility(&field.vis);
823 s.print_type(&field.ty)
827 self.print_where_clause(&generics.where_clause);
832 self.end() // close the outer-box
834 hir::VariantData::Struct(..) => {
835 self.print_where_clause(&generics.where_clause);
838 self.hardbreak_if_not_bol();
840 for field in struct_def.fields() {
841 self.hardbreak_if_not_bol();
842 self.maybe_print_comment(field.span.lo());
843 self.print_outer_attributes(&field.attrs);
844 self.print_visibility(&field.vis);
845 self.print_ident(field.ident);
847 self.print_type(&field.ty);
856 pub fn print_variant(&mut self, v: &hir::Variant<'_>) {
858 let generics = hir::Generics::empty();
859 self.print_struct(&v.data, &generics, v.ident.name, v.span, false);
860 if let Some(ref d) = v.disr_expr {
862 self.word_space("=");
863 self.print_anon_const(d);
866 pub fn print_method_sig(
870 generics: &hir::Generics<'_>,
871 vis: &hir::Visibility<'_>,
872 arg_names: &[ast::Ident],
873 body_id: Option<hir::BodyId>,
875 self.print_fn(&m.decl, m.header, Some(ident.name), generics, vis, arg_names, body_id)
878 pub fn print_trait_item(&mut self, ti: &hir::TraitItem<'_>) {
879 self.ann.pre(self, AnnNode::SubItem(ti.hir_id));
880 self.hardbreak_if_not_bol();
881 self.maybe_print_comment(ti.span.lo());
882 self.print_outer_attributes(&ti.attrs);
884 hir::TraitItemKind::Const(ref ty, default) => {
886 Spanned { span: rustc_span::DUMMY_SP, node: hir::VisibilityKind::Inherited };
887 self.print_associated_const(ti.ident, &ty, default, &vis);
889 hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Required(ref arg_names)) => {
891 Spanned { span: rustc_span::DUMMY_SP, node: hir::VisibilityKind::Inherited };
892 self.print_method_sig(ti.ident, sig, &ti.generics, &vis, arg_names, None);
895 hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Provided(body)) => {
897 Spanned { span: rustc_span::DUMMY_SP, node: hir::VisibilityKind::Inherited };
899 self.print_method_sig(ti.ident, sig, &ti.generics, &vis, &[], Some(body));
901 self.end(); // need to close a box
902 self.end(); // need to close a box
903 self.ann.nested(self, Nested::Body(body));
905 hir::TraitItemKind::Type(ref bounds, ref default) => {
906 self.print_associated_type(
909 default.as_ref().map(|ty| &**ty),
913 self.ann.post(self, AnnNode::SubItem(ti.hir_id))
916 pub fn print_impl_item(&mut self, ii: &hir::ImplItem<'_>) {
917 self.ann.pre(self, AnnNode::SubItem(ii.hir_id));
918 self.hardbreak_if_not_bol();
919 self.maybe_print_comment(ii.span.lo());
920 self.print_outer_attributes(&ii.attrs);
921 self.print_defaultness(ii.defaultness);
924 hir::ImplItemKind::Const(ref ty, expr) => {
925 self.print_associated_const(ii.ident, &ty, Some(expr), &ii.vis);
927 hir::ImplItemKind::Method(ref sig, body) => {
929 self.print_method_sig(ii.ident, sig, &ii.generics, &ii.vis, &[], Some(body));
931 self.end(); // need to close a box
932 self.end(); // need to close a box
933 self.ann.nested(self, Nested::Body(body));
935 hir::ImplItemKind::TyAlias(ref ty) => {
936 self.print_associated_type(ii.ident, None, Some(ty));
938 hir::ImplItemKind::OpaqueTy(bounds) => {
939 self.word_space("type");
940 self.print_ident(ii.ident);
941 self.print_bounds("= impl", bounds);
945 self.ann.post(self, AnnNode::SubItem(ii.hir_id))
948 pub fn print_local(&mut self, init: Option<&hir::Expr<'_>>, decl: impl Fn(&mut Self)) {
949 self.space_if_not_bol();
950 self.ibox(INDENT_UNIT);
951 self.word_nbsp("let");
953 self.ibox(INDENT_UNIT);
957 if let Some(ref init) = init {
959 self.word_space("=");
960 self.print_expr(&init);
965 pub fn print_stmt(&mut self, st: &hir::Stmt<'_>) {
966 self.maybe_print_comment(st.span.lo());
968 hir::StmtKind::Local(ref loc) => {
969 self.print_local(loc.init.as_deref(), |this| this.print_local_decl(&loc));
971 hir::StmtKind::Item(item) => self.ann.nested(self, Nested::Item(item)),
972 hir::StmtKind::Expr(ref expr) => {
973 self.space_if_not_bol();
974 self.print_expr(&expr);
976 hir::StmtKind::Semi(ref expr) => {
977 self.space_if_not_bol();
978 self.print_expr(&expr);
982 if stmt_ends_with_semi(&st.kind) {
985 self.maybe_print_trailing_comment(st.span, None)
988 pub fn print_block(&mut self, blk: &hir::Block<'_>) {
989 self.print_block_with_attrs(blk, &[])
992 pub fn print_block_unclosed(&mut self, blk: &hir::Block<'_>) {
993 self.print_block_maybe_unclosed(blk, &[], false)
996 pub fn print_block_with_attrs(&mut self, blk: &hir::Block<'_>, attrs: &[ast::Attribute]) {
997 self.print_block_maybe_unclosed(blk, attrs, true)
1000 pub fn print_block_maybe_unclosed(
1002 blk: &hir::Block<'_>,
1003 attrs: &[ast::Attribute],
1007 hir::UnsafeBlock(..) => self.word_space("unsafe"),
1008 hir::PushUnsafeBlock(..) => self.word_space("push_unsafe"),
1009 hir::PopUnsafeBlock(..) => self.word_space("pop_unsafe"),
1010 hir::DefaultBlock => (),
1012 self.maybe_print_comment(blk.span.lo());
1013 self.ann.pre(self, AnnNode::Block(blk));
1016 self.print_inner_attributes(attrs);
1018 for st in blk.stmts {
1019 self.print_stmt(st);
1021 if let Some(ref expr) = blk.expr {
1022 self.space_if_not_bol();
1023 self.print_expr(&expr);
1024 self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi()));
1026 self.bclose_maybe_open(blk.span, close_box);
1027 self.ann.post(self, AnnNode::Block(blk))
1030 pub fn print_anon_const(&mut self, constant: &hir::AnonConst) {
1031 self.ann.nested(self, Nested::Body(constant.body))
1034 fn print_call_post(&mut self, args: &[hir::Expr<'_>]) {
1036 self.commasep_exprs(Inconsistent, args);
1040 pub fn print_expr_maybe_paren(&mut self, expr: &hir::Expr<'_>, prec: i8) {
1041 let needs_par = expr.precedence().order() < prec;
1045 self.print_expr(expr);
1051 /// Print an expr using syntax that's acceptable in a condition position, such as the `cond` in
1052 /// `if cond { ... }`.
1053 pub fn print_expr_as_cond(&mut self, expr: &hir::Expr<'_>) {
1054 let needs_par = match expr.kind {
1055 // These cases need parens due to the parse error observed in #26461: `if return {}`
1056 // parses as the erroneous construct `if (return {})`, not `if (return) {}`.
1057 hir::ExprKind::Closure(..) | hir::ExprKind::Ret(..) | hir::ExprKind::Break(..) => true,
1059 _ => contains_exterior_struct_lit(expr),
1065 self.print_expr(expr);
1071 fn print_expr_vec(&mut self, exprs: &[hir::Expr<'_>]) {
1072 self.ibox(INDENT_UNIT);
1074 self.commasep_exprs(Inconsistent, exprs);
1079 fn print_expr_repeat(&mut self, element: &hir::Expr<'_>, count: &hir::AnonConst) {
1080 self.ibox(INDENT_UNIT);
1082 self.print_expr(element);
1083 self.word_space(";");
1084 self.print_anon_const(count);
1089 fn print_expr_struct(
1091 qpath: &hir::QPath<'_>,
1092 fields: &[hir::Field<'_>],
1093 wth: &Option<&'hir hir::Expr<'_>>,
1095 self.print_qpath(qpath, true);
1101 s.ibox(INDENT_UNIT);
1102 if !field.is_shorthand {
1103 s.print_ident(field.ident);
1106 s.print_expr(&field.expr);
1113 self.ibox(INDENT_UNIT);
1114 if !fields.is_empty() {
1119 self.print_expr(&expr);
1123 if !fields.is_empty() {
1131 fn print_expr_tup(&mut self, exprs: &[hir::Expr<'_>]) {
1133 self.commasep_exprs(Inconsistent, exprs);
1134 if exprs.len() == 1 {
1140 fn print_expr_call(&mut self, func: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
1141 let prec = match func.kind {
1142 hir::ExprKind::Field(..) => parser::PREC_FORCE_PAREN,
1143 _ => parser::PREC_POSTFIX,
1146 self.print_expr_maybe_paren(func, prec);
1147 self.print_call_post(args)
1150 fn print_expr_method_call(&mut self, segment: &hir::PathSegment<'_>, args: &[hir::Expr<'_>]) {
1151 let base_args = &args[1..];
1152 self.print_expr_maybe_paren(&args[0], parser::PREC_POSTFIX);
1154 self.print_ident(segment.ident);
1156 let generic_args = segment.generic_args();
1157 if !generic_args.args.is_empty() || !generic_args.bindings.is_empty() {
1158 self.print_generic_args(generic_args, segment.infer_args, true);
1161 self.print_call_post(base_args)
1164 fn print_expr_binary(&mut self, op: hir::BinOp, lhs: &hir::Expr<'_>, rhs: &hir::Expr<'_>) {
1165 let assoc_op = bin_op_to_assoc_op(op.node);
1166 let prec = assoc_op.precedence() as i8;
1167 let fixity = assoc_op.fixity();
1169 let (left_prec, right_prec) = match fixity {
1170 Fixity::Left => (prec, prec + 1),
1171 Fixity::Right => (prec + 1, prec),
1172 Fixity::None => (prec + 1, prec + 1),
1175 let left_prec = match (&lhs.kind, op.node) {
1176 // These cases need parens: `x as i32 < y` has the parser thinking that `i32 < y` is
1177 // the beginning of a path type. It starts trying to parse `x as (i32 < y ...` instead
1178 // of `(x as i32) < ...`. We need to convince it _not_ to do that.
1179 (&hir::ExprKind::Cast { .. }, hir::BinOpKind::Lt)
1180 | (&hir::ExprKind::Cast { .. }, hir::BinOpKind::Shl) => parser::PREC_FORCE_PAREN,
1184 self.print_expr_maybe_paren(lhs, left_prec);
1186 self.word_space(op.node.as_str());
1187 self.print_expr_maybe_paren(rhs, right_prec)
1190 fn print_expr_unary(&mut self, op: hir::UnOp, expr: &hir::Expr<'_>) {
1191 self.s.word(op.as_str());
1192 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1195 fn print_expr_addr_of(
1197 kind: hir::BorrowKind,
1198 mutability: hir::Mutability,
1199 expr: &hir::Expr<'_>,
1203 hir::BorrowKind::Ref => self.print_mutability(mutability, false),
1204 hir::BorrowKind::Raw => {
1205 self.word_nbsp("raw");
1206 self.print_mutability(mutability, true);
1209 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1212 fn print_literal(&mut self, lit: &hir::Lit) {
1213 self.maybe_print_comment(lit.span.lo());
1214 self.word(lit.node.to_lit_token().to_string())
1217 pub fn print_expr(&mut self, expr: &hir::Expr<'_>) {
1218 self.maybe_print_comment(expr.span.lo());
1219 self.print_outer_attributes(&expr.attrs);
1220 self.ibox(INDENT_UNIT);
1221 self.ann.pre(self, AnnNode::Expr(expr));
1223 hir::ExprKind::Box(ref expr) => {
1224 self.word_space("box");
1225 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX);
1227 hir::ExprKind::Array(ref exprs) => {
1228 self.print_expr_vec(exprs);
1230 hir::ExprKind::Repeat(ref element, ref count) => {
1231 self.print_expr_repeat(&element, count);
1233 hir::ExprKind::Struct(ref qpath, fields, ref wth) => {
1234 self.print_expr_struct(qpath, fields, wth);
1236 hir::ExprKind::Tup(ref exprs) => {
1237 self.print_expr_tup(exprs);
1239 hir::ExprKind::Call(ref func, ref args) => {
1240 self.print_expr_call(&func, args);
1242 hir::ExprKind::MethodCall(ref segment, _, ref args) => {
1243 self.print_expr_method_call(segment, args);
1245 hir::ExprKind::Binary(op, ref lhs, ref rhs) => {
1246 self.print_expr_binary(op, &lhs, &rhs);
1248 hir::ExprKind::Unary(op, ref expr) => {
1249 self.print_expr_unary(op, &expr);
1251 hir::ExprKind::AddrOf(k, m, ref expr) => {
1252 self.print_expr_addr_of(k, m, &expr);
1254 hir::ExprKind::Lit(ref lit) => {
1255 self.print_literal(&lit);
1257 hir::ExprKind::Cast(ref expr, ref ty) => {
1258 let prec = AssocOp::As.precedence() as i8;
1259 self.print_expr_maybe_paren(&expr, prec);
1261 self.word_space("as");
1262 self.print_type(&ty);
1264 hir::ExprKind::Type(ref expr, ref ty) => {
1265 let prec = AssocOp::Colon.precedence() as i8;
1266 self.print_expr_maybe_paren(&expr, prec);
1267 self.word_space(":");
1268 self.print_type(&ty);
1270 hir::ExprKind::DropTemps(ref init) => {
1272 self.cbox(INDENT_UNIT);
1276 // Print `let _t = $init;`:
1277 let temp = ast::Ident::from_str("_t");
1278 self.print_local(Some(init), |this| this.print_ident(temp));
1282 self.space_if_not_bol();
1283 self.print_ident(temp);
1286 self.bclose_maybe_open(expr.span, true);
1288 hir::ExprKind::Loop(ref blk, opt_label, _) => {
1289 if let Some(label) = opt_label {
1290 self.print_ident(label.ident);
1291 self.word_space(":");
1295 self.print_block(&blk);
1297 hir::ExprKind::Match(ref expr, arms, _) => {
1298 self.cbox(INDENT_UNIT);
1299 self.ibox(INDENT_UNIT);
1300 self.word_nbsp("match");
1301 self.print_expr_as_cond(&expr);
1305 self.print_arm(arm);
1307 self.bclose(expr.span);
1309 hir::ExprKind::Closure(capture_clause, ref decl, body, _fn_decl_span, _gen) => {
1310 self.print_capture_clause(capture_clause);
1312 self.print_closure_params(&decl, body);
1315 // This is a bare expression.
1316 self.ann.nested(self, Nested::Body(body));
1317 self.end(); // need to close a box
1319 // A box will be closed by `print_expr`, but we didn't want an overall
1320 // wrapper so we closed the corresponding opening. so create an
1321 // empty box to satisfy the close.
1324 hir::ExprKind::Block(ref blk, opt_label) => {
1325 if let Some(label) = opt_label {
1326 self.print_ident(label.ident);
1327 self.word_space(":");
1329 // containing cbox, will be closed by print-block at `}`
1330 self.cbox(INDENT_UNIT);
1331 // head-box, will be closed by print-block after `{`
1333 self.print_block(&blk);
1335 hir::ExprKind::Assign(ref lhs, ref rhs, _) => {
1336 let prec = AssocOp::Assign.precedence() as i8;
1337 self.print_expr_maybe_paren(&lhs, prec + 1);
1339 self.word_space("=");
1340 self.print_expr_maybe_paren(&rhs, prec);
1342 hir::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
1343 let prec = AssocOp::Assign.precedence() as i8;
1344 self.print_expr_maybe_paren(&lhs, prec + 1);
1346 self.s.word(op.node.as_str());
1347 self.word_space("=");
1348 self.print_expr_maybe_paren(&rhs, prec);
1350 hir::ExprKind::Field(ref expr, ident) => {
1351 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
1353 self.print_ident(ident);
1355 hir::ExprKind::Index(ref expr, ref index) => {
1356 self.print_expr_maybe_paren(&expr, parser::PREC_POSTFIX);
1358 self.print_expr(&index);
1361 hir::ExprKind::Path(ref qpath) => self.print_qpath(qpath, true),
1362 hir::ExprKind::Break(destination, ref opt_expr) => {
1363 self.s.word("break");
1365 if let Some(label) = destination.label {
1366 self.print_ident(label.ident);
1369 if let Some(ref expr) = *opt_expr {
1370 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
1374 hir::ExprKind::Continue(destination) => {
1375 self.s.word("continue");
1377 if let Some(label) = destination.label {
1378 self.print_ident(label.ident);
1382 hir::ExprKind::Ret(ref result) => {
1383 self.s.word("return");
1384 if let Some(ref expr) = *result {
1386 self.print_expr_maybe_paren(&expr, parser::PREC_JUMP);
1389 hir::ExprKind::InlineAsm(ref a) => {
1391 self.s.word("asm!");
1393 self.print_string(&i.asm.as_str(), i.asm_str_style);
1394 self.word_space(":");
1396 let mut out_idx = 0;
1397 self.commasep(Inconsistent, &i.outputs, |s, out| {
1398 let constraint = out.constraint.as_str();
1399 let mut ch = constraint.chars();
1401 Some('=') if out.is_rw => {
1402 s.print_string(&format!("+{}", ch.as_str()), ast::StrStyle::Cooked)
1404 _ => s.print_string(&constraint, ast::StrStyle::Cooked),
1407 s.print_expr(&a.outputs_exprs[out_idx]);
1412 self.word_space(":");
1415 self.commasep(Inconsistent, &i.inputs, |s, co| {
1416 s.print_string(&co.as_str(), ast::StrStyle::Cooked);
1418 s.print_expr(&a.inputs_exprs[in_idx]);
1423 self.word_space(":");
1425 self.commasep(Inconsistent, &i.clobbers, |s, co| {
1426 s.print_string(&co.as_str(), ast::StrStyle::Cooked);
1429 let mut options = vec![];
1431 options.push("volatile");
1434 options.push("alignstack");
1436 if i.dialect == ast::AsmDialect::Intel {
1437 options.push("intel");
1440 if !options.is_empty() {
1442 self.word_space(":");
1443 self.commasep(Inconsistent, &options, |s, &co| {
1444 s.print_string(co, ast::StrStyle::Cooked);
1450 hir::ExprKind::Yield(ref expr, _) => {
1451 self.word_space("yield");
1452 self.print_expr_maybe_paren(&expr, parser::PREC_JUMP);
1454 hir::ExprKind::Err => {
1456 self.s.word("/*ERROR*/");
1460 self.ann.post(self, AnnNode::Expr(expr));
1464 pub fn print_local_decl(&mut self, loc: &hir::Local<'_>) {
1465 self.print_pat(&loc.pat);
1466 if let Some(ref ty) = loc.ty {
1467 self.word_space(":");
1468 self.print_type(&ty);
1472 pub fn print_usize(&mut self, i: usize) {
1473 self.s.word(i.to_string())
1476 pub fn print_name(&mut self, name: ast::Name) {
1477 self.print_ident(ast::Ident::with_dummy_span(name))
1480 pub fn print_for_decl(&mut self, loc: &hir::Local<'_>, coll: &hir::Expr<'_>) {
1481 self.print_local_decl(loc);
1483 self.word_space("in");
1484 self.print_expr(coll)
1487 pub fn print_path(&mut self, path: &hir::Path<'_>, colons_before_params: bool) {
1488 self.maybe_print_comment(path.span.lo());
1490 for (i, segment) in path.segments.iter().enumerate() {
1494 if segment.ident.name != kw::PathRoot {
1495 self.print_ident(segment.ident);
1496 self.print_generic_args(
1497 segment.generic_args(),
1499 colons_before_params,
1505 pub fn print_path_segment(&mut self, segment: &hir::PathSegment<'_>) {
1506 if segment.ident.name != kw::PathRoot {
1507 self.print_ident(segment.ident);
1508 self.print_generic_args(segment.generic_args(), segment.infer_args, false);
1512 pub fn print_qpath(&mut self, qpath: &hir::QPath<'_>, colons_before_params: bool) {
1514 hir::QPath::Resolved(None, ref path) => self.print_path(path, colons_before_params),
1515 hir::QPath::Resolved(Some(ref qself), ref path) => {
1517 self.print_type(qself);
1519 self.word_space("as");
1521 for (i, segment) in path.segments[..path.segments.len() - 1].iter().enumerate() {
1525 if segment.ident.name != kw::PathRoot {
1526 self.print_ident(segment.ident);
1527 self.print_generic_args(
1528 segment.generic_args(),
1530 colons_before_params,
1537 let item_segment = path.segments.last().unwrap();
1538 self.print_ident(item_segment.ident);
1539 self.print_generic_args(
1540 item_segment.generic_args(),
1541 item_segment.infer_args,
1542 colons_before_params,
1545 hir::QPath::TypeRelative(ref qself, ref item_segment) => {
1546 // If we've got a compound-qualified-path, let's push an additional pair of angle
1547 // brackets, so that we pretty-print `<<A::B>::C>` as `<A::B>::C`, instead of just
1548 // `A::B::C` (since the latter could be ambiguous to the user)
1549 if let hir::TyKind::Path(hir::QPath::Resolved(None, _)) = &qself.kind {
1550 self.print_type(qself);
1553 self.print_type(qself);
1558 self.print_ident(item_segment.ident);
1559 self.print_generic_args(
1560 item_segment.generic_args(),
1561 item_segment.infer_args,
1562 colons_before_params,
1568 fn print_generic_args(
1570 generic_args: &hir::GenericArgs<'_>,
1572 colons_before_params: bool,
1574 if generic_args.parenthesized {
1576 self.commasep(Inconsistent, generic_args.inputs(), |s, ty| s.print_type(&ty));
1579 self.space_if_not_bol();
1580 self.word_space("->");
1581 self.print_type(generic_args.bindings[0].ty());
1583 let start = if colons_before_params { "::<" } else { "<" };
1584 let empty = Cell::new(true);
1585 let start_or_comma = |this: &mut Self| {
1590 this.word_space(",")
1594 let mut nonelided_generic_args: bool = false;
1595 let elide_lifetimes = generic_args.args.iter().all(|arg| match arg {
1596 GenericArg::Lifetime(lt) => lt.is_elided(),
1598 nonelided_generic_args = true;
1603 if nonelided_generic_args {
1604 start_or_comma(self);
1608 |s, generic_arg| match generic_arg {
1609 GenericArg::Lifetime(lt) if !elide_lifetimes => s.print_lifetime(lt),
1610 GenericArg::Lifetime(_) => {}
1611 GenericArg::Type(ty) => s.print_type(ty),
1612 GenericArg::Const(ct) => s.print_anon_const(&ct.value),
1617 // FIXME(eddyb): this would leak into error messages (e.g.,
1618 // "non-exhaustive patterns: `Some::<..>(_)` not covered").
1619 if infer_args && false {
1620 start_or_comma(self);
1624 for binding in generic_args.bindings.iter() {
1625 start_or_comma(self);
1626 self.print_ident(binding.ident);
1628 match generic_args.bindings[0].kind {
1629 hir::TypeBindingKind::Equality { ref ty } => {
1630 self.word_space("=");
1631 self.print_type(ty);
1633 hir::TypeBindingKind::Constraint { bounds } => {
1634 self.print_bounds(":", bounds);
1645 pub fn print_pat(&mut self, pat: &hir::Pat<'_>) {
1646 self.maybe_print_comment(pat.span.lo());
1647 self.ann.pre(self, AnnNode::Pat(pat));
1648 // Pat isn't normalized, but the beauty of it
1649 // is that it doesn't matter
1651 PatKind::Wild => self.s.word("_"),
1652 PatKind::Binding(binding_mode, _, ident, ref sub) => {
1653 match binding_mode {
1654 hir::BindingAnnotation::Ref => {
1655 self.word_nbsp("ref");
1656 self.print_mutability(hir::Mutability::Not, false);
1658 hir::BindingAnnotation::RefMut => {
1659 self.word_nbsp("ref");
1660 self.print_mutability(hir::Mutability::Mut, false);
1662 hir::BindingAnnotation::Unannotated => {}
1663 hir::BindingAnnotation::Mutable => {
1664 self.word_nbsp("mut");
1667 self.print_ident(ident);
1668 if let Some(ref p) = *sub {
1673 PatKind::TupleStruct(ref qpath, ref elts, ddpos) => {
1674 self.print_qpath(qpath, true);
1676 if let Some(ddpos) = ddpos {
1677 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p));
1679 self.word_space(",");
1682 if ddpos != elts.len() {
1684 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p));
1687 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p));
1691 PatKind::Path(ref qpath) => {
1692 self.print_qpath(qpath, true);
1694 PatKind::Struct(ref qpath, ref fields, etc) => {
1695 self.print_qpath(qpath, true);
1697 self.word_space("{");
1702 s.cbox(INDENT_UNIT);
1703 if !f.is_shorthand {
1704 s.print_ident(f.ident);
1707 s.print_pat(&f.pat);
1713 if !fields.is_empty() {
1714 self.word_space(",");
1721 PatKind::Or(ref pats) => {
1722 self.strsep("|", true, Inconsistent, &pats[..], |s, p| s.print_pat(&p));
1724 PatKind::Tuple(ref elts, ddpos) => {
1726 if let Some(ddpos) = ddpos {
1727 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p));
1729 self.word_space(",");
1732 if ddpos != elts.len() {
1734 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p));
1737 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p));
1738 if elts.len() == 1 {
1744 PatKind::Box(ref inner) => {
1745 let is_range_inner = match inner.kind {
1746 PatKind::Range(..) => true,
1749 self.s.word("box ");
1753 self.print_pat(&inner);
1758 PatKind::Ref(ref inner, mutbl) => {
1759 let is_range_inner = match inner.kind {
1760 PatKind::Range(..) => true,
1764 self.s.word(mutbl.prefix_str());
1768 self.print_pat(&inner);
1773 PatKind::Lit(ref e) => self.print_expr(&e),
1774 PatKind::Range(ref begin, ref end, ref end_kind) => {
1775 if let Some(expr) = begin {
1776 self.print_expr(expr);
1780 RangeEnd::Included => self.s.word("..."),
1781 RangeEnd::Excluded => self.s.word(".."),
1783 if let Some(expr) = end {
1784 self.print_expr(expr);
1787 PatKind::Slice(ref before, ref slice, ref after) => {
1789 self.commasep(Inconsistent, &before[..], |s, p| s.print_pat(&p));
1790 if let Some(ref p) = *slice {
1791 if !before.is_empty() {
1792 self.word_space(",");
1794 if let PatKind::Wild = p.kind {
1800 if !after.is_empty() {
1801 self.word_space(",");
1804 self.commasep(Inconsistent, &after[..], |s, p| s.print_pat(&p));
1808 self.ann.post(self, AnnNode::Pat(pat))
1811 pub fn print_param(&mut self, arg: &hir::Param<'_>) {
1812 self.print_outer_attributes(&arg.attrs);
1813 self.print_pat(&arg.pat);
1816 pub fn print_arm(&mut self, arm: &hir::Arm<'_>) {
1817 // I have no idea why this check is necessary, but here it
1819 if arm.attrs.is_empty() {
1822 self.cbox(INDENT_UNIT);
1823 self.ann.pre(self, AnnNode::Arm(arm));
1825 self.print_outer_attributes(&arm.attrs);
1826 self.print_pat(&arm.pat);
1828 if let Some(ref g) = arm.guard {
1830 hir::Guard::If(e) => {
1831 self.word_space("if");
1832 self.print_expr(&e);
1837 self.word_space("=>");
1839 match arm.body.kind {
1840 hir::ExprKind::Block(ref blk, opt_label) => {
1841 if let Some(label) = opt_label {
1842 self.print_ident(label.ident);
1843 self.word_space(":");
1845 // the block will close the pattern's ibox
1846 self.print_block_unclosed(&blk);
1848 // If it is a user-provided unsafe block, print a comma after it
1849 if let hir::UnsafeBlock(hir::UserProvided) = blk.rules {
1854 self.end(); // close the ibox for the pattern
1855 self.print_expr(&arm.body);
1859 self.ann.post(self, AnnNode::Arm(arm));
1860 self.end() // close enclosing cbox
1865 decl: &hir::FnDecl<'_>,
1866 header: hir::FnHeader,
1867 name: Option<ast::Name>,
1868 generics: &hir::Generics<'_>,
1869 vis: &hir::Visibility<'_>,
1870 arg_names: &[ast::Ident],
1871 body_id: Option<hir::BodyId>,
1873 self.print_fn_header_info(header, vis);
1875 if let Some(name) = name {
1877 self.print_name(name);
1879 self.print_generic_params(&generics.params);
1883 // Make sure we aren't supplied *both* `arg_names` and `body_id`.
1884 assert!(arg_names.is_empty() || body_id.is_none());
1885 self.commasep(Inconsistent, &decl.inputs, |s, ty| {
1886 s.ibox(INDENT_UNIT);
1887 if let Some(arg_name) = arg_names.get(i) {
1888 s.s.word(arg_name.to_string());
1891 } else if let Some(body_id) = body_id {
1892 s.ann.nested(s, Nested::BodyParamPat(body_id, i));
1900 if decl.c_variadic {
1901 self.s.word(", ...");
1905 self.print_fn_output(decl);
1906 self.print_where_clause(&generics.where_clause)
1909 fn print_closure_params(&mut self, decl: &hir::FnDecl<'_>, body_id: hir::BodyId) {
1912 self.commasep(Inconsistent, &decl.inputs, |s, ty| {
1913 s.ibox(INDENT_UNIT);
1915 s.ann.nested(s, Nested::BodyParamPat(body_id, i));
1918 if let hir::TyKind::Infer = ty.kind {
1929 if let hir::DefaultReturn(..) = decl.output {
1933 self.space_if_not_bol();
1934 self.word_space("->");
1936 hir::Return(ref ty) => {
1937 self.print_type(&ty);
1938 self.maybe_print_comment(ty.span.lo())
1940 hir::DefaultReturn(..) => unreachable!(),
1944 pub fn print_capture_clause(&mut self, capture_clause: hir::CaptureBy) {
1945 match capture_clause {
1946 hir::CaptureBy::Value => self.word_space("move"),
1947 hir::CaptureBy::Ref => {}
1951 pub fn print_bounds<'b>(
1953 prefix: &'static str,
1954 bounds: impl IntoIterator<Item = &'b hir::GenericBound<'b>>,
1956 let mut first = true;
1957 for bound in bounds {
1959 self.s.word(prefix);
1961 if !(first && prefix.is_empty()) {
1967 self.word_space("+");
1971 GenericBound::Trait(tref, modifier) => {
1972 if modifier == &TraitBoundModifier::Maybe {
1975 self.print_poly_trait_ref(tref);
1977 GenericBound::Outlives(lt) => {
1978 self.print_lifetime(lt);
1984 pub fn print_generic_params(&mut self, generic_params: &[GenericParam<'_>]) {
1985 if !generic_params.is_empty() {
1988 self.commasep(Inconsistent, generic_params, |s, param| s.print_generic_param(param));
1994 pub fn print_generic_param(&mut self, param: &GenericParam<'_>) {
1995 if let GenericParamKind::Const { .. } = param.kind {
1996 self.word_space("const");
1999 self.print_ident(param.name.ident());
2002 GenericParamKind::Lifetime { .. } => {
2004 for bound in param.bounds {
2006 GenericBound::Outlives(ref lt) => {
2008 self.print_lifetime(lt);
2015 GenericParamKind::Type { ref default, .. } => {
2016 self.print_bounds(":", param.bounds);
2020 self.word_space("=");
2021 self.print_type(&default)
2026 GenericParamKind::Const { ref ty } => {
2027 self.word_space(":");
2033 pub fn print_lifetime(&mut self, lifetime: &hir::Lifetime) {
2034 self.print_ident(lifetime.name.ident())
2037 pub fn print_where_clause(&mut self, where_clause: &hir::WhereClause<'_>) {
2038 if where_clause.predicates.is_empty() {
2043 self.word_space("where");
2045 for (i, predicate) in where_clause.predicates.iter().enumerate() {
2047 self.word_space(",");
2051 &hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
2052 ref bound_generic_params,
2057 self.print_formal_generic_params(bound_generic_params);
2058 self.print_type(&bounded_ty);
2059 self.print_bounds(":", bounds);
2061 &hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
2066 self.print_lifetime(lifetime);
2069 for (i, bound) in bounds.iter().enumerate() {
2071 GenericBound::Outlives(lt) => {
2072 self.print_lifetime(lt);
2082 &hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
2087 self.print_type(lhs_ty);
2089 self.word_space("=");
2090 self.print_type(rhs_ty);
2096 pub fn print_mutability(&mut self, mutbl: hir::Mutability, print_const: bool) {
2098 hir::Mutability::Mut => self.word_nbsp("mut"),
2099 hir::Mutability::Not => {
2101 self.word_nbsp("const")
2107 pub fn print_mt(&mut self, mt: &hir::MutTy<'_>, print_const: bool) {
2108 self.print_mutability(mt.mutbl, print_const);
2109 self.print_type(&mt.ty)
2112 pub fn print_fn_output(&mut self, decl: &hir::FnDecl<'_>) {
2113 if let hir::DefaultReturn(..) = decl.output {
2117 self.space_if_not_bol();
2118 self.ibox(INDENT_UNIT);
2119 self.word_space("->");
2121 hir::DefaultReturn(..) => unreachable!(),
2122 hir::Return(ref ty) => self.print_type(&ty),
2127 hir::Return(ref output) => self.maybe_print_comment(output.span.lo()),
2135 unsafety: hir::Unsafety,
2136 decl: &hir::FnDecl<'_>,
2137 name: Option<ast::Name>,
2138 generic_params: &[hir::GenericParam<'_>],
2139 arg_names: &[ast::Ident],
2141 self.ibox(INDENT_UNIT);
2142 if !generic_params.is_empty() {
2144 self.print_generic_params(generic_params);
2146 let generics = hir::Generics {
2148 where_clause: hir::WhereClause { predicates: &[], span: rustc_span::DUMMY_SP },
2149 span: rustc_span::DUMMY_SP,
2156 constness: hir::Constness::NotConst,
2157 asyncness: hir::IsAsync::NotAsync,
2161 &Spanned { span: rustc_span::DUMMY_SP, node: hir::VisibilityKind::Inherited },
2168 pub fn maybe_print_trailing_comment(
2170 span: rustc_span::Span,
2171 next_pos: Option<BytePos>,
2173 if let Some(cmnts) = self.comments() {
2174 if let Some(cmnt) = cmnts.trailing_comment(span, next_pos) {
2175 self.print_comment(&cmnt);
2180 pub fn print_remaining_comments(&mut self) {
2181 // If there aren't any remaining comments, then we need to manually
2182 // make sure there is a line break at the end.
2183 if self.next_comment().is_none() {
2186 while let Some(ref cmnt) = self.next_comment() {
2187 self.print_comment(cmnt)
2191 pub fn print_opt_abi_and_extern_if_nondefault(&mut self, opt_abi: Option<Abi>) {
2193 Some(Abi::Rust) => {}
2195 self.word_nbsp("extern");
2196 self.word_nbsp(abi.to_string())
2202 pub fn print_extern_opt_abi(&mut self, opt_abi: Option<Abi>) {
2205 self.word_nbsp("extern");
2206 self.word_nbsp(abi.to_string())
2212 pub fn print_fn_header_info(&mut self, header: hir::FnHeader, vis: &hir::Visibility<'_>) {
2213 self.s.word(visibility_qualified(vis, ""));
2215 match header.constness {
2216 hir::Constness::NotConst => {}
2217 hir::Constness::Const => self.word_nbsp("const"),
2220 match header.asyncness {
2221 hir::IsAsync::NotAsync => {}
2222 hir::IsAsync::Async => self.word_nbsp("async"),
2225 self.print_unsafety(header.unsafety);
2227 if header.abi != Abi::Rust {
2228 self.word_nbsp("extern");
2229 self.word_nbsp(header.abi.to_string());
2235 pub fn print_unsafety(&mut self, s: hir::Unsafety) {
2237 hir::Unsafety::Normal => {}
2238 hir::Unsafety::Unsafe => self.word_nbsp("unsafe"),
2242 pub fn print_is_auto(&mut self, s: hir::IsAuto) {
2244 hir::IsAuto::Yes => self.word_nbsp("auto"),
2245 hir::IsAuto::No => {}
2250 /// Does this expression require a semicolon to be treated
2251 /// as a statement? The negation of this: 'can this expression
2252 /// be used as a statement without a semicolon' -- is used
2253 /// as an early-bail-out in the parser so that, for instance,
2254 /// if true {...} else {...}
2256 /// isn't parsed as (if true {...} else {...} | x) | 5
2258 // Duplicated from `parse::classify`, but adapted for the HIR.
2259 fn expr_requires_semi_to_be_stmt(e: &hir::Expr<'_>) -> bool {
2261 hir::ExprKind::Match(..) | hir::ExprKind::Block(..) | hir::ExprKind::Loop(..) => false,
2266 /// This statement requires a semicolon after it.
2267 /// note that in one case (stmt_semi), we've already
2268 /// seen the semicolon, and thus don't need another.
2269 fn stmt_ends_with_semi(stmt: &hir::StmtKind<'_>) -> bool {
2271 hir::StmtKind::Local(_) => true,
2272 hir::StmtKind::Item(_) => false,
2273 hir::StmtKind::Expr(ref e) => expr_requires_semi_to_be_stmt(&e),
2274 hir::StmtKind::Semi(..) => false,
2278 fn bin_op_to_assoc_op(op: hir::BinOpKind) -> AssocOp {
2279 use crate::hir::BinOpKind::*;
2281 Add => AssocOp::Add,
2282 Sub => AssocOp::Subtract,
2283 Mul => AssocOp::Multiply,
2284 Div => AssocOp::Divide,
2285 Rem => AssocOp::Modulus,
2287 And => AssocOp::LAnd,
2290 BitXor => AssocOp::BitXor,
2291 BitAnd => AssocOp::BitAnd,
2292 BitOr => AssocOp::BitOr,
2293 Shl => AssocOp::ShiftLeft,
2294 Shr => AssocOp::ShiftRight,
2296 Eq => AssocOp::Equal,
2297 Lt => AssocOp::Less,
2298 Le => AssocOp::LessEqual,
2299 Ne => AssocOp::NotEqual,
2300 Ge => AssocOp::GreaterEqual,
2301 Gt => AssocOp::Greater,
2305 /// Expressions that syntactically contain an "exterior" struct literal, i.e., not surrounded by any
2306 /// parens or other delimiters, e.g., `X { y: 1 }`, `X { y: 1 }.method()`, `foo == X { y: 1 }` and
2307 /// `X { y: 1 } == foo` all do, but `(X { y: 1 }) == foo` does not.
2308 fn contains_exterior_struct_lit(value: &hir::Expr<'_>) -> bool {
2310 hir::ExprKind::Struct(..) => true,
2312 hir::ExprKind::Assign(ref lhs, ref rhs, _)
2313 | hir::ExprKind::AssignOp(_, ref lhs, ref rhs)
2314 | hir::ExprKind::Binary(_, ref lhs, ref rhs) => {
2315 // `X { y: 1 } + X { y: 2 }`
2316 contains_exterior_struct_lit(&lhs) || contains_exterior_struct_lit(&rhs)
2318 hir::ExprKind::Unary(_, ref x)
2319 | hir::ExprKind::Cast(ref x, _)
2320 | hir::ExprKind::Type(ref x, _)
2321 | hir::ExprKind::Field(ref x, _)
2322 | hir::ExprKind::Index(ref x, _) => {
2323 // `&X { y: 1 }, X { y: 1 }.y`
2324 contains_exterior_struct_lit(&x)
2327 hir::ExprKind::MethodCall(.., ref exprs) => {
2328 // `X { y: 1 }.bar(...)`
2329 contains_exterior_struct_lit(&exprs[0])