1 #![recursion_limit = "256"]
4 use rustc_ast::util::parser::{self, AssocOp, Fixity};
5 use rustc_ast_pretty::pp::Breaks::{Consistent, Inconsistent};
6 use rustc_ast_pretty::pp::{self, Breaks};
7 use rustc_ast_pretty::pprust::{Comments, PrintState};
9 use rustc_hir::{GenericArg, GenericParam, GenericParamKind, Node};
10 use rustc_hir::{GenericBound, PatKind, RangeEnd, TraitBoundModifier};
11 use rustc_span::source_map::{SourceMap, Spanned};
12 use rustc_span::symbol::{kw, Ident, IdentPrinter, Symbol};
13 use rustc_span::{self, BytePos, FileName};
14 use rustc_target::spec::abi::Abi;
20 pub fn id_to_string(map: &dyn rustc_hir::intravisit::Map<'_>, hir_id: hir::HirId) -> String {
21 to_string(&map, |s| s.print_node(map.find(hir_id).unwrap()))
24 pub enum AnnNode<'a> {
26 Block(&'a hir::Block<'a>),
27 Item(&'a hir::Item<'a>),
29 Expr(&'a hir::Expr<'a>),
30 Pat(&'a hir::Pat<'a>),
31 Arm(&'a hir::Arm<'a>),
36 TraitItem(hir::TraitItemId),
37 ImplItem(hir::ImplItemId),
38 ForeignItem(hir::ForeignItemId),
40 BodyParamPat(hir::BodyId, usize),
44 fn nested(&self, _state: &mut State<'_>, _nested: Nested) {}
45 fn pre(&self, _state: &mut State<'_>, _node: AnnNode<'_>) {}
46 fn post(&self, _state: &mut State<'_>, _node: AnnNode<'_>) {}
50 impl PpAnn for NoAnn {}
51 pub const NO_ANN: &dyn PpAnn = &NoAnn;
53 /// Identical to the `PpAnn` implementation for `hir::Crate`,
54 /// except it avoids creating a dependency on the whole crate.
55 impl PpAnn for &dyn rustc_hir::intravisit::Map<'_> {
56 fn nested(&self, state: &mut State<'_>, nested: Nested) {
58 Nested::Item(id) => state.print_item(self.item(id)),
59 Nested::TraitItem(id) => state.print_trait_item(self.trait_item(id)),
60 Nested::ImplItem(id) => state.print_impl_item(self.impl_item(id)),
61 Nested::ForeignItem(id) => state.print_foreign_item(self.foreign_item(id)),
62 Nested::Body(id) => state.print_expr(&self.body(id).value),
63 Nested::BodyParamPat(id, i) => state.print_pat(&self.body(id).params[i].pat),
68 pub struct State<'a> {
70 comments: Option<Comments<'a>>,
71 attrs: &'a dyn Fn(hir::HirId) -> &'a [ast::Attribute],
72 ann: &'a (dyn PpAnn + 'a),
76 pub fn print_node(&mut self, node: Node<'_>) {
78 Node::Param(a) => self.print_param(&a),
79 Node::Item(a) => self.print_item(&a),
80 Node::ForeignItem(a) => self.print_foreign_item(&a),
81 Node::TraitItem(a) => self.print_trait_item(a),
82 Node::ImplItem(a) => self.print_impl_item(a),
83 Node::Variant(a) => self.print_variant(&a),
84 Node::AnonConst(a) => self.print_anon_const(&a),
85 Node::Expr(a) => self.print_expr(&a),
86 Node::Stmt(a) => self.print_stmt(&a),
87 Node::PathSegment(a) => self.print_path_segment(&a),
88 Node::Ty(a) => self.print_type(&a),
89 Node::TraitRef(a) => self.print_trait_ref(&a),
90 Node::Binding(a) | Node::Pat(a) => self.print_pat(&a),
91 Node::Arm(a) => self.print_arm(&a),
92 Node::Infer(_) => self.s.word("_"),
94 // Containing cbox, will be closed by print-block at `}`.
95 self.cbox(INDENT_UNIT);
96 // Head-ibox, will be closed by print-block after `{`.
100 Node::Lifetime(a) => self.print_lifetime(&a),
101 Node::Visibility(a) => self.print_visibility(&a),
102 Node::GenericParam(_) => panic!("cannot print Node::GenericParam"),
103 Node::Field(_) => panic!("cannot print Node::Field"),
104 // These cases do not carry enough information in the
105 // `hir_map` to reconstruct their full structure for pretty
107 Node::Ctor(..) => panic!("cannot print isolated Ctor"),
108 Node::Local(a) => self.print_local_decl(&a),
109 Node::Crate(..) => panic!("cannot print Crate"),
114 impl std::ops::Deref for State<'_> {
115 type Target = pp::Printer;
116 fn deref(&self) -> &Self::Target {
121 impl std::ops::DerefMut for State<'_> {
122 fn deref_mut(&mut self) -> &mut Self::Target {
127 impl<'a> PrintState<'a> for State<'a> {
128 fn comments(&mut self) -> &mut Option<Comments<'a>> {
132 fn print_ident(&mut self, ident: Ident) {
133 self.s.word(IdentPrinter::for_ast_ident(ident, ident.is_raw_guess()).to_string());
134 self.ann.post(self, AnnNode::Name(&ident.name))
137 fn print_generic_args(&mut self, _: &ast::GenericArgs, _colons_before_params: bool) {
138 panic!("AST generic args printed by HIR pretty-printer");
142 pub const INDENT_UNIT: usize = 4;
144 /// Requires you to pass an input filename and reader so that
145 /// it can scan the input text for comments to copy forward.
146 pub fn print_crate<'a>(
148 krate: &hir::Mod<'_>,
151 attrs: &'a dyn Fn(hir::HirId) -> &'a [ast::Attribute],
154 let mut s = State::new_from_input(sm, filename, input, attrs, ann);
156 // When printing the AST, we sometimes need to inject `#[no_std]` here.
157 // Since you can't compile the HIR, it's not necessary.
159 s.print_mod(krate, (*attrs)(hir::CRATE_HIR_ID));
160 s.print_remaining_comments();
165 pub fn new_from_input(
169 attrs: &'a dyn Fn(hir::HirId) -> &'a [ast::Attribute],
174 comments: Some(Comments::new(sm, filename, input)),
180 fn attrs(&self, id: hir::HirId) -> &'a [ast::Attribute] {
185 pub fn to_string<F>(ann: &dyn PpAnn, f: F) -> String
187 F: FnOnce(&mut State<'_>),
189 let mut printer = State { s: pp::mk_printer(), comments: None, attrs: &|_| &[], ann };
194 pub fn visibility_qualified<S: Into<Cow<'static, str>>>(vis: &hir::Visibility<'_>, w: S) -> String {
195 to_string(NO_ANN, |s| {
196 s.print_visibility(vis);
201 pub fn generic_params_to_string(generic_params: &[GenericParam<'_>]) -> String {
202 to_string(NO_ANN, |s| s.print_generic_params(generic_params))
205 pub fn bounds_to_string<'b>(bounds: impl IntoIterator<Item = &'b hir::GenericBound<'b>>) -> String {
206 to_string(NO_ANN, |s| s.print_bounds("", bounds))
209 pub fn ty_to_string(ty: &hir::Ty<'_>) -> String {
210 to_string(NO_ANN, |s| s.print_type(ty))
213 pub fn path_segment_to_string(segment: &hir::PathSegment<'_>) -> String {
214 to_string(NO_ANN, |s| s.print_path_segment(segment))
217 pub fn path_to_string(segment: &hir::Path<'_>) -> String {
218 to_string(NO_ANN, |s| s.print_path(segment, false))
222 decl: &hir::FnDecl<'_>,
223 header: hir::FnHeader,
224 name: Option<Symbol>,
225 generics: &hir::Generics<'_>,
226 vis: &hir::Visibility<'_>,
228 body_id: Option<hir::BodyId>,
230 to_string(NO_ANN, |s| s.print_fn(decl, header, name, generics, vis, arg_names, body_id))
233 pub fn enum_def_to_string(
234 enum_definition: &hir::EnumDef<'_>,
235 generics: &hir::Generics<'_>,
237 span: rustc_span::Span,
238 visibility: &hir::Visibility<'_>,
240 to_string(NO_ANN, |s| s.print_enum_def(enum_definition, generics, name, span, visibility))
244 pub fn cbox(&mut self, u: usize) {
248 pub fn nbsp(&mut self) {
252 pub fn word_nbsp<S: Into<Cow<'static, str>>>(&mut self, w: S) {
257 pub fn head<S: Into<Cow<'static, str>>>(&mut self, w: S) {
259 // outer-box is consistent
260 self.cbox(INDENT_UNIT);
261 // head-box is inconsistent
262 self.ibox(w.len() + 1);
263 // keyword that starts the head
269 pub fn bopen(&mut self) {
271 self.end(); // close the head-box
274 pub fn bclose_maybe_open(&mut self, span: rustc_span::Span, close_box: bool) {
275 self.maybe_print_comment(span.hi());
276 self.break_offset_if_not_bol(1, -(INDENT_UNIT as isize));
279 self.end(); // close the outer-box
283 pub fn bclose(&mut self, span: rustc_span::Span) {
284 self.bclose_maybe_open(span, true)
287 pub fn space_if_not_bol(&mut self) {
288 if !self.s.is_beginning_of_line() {
293 pub fn break_offset_if_not_bol(&mut self, n: usize, off: isize) {
294 if !self.s.is_beginning_of_line() {
295 self.s.break_offset(n, off)
296 } else if off != 0 && self.s.last_token().is_hardbreak_tok() {
297 // We do something pretty sketchy here: tuck the nonzero
298 // offset-adjustment we were going to deposit along with the
299 // break into the previous hardbreak.
300 self.s.replace_last_token(pp::Printer::hardbreak_tok_offset(off));
304 // Synthesizes a comment that was not textually present in the original source
306 pub fn synth_comment(&mut self, text: String) {
314 pub fn commasep_cmnt<T, F, G>(&mut self, b: Breaks, elts: &[T], mut op: F, mut get_span: G)
316 F: FnMut(&mut State<'_>, &T),
317 G: FnMut(&T) -> rustc_span::Span,
320 let len = elts.len();
323 self.maybe_print_comment(get_span(elt).hi());
328 self.maybe_print_trailing_comment(get_span(elt), Some(get_span(&elts[i]).hi()));
329 self.space_if_not_bol();
335 pub fn commasep_exprs(&mut self, b: Breaks, exprs: &[hir::Expr<'_>]) {
336 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(&e), |e| e.span)
339 pub fn print_mod(&mut self, _mod: &hir::Mod<'_>, attrs: &[ast::Attribute]) {
340 self.print_inner_attributes(attrs);
341 for &item_id in _mod.item_ids {
342 self.ann.nested(self, Nested::Item(item_id));
346 pub fn print_opt_lifetime(&mut self, lifetime: &hir::Lifetime) {
347 if !lifetime.is_elided() {
348 self.print_lifetime(lifetime);
353 pub fn print_type(&mut self, ty: &hir::Ty<'_>) {
354 self.maybe_print_comment(ty.span.lo());
357 hir::TyKind::Slice(ref ty) => {
359 self.print_type(&ty);
362 hir::TyKind::Ptr(ref mt) => {
364 self.print_mt(mt, true);
366 hir::TyKind::Rptr(ref lifetime, ref mt) => {
368 self.print_opt_lifetime(lifetime);
369 self.print_mt(mt, false);
371 hir::TyKind::Never => {
374 hir::TyKind::Tup(ref elts) => {
376 self.commasep(Inconsistent, &elts[..], |s, ty| s.print_type(&ty));
382 hir::TyKind::BareFn(ref f) => {
392 hir::TyKind::OpaqueDef(..) => self.s.word("/*impl Trait*/"),
393 hir::TyKind::Path(ref qpath) => self.print_qpath(qpath, false),
394 hir::TyKind::TraitObject(bounds, ref lifetime, syntax) => {
395 if syntax == ast::TraitObjectSyntax::Dyn {
396 self.word_space("dyn");
398 let mut first = true;
399 for bound in bounds {
404 self.word_space("+");
406 self.print_poly_trait_ref(bound);
408 if !lifetime.is_elided() {
410 self.word_space("+");
411 self.print_lifetime(lifetime);
414 hir::TyKind::Array(ref ty, ref length) => {
416 self.print_type(&ty);
418 self.print_anon_const(length);
421 hir::TyKind::Typeof(ref e) => {
422 self.s.word("typeof(");
423 self.print_anon_const(e);
426 hir::TyKind::Err => {
428 self.s.word("/*ERROR*/");
431 hir::TyKind::Infer => {
438 pub fn print_foreign_item(&mut self, item: &hir::ForeignItem<'_>) {
439 self.hardbreak_if_not_bol();
440 self.maybe_print_comment(item.span.lo());
441 self.print_outer_attributes(self.attrs(item.hir_id()));
443 hir::ForeignItemKind::Fn(ref decl, ref arg_names, ref generics) => {
448 unsafety: hir::Unsafety::Normal,
449 constness: hir::Constness::NotConst,
451 asyncness: hir::IsAsync::NotAsync,
453 Some(item.ident.name),
459 self.end(); // end head-ibox
461 self.end() // end the outer fn box
463 hir::ForeignItemKind::Static(ref t, m) => {
464 self.head(visibility_qualified(&item.vis, "static"));
465 if m == hir::Mutability::Mut {
466 self.word_space("mut");
468 self.print_ident(item.ident);
469 self.word_space(":");
472 self.end(); // end the head-ibox
473 self.end() // end the outer cbox
475 hir::ForeignItemKind::Type => {
476 self.head(visibility_qualified(&item.vis, "type"));
477 self.print_ident(item.ident);
479 self.end(); // end the head-ibox
480 self.end() // end the outer cbox
485 fn print_associated_const(
489 default: Option<hir::BodyId>,
490 vis: &hir::Visibility<'_>,
492 self.s.word(visibility_qualified(vis, ""));
493 self.word_space("const");
494 self.print_ident(ident);
495 self.word_space(":");
497 if let Some(expr) = default {
499 self.word_space("=");
500 self.ann.nested(self, Nested::Body(expr));
505 fn print_associated_type(
508 generics: &hir::Generics<'_>,
509 bounds: Option<hir::GenericBounds<'_>>,
510 ty: Option<&hir::Ty<'_>>,
512 self.word_space("type");
513 self.print_ident(ident);
514 self.print_generic_params(&generics.params);
515 if let Some(bounds) = bounds {
516 self.print_bounds(":", bounds);
518 self.print_where_clause(&generics.where_clause);
519 if let Some(ty) = ty {
521 self.word_space("=");
529 item: &hir::Item<'_>,
530 generics: &hir::Generics<'_>,
531 inner: impl Fn(&mut Self),
533 self.head(visibility_qualified(&item.vis, "type"));
534 self.print_ident(item.ident);
535 self.print_generic_params(&generics.params);
536 self.end(); // end the inner ibox
538 self.print_where_clause(&generics.where_clause);
542 self.end(); // end the outer ibox
545 /// Pretty-print an item
546 pub fn print_item(&mut self, item: &hir::Item<'_>) {
547 self.hardbreak_if_not_bol();
548 self.maybe_print_comment(item.span.lo());
549 let attrs = self.attrs(item.hir_id());
550 self.print_outer_attributes(attrs);
551 self.ann.pre(self, AnnNode::Item(item));
553 hir::ItemKind::ExternCrate(orig_name) => {
554 self.head(visibility_qualified(&item.vis, "extern crate"));
555 if let Some(orig_name) = orig_name {
556 self.print_name(orig_name);
561 self.print_ident(item.ident);
563 self.end(); // end inner head-block
564 self.end(); // end outer head-block
566 hir::ItemKind::Use(ref path, kind) => {
567 self.head(visibility_qualified(&item.vis, "use"));
568 self.print_path(path, false);
571 hir::UseKind::Single => {
572 if path.segments.last().unwrap().ident != item.ident {
574 self.word_space("as");
575 self.print_ident(item.ident);
579 hir::UseKind::Glob => self.s.word("::*;"),
580 hir::UseKind::ListStem => self.s.word("::{};"),
582 self.end(); // end inner head-block
583 self.end(); // end outer head-block
585 hir::ItemKind::Static(ref ty, m, expr) => {
586 self.head(visibility_qualified(&item.vis, "static"));
587 if m == hir::Mutability::Mut {
588 self.word_space("mut");
590 self.print_ident(item.ident);
591 self.word_space(":");
592 self.print_type(&ty);
594 self.end(); // end the head-ibox
596 self.word_space("=");
597 self.ann.nested(self, Nested::Body(expr));
599 self.end(); // end the outer cbox
601 hir::ItemKind::Const(ref ty, expr) => {
602 self.head(visibility_qualified(&item.vis, "const"));
603 self.print_ident(item.ident);
604 self.word_space(":");
605 self.print_type(&ty);
607 self.end(); // end the head-ibox
609 self.word_space("=");
610 self.ann.nested(self, Nested::Body(expr));
612 self.end(); // end the outer cbox
614 hir::ItemKind::Fn(ref sig, ref param_names, body) => {
619 Some(item.ident.name),
626 self.end(); // need to close a box
627 self.end(); // need to close a box
628 self.ann.nested(self, Nested::Body(body));
630 hir::ItemKind::Macro(ref macro_def) => {
631 self.print_mac_def(macro_def, &item.ident, &item.span, |state| {
632 state.print_visibility(&item.vis)
635 hir::ItemKind::Mod(ref _mod) => {
636 self.head(visibility_qualified(&item.vis, "mod"));
637 self.print_ident(item.ident);
640 self.print_mod(_mod, attrs);
641 self.bclose(item.span);
643 hir::ItemKind::ForeignMod { abi, items } => {
645 self.word_nbsp(abi.to_string());
647 self.print_inner_attributes(self.attrs(item.hir_id()));
649 self.ann.nested(self, Nested::ForeignItem(item.id));
651 self.bclose(item.span);
653 hir::ItemKind::GlobalAsm(ref asm) => {
654 self.head(visibility_qualified(&item.vis, "global_asm!"));
655 self.print_inline_asm(asm);
658 hir::ItemKind::TyAlias(ref ty, ref generics) => {
659 self.print_item_type(item, &generics, |state| {
660 state.word_space("=");
661 state.print_type(&ty);
664 hir::ItemKind::OpaqueTy(ref opaque_ty) => {
665 self.print_item_type(item, &opaque_ty.generics, |state| {
666 let mut real_bounds = Vec::with_capacity(opaque_ty.bounds.len());
667 for b in opaque_ty.bounds.iter() {
668 if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
670 state.word_space("for ?");
671 state.print_trait_ref(&ptr.trait_ref);
676 state.print_bounds("= impl", real_bounds);
679 hir::ItemKind::Enum(ref enum_definition, ref params) => {
680 self.print_enum_def(enum_definition, params, item.ident.name, item.span, &item.vis);
682 hir::ItemKind::Struct(ref struct_def, ref generics) => {
683 self.head(visibility_qualified(&item.vis, "struct"));
684 self.print_struct(struct_def, generics, item.ident.name, item.span, true);
686 hir::ItemKind::Union(ref struct_def, ref generics) => {
687 self.head(visibility_qualified(&item.vis, "union"));
688 self.print_struct(struct_def, generics, item.ident.name, item.span, true);
690 hir::ItemKind::Impl(hir::Impl {
702 self.print_visibility(&item.vis);
703 self.print_defaultness(defaultness);
704 self.print_unsafety(unsafety);
705 self.word_nbsp("impl");
707 if !generics.params.is_empty() {
708 self.print_generic_params(&generics.params);
712 if constness == hir::Constness::Const {
713 self.word_nbsp("const");
716 if let hir::ImplPolarity::Negative(_) = polarity {
720 if let Some(ref t) = of_trait {
721 self.print_trait_ref(t);
723 self.word_space("for");
726 self.print_type(&self_ty);
727 self.print_where_clause(&generics.where_clause);
731 self.print_inner_attributes(attrs);
732 for impl_item in items {
733 self.ann.nested(self, Nested::ImplItem(impl_item.id));
735 self.bclose(item.span);
737 hir::ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, trait_items) => {
739 self.print_visibility(&item.vis);
740 self.print_is_auto(is_auto);
741 self.print_unsafety(unsafety);
742 self.word_nbsp("trait");
743 self.print_ident(item.ident);
744 self.print_generic_params(&generics.params);
745 let mut real_bounds = Vec::with_capacity(bounds.len());
746 for b in bounds.iter() {
747 if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
749 self.word_space("for ?");
750 self.print_trait_ref(&ptr.trait_ref);
755 self.print_bounds(":", real_bounds);
756 self.print_where_clause(&generics.where_clause);
759 for trait_item in trait_items {
760 self.ann.nested(self, Nested::TraitItem(trait_item.id));
762 self.bclose(item.span);
764 hir::ItemKind::TraitAlias(ref generics, ref bounds) => {
766 self.print_visibility(&item.vis);
767 self.word_nbsp("trait");
768 self.print_ident(item.ident);
769 self.print_generic_params(&generics.params);
770 let mut real_bounds = Vec::with_capacity(bounds.len());
771 // FIXME(durka) this seems to be some quite outdated syntax
772 for b in bounds.iter() {
773 if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
775 self.word_space("for ?");
776 self.print_trait_ref(&ptr.trait_ref);
782 self.print_bounds("=", real_bounds);
783 self.print_where_clause(&generics.where_clause);
787 self.ann.post(self, AnnNode::Item(item))
790 pub fn print_trait_ref(&mut self, t: &hir::TraitRef<'_>) {
791 self.print_path(&t.path, false)
794 fn print_formal_generic_params(&mut self, generic_params: &[hir::GenericParam<'_>]) {
795 if !generic_params.is_empty() {
797 self.print_generic_params(generic_params);
802 fn print_poly_trait_ref(&mut self, t: &hir::PolyTraitRef<'_>) {
803 self.print_formal_generic_params(&t.bound_generic_params);
804 self.print_trait_ref(&t.trait_ref)
807 pub fn print_enum_def(
809 enum_definition: &hir::EnumDef<'_>,
810 generics: &hir::Generics<'_>,
812 span: rustc_span::Span,
813 visibility: &hir::Visibility<'_>,
815 self.head(visibility_qualified(visibility, "enum"));
816 self.print_name(name);
817 self.print_generic_params(&generics.params);
818 self.print_where_clause(&generics.where_clause);
820 self.print_variants(&enum_definition.variants, span)
823 pub fn print_variants(&mut self, variants: &[hir::Variant<'_>], span: rustc_span::Span) {
826 self.space_if_not_bol();
827 self.maybe_print_comment(v.span.lo());
828 self.print_outer_attributes(self.attrs(v.id));
829 self.ibox(INDENT_UNIT);
830 self.print_variant(v);
833 self.maybe_print_trailing_comment(v.span, None);
838 pub fn print_visibility(&mut self, vis: &hir::Visibility<'_>) {
840 hir::VisibilityKind::Public => self.word_nbsp("pub"),
841 hir::VisibilityKind::Crate(ast::CrateSugar::JustCrate) => self.word_nbsp("crate"),
842 hir::VisibilityKind::Crate(ast::CrateSugar::PubCrate) => self.word_nbsp("pub(crate)"),
843 hir::VisibilityKind::Restricted { ref path, .. } => {
845 if path.segments.len() == 1 && path.segments[0].ident.name == kw::Super {
846 // Special case: `super` can print like `pub(super)`.
847 self.s.word("super");
849 // Everything else requires `in` at present.
850 self.word_nbsp("in");
851 self.print_path(path, false);
855 hir::VisibilityKind::Inherited => (),
859 pub fn print_defaultness(&mut self, defaultness: hir::Defaultness) {
861 hir::Defaultness::Default { .. } => self.word_nbsp("default"),
862 hir::Defaultness::Final => (),
868 struct_def: &hir::VariantData<'_>,
869 generics: &hir::Generics<'_>,
871 span: rustc_span::Span,
872 print_finalizer: bool,
874 self.print_name(name);
875 self.print_generic_params(&generics.params);
877 hir::VariantData::Tuple(..) | hir::VariantData::Unit(..) => {
878 if let hir::VariantData::Tuple(..) = struct_def {
880 self.commasep(Inconsistent, struct_def.fields(), |s, field| {
881 s.maybe_print_comment(field.span.lo());
882 s.print_outer_attributes(s.attrs(field.hir_id));
883 s.print_visibility(&field.vis);
884 s.print_type(&field.ty)
888 self.print_where_clause(&generics.where_clause);
893 self.end() // close the outer-box
895 hir::VariantData::Struct(..) => {
896 self.print_where_clause(&generics.where_clause);
899 self.hardbreak_if_not_bol();
901 for field in struct_def.fields() {
902 self.hardbreak_if_not_bol();
903 self.maybe_print_comment(field.span.lo());
904 self.print_outer_attributes(self.attrs(field.hir_id));
905 self.print_visibility(&field.vis);
906 self.print_ident(field.ident);
908 self.print_type(&field.ty);
917 pub fn print_variant(&mut self, v: &hir::Variant<'_>) {
919 let generics = hir::Generics::empty();
920 self.print_struct(&v.data, &generics, v.ident.name, v.span, false);
921 if let Some(ref d) = v.disr_expr {
923 self.word_space("=");
924 self.print_anon_const(d);
927 pub fn print_method_sig(
931 generics: &hir::Generics<'_>,
932 vis: &hir::Visibility<'_>,
934 body_id: Option<hir::BodyId>,
936 self.print_fn(&m.decl, m.header, Some(ident.name), generics, vis, arg_names, body_id)
939 pub fn print_trait_item(&mut self, ti: &hir::TraitItem<'_>) {
940 self.ann.pre(self, AnnNode::SubItem(ti.hir_id()));
941 self.hardbreak_if_not_bol();
942 self.maybe_print_comment(ti.span.lo());
943 self.print_outer_attributes(self.attrs(ti.hir_id()));
945 hir::TraitItemKind::Const(ref ty, default) => {
947 Spanned { span: rustc_span::DUMMY_SP, node: hir::VisibilityKind::Inherited };
948 self.print_associated_const(ti.ident, &ty, default, &vis);
950 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Required(ref arg_names)) => {
952 Spanned { span: rustc_span::DUMMY_SP, node: hir::VisibilityKind::Inherited };
953 self.print_method_sig(ti.ident, sig, &ti.generics, &vis, arg_names, None);
956 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Provided(body)) => {
958 Spanned { span: rustc_span::DUMMY_SP, node: hir::VisibilityKind::Inherited };
960 self.print_method_sig(ti.ident, sig, &ti.generics, &vis, &[], Some(body));
962 self.end(); // need to close a box
963 self.end(); // need to close a box
964 self.ann.nested(self, Nested::Body(body));
966 hir::TraitItemKind::Type(ref bounds, ref default) => {
967 self.print_associated_type(
971 default.as_ref().map(|ty| &**ty),
975 self.ann.post(self, AnnNode::SubItem(ti.hir_id()))
978 pub fn print_impl_item(&mut self, ii: &hir::ImplItem<'_>) {
979 self.ann.pre(self, AnnNode::SubItem(ii.hir_id()));
980 self.hardbreak_if_not_bol();
981 self.maybe_print_comment(ii.span.lo());
982 self.print_outer_attributes(self.attrs(ii.hir_id()));
983 self.print_defaultness(ii.defaultness);
986 hir::ImplItemKind::Const(ref ty, expr) => {
987 self.print_associated_const(ii.ident, &ty, Some(expr), &ii.vis);
989 hir::ImplItemKind::Fn(ref sig, body) => {
991 self.print_method_sig(ii.ident, sig, &ii.generics, &ii.vis, &[], Some(body));
993 self.end(); // need to close a box
994 self.end(); // need to close a box
995 self.ann.nested(self, Nested::Body(body));
997 hir::ImplItemKind::TyAlias(ref ty) => {
998 self.print_associated_type(ii.ident, &ii.generics, None, Some(ty));
1001 self.ann.post(self, AnnNode::SubItem(ii.hir_id()))
1004 pub fn print_local(&mut self, init: Option<&hir::Expr<'_>>, decl: impl Fn(&mut Self)) {
1005 self.space_if_not_bol();
1006 self.ibox(INDENT_UNIT);
1007 self.word_nbsp("let");
1009 self.ibox(INDENT_UNIT);
1013 if let Some(ref init) = init {
1015 self.word_space("=");
1016 self.print_expr(&init);
1021 pub fn print_stmt(&mut self, st: &hir::Stmt<'_>) {
1022 self.maybe_print_comment(st.span.lo());
1024 hir::StmtKind::Local(ref loc) => {
1025 self.print_local(loc.init, |this| this.print_local_decl(&loc));
1027 hir::StmtKind::Item(item) => self.ann.nested(self, Nested::Item(item)),
1028 hir::StmtKind::Expr(ref expr) => {
1029 self.space_if_not_bol();
1030 self.print_expr(&expr);
1032 hir::StmtKind::Semi(ref expr) => {
1033 self.space_if_not_bol();
1034 self.print_expr(&expr);
1038 if stmt_ends_with_semi(&st.kind) {
1041 self.maybe_print_trailing_comment(st.span, None)
1044 pub fn print_block(&mut self, blk: &hir::Block<'_>) {
1045 self.print_block_with_attrs(blk, &[])
1048 pub fn print_block_unclosed(&mut self, blk: &hir::Block<'_>) {
1049 self.print_block_maybe_unclosed(blk, &[], false)
1052 pub fn print_block_with_attrs(&mut self, blk: &hir::Block<'_>, attrs: &[ast::Attribute]) {
1053 self.print_block_maybe_unclosed(blk, attrs, true)
1056 pub fn print_block_maybe_unclosed(
1058 blk: &hir::Block<'_>,
1059 attrs: &[ast::Attribute],
1063 hir::BlockCheckMode::UnsafeBlock(..) => self.word_space("unsafe"),
1064 hir::BlockCheckMode::DefaultBlock => (),
1066 self.maybe_print_comment(blk.span.lo());
1067 self.ann.pre(self, AnnNode::Block(blk));
1070 self.print_inner_attributes(attrs);
1072 for st in blk.stmts {
1073 self.print_stmt(st);
1075 if let Some(ref expr) = blk.expr {
1076 self.space_if_not_bol();
1077 self.print_expr(&expr);
1078 self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi()));
1080 self.bclose_maybe_open(blk.span, close_box);
1081 self.ann.post(self, AnnNode::Block(blk))
1084 fn print_else(&mut self, els: Option<&hir::Expr<'_>>) {
1085 if let Some(els_inner) = els {
1086 match els_inner.kind {
1087 // Another `else if` block.
1088 hir::ExprKind::If(ref i, ref then, ref e) => {
1089 self.cbox(INDENT_UNIT - 1);
1091 self.s.word(" else if ");
1092 self.print_expr_as_cond(&i);
1094 self.print_expr(&then);
1095 self.print_else(e.as_ref().map(|e| &**e))
1097 // Final `else` block.
1098 hir::ExprKind::Block(ref b, _) => {
1099 self.cbox(INDENT_UNIT - 1);
1101 self.s.word(" else ");
1102 self.print_block(&b)
1104 // Constraints would be great here!
1106 panic!("print_if saw if with weird alternative");
1114 test: &hir::Expr<'_>,
1115 blk: &hir::Expr<'_>,
1116 elseopt: Option<&hir::Expr<'_>>,
1119 self.print_expr_as_cond(test);
1121 self.print_expr(blk);
1122 self.print_else(elseopt)
1125 pub fn print_anon_const(&mut self, constant: &hir::AnonConst) {
1126 self.ann.nested(self, Nested::Body(constant.body))
1129 fn print_call_post(&mut self, args: &[hir::Expr<'_>]) {
1131 self.commasep_exprs(Inconsistent, args);
1135 fn print_expr_maybe_paren(&mut self, expr: &hir::Expr<'_>, prec: i8) {
1136 self.print_expr_cond_paren(expr, expr.precedence().order() < prec)
1139 /// Prints an expr using syntax that's acceptable in a condition position, such as the `cond` in
1140 /// `if cond { ... }`.
1141 pub fn print_expr_as_cond(&mut self, expr: &hir::Expr<'_>) {
1142 self.print_expr_cond_paren(expr, Self::cond_needs_par(expr))
1145 /// Prints `expr` or `(expr)` when `needs_par` holds.
1146 fn print_expr_cond_paren(&mut self, expr: &hir::Expr<'_>, needs_par: bool) {
1150 if let hir::ExprKind::DropTemps(ref actual_expr) = expr.kind {
1151 self.print_expr(actual_expr);
1153 self.print_expr(expr);
1160 /// Print a `let pat = expr` expression.
1161 fn print_let(&mut self, pat: &hir::Pat<'_>, expr: &hir::Expr<'_>) {
1162 self.s.word("let ");
1163 self.print_pat(pat);
1165 self.word_space("=");
1166 let npals = || parser::needs_par_as_let_scrutinee(expr.precedence().order());
1167 self.print_expr_cond_paren(expr, Self::cond_needs_par(expr) || npals())
1170 // Does `expr` need parentheses when printed in a condition position?
1172 // These cases need parens due to the parse error observed in #26461: `if return {}`
1173 // parses as the erroneous construct `if (return {})`, not `if (return) {}`.
1174 fn cond_needs_par(expr: &hir::Expr<'_>) -> bool {
1176 hir::ExprKind::Break(..) | hir::ExprKind::Closure(..) | hir::ExprKind::Ret(..) => true,
1177 _ => contains_exterior_struct_lit(expr),
1181 fn print_expr_vec(&mut self, exprs: &[hir::Expr<'_>]) {
1182 self.ibox(INDENT_UNIT);
1184 self.commasep_exprs(Inconsistent, exprs);
1189 fn print_expr_anon_const(&mut self, anon_const: &hir::AnonConst) {
1190 self.ibox(INDENT_UNIT);
1191 self.s.word_space("const");
1192 self.print_anon_const(anon_const);
1196 fn print_expr_repeat(&mut self, element: &hir::Expr<'_>, count: &hir::AnonConst) {
1197 self.ibox(INDENT_UNIT);
1199 self.print_expr(element);
1200 self.word_space(";");
1201 self.print_anon_const(count);
1206 fn print_expr_struct(
1208 qpath: &hir::QPath<'_>,
1209 fields: &[hir::ExprField<'_>],
1210 wth: &Option<&hir::Expr<'_>>,
1212 self.print_qpath(qpath, true);
1218 s.ibox(INDENT_UNIT);
1219 if !field.is_shorthand {
1220 s.print_ident(field.ident);
1223 s.print_expr(&field.expr);
1230 self.ibox(INDENT_UNIT);
1231 if !fields.is_empty() {
1236 self.print_expr(&expr);
1240 if !fields.is_empty() {
1248 fn print_expr_tup(&mut self, exprs: &[hir::Expr<'_>]) {
1250 self.commasep_exprs(Inconsistent, exprs);
1251 if exprs.len() == 1 {
1257 fn print_expr_call(&mut self, func: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
1258 let prec = match func.kind {
1259 hir::ExprKind::Field(..) => parser::PREC_FORCE_PAREN,
1260 _ => parser::PREC_POSTFIX,
1263 self.print_expr_maybe_paren(func, prec);
1264 self.print_call_post(args)
1267 fn print_expr_method_call(&mut self, segment: &hir::PathSegment<'_>, args: &[hir::Expr<'_>]) {
1268 let base_args = &args[1..];
1269 self.print_expr_maybe_paren(&args[0], parser::PREC_POSTFIX);
1271 self.print_ident(segment.ident);
1273 let generic_args = segment.args();
1274 if !generic_args.args.is_empty() || !generic_args.bindings.is_empty() {
1275 self.print_generic_args(generic_args, segment.infer_args, true);
1278 self.print_call_post(base_args)
1281 fn print_expr_binary(&mut self, op: hir::BinOp, lhs: &hir::Expr<'_>, rhs: &hir::Expr<'_>) {
1282 let assoc_op = bin_op_to_assoc_op(op.node);
1283 let prec = assoc_op.precedence() as i8;
1284 let fixity = assoc_op.fixity();
1286 let (left_prec, right_prec) = match fixity {
1287 Fixity::Left => (prec, prec + 1),
1288 Fixity::Right => (prec + 1, prec),
1289 Fixity::None => (prec + 1, prec + 1),
1292 let left_prec = match (&lhs.kind, op.node) {
1293 // These cases need parens: `x as i32 < y` has the parser thinking that `i32 < y` is
1294 // the beginning of a path type. It starts trying to parse `x as (i32 < y ...` instead
1295 // of `(x as i32) < ...`. We need to convince it _not_ to do that.
1296 (&hir::ExprKind::Cast { .. }, hir::BinOpKind::Lt | hir::BinOpKind::Shl) => {
1297 parser::PREC_FORCE_PAREN
1299 (&hir::ExprKind::Let { .. }, _) if !parser::needs_par_as_let_scrutinee(prec) => {
1300 parser::PREC_FORCE_PAREN
1305 self.print_expr_maybe_paren(lhs, left_prec);
1307 self.word_space(op.node.as_str());
1308 self.print_expr_maybe_paren(rhs, right_prec)
1311 fn print_expr_unary(&mut self, op: hir::UnOp, expr: &hir::Expr<'_>) {
1312 self.s.word(op.as_str());
1313 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1316 fn print_expr_addr_of(
1318 kind: hir::BorrowKind,
1319 mutability: hir::Mutability,
1320 expr: &hir::Expr<'_>,
1324 hir::BorrowKind::Ref => self.print_mutability(mutability, false),
1325 hir::BorrowKind::Raw => {
1326 self.word_nbsp("raw");
1327 self.print_mutability(mutability, true);
1330 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1333 fn print_literal(&mut self, lit: &hir::Lit) {
1334 self.maybe_print_comment(lit.span.lo());
1335 self.word(lit.node.to_lit_token().to_string())
1338 fn print_inline_asm(&mut self, asm: &hir::InlineAsm<'_>) {
1341 Operand(&'a hir::InlineAsmOperand<'a>),
1342 Options(ast::InlineAsmOptions),
1346 vec![AsmArg::Template(ast::InlineAsmTemplatePiece::to_string(&asm.template))];
1347 args.extend(asm.operands.iter().map(|(o, _)| AsmArg::Operand(o)));
1348 if !asm.options.is_empty() {
1349 args.push(AsmArg::Options(asm.options));
1353 self.commasep(Consistent, &args, |s, arg| match arg {
1354 AsmArg::Template(template) => s.print_string(&template, ast::StrStyle::Cooked),
1355 AsmArg::Operand(op) => match op {
1356 hir::InlineAsmOperand::In { reg, expr } => {
1359 s.word(format!("{}", reg));
1364 hir::InlineAsmOperand::Out { reg, late, expr } => {
1365 s.word(if *late { "lateout" } else { "out" });
1367 s.word(format!("{}", reg));
1371 Some(expr) => s.print_expr(expr),
1372 None => s.word("_"),
1375 hir::InlineAsmOperand::InOut { reg, late, expr } => {
1376 s.word(if *late { "inlateout" } else { "inout" });
1378 s.word(format!("{}", reg));
1383 hir::InlineAsmOperand::SplitInOut { reg, late, in_expr, out_expr } => {
1384 s.word(if *late { "inlateout" } else { "inout" });
1386 s.word(format!("{}", reg));
1389 s.print_expr(in_expr);
1393 Some(out_expr) => s.print_expr(out_expr),
1394 None => s.word("_"),
1397 hir::InlineAsmOperand::Const { anon_const } => {
1400 s.print_anon_const(anon_const);
1402 hir::InlineAsmOperand::Sym { expr } => {
1408 AsmArg::Options(opts) => {
1411 let mut options = vec![];
1412 if opts.contains(ast::InlineAsmOptions::PURE) {
1413 options.push("pure");
1415 if opts.contains(ast::InlineAsmOptions::NOMEM) {
1416 options.push("nomem");
1418 if opts.contains(ast::InlineAsmOptions::READONLY) {
1419 options.push("readonly");
1421 if opts.contains(ast::InlineAsmOptions::PRESERVES_FLAGS) {
1422 options.push("preserves_flags");
1424 if opts.contains(ast::InlineAsmOptions::NORETURN) {
1425 options.push("noreturn");
1427 if opts.contains(ast::InlineAsmOptions::NOSTACK) {
1428 options.push("nostack");
1430 if opts.contains(ast::InlineAsmOptions::ATT_SYNTAX) {
1431 options.push("att_syntax");
1433 if opts.contains(ast::InlineAsmOptions::RAW) {
1434 options.push("raw");
1436 if opts.contains(ast::InlineAsmOptions::MAY_UNWIND) {
1437 options.push("may_unwind");
1439 s.commasep(Inconsistent, &options, |s, &opt| {
1448 pub fn print_expr(&mut self, expr: &hir::Expr<'_>) {
1449 self.maybe_print_comment(expr.span.lo());
1450 self.print_outer_attributes(self.attrs(expr.hir_id));
1451 self.ibox(INDENT_UNIT);
1452 self.ann.pre(self, AnnNode::Expr(expr));
1454 hir::ExprKind::Box(ref expr) => {
1455 self.word_space("box");
1456 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX);
1458 hir::ExprKind::Array(ref exprs) => {
1459 self.print_expr_vec(exprs);
1461 hir::ExprKind::ConstBlock(ref anon_const) => {
1462 self.print_expr_anon_const(anon_const);
1464 hir::ExprKind::Repeat(ref element, ref count) => {
1465 self.print_expr_repeat(&element, count);
1467 hir::ExprKind::Struct(ref qpath, fields, ref wth) => {
1468 self.print_expr_struct(qpath, fields, wth);
1470 hir::ExprKind::Tup(ref exprs) => {
1471 self.print_expr_tup(exprs);
1473 hir::ExprKind::Call(ref func, ref args) => {
1474 self.print_expr_call(&func, args);
1476 hir::ExprKind::MethodCall(ref segment, _, ref args, _) => {
1477 self.print_expr_method_call(segment, args);
1479 hir::ExprKind::Binary(op, ref lhs, ref rhs) => {
1480 self.print_expr_binary(op, &lhs, &rhs);
1482 hir::ExprKind::Unary(op, ref expr) => {
1483 self.print_expr_unary(op, &expr);
1485 hir::ExprKind::AddrOf(k, m, ref expr) => {
1486 self.print_expr_addr_of(k, m, &expr);
1488 hir::ExprKind::Lit(ref lit) => {
1489 self.print_literal(&lit);
1491 hir::ExprKind::Cast(ref expr, ref ty) => {
1492 let prec = AssocOp::As.precedence() as i8;
1493 self.print_expr_maybe_paren(&expr, prec);
1495 self.word_space("as");
1496 self.print_type(&ty);
1498 hir::ExprKind::Type(ref expr, ref ty) => {
1499 let prec = AssocOp::Colon.precedence() as i8;
1500 self.print_expr_maybe_paren(&expr, prec);
1501 self.word_space(":");
1502 self.print_type(&ty);
1504 hir::ExprKind::DropTemps(ref init) => {
1506 self.cbox(INDENT_UNIT);
1510 // Print `let _t = $init;`:
1511 let temp = Ident::from_str("_t");
1512 self.print_local(Some(init), |this| this.print_ident(temp));
1516 self.space_if_not_bol();
1517 self.print_ident(temp);
1520 self.bclose_maybe_open(expr.span, true);
1522 hir::ExprKind::Let(ref pat, ref scrutinee, _) => {
1523 self.print_let(pat, scrutinee);
1525 hir::ExprKind::If(ref test, ref blk, ref elseopt) => {
1526 self.print_if(&test, &blk, elseopt.as_ref().map(|e| &**e));
1528 hir::ExprKind::Loop(ref blk, opt_label, _, _) => {
1529 if let Some(label) = opt_label {
1530 self.print_ident(label.ident);
1531 self.word_space(":");
1534 self.print_block(&blk);
1536 hir::ExprKind::Match(ref expr, arms, _) => {
1537 self.cbox(INDENT_UNIT);
1538 self.ibox(INDENT_UNIT);
1539 self.word_nbsp("match");
1540 self.print_expr_as_cond(&expr);
1544 self.print_arm(arm);
1546 self.bclose(expr.span);
1548 hir::ExprKind::Closure(capture_clause, ref decl, body, _fn_decl_span, _gen) => {
1549 self.print_capture_clause(capture_clause);
1551 self.print_closure_params(&decl, body);
1554 // This is a bare expression.
1555 self.ann.nested(self, Nested::Body(body));
1556 self.end(); // need to close a box
1558 // A box will be closed by `print_expr`, but we didn't want an overall
1559 // wrapper so we closed the corresponding opening. so create an
1560 // empty box to satisfy the close.
1563 hir::ExprKind::Block(ref blk, opt_label) => {
1564 if let Some(label) = opt_label {
1565 self.print_ident(label.ident);
1566 self.word_space(":");
1568 // containing cbox, will be closed by print-block at `}`
1569 self.cbox(INDENT_UNIT);
1570 // head-box, will be closed by print-block after `{`
1572 self.print_block(&blk);
1574 hir::ExprKind::Assign(ref lhs, ref rhs, _) => {
1575 let prec = AssocOp::Assign.precedence() as i8;
1576 self.print_expr_maybe_paren(&lhs, prec + 1);
1578 self.word_space("=");
1579 self.print_expr_maybe_paren(&rhs, prec);
1581 hir::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
1582 let prec = AssocOp::Assign.precedence() as i8;
1583 self.print_expr_maybe_paren(&lhs, prec + 1);
1585 self.s.word(op.node.as_str());
1586 self.word_space("=");
1587 self.print_expr_maybe_paren(&rhs, prec);
1589 hir::ExprKind::Field(ref expr, ident) => {
1590 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
1592 self.print_ident(ident);
1594 hir::ExprKind::Index(ref expr, ref index) => {
1595 self.print_expr_maybe_paren(&expr, parser::PREC_POSTFIX);
1597 self.print_expr(&index);
1600 hir::ExprKind::Path(ref qpath) => self.print_qpath(qpath, true),
1601 hir::ExprKind::Break(destination, ref opt_expr) => {
1602 self.s.word("break");
1604 if let Some(label) = destination.label {
1605 self.print_ident(label.ident);
1608 if let Some(ref expr) = *opt_expr {
1609 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
1613 hir::ExprKind::Continue(destination) => {
1614 self.s.word("continue");
1616 if let Some(label) = destination.label {
1617 self.print_ident(label.ident);
1621 hir::ExprKind::Ret(ref result) => {
1622 self.s.word("return");
1623 if let Some(ref expr) = *result {
1625 self.print_expr_maybe_paren(&expr, parser::PREC_JUMP);
1628 hir::ExprKind::InlineAsm(ref asm) => {
1630 self.print_inline_asm(asm);
1632 hir::ExprKind::LlvmInlineAsm(ref a) => {
1634 self.s.word("llvm_asm!");
1636 self.print_symbol(i.asm, i.asm_str_style);
1637 self.word_space(":");
1639 let mut out_idx = 0;
1640 self.commasep(Inconsistent, &i.outputs, |s, out| {
1641 let constraint = out.constraint.as_str();
1642 let mut ch = constraint.chars();
1644 Some('=') if out.is_rw => {
1645 s.print_string(&format!("+{}", ch.as_str()), ast::StrStyle::Cooked)
1647 _ => s.print_string(&constraint, ast::StrStyle::Cooked),
1650 s.print_expr(&a.outputs_exprs[out_idx]);
1655 self.word_space(":");
1658 self.commasep(Inconsistent, &i.inputs, |s, &co| {
1659 s.print_symbol(co, ast::StrStyle::Cooked);
1661 s.print_expr(&a.inputs_exprs[in_idx]);
1666 self.word_space(":");
1668 self.commasep(Inconsistent, &i.clobbers, |s, &co| {
1669 s.print_symbol(co, ast::StrStyle::Cooked);
1672 let mut options = vec![];
1674 options.push("volatile");
1677 options.push("alignstack");
1679 if i.dialect == ast::LlvmAsmDialect::Intel {
1680 options.push("intel");
1683 if !options.is_empty() {
1685 self.word_space(":");
1686 self.commasep(Inconsistent, &options, |s, &co| {
1687 s.print_string(co, ast::StrStyle::Cooked);
1693 hir::ExprKind::Yield(ref expr, _) => {
1694 self.word_space("yield");
1695 self.print_expr_maybe_paren(&expr, parser::PREC_JUMP);
1697 hir::ExprKind::Err => {
1699 self.s.word("/*ERROR*/");
1703 self.ann.post(self, AnnNode::Expr(expr));
1707 pub fn print_local_decl(&mut self, loc: &hir::Local<'_>) {
1708 self.print_pat(&loc.pat);
1709 if let Some(ref ty) = loc.ty {
1710 self.word_space(":");
1711 self.print_type(&ty);
1715 pub fn print_name(&mut self, name: Symbol) {
1716 self.print_ident(Ident::with_dummy_span(name))
1719 pub fn print_path(&mut self, path: &hir::Path<'_>, colons_before_params: bool) {
1720 self.maybe_print_comment(path.span.lo());
1722 for (i, segment) in path.segments.iter().enumerate() {
1726 if segment.ident.name != kw::PathRoot {
1727 self.print_ident(segment.ident);
1728 self.print_generic_args(segment.args(), segment.infer_args, colons_before_params);
1733 pub fn print_path_segment(&mut self, segment: &hir::PathSegment<'_>) {
1734 if segment.ident.name != kw::PathRoot {
1735 self.print_ident(segment.ident);
1736 self.print_generic_args(segment.args(), segment.infer_args, false);
1740 pub fn print_qpath(&mut self, qpath: &hir::QPath<'_>, colons_before_params: bool) {
1742 hir::QPath::Resolved(None, ref path) => self.print_path(path, colons_before_params),
1743 hir::QPath::Resolved(Some(ref qself), ref path) => {
1745 self.print_type(qself);
1747 self.word_space("as");
1749 for (i, segment) in path.segments[..path.segments.len() - 1].iter().enumerate() {
1753 if segment.ident.name != kw::PathRoot {
1754 self.print_ident(segment.ident);
1755 self.print_generic_args(
1758 colons_before_params,
1765 let item_segment = path.segments.last().unwrap();
1766 self.print_ident(item_segment.ident);
1767 self.print_generic_args(
1768 item_segment.args(),
1769 item_segment.infer_args,
1770 colons_before_params,
1773 hir::QPath::TypeRelative(ref qself, ref item_segment) => {
1774 // If we've got a compound-qualified-path, let's push an additional pair of angle
1775 // brackets, so that we pretty-print `<<A::B>::C>` as `<A::B>::C`, instead of just
1776 // `A::B::C` (since the latter could be ambiguous to the user)
1777 if let hir::TyKind::Path(hir::QPath::Resolved(None, _)) = &qself.kind {
1778 self.print_type(qself);
1781 self.print_type(qself);
1786 self.print_ident(item_segment.ident);
1787 self.print_generic_args(
1788 item_segment.args(),
1789 item_segment.infer_args,
1790 colons_before_params,
1793 hir::QPath::LangItem(lang_item, span) => {
1794 self.s.word("#[lang = \"");
1795 self.print_ident(Ident::new(lang_item.name(), span));
1801 fn print_generic_args(
1803 generic_args: &hir::GenericArgs<'_>,
1805 colons_before_params: bool,
1807 if generic_args.parenthesized {
1809 self.commasep(Inconsistent, generic_args.inputs(), |s, ty| s.print_type(&ty));
1812 self.space_if_not_bol();
1813 self.word_space("->");
1814 self.print_type(generic_args.bindings[0].ty());
1816 let start = if colons_before_params { "::<" } else { "<" };
1817 let empty = Cell::new(true);
1818 let start_or_comma = |this: &mut Self| {
1823 this.word_space(",")
1827 let mut nonelided_generic_args: bool = false;
1828 let elide_lifetimes = generic_args.args.iter().all(|arg| match arg {
1829 GenericArg::Lifetime(lt) => lt.is_elided(),
1831 nonelided_generic_args = true;
1836 if nonelided_generic_args {
1837 start_or_comma(self);
1841 |s, generic_arg| match generic_arg {
1842 GenericArg::Lifetime(lt) if !elide_lifetimes => s.print_lifetime(lt),
1843 GenericArg::Lifetime(_) => {}
1844 GenericArg::Type(ty) => s.print_type(ty),
1845 GenericArg::Const(ct) => s.print_anon_const(&ct.value),
1846 GenericArg::Infer(_inf) => s.word("_"),
1851 // FIXME(eddyb): this would leak into error messages (e.g.,
1852 // "non-exhaustive patterns: `Some::<..>(_)` not covered").
1853 if infer_args && false {
1854 start_or_comma(self);
1858 for binding in generic_args.bindings.iter() {
1859 start_or_comma(self);
1860 self.print_ident(binding.ident);
1861 self.print_generic_args(binding.gen_args, false, false);
1863 match generic_args.bindings[0].kind {
1864 hir::TypeBindingKind::Equality { ref ty } => {
1865 self.word_space("=");
1866 self.print_type(ty);
1868 hir::TypeBindingKind::Constraint { bounds } => {
1869 self.print_bounds(":", bounds);
1880 pub fn print_pat(&mut self, pat: &hir::Pat<'_>) {
1881 self.maybe_print_comment(pat.span.lo());
1882 self.ann.pre(self, AnnNode::Pat(pat));
1883 // Pat isn't normalized, but the beauty of it
1884 // is that it doesn't matter
1886 PatKind::Wild => self.s.word("_"),
1887 PatKind::Binding(binding_mode, _, ident, ref sub) => {
1888 match binding_mode {
1889 hir::BindingAnnotation::Ref => {
1890 self.word_nbsp("ref");
1891 self.print_mutability(hir::Mutability::Not, false);
1893 hir::BindingAnnotation::RefMut => {
1894 self.word_nbsp("ref");
1895 self.print_mutability(hir::Mutability::Mut, false);
1897 hir::BindingAnnotation::Unannotated => {}
1898 hir::BindingAnnotation::Mutable => {
1899 self.word_nbsp("mut");
1902 self.print_ident(ident);
1903 if let Some(ref p) = *sub {
1908 PatKind::TupleStruct(ref qpath, ref elts, ddpos) => {
1909 self.print_qpath(qpath, true);
1911 if let Some(ddpos) = ddpos {
1912 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p));
1914 self.word_space(",");
1917 if ddpos != elts.len() {
1919 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p));
1922 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p));
1926 PatKind::Path(ref qpath) => {
1927 self.print_qpath(qpath, true);
1929 PatKind::Struct(ref qpath, ref fields, etc) => {
1930 self.print_qpath(qpath, true);
1932 self.word_space("{");
1937 s.cbox(INDENT_UNIT);
1938 if !f.is_shorthand {
1939 s.print_ident(f.ident);
1942 s.print_pat(&f.pat);
1948 if !fields.is_empty() {
1949 self.word_space(",");
1956 PatKind::Or(ref pats) => {
1957 self.strsep("|", true, Inconsistent, &pats[..], |s, p| s.print_pat(&p));
1959 PatKind::Tuple(ref elts, ddpos) => {
1961 if let Some(ddpos) = ddpos {
1962 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p));
1964 self.word_space(",");
1967 if ddpos != elts.len() {
1969 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p));
1972 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p));
1973 if elts.len() == 1 {
1979 PatKind::Box(ref inner) => {
1980 let is_range_inner = matches!(inner.kind, PatKind::Range(..));
1981 self.s.word("box ");
1985 self.print_pat(&inner);
1990 PatKind::Ref(ref inner, mutbl) => {
1991 let is_range_inner = matches!(inner.kind, PatKind::Range(..));
1993 self.s.word(mutbl.prefix_str());
1997 self.print_pat(&inner);
2002 PatKind::Lit(ref e) => self.print_expr(&e),
2003 PatKind::Range(ref begin, ref end, ref end_kind) => {
2004 if let Some(expr) = begin {
2005 self.print_expr(expr);
2009 RangeEnd::Included => self.s.word("..."),
2010 RangeEnd::Excluded => self.s.word(".."),
2012 if let Some(expr) = end {
2013 self.print_expr(expr);
2016 PatKind::Slice(ref before, ref slice, ref after) => {
2018 self.commasep(Inconsistent, &before[..], |s, p| s.print_pat(&p));
2019 if let Some(ref p) = *slice {
2020 if !before.is_empty() {
2021 self.word_space(",");
2023 if let PatKind::Wild = p.kind {
2029 if !after.is_empty() {
2030 self.word_space(",");
2033 self.commasep(Inconsistent, &after[..], |s, p| s.print_pat(&p));
2037 self.ann.post(self, AnnNode::Pat(pat))
2040 pub fn print_param(&mut self, arg: &hir::Param<'_>) {
2041 self.print_outer_attributes(self.attrs(arg.hir_id));
2042 self.print_pat(&arg.pat);
2045 pub fn print_arm(&mut self, arm: &hir::Arm<'_>) {
2046 // I have no idea why this check is necessary, but here it
2048 if self.attrs(arm.hir_id).is_empty() {
2051 self.cbox(INDENT_UNIT);
2052 self.ann.pre(self, AnnNode::Arm(arm));
2054 self.print_outer_attributes(&self.attrs(arm.hir_id));
2055 self.print_pat(&arm.pat);
2057 if let Some(ref g) = arm.guard {
2059 hir::Guard::If(e) => {
2060 self.word_space("if");
2061 self.print_expr(&e);
2064 hir::Guard::IfLet(pat, e) => {
2065 self.word_nbsp("if");
2066 self.word_nbsp("let");
2067 self.print_pat(&pat);
2069 self.word_space("=");
2070 self.print_expr(&e);
2075 self.word_space("=>");
2077 match arm.body.kind {
2078 hir::ExprKind::Block(ref blk, opt_label) => {
2079 if let Some(label) = opt_label {
2080 self.print_ident(label.ident);
2081 self.word_space(":");
2083 // the block will close the pattern's ibox
2084 self.print_block_unclosed(&blk);
2086 // If it is a user-provided unsafe block, print a comma after it
2087 if let hir::BlockCheckMode::UnsafeBlock(hir::UnsafeSource::UserProvided) = blk.rules
2093 self.end(); // close the ibox for the pattern
2094 self.print_expr(&arm.body);
2098 self.ann.post(self, AnnNode::Arm(arm));
2099 self.end() // close enclosing cbox
2104 decl: &hir::FnDecl<'_>,
2105 header: hir::FnHeader,
2106 name: Option<Symbol>,
2107 generics: &hir::Generics<'_>,
2108 vis: &hir::Visibility<'_>,
2109 arg_names: &[Ident],
2110 body_id: Option<hir::BodyId>,
2112 self.print_fn_header_info(header, vis);
2114 if let Some(name) = name {
2116 self.print_name(name);
2118 self.print_generic_params(&generics.params);
2122 // Make sure we aren't supplied *both* `arg_names` and `body_id`.
2123 assert!(arg_names.is_empty() || body_id.is_none());
2124 self.commasep(Inconsistent, &decl.inputs, |s, ty| {
2125 s.ibox(INDENT_UNIT);
2126 if let Some(arg_name) = arg_names.get(i) {
2127 s.s.word(arg_name.to_string());
2130 } else if let Some(body_id) = body_id {
2131 s.ann.nested(s, Nested::BodyParamPat(body_id, i));
2139 if decl.c_variadic {
2140 self.s.word(", ...");
2144 self.print_fn_output(decl);
2145 self.print_where_clause(&generics.where_clause)
2148 fn print_closure_params(&mut self, decl: &hir::FnDecl<'_>, body_id: hir::BodyId) {
2151 self.commasep(Inconsistent, &decl.inputs, |s, ty| {
2152 s.ibox(INDENT_UNIT);
2154 s.ann.nested(s, Nested::BodyParamPat(body_id, i));
2157 if let hir::TyKind::Infer = ty.kind {
2168 if let hir::FnRetTy::DefaultReturn(..) = decl.output {
2172 self.space_if_not_bol();
2173 self.word_space("->");
2175 hir::FnRetTy::Return(ref ty) => {
2176 self.print_type(&ty);
2177 self.maybe_print_comment(ty.span.lo())
2179 hir::FnRetTy::DefaultReturn(..) => unreachable!(),
2183 pub fn print_capture_clause(&mut self, capture_clause: hir::CaptureBy) {
2184 match capture_clause {
2185 hir::CaptureBy::Value => self.word_space("move"),
2186 hir::CaptureBy::Ref => {}
2190 pub fn print_bounds<'b>(
2192 prefix: &'static str,
2193 bounds: impl IntoIterator<Item = &'b hir::GenericBound<'b>>,
2195 let mut first = true;
2196 for bound in bounds {
2198 self.s.word(prefix);
2200 if !(first && prefix.is_empty()) {
2206 self.word_space("+");
2210 GenericBound::Trait(tref, modifier) => {
2211 if modifier == &TraitBoundModifier::Maybe {
2214 self.print_poly_trait_ref(tref);
2216 GenericBound::LangItemTrait(lang_item, span, ..) => {
2217 self.s.word("#[lang = \"");
2218 self.print_ident(Ident::new(lang_item.name(), *span));
2221 GenericBound::Outlives(lt) => {
2222 self.print_lifetime(lt);
2228 pub fn print_generic_params(&mut self, generic_params: &[GenericParam<'_>]) {
2229 if !generic_params.is_empty() {
2232 self.commasep(Inconsistent, generic_params, |s, param| s.print_generic_param(param));
2238 pub fn print_generic_param(&mut self, param: &GenericParam<'_>) {
2239 if let GenericParamKind::Const { .. } = param.kind {
2240 self.word_space("const");
2243 self.print_ident(param.name.ident());
2246 GenericParamKind::Lifetime { .. } => {
2248 for bound in param.bounds {
2250 GenericBound::Outlives(ref lt) => {
2252 self.print_lifetime(lt);
2259 GenericParamKind::Type { ref default, .. } => {
2260 self.print_bounds(":", param.bounds);
2261 if let Some(default) = default {
2263 self.word_space("=");
2264 self.print_type(&default)
2267 GenericParamKind::Const { ref ty, ref default } => {
2268 self.word_space(":");
2269 self.print_type(ty);
2270 if let Some(ref default) = default {
2272 self.word_space("=");
2273 self.print_anon_const(&default)
2279 pub fn print_lifetime(&mut self, lifetime: &hir::Lifetime) {
2280 self.print_ident(lifetime.name.ident())
2283 pub fn print_where_clause(&mut self, where_clause: &hir::WhereClause<'_>) {
2284 if where_clause.predicates.is_empty() {
2289 self.word_space("where");
2291 for (i, predicate) in where_clause.predicates.iter().enumerate() {
2293 self.word_space(",");
2297 hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
2298 bound_generic_params,
2303 self.print_formal_generic_params(bound_generic_params);
2304 self.print_type(&bounded_ty);
2305 self.print_bounds(":", *bounds);
2307 hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
2312 self.print_lifetime(lifetime);
2315 for (i, bound) in bounds.iter().enumerate() {
2317 GenericBound::Outlives(lt) => {
2318 self.print_lifetime(lt);
2328 hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
2331 self.print_type(lhs_ty);
2333 self.word_space("=");
2334 self.print_type(rhs_ty);
2340 pub fn print_mutability(&mut self, mutbl: hir::Mutability, print_const: bool) {
2342 hir::Mutability::Mut => self.word_nbsp("mut"),
2343 hir::Mutability::Not => {
2345 self.word_nbsp("const")
2351 pub fn print_mt(&mut self, mt: &hir::MutTy<'_>, print_const: bool) {
2352 self.print_mutability(mt.mutbl, print_const);
2353 self.print_type(&mt.ty)
2356 pub fn print_fn_output(&mut self, decl: &hir::FnDecl<'_>) {
2357 if let hir::FnRetTy::DefaultReturn(..) = decl.output {
2361 self.space_if_not_bol();
2362 self.ibox(INDENT_UNIT);
2363 self.word_space("->");
2365 hir::FnRetTy::DefaultReturn(..) => unreachable!(),
2366 hir::FnRetTy::Return(ref ty) => self.print_type(&ty),
2370 if let hir::FnRetTy::Return(ref output) = decl.output {
2371 self.maybe_print_comment(output.span.lo())
2378 unsafety: hir::Unsafety,
2379 decl: &hir::FnDecl<'_>,
2380 name: Option<Symbol>,
2381 generic_params: &[hir::GenericParam<'_>],
2382 arg_names: &[Ident],
2384 self.ibox(INDENT_UNIT);
2385 if !generic_params.is_empty() {
2387 self.print_generic_params(generic_params);
2389 let generics = hir::Generics {
2391 where_clause: hir::WhereClause { predicates: &[], span: rustc_span::DUMMY_SP },
2392 span: rustc_span::DUMMY_SP,
2399 constness: hir::Constness::NotConst,
2400 asyncness: hir::IsAsync::NotAsync,
2404 &Spanned { span: rustc_span::DUMMY_SP, node: hir::VisibilityKind::Inherited },
2411 pub fn maybe_print_trailing_comment(
2413 span: rustc_span::Span,
2414 next_pos: Option<BytePos>,
2416 if let Some(cmnts) = self.comments() {
2417 if let Some(cmnt) = cmnts.trailing_comment(span, next_pos) {
2418 self.print_comment(&cmnt);
2423 pub fn print_remaining_comments(&mut self) {
2424 // If there aren't any remaining comments, then we need to manually
2425 // make sure there is a line break at the end.
2426 if self.next_comment().is_none() {
2429 while let Some(ref cmnt) = self.next_comment() {
2430 self.print_comment(cmnt)
2434 pub fn print_fn_header_info(&mut self, header: hir::FnHeader, vis: &hir::Visibility<'_>) {
2435 self.s.word(visibility_qualified(vis, ""));
2437 match header.constness {
2438 hir::Constness::NotConst => {}
2439 hir::Constness::Const => self.word_nbsp("const"),
2442 match header.asyncness {
2443 hir::IsAsync::NotAsync => {}
2444 hir::IsAsync::Async => self.word_nbsp("async"),
2447 self.print_unsafety(header.unsafety);
2449 if header.abi != Abi::Rust {
2450 self.word_nbsp("extern");
2451 self.word_nbsp(header.abi.to_string());
2457 pub fn print_unsafety(&mut self, s: hir::Unsafety) {
2459 hir::Unsafety::Normal => {}
2460 hir::Unsafety::Unsafe => self.word_nbsp("unsafe"),
2464 pub fn print_is_auto(&mut self, s: hir::IsAuto) {
2466 hir::IsAuto::Yes => self.word_nbsp("auto"),
2467 hir::IsAuto::No => {}
2472 /// Does this expression require a semicolon to be treated
2473 /// as a statement? The negation of this: 'can this expression
2474 /// be used as a statement without a semicolon' -- is used
2475 /// as an early-bail-out in the parser so that, for instance,
2476 /// if true {...} else {...}
2478 /// isn't parsed as (if true {...} else {...} | x) | 5
2480 // Duplicated from `parse::classify`, but adapted for the HIR.
2481 fn expr_requires_semi_to_be_stmt(e: &hir::Expr<'_>) -> bool {
2484 hir::ExprKind::If(..)
2485 | hir::ExprKind::Match(..)
2486 | hir::ExprKind::Block(..)
2487 | hir::ExprKind::Loop(..)
2491 /// This statement requires a semicolon after it.
2492 /// note that in one case (stmt_semi), we've already
2493 /// seen the semicolon, and thus don't need another.
2494 fn stmt_ends_with_semi(stmt: &hir::StmtKind<'_>) -> bool {
2496 hir::StmtKind::Local(_) => true,
2497 hir::StmtKind::Item(_) => false,
2498 hir::StmtKind::Expr(ref e) => expr_requires_semi_to_be_stmt(&e),
2499 hir::StmtKind::Semi(..) => false,
2503 fn bin_op_to_assoc_op(op: hir::BinOpKind) -> AssocOp {
2504 use crate::hir::BinOpKind::*;
2506 Add => AssocOp::Add,
2507 Sub => AssocOp::Subtract,
2508 Mul => AssocOp::Multiply,
2509 Div => AssocOp::Divide,
2510 Rem => AssocOp::Modulus,
2512 And => AssocOp::LAnd,
2515 BitXor => AssocOp::BitXor,
2516 BitAnd => AssocOp::BitAnd,
2517 BitOr => AssocOp::BitOr,
2518 Shl => AssocOp::ShiftLeft,
2519 Shr => AssocOp::ShiftRight,
2521 Eq => AssocOp::Equal,
2522 Lt => AssocOp::Less,
2523 Le => AssocOp::LessEqual,
2524 Ne => AssocOp::NotEqual,
2525 Ge => AssocOp::GreaterEqual,
2526 Gt => AssocOp::Greater,
2530 /// Expressions that syntactically contain an "exterior" struct literal, i.e., not surrounded by any
2531 /// parens or other delimiters, e.g., `X { y: 1 }`, `X { y: 1 }.method()`, `foo == X { y: 1 }` and
2532 /// `X { y: 1 } == foo` all do, but `(X { y: 1 }) == foo` does not.
2533 fn contains_exterior_struct_lit(value: &hir::Expr<'_>) -> bool {
2535 hir::ExprKind::Struct(..) => true,
2537 hir::ExprKind::Assign(ref lhs, ref rhs, _)
2538 | hir::ExprKind::AssignOp(_, ref lhs, ref rhs)
2539 | hir::ExprKind::Binary(_, ref lhs, ref rhs) => {
2540 // `X { y: 1 } + X { y: 2 }`
2541 contains_exterior_struct_lit(&lhs) || contains_exterior_struct_lit(&rhs)
2543 hir::ExprKind::Unary(_, ref x)
2544 | hir::ExprKind::Cast(ref x, _)
2545 | hir::ExprKind::Type(ref x, _)
2546 | hir::ExprKind::Field(ref x, _)
2547 | hir::ExprKind::Index(ref x, _) => {
2548 // `&X { y: 1 }, X { y: 1 }.y`
2549 contains_exterior_struct_lit(&x)
2552 hir::ExprKind::MethodCall(.., ref exprs, _) => {
2553 // `X { y: 1 }.bar(...)`
2554 contains_exterior_struct_lit(&exprs[0])