1 #![feature(or_patterns)]
2 #![recursion_limit = "256"]
5 use rustc_ast::util::parser::{self, AssocOp, Fixity};
6 use rustc_ast_pretty::pp::Breaks::{Consistent, Inconsistent};
7 use rustc_ast_pretty::pp::{self, Breaks};
8 use rustc_ast_pretty::pprust::{Comments, PrintState};
10 use rustc_hir::{GenericArg, GenericParam, GenericParamKind, Node};
11 use rustc_hir::{GenericBound, PatKind, RangeEnd, TraitBoundModifier};
12 use rustc_span::source_map::{SourceMap, Spanned};
13 use rustc_span::symbol::{kw, Ident, IdentPrinter, Symbol};
14 use rustc_span::{self, BytePos, FileName};
15 use rustc_target::spec::abi::Abi;
21 pub fn id_to_string(map: &dyn rustc_hir::intravisit::Map<'_>, hir_id: hir::HirId) -> String {
22 to_string(&map, |s| s.print_node(map.find(hir_id).unwrap()))
25 pub enum AnnNode<'a> {
27 Block(&'a hir::Block<'a>),
28 Item(&'a hir::Item<'a>),
30 Expr(&'a hir::Expr<'a>),
31 Pat(&'a hir::Pat<'a>),
32 Arm(&'a hir::Arm<'a>),
37 TraitItem(hir::TraitItemId),
38 ImplItem(hir::ImplItemId),
40 BodyParamPat(hir::BodyId, usize),
44 fn nested(&self, _state: &mut State<'_>, _nested: Nested) {}
45 fn pre(&self, _state: &mut State<'_>, _node: AnnNode<'_>) {}
46 fn post(&self, _state: &mut State<'_>, _node: AnnNode<'_>) {}
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: 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);
206 pub fn generic_params_to_string(generic_params: &[GenericParam<'_>]) -> String {
207 to_string(NO_ANN, |s| s.print_generic_params(generic_params))
210 pub fn bounds_to_string<'b>(bounds: impl IntoIterator<Item = &'b hir::GenericBound<'b>>) -> String {
211 to_string(NO_ANN, |s| s.print_bounds("", bounds))
214 pub fn param_to_string(arg: &hir::Param<'_>) -> String {
215 to_string(NO_ANN, |s| s.print_param(arg))
218 pub fn ty_to_string(ty: &hir::Ty<'_>) -> String {
219 to_string(NO_ANN, |s| s.print_type(ty))
222 pub fn path_segment_to_string(segment: &hir::PathSegment<'_>) -> String {
223 to_string(NO_ANN, |s| s.print_path_segment(segment))
226 pub fn path_to_string(segment: &hir::Path<'_>) -> String {
227 to_string(NO_ANN, |s| s.print_path(segment, false))
231 pub fn cbox(&mut self, u: usize) {
235 pub fn nbsp(&mut self) {
239 pub fn word_nbsp<S: Into<Cow<'static, str>>>(&mut self, w: S) {
244 pub fn head<S: Into<Cow<'static, str>>>(&mut self, w: S) {
246 // outer-box is consistent
247 self.cbox(INDENT_UNIT);
248 // head-box is inconsistent
249 self.ibox(w.len() + 1);
250 // keyword that starts the head
256 pub fn bopen(&mut self) {
258 self.end(); // close the head-box
261 pub fn bclose_maybe_open(&mut self, span: rustc_span::Span, close_box: bool) {
262 self.maybe_print_comment(span.hi());
263 self.break_offset_if_not_bol(1, -(INDENT_UNIT as isize));
266 self.end(); // close the outer-box
270 pub fn bclose(&mut self, span: rustc_span::Span) {
271 self.bclose_maybe_open(span, true)
274 pub fn space_if_not_bol(&mut self) {
275 if !self.s.is_beginning_of_line() {
280 pub fn break_offset_if_not_bol(&mut self, n: usize, off: isize) {
281 if !self.s.is_beginning_of_line() {
282 self.s.break_offset(n, off)
284 if off != 0 && self.s.last_token().is_hardbreak_tok() {
285 // We do something pretty sketchy here: tuck the nonzero
286 // offset-adjustment we were going to deposit along with the
287 // break into the previous hardbreak.
288 self.s.replace_last_token(pp::Printer::hardbreak_tok_offset(off));
293 // Synthesizes a comment that was not textually present in the original source
295 pub fn synth_comment(&mut self, text: String) {
303 pub fn commasep_cmnt<T, F, G>(&mut self, b: Breaks, elts: &[T], mut op: F, mut get_span: G)
305 F: FnMut(&mut State<'_>, &T),
306 G: FnMut(&T) -> rustc_span::Span,
309 let len = elts.len();
312 self.maybe_print_comment(get_span(elt).hi());
317 self.maybe_print_trailing_comment(get_span(elt), Some(get_span(&elts[i]).hi()));
318 self.space_if_not_bol();
324 pub fn commasep_exprs(&mut self, b: Breaks, exprs: &[hir::Expr<'_>]) {
325 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(&e), |e| e.span)
328 pub fn print_mod(&mut self, _mod: &hir::Mod<'_>, attrs: &[ast::Attribute]) {
329 self.print_inner_attributes(attrs);
330 for &item_id in _mod.item_ids {
331 self.ann.nested(self, Nested::Item(item_id));
335 pub fn print_foreign_mod(&mut self, nmod: &hir::ForeignMod<'_>, attrs: &[ast::Attribute]) {
336 self.print_inner_attributes(attrs);
337 for item in nmod.items {
338 self.print_foreign_item(item);
342 pub fn print_opt_lifetime(&mut self, lifetime: &hir::Lifetime) {
343 if !lifetime.is_elided() {
344 self.print_lifetime(lifetime);
349 pub fn print_type(&mut self, ty: &hir::Ty<'_>) {
350 self.maybe_print_comment(ty.span.lo());
353 hir::TyKind::Slice(ref ty) => {
355 self.print_type(&ty);
358 hir::TyKind::Ptr(ref mt) => {
360 self.print_mt(mt, true);
362 hir::TyKind::Rptr(ref lifetime, ref mt) => {
364 self.print_opt_lifetime(lifetime);
365 self.print_mt(mt, false);
367 hir::TyKind::Never => {
370 hir::TyKind::Tup(ref elts) => {
372 self.commasep(Inconsistent, &elts[..], |s, ty| s.print_type(&ty));
378 hir::TyKind::BareFn(ref f) => {
388 hir::TyKind::Def(..) => {}
389 hir::TyKind::Path(ref qpath) => self.print_qpath(qpath, false),
390 hir::TyKind::TraitObject(bounds, ref lifetime) => {
391 let mut first = true;
392 for bound in bounds {
397 self.word_space("+");
399 self.print_poly_trait_ref(bound);
401 if !lifetime.is_elided() {
403 self.word_space("+");
404 self.print_lifetime(lifetime);
407 hir::TyKind::Array(ref ty, ref length) => {
409 self.print_type(&ty);
411 self.print_anon_const(length);
414 hir::TyKind::Typeof(ref e) => {
415 self.s.word("typeof(");
416 self.print_anon_const(e);
419 hir::TyKind::Infer => {
422 hir::TyKind::Err => {
424 self.s.word("/*ERROR*/");
431 pub fn print_foreign_item(&mut self, item: &hir::ForeignItem<'_>) {
432 self.hardbreak_if_not_bol();
433 self.maybe_print_comment(item.span.lo());
434 self.print_outer_attributes(&item.attrs);
436 hir::ForeignItemKind::Fn(ref decl, ref arg_names, ref generics) => {
441 unsafety: hir::Unsafety::Normal,
442 constness: hir::Constness::NotConst,
444 asyncness: hir::IsAsync::NotAsync,
446 Some(item.ident.name),
452 self.end(); // end head-ibox
454 self.end() // end the outer fn box
456 hir::ForeignItemKind::Static(ref t, m) => {
457 self.head(visibility_qualified(&item.vis, "static"));
458 if m == hir::Mutability::Mut {
459 self.word_space("mut");
461 self.print_ident(item.ident);
462 self.word_space(":");
465 self.end(); // end the head-ibox
466 self.end() // end the outer cbox
468 hir::ForeignItemKind::Type => {
469 self.head(visibility_qualified(&item.vis, "type"));
470 self.print_ident(item.ident);
472 self.end(); // end the head-ibox
473 self.end() // end the outer cbox
478 fn print_associated_const(
482 default: Option<hir::BodyId>,
483 vis: &hir::Visibility<'_>,
485 self.s.word(visibility_qualified(vis, ""));
486 self.word_space("const");
487 self.print_ident(ident);
488 self.word_space(":");
490 if let Some(expr) = default {
492 self.word_space("=");
493 self.ann.nested(self, Nested::Body(expr));
498 fn print_associated_type(
501 generics: &hir::Generics<'_>,
502 bounds: Option<hir::GenericBounds<'_>>,
503 ty: Option<&hir::Ty<'_>>,
505 self.word_space("type");
506 self.print_ident(ident);
507 self.print_generic_params(&generics.params);
508 if let Some(bounds) = bounds {
509 self.print_bounds(":", bounds);
511 self.print_where_clause(&generics.where_clause);
512 if let Some(ty) = ty {
514 self.word_space("=");
522 item: &hir::Item<'_>,
523 generics: &hir::Generics<'_>,
524 inner: impl Fn(&mut Self),
526 self.head(visibility_qualified(&item.vis, "type"));
527 self.print_ident(item.ident);
528 self.print_generic_params(&generics.params);
529 self.end(); // end the inner ibox
531 self.print_where_clause(&generics.where_clause);
535 self.end(); // end the outer ibox
538 /// Pretty-print an item
539 pub fn print_item(&mut self, item: &hir::Item<'_>) {
540 self.hardbreak_if_not_bol();
541 self.maybe_print_comment(item.span.lo());
542 self.print_outer_attributes(&item.attrs);
543 self.ann.pre(self, AnnNode::Item(item));
545 hir::ItemKind::ExternCrate(orig_name) => {
546 self.head(visibility_qualified(&item.vis, "extern crate"));
547 if let Some(orig_name) = orig_name {
548 self.print_name(orig_name);
553 self.print_ident(item.ident);
555 self.end(); // end inner head-block
556 self.end(); // end outer head-block
558 hir::ItemKind::Use(ref path, kind) => {
559 self.head(visibility_qualified(&item.vis, "use"));
560 self.print_path(path, false);
563 hir::UseKind::Single => {
564 if path.segments.last().unwrap().ident != item.ident {
566 self.word_space("as");
567 self.print_ident(item.ident);
571 hir::UseKind::Glob => self.s.word("::*;"),
572 hir::UseKind::ListStem => self.s.word("::{};"),
574 self.end(); // end inner head-block
575 self.end(); // end outer head-block
577 hir::ItemKind::Static(ref ty, m, expr) => {
578 self.head(visibility_qualified(&item.vis, "static"));
579 if m == hir::Mutability::Mut {
580 self.word_space("mut");
582 self.print_ident(item.ident);
583 self.word_space(":");
584 self.print_type(&ty);
586 self.end(); // end the head-ibox
588 self.word_space("=");
589 self.ann.nested(self, Nested::Body(expr));
591 self.end(); // end the outer cbox
593 hir::ItemKind::Const(ref ty, expr) => {
594 self.head(visibility_qualified(&item.vis, "const"));
595 self.print_ident(item.ident);
596 self.word_space(":");
597 self.print_type(&ty);
599 self.end(); // end the head-ibox
601 self.word_space("=");
602 self.ann.nested(self, Nested::Body(expr));
604 self.end(); // end the outer cbox
606 hir::ItemKind::Fn(ref sig, ref param_names, body) => {
611 Some(item.ident.name),
618 self.end(); // need to close a box
619 self.end(); // need to close a box
620 self.ann.nested(self, Nested::Body(body));
622 hir::ItemKind::Mod(ref _mod) => {
623 self.head(visibility_qualified(&item.vis, "mod"));
624 self.print_ident(item.ident);
627 self.print_mod(_mod, &item.attrs);
628 self.bclose(item.span);
630 hir::ItemKind::ForeignMod(ref nmod) => {
632 self.word_nbsp(nmod.abi.to_string());
634 self.print_foreign_mod(nmod, &item.attrs);
635 self.bclose(item.span);
637 hir::ItemKind::GlobalAsm(ref ga) => {
638 self.head(visibility_qualified(&item.vis, "global asm"));
639 self.s.word(ga.asm.to_string());
642 hir::ItemKind::TyAlias(ref ty, ref generics) => {
643 self.print_item_type(item, &generics, |state| {
644 state.word_space("=");
645 state.print_type(&ty);
648 hir::ItemKind::OpaqueTy(ref opaque_ty) => {
649 self.print_item_type(item, &opaque_ty.generics, |state| {
650 let mut real_bounds = Vec::with_capacity(opaque_ty.bounds.len());
651 for b in opaque_ty.bounds.iter() {
652 if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
654 state.word_space("for ?");
655 state.print_trait_ref(&ptr.trait_ref);
660 state.print_bounds("= impl", real_bounds);
663 hir::ItemKind::Enum(ref enum_definition, ref params) => {
664 self.print_enum_def(enum_definition, params, item.ident.name, item.span, &item.vis);
666 hir::ItemKind::Struct(ref struct_def, ref generics) => {
667 self.head(visibility_qualified(&item.vis, "struct"));
668 self.print_struct(struct_def, generics, item.ident.name, item.span, true);
670 hir::ItemKind::Union(ref struct_def, ref generics) => {
671 self.head(visibility_qualified(&item.vis, "union"));
672 self.print_struct(struct_def, generics, item.ident.name, item.span, true);
674 hir::ItemKind::Impl {
686 self.print_visibility(&item.vis);
687 self.print_defaultness(defaultness);
688 self.print_unsafety(unsafety);
689 self.word_nbsp("impl");
691 if !generics.params.is_empty() {
692 self.print_generic_params(&generics.params);
696 if constness == hir::Constness::Const {
697 self.word_nbsp("const");
700 if let hir::ImplPolarity::Negative(_) = polarity {
704 if let Some(ref t) = of_trait {
705 self.print_trait_ref(t);
707 self.word_space("for");
710 self.print_type(&self_ty);
711 self.print_where_clause(&generics.where_clause);
715 self.print_inner_attributes(&item.attrs);
716 for impl_item in items {
717 self.ann.nested(self, Nested::ImplItem(impl_item.id));
719 self.bclose(item.span);
721 hir::ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, trait_items) => {
723 self.print_visibility(&item.vis);
724 self.print_is_auto(is_auto);
725 self.print_unsafety(unsafety);
726 self.word_nbsp("trait");
727 self.print_ident(item.ident);
728 self.print_generic_params(&generics.params);
729 let mut real_bounds = Vec::with_capacity(bounds.len());
730 for b in bounds.iter() {
731 if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
733 self.word_space("for ?");
734 self.print_trait_ref(&ptr.trait_ref);
739 self.print_bounds(":", real_bounds);
740 self.print_where_clause(&generics.where_clause);
743 for trait_item in trait_items {
744 self.ann.nested(self, Nested::TraitItem(trait_item.id));
746 self.bclose(item.span);
748 hir::ItemKind::TraitAlias(ref generics, ref bounds) => {
750 self.print_visibility(&item.vis);
751 self.word_nbsp("trait");
752 self.print_ident(item.ident);
753 self.print_generic_params(&generics.params);
754 let mut real_bounds = Vec::with_capacity(bounds.len());
755 // FIXME(durka) this seems to be some quite outdated syntax
756 for b in bounds.iter() {
757 if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
759 self.word_space("for ?");
760 self.print_trait_ref(&ptr.trait_ref);
766 self.print_bounds("=", real_bounds);
767 self.print_where_clause(&generics.where_clause);
771 self.ann.post(self, AnnNode::Item(item))
774 pub fn print_trait_ref(&mut self, t: &hir::TraitRef<'_>) {
775 self.print_path(&t.path, false)
778 fn print_formal_generic_params(&mut self, generic_params: &[hir::GenericParam<'_>]) {
779 if !generic_params.is_empty() {
781 self.print_generic_params(generic_params);
786 fn print_poly_trait_ref(&mut self, t: &hir::PolyTraitRef<'_>) {
787 self.print_formal_generic_params(&t.bound_generic_params);
788 self.print_trait_ref(&t.trait_ref)
791 pub fn print_enum_def(
793 enum_definition: &hir::EnumDef<'_>,
794 generics: &hir::Generics<'_>,
796 span: rustc_span::Span,
797 visibility: &hir::Visibility<'_>,
799 self.head(visibility_qualified(visibility, "enum"));
800 self.print_name(name);
801 self.print_generic_params(&generics.params);
802 self.print_where_clause(&generics.where_clause);
804 self.print_variants(&enum_definition.variants, span)
807 pub fn print_variants(&mut self, variants: &[hir::Variant<'_>], span: rustc_span::Span) {
810 self.space_if_not_bol();
811 self.maybe_print_comment(v.span.lo());
812 self.print_outer_attributes(&v.attrs);
813 self.ibox(INDENT_UNIT);
814 self.print_variant(v);
817 self.maybe_print_trailing_comment(v.span, None);
822 pub fn print_visibility(&mut self, vis: &hir::Visibility<'_>) {
824 hir::VisibilityKind::Public => self.word_nbsp("pub"),
825 hir::VisibilityKind::Crate(ast::CrateSugar::JustCrate) => self.word_nbsp("crate"),
826 hir::VisibilityKind::Crate(ast::CrateSugar::PubCrate) => self.word_nbsp("pub(crate)"),
827 hir::VisibilityKind::Restricted { ref path, .. } => {
829 if path.segments.len() == 1 && path.segments[0].ident.name == kw::Super {
830 // Special case: `super` can print like `pub(super)`.
831 self.s.word("super");
833 // Everything else requires `in` at present.
834 self.word_nbsp("in");
835 self.print_path(path, false);
839 hir::VisibilityKind::Inherited => (),
843 pub fn print_defaultness(&mut self, defaultness: hir::Defaultness) {
845 hir::Defaultness::Default { .. } => self.word_nbsp("default"),
846 hir::Defaultness::Final => (),
852 struct_def: &hir::VariantData<'_>,
853 generics: &hir::Generics<'_>,
855 span: rustc_span::Span,
856 print_finalizer: bool,
858 self.print_name(name);
859 self.print_generic_params(&generics.params);
861 hir::VariantData::Tuple(..) | hir::VariantData::Unit(..) => {
862 if let hir::VariantData::Tuple(..) = struct_def {
864 self.commasep(Inconsistent, struct_def.fields(), |s, field| {
865 s.maybe_print_comment(field.span.lo());
866 s.print_outer_attributes(&field.attrs);
867 s.print_visibility(&field.vis);
868 s.print_type(&field.ty)
872 self.print_where_clause(&generics.where_clause);
877 self.end() // close the outer-box
879 hir::VariantData::Struct(..) => {
880 self.print_where_clause(&generics.where_clause);
883 self.hardbreak_if_not_bol();
885 for field in struct_def.fields() {
886 self.hardbreak_if_not_bol();
887 self.maybe_print_comment(field.span.lo());
888 self.print_outer_attributes(&field.attrs);
889 self.print_visibility(&field.vis);
890 self.print_ident(field.ident);
892 self.print_type(&field.ty);
901 pub fn print_variant(&mut self, v: &hir::Variant<'_>) {
903 let generics = hir::Generics::empty();
904 self.print_struct(&v.data, &generics, v.ident.name, v.span, false);
905 if let Some(ref d) = v.disr_expr {
907 self.word_space("=");
908 self.print_anon_const(d);
911 pub fn print_method_sig(
915 generics: &hir::Generics<'_>,
916 vis: &hir::Visibility<'_>,
918 body_id: Option<hir::BodyId>,
920 self.print_fn(&m.decl, m.header, Some(ident.name), generics, vis, arg_names, body_id)
923 pub fn print_trait_item(&mut self, ti: &hir::TraitItem<'_>) {
924 self.ann.pre(self, AnnNode::SubItem(ti.hir_id));
925 self.hardbreak_if_not_bol();
926 self.maybe_print_comment(ti.span.lo());
927 self.print_outer_attributes(&ti.attrs);
929 hir::TraitItemKind::Const(ref ty, default) => {
931 Spanned { span: rustc_span::DUMMY_SP, node: hir::VisibilityKind::Inherited };
932 self.print_associated_const(ti.ident, &ty, default, &vis);
934 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Required(ref arg_names)) => {
936 Spanned { span: rustc_span::DUMMY_SP, node: hir::VisibilityKind::Inherited };
937 self.print_method_sig(ti.ident, sig, &ti.generics, &vis, arg_names, None);
940 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Provided(body)) => {
942 Spanned { span: rustc_span::DUMMY_SP, node: hir::VisibilityKind::Inherited };
944 self.print_method_sig(ti.ident, sig, &ti.generics, &vis, &[], Some(body));
946 self.end(); // need to close a box
947 self.end(); // need to close a box
948 self.ann.nested(self, Nested::Body(body));
950 hir::TraitItemKind::Type(ref bounds, ref default) => {
951 self.print_associated_type(
955 default.as_ref().map(|ty| &**ty),
959 self.ann.post(self, AnnNode::SubItem(ti.hir_id))
962 pub fn print_impl_item(&mut self, ii: &hir::ImplItem<'_>) {
963 self.ann.pre(self, AnnNode::SubItem(ii.hir_id));
964 self.hardbreak_if_not_bol();
965 self.maybe_print_comment(ii.span.lo());
966 self.print_outer_attributes(&ii.attrs);
967 self.print_defaultness(ii.defaultness);
970 hir::ImplItemKind::Const(ref ty, expr) => {
971 self.print_associated_const(ii.ident, &ty, Some(expr), &ii.vis);
973 hir::ImplItemKind::Fn(ref sig, body) => {
975 self.print_method_sig(ii.ident, sig, &ii.generics, &ii.vis, &[], Some(body));
977 self.end(); // need to close a box
978 self.end(); // need to close a box
979 self.ann.nested(self, Nested::Body(body));
981 hir::ImplItemKind::TyAlias(ref ty) => {
982 self.print_associated_type(ii.ident, &ii.generics, None, Some(ty));
984 hir::ImplItemKind::OpaqueTy(bounds) => {
985 self.word_space("type");
986 self.print_ident(ii.ident);
987 self.print_bounds("= impl", bounds);
991 self.ann.post(self, AnnNode::SubItem(ii.hir_id))
994 pub fn print_local(&mut self, init: Option<&hir::Expr<'_>>, decl: impl Fn(&mut Self)) {
995 self.space_if_not_bol();
996 self.ibox(INDENT_UNIT);
997 self.word_nbsp("let");
999 self.ibox(INDENT_UNIT);
1003 if let Some(ref init) = init {
1005 self.word_space("=");
1006 self.print_expr(&init);
1011 pub fn print_stmt(&mut self, st: &hir::Stmt<'_>) {
1012 self.maybe_print_comment(st.span.lo());
1014 hir::StmtKind::Local(ref loc) => {
1015 self.print_local(loc.init.as_deref(), |this| this.print_local_decl(&loc));
1017 hir::StmtKind::Item(item) => self.ann.nested(self, Nested::Item(item)),
1018 hir::StmtKind::Expr(ref expr) => {
1019 self.space_if_not_bol();
1020 self.print_expr(&expr);
1022 hir::StmtKind::Semi(ref expr) => {
1023 self.space_if_not_bol();
1024 self.print_expr(&expr);
1028 if stmt_ends_with_semi(&st.kind) {
1031 self.maybe_print_trailing_comment(st.span, None)
1034 pub fn print_block(&mut self, blk: &hir::Block<'_>) {
1035 self.print_block_with_attrs(blk, &[])
1038 pub fn print_block_unclosed(&mut self, blk: &hir::Block<'_>) {
1039 self.print_block_maybe_unclosed(blk, &[], false)
1042 pub fn print_block_with_attrs(&mut self, blk: &hir::Block<'_>, attrs: &[ast::Attribute]) {
1043 self.print_block_maybe_unclosed(blk, attrs, true)
1046 pub fn print_block_maybe_unclosed(
1048 blk: &hir::Block<'_>,
1049 attrs: &[ast::Attribute],
1053 hir::BlockCheckMode::UnsafeBlock(..) => self.word_space("unsafe"),
1054 hir::BlockCheckMode::PushUnsafeBlock(..) => self.word_space("push_unsafe"),
1055 hir::BlockCheckMode::PopUnsafeBlock(..) => self.word_space("pop_unsafe"),
1056 hir::BlockCheckMode::DefaultBlock => (),
1058 self.maybe_print_comment(blk.span.lo());
1059 self.ann.pre(self, AnnNode::Block(blk));
1062 self.print_inner_attributes(attrs);
1064 for st in blk.stmts {
1065 self.print_stmt(st);
1067 if let Some(ref expr) = blk.expr {
1068 self.space_if_not_bol();
1069 self.print_expr(&expr);
1070 self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi()));
1072 self.bclose_maybe_open(blk.span, close_box);
1073 self.ann.post(self, AnnNode::Block(blk))
1076 pub fn print_anon_const(&mut self, constant: &hir::AnonConst) {
1077 self.ann.nested(self, Nested::Body(constant.body))
1080 fn print_call_post(&mut self, args: &[hir::Expr<'_>]) {
1082 self.commasep_exprs(Inconsistent, args);
1086 pub fn print_expr_maybe_paren(&mut self, expr: &hir::Expr<'_>, prec: i8) {
1087 let needs_par = expr.precedence().order() < prec;
1091 self.print_expr(expr);
1097 /// Print an expr using syntax that's acceptable in a condition position, such as the `cond` in
1098 /// `if cond { ... }`.
1099 pub fn print_expr_as_cond(&mut self, expr: &hir::Expr<'_>) {
1100 let needs_par = match expr.kind {
1101 // These cases need parens due to the parse error observed in #26461: `if return {}`
1102 // parses as the erroneous construct `if (return {})`, not `if (return) {}`.
1103 hir::ExprKind::Closure(..) | hir::ExprKind::Ret(..) | hir::ExprKind::Break(..) => true,
1105 _ => contains_exterior_struct_lit(expr),
1111 self.print_expr(expr);
1117 fn print_expr_vec(&mut self, exprs: &[hir::Expr<'_>]) {
1118 self.ibox(INDENT_UNIT);
1120 self.commasep_exprs(Inconsistent, exprs);
1125 fn print_expr_repeat(&mut self, element: &hir::Expr<'_>, count: &hir::AnonConst) {
1126 self.ibox(INDENT_UNIT);
1128 self.print_expr(element);
1129 self.word_space(";");
1130 self.print_anon_const(count);
1135 fn print_expr_struct(
1137 qpath: &hir::QPath<'_>,
1138 fields: &[hir::Field<'_>],
1139 wth: &Option<&hir::Expr<'_>>,
1141 self.print_qpath(qpath, true);
1147 s.ibox(INDENT_UNIT);
1148 if !field.is_shorthand {
1149 s.print_ident(field.ident);
1152 s.print_expr(&field.expr);
1159 self.ibox(INDENT_UNIT);
1160 if !fields.is_empty() {
1165 self.print_expr(&expr);
1169 if !fields.is_empty() {
1177 fn print_expr_tup(&mut self, exprs: &[hir::Expr<'_>]) {
1179 self.commasep_exprs(Inconsistent, exprs);
1180 if exprs.len() == 1 {
1186 fn print_expr_call(&mut self, func: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
1187 let prec = match func.kind {
1188 hir::ExprKind::Field(..) => parser::PREC_FORCE_PAREN,
1189 _ => parser::PREC_POSTFIX,
1192 self.print_expr_maybe_paren(func, prec);
1193 self.print_call_post(args)
1196 fn print_expr_method_call(&mut self, segment: &hir::PathSegment<'_>, args: &[hir::Expr<'_>]) {
1197 let base_args = &args[1..];
1198 self.print_expr_maybe_paren(&args[0], parser::PREC_POSTFIX);
1200 self.print_ident(segment.ident);
1202 let generic_args = segment.generic_args();
1203 if !generic_args.args.is_empty() || !generic_args.bindings.is_empty() {
1204 self.print_generic_args(generic_args, segment.infer_args, true);
1207 self.print_call_post(base_args)
1210 fn print_expr_binary(&mut self, op: hir::BinOp, lhs: &hir::Expr<'_>, rhs: &hir::Expr<'_>) {
1211 let assoc_op = bin_op_to_assoc_op(op.node);
1212 let prec = assoc_op.precedence() as i8;
1213 let fixity = assoc_op.fixity();
1215 let (left_prec, right_prec) = match fixity {
1216 Fixity::Left => (prec, prec + 1),
1217 Fixity::Right => (prec + 1, prec),
1218 Fixity::None => (prec + 1, prec + 1),
1221 let left_prec = match (&lhs.kind, op.node) {
1222 // These cases need parens: `x as i32 < y` has the parser thinking that `i32 < y` is
1223 // the beginning of a path type. It starts trying to parse `x as (i32 < y ...` instead
1224 // of `(x as i32) < ...`. We need to convince it _not_ to do that.
1225 (&hir::ExprKind::Cast { .. }, hir::BinOpKind::Lt | hir::BinOpKind::Shl) => {
1226 parser::PREC_FORCE_PAREN
1231 self.print_expr_maybe_paren(lhs, left_prec);
1233 self.word_space(op.node.as_str());
1234 self.print_expr_maybe_paren(rhs, right_prec)
1237 fn print_expr_unary(&mut self, op: hir::UnOp, expr: &hir::Expr<'_>) {
1238 self.s.word(op.as_str());
1239 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1242 fn print_expr_addr_of(
1244 kind: hir::BorrowKind,
1245 mutability: hir::Mutability,
1246 expr: &hir::Expr<'_>,
1250 hir::BorrowKind::Ref => self.print_mutability(mutability, false),
1251 hir::BorrowKind::Raw => {
1252 self.word_nbsp("raw");
1253 self.print_mutability(mutability, true);
1256 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1259 fn print_literal(&mut self, lit: &hir::Lit) {
1260 self.maybe_print_comment(lit.span.lo());
1261 self.word(lit.node.to_lit_token().to_string())
1264 pub fn print_expr(&mut self, expr: &hir::Expr<'_>) {
1265 self.maybe_print_comment(expr.span.lo());
1266 self.print_outer_attributes(&expr.attrs);
1267 self.ibox(INDENT_UNIT);
1268 self.ann.pre(self, AnnNode::Expr(expr));
1270 hir::ExprKind::Box(ref expr) => {
1271 self.word_space("box");
1272 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX);
1274 hir::ExprKind::Array(ref exprs) => {
1275 self.print_expr_vec(exprs);
1277 hir::ExprKind::Repeat(ref element, ref count) => {
1278 self.print_expr_repeat(&element, count);
1280 hir::ExprKind::Struct(ref qpath, fields, ref wth) => {
1281 self.print_expr_struct(qpath, fields, wth);
1283 hir::ExprKind::Tup(ref exprs) => {
1284 self.print_expr_tup(exprs);
1286 hir::ExprKind::Call(ref func, ref args) => {
1287 self.print_expr_call(&func, args);
1289 hir::ExprKind::MethodCall(ref segment, _, ref args) => {
1290 self.print_expr_method_call(segment, args);
1292 hir::ExprKind::Binary(op, ref lhs, ref rhs) => {
1293 self.print_expr_binary(op, &lhs, &rhs);
1295 hir::ExprKind::Unary(op, ref expr) => {
1296 self.print_expr_unary(op, &expr);
1298 hir::ExprKind::AddrOf(k, m, ref expr) => {
1299 self.print_expr_addr_of(k, m, &expr);
1301 hir::ExprKind::Lit(ref lit) => {
1302 self.print_literal(&lit);
1304 hir::ExprKind::Cast(ref expr, ref ty) => {
1305 let prec = AssocOp::As.precedence() as i8;
1306 self.print_expr_maybe_paren(&expr, prec);
1308 self.word_space("as");
1309 self.print_type(&ty);
1311 hir::ExprKind::Type(ref expr, ref ty) => {
1312 let prec = AssocOp::Colon.precedence() as i8;
1313 self.print_expr_maybe_paren(&expr, prec);
1314 self.word_space(":");
1315 self.print_type(&ty);
1317 hir::ExprKind::DropTemps(ref init) => {
1319 self.cbox(INDENT_UNIT);
1323 // Print `let _t = $init;`:
1324 let temp = Ident::from_str("_t");
1325 self.print_local(Some(init), |this| this.print_ident(temp));
1329 self.space_if_not_bol();
1330 self.print_ident(temp);
1333 self.bclose_maybe_open(expr.span, true);
1335 hir::ExprKind::Loop(ref blk, opt_label, _) => {
1336 if let Some(label) = opt_label {
1337 self.print_ident(label.ident);
1338 self.word_space(":");
1342 self.print_block(&blk);
1344 hir::ExprKind::Match(ref expr, arms, _) => {
1345 self.cbox(INDENT_UNIT);
1346 self.ibox(INDENT_UNIT);
1347 self.word_nbsp("match");
1348 self.print_expr_as_cond(&expr);
1352 self.print_arm(arm);
1354 self.bclose(expr.span);
1356 hir::ExprKind::Closure(capture_clause, ref decl, body, _fn_decl_span, _gen) => {
1357 self.print_capture_clause(capture_clause);
1359 self.print_closure_params(&decl, body);
1362 // This is a bare expression.
1363 self.ann.nested(self, Nested::Body(body));
1364 self.end(); // need to close a box
1366 // A box will be closed by `print_expr`, but we didn't want an overall
1367 // wrapper so we closed the corresponding opening. so create an
1368 // empty box to satisfy the close.
1371 hir::ExprKind::Block(ref blk, opt_label) => {
1372 if let Some(label) = opt_label {
1373 self.print_ident(label.ident);
1374 self.word_space(":");
1376 // containing cbox, will be closed by print-block at `}`
1377 self.cbox(INDENT_UNIT);
1378 // head-box, will be closed by print-block after `{`
1380 self.print_block(&blk);
1382 hir::ExprKind::Assign(ref lhs, ref rhs, _) => {
1383 let prec = AssocOp::Assign.precedence() as i8;
1384 self.print_expr_maybe_paren(&lhs, prec + 1);
1386 self.word_space("=");
1387 self.print_expr_maybe_paren(&rhs, prec);
1389 hir::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
1390 let prec = AssocOp::Assign.precedence() as i8;
1391 self.print_expr_maybe_paren(&lhs, prec + 1);
1393 self.s.word(op.node.as_str());
1394 self.word_space("=");
1395 self.print_expr_maybe_paren(&rhs, prec);
1397 hir::ExprKind::Field(ref expr, ident) => {
1398 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
1400 self.print_ident(ident);
1402 hir::ExprKind::Index(ref expr, ref index) => {
1403 self.print_expr_maybe_paren(&expr, parser::PREC_POSTFIX);
1405 self.print_expr(&index);
1408 hir::ExprKind::Path(ref qpath) => self.print_qpath(qpath, true),
1409 hir::ExprKind::Break(destination, ref opt_expr) => {
1410 self.s.word("break");
1412 if let Some(label) = destination.label {
1413 self.print_ident(label.ident);
1416 if let Some(ref expr) = *opt_expr {
1417 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
1421 hir::ExprKind::Continue(destination) => {
1422 self.s.word("continue");
1424 if let Some(label) = destination.label {
1425 self.print_ident(label.ident);
1429 hir::ExprKind::Ret(ref result) => {
1430 self.s.word("return");
1431 if let Some(ref expr) = *result {
1433 self.print_expr_maybe_paren(&expr, parser::PREC_JUMP);
1436 hir::ExprKind::InlineAsm(ref a) => {
1439 Operand(&'a hir::InlineAsmOperand<'a>),
1440 Options(ast::InlineAsmOptions),
1443 let mut args = vec![];
1444 args.push(AsmArg::Template(ast::InlineAsmTemplatePiece::to_string(&a.template)));
1445 args.extend(a.operands.iter().map(|o| AsmArg::Operand(o)));
1446 if !a.options.is_empty() {
1447 args.push(AsmArg::Options(a.options));
1452 self.commasep(Consistent, &args, |s, arg| match arg {
1453 AsmArg::Template(template) => s.print_string(&template, ast::StrStyle::Cooked),
1454 AsmArg::Operand(op) => match op {
1455 hir::InlineAsmOperand::In { reg, expr } => {
1458 s.word(format!("{}", reg));
1463 hir::InlineAsmOperand::Out { reg, late, expr } => {
1464 s.word(if *late { "lateout" } else { "out" });
1466 s.word(format!("{}", reg));
1470 Some(expr) => s.print_expr(expr),
1471 None => s.word("_"),
1474 hir::InlineAsmOperand::InOut { reg, late, expr } => {
1475 s.word(if *late { "inlateout" } else { "inout" });
1477 s.word(format!("{}", reg));
1482 hir::InlineAsmOperand::SplitInOut { reg, late, in_expr, out_expr } => {
1483 s.word(if *late { "inlateout" } else { "inout" });
1485 s.word(format!("{}", reg));
1488 s.print_expr(in_expr);
1492 Some(out_expr) => s.print_expr(out_expr),
1493 None => s.word("_"),
1496 hir::InlineAsmOperand::Const { expr } => {
1501 hir::InlineAsmOperand::Sym { expr } => {
1507 AsmArg::Options(opts) => {
1510 let mut options = vec![];
1511 if opts.contains(ast::InlineAsmOptions::PURE) {
1512 options.push("pure");
1514 if opts.contains(ast::InlineAsmOptions::NOMEM) {
1515 options.push("nomem");
1517 if opts.contains(ast::InlineAsmOptions::READONLY) {
1518 options.push("readonly");
1520 if opts.contains(ast::InlineAsmOptions::PRESERVES_FLAGS) {
1521 options.push("preserves_flags");
1523 if opts.contains(ast::InlineAsmOptions::NORETURN) {
1524 options.push("noreturn");
1526 if opts.contains(ast::InlineAsmOptions::NOSTACK) {
1527 options.push("nostack");
1529 if opts.contains(ast::InlineAsmOptions::ATT_SYNTAX) {
1530 options.push("att_syntax");
1532 s.commasep(Inconsistent, &options, |s, &opt| {
1540 hir::ExprKind::LlvmInlineAsm(ref a) => {
1542 self.s.word("llvm_asm!");
1544 self.print_string(&i.asm.as_str(), i.asm_str_style);
1545 self.word_space(":");
1547 let mut out_idx = 0;
1548 self.commasep(Inconsistent, &i.outputs, |s, out| {
1549 let constraint = out.constraint.as_str();
1550 let mut ch = constraint.chars();
1552 Some('=') if out.is_rw => {
1553 s.print_string(&format!("+{}", ch.as_str()), ast::StrStyle::Cooked)
1555 _ => s.print_string(&constraint, ast::StrStyle::Cooked),
1558 s.print_expr(&a.outputs_exprs[out_idx]);
1563 self.word_space(":");
1566 self.commasep(Inconsistent, &i.inputs, |s, co| {
1567 s.print_string(&co.as_str(), ast::StrStyle::Cooked);
1569 s.print_expr(&a.inputs_exprs[in_idx]);
1574 self.word_space(":");
1576 self.commasep(Inconsistent, &i.clobbers, |s, co| {
1577 s.print_string(&co.as_str(), ast::StrStyle::Cooked);
1580 let mut options = vec![];
1582 options.push("volatile");
1585 options.push("alignstack");
1587 if i.dialect == ast::LlvmAsmDialect::Intel {
1588 options.push("intel");
1591 if !options.is_empty() {
1593 self.word_space(":");
1594 self.commasep(Inconsistent, &options, |s, &co| {
1595 s.print_string(co, ast::StrStyle::Cooked);
1601 hir::ExprKind::Yield(ref expr, _) => {
1602 self.word_space("yield");
1603 self.print_expr_maybe_paren(&expr, parser::PREC_JUMP);
1605 hir::ExprKind::Err => {
1607 self.s.word("/*ERROR*/");
1611 self.ann.post(self, AnnNode::Expr(expr));
1615 pub fn print_local_decl(&mut self, loc: &hir::Local<'_>) {
1616 self.print_pat(&loc.pat);
1617 if let Some(ref ty) = loc.ty {
1618 self.word_space(":");
1619 self.print_type(&ty);
1623 pub fn print_usize(&mut self, i: usize) {
1624 self.s.word(i.to_string())
1627 pub fn print_name(&mut self, name: Symbol) {
1628 self.print_ident(Ident::with_dummy_span(name))
1631 pub fn print_for_decl(&mut self, loc: &hir::Local<'_>, coll: &hir::Expr<'_>) {
1632 self.print_local_decl(loc);
1634 self.word_space("in");
1635 self.print_expr(coll)
1638 pub fn print_path(&mut self, path: &hir::Path<'_>, colons_before_params: bool) {
1639 self.maybe_print_comment(path.span.lo());
1641 for (i, segment) in path.segments.iter().enumerate() {
1645 if segment.ident.name != kw::PathRoot {
1646 self.print_ident(segment.ident);
1647 self.print_generic_args(
1648 segment.generic_args(),
1650 colons_before_params,
1656 pub fn print_path_segment(&mut self, segment: &hir::PathSegment<'_>) {
1657 if segment.ident.name != kw::PathRoot {
1658 self.print_ident(segment.ident);
1659 self.print_generic_args(segment.generic_args(), segment.infer_args, false);
1663 pub fn print_qpath(&mut self, qpath: &hir::QPath<'_>, colons_before_params: bool) {
1665 hir::QPath::Resolved(None, ref path) => self.print_path(path, colons_before_params),
1666 hir::QPath::Resolved(Some(ref qself), ref path) => {
1668 self.print_type(qself);
1670 self.word_space("as");
1672 for (i, segment) in path.segments[..path.segments.len() - 1].iter().enumerate() {
1676 if segment.ident.name != kw::PathRoot {
1677 self.print_ident(segment.ident);
1678 self.print_generic_args(
1679 segment.generic_args(),
1681 colons_before_params,
1688 let item_segment = path.segments.last().unwrap();
1689 self.print_ident(item_segment.ident);
1690 self.print_generic_args(
1691 item_segment.generic_args(),
1692 item_segment.infer_args,
1693 colons_before_params,
1696 hir::QPath::TypeRelative(ref qself, ref item_segment) => {
1697 // If we've got a compound-qualified-path, let's push an additional pair of angle
1698 // brackets, so that we pretty-print `<<A::B>::C>` as `<A::B>::C`, instead of just
1699 // `A::B::C` (since the latter could be ambiguous to the user)
1700 if let hir::TyKind::Path(hir::QPath::Resolved(None, _)) = &qself.kind {
1701 self.print_type(qself);
1704 self.print_type(qself);
1709 self.print_ident(item_segment.ident);
1710 self.print_generic_args(
1711 item_segment.generic_args(),
1712 item_segment.infer_args,
1713 colons_before_params,
1719 fn print_generic_args(
1721 generic_args: &hir::GenericArgs<'_>,
1723 colons_before_params: bool,
1725 if generic_args.parenthesized {
1727 self.commasep(Inconsistent, generic_args.inputs(), |s, ty| s.print_type(&ty));
1730 self.space_if_not_bol();
1731 self.word_space("->");
1732 self.print_type(generic_args.bindings[0].ty());
1734 let start = if colons_before_params { "::<" } else { "<" };
1735 let empty = Cell::new(true);
1736 let start_or_comma = |this: &mut Self| {
1741 this.word_space(",")
1745 let mut nonelided_generic_args: bool = false;
1746 let elide_lifetimes = generic_args.args.iter().all(|arg| match arg {
1747 GenericArg::Lifetime(lt) => lt.is_elided(),
1749 nonelided_generic_args = true;
1754 if nonelided_generic_args {
1755 start_or_comma(self);
1759 |s, generic_arg| match generic_arg {
1760 GenericArg::Lifetime(lt) if !elide_lifetimes => s.print_lifetime(lt),
1761 GenericArg::Lifetime(_) => {}
1762 GenericArg::Type(ty) => s.print_type(ty),
1763 GenericArg::Const(ct) => s.print_anon_const(&ct.value),
1768 // FIXME(eddyb): this would leak into error messages (e.g.,
1769 // "non-exhaustive patterns: `Some::<..>(_)` not covered").
1770 if infer_args && false {
1771 start_or_comma(self);
1775 for binding in generic_args.bindings.iter() {
1776 start_or_comma(self);
1777 self.print_ident(binding.ident);
1779 match generic_args.bindings[0].kind {
1780 hir::TypeBindingKind::Equality { ref ty } => {
1781 self.word_space("=");
1782 self.print_type(ty);
1784 hir::TypeBindingKind::Constraint { bounds } => {
1785 self.print_bounds(":", bounds);
1796 pub fn print_pat(&mut self, pat: &hir::Pat<'_>) {
1797 self.maybe_print_comment(pat.span.lo());
1798 self.ann.pre(self, AnnNode::Pat(pat));
1799 // Pat isn't normalized, but the beauty of it
1800 // is that it doesn't matter
1802 PatKind::Wild => self.s.word("_"),
1803 PatKind::Binding(binding_mode, _, ident, ref sub) => {
1804 match binding_mode {
1805 hir::BindingAnnotation::Ref => {
1806 self.word_nbsp("ref");
1807 self.print_mutability(hir::Mutability::Not, false);
1809 hir::BindingAnnotation::RefMut => {
1810 self.word_nbsp("ref");
1811 self.print_mutability(hir::Mutability::Mut, false);
1813 hir::BindingAnnotation::Unannotated => {}
1814 hir::BindingAnnotation::Mutable => {
1815 self.word_nbsp("mut");
1818 self.print_ident(ident);
1819 if let Some(ref p) = *sub {
1824 PatKind::TupleStruct(ref qpath, ref elts, ddpos) => {
1825 self.print_qpath(qpath, true);
1827 if let Some(ddpos) = ddpos {
1828 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p));
1830 self.word_space(",");
1833 if ddpos != elts.len() {
1835 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p));
1838 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p));
1842 PatKind::Path(ref qpath) => {
1843 self.print_qpath(qpath, true);
1845 PatKind::Struct(ref qpath, ref fields, etc) => {
1846 self.print_qpath(qpath, true);
1848 self.word_space("{");
1853 s.cbox(INDENT_UNIT);
1854 if !f.is_shorthand {
1855 s.print_ident(f.ident);
1858 s.print_pat(&f.pat);
1864 if !fields.is_empty() {
1865 self.word_space(",");
1872 PatKind::Or(ref pats) => {
1873 self.strsep("|", true, Inconsistent, &pats[..], |s, p| s.print_pat(&p));
1875 PatKind::Tuple(ref elts, ddpos) => {
1877 if let Some(ddpos) = ddpos {
1878 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p));
1880 self.word_space(",");
1883 if ddpos != elts.len() {
1885 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p));
1888 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p));
1889 if elts.len() == 1 {
1895 PatKind::Box(ref inner) => {
1896 let is_range_inner = match inner.kind {
1897 PatKind::Range(..) => true,
1900 self.s.word("box ");
1904 self.print_pat(&inner);
1909 PatKind::Ref(ref inner, mutbl) => {
1910 let is_range_inner = match inner.kind {
1911 PatKind::Range(..) => true,
1915 self.s.word(mutbl.prefix_str());
1919 self.print_pat(&inner);
1924 PatKind::Lit(ref e) => self.print_expr(&e),
1925 PatKind::Range(ref begin, ref end, ref end_kind) => {
1926 if let Some(expr) = begin {
1927 self.print_expr(expr);
1931 RangeEnd::Included => self.s.word("..."),
1932 RangeEnd::Excluded => self.s.word(".."),
1934 if let Some(expr) = end {
1935 self.print_expr(expr);
1938 PatKind::Slice(ref before, ref slice, ref after) => {
1940 self.commasep(Inconsistent, &before[..], |s, p| s.print_pat(&p));
1941 if let Some(ref p) = *slice {
1942 if !before.is_empty() {
1943 self.word_space(",");
1945 if let PatKind::Wild = p.kind {
1951 if !after.is_empty() {
1952 self.word_space(",");
1955 self.commasep(Inconsistent, &after[..], |s, p| s.print_pat(&p));
1959 self.ann.post(self, AnnNode::Pat(pat))
1962 pub fn print_param(&mut self, arg: &hir::Param<'_>) {
1963 self.print_outer_attributes(&arg.attrs);
1964 self.print_pat(&arg.pat);
1967 pub fn print_arm(&mut self, arm: &hir::Arm<'_>) {
1968 // I have no idea why this check is necessary, but here it
1970 if arm.attrs.is_empty() {
1973 self.cbox(INDENT_UNIT);
1974 self.ann.pre(self, AnnNode::Arm(arm));
1976 self.print_outer_attributes(&arm.attrs);
1977 self.print_pat(&arm.pat);
1979 if let Some(ref g) = arm.guard {
1981 hir::Guard::If(e) => {
1982 self.word_space("if");
1983 self.print_expr(&e);
1988 self.word_space("=>");
1990 match arm.body.kind {
1991 hir::ExprKind::Block(ref blk, opt_label) => {
1992 if let Some(label) = opt_label {
1993 self.print_ident(label.ident);
1994 self.word_space(":");
1996 // the block will close the pattern's ibox
1997 self.print_block_unclosed(&blk);
1999 // If it is a user-provided unsafe block, print a comma after it
2000 if let hir::BlockCheckMode::UnsafeBlock(hir::UnsafeSource::UserProvided) = blk.rules
2006 self.end(); // close the ibox for the pattern
2007 self.print_expr(&arm.body);
2011 self.ann.post(self, AnnNode::Arm(arm));
2012 self.end() // close enclosing cbox
2017 decl: &hir::FnDecl<'_>,
2018 header: hir::FnHeader,
2019 name: Option<Symbol>,
2020 generics: &hir::Generics<'_>,
2021 vis: &hir::Visibility<'_>,
2022 arg_names: &[Ident],
2023 body_id: Option<hir::BodyId>,
2025 self.print_fn_header_info(header, vis);
2027 if let Some(name) = name {
2029 self.print_name(name);
2031 self.print_generic_params(&generics.params);
2035 // Make sure we aren't supplied *both* `arg_names` and `body_id`.
2036 assert!(arg_names.is_empty() || body_id.is_none());
2037 self.commasep(Inconsistent, &decl.inputs, |s, ty| {
2038 s.ibox(INDENT_UNIT);
2039 if let Some(arg_name) = arg_names.get(i) {
2040 s.s.word(arg_name.to_string());
2043 } else if let Some(body_id) = body_id {
2044 s.ann.nested(s, Nested::BodyParamPat(body_id, i));
2052 if decl.c_variadic {
2053 self.s.word(", ...");
2057 self.print_fn_output(decl);
2058 self.print_where_clause(&generics.where_clause)
2061 fn print_closure_params(&mut self, decl: &hir::FnDecl<'_>, body_id: hir::BodyId) {
2064 self.commasep(Inconsistent, &decl.inputs, |s, ty| {
2065 s.ibox(INDENT_UNIT);
2067 s.ann.nested(s, Nested::BodyParamPat(body_id, i));
2070 if let hir::TyKind::Infer = ty.kind {
2081 if let hir::FnRetTy::DefaultReturn(..) = decl.output {
2085 self.space_if_not_bol();
2086 self.word_space("->");
2088 hir::FnRetTy::Return(ref ty) => {
2089 self.print_type(&ty);
2090 self.maybe_print_comment(ty.span.lo())
2092 hir::FnRetTy::DefaultReturn(..) => unreachable!(),
2096 pub fn print_capture_clause(&mut self, capture_clause: hir::CaptureBy) {
2097 match capture_clause {
2098 hir::CaptureBy::Value => self.word_space("move"),
2099 hir::CaptureBy::Ref => {}
2103 pub fn print_bounds<'b>(
2105 prefix: &'static str,
2106 bounds: impl IntoIterator<Item = &'b hir::GenericBound<'b>>,
2108 let mut first = true;
2109 for bound in bounds {
2111 self.s.word(prefix);
2113 if !(first && prefix.is_empty()) {
2119 self.word_space("+");
2123 GenericBound::Trait(tref, modifier) => {
2124 if modifier == &TraitBoundModifier::Maybe {
2127 self.print_poly_trait_ref(tref);
2129 GenericBound::Outlives(lt) => {
2130 self.print_lifetime(lt);
2136 pub fn print_generic_params(&mut self, generic_params: &[GenericParam<'_>]) {
2137 if !generic_params.is_empty() {
2140 self.commasep(Inconsistent, generic_params, |s, param| s.print_generic_param(param));
2146 pub fn print_generic_param(&mut self, param: &GenericParam<'_>) {
2147 if let GenericParamKind::Const { .. } = param.kind {
2148 self.word_space("const");
2151 self.print_ident(param.name.ident());
2154 GenericParamKind::Lifetime { .. } => {
2156 for bound in param.bounds {
2158 GenericBound::Outlives(ref lt) => {
2160 self.print_lifetime(lt);
2167 GenericParamKind::Type { ref default, .. } => {
2168 self.print_bounds(":", param.bounds);
2169 if let Some(default) = default {
2171 self.word_space("=");
2172 self.print_type(&default)
2175 GenericParamKind::Const { ref ty } => {
2176 self.word_space(":");
2182 pub fn print_lifetime(&mut self, lifetime: &hir::Lifetime) {
2183 self.print_ident(lifetime.name.ident())
2186 pub fn print_where_clause(&mut self, where_clause: &hir::WhereClause<'_>) {
2187 if where_clause.predicates.is_empty() {
2192 self.word_space("where");
2194 for (i, predicate) in where_clause.predicates.iter().enumerate() {
2196 self.word_space(",");
2200 &hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
2201 ref bound_generic_params,
2206 self.print_formal_generic_params(bound_generic_params);
2207 self.print_type(&bounded_ty);
2208 self.print_bounds(":", bounds);
2210 &hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
2215 self.print_lifetime(lifetime);
2218 for (i, bound) in bounds.iter().enumerate() {
2220 GenericBound::Outlives(lt) => {
2221 self.print_lifetime(lt);
2231 &hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
2236 self.print_type(lhs_ty);
2238 self.word_space("=");
2239 self.print_type(rhs_ty);
2245 pub fn print_mutability(&mut self, mutbl: hir::Mutability, print_const: bool) {
2247 hir::Mutability::Mut => self.word_nbsp("mut"),
2248 hir::Mutability::Not => {
2250 self.word_nbsp("const")
2256 pub fn print_mt(&mut self, mt: &hir::MutTy<'_>, print_const: bool) {
2257 self.print_mutability(mt.mutbl, print_const);
2258 self.print_type(&mt.ty)
2261 pub fn print_fn_output(&mut self, decl: &hir::FnDecl<'_>) {
2262 if let hir::FnRetTy::DefaultReturn(..) = decl.output {
2266 self.space_if_not_bol();
2267 self.ibox(INDENT_UNIT);
2268 self.word_space("->");
2270 hir::FnRetTy::DefaultReturn(..) => unreachable!(),
2271 hir::FnRetTy::Return(ref ty) => self.print_type(&ty),
2275 if let hir::FnRetTy::Return(ref output) = decl.output {
2276 self.maybe_print_comment(output.span.lo())
2283 unsafety: hir::Unsafety,
2284 decl: &hir::FnDecl<'_>,
2285 name: Option<Symbol>,
2286 generic_params: &[hir::GenericParam<'_>],
2287 arg_names: &[Ident],
2289 self.ibox(INDENT_UNIT);
2290 if !generic_params.is_empty() {
2292 self.print_generic_params(generic_params);
2294 let generics = hir::Generics {
2296 where_clause: hir::WhereClause { predicates: &[], span: rustc_span::DUMMY_SP },
2297 span: rustc_span::DUMMY_SP,
2304 constness: hir::Constness::NotConst,
2305 asyncness: hir::IsAsync::NotAsync,
2309 &Spanned { span: rustc_span::DUMMY_SP, node: hir::VisibilityKind::Inherited },
2316 pub fn maybe_print_trailing_comment(
2318 span: rustc_span::Span,
2319 next_pos: Option<BytePos>,
2321 if let Some(cmnts) = self.comments() {
2322 if let Some(cmnt) = cmnts.trailing_comment(span, next_pos) {
2323 self.print_comment(&cmnt);
2328 pub fn print_remaining_comments(&mut self) {
2329 // If there aren't any remaining comments, then we need to manually
2330 // make sure there is a line break at the end.
2331 if self.next_comment().is_none() {
2334 while let Some(ref cmnt) = self.next_comment() {
2335 self.print_comment(cmnt)
2339 pub fn print_opt_abi_and_extern_if_nondefault(&mut self, opt_abi: Option<Abi>) {
2341 Some(Abi::Rust) => {}
2343 self.word_nbsp("extern");
2344 self.word_nbsp(abi.to_string())
2350 pub fn print_extern_opt_abi(&mut self, opt_abi: Option<Abi>) {
2351 if let Some(abi) = opt_abi {
2352 self.word_nbsp("extern");
2353 self.word_nbsp(abi.to_string())
2357 pub fn print_fn_header_info(&mut self, header: hir::FnHeader, vis: &hir::Visibility<'_>) {
2358 self.s.word(visibility_qualified(vis, ""));
2360 match header.constness {
2361 hir::Constness::NotConst => {}
2362 hir::Constness::Const => self.word_nbsp("const"),
2365 match header.asyncness {
2366 hir::IsAsync::NotAsync => {}
2367 hir::IsAsync::Async => self.word_nbsp("async"),
2370 self.print_unsafety(header.unsafety);
2372 if header.abi != Abi::Rust {
2373 self.word_nbsp("extern");
2374 self.word_nbsp(header.abi.to_string());
2380 pub fn print_unsafety(&mut self, s: hir::Unsafety) {
2382 hir::Unsafety::Normal => {}
2383 hir::Unsafety::Unsafe => self.word_nbsp("unsafe"),
2387 pub fn print_is_auto(&mut self, s: hir::IsAuto) {
2389 hir::IsAuto::Yes => self.word_nbsp("auto"),
2390 hir::IsAuto::No => {}
2395 /// Does this expression require a semicolon to be treated
2396 /// as a statement? The negation of this: 'can this expression
2397 /// be used as a statement without a semicolon' -- is used
2398 /// as an early-bail-out in the parser so that, for instance,
2399 /// if true {...} else {...}
2401 /// isn't parsed as (if true {...} else {...} | x) | 5
2403 // Duplicated from `parse::classify`, but adapted for the HIR.
2404 fn expr_requires_semi_to_be_stmt(e: &hir::Expr<'_>) -> bool {
2406 hir::ExprKind::Match(..) | hir::ExprKind::Block(..) | hir::ExprKind::Loop(..) => false,
2411 /// This statement requires a semicolon after it.
2412 /// note that in one case (stmt_semi), we've already
2413 /// seen the semicolon, and thus don't need another.
2414 fn stmt_ends_with_semi(stmt: &hir::StmtKind<'_>) -> bool {
2416 hir::StmtKind::Local(_) => true,
2417 hir::StmtKind::Item(_) => false,
2418 hir::StmtKind::Expr(ref e) => expr_requires_semi_to_be_stmt(&e),
2419 hir::StmtKind::Semi(..) => false,
2423 fn bin_op_to_assoc_op(op: hir::BinOpKind) -> AssocOp {
2424 use crate::hir::BinOpKind::*;
2426 Add => AssocOp::Add,
2427 Sub => AssocOp::Subtract,
2428 Mul => AssocOp::Multiply,
2429 Div => AssocOp::Divide,
2430 Rem => AssocOp::Modulus,
2432 And => AssocOp::LAnd,
2435 BitXor => AssocOp::BitXor,
2436 BitAnd => AssocOp::BitAnd,
2437 BitOr => AssocOp::BitOr,
2438 Shl => AssocOp::ShiftLeft,
2439 Shr => AssocOp::ShiftRight,
2441 Eq => AssocOp::Equal,
2442 Lt => AssocOp::Less,
2443 Le => AssocOp::LessEqual,
2444 Ne => AssocOp::NotEqual,
2445 Ge => AssocOp::GreaterEqual,
2446 Gt => AssocOp::Greater,
2450 /// Expressions that syntactically contain an "exterior" struct literal, i.e., not surrounded by any
2451 /// parens or other delimiters, e.g., `X { y: 1 }`, `X { y: 1 }.method()`, `foo == X { y: 1 }` and
2452 /// `X { y: 1 } == foo` all do, but `(X { y: 1 }) == foo` does not.
2453 fn contains_exterior_struct_lit(value: &hir::Expr<'_>) -> bool {
2455 hir::ExprKind::Struct(..) => true,
2457 hir::ExprKind::Assign(ref lhs, ref rhs, _)
2458 | hir::ExprKind::AssignOp(_, ref lhs, ref rhs)
2459 | hir::ExprKind::Binary(_, ref lhs, ref rhs) => {
2460 // `X { y: 1 } + X { y: 2 }`
2461 contains_exterior_struct_lit(&lhs) || contains_exterior_struct_lit(&rhs)
2463 hir::ExprKind::Unary(_, ref x)
2464 | hir::ExprKind::Cast(ref x, _)
2465 | hir::ExprKind::Type(ref x, _)
2466 | hir::ExprKind::Field(ref x, _)
2467 | hir::ExprKind::Index(ref x, _) => {
2468 // `&X { y: 1 }, X { y: 1 }.y`
2469 contains_exterior_struct_lit(&x)
2472 hir::ExprKind::MethodCall(.., ref exprs) => {
2473 // `X { y: 1 }.bar(...)`
2474 contains_exterior_struct_lit(&exprs[0])