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<'_>) {}
50 impl PpAnn for NoAnn {}
51 pub const NO_ANN: &dyn PpAnn = &NoAnn;
53 impl PpAnn for hir::Crate<'_> {
54 fn nested(&self, state: &mut State<'_>, nested: Nested) {
56 Nested::Item(id) => state.print_item(self.item(id.id)),
57 Nested::TraitItem(id) => state.print_trait_item(self.trait_item(id)),
58 Nested::ImplItem(id) => state.print_impl_item(self.impl_item(id)),
59 Nested::Body(id) => state.print_expr(&self.body(id).value),
60 Nested::BodyParamPat(id, i) => state.print_pat(&self.body(id).params[i].pat),
65 /// Identical to the `PpAnn` implementation for `hir::Crate`,
66 /// except it avoids creating a dependency on the whole crate.
67 impl PpAnn for &dyn rustc_hir::intravisit::Map<'_> {
68 fn nested(&self, state: &mut State<'_>, nested: Nested) {
70 Nested::Item(id) => state.print_item(self.item(id.id)),
71 Nested::TraitItem(id) => state.print_trait_item(self.trait_item(id)),
72 Nested::ImplItem(id) => state.print_impl_item(self.impl_item(id)),
73 Nested::Body(id) => state.print_expr(&self.body(id).value),
74 Nested::BodyParamPat(id, i) => state.print_pat(&self.body(id).params[i].pat),
79 pub struct State<'a> {
81 comments: Option<Comments<'a>>,
82 ann: &'a (dyn PpAnn + 'a),
86 pub fn print_node(&mut self, node: Node<'_>) {
88 Node::Param(a) => self.print_param(&a),
89 Node::Item(a) => self.print_item(&a),
90 Node::ForeignItem(a) => self.print_foreign_item(&a),
91 Node::TraitItem(a) => self.print_trait_item(a),
92 Node::ImplItem(a) => self.print_impl_item(a),
93 Node::Variant(a) => self.print_variant(&a),
94 Node::AnonConst(a) => self.print_anon_const(&a),
95 Node::Expr(a) => self.print_expr(&a),
96 Node::Stmt(a) => self.print_stmt(&a),
97 Node::PathSegment(a) => self.print_path_segment(&a),
98 Node::Ty(a) => self.print_type(&a),
99 Node::TraitRef(a) => self.print_trait_ref(&a),
100 Node::Binding(a) | Node::Pat(a) => self.print_pat(&a),
101 Node::Arm(a) => self.print_arm(&a),
103 // Containing cbox, will be closed by print-block at `}`.
104 self.cbox(INDENT_UNIT);
105 // Head-ibox, will be closed by print-block after `{`.
109 Node::Lifetime(a) => self.print_lifetime(&a),
110 Node::Visibility(a) => self.print_visibility(&a),
111 Node::GenericParam(_) => panic!("cannot print Node::GenericParam"),
112 Node::Field(_) => panic!("cannot print StructField"),
113 // These cases do not carry enough information in the
114 // `hir_map` to reconstruct their full structure for pretty
116 Node::Ctor(..) => panic!("cannot print isolated Ctor"),
117 Node::Local(a) => self.print_local_decl(&a),
118 Node::MacroDef(_) => panic!("cannot print MacroDef"),
119 Node::Crate(..) => panic!("cannot print Crate"),
124 impl std::ops::Deref for State<'_> {
125 type Target = pp::Printer;
126 fn deref(&self) -> &Self::Target {
131 impl std::ops::DerefMut for State<'_> {
132 fn deref_mut(&mut self) -> &mut Self::Target {
137 impl<'a> PrintState<'a> for State<'a> {
138 fn comments(&mut self) -> &mut Option<Comments<'a>> {
142 fn print_ident(&mut self, ident: Ident) {
143 self.s.word(IdentPrinter::for_ast_ident(ident, ident.is_raw_guess()).to_string());
144 self.ann.post(self, AnnNode::Name(&ident.name))
147 fn print_generic_args(&mut self, _: &ast::GenericArgs, _colons_before_params: bool) {
148 panic!("AST generic args printed by HIR pretty-printer");
152 pub const INDENT_UNIT: usize = 4;
154 /// Requires you to pass an input filename and reader so that
155 /// it can scan the input text for comments to copy forward.
156 pub fn print_crate<'a>(
158 krate: &hir::Crate<'_>,
163 let mut s = State::new_from_input(sm, filename, input, ann);
165 // When printing the AST, we sometimes need to inject `#[no_std]` here.
166 // Since you can't compile the HIR, it's not necessary.
168 s.print_mod(&krate.item.module, &krate.item.attrs);
169 s.print_remaining_comments();
174 pub fn new_from_input(
180 State { s: pp::mk_printer(), comments: Some(Comments::new(sm, filename, input)), ann }
184 pub fn to_string<F>(ann: &dyn PpAnn, f: F) -> String
186 F: FnOnce(&mut State<'_>),
188 let mut printer = State { s: pp::mk_printer(), comments: None, ann };
193 pub fn visibility_qualified<S: Into<Cow<'static, str>>>(vis: &hir::Visibility<'_>, w: S) -> String {
194 to_string(NO_ANN, |s| {
195 s.print_visibility(vis);
200 pub fn generic_params_to_string(generic_params: &[GenericParam<'_>]) -> String {
201 to_string(NO_ANN, |s| s.print_generic_params(generic_params))
204 pub fn bounds_to_string<'b>(bounds: impl IntoIterator<Item = &'b hir::GenericBound<'b>>) -> String {
205 to_string(NO_ANN, |s| s.print_bounds("", bounds))
208 pub fn param_to_string(arg: &hir::Param<'_>) -> String {
209 to_string(NO_ANN, |s| s.print_param(arg))
212 pub fn ty_to_string(ty: &hir::Ty<'_>) -> String {
213 to_string(NO_ANN, |s| s.print_type(ty))
216 pub fn path_segment_to_string(segment: &hir::PathSegment<'_>) -> String {
217 to_string(NO_ANN, |s| s.print_path_segment(segment))
220 pub fn path_to_string(segment: &hir::Path<'_>) -> String {
221 to_string(NO_ANN, |s| s.print_path(segment, false))
225 decl: &hir::FnDecl<'_>,
226 header: hir::FnHeader,
227 name: Option<Symbol>,
228 generics: &hir::Generics<'_>,
229 vis: &hir::Visibility<'_>,
231 body_id: Option<hir::BodyId>,
233 to_string(NO_ANN, |s| s.print_fn(decl, header, name, generics, vis, arg_names, body_id))
236 pub fn enum_def_to_string(
237 enum_definition: &hir::EnumDef<'_>,
238 generics: &hir::Generics<'_>,
240 span: rustc_span::Span,
241 visibility: &hir::Visibility<'_>,
243 to_string(NO_ANN, |s| s.print_enum_def(enum_definition, generics, name, span, visibility))
247 pub fn cbox(&mut self, u: usize) {
251 pub fn nbsp(&mut self) {
255 pub fn word_nbsp<S: Into<Cow<'static, str>>>(&mut self, w: S) {
260 pub fn head<S: Into<Cow<'static, str>>>(&mut self, w: S) {
262 // outer-box is consistent
263 self.cbox(INDENT_UNIT);
264 // head-box is inconsistent
265 self.ibox(w.len() + 1);
266 // keyword that starts the head
272 pub fn bopen(&mut self) {
274 self.end(); // close the head-box
277 pub fn bclose_maybe_open(&mut self, span: rustc_span::Span, close_box: bool) {
278 self.maybe_print_comment(span.hi());
279 self.break_offset_if_not_bol(1, -(INDENT_UNIT as isize));
282 self.end(); // close the outer-box
286 pub fn bclose(&mut self, span: rustc_span::Span) {
287 self.bclose_maybe_open(span, true)
290 pub fn space_if_not_bol(&mut self) {
291 if !self.s.is_beginning_of_line() {
296 pub fn break_offset_if_not_bol(&mut self, n: usize, off: isize) {
297 if !self.s.is_beginning_of_line() {
298 self.s.break_offset(n, off)
300 if off != 0 && self.s.last_token().is_hardbreak_tok() {
301 // We do something pretty sketchy here: tuck the nonzero
302 // offset-adjustment we were going to deposit along with the
303 // break into the previous hardbreak.
304 self.s.replace_last_token(pp::Printer::hardbreak_tok_offset(off));
309 // Synthesizes a comment that was not textually present in the original source
311 pub fn synth_comment(&mut self, text: String) {
319 pub fn commasep_cmnt<T, F, G>(&mut self, b: Breaks, elts: &[T], mut op: F, mut get_span: G)
321 F: FnMut(&mut State<'_>, &T),
322 G: FnMut(&T) -> rustc_span::Span,
325 let len = elts.len();
328 self.maybe_print_comment(get_span(elt).hi());
333 self.maybe_print_trailing_comment(get_span(elt), Some(get_span(&elts[i]).hi()));
334 self.space_if_not_bol();
340 pub fn commasep_exprs(&mut self, b: Breaks, exprs: &[hir::Expr<'_>]) {
341 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(&e), |e| e.span)
344 pub fn print_mod(&mut self, _mod: &hir::Mod<'_>, attrs: &[ast::Attribute]) {
345 self.print_inner_attributes(attrs);
346 for &item_id in _mod.item_ids {
347 self.ann.nested(self, Nested::Item(item_id));
351 pub fn print_foreign_mod(&mut self, nmod: &hir::ForeignMod<'_>, attrs: &[ast::Attribute]) {
352 self.print_inner_attributes(attrs);
353 for item in nmod.items {
354 self.print_foreign_item(item);
358 pub fn print_opt_lifetime(&mut self, lifetime: &hir::Lifetime) {
359 if !lifetime.is_elided() {
360 self.print_lifetime(lifetime);
365 pub fn print_type(&mut self, ty: &hir::Ty<'_>) {
366 self.maybe_print_comment(ty.span.lo());
369 hir::TyKind::Slice(ref ty) => {
371 self.print_type(&ty);
374 hir::TyKind::Ptr(ref mt) => {
376 self.print_mt(mt, true);
378 hir::TyKind::Rptr(ref lifetime, ref mt) => {
380 self.print_opt_lifetime(lifetime);
381 self.print_mt(mt, false);
383 hir::TyKind::Never => {
386 hir::TyKind::Tup(ref elts) => {
388 self.commasep(Inconsistent, &elts[..], |s, ty| s.print_type(&ty));
394 hir::TyKind::BareFn(ref f) => {
404 hir::TyKind::OpaqueDef(..) => self.s.word("/*impl Trait*/"),
405 hir::TyKind::Path(ref qpath) => self.print_qpath(qpath, false),
406 hir::TyKind::TraitObject(bounds, ref lifetime) => {
407 let mut first = true;
408 for bound in bounds {
413 self.word_space("+");
415 self.print_poly_trait_ref(bound);
417 if !lifetime.is_elided() {
419 self.word_space("+");
420 self.print_lifetime(lifetime);
423 hir::TyKind::Array(ref ty, ref length) => {
425 self.print_type(&ty);
427 self.print_anon_const(length);
430 hir::TyKind::Typeof(ref e) => {
431 self.s.word("typeof(");
432 self.print_anon_const(e);
435 hir::TyKind::Infer => {
438 hir::TyKind::Err => {
440 self.s.word("/*ERROR*/");
447 pub fn print_foreign_item(&mut self, item: &hir::ForeignItem<'_>) {
448 self.hardbreak_if_not_bol();
449 self.maybe_print_comment(item.span.lo());
450 self.print_outer_attributes(&item.attrs);
452 hir::ForeignItemKind::Fn(ref decl, ref arg_names, ref generics) => {
457 unsafety: hir::Unsafety::Normal,
458 constness: hir::Constness::NotConst,
460 asyncness: hir::IsAsync::NotAsync,
462 Some(item.ident.name),
468 self.end(); // end head-ibox
470 self.end() // end the outer fn box
472 hir::ForeignItemKind::Static(ref t, m) => {
473 self.head(visibility_qualified(&item.vis, "static"));
474 if m == hir::Mutability::Mut {
475 self.word_space("mut");
477 self.print_ident(item.ident);
478 self.word_space(":");
481 self.end(); // end the head-ibox
482 self.end() // end the outer cbox
484 hir::ForeignItemKind::Type => {
485 self.head(visibility_qualified(&item.vis, "type"));
486 self.print_ident(item.ident);
488 self.end(); // end the head-ibox
489 self.end() // end the outer cbox
494 fn print_associated_const(
498 default: Option<hir::BodyId>,
499 vis: &hir::Visibility<'_>,
501 self.s.word(visibility_qualified(vis, ""));
502 self.word_space("const");
503 self.print_ident(ident);
504 self.word_space(":");
506 if let Some(expr) = default {
508 self.word_space("=");
509 self.ann.nested(self, Nested::Body(expr));
514 fn print_associated_type(
517 generics: &hir::Generics<'_>,
518 bounds: Option<hir::GenericBounds<'_>>,
519 ty: Option<&hir::Ty<'_>>,
521 self.word_space("type");
522 self.print_ident(ident);
523 self.print_generic_params(&generics.params);
524 if let Some(bounds) = bounds {
525 self.print_bounds(":", bounds);
527 self.print_where_clause(&generics.where_clause);
528 if let Some(ty) = ty {
530 self.word_space("=");
538 item: &hir::Item<'_>,
539 generics: &hir::Generics<'_>,
540 inner: impl Fn(&mut Self),
542 self.head(visibility_qualified(&item.vis, "type"));
543 self.print_ident(item.ident);
544 self.print_generic_params(&generics.params);
545 self.end(); // end the inner ibox
547 self.print_where_clause(&generics.where_clause);
551 self.end(); // end the outer ibox
554 /// Pretty-print an item
555 pub fn print_item(&mut self, item: &hir::Item<'_>) {
556 self.hardbreak_if_not_bol();
557 self.maybe_print_comment(item.span.lo());
558 self.print_outer_attributes(&item.attrs);
559 self.ann.pre(self, AnnNode::Item(item));
561 hir::ItemKind::ExternCrate(orig_name) => {
562 self.head(visibility_qualified(&item.vis, "extern crate"));
563 if let Some(orig_name) = orig_name {
564 self.print_name(orig_name);
569 self.print_ident(item.ident);
571 self.end(); // end inner head-block
572 self.end(); // end outer head-block
574 hir::ItemKind::Use(ref path, kind) => {
575 self.head(visibility_qualified(&item.vis, "use"));
576 self.print_path(path, false);
579 hir::UseKind::Single => {
580 if path.segments.last().unwrap().ident != item.ident {
582 self.word_space("as");
583 self.print_ident(item.ident);
587 hir::UseKind::Glob => self.s.word("::*;"),
588 hir::UseKind::ListStem => self.s.word("::{};"),
590 self.end(); // end inner head-block
591 self.end(); // end outer head-block
593 hir::ItemKind::Static(ref ty, m, expr) => {
594 self.head(visibility_qualified(&item.vis, "static"));
595 if m == hir::Mutability::Mut {
596 self.word_space("mut");
598 self.print_ident(item.ident);
599 self.word_space(":");
600 self.print_type(&ty);
602 self.end(); // end the head-ibox
604 self.word_space("=");
605 self.ann.nested(self, Nested::Body(expr));
607 self.end(); // end the outer cbox
609 hir::ItemKind::Const(ref ty, expr) => {
610 self.head(visibility_qualified(&item.vis, "const"));
611 self.print_ident(item.ident);
612 self.word_space(":");
613 self.print_type(&ty);
615 self.end(); // end the head-ibox
617 self.word_space("=");
618 self.ann.nested(self, Nested::Body(expr));
620 self.end(); // end the outer cbox
622 hir::ItemKind::Fn(ref sig, ref param_names, body) => {
627 Some(item.ident.name),
634 self.end(); // need to close a box
635 self.end(); // need to close a box
636 self.ann.nested(self, Nested::Body(body));
638 hir::ItemKind::Mod(ref _mod) => {
639 self.head(visibility_qualified(&item.vis, "mod"));
640 self.print_ident(item.ident);
643 self.print_mod(_mod, &item.attrs);
644 self.bclose(item.span);
646 hir::ItemKind::ForeignMod(ref nmod) => {
648 self.word_nbsp(nmod.abi.to_string());
650 self.print_foreign_mod(nmod, &item.attrs);
651 self.bclose(item.span);
653 hir::ItemKind::GlobalAsm(ref ga) => {
654 self.head(visibility_qualified(&item.vis, "global asm"));
655 self.s.word(ga.asm.to_string());
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 {
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(&item.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(&v.attrs);
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(&field.attrs);
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(&field.attrs);
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(&ti.attrs);
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(&ii.attrs);
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.as_deref(), |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::PushUnsafeBlock(..) => self.word_space("push_unsafe"),
1065 hir::BlockCheckMode::PopUnsafeBlock(..) => self.word_space("pop_unsafe"),
1066 hir::BlockCheckMode::DefaultBlock => (),
1068 self.maybe_print_comment(blk.span.lo());
1069 self.ann.pre(self, AnnNode::Block(blk));
1072 self.print_inner_attributes(attrs);
1074 for st in blk.stmts {
1075 self.print_stmt(st);
1077 if let Some(ref expr) = blk.expr {
1078 self.space_if_not_bol();
1079 self.print_expr(&expr);
1080 self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi()));
1082 self.bclose_maybe_open(blk.span, close_box);
1083 self.ann.post(self, AnnNode::Block(blk))
1086 pub fn print_anon_const(&mut self, constant: &hir::AnonConst) {
1087 self.ann.nested(self, Nested::Body(constant.body))
1090 fn print_call_post(&mut self, args: &[hir::Expr<'_>]) {
1092 self.commasep_exprs(Inconsistent, args);
1096 pub fn print_expr_maybe_paren(&mut self, expr: &hir::Expr<'_>, prec: i8) {
1097 let needs_par = expr.precedence().order() < prec;
1101 self.print_expr(expr);
1107 /// Print an expr using syntax that's acceptable in a condition position, such as the `cond` in
1108 /// `if cond { ... }`.
1109 pub fn print_expr_as_cond(&mut self, expr: &hir::Expr<'_>) {
1110 let needs_par = match expr.kind {
1111 // These cases need parens due to the parse error observed in #26461: `if return {}`
1112 // parses as the erroneous construct `if (return {})`, not `if (return) {}`.
1113 hir::ExprKind::Closure(..) | hir::ExprKind::Ret(..) | hir::ExprKind::Break(..) => true,
1115 _ => contains_exterior_struct_lit(expr),
1121 self.print_expr(expr);
1127 fn print_expr_vec(&mut self, exprs: &[hir::Expr<'_>]) {
1128 self.ibox(INDENT_UNIT);
1130 self.commasep_exprs(Inconsistent, exprs);
1135 fn print_expr_repeat(&mut self, element: &hir::Expr<'_>, count: &hir::AnonConst) {
1136 self.ibox(INDENT_UNIT);
1138 self.print_expr(element);
1139 self.word_space(";");
1140 self.print_anon_const(count);
1145 fn print_expr_struct(
1147 qpath: &hir::QPath<'_>,
1148 fields: &[hir::Field<'_>],
1149 wth: &Option<&hir::Expr<'_>>,
1151 self.print_qpath(qpath, true);
1157 s.ibox(INDENT_UNIT);
1158 if !field.is_shorthand {
1159 s.print_ident(field.ident);
1162 s.print_expr(&field.expr);
1169 self.ibox(INDENT_UNIT);
1170 if !fields.is_empty() {
1175 self.print_expr(&expr);
1179 if !fields.is_empty() {
1187 fn print_expr_tup(&mut self, exprs: &[hir::Expr<'_>]) {
1189 self.commasep_exprs(Inconsistent, exprs);
1190 if exprs.len() == 1 {
1196 fn print_expr_call(&mut self, func: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
1197 let prec = match func.kind {
1198 hir::ExprKind::Field(..) => parser::PREC_FORCE_PAREN,
1199 _ => parser::PREC_POSTFIX,
1202 self.print_expr_maybe_paren(func, prec);
1203 self.print_call_post(args)
1206 fn print_expr_method_call(&mut self, segment: &hir::PathSegment<'_>, args: &[hir::Expr<'_>]) {
1207 let base_args = &args[1..];
1208 self.print_expr_maybe_paren(&args[0], parser::PREC_POSTFIX);
1210 self.print_ident(segment.ident);
1212 let generic_args = segment.generic_args();
1213 if !generic_args.args.is_empty() || !generic_args.bindings.is_empty() {
1214 self.print_generic_args(generic_args, segment.infer_args, true);
1217 self.print_call_post(base_args)
1220 fn print_expr_binary(&mut self, op: hir::BinOp, lhs: &hir::Expr<'_>, rhs: &hir::Expr<'_>) {
1221 let assoc_op = bin_op_to_assoc_op(op.node);
1222 let prec = assoc_op.precedence() as i8;
1223 let fixity = assoc_op.fixity();
1225 let (left_prec, right_prec) = match fixity {
1226 Fixity::Left => (prec, prec + 1),
1227 Fixity::Right => (prec + 1, prec),
1228 Fixity::None => (prec + 1, prec + 1),
1231 let left_prec = match (&lhs.kind, op.node) {
1232 // These cases need parens: `x as i32 < y` has the parser thinking that `i32 < y` is
1233 // the beginning of a path type. It starts trying to parse `x as (i32 < y ...` instead
1234 // of `(x as i32) < ...`. We need to convince it _not_ to do that.
1235 (&hir::ExprKind::Cast { .. }, hir::BinOpKind::Lt | hir::BinOpKind::Shl) => {
1236 parser::PREC_FORCE_PAREN
1241 self.print_expr_maybe_paren(lhs, left_prec);
1243 self.word_space(op.node.as_str());
1244 self.print_expr_maybe_paren(rhs, right_prec)
1247 fn print_expr_unary(&mut self, op: hir::UnOp, expr: &hir::Expr<'_>) {
1248 self.s.word(op.as_str());
1249 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1252 fn print_expr_addr_of(
1254 kind: hir::BorrowKind,
1255 mutability: hir::Mutability,
1256 expr: &hir::Expr<'_>,
1260 hir::BorrowKind::Ref => self.print_mutability(mutability, false),
1261 hir::BorrowKind::Raw => {
1262 self.word_nbsp("raw");
1263 self.print_mutability(mutability, true);
1266 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1269 fn print_literal(&mut self, lit: &hir::Lit) {
1270 self.maybe_print_comment(lit.span.lo());
1271 self.word(lit.node.to_lit_token().to_string())
1274 pub fn print_expr(&mut self, expr: &hir::Expr<'_>) {
1275 self.maybe_print_comment(expr.span.lo());
1276 self.print_outer_attributes(&expr.attrs);
1277 self.ibox(INDENT_UNIT);
1278 self.ann.pre(self, AnnNode::Expr(expr));
1280 hir::ExprKind::Box(ref expr) => {
1281 self.word_space("box");
1282 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX);
1284 hir::ExprKind::Array(ref exprs) => {
1285 self.print_expr_vec(exprs);
1287 hir::ExprKind::Repeat(ref element, ref count) => {
1288 self.print_expr_repeat(&element, count);
1290 hir::ExprKind::Struct(ref qpath, fields, ref wth) => {
1291 self.print_expr_struct(qpath, fields, wth);
1293 hir::ExprKind::Tup(ref exprs) => {
1294 self.print_expr_tup(exprs);
1296 hir::ExprKind::Call(ref func, ref args) => {
1297 self.print_expr_call(&func, args);
1299 hir::ExprKind::MethodCall(ref segment, _, ref args, _) => {
1300 self.print_expr_method_call(segment, args);
1302 hir::ExprKind::Binary(op, ref lhs, ref rhs) => {
1303 self.print_expr_binary(op, &lhs, &rhs);
1305 hir::ExprKind::Unary(op, ref expr) => {
1306 self.print_expr_unary(op, &expr);
1308 hir::ExprKind::AddrOf(k, m, ref expr) => {
1309 self.print_expr_addr_of(k, m, &expr);
1311 hir::ExprKind::Lit(ref lit) => {
1312 self.print_literal(&lit);
1314 hir::ExprKind::Cast(ref expr, ref ty) => {
1315 let prec = AssocOp::As.precedence() as i8;
1316 self.print_expr_maybe_paren(&expr, prec);
1318 self.word_space("as");
1319 self.print_type(&ty);
1321 hir::ExprKind::Type(ref expr, ref ty) => {
1322 let prec = AssocOp::Colon.precedence() as i8;
1323 self.print_expr_maybe_paren(&expr, prec);
1324 self.word_space(":");
1325 self.print_type(&ty);
1327 hir::ExprKind::DropTemps(ref init) => {
1329 self.cbox(INDENT_UNIT);
1333 // Print `let _t = $init;`:
1334 let temp = Ident::from_str("_t");
1335 self.print_local(Some(init), |this| this.print_ident(temp));
1339 self.space_if_not_bol();
1340 self.print_ident(temp);
1343 self.bclose_maybe_open(expr.span, true);
1345 hir::ExprKind::Loop(ref blk, opt_label, _) => {
1346 if let Some(label) = opt_label {
1347 self.print_ident(label.ident);
1348 self.word_space(":");
1352 self.print_block(&blk);
1354 hir::ExprKind::Match(ref expr, arms, _) => {
1355 self.cbox(INDENT_UNIT);
1356 self.ibox(INDENT_UNIT);
1357 self.word_nbsp("match");
1358 self.print_expr_as_cond(&expr);
1362 self.print_arm(arm);
1364 self.bclose(expr.span);
1366 hir::ExprKind::Closure(capture_clause, ref decl, body, _fn_decl_span, _gen) => {
1367 self.print_capture_clause(capture_clause);
1369 self.print_closure_params(&decl, body);
1372 // This is a bare expression.
1373 self.ann.nested(self, Nested::Body(body));
1374 self.end(); // need to close a box
1376 // A box will be closed by `print_expr`, but we didn't want an overall
1377 // wrapper so we closed the corresponding opening. so create an
1378 // empty box to satisfy the close.
1381 hir::ExprKind::Block(ref blk, opt_label) => {
1382 if let Some(label) = opt_label {
1383 self.print_ident(label.ident);
1384 self.word_space(":");
1386 // containing cbox, will be closed by print-block at `}`
1387 self.cbox(INDENT_UNIT);
1388 // head-box, will be closed by print-block after `{`
1390 self.print_block(&blk);
1392 hir::ExprKind::Assign(ref lhs, ref rhs, _) => {
1393 let prec = AssocOp::Assign.precedence() as i8;
1394 self.print_expr_maybe_paren(&lhs, prec + 1);
1396 self.word_space("=");
1397 self.print_expr_maybe_paren(&rhs, prec);
1399 hir::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
1400 let prec = AssocOp::Assign.precedence() as i8;
1401 self.print_expr_maybe_paren(&lhs, prec + 1);
1403 self.s.word(op.node.as_str());
1404 self.word_space("=");
1405 self.print_expr_maybe_paren(&rhs, prec);
1407 hir::ExprKind::Field(ref expr, ident) => {
1408 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
1410 self.print_ident(ident);
1412 hir::ExprKind::Index(ref expr, ref index) => {
1413 self.print_expr_maybe_paren(&expr, parser::PREC_POSTFIX);
1415 self.print_expr(&index);
1418 hir::ExprKind::Path(ref qpath) => self.print_qpath(qpath, true),
1419 hir::ExprKind::Break(destination, ref opt_expr) => {
1420 self.s.word("break");
1422 if let Some(label) = destination.label {
1423 self.print_ident(label.ident);
1426 if let Some(ref expr) = *opt_expr {
1427 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
1431 hir::ExprKind::Continue(destination) => {
1432 self.s.word("continue");
1434 if let Some(label) = destination.label {
1435 self.print_ident(label.ident);
1439 hir::ExprKind::Ret(ref result) => {
1440 self.s.word("return");
1441 if let Some(ref expr) = *result {
1443 self.print_expr_maybe_paren(&expr, parser::PREC_JUMP);
1446 hir::ExprKind::InlineAsm(ref a) => {
1449 Operand(&'a hir::InlineAsmOperand<'a>),
1450 Options(ast::InlineAsmOptions),
1453 let mut args = vec![];
1454 args.push(AsmArg::Template(ast::InlineAsmTemplatePiece::to_string(&a.template)));
1455 args.extend(a.operands.iter().map(|o| AsmArg::Operand(o)));
1456 if !a.options.is_empty() {
1457 args.push(AsmArg::Options(a.options));
1462 self.commasep(Consistent, &args, |s, arg| match arg {
1463 AsmArg::Template(template) => s.print_string(&template, ast::StrStyle::Cooked),
1464 AsmArg::Operand(op) => match op {
1465 hir::InlineAsmOperand::In { reg, expr } => {
1468 s.word(format!("{}", reg));
1473 hir::InlineAsmOperand::Out { reg, late, expr } => {
1474 s.word(if *late { "lateout" } else { "out" });
1476 s.word(format!("{}", reg));
1480 Some(expr) => s.print_expr(expr),
1481 None => s.word("_"),
1484 hir::InlineAsmOperand::InOut { reg, late, expr } => {
1485 s.word(if *late { "inlateout" } else { "inout" });
1487 s.word(format!("{}", reg));
1492 hir::InlineAsmOperand::SplitInOut { reg, late, in_expr, out_expr } => {
1493 s.word(if *late { "inlateout" } else { "inout" });
1495 s.word(format!("{}", reg));
1498 s.print_expr(in_expr);
1502 Some(out_expr) => s.print_expr(out_expr),
1503 None => s.word("_"),
1506 hir::InlineAsmOperand::Const { expr } => {
1511 hir::InlineAsmOperand::Sym { expr } => {
1517 AsmArg::Options(opts) => {
1520 let mut options = vec![];
1521 if opts.contains(ast::InlineAsmOptions::PURE) {
1522 options.push("pure");
1524 if opts.contains(ast::InlineAsmOptions::NOMEM) {
1525 options.push("nomem");
1527 if opts.contains(ast::InlineAsmOptions::READONLY) {
1528 options.push("readonly");
1530 if opts.contains(ast::InlineAsmOptions::PRESERVES_FLAGS) {
1531 options.push("preserves_flags");
1533 if opts.contains(ast::InlineAsmOptions::NORETURN) {
1534 options.push("noreturn");
1536 if opts.contains(ast::InlineAsmOptions::NOSTACK) {
1537 options.push("nostack");
1539 if opts.contains(ast::InlineAsmOptions::ATT_SYNTAX) {
1540 options.push("att_syntax");
1542 s.commasep(Inconsistent, &options, |s, &opt| {
1550 hir::ExprKind::LlvmInlineAsm(ref a) => {
1552 self.s.word("llvm_asm!");
1554 self.print_symbol(i.asm, i.asm_str_style);
1555 self.word_space(":");
1557 let mut out_idx = 0;
1558 self.commasep(Inconsistent, &i.outputs, |s, out| {
1559 let constraint = out.constraint.as_str();
1560 let mut ch = constraint.chars();
1562 Some('=') if out.is_rw => {
1563 s.print_string(&format!("+{}", ch.as_str()), ast::StrStyle::Cooked)
1565 _ => s.print_string(&constraint, ast::StrStyle::Cooked),
1568 s.print_expr(&a.outputs_exprs[out_idx]);
1573 self.word_space(":");
1576 self.commasep(Inconsistent, &i.inputs, |s, &co| {
1577 s.print_symbol(co, ast::StrStyle::Cooked);
1579 s.print_expr(&a.inputs_exprs[in_idx]);
1584 self.word_space(":");
1586 self.commasep(Inconsistent, &i.clobbers, |s, &co| {
1587 s.print_symbol(co, ast::StrStyle::Cooked);
1590 let mut options = vec![];
1592 options.push("volatile");
1595 options.push("alignstack");
1597 if i.dialect == ast::LlvmAsmDialect::Intel {
1598 options.push("intel");
1601 if !options.is_empty() {
1603 self.word_space(":");
1604 self.commasep(Inconsistent, &options, |s, &co| {
1605 s.print_string(co, ast::StrStyle::Cooked);
1611 hir::ExprKind::Yield(ref expr, _) => {
1612 self.word_space("yield");
1613 self.print_expr_maybe_paren(&expr, parser::PREC_JUMP);
1615 hir::ExprKind::Err => {
1617 self.s.word("/*ERROR*/");
1621 self.ann.post(self, AnnNode::Expr(expr));
1625 pub fn print_local_decl(&mut self, loc: &hir::Local<'_>) {
1626 self.print_pat(&loc.pat);
1627 if let Some(ref ty) = loc.ty {
1628 self.word_space(":");
1629 self.print_type(&ty);
1633 pub fn print_usize(&mut self, i: usize) {
1634 self.s.word(i.to_string())
1637 pub fn print_name(&mut self, name: Symbol) {
1638 self.print_ident(Ident::with_dummy_span(name))
1641 pub fn print_for_decl(&mut self, loc: &hir::Local<'_>, coll: &hir::Expr<'_>) {
1642 self.print_local_decl(loc);
1644 self.word_space("in");
1645 self.print_expr(coll)
1648 pub fn print_path(&mut self, path: &hir::Path<'_>, colons_before_params: bool) {
1649 self.maybe_print_comment(path.span.lo());
1651 for (i, segment) in path.segments.iter().enumerate() {
1655 if segment.ident.name != kw::PathRoot {
1656 self.print_ident(segment.ident);
1657 self.print_generic_args(
1658 segment.generic_args(),
1660 colons_before_params,
1666 pub fn print_path_segment(&mut self, segment: &hir::PathSegment<'_>) {
1667 if segment.ident.name != kw::PathRoot {
1668 self.print_ident(segment.ident);
1669 self.print_generic_args(segment.generic_args(), segment.infer_args, false);
1673 pub fn print_qpath(&mut self, qpath: &hir::QPath<'_>, colons_before_params: bool) {
1675 hir::QPath::Resolved(None, ref path) => self.print_path(path, colons_before_params),
1676 hir::QPath::Resolved(Some(ref qself), ref path) => {
1678 self.print_type(qself);
1680 self.word_space("as");
1682 for (i, segment) in path.segments[..path.segments.len() - 1].iter().enumerate() {
1686 if segment.ident.name != kw::PathRoot {
1687 self.print_ident(segment.ident);
1688 self.print_generic_args(
1689 segment.generic_args(),
1691 colons_before_params,
1698 let item_segment = path.segments.last().unwrap();
1699 self.print_ident(item_segment.ident);
1700 self.print_generic_args(
1701 item_segment.generic_args(),
1702 item_segment.infer_args,
1703 colons_before_params,
1706 hir::QPath::TypeRelative(ref qself, ref item_segment) => {
1707 // If we've got a compound-qualified-path, let's push an additional pair of angle
1708 // brackets, so that we pretty-print `<<A::B>::C>` as `<A::B>::C`, instead of just
1709 // `A::B::C` (since the latter could be ambiguous to the user)
1710 if let hir::TyKind::Path(hir::QPath::Resolved(None, _)) = &qself.kind {
1711 self.print_type(qself);
1714 self.print_type(qself);
1719 self.print_ident(item_segment.ident);
1720 self.print_generic_args(
1721 item_segment.generic_args(),
1722 item_segment.infer_args,
1723 colons_before_params,
1726 hir::QPath::LangItem(lang_item, span) => {
1727 self.s.word("#[lang = \"");
1728 self.print_ident(Ident::new(lang_item.name(), span));
1734 fn print_generic_args(
1736 generic_args: &hir::GenericArgs<'_>,
1738 colons_before_params: bool,
1740 if generic_args.parenthesized {
1742 self.commasep(Inconsistent, generic_args.inputs(), |s, ty| s.print_type(&ty));
1745 self.space_if_not_bol();
1746 self.word_space("->");
1747 self.print_type(generic_args.bindings[0].ty());
1749 let start = if colons_before_params { "::<" } else { "<" };
1750 let empty = Cell::new(true);
1751 let start_or_comma = |this: &mut Self| {
1756 this.word_space(",")
1760 let mut nonelided_generic_args: bool = false;
1761 let elide_lifetimes = generic_args.args.iter().all(|arg| match arg {
1762 GenericArg::Lifetime(lt) => lt.is_elided(),
1764 nonelided_generic_args = true;
1769 if nonelided_generic_args {
1770 start_or_comma(self);
1774 |s, generic_arg| match generic_arg {
1775 GenericArg::Lifetime(lt) if !elide_lifetimes => s.print_lifetime(lt),
1776 GenericArg::Lifetime(_) => {}
1777 GenericArg::Type(ty) => s.print_type(ty),
1778 GenericArg::Const(ct) => s.print_anon_const(&ct.value),
1783 // FIXME(eddyb): this would leak into error messages (e.g.,
1784 // "non-exhaustive patterns: `Some::<..>(_)` not covered").
1785 if infer_args && false {
1786 start_or_comma(self);
1790 for binding in generic_args.bindings.iter() {
1791 start_or_comma(self);
1792 self.print_ident(binding.ident);
1794 match generic_args.bindings[0].kind {
1795 hir::TypeBindingKind::Equality { ref ty } => {
1796 self.word_space("=");
1797 self.print_type(ty);
1799 hir::TypeBindingKind::Constraint { bounds } => {
1800 self.print_bounds(":", bounds);
1811 pub fn print_pat(&mut self, pat: &hir::Pat<'_>) {
1812 self.maybe_print_comment(pat.span.lo());
1813 self.ann.pre(self, AnnNode::Pat(pat));
1814 // Pat isn't normalized, but the beauty of it
1815 // is that it doesn't matter
1817 PatKind::Wild => self.s.word("_"),
1818 PatKind::Binding(binding_mode, _, ident, ref sub) => {
1819 match binding_mode {
1820 hir::BindingAnnotation::Ref => {
1821 self.word_nbsp("ref");
1822 self.print_mutability(hir::Mutability::Not, false);
1824 hir::BindingAnnotation::RefMut => {
1825 self.word_nbsp("ref");
1826 self.print_mutability(hir::Mutability::Mut, false);
1828 hir::BindingAnnotation::Unannotated => {}
1829 hir::BindingAnnotation::Mutable => {
1830 self.word_nbsp("mut");
1833 self.print_ident(ident);
1834 if let Some(ref p) = *sub {
1839 PatKind::TupleStruct(ref qpath, ref elts, ddpos) => {
1840 self.print_qpath(qpath, true);
1842 if let Some(ddpos) = ddpos {
1843 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p));
1845 self.word_space(",");
1848 if ddpos != elts.len() {
1850 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p));
1853 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p));
1857 PatKind::Path(ref qpath) => {
1858 self.print_qpath(qpath, true);
1860 PatKind::Struct(ref qpath, ref fields, etc) => {
1861 self.print_qpath(qpath, true);
1863 self.word_space("{");
1868 s.cbox(INDENT_UNIT);
1869 if !f.is_shorthand {
1870 s.print_ident(f.ident);
1873 s.print_pat(&f.pat);
1879 if !fields.is_empty() {
1880 self.word_space(",");
1887 PatKind::Or(ref pats) => {
1888 self.strsep("|", true, Inconsistent, &pats[..], |s, p| s.print_pat(&p));
1890 PatKind::Tuple(ref elts, ddpos) => {
1892 if let Some(ddpos) = ddpos {
1893 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p));
1895 self.word_space(",");
1898 if ddpos != elts.len() {
1900 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p));
1903 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p));
1904 if elts.len() == 1 {
1910 PatKind::Box(ref inner) => {
1911 let is_range_inner = match inner.kind {
1912 PatKind::Range(..) => true,
1915 self.s.word("box ");
1919 self.print_pat(&inner);
1924 PatKind::Ref(ref inner, mutbl) => {
1925 let is_range_inner = match inner.kind {
1926 PatKind::Range(..) => true,
1930 self.s.word(mutbl.prefix_str());
1934 self.print_pat(&inner);
1939 PatKind::Lit(ref e) => self.print_expr(&e),
1940 PatKind::Range(ref begin, ref end, ref end_kind) => {
1941 if let Some(expr) = begin {
1942 self.print_expr(expr);
1946 RangeEnd::Included => self.s.word("..."),
1947 RangeEnd::Excluded => self.s.word(".."),
1949 if let Some(expr) = end {
1950 self.print_expr(expr);
1953 PatKind::Slice(ref before, ref slice, ref after) => {
1955 self.commasep(Inconsistent, &before[..], |s, p| s.print_pat(&p));
1956 if let Some(ref p) = *slice {
1957 if !before.is_empty() {
1958 self.word_space(",");
1960 if let PatKind::Wild = p.kind {
1966 if !after.is_empty() {
1967 self.word_space(",");
1970 self.commasep(Inconsistent, &after[..], |s, p| s.print_pat(&p));
1974 self.ann.post(self, AnnNode::Pat(pat))
1977 pub fn print_param(&mut self, arg: &hir::Param<'_>) {
1978 self.print_outer_attributes(&arg.attrs);
1979 self.print_pat(&arg.pat);
1982 pub fn print_arm(&mut self, arm: &hir::Arm<'_>) {
1983 // I have no idea why this check is necessary, but here it
1985 if arm.attrs.is_empty() {
1988 self.cbox(INDENT_UNIT);
1989 self.ann.pre(self, AnnNode::Arm(arm));
1991 self.print_outer_attributes(&arm.attrs);
1992 self.print_pat(&arm.pat);
1994 if let Some(ref g) = arm.guard {
1996 hir::Guard::If(e) => {
1997 self.word_space("if");
1998 self.print_expr(&e);
2003 self.word_space("=>");
2005 match arm.body.kind {
2006 hir::ExprKind::Block(ref blk, opt_label) => {
2007 if let Some(label) = opt_label {
2008 self.print_ident(label.ident);
2009 self.word_space(":");
2011 // the block will close the pattern's ibox
2012 self.print_block_unclosed(&blk);
2014 // If it is a user-provided unsafe block, print a comma after it
2015 if let hir::BlockCheckMode::UnsafeBlock(hir::UnsafeSource::UserProvided) = blk.rules
2021 self.end(); // close the ibox for the pattern
2022 self.print_expr(&arm.body);
2026 self.ann.post(self, AnnNode::Arm(arm));
2027 self.end() // close enclosing cbox
2032 decl: &hir::FnDecl<'_>,
2033 header: hir::FnHeader,
2034 name: Option<Symbol>,
2035 generics: &hir::Generics<'_>,
2036 vis: &hir::Visibility<'_>,
2037 arg_names: &[Ident],
2038 body_id: Option<hir::BodyId>,
2040 self.print_fn_header_info(header, vis);
2042 if let Some(name) = name {
2044 self.print_name(name);
2046 self.print_generic_params(&generics.params);
2050 // Make sure we aren't supplied *both* `arg_names` and `body_id`.
2051 assert!(arg_names.is_empty() || body_id.is_none());
2052 self.commasep(Inconsistent, &decl.inputs, |s, ty| {
2053 s.ibox(INDENT_UNIT);
2054 if let Some(arg_name) = arg_names.get(i) {
2055 s.s.word(arg_name.to_string());
2058 } else if let Some(body_id) = body_id {
2059 s.ann.nested(s, Nested::BodyParamPat(body_id, i));
2067 if decl.c_variadic {
2068 self.s.word(", ...");
2072 self.print_fn_output(decl);
2073 self.print_where_clause(&generics.where_clause)
2076 fn print_closure_params(&mut self, decl: &hir::FnDecl<'_>, body_id: hir::BodyId) {
2079 self.commasep(Inconsistent, &decl.inputs, |s, ty| {
2080 s.ibox(INDENT_UNIT);
2082 s.ann.nested(s, Nested::BodyParamPat(body_id, i));
2085 if let hir::TyKind::Infer = ty.kind {
2096 if let hir::FnRetTy::DefaultReturn(..) = decl.output {
2100 self.space_if_not_bol();
2101 self.word_space("->");
2103 hir::FnRetTy::Return(ref ty) => {
2104 self.print_type(&ty);
2105 self.maybe_print_comment(ty.span.lo())
2107 hir::FnRetTy::DefaultReturn(..) => unreachable!(),
2111 pub fn print_capture_clause(&mut self, capture_clause: hir::CaptureBy) {
2112 match capture_clause {
2113 hir::CaptureBy::Value => self.word_space("move"),
2114 hir::CaptureBy::Ref => {}
2118 pub fn print_bounds<'b>(
2120 prefix: &'static str,
2121 bounds: impl IntoIterator<Item = &'b hir::GenericBound<'b>>,
2123 let mut first = true;
2124 for bound in bounds {
2126 self.s.word(prefix);
2128 if !(first && prefix.is_empty()) {
2134 self.word_space("+");
2138 GenericBound::Trait(tref, modifier) => {
2139 if modifier == &TraitBoundModifier::Maybe {
2142 self.print_poly_trait_ref(tref);
2144 GenericBound::LangItemTrait(lang_item, span, ..) => {
2145 self.s.word("#[lang = \"");
2146 self.print_ident(Ident::new(lang_item.name(), *span));
2149 GenericBound::Outlives(lt) => {
2150 self.print_lifetime(lt);
2156 pub fn print_generic_params(&mut self, generic_params: &[GenericParam<'_>]) {
2157 if !generic_params.is_empty() {
2160 self.commasep(Inconsistent, generic_params, |s, param| s.print_generic_param(param));
2166 pub fn print_generic_param(&mut self, param: &GenericParam<'_>) {
2167 if let GenericParamKind::Const { .. } = param.kind {
2168 self.word_space("const");
2171 self.print_ident(param.name.ident());
2174 GenericParamKind::Lifetime { .. } => {
2176 for bound in param.bounds {
2178 GenericBound::Outlives(ref lt) => {
2180 self.print_lifetime(lt);
2187 GenericParamKind::Type { ref default, .. } => {
2188 self.print_bounds(":", param.bounds);
2189 if let Some(default) = default {
2191 self.word_space("=");
2192 self.print_type(&default)
2195 GenericParamKind::Const { ref ty } => {
2196 self.word_space(":");
2202 pub fn print_lifetime(&mut self, lifetime: &hir::Lifetime) {
2203 self.print_ident(lifetime.name.ident())
2206 pub fn print_where_clause(&mut self, where_clause: &hir::WhereClause<'_>) {
2207 if where_clause.predicates.is_empty() {
2212 self.word_space("where");
2214 for (i, predicate) in where_clause.predicates.iter().enumerate() {
2216 self.word_space(",");
2220 &hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
2221 ref bound_generic_params,
2226 self.print_formal_generic_params(bound_generic_params);
2227 self.print_type(&bounded_ty);
2228 self.print_bounds(":", bounds);
2230 &hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
2235 self.print_lifetime(lifetime);
2238 for (i, bound) in bounds.iter().enumerate() {
2240 GenericBound::Outlives(lt) => {
2241 self.print_lifetime(lt);
2251 &hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
2256 self.print_type(lhs_ty);
2258 self.word_space("=");
2259 self.print_type(rhs_ty);
2265 pub fn print_mutability(&mut self, mutbl: hir::Mutability, print_const: bool) {
2267 hir::Mutability::Mut => self.word_nbsp("mut"),
2268 hir::Mutability::Not => {
2270 self.word_nbsp("const")
2276 pub fn print_mt(&mut self, mt: &hir::MutTy<'_>, print_const: bool) {
2277 self.print_mutability(mt.mutbl, print_const);
2278 self.print_type(&mt.ty)
2281 pub fn print_fn_output(&mut self, decl: &hir::FnDecl<'_>) {
2282 if let hir::FnRetTy::DefaultReturn(..) = decl.output {
2286 self.space_if_not_bol();
2287 self.ibox(INDENT_UNIT);
2288 self.word_space("->");
2290 hir::FnRetTy::DefaultReturn(..) => unreachable!(),
2291 hir::FnRetTy::Return(ref ty) => self.print_type(&ty),
2295 if let hir::FnRetTy::Return(ref output) = decl.output {
2296 self.maybe_print_comment(output.span.lo())
2303 unsafety: hir::Unsafety,
2304 decl: &hir::FnDecl<'_>,
2305 name: Option<Symbol>,
2306 generic_params: &[hir::GenericParam<'_>],
2307 arg_names: &[Ident],
2309 self.ibox(INDENT_UNIT);
2310 if !generic_params.is_empty() {
2312 self.print_generic_params(generic_params);
2314 let generics = hir::Generics {
2316 where_clause: hir::WhereClause { predicates: &[], span: rustc_span::DUMMY_SP },
2317 span: rustc_span::DUMMY_SP,
2324 constness: hir::Constness::NotConst,
2325 asyncness: hir::IsAsync::NotAsync,
2329 &Spanned { span: rustc_span::DUMMY_SP, node: hir::VisibilityKind::Inherited },
2336 pub fn maybe_print_trailing_comment(
2338 span: rustc_span::Span,
2339 next_pos: Option<BytePos>,
2341 if let Some(cmnts) = self.comments() {
2342 if let Some(cmnt) = cmnts.trailing_comment(span, next_pos) {
2343 self.print_comment(&cmnt);
2348 pub fn print_remaining_comments(&mut self) {
2349 // If there aren't any remaining comments, then we need to manually
2350 // make sure there is a line break at the end.
2351 if self.next_comment().is_none() {
2354 while let Some(ref cmnt) = self.next_comment() {
2355 self.print_comment(cmnt)
2359 pub fn print_opt_abi_and_extern_if_nondefault(&mut self, opt_abi: Option<Abi>) {
2361 Some(Abi::Rust) => {}
2363 self.word_nbsp("extern");
2364 self.word_nbsp(abi.to_string())
2370 pub fn print_extern_opt_abi(&mut self, opt_abi: Option<Abi>) {
2371 if let Some(abi) = opt_abi {
2372 self.word_nbsp("extern");
2373 self.word_nbsp(abi.to_string())
2377 pub fn print_fn_header_info(&mut self, header: hir::FnHeader, vis: &hir::Visibility<'_>) {
2378 self.s.word(visibility_qualified(vis, ""));
2380 match header.constness {
2381 hir::Constness::NotConst => {}
2382 hir::Constness::Const => self.word_nbsp("const"),
2385 match header.asyncness {
2386 hir::IsAsync::NotAsync => {}
2387 hir::IsAsync::Async => self.word_nbsp("async"),
2390 self.print_unsafety(header.unsafety);
2392 if header.abi != Abi::Rust {
2393 self.word_nbsp("extern");
2394 self.word_nbsp(header.abi.to_string());
2400 pub fn print_unsafety(&mut self, s: hir::Unsafety) {
2402 hir::Unsafety::Normal => {}
2403 hir::Unsafety::Unsafe => self.word_nbsp("unsafe"),
2407 pub fn print_is_auto(&mut self, s: hir::IsAuto) {
2409 hir::IsAuto::Yes => self.word_nbsp("auto"),
2410 hir::IsAuto::No => {}
2415 /// Does this expression require a semicolon to be treated
2416 /// as a statement? The negation of this: 'can this expression
2417 /// be used as a statement without a semicolon' -- is used
2418 /// as an early-bail-out in the parser so that, for instance,
2419 /// if true {...} else {...}
2421 /// isn't parsed as (if true {...} else {...} | x) | 5
2423 // Duplicated from `parse::classify`, but adapted for the HIR.
2424 fn expr_requires_semi_to_be_stmt(e: &hir::Expr<'_>) -> bool {
2426 hir::ExprKind::Match(..) | hir::ExprKind::Block(..) | hir::ExprKind::Loop(..) => false,
2431 /// This statement requires a semicolon after it.
2432 /// note that in one case (stmt_semi), we've already
2433 /// seen the semicolon, and thus don't need another.
2434 fn stmt_ends_with_semi(stmt: &hir::StmtKind<'_>) -> bool {
2436 hir::StmtKind::Local(_) => true,
2437 hir::StmtKind::Item(_) => false,
2438 hir::StmtKind::Expr(ref e) => expr_requires_semi_to_be_stmt(&e),
2439 hir::StmtKind::Semi(..) => false,
2443 fn bin_op_to_assoc_op(op: hir::BinOpKind) -> AssocOp {
2444 use crate::hir::BinOpKind::*;
2446 Add => AssocOp::Add,
2447 Sub => AssocOp::Subtract,
2448 Mul => AssocOp::Multiply,
2449 Div => AssocOp::Divide,
2450 Rem => AssocOp::Modulus,
2452 And => AssocOp::LAnd,
2455 BitXor => AssocOp::BitXor,
2456 BitAnd => AssocOp::BitAnd,
2457 BitOr => AssocOp::BitOr,
2458 Shl => AssocOp::ShiftLeft,
2459 Shr => AssocOp::ShiftRight,
2461 Eq => AssocOp::Equal,
2462 Lt => AssocOp::Less,
2463 Le => AssocOp::LessEqual,
2464 Ne => AssocOp::NotEqual,
2465 Ge => AssocOp::GreaterEqual,
2466 Gt => AssocOp::Greater,
2470 /// Expressions that syntactically contain an "exterior" struct literal, i.e., not surrounded by any
2471 /// parens or other delimiters, e.g., `X { y: 1 }`, `X { y: 1 }.method()`, `foo == X { y: 1 }` and
2472 /// `X { y: 1 } == foo` all do, but `(X { y: 1 }) == foo` does not.
2473 fn contains_exterior_struct_lit(value: &hir::Expr<'_>) -> bool {
2475 hir::ExprKind::Struct(..) => true,
2477 hir::ExprKind::Assign(ref lhs, ref rhs, _)
2478 | hir::ExprKind::AssignOp(_, ref lhs, ref rhs)
2479 | hir::ExprKind::Binary(_, ref lhs, ref rhs) => {
2480 // `X { y: 1 } + X { y: 2 }`
2481 contains_exterior_struct_lit(&lhs) || contains_exterior_struct_lit(&rhs)
2483 hir::ExprKind::Unary(_, ref x)
2484 | hir::ExprKind::Cast(ref x, _)
2485 | hir::ExprKind::Type(ref x, _)
2486 | hir::ExprKind::Field(ref x, _)
2487 | hir::ExprKind::Index(ref x, _) => {
2488 // `&X { y: 1 }, X { y: 1 }.y`
2489 contains_exterior_struct_lit(&x)
2492 hir::ExprKind::MethodCall(.., ref exprs, _) => {
2493 // `X { y: 1 }.bar(...)`
2494 contains_exterior_struct_lit(&exprs[0])