1 use rustc_ast_pretty::pp::Breaks::{Consistent, Inconsistent};
2 use rustc_ast_pretty::pp::{self, Breaks};
3 use rustc_ast_pretty::pprust::{self, Comments, PrintState};
4 use rustc_span::source_map::{SourceMap, Spanned};
5 use rustc_span::symbol::kw;
6 use rustc_span::{self, BytePos, FileName};
7 use rustc_target::spec::abi::Abi;
9 use syntax::util::parser::{self, AssocOp, Fixity};
12 use crate::hir::{GenericArg, GenericParam, GenericParamKind, Node};
13 use crate::hir::{GenericBound, PatKind, RangeEnd, TraitBoundModifier};
19 pub enum AnnNode<'a> {
21 Block(&'a hir::Block<'a>),
22 Item(&'a hir::Item<'a>),
24 Expr(&'a hir::Expr<'a>),
25 Pat(&'a hir::Pat<'a>),
26 Arm(&'a hir::Arm<'a>),
31 TraitItem(hir::TraitItemId),
32 ImplItem(hir::ImplItemId),
34 BodyParamPat(hir::BodyId, usize),
38 fn nested(&self, _state: &mut State<'_>, _nested: Nested) {}
39 fn pre(&self, _state: &mut State<'_>, _node: AnnNode<'_>) {}
40 fn post(&self, _state: &mut State<'_>, _node: AnnNode<'_>) {}
41 fn try_fetch_item(&self, _: hir::HirId) -> Option<&hir::Item<'_>> {
47 impl PpAnn for NoAnn {}
48 pub const NO_ANN: &dyn PpAnn = &NoAnn;
50 impl PpAnn for hir::Crate<'a> {
51 fn try_fetch_item(&self, item: hir::HirId) -> Option<&hir::Item<'_>> {
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 pub struct State<'a> {
67 comments: Option<Comments<'a>>,
68 ann: &'a (dyn PpAnn + 'a),
72 pub fn print_node(&mut self, node: Node<'_>) {
74 Node::Param(a) => self.print_param(&a),
75 Node::Item(a) => self.print_item(&a),
76 Node::ForeignItem(a) => self.print_foreign_item(&a),
77 Node::TraitItem(a) => self.print_trait_item(a),
78 Node::ImplItem(a) => self.print_impl_item(a),
79 Node::Variant(a) => self.print_variant(&a),
80 Node::AnonConst(a) => self.print_anon_const(&a),
81 Node::Expr(a) => self.print_expr(&a),
82 Node::Stmt(a) => self.print_stmt(&a),
83 Node::PathSegment(a) => self.print_path_segment(&a),
84 Node::Ty(a) => self.print_type(&a),
85 Node::TraitRef(a) => self.print_trait_ref(&a),
86 Node::Binding(a) | Node::Pat(a) => self.print_pat(&a),
87 Node::Arm(a) => self.print_arm(&a),
89 // Containing cbox, will be closed by print-block at `}`.
90 self.cbox(INDENT_UNIT);
91 // Head-ibox, will be closed by print-block after `{`.
95 Node::Lifetime(a) => self.print_lifetime(&a),
96 Node::Visibility(a) => self.print_visibility(&a),
97 Node::GenericParam(_) => panic!("cannot print Node::GenericParam"),
98 Node::Field(_) => panic!("cannot print StructField"),
99 // These cases do not carry enough information in the
100 // `hir_map` to reconstruct their full structure for pretty
102 Node::Ctor(..) => panic!("cannot print isolated Ctor"),
103 Node::Local(a) => self.print_local_decl(&a),
104 Node::MacroDef(_) => panic!("cannot print MacroDef"),
105 Node::Crate => panic!("cannot print Crate"),
110 impl std::ops::Deref for State<'_> {
111 type Target = pp::Printer;
112 fn deref(&self) -> &Self::Target {
117 impl std::ops::DerefMut for State<'_> {
118 fn deref_mut(&mut self) -> &mut Self::Target {
123 impl<'a> PrintState<'a> for State<'a> {
124 fn comments(&mut self) -> &mut Option<Comments<'a>> {
128 fn print_ident(&mut self, ident: ast::Ident) {
129 self.s.word(pprust::ast_ident_to_string(ident, ident.is_raw_guess()));
130 self.ann.post(self, AnnNode::Name(&ident.name))
133 fn print_generic_args(&mut self, _: &ast::GenericArgs, _colons_before_params: bool) {
134 panic!("AST generic args printed by HIR pretty-printer");
138 pub const INDENT_UNIT: usize = 4;
140 /// Requires you to pass an input filename and reader so that
141 /// it can scan the input text for comments to copy forward.
142 pub fn print_crate<'a>(
144 krate: &hir::Crate<'_>,
149 let mut s = State::new_from_input(cm, filename, input, ann);
151 // When printing the AST, we sometimes need to inject `#[no_std]` here.
152 // Since you can't compile the HIR, it's not necessary.
154 s.print_mod(&krate.module, &krate.attrs);
155 s.print_remaining_comments();
160 pub fn new_from_input(
166 State { s: pp::mk_printer(), comments: Some(Comments::new(cm, filename, input)), ann }
170 pub fn to_string<F>(ann: &dyn PpAnn, f: F) -> String
172 F: FnOnce(&mut State<'_>),
174 let mut printer = State { s: pp::mk_printer(), comments: None, ann };
179 pub fn visibility_qualified<S: Into<Cow<'static, str>>>(vis: &hir::Visibility<'_>, w: S) -> String {
180 to_string(NO_ANN, |s| {
181 s.print_visibility(vis);
187 pub fn cbox(&mut self, u: usize) {
191 pub fn nbsp(&mut self) {
195 pub fn word_nbsp<S: Into<Cow<'static, str>>>(&mut self, w: S) {
200 pub fn head<S: Into<Cow<'static, str>>>(&mut self, w: S) {
202 // outer-box is consistent
203 self.cbox(INDENT_UNIT);
204 // head-box is inconsistent
205 self.ibox(w.len() + 1);
206 // keyword that starts the head
212 pub fn bopen(&mut self) {
214 self.end(); // close the head-box
217 pub fn bclose_maybe_open(&mut self, span: rustc_span::Span, close_box: bool) {
218 self.maybe_print_comment(span.hi());
219 self.break_offset_if_not_bol(1, -(INDENT_UNIT as isize));
222 self.end(); // close the outer-box
226 pub fn bclose(&mut self, span: rustc_span::Span) {
227 self.bclose_maybe_open(span, true)
230 pub fn space_if_not_bol(&mut self) {
231 if !self.s.is_beginning_of_line() {
236 pub fn break_offset_if_not_bol(&mut self, n: usize, off: isize) {
237 if !self.s.is_beginning_of_line() {
238 self.s.break_offset(n, off)
240 if off != 0 && self.s.last_token().is_hardbreak_tok() {
241 // We do something pretty sketchy here: tuck the nonzero
242 // offset-adjustment we were going to deposit along with the
243 // break into the previous hardbreak.
244 self.s.replace_last_token(pp::Printer::hardbreak_tok_offset(off));
249 // Synthesizes a comment that was not textually present in the original source
251 pub fn synth_comment(&mut self, text: String) {
259 pub fn commasep_cmnt<T, F, G>(&mut self, b: Breaks, elts: &[T], mut op: F, mut get_span: G)
261 F: FnMut(&mut State<'_>, &T),
262 G: FnMut(&T) -> rustc_span::Span,
265 let len = elts.len();
268 self.maybe_print_comment(get_span(elt).hi());
273 self.maybe_print_trailing_comment(get_span(elt), Some(get_span(&elts[i]).hi()));
274 self.space_if_not_bol();
280 pub fn commasep_exprs(&mut self, b: Breaks, exprs: &[hir::Expr<'_>]) {
281 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(&e), |e| e.span)
284 pub fn print_mod(&mut self, _mod: &hir::Mod<'_>, attrs: &[ast::Attribute]) {
285 self.print_inner_attributes(attrs);
286 for &item_id in _mod.item_ids {
287 self.ann.nested(self, Nested::Item(item_id));
291 pub fn print_foreign_mod(&mut self, nmod: &hir::ForeignMod<'_>, attrs: &[ast::Attribute]) {
292 self.print_inner_attributes(attrs);
293 for item in nmod.items {
294 self.print_foreign_item(item);
298 pub fn print_opt_lifetime(&mut self, lifetime: &hir::Lifetime) {
299 if !lifetime.is_elided() {
300 self.print_lifetime(lifetime);
305 pub fn print_type(&mut self, ty: &hir::Ty<'_>) {
306 self.maybe_print_comment(ty.span.lo());
309 hir::TyKind::Slice(ref ty) => {
311 self.print_type(&ty);
314 hir::TyKind::Ptr(ref mt) => {
316 self.print_mt(mt, true);
318 hir::TyKind::Rptr(ref lifetime, ref mt) => {
320 self.print_opt_lifetime(lifetime);
321 self.print_mt(mt, false);
323 hir::TyKind::Never => {
326 hir::TyKind::Tup(ref elts) => {
328 self.commasep(Inconsistent, &elts[..], |s, ty| s.print_type(&ty));
334 hir::TyKind::BareFn(ref f) => {
344 hir::TyKind::Def(..) => {}
345 hir::TyKind::Path(ref qpath) => self.print_qpath(qpath, false),
346 hir::TyKind::TraitObject(bounds, ref lifetime) => {
347 let mut first = true;
348 for bound in bounds {
353 self.word_space("+");
355 self.print_poly_trait_ref(bound);
357 if !lifetime.is_elided() {
359 self.word_space("+");
360 self.print_lifetime(lifetime);
363 hir::TyKind::Array(ref ty, ref length) => {
365 self.print_type(&ty);
367 self.print_anon_const(length);
370 hir::TyKind::Typeof(ref e) => {
371 self.s.word("typeof(");
372 self.print_anon_const(e);
375 hir::TyKind::Infer => {
378 hir::TyKind::Err => {
380 self.s.word("/*ERROR*/");
387 pub fn print_foreign_item(&mut self, item: &hir::ForeignItem<'_>) {
388 self.hardbreak_if_not_bol();
389 self.maybe_print_comment(item.span.lo());
390 self.print_outer_attributes(&item.attrs);
392 hir::ForeignItemKind::Fn(ref decl, ref arg_names, ref generics) => {
397 unsafety: hir::Unsafety::Normal,
398 constness: hir::Constness::NotConst,
400 asyncness: hir::IsAsync::NotAsync,
402 Some(item.ident.name),
408 self.end(); // end head-ibox
410 self.end() // end the outer fn box
412 hir::ForeignItemKind::Static(ref t, m) => {
413 self.head(visibility_qualified(&item.vis, "static"));
414 if m == hir::Mutability::Mut {
415 self.word_space("mut");
417 self.print_ident(item.ident);
418 self.word_space(":");
421 self.end(); // end the head-ibox
422 self.end() // end the outer cbox
424 hir::ForeignItemKind::Type => {
425 self.head(visibility_qualified(&item.vis, "type"));
426 self.print_ident(item.ident);
428 self.end(); // end the head-ibox
429 self.end() // end the outer cbox
434 fn print_associated_const(
438 default: Option<hir::BodyId>,
439 vis: &hir::Visibility<'_>,
441 self.s.word(visibility_qualified(vis, ""));
442 self.word_space("const");
443 self.print_ident(ident);
444 self.word_space(":");
446 if let Some(expr) = default {
448 self.word_space("=");
449 self.ann.nested(self, Nested::Body(expr));
454 fn print_associated_type(
457 generics: &hir::Generics<'_>,
458 bounds: Option<hir::GenericBounds<'_>>,
459 ty: Option<&hir::Ty<'_>>,
461 self.word_space("type");
462 self.print_ident(ident);
463 self.print_generic_params(&generics.params);
464 if let Some(bounds) = bounds {
465 self.print_bounds(":", bounds);
467 self.print_where_clause(&generics.where_clause);
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 == hir::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(
910 default.as_ref().map(|ty| &**ty),
914 self.ann.post(self, AnnNode::SubItem(ti.hir_id))
917 pub fn print_impl_item(&mut self, ii: &hir::ImplItem<'_>) {
918 self.ann.pre(self, AnnNode::SubItem(ii.hir_id));
919 self.hardbreak_if_not_bol();
920 self.maybe_print_comment(ii.span.lo());
921 self.print_outer_attributes(&ii.attrs);
922 self.print_defaultness(ii.defaultness);
925 hir::ImplItemKind::Const(ref ty, expr) => {
926 self.print_associated_const(ii.ident, &ty, Some(expr), &ii.vis);
928 hir::ImplItemKind::Method(ref sig, body) => {
930 self.print_method_sig(ii.ident, sig, &ii.generics, &ii.vis, &[], Some(body));
932 self.end(); // need to close a box
933 self.end(); // need to close a box
934 self.ann.nested(self, Nested::Body(body));
936 hir::ImplItemKind::TyAlias(ref ty) => {
937 self.print_associated_type(ii.ident, &ii.generics, None, Some(ty));
939 hir::ImplItemKind::OpaqueTy(bounds) => {
940 self.word_space("type");
941 self.print_ident(ii.ident);
942 self.print_bounds("= impl", bounds);
946 self.ann.post(self, AnnNode::SubItem(ii.hir_id))
949 pub fn print_local(&mut self, init: Option<&hir::Expr<'_>>, decl: impl Fn(&mut Self)) {
950 self.space_if_not_bol();
951 self.ibox(INDENT_UNIT);
952 self.word_nbsp("let");
954 self.ibox(INDENT_UNIT);
958 if let Some(ref init) = init {
960 self.word_space("=");
961 self.print_expr(&init);
966 pub fn print_stmt(&mut self, st: &hir::Stmt<'_>) {
967 self.maybe_print_comment(st.span.lo());
969 hir::StmtKind::Local(ref loc) => {
970 self.print_local(loc.init.as_deref(), |this| this.print_local_decl(&loc));
972 hir::StmtKind::Item(item) => self.ann.nested(self, Nested::Item(item)),
973 hir::StmtKind::Expr(ref expr) => {
974 self.space_if_not_bol();
975 self.print_expr(&expr);
977 hir::StmtKind::Semi(ref expr) => {
978 self.space_if_not_bol();
979 self.print_expr(&expr);
983 if stmt_ends_with_semi(&st.kind) {
986 self.maybe_print_trailing_comment(st.span, None)
989 pub fn print_block(&mut self, blk: &hir::Block<'_>) {
990 self.print_block_with_attrs(blk, &[])
993 pub fn print_block_unclosed(&mut self, blk: &hir::Block<'_>) {
994 self.print_block_maybe_unclosed(blk, &[], false)
997 pub fn print_block_with_attrs(&mut self, blk: &hir::Block<'_>, attrs: &[ast::Attribute]) {
998 self.print_block_maybe_unclosed(blk, attrs, true)
1001 pub fn print_block_maybe_unclosed(
1003 blk: &hir::Block<'_>,
1004 attrs: &[ast::Attribute],
1008 hir::UnsafeBlock(..) => self.word_space("unsafe"),
1009 hir::PushUnsafeBlock(..) => self.word_space("push_unsafe"),
1010 hir::PopUnsafeBlock(..) => self.word_space("pop_unsafe"),
1011 hir::DefaultBlock => (),
1013 self.maybe_print_comment(blk.span.lo());
1014 self.ann.pre(self, AnnNode::Block(blk));
1017 self.print_inner_attributes(attrs);
1019 for st in blk.stmts {
1020 self.print_stmt(st);
1022 if let Some(ref expr) = blk.expr {
1023 self.space_if_not_bol();
1024 self.print_expr(&expr);
1025 self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi()));
1027 self.bclose_maybe_open(blk.span, close_box);
1028 self.ann.post(self, AnnNode::Block(blk))
1031 pub fn print_anon_const(&mut self, constant: &hir::AnonConst) {
1032 self.ann.nested(self, Nested::Body(constant.body))
1035 fn print_call_post(&mut self, args: &[hir::Expr<'_>]) {
1037 self.commasep_exprs(Inconsistent, args);
1041 pub fn print_expr_maybe_paren(&mut self, expr: &hir::Expr<'_>, prec: i8) {
1042 let needs_par = expr.precedence().order() < prec;
1046 self.print_expr(expr);
1052 /// Print an expr using syntax that's acceptable in a condition position, such as the `cond` in
1053 /// `if cond { ... }`.
1054 pub fn print_expr_as_cond(&mut self, expr: &hir::Expr<'_>) {
1055 let needs_par = match expr.kind {
1056 // These cases need parens due to the parse error observed in #26461: `if return {}`
1057 // parses as the erroneous construct `if (return {})`, not `if (return) {}`.
1058 hir::ExprKind::Closure(..) | hir::ExprKind::Ret(..) | hir::ExprKind::Break(..) => true,
1060 _ => contains_exterior_struct_lit(expr),
1066 self.print_expr(expr);
1072 fn print_expr_vec(&mut self, exprs: &[hir::Expr<'_>]) {
1073 self.ibox(INDENT_UNIT);
1075 self.commasep_exprs(Inconsistent, exprs);
1080 fn print_expr_repeat(&mut self, element: &hir::Expr<'_>, count: &hir::AnonConst) {
1081 self.ibox(INDENT_UNIT);
1083 self.print_expr(element);
1084 self.word_space(";");
1085 self.print_anon_const(count);
1090 fn print_expr_struct(
1092 qpath: &hir::QPath<'_>,
1093 fields: &[hir::Field<'_>],
1094 wth: &Option<&'hir hir::Expr<'_>>,
1096 self.print_qpath(qpath, true);
1102 s.ibox(INDENT_UNIT);
1103 if !field.is_shorthand {
1104 s.print_ident(field.ident);
1107 s.print_expr(&field.expr);
1114 self.ibox(INDENT_UNIT);
1115 if !fields.is_empty() {
1120 self.print_expr(&expr);
1124 if !fields.is_empty() {
1132 fn print_expr_tup(&mut self, exprs: &[hir::Expr<'_>]) {
1134 self.commasep_exprs(Inconsistent, exprs);
1135 if exprs.len() == 1 {
1141 fn print_expr_call(&mut self, func: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
1142 let prec = match func.kind {
1143 hir::ExprKind::Field(..) => parser::PREC_FORCE_PAREN,
1144 _ => parser::PREC_POSTFIX,
1147 self.print_expr_maybe_paren(func, prec);
1148 self.print_call_post(args)
1151 fn print_expr_method_call(&mut self, segment: &hir::PathSegment<'_>, args: &[hir::Expr<'_>]) {
1152 let base_args = &args[1..];
1153 self.print_expr_maybe_paren(&args[0], parser::PREC_POSTFIX);
1155 self.print_ident(segment.ident);
1157 let generic_args = segment.generic_args();
1158 if !generic_args.args.is_empty() || !generic_args.bindings.is_empty() {
1159 self.print_generic_args(generic_args, segment.infer_args, true);
1162 self.print_call_post(base_args)
1165 fn print_expr_binary(&mut self, op: hir::BinOp, lhs: &hir::Expr<'_>, rhs: &hir::Expr<'_>) {
1166 let assoc_op = bin_op_to_assoc_op(op.node);
1167 let prec = assoc_op.precedence() as i8;
1168 let fixity = assoc_op.fixity();
1170 let (left_prec, right_prec) = match fixity {
1171 Fixity::Left => (prec, prec + 1),
1172 Fixity::Right => (prec + 1, prec),
1173 Fixity::None => (prec + 1, prec + 1),
1176 let left_prec = match (&lhs.kind, op.node) {
1177 // These cases need parens: `x as i32 < y` has the parser thinking that `i32 < y` is
1178 // the beginning of a path type. It starts trying to parse `x as (i32 < y ...` instead
1179 // of `(x as i32) < ...`. We need to convince it _not_ to do that.
1180 (&hir::ExprKind::Cast { .. }, hir::BinOpKind::Lt)
1181 | (&hir::ExprKind::Cast { .. }, hir::BinOpKind::Shl) => parser::PREC_FORCE_PAREN,
1185 self.print_expr_maybe_paren(lhs, left_prec);
1187 self.word_space(op.node.as_str());
1188 self.print_expr_maybe_paren(rhs, right_prec)
1191 fn print_expr_unary(&mut self, op: hir::UnOp, expr: &hir::Expr<'_>) {
1192 self.s.word(op.as_str());
1193 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1196 fn print_expr_addr_of(
1198 kind: hir::BorrowKind,
1199 mutability: hir::Mutability,
1200 expr: &hir::Expr<'_>,
1204 hir::BorrowKind::Ref => self.print_mutability(mutability, false),
1205 hir::BorrowKind::Raw => {
1206 self.word_nbsp("raw");
1207 self.print_mutability(mutability, true);
1210 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1213 fn print_literal(&mut self, lit: &hir::Lit) {
1214 self.maybe_print_comment(lit.span.lo());
1215 self.word(lit.node.to_lit_token().to_string())
1218 pub fn print_expr(&mut self, expr: &hir::Expr<'_>) {
1219 self.maybe_print_comment(expr.span.lo());
1220 self.print_outer_attributes(&expr.attrs);
1221 self.ibox(INDENT_UNIT);
1222 self.ann.pre(self, AnnNode::Expr(expr));
1224 hir::ExprKind::Box(ref expr) => {
1225 self.word_space("box");
1226 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX);
1228 hir::ExprKind::Array(ref exprs) => {
1229 self.print_expr_vec(exprs);
1231 hir::ExprKind::Repeat(ref element, ref count) => {
1232 self.print_expr_repeat(&element, count);
1234 hir::ExprKind::Struct(ref qpath, fields, ref wth) => {
1235 self.print_expr_struct(qpath, fields, wth);
1237 hir::ExprKind::Tup(ref exprs) => {
1238 self.print_expr_tup(exprs);
1240 hir::ExprKind::Call(ref func, ref args) => {
1241 self.print_expr_call(&func, args);
1243 hir::ExprKind::MethodCall(ref segment, _, ref args) => {
1244 self.print_expr_method_call(segment, args);
1246 hir::ExprKind::Binary(op, ref lhs, ref rhs) => {
1247 self.print_expr_binary(op, &lhs, &rhs);
1249 hir::ExprKind::Unary(op, ref expr) => {
1250 self.print_expr_unary(op, &expr);
1252 hir::ExprKind::AddrOf(k, m, ref expr) => {
1253 self.print_expr_addr_of(k, m, &expr);
1255 hir::ExprKind::Lit(ref lit) => {
1256 self.print_literal(&lit);
1258 hir::ExprKind::Cast(ref expr, ref ty) => {
1259 let prec = AssocOp::As.precedence() as i8;
1260 self.print_expr_maybe_paren(&expr, prec);
1262 self.word_space("as");
1263 self.print_type(&ty);
1265 hir::ExprKind::Type(ref expr, ref ty) => {
1266 let prec = AssocOp::Colon.precedence() as i8;
1267 self.print_expr_maybe_paren(&expr, prec);
1268 self.word_space(":");
1269 self.print_type(&ty);
1271 hir::ExprKind::DropTemps(ref init) => {
1273 self.cbox(INDENT_UNIT);
1277 // Print `let _t = $init;`:
1278 let temp = ast::Ident::from_str("_t");
1279 self.print_local(Some(init), |this| this.print_ident(temp));
1283 self.space_if_not_bol();
1284 self.print_ident(temp);
1287 self.bclose_maybe_open(expr.span, true);
1289 hir::ExprKind::Loop(ref blk, opt_label, _) => {
1290 if let Some(label) = opt_label {
1291 self.print_ident(label.ident);
1292 self.word_space(":");
1296 self.print_block(&blk);
1298 hir::ExprKind::Match(ref expr, arms, _) => {
1299 self.cbox(INDENT_UNIT);
1300 self.ibox(INDENT_UNIT);
1301 self.word_nbsp("match");
1302 self.print_expr_as_cond(&expr);
1306 self.print_arm(arm);
1308 self.bclose(expr.span);
1310 hir::ExprKind::Closure(capture_clause, ref decl, body, _fn_decl_span, _gen) => {
1311 self.print_capture_clause(capture_clause);
1313 self.print_closure_params(&decl, body);
1316 // This is a bare expression.
1317 self.ann.nested(self, Nested::Body(body));
1318 self.end(); // need to close a box
1320 // A box will be closed by `print_expr`, but we didn't want an overall
1321 // wrapper so we closed the corresponding opening. so create an
1322 // empty box to satisfy the close.
1325 hir::ExprKind::Block(ref blk, opt_label) => {
1326 if let Some(label) = opt_label {
1327 self.print_ident(label.ident);
1328 self.word_space(":");
1330 // containing cbox, will be closed by print-block at `}`
1331 self.cbox(INDENT_UNIT);
1332 // head-box, will be closed by print-block after `{`
1334 self.print_block(&blk);
1336 hir::ExprKind::Assign(ref lhs, ref rhs, _) => {
1337 let prec = AssocOp::Assign.precedence() as i8;
1338 self.print_expr_maybe_paren(&lhs, prec + 1);
1340 self.word_space("=");
1341 self.print_expr_maybe_paren(&rhs, prec);
1343 hir::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
1344 let prec = AssocOp::Assign.precedence() as i8;
1345 self.print_expr_maybe_paren(&lhs, prec + 1);
1347 self.s.word(op.node.as_str());
1348 self.word_space("=");
1349 self.print_expr_maybe_paren(&rhs, prec);
1351 hir::ExprKind::Field(ref expr, ident) => {
1352 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
1354 self.print_ident(ident);
1356 hir::ExprKind::Index(ref expr, ref index) => {
1357 self.print_expr_maybe_paren(&expr, parser::PREC_POSTFIX);
1359 self.print_expr(&index);
1362 hir::ExprKind::Path(ref qpath) => self.print_qpath(qpath, true),
1363 hir::ExprKind::Break(destination, ref opt_expr) => {
1364 self.s.word("break");
1366 if let Some(label) = destination.label {
1367 self.print_ident(label.ident);
1370 if let Some(ref expr) = *opt_expr {
1371 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
1375 hir::ExprKind::Continue(destination) => {
1376 self.s.word("continue");
1378 if let Some(label) = destination.label {
1379 self.print_ident(label.ident);
1383 hir::ExprKind::Ret(ref result) => {
1384 self.s.word("return");
1385 if let Some(ref expr) = *result {
1387 self.print_expr_maybe_paren(&expr, parser::PREC_JUMP);
1390 hir::ExprKind::InlineAsm(ref a) => {
1392 self.s.word("asm!");
1394 self.print_string(&i.asm.as_str(), i.asm_str_style);
1395 self.word_space(":");
1397 let mut out_idx = 0;
1398 self.commasep(Inconsistent, &i.outputs, |s, out| {
1399 let constraint = out.constraint.as_str();
1400 let mut ch = constraint.chars();
1402 Some('=') if out.is_rw => {
1403 s.print_string(&format!("+{}", ch.as_str()), ast::StrStyle::Cooked)
1405 _ => s.print_string(&constraint, ast::StrStyle::Cooked),
1408 s.print_expr(&a.outputs_exprs[out_idx]);
1413 self.word_space(":");
1416 self.commasep(Inconsistent, &i.inputs, |s, co| {
1417 s.print_string(&co.as_str(), ast::StrStyle::Cooked);
1419 s.print_expr(&a.inputs_exprs[in_idx]);
1424 self.word_space(":");
1426 self.commasep(Inconsistent, &i.clobbers, |s, co| {
1427 s.print_string(&co.as_str(), ast::StrStyle::Cooked);
1430 let mut options = vec![];
1432 options.push("volatile");
1435 options.push("alignstack");
1437 if i.dialect == ast::AsmDialect::Intel {
1438 options.push("intel");
1441 if !options.is_empty() {
1443 self.word_space(":");
1444 self.commasep(Inconsistent, &options, |s, &co| {
1445 s.print_string(co, ast::StrStyle::Cooked);
1451 hir::ExprKind::Yield(ref expr, _) => {
1452 self.word_space("yield");
1453 self.print_expr_maybe_paren(&expr, parser::PREC_JUMP);
1455 hir::ExprKind::Err => {
1457 self.s.word("/*ERROR*/");
1461 self.ann.post(self, AnnNode::Expr(expr));
1465 pub fn print_local_decl(&mut self, loc: &hir::Local<'_>) {
1466 self.print_pat(&loc.pat);
1467 if let Some(ref ty) = loc.ty {
1468 self.word_space(":");
1469 self.print_type(&ty);
1473 pub fn print_usize(&mut self, i: usize) {
1474 self.s.word(i.to_string())
1477 pub fn print_name(&mut self, name: ast::Name) {
1478 self.print_ident(ast::Ident::with_dummy_span(name))
1481 pub fn print_for_decl(&mut self, loc: &hir::Local<'_>, coll: &hir::Expr<'_>) {
1482 self.print_local_decl(loc);
1484 self.word_space("in");
1485 self.print_expr(coll)
1488 pub fn print_path(&mut self, path: &hir::Path<'_>, colons_before_params: bool) {
1489 self.maybe_print_comment(path.span.lo());
1491 for (i, segment) in path.segments.iter().enumerate() {
1495 if segment.ident.name != kw::PathRoot {
1496 self.print_ident(segment.ident);
1497 self.print_generic_args(
1498 segment.generic_args(),
1500 colons_before_params,
1506 pub fn print_path_segment(&mut self, segment: &hir::PathSegment<'_>) {
1507 if segment.ident.name != kw::PathRoot {
1508 self.print_ident(segment.ident);
1509 self.print_generic_args(segment.generic_args(), segment.infer_args, false);
1513 pub fn print_qpath(&mut self, qpath: &hir::QPath<'_>, colons_before_params: bool) {
1515 hir::QPath::Resolved(None, ref path) => self.print_path(path, colons_before_params),
1516 hir::QPath::Resolved(Some(ref qself), ref path) => {
1518 self.print_type(qself);
1520 self.word_space("as");
1522 for (i, segment) in path.segments[..path.segments.len() - 1].iter().enumerate() {
1526 if segment.ident.name != kw::PathRoot {
1527 self.print_ident(segment.ident);
1528 self.print_generic_args(
1529 segment.generic_args(),
1531 colons_before_params,
1538 let item_segment = path.segments.last().unwrap();
1539 self.print_ident(item_segment.ident);
1540 self.print_generic_args(
1541 item_segment.generic_args(),
1542 item_segment.infer_args,
1543 colons_before_params,
1546 hir::QPath::TypeRelative(ref qself, ref item_segment) => {
1547 // If we've got a compound-qualified-path, let's push an additional pair of angle
1548 // brackets, so that we pretty-print `<<A::B>::C>` as `<A::B>::C`, instead of just
1549 // `A::B::C` (since the latter could be ambiguous to the user)
1550 if let hir::TyKind::Path(hir::QPath::Resolved(None, _)) = &qself.kind {
1551 self.print_type(qself);
1554 self.print_type(qself);
1559 self.print_ident(item_segment.ident);
1560 self.print_generic_args(
1561 item_segment.generic_args(),
1562 item_segment.infer_args,
1563 colons_before_params,
1569 fn print_generic_args(
1571 generic_args: &hir::GenericArgs<'_>,
1573 colons_before_params: bool,
1575 if generic_args.parenthesized {
1577 self.commasep(Inconsistent, generic_args.inputs(), |s, ty| s.print_type(&ty));
1580 self.space_if_not_bol();
1581 self.word_space("->");
1582 self.print_type(generic_args.bindings[0].ty());
1584 let start = if colons_before_params { "::<" } else { "<" };
1585 let empty = Cell::new(true);
1586 let start_or_comma = |this: &mut Self| {
1591 this.word_space(",")
1595 let mut nonelided_generic_args: bool = false;
1596 let elide_lifetimes = generic_args.args.iter().all(|arg| match arg {
1597 GenericArg::Lifetime(lt) => lt.is_elided(),
1599 nonelided_generic_args = true;
1604 if nonelided_generic_args {
1605 start_or_comma(self);
1609 |s, generic_arg| match generic_arg {
1610 GenericArg::Lifetime(lt) if !elide_lifetimes => s.print_lifetime(lt),
1611 GenericArg::Lifetime(_) => {}
1612 GenericArg::Type(ty) => s.print_type(ty),
1613 GenericArg::Const(ct) => s.print_anon_const(&ct.value),
1618 // FIXME(eddyb): this would leak into error messages (e.g.,
1619 // "non-exhaustive patterns: `Some::<..>(_)` not covered").
1620 if infer_args && false {
1621 start_or_comma(self);
1625 for binding in generic_args.bindings.iter() {
1626 start_or_comma(self);
1627 self.print_ident(binding.ident);
1629 match generic_args.bindings[0].kind {
1630 hir::TypeBindingKind::Equality { ref ty } => {
1631 self.word_space("=");
1632 self.print_type(ty);
1634 hir::TypeBindingKind::Constraint { bounds } => {
1635 self.print_bounds(":", bounds);
1646 pub fn print_pat(&mut self, pat: &hir::Pat<'_>) {
1647 self.maybe_print_comment(pat.span.lo());
1648 self.ann.pre(self, AnnNode::Pat(pat));
1649 // Pat isn't normalized, but the beauty of it
1650 // is that it doesn't matter
1652 PatKind::Wild => self.s.word("_"),
1653 PatKind::Binding(binding_mode, _, ident, ref sub) => {
1654 match binding_mode {
1655 hir::BindingAnnotation::Ref => {
1656 self.word_nbsp("ref");
1657 self.print_mutability(hir::Mutability::Not, false);
1659 hir::BindingAnnotation::RefMut => {
1660 self.word_nbsp("ref");
1661 self.print_mutability(hir::Mutability::Mut, false);
1663 hir::BindingAnnotation::Unannotated => {}
1664 hir::BindingAnnotation::Mutable => {
1665 self.word_nbsp("mut");
1668 self.print_ident(ident);
1669 if let Some(ref p) = *sub {
1674 PatKind::TupleStruct(ref qpath, ref elts, ddpos) => {
1675 self.print_qpath(qpath, true);
1677 if let Some(ddpos) = ddpos {
1678 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p));
1680 self.word_space(",");
1683 if ddpos != elts.len() {
1685 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p));
1688 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p));
1692 PatKind::Path(ref qpath) => {
1693 self.print_qpath(qpath, true);
1695 PatKind::Struct(ref qpath, ref fields, etc) => {
1696 self.print_qpath(qpath, true);
1698 self.word_space("{");
1703 s.cbox(INDENT_UNIT);
1704 if !f.is_shorthand {
1705 s.print_ident(f.ident);
1708 s.print_pat(&f.pat);
1714 if !fields.is_empty() {
1715 self.word_space(",");
1722 PatKind::Or(ref pats) => {
1723 self.strsep("|", true, Inconsistent, &pats[..], |s, p| s.print_pat(&p));
1725 PatKind::Tuple(ref elts, ddpos) => {
1727 if let Some(ddpos) = ddpos {
1728 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p));
1730 self.word_space(",");
1733 if ddpos != elts.len() {
1735 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p));
1738 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p));
1739 if elts.len() == 1 {
1745 PatKind::Box(ref inner) => {
1746 let is_range_inner = match inner.kind {
1747 PatKind::Range(..) => true,
1750 self.s.word("box ");
1754 self.print_pat(&inner);
1759 PatKind::Ref(ref inner, mutbl) => {
1760 let is_range_inner = match inner.kind {
1761 PatKind::Range(..) => true,
1765 self.s.word(mutbl.prefix_str());
1769 self.print_pat(&inner);
1774 PatKind::Lit(ref e) => self.print_expr(&e),
1775 PatKind::Range(ref begin, ref end, ref end_kind) => {
1776 if let Some(expr) = begin {
1777 self.print_expr(expr);
1781 RangeEnd::Included => self.s.word("..."),
1782 RangeEnd::Excluded => self.s.word(".."),
1784 if let Some(expr) = end {
1785 self.print_expr(expr);
1788 PatKind::Slice(ref before, ref slice, ref after) => {
1790 self.commasep(Inconsistent, &before[..], |s, p| s.print_pat(&p));
1791 if let Some(ref p) = *slice {
1792 if !before.is_empty() {
1793 self.word_space(",");
1795 if let PatKind::Wild = p.kind {
1801 if !after.is_empty() {
1802 self.word_space(",");
1805 self.commasep(Inconsistent, &after[..], |s, p| s.print_pat(&p));
1809 self.ann.post(self, AnnNode::Pat(pat))
1812 pub fn print_param(&mut self, arg: &hir::Param<'_>) {
1813 self.print_outer_attributes(&arg.attrs);
1814 self.print_pat(&arg.pat);
1817 pub fn print_arm(&mut self, arm: &hir::Arm<'_>) {
1818 // I have no idea why this check is necessary, but here it
1820 if arm.attrs.is_empty() {
1823 self.cbox(INDENT_UNIT);
1824 self.ann.pre(self, AnnNode::Arm(arm));
1826 self.print_outer_attributes(&arm.attrs);
1827 self.print_pat(&arm.pat);
1829 if let Some(ref g) = arm.guard {
1831 hir::Guard::If(e) => {
1832 self.word_space("if");
1833 self.print_expr(&e);
1838 self.word_space("=>");
1840 match arm.body.kind {
1841 hir::ExprKind::Block(ref blk, opt_label) => {
1842 if let Some(label) = opt_label {
1843 self.print_ident(label.ident);
1844 self.word_space(":");
1846 // the block will close the pattern's ibox
1847 self.print_block_unclosed(&blk);
1849 // If it is a user-provided unsafe block, print a comma after it
1850 if let hir::UnsafeBlock(hir::UserProvided) = blk.rules {
1855 self.end(); // close the ibox for the pattern
1856 self.print_expr(&arm.body);
1860 self.ann.post(self, AnnNode::Arm(arm));
1861 self.end() // close enclosing cbox
1866 decl: &hir::FnDecl<'_>,
1867 header: hir::FnHeader,
1868 name: Option<ast::Name>,
1869 generics: &hir::Generics<'_>,
1870 vis: &hir::Visibility<'_>,
1871 arg_names: &[ast::Ident],
1872 body_id: Option<hir::BodyId>,
1874 self.print_fn_header_info(header, vis);
1876 if let Some(name) = name {
1878 self.print_name(name);
1880 self.print_generic_params(&generics.params);
1884 // Make sure we aren't supplied *both* `arg_names` and `body_id`.
1885 assert!(arg_names.is_empty() || body_id.is_none());
1886 self.commasep(Inconsistent, &decl.inputs, |s, ty| {
1887 s.ibox(INDENT_UNIT);
1888 if let Some(arg_name) = arg_names.get(i) {
1889 s.s.word(arg_name.to_string());
1892 } else if let Some(body_id) = body_id {
1893 s.ann.nested(s, Nested::BodyParamPat(body_id, i));
1901 if decl.c_variadic {
1902 self.s.word(", ...");
1906 self.print_fn_output(decl);
1907 self.print_where_clause(&generics.where_clause)
1910 fn print_closure_params(&mut self, decl: &hir::FnDecl<'_>, body_id: hir::BodyId) {
1913 self.commasep(Inconsistent, &decl.inputs, |s, ty| {
1914 s.ibox(INDENT_UNIT);
1916 s.ann.nested(s, Nested::BodyParamPat(body_id, i));
1919 if let hir::TyKind::Infer = ty.kind {
1930 if let hir::DefaultReturn(..) = decl.output {
1934 self.space_if_not_bol();
1935 self.word_space("->");
1937 hir::Return(ref ty) => {
1938 self.print_type(&ty);
1939 self.maybe_print_comment(ty.span.lo())
1941 hir::DefaultReturn(..) => unreachable!(),
1945 pub fn print_capture_clause(&mut self, capture_clause: hir::CaptureBy) {
1946 match capture_clause {
1947 hir::CaptureBy::Value => self.word_space("move"),
1948 hir::CaptureBy::Ref => {}
1952 pub fn print_bounds<'b>(
1954 prefix: &'static str,
1955 bounds: impl IntoIterator<Item = &'b hir::GenericBound<'b>>,
1957 let mut first = true;
1958 for bound in bounds {
1960 self.s.word(prefix);
1962 if !(first && prefix.is_empty()) {
1968 self.word_space("+");
1972 GenericBound::Trait(tref, modifier) => {
1973 if modifier == &TraitBoundModifier::Maybe {
1976 self.print_poly_trait_ref(tref);
1978 GenericBound::Outlives(lt) => {
1979 self.print_lifetime(lt);
1985 pub fn print_generic_params(&mut self, generic_params: &[GenericParam<'_>]) {
1986 if !generic_params.is_empty() {
1989 self.commasep(Inconsistent, generic_params, |s, param| s.print_generic_param(param));
1995 pub fn print_generic_param(&mut self, param: &GenericParam<'_>) {
1996 if let GenericParamKind::Const { .. } = param.kind {
1997 self.word_space("const");
2000 self.print_ident(param.name.ident());
2003 GenericParamKind::Lifetime { .. } => {
2005 for bound in param.bounds {
2007 GenericBound::Outlives(ref lt) => {
2009 self.print_lifetime(lt);
2016 GenericParamKind::Type { ref default, .. } => {
2017 self.print_bounds(":", param.bounds);
2021 self.word_space("=");
2022 self.print_type(&default)
2027 GenericParamKind::Const { ref ty } => {
2028 self.word_space(":");
2034 pub fn print_lifetime(&mut self, lifetime: &hir::Lifetime) {
2035 self.print_ident(lifetime.name.ident())
2038 pub fn print_where_clause(&mut self, where_clause: &hir::WhereClause<'_>) {
2039 if where_clause.predicates.is_empty() {
2044 self.word_space("where");
2046 for (i, predicate) in where_clause.predicates.iter().enumerate() {
2048 self.word_space(",");
2052 &hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
2053 ref bound_generic_params,
2058 self.print_formal_generic_params(bound_generic_params);
2059 self.print_type(&bounded_ty);
2060 self.print_bounds(":", bounds);
2062 &hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
2067 self.print_lifetime(lifetime);
2070 for (i, bound) in bounds.iter().enumerate() {
2072 GenericBound::Outlives(lt) => {
2073 self.print_lifetime(lt);
2083 &hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
2088 self.print_type(lhs_ty);
2090 self.word_space("=");
2091 self.print_type(rhs_ty);
2097 pub fn print_mutability(&mut self, mutbl: hir::Mutability, print_const: bool) {
2099 hir::Mutability::Mut => self.word_nbsp("mut"),
2100 hir::Mutability::Not => {
2102 self.word_nbsp("const")
2108 pub fn print_mt(&mut self, mt: &hir::MutTy<'_>, print_const: bool) {
2109 self.print_mutability(mt.mutbl, print_const);
2110 self.print_type(&mt.ty)
2113 pub fn print_fn_output(&mut self, decl: &hir::FnDecl<'_>) {
2114 if let hir::DefaultReturn(..) = decl.output {
2118 self.space_if_not_bol();
2119 self.ibox(INDENT_UNIT);
2120 self.word_space("->");
2122 hir::DefaultReturn(..) => unreachable!(),
2123 hir::Return(ref ty) => self.print_type(&ty),
2128 hir::Return(ref output) => self.maybe_print_comment(output.span.lo()),
2136 unsafety: hir::Unsafety,
2137 decl: &hir::FnDecl<'_>,
2138 name: Option<ast::Name>,
2139 generic_params: &[hir::GenericParam<'_>],
2140 arg_names: &[ast::Ident],
2142 self.ibox(INDENT_UNIT);
2143 if !generic_params.is_empty() {
2145 self.print_generic_params(generic_params);
2147 let generics = hir::Generics {
2149 where_clause: hir::WhereClause { predicates: &[], span: rustc_span::DUMMY_SP },
2150 span: rustc_span::DUMMY_SP,
2157 constness: hir::Constness::NotConst,
2158 asyncness: hir::IsAsync::NotAsync,
2162 &Spanned { span: rustc_span::DUMMY_SP, node: hir::VisibilityKind::Inherited },
2169 pub fn maybe_print_trailing_comment(
2171 span: rustc_span::Span,
2172 next_pos: Option<BytePos>,
2174 if let Some(cmnts) = self.comments() {
2175 if let Some(cmnt) = cmnts.trailing_comment(span, next_pos) {
2176 self.print_comment(&cmnt);
2181 pub fn print_remaining_comments(&mut self) {
2182 // If there aren't any remaining comments, then we need to manually
2183 // make sure there is a line break at the end.
2184 if self.next_comment().is_none() {
2187 while let Some(ref cmnt) = self.next_comment() {
2188 self.print_comment(cmnt)
2192 pub fn print_opt_abi_and_extern_if_nondefault(&mut self, opt_abi: Option<Abi>) {
2194 Some(Abi::Rust) => {}
2196 self.word_nbsp("extern");
2197 self.word_nbsp(abi.to_string())
2203 pub fn print_extern_opt_abi(&mut self, opt_abi: Option<Abi>) {
2206 self.word_nbsp("extern");
2207 self.word_nbsp(abi.to_string())
2213 pub fn print_fn_header_info(&mut self, header: hir::FnHeader, vis: &hir::Visibility<'_>) {
2214 self.s.word(visibility_qualified(vis, ""));
2216 match header.constness {
2217 hir::Constness::NotConst => {}
2218 hir::Constness::Const => self.word_nbsp("const"),
2221 match header.asyncness {
2222 hir::IsAsync::NotAsync => {}
2223 hir::IsAsync::Async => self.word_nbsp("async"),
2226 self.print_unsafety(header.unsafety);
2228 if header.abi != Abi::Rust {
2229 self.word_nbsp("extern");
2230 self.word_nbsp(header.abi.to_string());
2236 pub fn print_unsafety(&mut self, s: hir::Unsafety) {
2238 hir::Unsafety::Normal => {}
2239 hir::Unsafety::Unsafe => self.word_nbsp("unsafe"),
2243 pub fn print_is_auto(&mut self, s: hir::IsAuto) {
2245 hir::IsAuto::Yes => self.word_nbsp("auto"),
2246 hir::IsAuto::No => {}
2251 /// Does this expression require a semicolon to be treated
2252 /// as a statement? The negation of this: 'can this expression
2253 /// be used as a statement without a semicolon' -- is used
2254 /// as an early-bail-out in the parser so that, for instance,
2255 /// if true {...} else {...}
2257 /// isn't parsed as (if true {...} else {...} | x) | 5
2259 // Duplicated from `parse::classify`, but adapted for the HIR.
2260 fn expr_requires_semi_to_be_stmt(e: &hir::Expr<'_>) -> bool {
2262 hir::ExprKind::Match(..) | hir::ExprKind::Block(..) | hir::ExprKind::Loop(..) => false,
2267 /// This statement requires a semicolon after it.
2268 /// note that in one case (stmt_semi), we've already
2269 /// seen the semicolon, and thus don't need another.
2270 fn stmt_ends_with_semi(stmt: &hir::StmtKind<'_>) -> bool {
2272 hir::StmtKind::Local(_) => true,
2273 hir::StmtKind::Item(_) => false,
2274 hir::StmtKind::Expr(ref e) => expr_requires_semi_to_be_stmt(&e),
2275 hir::StmtKind::Semi(..) => false,
2279 fn bin_op_to_assoc_op(op: hir::BinOpKind) -> AssocOp {
2280 use crate::hir::BinOpKind::*;
2282 Add => AssocOp::Add,
2283 Sub => AssocOp::Subtract,
2284 Mul => AssocOp::Multiply,
2285 Div => AssocOp::Divide,
2286 Rem => AssocOp::Modulus,
2288 And => AssocOp::LAnd,
2291 BitXor => AssocOp::BitXor,
2292 BitAnd => AssocOp::BitAnd,
2293 BitOr => AssocOp::BitOr,
2294 Shl => AssocOp::ShiftLeft,
2295 Shr => AssocOp::ShiftRight,
2297 Eq => AssocOp::Equal,
2298 Lt => AssocOp::Less,
2299 Le => AssocOp::LessEqual,
2300 Ne => AssocOp::NotEqual,
2301 Ge => AssocOp::GreaterEqual,
2302 Gt => AssocOp::Greater,
2306 /// Expressions that syntactically contain an "exterior" struct literal, i.e., not surrounded by any
2307 /// parens or other delimiters, e.g., `X { y: 1 }`, `X { y: 1 }.method()`, `foo == X { y: 1 }` and
2308 /// `X { y: 1 } == foo` all do, but `(X { y: 1 }) == foo` does not.
2309 fn contains_exterior_struct_lit(value: &hir::Expr<'_>) -> bool {
2311 hir::ExprKind::Struct(..) => true,
2313 hir::ExprKind::Assign(ref lhs, ref rhs, _)
2314 | hir::ExprKind::AssignOp(_, ref lhs, ref rhs)
2315 | hir::ExprKind::Binary(_, ref lhs, ref rhs) => {
2316 // `X { y: 1 } + X { y: 2 }`
2317 contains_exterior_struct_lit(&lhs) || contains_exterior_struct_lit(&rhs)
2319 hir::ExprKind::Unary(_, ref x)
2320 | hir::ExprKind::Cast(ref x, _)
2321 | hir::ExprKind::Type(ref x, _)
2322 | hir::ExprKind::Field(ref x, _)
2323 | hir::ExprKind::Index(ref x, _) => {
2324 // `&X { y: 1 }, X { y: 1 }.y`
2325 contains_exterior_struct_lit(&x)
2328 hir::ExprKind::MethodCall(.., ref exprs) => {
2329 // `X { y: 1 }.bar(...)`
2330 contains_exterior_struct_lit(&exprs[0])