1 #![feature(or_patterns)]
2 #![recursion_limit = "256"]
5 use rustc_ast::util::parser::{self, AssocOp, Fixity};
6 use rustc_ast_pretty::pp::Breaks::{Consistent, Inconsistent};
7 use rustc_ast_pretty::pp::{self, Breaks};
8 use rustc_ast_pretty::pprust::{Comments, PrintState};
10 use rustc_hir::{GenericArg, GenericParam, GenericParamKind, Node};
11 use rustc_hir::{GenericBound, PatKind, RangeEnd, TraitBoundModifier};
12 use rustc_span::source_map::{SourceMap, Spanned};
13 use rustc_span::symbol::{kw, IdentPrinter};
14 use rustc_span::{self, BytePos, FileName};
15 use rustc_target::spec::abi::Abi;
21 pub fn id_to_string(map: &dyn rustc_hir::intravisit::Map<'_>, hir_id: hir::HirId) -> String {
22 to_string(&map, |s| s.print_node(map.find(hir_id).unwrap()))
25 pub enum AnnNode<'a> {
27 Block(&'a hir::Block<'a>),
28 Item(&'a hir::Item<'a>),
30 Expr(&'a hir::Expr<'a>),
31 Pat(&'a hir::Pat<'a>),
32 Arm(&'a hir::Arm<'a>),
37 TraitItem(hir::TraitItemId),
38 ImplItem(hir::ImplItemId),
40 BodyParamPat(hir::BodyId, usize),
44 fn nested(&self, _state: &mut State<'_>, _nested: Nested) {}
45 fn pre(&self, _state: &mut State<'_>, _node: AnnNode<'_>) {}
46 fn post(&self, _state: &mut State<'_>, _node: AnnNode<'_>) {}
47 fn try_fetch_item(&self, _: hir::HirId) -> Option<&hir::Item<'_>> {
53 impl PpAnn for NoAnn {}
54 pub const NO_ANN: &dyn PpAnn = &NoAnn;
56 impl PpAnn for hir::Crate<'_> {
57 fn try_fetch_item(&self, item: hir::HirId) -> Option<&hir::Item<'_>> {
60 fn nested(&self, state: &mut State<'_>, nested: Nested) {
62 Nested::Item(id) => state.print_item(self.item(id.id)),
63 Nested::TraitItem(id) => state.print_trait_item(self.trait_item(id)),
64 Nested::ImplItem(id) => state.print_impl_item(self.impl_item(id)),
65 Nested::Body(id) => state.print_expr(&self.body(id).value),
66 Nested::BodyParamPat(id, i) => state.print_pat(&self.body(id).params[i].pat),
71 /// Identical to the `PpAnn` implementation for `hir::Crate`,
72 /// except it avoids creating a dependency on the whole crate.
73 impl PpAnn for &dyn rustc_hir::intravisit::Map<'_> {
74 fn nested(&self, state: &mut State<'_>, nested: Nested) {
76 Nested::Item(id) => state.print_item(self.item(id.id)),
77 Nested::TraitItem(id) => state.print_trait_item(self.trait_item(id)),
78 Nested::ImplItem(id) => state.print_impl_item(self.impl_item(id)),
79 Nested::Body(id) => state.print_expr(&self.body(id).value),
80 Nested::BodyParamPat(id, i) => state.print_pat(&self.body(id).params[i].pat),
85 pub struct State<'a> {
87 comments: Option<Comments<'a>>,
88 ann: &'a (dyn PpAnn + 'a),
92 pub fn print_node(&mut self, node: Node<'_>) {
94 Node::Param(a) => self.print_param(&a),
95 Node::Item(a) => self.print_item(&a),
96 Node::ForeignItem(a) => self.print_foreign_item(&a),
97 Node::TraitItem(a) => self.print_trait_item(a),
98 Node::ImplItem(a) => self.print_impl_item(a),
99 Node::Variant(a) => self.print_variant(&a),
100 Node::AnonConst(a) => self.print_anon_const(&a),
101 Node::Expr(a) => self.print_expr(&a),
102 Node::Stmt(a) => self.print_stmt(&a),
103 Node::PathSegment(a) => self.print_path_segment(&a),
104 Node::Ty(a) => self.print_type(&a),
105 Node::TraitRef(a) => self.print_trait_ref(&a),
106 Node::Binding(a) | Node::Pat(a) => self.print_pat(&a),
107 Node::Arm(a) => self.print_arm(&a),
109 // Containing cbox, will be closed by print-block at `}`.
110 self.cbox(INDENT_UNIT);
111 // Head-ibox, will be closed by print-block after `{`.
115 Node::Lifetime(a) => self.print_lifetime(&a),
116 Node::Visibility(a) => self.print_visibility(&a),
117 Node::GenericParam(_) => panic!("cannot print Node::GenericParam"),
118 Node::Field(_) => panic!("cannot print StructField"),
119 // These cases do not carry enough information in the
120 // `hir_map` to reconstruct their full structure for pretty
122 Node::Ctor(..) => panic!("cannot print isolated Ctor"),
123 Node::Local(a) => self.print_local_decl(&a),
124 Node::MacroDef(_) => panic!("cannot print MacroDef"),
125 Node::Crate(..) => panic!("cannot print Crate"),
130 impl std::ops::Deref for State<'_> {
131 type Target = pp::Printer;
132 fn deref(&self) -> &Self::Target {
137 impl std::ops::DerefMut for State<'_> {
138 fn deref_mut(&mut self) -> &mut Self::Target {
143 impl<'a> PrintState<'a> for State<'a> {
144 fn comments(&mut self) -> &mut Option<Comments<'a>> {
148 fn print_ident(&mut self, ident: ast::Ident) {
149 self.s.word(IdentPrinter::for_ast_ident(ident, ident.is_raw_guess()).to_string());
150 self.ann.post(self, AnnNode::Name(&ident.name))
153 fn print_generic_args(&mut self, _: &ast::GenericArgs, _colons_before_params: bool) {
154 panic!("AST generic args printed by HIR pretty-printer");
158 pub const INDENT_UNIT: usize = 4;
160 /// Requires you to pass an input filename and reader so that
161 /// it can scan the input text for comments to copy forward.
162 pub fn print_crate<'a>(
164 krate: &hir::Crate<'_>,
169 let mut s = State::new_from_input(sm, filename, input, ann);
171 // When printing the AST, we sometimes need to inject `#[no_std]` here.
172 // Since you can't compile the HIR, it's not necessary.
174 s.print_mod(&krate.item.module, &krate.item.attrs);
175 s.print_remaining_comments();
180 pub fn new_from_input(
186 State { s: pp::mk_printer(), comments: Some(Comments::new(sm, filename, input)), ann }
190 pub fn to_string<F>(ann: &dyn PpAnn, f: F) -> String
192 F: FnOnce(&mut State<'_>),
194 let mut printer = State { s: pp::mk_printer(), comments: None, ann };
199 pub fn visibility_qualified<S: Into<Cow<'static, str>>>(vis: &hir::Visibility<'_>, w: S) -> String {
200 to_string(NO_ANN, |s| {
201 s.print_visibility(vis);
207 pub fn cbox(&mut self, u: usize) {
211 pub fn nbsp(&mut self) {
215 pub fn word_nbsp<S: Into<Cow<'static, str>>>(&mut self, w: S) {
220 pub fn head<S: Into<Cow<'static, str>>>(&mut self, w: S) {
222 // outer-box is consistent
223 self.cbox(INDENT_UNIT);
224 // head-box is inconsistent
225 self.ibox(w.len() + 1);
226 // keyword that starts the head
232 pub fn bopen(&mut self) {
234 self.end(); // close the head-box
237 pub fn bclose_maybe_open(&mut self, span: rustc_span::Span, close_box: bool) {
238 self.maybe_print_comment(span.hi());
239 self.break_offset_if_not_bol(1, -(INDENT_UNIT as isize));
242 self.end(); // close the outer-box
246 pub fn bclose(&mut self, span: rustc_span::Span) {
247 self.bclose_maybe_open(span, true)
250 pub fn space_if_not_bol(&mut self) {
251 if !self.s.is_beginning_of_line() {
256 pub fn break_offset_if_not_bol(&mut self, n: usize, off: isize) {
257 if !self.s.is_beginning_of_line() {
258 self.s.break_offset(n, off)
260 if off != 0 && self.s.last_token().is_hardbreak_tok() {
261 // We do something pretty sketchy here: tuck the nonzero
262 // offset-adjustment we were going to deposit along with the
263 // break into the previous hardbreak.
264 self.s.replace_last_token(pp::Printer::hardbreak_tok_offset(off));
269 // Synthesizes a comment that was not textually present in the original source
271 pub fn synth_comment(&mut self, text: String) {
279 pub fn commasep_cmnt<T, F, G>(&mut self, b: Breaks, elts: &[T], mut op: F, mut get_span: G)
281 F: FnMut(&mut State<'_>, &T),
282 G: FnMut(&T) -> rustc_span::Span,
285 let len = elts.len();
288 self.maybe_print_comment(get_span(elt).hi());
293 self.maybe_print_trailing_comment(get_span(elt), Some(get_span(&elts[i]).hi()));
294 self.space_if_not_bol();
300 pub fn commasep_exprs(&mut self, b: Breaks, exprs: &[hir::Expr<'_>]) {
301 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(&e), |e| e.span)
304 pub fn print_mod(&mut self, _mod: &hir::Mod<'_>, attrs: &[ast::Attribute]) {
305 self.print_inner_attributes(attrs);
306 for &item_id in _mod.item_ids {
307 self.ann.nested(self, Nested::Item(item_id));
311 pub fn print_foreign_mod(&mut self, nmod: &hir::ForeignMod<'_>, attrs: &[ast::Attribute]) {
312 self.print_inner_attributes(attrs);
313 for item in nmod.items {
314 self.print_foreign_item(item);
318 pub fn print_opt_lifetime(&mut self, lifetime: &hir::Lifetime) {
319 if !lifetime.is_elided() {
320 self.print_lifetime(lifetime);
325 pub fn print_type(&mut self, ty: &hir::Ty<'_>) {
326 self.maybe_print_comment(ty.span.lo());
329 hir::TyKind::Slice(ref ty) => {
331 self.print_type(&ty);
334 hir::TyKind::Ptr(ref mt) => {
336 self.print_mt(mt, true);
338 hir::TyKind::Rptr(ref lifetime, ref mt) => {
340 self.print_opt_lifetime(lifetime);
341 self.print_mt(mt, false);
343 hir::TyKind::Never => {
346 hir::TyKind::Tup(ref elts) => {
348 self.commasep(Inconsistent, &elts[..], |s, ty| s.print_type(&ty));
354 hir::TyKind::BareFn(ref f) => {
364 hir::TyKind::Def(..) => {}
365 hir::TyKind::Path(ref qpath) => self.print_qpath(qpath, false),
366 hir::TyKind::TraitObject(bounds, ref lifetime) => {
367 let mut first = true;
368 for bound in bounds {
373 self.word_space("+");
375 self.print_poly_trait_ref(bound);
377 if !lifetime.is_elided() {
379 self.word_space("+");
380 self.print_lifetime(lifetime);
383 hir::TyKind::Array(ref ty, ref length) => {
385 self.print_type(&ty);
387 self.print_anon_const(length);
390 hir::TyKind::Typeof(ref e) => {
391 self.s.word("typeof(");
392 self.print_anon_const(e);
395 hir::TyKind::Infer => {
398 hir::TyKind::Err => {
400 self.s.word("/*ERROR*/");
407 pub fn print_foreign_item(&mut self, item: &hir::ForeignItem<'_>) {
408 self.hardbreak_if_not_bol();
409 self.maybe_print_comment(item.span.lo());
410 self.print_outer_attributes(&item.attrs);
412 hir::ForeignItemKind::Fn(ref decl, ref arg_names, ref generics) => {
417 unsafety: hir::Unsafety::Normal,
418 constness: hir::Constness::NotConst,
420 asyncness: hir::IsAsync::NotAsync,
422 Some(item.ident.name),
428 self.end(); // end head-ibox
430 self.end() // end the outer fn box
432 hir::ForeignItemKind::Static(ref t, m) => {
433 self.head(visibility_qualified(&item.vis, "static"));
434 if m == hir::Mutability::Mut {
435 self.word_space("mut");
437 self.print_ident(item.ident);
438 self.word_space(":");
441 self.end(); // end the head-ibox
442 self.end() // end the outer cbox
444 hir::ForeignItemKind::Type => {
445 self.head(visibility_qualified(&item.vis, "type"));
446 self.print_ident(item.ident);
448 self.end(); // end the head-ibox
449 self.end() // end the outer cbox
454 fn print_associated_const(
458 default: Option<hir::BodyId>,
459 vis: &hir::Visibility<'_>,
461 self.s.word(visibility_qualified(vis, ""));
462 self.word_space("const");
463 self.print_ident(ident);
464 self.word_space(":");
466 if let Some(expr) = default {
468 self.word_space("=");
469 self.ann.nested(self, Nested::Body(expr));
474 fn print_associated_type(
477 generics: &hir::Generics<'_>,
478 bounds: Option<hir::GenericBounds<'_>>,
479 ty: Option<&hir::Ty<'_>>,
481 self.word_space("type");
482 self.print_ident(ident);
483 self.print_generic_params(&generics.params);
484 if let Some(bounds) = bounds {
485 self.print_bounds(":", bounds);
487 self.print_where_clause(&generics.where_clause);
488 if let Some(ty) = ty {
490 self.word_space("=");
498 item: &hir::Item<'_>,
499 generics: &hir::Generics<'_>,
500 inner: impl Fn(&mut Self),
502 self.head(visibility_qualified(&item.vis, "type"));
503 self.print_ident(item.ident);
504 self.print_generic_params(&generics.params);
505 self.end(); // end the inner ibox
507 self.print_where_clause(&generics.where_clause);
511 self.end(); // end the outer ibox
514 /// Pretty-print an item
515 pub fn print_item(&mut self, item: &hir::Item<'_>) {
516 self.hardbreak_if_not_bol();
517 self.maybe_print_comment(item.span.lo());
518 self.print_outer_attributes(&item.attrs);
519 self.ann.pre(self, AnnNode::Item(item));
521 hir::ItemKind::ExternCrate(orig_name) => {
522 self.head(visibility_qualified(&item.vis, "extern crate"));
523 if let Some(orig_name) = orig_name {
524 self.print_name(orig_name);
529 self.print_ident(item.ident);
531 self.end(); // end inner head-block
532 self.end(); // end outer head-block
534 hir::ItemKind::Use(ref path, kind) => {
535 self.head(visibility_qualified(&item.vis, "use"));
536 self.print_path(path, false);
539 hir::UseKind::Single => {
540 if path.segments.last().unwrap().ident != item.ident {
542 self.word_space("as");
543 self.print_ident(item.ident);
547 hir::UseKind::Glob => self.s.word("::*;"),
548 hir::UseKind::ListStem => self.s.word("::{};"),
550 self.end(); // end inner head-block
551 self.end(); // end outer head-block
553 hir::ItemKind::Static(ref ty, m, expr) => {
554 self.head(visibility_qualified(&item.vis, "static"));
555 if m == hir::Mutability::Mut {
556 self.word_space("mut");
558 self.print_ident(item.ident);
559 self.word_space(":");
560 self.print_type(&ty);
562 self.end(); // end the head-ibox
564 self.word_space("=");
565 self.ann.nested(self, Nested::Body(expr));
567 self.end(); // end the outer cbox
569 hir::ItemKind::Const(ref ty, expr) => {
570 self.head(visibility_qualified(&item.vis, "const"));
571 self.print_ident(item.ident);
572 self.word_space(":");
573 self.print_type(&ty);
575 self.end(); // end the head-ibox
577 self.word_space("=");
578 self.ann.nested(self, Nested::Body(expr));
580 self.end(); // end the outer cbox
582 hir::ItemKind::Fn(ref sig, ref param_names, body) => {
587 Some(item.ident.name),
594 self.end(); // need to close a box
595 self.end(); // need to close a box
596 self.ann.nested(self, Nested::Body(body));
598 hir::ItemKind::Mod(ref _mod) => {
599 self.head(visibility_qualified(&item.vis, "mod"));
600 self.print_ident(item.ident);
603 self.print_mod(_mod, &item.attrs);
604 self.bclose(item.span);
606 hir::ItemKind::ForeignMod(ref nmod) => {
608 self.word_nbsp(nmod.abi.to_string());
610 self.print_foreign_mod(nmod, &item.attrs);
611 self.bclose(item.span);
613 hir::ItemKind::GlobalAsm(ref ga) => {
614 self.head(visibility_qualified(&item.vis, "global asm"));
615 self.s.word(ga.asm.to_string());
618 hir::ItemKind::TyAlias(ref ty, ref generics) => {
619 self.print_item_type(item, &generics, |state| {
620 state.word_space("=");
621 state.print_type(&ty);
624 hir::ItemKind::OpaqueTy(ref opaque_ty) => {
625 self.print_item_type(item, &opaque_ty.generics, |state| {
626 let mut real_bounds = Vec::with_capacity(opaque_ty.bounds.len());
627 for b in opaque_ty.bounds.iter() {
628 if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
630 state.word_space("for ?");
631 state.print_trait_ref(&ptr.trait_ref);
636 state.print_bounds("= impl", real_bounds);
639 hir::ItemKind::Enum(ref enum_definition, ref params) => {
640 self.print_enum_def(enum_definition, params, item.ident.name, item.span, &item.vis);
642 hir::ItemKind::Struct(ref struct_def, ref generics) => {
643 self.head(visibility_qualified(&item.vis, "struct"));
644 self.print_struct(struct_def, generics, item.ident.name, item.span, true);
646 hir::ItemKind::Union(ref struct_def, ref generics) => {
647 self.head(visibility_qualified(&item.vis, "union"));
648 self.print_struct(struct_def, generics, item.ident.name, item.span, true);
650 hir::ItemKind::Impl {
662 self.print_visibility(&item.vis);
663 self.print_defaultness(defaultness);
664 self.print_unsafety(unsafety);
665 self.word_nbsp("impl");
667 if !generics.params.is_empty() {
668 self.print_generic_params(&generics.params);
672 if constness == hir::Constness::Const {
673 self.word_nbsp("const");
676 if let hir::ImplPolarity::Negative(_) = polarity {
680 if let Some(ref t) = of_trait {
681 self.print_trait_ref(t);
683 self.word_space("for");
686 self.print_type(&self_ty);
687 self.print_where_clause(&generics.where_clause);
691 self.print_inner_attributes(&item.attrs);
692 for impl_item in items {
693 self.ann.nested(self, Nested::ImplItem(impl_item.id));
695 self.bclose(item.span);
697 hir::ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, trait_items) => {
699 self.print_visibility(&item.vis);
700 self.print_is_auto(is_auto);
701 self.print_unsafety(unsafety);
702 self.word_nbsp("trait");
703 self.print_ident(item.ident);
704 self.print_generic_params(&generics.params);
705 let mut real_bounds = Vec::with_capacity(bounds.len());
706 for b in bounds.iter() {
707 if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
709 self.word_space("for ?");
710 self.print_trait_ref(&ptr.trait_ref);
715 self.print_bounds(":", real_bounds);
716 self.print_where_clause(&generics.where_clause);
719 for trait_item in trait_items {
720 self.ann.nested(self, Nested::TraitItem(trait_item.id));
722 self.bclose(item.span);
724 hir::ItemKind::TraitAlias(ref generics, ref bounds) => {
726 self.print_visibility(&item.vis);
727 self.word_nbsp("trait");
728 self.print_ident(item.ident);
729 self.print_generic_params(&generics.params);
730 let mut real_bounds = Vec::with_capacity(bounds.len());
731 // FIXME(durka) this seems to be some quite outdated syntax
732 for b in bounds.iter() {
733 if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
735 self.word_space("for ?");
736 self.print_trait_ref(&ptr.trait_ref);
742 self.print_bounds("=", real_bounds);
743 self.print_where_clause(&generics.where_clause);
747 self.ann.post(self, AnnNode::Item(item))
750 pub fn print_trait_ref(&mut self, t: &hir::TraitRef<'_>) {
751 self.print_path(&t.path, false)
754 fn print_formal_generic_params(&mut self, generic_params: &[hir::GenericParam<'_>]) {
755 if !generic_params.is_empty() {
757 self.print_generic_params(generic_params);
762 fn print_poly_trait_ref(&mut self, t: &hir::PolyTraitRef<'_>) {
763 self.print_formal_generic_params(&t.bound_generic_params);
764 self.print_trait_ref(&t.trait_ref)
767 pub fn print_enum_def(
769 enum_definition: &hir::EnumDef<'_>,
770 generics: &hir::Generics<'_>,
772 span: rustc_span::Span,
773 visibility: &hir::Visibility<'_>,
775 self.head(visibility_qualified(visibility, "enum"));
776 self.print_name(name);
777 self.print_generic_params(&generics.params);
778 self.print_where_clause(&generics.where_clause);
780 self.print_variants(&enum_definition.variants, span)
783 pub fn print_variants(&mut self, variants: &[hir::Variant<'_>], span: rustc_span::Span) {
786 self.space_if_not_bol();
787 self.maybe_print_comment(v.span.lo());
788 self.print_outer_attributes(&v.attrs);
789 self.ibox(INDENT_UNIT);
790 self.print_variant(v);
793 self.maybe_print_trailing_comment(v.span, None);
798 pub fn print_visibility(&mut self, vis: &hir::Visibility<'_>) {
800 hir::VisibilityKind::Public => self.word_nbsp("pub"),
801 hir::VisibilityKind::Crate(ast::CrateSugar::JustCrate) => self.word_nbsp("crate"),
802 hir::VisibilityKind::Crate(ast::CrateSugar::PubCrate) => self.word_nbsp("pub(crate)"),
803 hir::VisibilityKind::Restricted { ref path, .. } => {
805 if path.segments.len() == 1 && path.segments[0].ident.name == kw::Super {
806 // Special case: `super` can print like `pub(super)`.
807 self.s.word("super");
809 // Everything else requires `in` at present.
810 self.word_nbsp("in");
811 self.print_path(path, false);
815 hir::VisibilityKind::Inherited => (),
819 pub fn print_defaultness(&mut self, defaultness: hir::Defaultness) {
821 hir::Defaultness::Default { .. } => self.word_nbsp("default"),
822 hir::Defaultness::Final => (),
828 struct_def: &hir::VariantData<'_>,
829 generics: &hir::Generics<'_>,
831 span: rustc_span::Span,
832 print_finalizer: bool,
834 self.print_name(name);
835 self.print_generic_params(&generics.params);
837 hir::VariantData::Tuple(..) | hir::VariantData::Unit(..) => {
838 if let hir::VariantData::Tuple(..) = struct_def {
840 self.commasep(Inconsistent, struct_def.fields(), |s, field| {
841 s.maybe_print_comment(field.span.lo());
842 s.print_outer_attributes(&field.attrs);
843 s.print_visibility(&field.vis);
844 s.print_type(&field.ty)
848 self.print_where_clause(&generics.where_clause);
853 self.end() // close the outer-box
855 hir::VariantData::Struct(..) => {
856 self.print_where_clause(&generics.where_clause);
859 self.hardbreak_if_not_bol();
861 for field in struct_def.fields() {
862 self.hardbreak_if_not_bol();
863 self.maybe_print_comment(field.span.lo());
864 self.print_outer_attributes(&field.attrs);
865 self.print_visibility(&field.vis);
866 self.print_ident(field.ident);
868 self.print_type(&field.ty);
877 pub fn print_variant(&mut self, v: &hir::Variant<'_>) {
879 let generics = hir::Generics::empty();
880 self.print_struct(&v.data, &generics, v.ident.name, v.span, false);
881 if let Some(ref d) = v.disr_expr {
883 self.word_space("=");
884 self.print_anon_const(d);
887 pub fn print_method_sig(
891 generics: &hir::Generics<'_>,
892 vis: &hir::Visibility<'_>,
893 arg_names: &[ast::Ident],
894 body_id: Option<hir::BodyId>,
896 self.print_fn(&m.decl, m.header, Some(ident.name), generics, vis, arg_names, body_id)
899 pub fn print_trait_item(&mut self, ti: &hir::TraitItem<'_>) {
900 self.ann.pre(self, AnnNode::SubItem(ti.hir_id));
901 self.hardbreak_if_not_bol();
902 self.maybe_print_comment(ti.span.lo());
903 self.print_outer_attributes(&ti.attrs);
905 hir::TraitItemKind::Const(ref ty, default) => {
907 Spanned { span: rustc_span::DUMMY_SP, node: hir::VisibilityKind::Inherited };
908 self.print_associated_const(ti.ident, &ty, default, &vis);
910 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Required(ref arg_names)) => {
912 Spanned { span: rustc_span::DUMMY_SP, node: hir::VisibilityKind::Inherited };
913 self.print_method_sig(ti.ident, sig, &ti.generics, &vis, arg_names, None);
916 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Provided(body)) => {
918 Spanned { span: rustc_span::DUMMY_SP, node: hir::VisibilityKind::Inherited };
920 self.print_method_sig(ti.ident, sig, &ti.generics, &vis, &[], Some(body));
922 self.end(); // need to close a box
923 self.end(); // need to close a box
924 self.ann.nested(self, Nested::Body(body));
926 hir::TraitItemKind::Type(ref bounds, ref default) => {
927 self.print_associated_type(
931 default.as_ref().map(|ty| &**ty),
935 self.ann.post(self, AnnNode::SubItem(ti.hir_id))
938 pub fn print_impl_item(&mut self, ii: &hir::ImplItem<'_>) {
939 self.ann.pre(self, AnnNode::SubItem(ii.hir_id));
940 self.hardbreak_if_not_bol();
941 self.maybe_print_comment(ii.span.lo());
942 self.print_outer_attributes(&ii.attrs);
943 self.print_defaultness(ii.defaultness);
946 hir::ImplItemKind::Const(ref ty, expr) => {
947 self.print_associated_const(ii.ident, &ty, Some(expr), &ii.vis);
949 hir::ImplItemKind::Fn(ref sig, body) => {
951 self.print_method_sig(ii.ident, sig, &ii.generics, &ii.vis, &[], Some(body));
953 self.end(); // need to close a box
954 self.end(); // need to close a box
955 self.ann.nested(self, Nested::Body(body));
957 hir::ImplItemKind::TyAlias(ref ty) => {
958 self.print_associated_type(ii.ident, &ii.generics, None, Some(ty));
960 hir::ImplItemKind::OpaqueTy(bounds) => {
961 self.word_space("type");
962 self.print_ident(ii.ident);
963 self.print_bounds("= impl", bounds);
967 self.ann.post(self, AnnNode::SubItem(ii.hir_id))
970 pub fn print_local(&mut self, init: Option<&hir::Expr<'_>>, decl: impl Fn(&mut Self)) {
971 self.space_if_not_bol();
972 self.ibox(INDENT_UNIT);
973 self.word_nbsp("let");
975 self.ibox(INDENT_UNIT);
979 if let Some(ref init) = init {
981 self.word_space("=");
982 self.print_expr(&init);
987 pub fn print_stmt(&mut self, st: &hir::Stmt<'_>) {
988 self.maybe_print_comment(st.span.lo());
990 hir::StmtKind::Local(ref loc) => {
991 self.print_local(loc.init.as_deref(), |this| this.print_local_decl(&loc));
993 hir::StmtKind::Item(item) => self.ann.nested(self, Nested::Item(item)),
994 hir::StmtKind::Expr(ref expr) => {
995 self.space_if_not_bol();
996 self.print_expr(&expr);
998 hir::StmtKind::Semi(ref expr) => {
999 self.space_if_not_bol();
1000 self.print_expr(&expr);
1004 if stmt_ends_with_semi(&st.kind) {
1007 self.maybe_print_trailing_comment(st.span, None)
1010 pub fn print_block(&mut self, blk: &hir::Block<'_>) {
1011 self.print_block_with_attrs(blk, &[])
1014 pub fn print_block_unclosed(&mut self, blk: &hir::Block<'_>) {
1015 self.print_block_maybe_unclosed(blk, &[], false)
1018 pub fn print_block_with_attrs(&mut self, blk: &hir::Block<'_>, attrs: &[ast::Attribute]) {
1019 self.print_block_maybe_unclosed(blk, attrs, true)
1022 pub fn print_block_maybe_unclosed(
1024 blk: &hir::Block<'_>,
1025 attrs: &[ast::Attribute],
1029 hir::BlockCheckMode::UnsafeBlock(..) => self.word_space("unsafe"),
1030 hir::BlockCheckMode::PushUnsafeBlock(..) => self.word_space("push_unsafe"),
1031 hir::BlockCheckMode::PopUnsafeBlock(..) => self.word_space("pop_unsafe"),
1032 hir::BlockCheckMode::DefaultBlock => (),
1034 self.maybe_print_comment(blk.span.lo());
1035 self.ann.pre(self, AnnNode::Block(blk));
1038 self.print_inner_attributes(attrs);
1040 for st in blk.stmts {
1041 self.print_stmt(st);
1043 if let Some(ref expr) = blk.expr {
1044 self.space_if_not_bol();
1045 self.print_expr(&expr);
1046 self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi()));
1048 self.bclose_maybe_open(blk.span, close_box);
1049 self.ann.post(self, AnnNode::Block(blk))
1052 pub fn print_anon_const(&mut self, constant: &hir::AnonConst) {
1053 self.ann.nested(self, Nested::Body(constant.body))
1056 fn print_call_post(&mut self, args: &[hir::Expr<'_>]) {
1058 self.commasep_exprs(Inconsistent, args);
1062 pub fn print_expr_maybe_paren(&mut self, expr: &hir::Expr<'_>, prec: i8) {
1063 let needs_par = expr.precedence().order() < prec;
1067 self.print_expr(expr);
1073 /// Print an expr using syntax that's acceptable in a condition position, such as the `cond` in
1074 /// `if cond { ... }`.
1075 pub fn print_expr_as_cond(&mut self, expr: &hir::Expr<'_>) {
1076 let needs_par = match expr.kind {
1077 // These cases need parens due to the parse error observed in #26461: `if return {}`
1078 // parses as the erroneous construct `if (return {})`, not `if (return) {}`.
1079 hir::ExprKind::Closure(..) | hir::ExprKind::Ret(..) | hir::ExprKind::Break(..) => true,
1081 _ => contains_exterior_struct_lit(expr),
1087 self.print_expr(expr);
1093 fn print_expr_vec(&mut self, exprs: &[hir::Expr<'_>]) {
1094 self.ibox(INDENT_UNIT);
1096 self.commasep_exprs(Inconsistent, exprs);
1101 fn print_expr_repeat(&mut self, element: &hir::Expr<'_>, count: &hir::AnonConst) {
1102 self.ibox(INDENT_UNIT);
1104 self.print_expr(element);
1105 self.word_space(";");
1106 self.print_anon_const(count);
1111 fn print_expr_struct(
1113 qpath: &hir::QPath<'_>,
1114 fields: &[hir::Field<'_>],
1115 wth: &Option<&hir::Expr<'_>>,
1117 self.print_qpath(qpath, true);
1123 s.ibox(INDENT_UNIT);
1124 if !field.is_shorthand {
1125 s.print_ident(field.ident);
1128 s.print_expr(&field.expr);
1135 self.ibox(INDENT_UNIT);
1136 if !fields.is_empty() {
1141 self.print_expr(&expr);
1145 if !fields.is_empty() {
1153 fn print_expr_tup(&mut self, exprs: &[hir::Expr<'_>]) {
1155 self.commasep_exprs(Inconsistent, exprs);
1156 if exprs.len() == 1 {
1162 fn print_expr_call(&mut self, func: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
1163 let prec = match func.kind {
1164 hir::ExprKind::Field(..) => parser::PREC_FORCE_PAREN,
1165 _ => parser::PREC_POSTFIX,
1168 self.print_expr_maybe_paren(func, prec);
1169 self.print_call_post(args)
1172 fn print_expr_method_call(&mut self, segment: &hir::PathSegment<'_>, args: &[hir::Expr<'_>]) {
1173 let base_args = &args[1..];
1174 self.print_expr_maybe_paren(&args[0], parser::PREC_POSTFIX);
1176 self.print_ident(segment.ident);
1178 let generic_args = segment.generic_args();
1179 if !generic_args.args.is_empty() || !generic_args.bindings.is_empty() {
1180 self.print_generic_args(generic_args, segment.infer_args, true);
1183 self.print_call_post(base_args)
1186 fn print_expr_binary(&mut self, op: hir::BinOp, lhs: &hir::Expr<'_>, rhs: &hir::Expr<'_>) {
1187 let assoc_op = bin_op_to_assoc_op(op.node);
1188 let prec = assoc_op.precedence() as i8;
1189 let fixity = assoc_op.fixity();
1191 let (left_prec, right_prec) = match fixity {
1192 Fixity::Left => (prec, prec + 1),
1193 Fixity::Right => (prec + 1, prec),
1194 Fixity::None => (prec + 1, prec + 1),
1197 let left_prec = match (&lhs.kind, op.node) {
1198 // These cases need parens: `x as i32 < y` has the parser thinking that `i32 < y` is
1199 // the beginning of a path type. It starts trying to parse `x as (i32 < y ...` instead
1200 // of `(x as i32) < ...`. We need to convince it _not_ to do that.
1201 (&hir::ExprKind::Cast { .. }, hir::BinOpKind::Lt | hir::BinOpKind::Shl) => {
1202 parser::PREC_FORCE_PAREN
1207 self.print_expr_maybe_paren(lhs, left_prec);
1209 self.word_space(op.node.as_str());
1210 self.print_expr_maybe_paren(rhs, right_prec)
1213 fn print_expr_unary(&mut self, op: hir::UnOp, expr: &hir::Expr<'_>) {
1214 self.s.word(op.as_str());
1215 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1218 fn print_expr_addr_of(
1220 kind: hir::BorrowKind,
1221 mutability: hir::Mutability,
1222 expr: &hir::Expr<'_>,
1226 hir::BorrowKind::Ref => self.print_mutability(mutability, false),
1227 hir::BorrowKind::Raw => {
1228 self.word_nbsp("raw");
1229 self.print_mutability(mutability, true);
1232 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1235 fn print_literal(&mut self, lit: &hir::Lit) {
1236 self.maybe_print_comment(lit.span.lo());
1237 self.word(lit.node.to_lit_token().to_string())
1240 pub fn print_expr(&mut self, expr: &hir::Expr<'_>) {
1241 self.maybe_print_comment(expr.span.lo());
1242 self.print_outer_attributes(&expr.attrs);
1243 self.ibox(INDENT_UNIT);
1244 self.ann.pre(self, AnnNode::Expr(expr));
1246 hir::ExprKind::Box(ref expr) => {
1247 self.word_space("box");
1248 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX);
1250 hir::ExprKind::Array(ref exprs) => {
1251 self.print_expr_vec(exprs);
1253 hir::ExprKind::Repeat(ref element, ref count) => {
1254 self.print_expr_repeat(&element, count);
1256 hir::ExprKind::Struct(ref qpath, fields, ref wth) => {
1257 self.print_expr_struct(qpath, fields, wth);
1259 hir::ExprKind::Tup(ref exprs) => {
1260 self.print_expr_tup(exprs);
1262 hir::ExprKind::Call(ref func, ref args) => {
1263 self.print_expr_call(&func, args);
1265 hir::ExprKind::MethodCall(ref segment, _, ref args) => {
1266 self.print_expr_method_call(segment, args);
1268 hir::ExprKind::Binary(op, ref lhs, ref rhs) => {
1269 self.print_expr_binary(op, &lhs, &rhs);
1271 hir::ExprKind::Unary(op, ref expr) => {
1272 self.print_expr_unary(op, &expr);
1274 hir::ExprKind::AddrOf(k, m, ref expr) => {
1275 self.print_expr_addr_of(k, m, &expr);
1277 hir::ExprKind::Lit(ref lit) => {
1278 self.print_literal(&lit);
1280 hir::ExprKind::Cast(ref expr, ref ty) => {
1281 let prec = AssocOp::As.precedence() as i8;
1282 self.print_expr_maybe_paren(&expr, prec);
1284 self.word_space("as");
1285 self.print_type(&ty);
1287 hir::ExprKind::Type(ref expr, ref ty) => {
1288 let prec = AssocOp::Colon.precedence() as i8;
1289 self.print_expr_maybe_paren(&expr, prec);
1290 self.word_space(":");
1291 self.print_type(&ty);
1293 hir::ExprKind::DropTemps(ref init) => {
1295 self.cbox(INDENT_UNIT);
1299 // Print `let _t = $init;`:
1300 let temp = ast::Ident::from_str("_t");
1301 self.print_local(Some(init), |this| this.print_ident(temp));
1305 self.space_if_not_bol();
1306 self.print_ident(temp);
1309 self.bclose_maybe_open(expr.span, true);
1311 hir::ExprKind::Loop(ref blk, opt_label, _) => {
1312 if let Some(label) = opt_label {
1313 self.print_ident(label.ident);
1314 self.word_space(":");
1318 self.print_block(&blk);
1320 hir::ExprKind::Match(ref expr, arms, _) => {
1321 self.cbox(INDENT_UNIT);
1322 self.ibox(INDENT_UNIT);
1323 self.word_nbsp("match");
1324 self.print_expr_as_cond(&expr);
1328 self.print_arm(arm);
1330 self.bclose(expr.span);
1332 hir::ExprKind::Closure(capture_clause, ref decl, body, _fn_decl_span, _gen) => {
1333 self.print_capture_clause(capture_clause);
1335 self.print_closure_params(&decl, body);
1338 // This is a bare expression.
1339 self.ann.nested(self, Nested::Body(body));
1340 self.end(); // need to close a box
1342 // A box will be closed by `print_expr`, but we didn't want an overall
1343 // wrapper so we closed the corresponding opening. so create an
1344 // empty box to satisfy the close.
1347 hir::ExprKind::Block(ref blk, opt_label) => {
1348 if let Some(label) = opt_label {
1349 self.print_ident(label.ident);
1350 self.word_space(":");
1352 // containing cbox, will be closed by print-block at `}`
1353 self.cbox(INDENT_UNIT);
1354 // head-box, will be closed by print-block after `{`
1356 self.print_block(&blk);
1358 hir::ExprKind::Assign(ref lhs, ref rhs, _) => {
1359 let prec = AssocOp::Assign.precedence() as i8;
1360 self.print_expr_maybe_paren(&lhs, prec + 1);
1362 self.word_space("=");
1363 self.print_expr_maybe_paren(&rhs, prec);
1365 hir::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
1366 let prec = AssocOp::Assign.precedence() as i8;
1367 self.print_expr_maybe_paren(&lhs, prec + 1);
1369 self.s.word(op.node.as_str());
1370 self.word_space("=");
1371 self.print_expr_maybe_paren(&rhs, prec);
1373 hir::ExprKind::Field(ref expr, ident) => {
1374 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
1376 self.print_ident(ident);
1378 hir::ExprKind::Index(ref expr, ref index) => {
1379 self.print_expr_maybe_paren(&expr, parser::PREC_POSTFIX);
1381 self.print_expr(&index);
1384 hir::ExprKind::Path(ref qpath) => self.print_qpath(qpath, true),
1385 hir::ExprKind::Break(destination, ref opt_expr) => {
1386 self.s.word("break");
1388 if let Some(label) = destination.label {
1389 self.print_ident(label.ident);
1392 if let Some(ref expr) = *opt_expr {
1393 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
1397 hir::ExprKind::Continue(destination) => {
1398 self.s.word("continue");
1400 if let Some(label) = destination.label {
1401 self.print_ident(label.ident);
1405 hir::ExprKind::Ret(ref result) => {
1406 self.s.word("return");
1407 if let Some(ref expr) = *result {
1409 self.print_expr_maybe_paren(&expr, parser::PREC_JUMP);
1412 hir::ExprKind::LlvmInlineAsm(ref a) => {
1414 self.s.word("llvm_asm!");
1416 self.print_string(&i.asm.as_str(), i.asm_str_style);
1417 self.word_space(":");
1419 let mut out_idx = 0;
1420 self.commasep(Inconsistent, &i.outputs, |s, out| {
1421 let constraint = out.constraint.as_str();
1422 let mut ch = constraint.chars();
1424 Some('=') if out.is_rw => {
1425 s.print_string(&format!("+{}", ch.as_str()), ast::StrStyle::Cooked)
1427 _ => s.print_string(&constraint, ast::StrStyle::Cooked),
1430 s.print_expr(&a.outputs_exprs[out_idx]);
1435 self.word_space(":");
1438 self.commasep(Inconsistent, &i.inputs, |s, co| {
1439 s.print_string(&co.as_str(), ast::StrStyle::Cooked);
1441 s.print_expr(&a.inputs_exprs[in_idx]);
1446 self.word_space(":");
1448 self.commasep(Inconsistent, &i.clobbers, |s, co| {
1449 s.print_string(&co.as_str(), ast::StrStyle::Cooked);
1452 let mut options = vec![];
1454 options.push("volatile");
1457 options.push("alignstack");
1459 if i.dialect == ast::LlvmAsmDialect::Intel {
1460 options.push("intel");
1463 if !options.is_empty() {
1465 self.word_space(":");
1466 self.commasep(Inconsistent, &options, |s, &co| {
1467 s.print_string(co, ast::StrStyle::Cooked);
1473 hir::ExprKind::Yield(ref expr, _) => {
1474 self.word_space("yield");
1475 self.print_expr_maybe_paren(&expr, parser::PREC_JUMP);
1477 hir::ExprKind::Err => {
1479 self.s.word("/*ERROR*/");
1483 self.ann.post(self, AnnNode::Expr(expr));
1487 pub fn print_local_decl(&mut self, loc: &hir::Local<'_>) {
1488 self.print_pat(&loc.pat);
1489 if let Some(ref ty) = loc.ty {
1490 self.word_space(":");
1491 self.print_type(&ty);
1495 pub fn print_usize(&mut self, i: usize) {
1496 self.s.word(i.to_string())
1499 pub fn print_name(&mut self, name: ast::Name) {
1500 self.print_ident(ast::Ident::with_dummy_span(name))
1503 pub fn print_for_decl(&mut self, loc: &hir::Local<'_>, coll: &hir::Expr<'_>) {
1504 self.print_local_decl(loc);
1506 self.word_space("in");
1507 self.print_expr(coll)
1510 pub fn print_path(&mut self, path: &hir::Path<'_>, colons_before_params: bool) {
1511 self.maybe_print_comment(path.span.lo());
1513 for (i, segment) in path.segments.iter().enumerate() {
1517 if segment.ident.name != kw::PathRoot {
1518 self.print_ident(segment.ident);
1519 self.print_generic_args(
1520 segment.generic_args(),
1522 colons_before_params,
1528 pub fn print_path_segment(&mut self, segment: &hir::PathSegment<'_>) {
1529 if segment.ident.name != kw::PathRoot {
1530 self.print_ident(segment.ident);
1531 self.print_generic_args(segment.generic_args(), segment.infer_args, false);
1535 pub fn print_qpath(&mut self, qpath: &hir::QPath<'_>, colons_before_params: bool) {
1537 hir::QPath::Resolved(None, ref path) => self.print_path(path, colons_before_params),
1538 hir::QPath::Resolved(Some(ref qself), ref path) => {
1540 self.print_type(qself);
1542 self.word_space("as");
1544 for (i, segment) in path.segments[..path.segments.len() - 1].iter().enumerate() {
1548 if segment.ident.name != kw::PathRoot {
1549 self.print_ident(segment.ident);
1550 self.print_generic_args(
1551 segment.generic_args(),
1553 colons_before_params,
1560 let item_segment = path.segments.last().unwrap();
1561 self.print_ident(item_segment.ident);
1562 self.print_generic_args(
1563 item_segment.generic_args(),
1564 item_segment.infer_args,
1565 colons_before_params,
1568 hir::QPath::TypeRelative(ref qself, ref item_segment) => {
1569 // If we've got a compound-qualified-path, let's push an additional pair of angle
1570 // brackets, so that we pretty-print `<<A::B>::C>` as `<A::B>::C`, instead of just
1571 // `A::B::C` (since the latter could be ambiguous to the user)
1572 if let hir::TyKind::Path(hir::QPath::Resolved(None, _)) = &qself.kind {
1573 self.print_type(qself);
1576 self.print_type(qself);
1581 self.print_ident(item_segment.ident);
1582 self.print_generic_args(
1583 item_segment.generic_args(),
1584 item_segment.infer_args,
1585 colons_before_params,
1591 fn print_generic_args(
1593 generic_args: &hir::GenericArgs<'_>,
1595 colons_before_params: bool,
1597 if generic_args.parenthesized {
1599 self.commasep(Inconsistent, generic_args.inputs(), |s, ty| s.print_type(&ty));
1602 self.space_if_not_bol();
1603 self.word_space("->");
1604 self.print_type(generic_args.bindings[0].ty());
1606 let start = if colons_before_params { "::<" } else { "<" };
1607 let empty = Cell::new(true);
1608 let start_or_comma = |this: &mut Self| {
1613 this.word_space(",")
1617 let mut nonelided_generic_args: bool = false;
1618 let elide_lifetimes = generic_args.args.iter().all(|arg| match arg {
1619 GenericArg::Lifetime(lt) => lt.is_elided(),
1621 nonelided_generic_args = true;
1626 if nonelided_generic_args {
1627 start_or_comma(self);
1631 |s, generic_arg| match generic_arg {
1632 GenericArg::Lifetime(lt) if !elide_lifetimes => s.print_lifetime(lt),
1633 GenericArg::Lifetime(_) => {}
1634 GenericArg::Type(ty) => s.print_type(ty),
1635 GenericArg::Const(ct) => s.print_anon_const(&ct.value),
1640 // FIXME(eddyb): this would leak into error messages (e.g.,
1641 // "non-exhaustive patterns: `Some::<..>(_)` not covered").
1642 if infer_args && false {
1643 start_or_comma(self);
1647 for binding in generic_args.bindings.iter() {
1648 start_or_comma(self);
1649 self.print_ident(binding.ident);
1651 match generic_args.bindings[0].kind {
1652 hir::TypeBindingKind::Equality { ref ty } => {
1653 self.word_space("=");
1654 self.print_type(ty);
1656 hir::TypeBindingKind::Constraint { bounds } => {
1657 self.print_bounds(":", bounds);
1668 pub fn print_pat(&mut self, pat: &hir::Pat<'_>) {
1669 self.maybe_print_comment(pat.span.lo());
1670 self.ann.pre(self, AnnNode::Pat(pat));
1671 // Pat isn't normalized, but the beauty of it
1672 // is that it doesn't matter
1674 PatKind::Wild => self.s.word("_"),
1675 PatKind::Binding(binding_mode, _, ident, ref sub) => {
1676 match binding_mode {
1677 hir::BindingAnnotation::Ref => {
1678 self.word_nbsp("ref");
1679 self.print_mutability(hir::Mutability::Not, false);
1681 hir::BindingAnnotation::RefMut => {
1682 self.word_nbsp("ref");
1683 self.print_mutability(hir::Mutability::Mut, false);
1685 hir::BindingAnnotation::Unannotated => {}
1686 hir::BindingAnnotation::Mutable => {
1687 self.word_nbsp("mut");
1690 self.print_ident(ident);
1691 if let Some(ref p) = *sub {
1696 PatKind::TupleStruct(ref qpath, ref elts, ddpos) => {
1697 self.print_qpath(qpath, true);
1699 if let Some(ddpos) = ddpos {
1700 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p));
1702 self.word_space(",");
1705 if ddpos != elts.len() {
1707 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p));
1710 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p));
1714 PatKind::Path(ref qpath) => {
1715 self.print_qpath(qpath, true);
1717 PatKind::Struct(ref qpath, ref fields, etc) => {
1718 self.print_qpath(qpath, true);
1720 self.word_space("{");
1725 s.cbox(INDENT_UNIT);
1726 if !f.is_shorthand {
1727 s.print_ident(f.ident);
1730 s.print_pat(&f.pat);
1736 if !fields.is_empty() {
1737 self.word_space(",");
1744 PatKind::Or(ref pats) => {
1745 self.strsep("|", true, Inconsistent, &pats[..], |s, p| s.print_pat(&p));
1747 PatKind::Tuple(ref elts, ddpos) => {
1749 if let Some(ddpos) = ddpos {
1750 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p));
1752 self.word_space(",");
1755 if ddpos != elts.len() {
1757 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p));
1760 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p));
1761 if elts.len() == 1 {
1767 PatKind::Box(ref inner) => {
1768 let is_range_inner = match inner.kind {
1769 PatKind::Range(..) => true,
1772 self.s.word("box ");
1776 self.print_pat(&inner);
1781 PatKind::Ref(ref inner, mutbl) => {
1782 let is_range_inner = match inner.kind {
1783 PatKind::Range(..) => true,
1787 self.s.word(mutbl.prefix_str());
1791 self.print_pat(&inner);
1796 PatKind::Lit(ref e) => self.print_expr(&e),
1797 PatKind::Range(ref begin, ref end, ref end_kind) => {
1798 if let Some(expr) = begin {
1799 self.print_expr(expr);
1803 RangeEnd::Included => self.s.word("..."),
1804 RangeEnd::Excluded => self.s.word(".."),
1806 if let Some(expr) = end {
1807 self.print_expr(expr);
1810 PatKind::Slice(ref before, ref slice, ref after) => {
1812 self.commasep(Inconsistent, &before[..], |s, p| s.print_pat(&p));
1813 if let Some(ref p) = *slice {
1814 if !before.is_empty() {
1815 self.word_space(",");
1817 if let PatKind::Wild = p.kind {
1823 if !after.is_empty() {
1824 self.word_space(",");
1827 self.commasep(Inconsistent, &after[..], |s, p| s.print_pat(&p));
1831 self.ann.post(self, AnnNode::Pat(pat))
1834 pub fn print_param(&mut self, arg: &hir::Param<'_>) {
1835 self.print_outer_attributes(&arg.attrs);
1836 self.print_pat(&arg.pat);
1839 pub fn print_arm(&mut self, arm: &hir::Arm<'_>) {
1840 // I have no idea why this check is necessary, but here it
1842 if arm.attrs.is_empty() {
1845 self.cbox(INDENT_UNIT);
1846 self.ann.pre(self, AnnNode::Arm(arm));
1848 self.print_outer_attributes(&arm.attrs);
1849 self.print_pat(&arm.pat);
1851 if let Some(ref g) = arm.guard {
1853 hir::Guard::If(e) => {
1854 self.word_space("if");
1855 self.print_expr(&e);
1860 self.word_space("=>");
1862 match arm.body.kind {
1863 hir::ExprKind::Block(ref blk, opt_label) => {
1864 if let Some(label) = opt_label {
1865 self.print_ident(label.ident);
1866 self.word_space(":");
1868 // the block will close the pattern's ibox
1869 self.print_block_unclosed(&blk);
1871 // If it is a user-provided unsafe block, print a comma after it
1872 if let hir::BlockCheckMode::UnsafeBlock(hir::UnsafeSource::UserProvided) = blk.rules
1878 self.end(); // close the ibox for the pattern
1879 self.print_expr(&arm.body);
1883 self.ann.post(self, AnnNode::Arm(arm));
1884 self.end() // close enclosing cbox
1889 decl: &hir::FnDecl<'_>,
1890 header: hir::FnHeader,
1891 name: Option<ast::Name>,
1892 generics: &hir::Generics<'_>,
1893 vis: &hir::Visibility<'_>,
1894 arg_names: &[ast::Ident],
1895 body_id: Option<hir::BodyId>,
1897 self.print_fn_header_info(header, vis);
1899 if let Some(name) = name {
1901 self.print_name(name);
1903 self.print_generic_params(&generics.params);
1907 // Make sure we aren't supplied *both* `arg_names` and `body_id`.
1908 assert!(arg_names.is_empty() || body_id.is_none());
1909 self.commasep(Inconsistent, &decl.inputs, |s, ty| {
1910 s.ibox(INDENT_UNIT);
1911 if let Some(arg_name) = arg_names.get(i) {
1912 s.s.word(arg_name.to_string());
1915 } else if let Some(body_id) = body_id {
1916 s.ann.nested(s, Nested::BodyParamPat(body_id, i));
1924 if decl.c_variadic {
1925 self.s.word(", ...");
1929 self.print_fn_output(decl);
1930 self.print_where_clause(&generics.where_clause)
1933 fn print_closure_params(&mut self, decl: &hir::FnDecl<'_>, body_id: hir::BodyId) {
1936 self.commasep(Inconsistent, &decl.inputs, |s, ty| {
1937 s.ibox(INDENT_UNIT);
1939 s.ann.nested(s, Nested::BodyParamPat(body_id, i));
1942 if let hir::TyKind::Infer = ty.kind {
1953 if let hir::FnRetTy::DefaultReturn(..) = decl.output {
1957 self.space_if_not_bol();
1958 self.word_space("->");
1960 hir::FnRetTy::Return(ref ty) => {
1961 self.print_type(&ty);
1962 self.maybe_print_comment(ty.span.lo())
1964 hir::FnRetTy::DefaultReturn(..) => unreachable!(),
1968 pub fn print_capture_clause(&mut self, capture_clause: hir::CaptureBy) {
1969 match capture_clause {
1970 hir::CaptureBy::Value => self.word_space("move"),
1971 hir::CaptureBy::Ref => {}
1975 pub fn print_bounds<'b>(
1977 prefix: &'static str,
1978 bounds: impl IntoIterator<Item = &'b hir::GenericBound<'b>>,
1980 let mut first = true;
1981 for bound in bounds {
1983 self.s.word(prefix);
1985 if !(first && prefix.is_empty()) {
1991 self.word_space("+");
1995 GenericBound::Trait(tref, modifier) => {
1996 if modifier == &TraitBoundModifier::Maybe {
1999 self.print_poly_trait_ref(tref);
2001 GenericBound::Outlives(lt) => {
2002 self.print_lifetime(lt);
2008 pub fn print_generic_params(&mut self, generic_params: &[GenericParam<'_>]) {
2009 if !generic_params.is_empty() {
2012 self.commasep(Inconsistent, generic_params, |s, param| s.print_generic_param(param));
2018 pub fn print_generic_param(&mut self, param: &GenericParam<'_>) {
2019 if let GenericParamKind::Const { .. } = param.kind {
2020 self.word_space("const");
2023 self.print_ident(param.name.ident());
2026 GenericParamKind::Lifetime { .. } => {
2028 for bound in param.bounds {
2030 GenericBound::Outlives(ref lt) => {
2032 self.print_lifetime(lt);
2039 GenericParamKind::Type { ref default, .. } => {
2040 self.print_bounds(":", param.bounds);
2041 if let Some(default) = default {
2043 self.word_space("=");
2044 self.print_type(&default)
2047 GenericParamKind::Const { ref ty } => {
2048 self.word_space(":");
2054 pub fn print_lifetime(&mut self, lifetime: &hir::Lifetime) {
2055 self.print_ident(lifetime.name.ident())
2058 pub fn print_where_clause(&mut self, where_clause: &hir::WhereClause<'_>) {
2059 if where_clause.predicates.is_empty() {
2064 self.word_space("where");
2066 for (i, predicate) in where_clause.predicates.iter().enumerate() {
2068 self.word_space(",");
2072 &hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
2073 ref bound_generic_params,
2078 self.print_formal_generic_params(bound_generic_params);
2079 self.print_type(&bounded_ty);
2080 self.print_bounds(":", bounds);
2082 &hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
2087 self.print_lifetime(lifetime);
2090 for (i, bound) in bounds.iter().enumerate() {
2092 GenericBound::Outlives(lt) => {
2093 self.print_lifetime(lt);
2103 &hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
2108 self.print_type(lhs_ty);
2110 self.word_space("=");
2111 self.print_type(rhs_ty);
2117 pub fn print_mutability(&mut self, mutbl: hir::Mutability, print_const: bool) {
2119 hir::Mutability::Mut => self.word_nbsp("mut"),
2120 hir::Mutability::Not => {
2122 self.word_nbsp("const")
2128 pub fn print_mt(&mut self, mt: &hir::MutTy<'_>, print_const: bool) {
2129 self.print_mutability(mt.mutbl, print_const);
2130 self.print_type(&mt.ty)
2133 pub fn print_fn_output(&mut self, decl: &hir::FnDecl<'_>) {
2134 if let hir::FnRetTy::DefaultReturn(..) = decl.output {
2138 self.space_if_not_bol();
2139 self.ibox(INDENT_UNIT);
2140 self.word_space("->");
2142 hir::FnRetTy::DefaultReturn(..) => unreachable!(),
2143 hir::FnRetTy::Return(ref ty) => self.print_type(&ty),
2147 if let hir::FnRetTy::Return(ref output) = decl.output {
2148 self.maybe_print_comment(output.span.lo())
2155 unsafety: hir::Unsafety,
2156 decl: &hir::FnDecl<'_>,
2157 name: Option<ast::Name>,
2158 generic_params: &[hir::GenericParam<'_>],
2159 arg_names: &[ast::Ident],
2161 self.ibox(INDENT_UNIT);
2162 if !generic_params.is_empty() {
2164 self.print_generic_params(generic_params);
2166 let generics = hir::Generics {
2168 where_clause: hir::WhereClause { predicates: &[], span: rustc_span::DUMMY_SP },
2169 span: rustc_span::DUMMY_SP,
2176 constness: hir::Constness::NotConst,
2177 asyncness: hir::IsAsync::NotAsync,
2181 &Spanned { span: rustc_span::DUMMY_SP, node: hir::VisibilityKind::Inherited },
2188 pub fn maybe_print_trailing_comment(
2190 span: rustc_span::Span,
2191 next_pos: Option<BytePos>,
2193 if let Some(cmnts) = self.comments() {
2194 if let Some(cmnt) = cmnts.trailing_comment(span, next_pos) {
2195 self.print_comment(&cmnt);
2200 pub fn print_remaining_comments(&mut self) {
2201 // If there aren't any remaining comments, then we need to manually
2202 // make sure there is a line break at the end.
2203 if self.next_comment().is_none() {
2206 while let Some(ref cmnt) = self.next_comment() {
2207 self.print_comment(cmnt)
2211 pub fn print_opt_abi_and_extern_if_nondefault(&mut self, opt_abi: Option<Abi>) {
2213 Some(Abi::Rust) => {}
2215 self.word_nbsp("extern");
2216 self.word_nbsp(abi.to_string())
2222 pub fn print_extern_opt_abi(&mut self, opt_abi: Option<Abi>) {
2223 if let Some(abi) = opt_abi {
2224 self.word_nbsp("extern");
2225 self.word_nbsp(abi.to_string())
2229 pub fn print_fn_header_info(&mut self, header: hir::FnHeader, vis: &hir::Visibility<'_>) {
2230 self.s.word(visibility_qualified(vis, ""));
2232 match header.constness {
2233 hir::Constness::NotConst => {}
2234 hir::Constness::Const => self.word_nbsp("const"),
2237 match header.asyncness {
2238 hir::IsAsync::NotAsync => {}
2239 hir::IsAsync::Async => self.word_nbsp("async"),
2242 self.print_unsafety(header.unsafety);
2244 if header.abi != Abi::Rust {
2245 self.word_nbsp("extern");
2246 self.word_nbsp(header.abi.to_string());
2252 pub fn print_unsafety(&mut self, s: hir::Unsafety) {
2254 hir::Unsafety::Normal => {}
2255 hir::Unsafety::Unsafe => self.word_nbsp("unsafe"),
2259 pub fn print_is_auto(&mut self, s: hir::IsAuto) {
2261 hir::IsAuto::Yes => self.word_nbsp("auto"),
2262 hir::IsAuto::No => {}
2267 /// Does this expression require a semicolon to be treated
2268 /// as a statement? The negation of this: 'can this expression
2269 /// be used as a statement without a semicolon' -- is used
2270 /// as an early-bail-out in the parser so that, for instance,
2271 /// if true {...} else {...}
2273 /// isn't parsed as (if true {...} else {...} | x) | 5
2275 // Duplicated from `parse::classify`, but adapted for the HIR.
2276 fn expr_requires_semi_to_be_stmt(e: &hir::Expr<'_>) -> bool {
2278 hir::ExprKind::Match(..) | hir::ExprKind::Block(..) | hir::ExprKind::Loop(..) => false,
2283 /// This statement requires a semicolon after it.
2284 /// note that in one case (stmt_semi), we've already
2285 /// seen the semicolon, and thus don't need another.
2286 fn stmt_ends_with_semi(stmt: &hir::StmtKind<'_>) -> bool {
2288 hir::StmtKind::Local(_) => true,
2289 hir::StmtKind::Item(_) => false,
2290 hir::StmtKind::Expr(ref e) => expr_requires_semi_to_be_stmt(&e),
2291 hir::StmtKind::Semi(..) => false,
2295 fn bin_op_to_assoc_op(op: hir::BinOpKind) -> AssocOp {
2296 use crate::hir::BinOpKind::*;
2298 Add => AssocOp::Add,
2299 Sub => AssocOp::Subtract,
2300 Mul => AssocOp::Multiply,
2301 Div => AssocOp::Divide,
2302 Rem => AssocOp::Modulus,
2304 And => AssocOp::LAnd,
2307 BitXor => AssocOp::BitXor,
2308 BitAnd => AssocOp::BitAnd,
2309 BitOr => AssocOp::BitOr,
2310 Shl => AssocOp::ShiftLeft,
2311 Shr => AssocOp::ShiftRight,
2313 Eq => AssocOp::Equal,
2314 Lt => AssocOp::Less,
2315 Le => AssocOp::LessEqual,
2316 Ne => AssocOp::NotEqual,
2317 Ge => AssocOp::GreaterEqual,
2318 Gt => AssocOp::Greater,
2322 /// Expressions that syntactically contain an "exterior" struct literal, i.e., not surrounded by any
2323 /// parens or other delimiters, e.g., `X { y: 1 }`, `X { y: 1 }.method()`, `foo == X { y: 1 }` and
2324 /// `X { y: 1 } == foo` all do, but `(X { y: 1 }) == foo` does not.
2325 fn contains_exterior_struct_lit(value: &hir::Expr<'_>) -> bool {
2327 hir::ExprKind::Struct(..) => true,
2329 hir::ExprKind::Assign(ref lhs, ref rhs, _)
2330 | hir::ExprKind::AssignOp(_, ref lhs, ref rhs)
2331 | hir::ExprKind::Binary(_, ref lhs, ref rhs) => {
2332 // `X { y: 1 } + X { y: 2 }`
2333 contains_exterior_struct_lit(&lhs) || contains_exterior_struct_lit(&rhs)
2335 hir::ExprKind::Unary(_, ref x)
2336 | hir::ExprKind::Cast(ref x, _)
2337 | hir::ExprKind::Type(ref x, _)
2338 | hir::ExprKind::Field(ref x, _)
2339 | hir::ExprKind::Index(ref x, _) => {
2340 // `&X { y: 1 }, X { y: 1 }.y`
2341 contains_exterior_struct_lit(&x)
2344 hir::ExprKind::MethodCall(.., ref exprs) => {
2345 // `X { y: 1 }.bar(...)`
2346 contains_exterior_struct_lit(&exprs[0])