1 #![feature(or_patterns)]
2 #![recursion_limit = "256"]
5 use rustc_ast::util::parser::{self, AssocOp, Fixity};
6 use rustc_ast_pretty::pp::Breaks::{Consistent, Inconsistent};
7 use rustc_ast_pretty::pp::{self, Breaks};
8 use rustc_ast_pretty::pprust::{Comments, PrintState};
10 use rustc_hir::{GenericArg, GenericParam, GenericParamKind, Node};
11 use rustc_hir::{GenericBound, PatKind, RangeEnd, TraitBoundModifier};
12 use rustc_span::source_map::{SourceMap, Spanned};
13 use rustc_span::symbol::{kw, Ident, IdentPrinter, Symbol};
14 use rustc_span::{self, BytePos, FileName};
15 use rustc_target::spec::abi::Abi;
21 pub fn id_to_string(map: &dyn rustc_hir::intravisit::Map<'_>, hir_id: hir::HirId) -> String {
22 to_string(&map, |s| s.print_node(map.find(hir_id).unwrap()))
25 pub enum AnnNode<'a> {
27 Block(&'a hir::Block<'a>),
28 Item(&'a hir::Item<'a>),
30 Expr(&'a hir::Expr<'a>),
31 Pat(&'a hir::Pat<'a>),
32 Arm(&'a hir::Arm<'a>),
37 TraitItem(hir::TraitItemId),
38 ImplItem(hir::ImplItemId),
40 BodyParamPat(hir::BodyId, usize),
44 fn nested(&self, _state: &mut State<'_>, _nested: Nested) {}
45 fn pre(&self, _state: &mut State<'_>, _node: AnnNode<'_>) {}
46 fn post(&self, _state: &mut State<'_>, _node: AnnNode<'_>) {}
47 fn try_fetch_item(&self, _: hir::HirId) -> Option<&hir::Item<'_>> {
53 impl PpAnn for NoAnn {}
54 pub const NO_ANN: &dyn PpAnn = &NoAnn;
56 impl PpAnn for hir::Crate<'_> {
57 fn try_fetch_item(&self, item: hir::HirId) -> Option<&hir::Item<'_>> {
60 fn nested(&self, state: &mut State<'_>, nested: Nested) {
62 Nested::Item(id) => state.print_item(self.item(id.id)),
63 Nested::TraitItem(id) => state.print_trait_item(self.trait_item(id)),
64 Nested::ImplItem(id) => state.print_impl_item(self.impl_item(id)),
65 Nested::Body(id) => state.print_expr(&self.body(id).value),
66 Nested::BodyParamPat(id, i) => state.print_pat(&self.body(id).params[i].pat),
71 /// Identical to the `PpAnn` implementation for `hir::Crate`,
72 /// except it avoids creating a dependency on the whole crate.
73 impl PpAnn for &dyn rustc_hir::intravisit::Map<'_> {
74 fn nested(&self, state: &mut State<'_>, nested: Nested) {
76 Nested::Item(id) => state.print_item(self.item(id.id)),
77 Nested::TraitItem(id) => state.print_trait_item(self.trait_item(id)),
78 Nested::ImplItem(id) => state.print_impl_item(self.impl_item(id)),
79 Nested::Body(id) => state.print_expr(&self.body(id).value),
80 Nested::BodyParamPat(id, i) => state.print_pat(&self.body(id).params[i].pat),
85 pub struct State<'a> {
87 comments: Option<Comments<'a>>,
88 ann: &'a (dyn PpAnn + 'a),
92 pub fn print_node(&mut self, node: Node<'_>) {
94 Node::Param(a) => self.print_param(&a),
95 Node::Item(a) => self.print_item(&a),
96 Node::ForeignItem(a) => self.print_foreign_item(&a),
97 Node::TraitItem(a) => self.print_trait_item(a),
98 Node::ImplItem(a) => self.print_impl_item(a),
99 Node::Variant(a) => self.print_variant(&a),
100 Node::AnonConst(a) => self.print_anon_const(&a),
101 Node::Expr(a) => self.print_expr(&a),
102 Node::Stmt(a) => self.print_stmt(&a),
103 Node::PathSegment(a) => self.print_path_segment(&a),
104 Node::Ty(a) => self.print_type(&a),
105 Node::TraitRef(a) => self.print_trait_ref(&a),
106 Node::Binding(a) | Node::Pat(a) => self.print_pat(&a),
107 Node::Arm(a) => self.print_arm(&a),
109 // Containing cbox, will be closed by print-block at `}`.
110 self.cbox(INDENT_UNIT);
111 // Head-ibox, will be closed by print-block after `{`.
115 Node::Lifetime(a) => self.print_lifetime(&a),
116 Node::Visibility(a) => self.print_visibility(&a),
117 Node::GenericParam(_) => panic!("cannot print Node::GenericParam"),
118 Node::Field(_) => panic!("cannot print StructField"),
119 // These cases do not carry enough information in the
120 // `hir_map` to reconstruct their full structure for pretty
122 Node::Ctor(..) => panic!("cannot print isolated Ctor"),
123 Node::Local(a) => self.print_local_decl(&a),
124 Node::MacroDef(_) => panic!("cannot print MacroDef"),
125 Node::Crate(..) => panic!("cannot print Crate"),
130 impl std::ops::Deref for State<'_> {
131 type Target = pp::Printer;
132 fn deref(&self) -> &Self::Target {
137 impl std::ops::DerefMut for State<'_> {
138 fn deref_mut(&mut self) -> &mut Self::Target {
143 impl<'a> PrintState<'a> for State<'a> {
144 fn insert_extra_parens(&self) -> bool {
147 fn comments(&mut self) -> &mut Option<Comments<'a>> {
151 fn print_ident(&mut self, ident: Ident) {
152 self.s.word(IdentPrinter::for_ast_ident(ident, ident.is_raw_guess()).to_string());
153 self.ann.post(self, AnnNode::Name(&ident.name))
156 fn print_generic_args(&mut self, _: &ast::GenericArgs, _colons_before_params: bool) {
157 panic!("AST generic args printed by HIR pretty-printer");
161 pub const INDENT_UNIT: usize = 4;
163 /// Requires you to pass an input filename and reader so that
164 /// it can scan the input text for comments to copy forward.
165 pub fn print_crate<'a>(
167 krate: &hir::Crate<'_>,
172 let mut s = State::new_from_input(sm, filename, input, ann);
174 // When printing the AST, we sometimes need to inject `#[no_std]` here.
175 // Since you can't compile the HIR, it's not necessary.
177 s.print_mod(&krate.item.module, &krate.item.attrs);
178 s.print_remaining_comments();
183 pub fn new_from_input(
189 State { s: pp::mk_printer(), comments: Some(Comments::new(sm, filename, input)), ann }
193 pub fn to_string<F>(ann: &dyn PpAnn, f: F) -> String
195 F: FnOnce(&mut State<'_>),
197 let mut printer = State { s: pp::mk_printer(), comments: None, ann };
202 pub fn visibility_qualified<S: Into<Cow<'static, str>>>(vis: &hir::Visibility<'_>, w: S) -> String {
203 to_string(NO_ANN, |s| {
204 s.print_visibility(vis);
209 pub fn generic_params_to_string(generic_params: &[GenericParam<'_>]) -> String {
210 to_string(NO_ANN, |s| s.print_generic_params(generic_params))
213 pub fn bounds_to_string<'b>(bounds: impl IntoIterator<Item = &'b hir::GenericBound<'b>>) -> String {
214 to_string(NO_ANN, |s| s.print_bounds("", bounds))
217 pub fn param_to_string(arg: &hir::Param<'_>) -> String {
218 to_string(NO_ANN, |s| s.print_param(arg))
221 pub fn ty_to_string(ty: &hir::Ty<'_>) -> String {
222 to_string(NO_ANN, |s| s.print_type(ty))
225 pub fn path_segment_to_string(segment: &hir::PathSegment<'_>) -> String {
226 to_string(NO_ANN, |s| s.print_path_segment(segment))
229 pub fn path_to_string(segment: &hir::Path<'_>) -> String {
230 to_string(NO_ANN, |s| s.print_path(segment, false))
234 decl: &hir::FnDecl<'_>,
235 header: hir::FnHeader,
236 name: Option<Symbol>,
237 generics: &hir::Generics<'_>,
238 vis: &hir::Visibility<'_>,
240 body_id: Option<hir::BodyId>,
242 to_string(NO_ANN, |s| s.print_fn(decl, header, name, generics, vis, arg_names, body_id))
245 pub fn enum_def_to_string(
246 enum_definition: &hir::EnumDef<'_>,
247 generics: &hir::Generics<'_>,
249 span: rustc_span::Span,
250 visibility: &hir::Visibility<'_>,
252 to_string(NO_ANN, |s| s.print_enum_def(enum_definition, generics, name, span, visibility))
256 pub fn cbox(&mut self, u: usize) {
260 pub fn nbsp(&mut self) {
264 pub fn word_nbsp<S: Into<Cow<'static, str>>>(&mut self, w: S) {
269 pub fn head<S: Into<Cow<'static, str>>>(&mut self, w: S) {
271 // outer-box is consistent
272 self.cbox(INDENT_UNIT);
273 // head-box is inconsistent
274 self.ibox(w.len() + 1);
275 // keyword that starts the head
281 pub fn bopen(&mut self) {
283 self.end(); // close the head-box
286 pub fn bclose_maybe_open(&mut self, span: rustc_span::Span, close_box: bool) {
287 self.maybe_print_comment(span.hi());
288 self.break_offset_if_not_bol(1, -(INDENT_UNIT as isize));
291 self.end(); // close the outer-box
295 pub fn bclose(&mut self, span: rustc_span::Span) {
296 self.bclose_maybe_open(span, true)
299 pub fn space_if_not_bol(&mut self) {
300 if !self.s.is_beginning_of_line() {
305 pub fn break_offset_if_not_bol(&mut self, n: usize, off: isize) {
306 if !self.s.is_beginning_of_line() {
307 self.s.break_offset(n, off)
309 if off != 0 && self.s.last_token().is_hardbreak_tok() {
310 // We do something pretty sketchy here: tuck the nonzero
311 // offset-adjustment we were going to deposit along with the
312 // break into the previous hardbreak.
313 self.s.replace_last_token(pp::Printer::hardbreak_tok_offset(off));
318 // Synthesizes a comment that was not textually present in the original source
320 pub fn synth_comment(&mut self, text: String) {
328 pub fn commasep_cmnt<T, F, G>(&mut self, b: Breaks, elts: &[T], mut op: F, mut get_span: G)
330 F: FnMut(&mut State<'_>, &T),
331 G: FnMut(&T) -> rustc_span::Span,
334 let len = elts.len();
337 self.maybe_print_comment(get_span(elt).hi());
342 self.maybe_print_trailing_comment(get_span(elt), Some(get_span(&elts[i]).hi()));
343 self.space_if_not_bol();
349 pub fn commasep_exprs(&mut self, b: Breaks, exprs: &[hir::Expr<'_>]) {
350 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(&e), |e| e.span)
353 pub fn print_mod(&mut self, _mod: &hir::Mod<'_>, attrs: &[ast::Attribute]) {
354 self.print_inner_attributes(attrs);
355 for &item_id in _mod.item_ids {
356 self.ann.nested(self, Nested::Item(item_id));
360 pub fn print_foreign_mod(&mut self, nmod: &hir::ForeignMod<'_>, attrs: &[ast::Attribute]) {
361 self.print_inner_attributes(attrs);
362 for item in nmod.items {
363 self.print_foreign_item(item);
367 pub fn print_opt_lifetime(&mut self, lifetime: &hir::Lifetime) {
368 if !lifetime.is_elided() {
369 self.print_lifetime(lifetime);
374 pub fn print_type(&mut self, ty: &hir::Ty<'_>) {
375 self.maybe_print_comment(ty.span.lo());
378 hir::TyKind::Slice(ref ty) => {
380 self.print_type(&ty);
383 hir::TyKind::Ptr(ref mt) => {
385 self.print_mt(mt, true);
387 hir::TyKind::Rptr(ref lifetime, ref mt) => {
389 self.print_opt_lifetime(lifetime);
390 self.print_mt(mt, false);
392 hir::TyKind::Never => {
395 hir::TyKind::Tup(ref elts) => {
397 self.commasep(Inconsistent, &elts[..], |s, ty| s.print_type(&ty));
403 hir::TyKind::BareFn(ref f) => {
413 hir::TyKind::OpaqueDef(..) => self.s.word("/*impl Trait*/"),
414 hir::TyKind::Path(ref qpath) => self.print_qpath(qpath, false),
415 hir::TyKind::TraitObject(bounds, ref lifetime) => {
416 let mut first = true;
417 for bound in bounds {
422 self.word_space("+");
424 self.print_poly_trait_ref(bound);
426 if !lifetime.is_elided() {
428 self.word_space("+");
429 self.print_lifetime(lifetime);
432 hir::TyKind::Array(ref ty, ref length) => {
434 self.print_type(&ty);
436 self.print_anon_const(length);
439 hir::TyKind::Typeof(ref e) => {
440 self.s.word("typeof(");
441 self.print_anon_const(e);
444 hir::TyKind::Infer => {
447 hir::TyKind::Err => {
449 self.s.word("/*ERROR*/");
456 pub fn print_foreign_item(&mut self, item: &hir::ForeignItem<'_>) {
457 self.hardbreak_if_not_bol();
458 self.maybe_print_comment(item.span.lo());
459 self.print_outer_attributes(&item.attrs);
461 hir::ForeignItemKind::Fn(ref decl, ref arg_names, ref generics) => {
466 unsafety: hir::Unsafety::Normal,
467 constness: hir::Constness::NotConst,
469 asyncness: hir::IsAsync::NotAsync,
471 Some(item.ident.name),
477 self.end(); // end head-ibox
479 self.end() // end the outer fn box
481 hir::ForeignItemKind::Static(ref t, m) => {
482 self.head(visibility_qualified(&item.vis, "static"));
483 if m == hir::Mutability::Mut {
484 self.word_space("mut");
486 self.print_ident(item.ident);
487 self.word_space(":");
490 self.end(); // end the head-ibox
491 self.end() // end the outer cbox
493 hir::ForeignItemKind::Type => {
494 self.head(visibility_qualified(&item.vis, "type"));
495 self.print_ident(item.ident);
497 self.end(); // end the head-ibox
498 self.end() // end the outer cbox
503 fn print_associated_const(
507 default: Option<hir::BodyId>,
508 vis: &hir::Visibility<'_>,
510 self.s.word(visibility_qualified(vis, ""));
511 self.word_space("const");
512 self.print_ident(ident);
513 self.word_space(":");
515 if let Some(expr) = default {
517 self.word_space("=");
518 self.ann.nested(self, Nested::Body(expr));
523 fn print_associated_type(
526 generics: &hir::Generics<'_>,
527 bounds: Option<hir::GenericBounds<'_>>,
528 ty: Option<&hir::Ty<'_>>,
530 self.word_space("type");
531 self.print_ident(ident);
532 self.print_generic_params(&generics.params);
533 if let Some(bounds) = bounds {
534 self.print_bounds(":", bounds);
536 self.print_where_clause(&generics.where_clause);
537 if let Some(ty) = ty {
539 self.word_space("=");
547 item: &hir::Item<'_>,
548 generics: &hir::Generics<'_>,
549 inner: impl Fn(&mut Self),
551 self.head(visibility_qualified(&item.vis, "type"));
552 self.print_ident(item.ident);
553 self.print_generic_params(&generics.params);
554 self.end(); // end the inner ibox
556 self.print_where_clause(&generics.where_clause);
560 self.end(); // end the outer ibox
563 /// Pretty-print an item
564 pub fn print_item(&mut self, item: &hir::Item<'_>) {
565 self.hardbreak_if_not_bol();
566 self.maybe_print_comment(item.span.lo());
567 self.print_outer_attributes(&item.attrs);
568 self.ann.pre(self, AnnNode::Item(item));
570 hir::ItemKind::ExternCrate(orig_name) => {
571 self.head(visibility_qualified(&item.vis, "extern crate"));
572 if let Some(orig_name) = orig_name {
573 self.print_name(orig_name);
578 self.print_ident(item.ident);
580 self.end(); // end inner head-block
581 self.end(); // end outer head-block
583 hir::ItemKind::Use(ref path, kind) => {
584 self.head(visibility_qualified(&item.vis, "use"));
585 self.print_path(path, false);
588 hir::UseKind::Single => {
589 if path.segments.last().unwrap().ident != item.ident {
591 self.word_space("as");
592 self.print_ident(item.ident);
596 hir::UseKind::Glob => self.s.word("::*;"),
597 hir::UseKind::ListStem => self.s.word("::{};"),
599 self.end(); // end inner head-block
600 self.end(); // end outer head-block
602 hir::ItemKind::Static(ref ty, m, expr) => {
603 self.head(visibility_qualified(&item.vis, "static"));
604 if m == hir::Mutability::Mut {
605 self.word_space("mut");
607 self.print_ident(item.ident);
608 self.word_space(":");
609 self.print_type(&ty);
611 self.end(); // end the head-ibox
613 self.word_space("=");
614 self.ann.nested(self, Nested::Body(expr));
616 self.end(); // end the outer cbox
618 hir::ItemKind::Const(ref ty, expr) => {
619 self.head(visibility_qualified(&item.vis, "const"));
620 self.print_ident(item.ident);
621 self.word_space(":");
622 self.print_type(&ty);
624 self.end(); // end the head-ibox
626 self.word_space("=");
627 self.ann.nested(self, Nested::Body(expr));
629 self.end(); // end the outer cbox
631 hir::ItemKind::Fn(ref sig, ref param_names, body) => {
636 Some(item.ident.name),
643 self.end(); // need to close a box
644 self.end(); // need to close a box
645 self.ann.nested(self, Nested::Body(body));
647 hir::ItemKind::Mod(ref _mod) => {
648 self.head(visibility_qualified(&item.vis, "mod"));
649 self.print_ident(item.ident);
652 self.print_mod(_mod, &item.attrs);
653 self.bclose(item.span);
655 hir::ItemKind::ForeignMod(ref nmod) => {
657 self.word_nbsp(nmod.abi.to_string());
659 self.print_foreign_mod(nmod, &item.attrs);
660 self.bclose(item.span);
662 hir::ItemKind::GlobalAsm(ref ga) => {
663 self.head(visibility_qualified(&item.vis, "global asm"));
664 self.s.word(ga.asm.to_string());
667 hir::ItemKind::TyAlias(ref ty, ref generics) => {
668 self.print_item_type(item, &generics, |state| {
669 state.word_space("=");
670 state.print_type(&ty);
673 hir::ItemKind::OpaqueTy(ref opaque_ty) => {
674 self.print_item_type(item, &opaque_ty.generics, |state| {
675 let mut real_bounds = Vec::with_capacity(opaque_ty.bounds.len());
676 for b in opaque_ty.bounds.iter() {
677 if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
679 state.word_space("for ?");
680 state.print_trait_ref(&ptr.trait_ref);
685 state.print_bounds("= impl", real_bounds);
688 hir::ItemKind::Enum(ref enum_definition, ref params) => {
689 self.print_enum_def(enum_definition, params, item.ident.name, item.span, &item.vis);
691 hir::ItemKind::Struct(ref struct_def, ref generics) => {
692 self.head(visibility_qualified(&item.vis, "struct"));
693 self.print_struct(struct_def, generics, item.ident.name, item.span, true);
695 hir::ItemKind::Union(ref struct_def, ref generics) => {
696 self.head(visibility_qualified(&item.vis, "union"));
697 self.print_struct(struct_def, generics, item.ident.name, item.span, true);
699 hir::ItemKind::Impl {
711 self.print_visibility(&item.vis);
712 self.print_defaultness(defaultness);
713 self.print_unsafety(unsafety);
714 self.word_nbsp("impl");
716 if !generics.params.is_empty() {
717 self.print_generic_params(&generics.params);
721 if constness == hir::Constness::Const {
722 self.word_nbsp("const");
725 if let hir::ImplPolarity::Negative(_) = polarity {
729 if let Some(ref t) = of_trait {
730 self.print_trait_ref(t);
732 self.word_space("for");
735 self.print_type(&self_ty);
736 self.print_where_clause(&generics.where_clause);
740 self.print_inner_attributes(&item.attrs);
741 for impl_item in items {
742 self.ann.nested(self, Nested::ImplItem(impl_item.id));
744 self.bclose(item.span);
746 hir::ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, trait_items) => {
748 self.print_visibility(&item.vis);
749 self.print_is_auto(is_auto);
750 self.print_unsafety(unsafety);
751 self.word_nbsp("trait");
752 self.print_ident(item.ident);
753 self.print_generic_params(&generics.params);
754 let mut real_bounds = Vec::with_capacity(bounds.len());
755 for b in bounds.iter() {
756 if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
758 self.word_space("for ?");
759 self.print_trait_ref(&ptr.trait_ref);
764 self.print_bounds(":", real_bounds);
765 self.print_where_clause(&generics.where_clause);
768 for trait_item in trait_items {
769 self.ann.nested(self, Nested::TraitItem(trait_item.id));
771 self.bclose(item.span);
773 hir::ItemKind::TraitAlias(ref generics, ref bounds) => {
775 self.print_visibility(&item.vis);
776 self.word_nbsp("trait");
777 self.print_ident(item.ident);
778 self.print_generic_params(&generics.params);
779 let mut real_bounds = Vec::with_capacity(bounds.len());
780 // FIXME(durka) this seems to be some quite outdated syntax
781 for b in bounds.iter() {
782 if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
784 self.word_space("for ?");
785 self.print_trait_ref(&ptr.trait_ref);
791 self.print_bounds("=", real_bounds);
792 self.print_where_clause(&generics.where_clause);
796 self.ann.post(self, AnnNode::Item(item))
799 pub fn print_trait_ref(&mut self, t: &hir::TraitRef<'_>) {
800 self.print_path(&t.path, false)
803 fn print_formal_generic_params(&mut self, generic_params: &[hir::GenericParam<'_>]) {
804 if !generic_params.is_empty() {
806 self.print_generic_params(generic_params);
811 fn print_poly_trait_ref(&mut self, t: &hir::PolyTraitRef<'_>) {
812 self.print_formal_generic_params(&t.bound_generic_params);
813 self.print_trait_ref(&t.trait_ref)
816 pub fn print_enum_def(
818 enum_definition: &hir::EnumDef<'_>,
819 generics: &hir::Generics<'_>,
821 span: rustc_span::Span,
822 visibility: &hir::Visibility<'_>,
824 self.head(visibility_qualified(visibility, "enum"));
825 self.print_name(name);
826 self.print_generic_params(&generics.params);
827 self.print_where_clause(&generics.where_clause);
829 self.print_variants(&enum_definition.variants, span)
832 pub fn print_variants(&mut self, variants: &[hir::Variant<'_>], span: rustc_span::Span) {
835 self.space_if_not_bol();
836 self.maybe_print_comment(v.span.lo());
837 self.print_outer_attributes(&v.attrs);
838 self.ibox(INDENT_UNIT);
839 self.print_variant(v);
842 self.maybe_print_trailing_comment(v.span, None);
847 pub fn print_visibility(&mut self, vis: &hir::Visibility<'_>) {
849 hir::VisibilityKind::Public => self.word_nbsp("pub"),
850 hir::VisibilityKind::Crate(ast::CrateSugar::JustCrate) => self.word_nbsp("crate"),
851 hir::VisibilityKind::Crate(ast::CrateSugar::PubCrate) => self.word_nbsp("pub(crate)"),
852 hir::VisibilityKind::Restricted { ref path, .. } => {
854 if path.segments.len() == 1 && path.segments[0].ident.name == kw::Super {
855 // Special case: `super` can print like `pub(super)`.
856 self.s.word("super");
858 // Everything else requires `in` at present.
859 self.word_nbsp("in");
860 self.print_path(path, false);
864 hir::VisibilityKind::Inherited => (),
868 pub fn print_defaultness(&mut self, defaultness: hir::Defaultness) {
870 hir::Defaultness::Default { .. } => self.word_nbsp("default"),
871 hir::Defaultness::Final => (),
877 struct_def: &hir::VariantData<'_>,
878 generics: &hir::Generics<'_>,
880 span: rustc_span::Span,
881 print_finalizer: bool,
883 self.print_name(name);
884 self.print_generic_params(&generics.params);
886 hir::VariantData::Tuple(..) | hir::VariantData::Unit(..) => {
887 if let hir::VariantData::Tuple(..) = struct_def {
889 self.commasep(Inconsistent, struct_def.fields(), |s, field| {
890 s.maybe_print_comment(field.span.lo());
891 s.print_outer_attributes(&field.attrs);
892 s.print_visibility(&field.vis);
893 s.print_type(&field.ty)
897 self.print_where_clause(&generics.where_clause);
902 self.end() // close the outer-box
904 hir::VariantData::Struct(..) => {
905 self.print_where_clause(&generics.where_clause);
908 self.hardbreak_if_not_bol();
910 for field in struct_def.fields() {
911 self.hardbreak_if_not_bol();
912 self.maybe_print_comment(field.span.lo());
913 self.print_outer_attributes(&field.attrs);
914 self.print_visibility(&field.vis);
915 self.print_ident(field.ident);
917 self.print_type(&field.ty);
926 pub fn print_variant(&mut self, v: &hir::Variant<'_>) {
928 let generics = hir::Generics::empty();
929 self.print_struct(&v.data, &generics, v.ident.name, v.span, false);
930 if let Some(ref d) = v.disr_expr {
932 self.word_space("=");
933 self.print_anon_const(d);
936 pub fn print_method_sig(
940 generics: &hir::Generics<'_>,
941 vis: &hir::Visibility<'_>,
943 body_id: Option<hir::BodyId>,
945 self.print_fn(&m.decl, m.header, Some(ident.name), generics, vis, arg_names, body_id)
948 pub fn print_trait_item(&mut self, ti: &hir::TraitItem<'_>) {
949 self.ann.pre(self, AnnNode::SubItem(ti.hir_id));
950 self.hardbreak_if_not_bol();
951 self.maybe_print_comment(ti.span.lo());
952 self.print_outer_attributes(&ti.attrs);
954 hir::TraitItemKind::Const(ref ty, default) => {
956 Spanned { span: rustc_span::DUMMY_SP, node: hir::VisibilityKind::Inherited };
957 self.print_associated_const(ti.ident, &ty, default, &vis);
959 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Required(ref arg_names)) => {
961 Spanned { span: rustc_span::DUMMY_SP, node: hir::VisibilityKind::Inherited };
962 self.print_method_sig(ti.ident, sig, &ti.generics, &vis, arg_names, None);
965 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Provided(body)) => {
967 Spanned { span: rustc_span::DUMMY_SP, node: hir::VisibilityKind::Inherited };
969 self.print_method_sig(ti.ident, sig, &ti.generics, &vis, &[], Some(body));
971 self.end(); // need to close a box
972 self.end(); // need to close a box
973 self.ann.nested(self, Nested::Body(body));
975 hir::TraitItemKind::Type(ref bounds, ref default) => {
976 self.print_associated_type(
980 default.as_ref().map(|ty| &**ty),
984 self.ann.post(self, AnnNode::SubItem(ti.hir_id))
987 pub fn print_impl_item(&mut self, ii: &hir::ImplItem<'_>) {
988 self.ann.pre(self, AnnNode::SubItem(ii.hir_id));
989 self.hardbreak_if_not_bol();
990 self.maybe_print_comment(ii.span.lo());
991 self.print_outer_attributes(&ii.attrs);
992 self.print_defaultness(ii.defaultness);
995 hir::ImplItemKind::Const(ref ty, expr) => {
996 self.print_associated_const(ii.ident, &ty, Some(expr), &ii.vis);
998 hir::ImplItemKind::Fn(ref sig, body) => {
1000 self.print_method_sig(ii.ident, sig, &ii.generics, &ii.vis, &[], Some(body));
1002 self.end(); // need to close a box
1003 self.end(); // need to close a box
1004 self.ann.nested(self, Nested::Body(body));
1006 hir::ImplItemKind::TyAlias(ref ty) => {
1007 self.print_associated_type(ii.ident, &ii.generics, None, Some(ty));
1010 self.ann.post(self, AnnNode::SubItem(ii.hir_id))
1013 pub fn print_local(&mut self, init: Option<&hir::Expr<'_>>, decl: impl Fn(&mut Self)) {
1014 self.space_if_not_bol();
1015 self.ibox(INDENT_UNIT);
1016 self.word_nbsp("let");
1018 self.ibox(INDENT_UNIT);
1022 if let Some(ref init) = init {
1024 self.word_space("=");
1025 self.print_expr(&init);
1030 pub fn print_stmt(&mut self, st: &hir::Stmt<'_>) {
1031 self.maybe_print_comment(st.span.lo());
1033 hir::StmtKind::Local(ref loc) => {
1034 self.print_local(loc.init.as_deref(), |this| this.print_local_decl(&loc));
1036 hir::StmtKind::Item(item) => self.ann.nested(self, Nested::Item(item)),
1037 hir::StmtKind::Expr(ref expr) => {
1038 self.space_if_not_bol();
1039 self.print_expr(&expr);
1041 hir::StmtKind::Semi(ref expr) => {
1042 self.space_if_not_bol();
1043 self.print_expr(&expr);
1047 if stmt_ends_with_semi(&st.kind) {
1050 self.maybe_print_trailing_comment(st.span, None)
1053 pub fn print_block(&mut self, blk: &hir::Block<'_>) {
1054 self.print_block_with_attrs(blk, &[])
1057 pub fn print_block_unclosed(&mut self, blk: &hir::Block<'_>) {
1058 self.print_block_maybe_unclosed(blk, &[], false)
1061 pub fn print_block_with_attrs(&mut self, blk: &hir::Block<'_>, attrs: &[ast::Attribute]) {
1062 self.print_block_maybe_unclosed(blk, attrs, true)
1065 pub fn print_block_maybe_unclosed(
1067 blk: &hir::Block<'_>,
1068 attrs: &[ast::Attribute],
1072 hir::BlockCheckMode::UnsafeBlock(..) => self.word_space("unsafe"),
1073 hir::BlockCheckMode::PushUnsafeBlock(..) => self.word_space("push_unsafe"),
1074 hir::BlockCheckMode::PopUnsafeBlock(..) => self.word_space("pop_unsafe"),
1075 hir::BlockCheckMode::DefaultBlock => (),
1077 self.maybe_print_comment(blk.span.lo());
1078 self.ann.pre(self, AnnNode::Block(blk));
1081 self.print_inner_attributes(attrs);
1083 for st in blk.stmts {
1084 self.print_stmt(st);
1086 if let Some(ref expr) = blk.expr {
1087 self.space_if_not_bol();
1088 self.print_expr(&expr);
1089 self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi()));
1091 self.bclose_maybe_open(blk.span, close_box);
1092 self.ann.post(self, AnnNode::Block(blk))
1095 pub fn print_anon_const(&mut self, constant: &hir::AnonConst) {
1096 self.ann.nested(self, Nested::Body(constant.body))
1099 fn print_call_post(&mut self, args: &[hir::Expr<'_>]) {
1101 self.commasep_exprs(Inconsistent, args);
1105 pub fn print_expr_maybe_paren(&mut self, expr: &hir::Expr<'_>, prec: i8) {
1106 let needs_par = expr.precedence().order() < prec;
1110 self.print_expr(expr);
1116 /// Print an expr using syntax that's acceptable in a condition position, such as the `cond` in
1117 /// `if cond { ... }`.
1118 pub fn print_expr_as_cond(&mut self, expr: &hir::Expr<'_>) {
1119 let needs_par = match expr.kind {
1120 // These cases need parens due to the parse error observed in #26461: `if return {}`
1121 // parses as the erroneous construct `if (return {})`, not `if (return) {}`.
1122 hir::ExprKind::Closure(..) | hir::ExprKind::Ret(..) | hir::ExprKind::Break(..) => true,
1124 _ => contains_exterior_struct_lit(expr),
1130 self.print_expr(expr);
1136 fn print_expr_vec(&mut self, exprs: &[hir::Expr<'_>]) {
1137 self.ibox(INDENT_UNIT);
1139 self.commasep_exprs(Inconsistent, exprs);
1144 fn print_expr_repeat(&mut self, element: &hir::Expr<'_>, count: &hir::AnonConst) {
1145 self.ibox(INDENT_UNIT);
1147 self.print_expr(element);
1148 self.word_space(";");
1149 self.print_anon_const(count);
1154 fn print_expr_struct(
1156 qpath: &hir::QPath<'_>,
1157 fields: &[hir::Field<'_>],
1158 wth: &Option<&hir::Expr<'_>>,
1160 self.print_qpath(qpath, true);
1166 s.ibox(INDENT_UNIT);
1167 if !field.is_shorthand {
1168 s.print_ident(field.ident);
1171 s.print_expr(&field.expr);
1178 self.ibox(INDENT_UNIT);
1179 if !fields.is_empty() {
1184 self.print_expr(&expr);
1188 if !fields.is_empty() {
1196 fn print_expr_tup(&mut self, exprs: &[hir::Expr<'_>]) {
1198 self.commasep_exprs(Inconsistent, exprs);
1199 if exprs.len() == 1 {
1205 fn print_expr_call(&mut self, func: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
1206 let prec = match func.kind {
1207 hir::ExprKind::Field(..) => parser::PREC_FORCE_PAREN,
1208 _ => parser::PREC_POSTFIX,
1211 self.print_expr_maybe_paren(func, prec);
1212 self.print_call_post(args)
1215 fn print_expr_method_call(&mut self, segment: &hir::PathSegment<'_>, args: &[hir::Expr<'_>]) {
1216 let base_args = &args[1..];
1217 self.print_expr_maybe_paren(&args[0], parser::PREC_POSTFIX);
1219 self.print_ident(segment.ident);
1221 let generic_args = segment.generic_args();
1222 if !generic_args.args.is_empty() || !generic_args.bindings.is_empty() {
1223 self.print_generic_args(generic_args, segment.infer_args, true);
1226 self.print_call_post(base_args)
1229 fn print_expr_binary(&mut self, op: hir::BinOp, lhs: &hir::Expr<'_>, rhs: &hir::Expr<'_>) {
1230 let assoc_op = bin_op_to_assoc_op(op.node);
1231 let prec = assoc_op.precedence() as i8;
1232 let fixity = assoc_op.fixity();
1234 let (left_prec, right_prec) = match fixity {
1235 Fixity::Left => (prec, prec + 1),
1236 Fixity::Right => (prec + 1, prec),
1237 Fixity::None => (prec + 1, prec + 1),
1240 let left_prec = match (&lhs.kind, op.node) {
1241 // These cases need parens: `x as i32 < y` has the parser thinking that `i32 < y` is
1242 // the beginning of a path type. It starts trying to parse `x as (i32 < y ...` instead
1243 // of `(x as i32) < ...`. We need to convince it _not_ to do that.
1244 (&hir::ExprKind::Cast { .. }, hir::BinOpKind::Lt | hir::BinOpKind::Shl) => {
1245 parser::PREC_FORCE_PAREN
1250 self.print_expr_maybe_paren(lhs, left_prec);
1252 self.word_space(op.node.as_str());
1253 self.print_expr_maybe_paren(rhs, right_prec)
1256 fn print_expr_unary(&mut self, op: hir::UnOp, expr: &hir::Expr<'_>) {
1257 self.s.word(op.as_str());
1258 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1261 fn print_expr_addr_of(
1263 kind: hir::BorrowKind,
1264 mutability: hir::Mutability,
1265 expr: &hir::Expr<'_>,
1269 hir::BorrowKind::Ref => self.print_mutability(mutability, false),
1270 hir::BorrowKind::Raw => {
1271 self.word_nbsp("raw");
1272 self.print_mutability(mutability, true);
1275 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1278 fn print_literal(&mut self, lit: &hir::Lit) {
1279 self.maybe_print_comment(lit.span.lo());
1280 self.word(lit.node.to_lit_token().to_string())
1283 pub fn print_expr(&mut self, expr: &hir::Expr<'_>) {
1284 self.maybe_print_comment(expr.span.lo());
1285 self.print_outer_attributes(&expr.attrs);
1286 self.ibox(INDENT_UNIT);
1287 self.ann.pre(self, AnnNode::Expr(expr));
1289 hir::ExprKind::Box(ref expr) => {
1290 self.word_space("box");
1291 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX);
1293 hir::ExprKind::Array(ref exprs) => {
1294 self.print_expr_vec(exprs);
1296 hir::ExprKind::Repeat(ref element, ref count) => {
1297 self.print_expr_repeat(&element, count);
1299 hir::ExprKind::Struct(ref qpath, fields, ref wth) => {
1300 self.print_expr_struct(qpath, fields, wth);
1302 hir::ExprKind::Tup(ref exprs) => {
1303 self.print_expr_tup(exprs);
1305 hir::ExprKind::Call(ref func, ref args) => {
1306 self.print_expr_call(&func, args);
1308 hir::ExprKind::MethodCall(ref segment, _, ref args, _) => {
1309 self.print_expr_method_call(segment, args);
1311 hir::ExprKind::Binary(op, ref lhs, ref rhs) => {
1312 self.print_expr_binary(op, &lhs, &rhs);
1314 hir::ExprKind::Unary(op, ref expr) => {
1315 self.print_expr_unary(op, &expr);
1317 hir::ExprKind::AddrOf(k, m, ref expr) => {
1318 self.print_expr_addr_of(k, m, &expr);
1320 hir::ExprKind::Lit(ref lit) => {
1321 self.print_literal(&lit);
1323 hir::ExprKind::Cast(ref expr, ref ty) => {
1324 let prec = AssocOp::As.precedence() as i8;
1325 self.print_expr_maybe_paren(&expr, prec);
1327 self.word_space("as");
1328 self.print_type(&ty);
1330 hir::ExprKind::Type(ref expr, ref ty) => {
1331 let prec = AssocOp::Colon.precedence() as i8;
1332 self.print_expr_maybe_paren(&expr, prec);
1333 self.word_space(":");
1334 self.print_type(&ty);
1336 hir::ExprKind::DropTemps(ref init) => {
1338 self.cbox(INDENT_UNIT);
1342 // Print `let _t = $init;`:
1343 let temp = Ident::from_str("_t");
1344 self.print_local(Some(init), |this| this.print_ident(temp));
1348 self.space_if_not_bol();
1349 self.print_ident(temp);
1352 self.bclose_maybe_open(expr.span, true);
1354 hir::ExprKind::Loop(ref blk, opt_label, _) => {
1355 if let Some(label) = opt_label {
1356 self.print_ident(label.ident);
1357 self.word_space(":");
1361 self.print_block(&blk);
1363 hir::ExprKind::Match(ref expr, arms, _) => {
1364 self.cbox(INDENT_UNIT);
1365 self.ibox(INDENT_UNIT);
1366 self.word_nbsp("match");
1367 self.print_expr_as_cond(&expr);
1371 self.print_arm(arm);
1373 self.bclose(expr.span);
1375 hir::ExprKind::Closure(capture_clause, ref decl, body, _fn_decl_span, _gen) => {
1376 self.print_capture_clause(capture_clause);
1378 self.print_closure_params(&decl, body);
1381 // This is a bare expression.
1382 self.ann.nested(self, Nested::Body(body));
1383 self.end(); // need to close a box
1385 // A box will be closed by `print_expr`, but we didn't want an overall
1386 // wrapper so we closed the corresponding opening. so create an
1387 // empty box to satisfy the close.
1390 hir::ExprKind::Block(ref blk, opt_label) => {
1391 if let Some(label) = opt_label {
1392 self.print_ident(label.ident);
1393 self.word_space(":");
1395 // containing cbox, will be closed by print-block at `}`
1396 self.cbox(INDENT_UNIT);
1397 // head-box, will be closed by print-block after `{`
1399 self.print_block(&blk);
1401 hir::ExprKind::Assign(ref lhs, ref rhs, _) => {
1402 let prec = AssocOp::Assign.precedence() as i8;
1403 self.print_expr_maybe_paren(&lhs, prec + 1);
1405 self.word_space("=");
1406 self.print_expr_maybe_paren(&rhs, prec);
1408 hir::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
1409 let prec = AssocOp::Assign.precedence() as i8;
1410 self.print_expr_maybe_paren(&lhs, prec + 1);
1412 self.s.word(op.node.as_str());
1413 self.word_space("=");
1414 self.print_expr_maybe_paren(&rhs, prec);
1416 hir::ExprKind::Field(ref expr, ident) => {
1417 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
1419 self.print_ident(ident);
1421 hir::ExprKind::Index(ref expr, ref index) => {
1422 self.print_expr_maybe_paren(&expr, parser::PREC_POSTFIX);
1424 self.print_expr(&index);
1427 hir::ExprKind::Path(ref qpath) => self.print_qpath(qpath, true),
1428 hir::ExprKind::Break(destination, ref opt_expr) => {
1429 self.s.word("break");
1431 if let Some(label) = destination.label {
1432 self.print_ident(label.ident);
1435 if let Some(ref expr) = *opt_expr {
1436 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
1440 hir::ExprKind::Continue(destination) => {
1441 self.s.word("continue");
1443 if let Some(label) = destination.label {
1444 self.print_ident(label.ident);
1448 hir::ExprKind::Ret(ref result) => {
1449 self.s.word("return");
1450 if let Some(ref expr) = *result {
1452 self.print_expr_maybe_paren(&expr, parser::PREC_JUMP);
1455 hir::ExprKind::InlineAsm(ref a) => {
1458 Operand(&'a hir::InlineAsmOperand<'a>),
1459 Options(ast::InlineAsmOptions),
1462 let mut args = vec![];
1463 args.push(AsmArg::Template(ast::InlineAsmTemplatePiece::to_string(&a.template)));
1464 args.extend(a.operands.iter().map(|o| AsmArg::Operand(o)));
1465 if !a.options.is_empty() {
1466 args.push(AsmArg::Options(a.options));
1471 self.commasep(Consistent, &args, |s, arg| match arg {
1472 AsmArg::Template(template) => s.print_string(&template, ast::StrStyle::Cooked),
1473 AsmArg::Operand(op) => match op {
1474 hir::InlineAsmOperand::In { reg, expr } => {
1477 s.word(format!("{}", reg));
1482 hir::InlineAsmOperand::Out { reg, late, expr } => {
1483 s.word(if *late { "lateout" } else { "out" });
1485 s.word(format!("{}", reg));
1489 Some(expr) => s.print_expr(expr),
1490 None => s.word("_"),
1493 hir::InlineAsmOperand::InOut { reg, late, expr } => {
1494 s.word(if *late { "inlateout" } else { "inout" });
1496 s.word(format!("{}", reg));
1501 hir::InlineAsmOperand::SplitInOut { reg, late, in_expr, out_expr } => {
1502 s.word(if *late { "inlateout" } else { "inout" });
1504 s.word(format!("{}", reg));
1507 s.print_expr(in_expr);
1511 Some(out_expr) => s.print_expr(out_expr),
1512 None => s.word("_"),
1515 hir::InlineAsmOperand::Const { expr } => {
1520 hir::InlineAsmOperand::Sym { expr } => {
1526 AsmArg::Options(opts) => {
1529 let mut options = vec![];
1530 if opts.contains(ast::InlineAsmOptions::PURE) {
1531 options.push("pure");
1533 if opts.contains(ast::InlineAsmOptions::NOMEM) {
1534 options.push("nomem");
1536 if opts.contains(ast::InlineAsmOptions::READONLY) {
1537 options.push("readonly");
1539 if opts.contains(ast::InlineAsmOptions::PRESERVES_FLAGS) {
1540 options.push("preserves_flags");
1542 if opts.contains(ast::InlineAsmOptions::NORETURN) {
1543 options.push("noreturn");
1545 if opts.contains(ast::InlineAsmOptions::NOSTACK) {
1546 options.push("nostack");
1548 if opts.contains(ast::InlineAsmOptions::ATT_SYNTAX) {
1549 options.push("att_syntax");
1551 s.commasep(Inconsistent, &options, |s, &opt| {
1559 hir::ExprKind::LlvmInlineAsm(ref a) => {
1561 self.s.word("llvm_asm!");
1563 self.print_symbol(i.asm, i.asm_str_style);
1564 self.word_space(":");
1566 let mut out_idx = 0;
1567 self.commasep(Inconsistent, &i.outputs, |s, out| {
1568 let constraint = out.constraint.as_str();
1569 let mut ch = constraint.chars();
1571 Some('=') if out.is_rw => {
1572 s.print_string(&format!("+{}", ch.as_str()), ast::StrStyle::Cooked)
1574 _ => s.print_string(&constraint, ast::StrStyle::Cooked),
1577 s.print_expr(&a.outputs_exprs[out_idx]);
1582 self.word_space(":");
1585 self.commasep(Inconsistent, &i.inputs, |s, &co| {
1586 s.print_symbol(co, ast::StrStyle::Cooked);
1588 s.print_expr(&a.inputs_exprs[in_idx]);
1593 self.word_space(":");
1595 self.commasep(Inconsistent, &i.clobbers, |s, &co| {
1596 s.print_symbol(co, ast::StrStyle::Cooked);
1599 let mut options = vec![];
1601 options.push("volatile");
1604 options.push("alignstack");
1606 if i.dialect == ast::LlvmAsmDialect::Intel {
1607 options.push("intel");
1610 if !options.is_empty() {
1612 self.word_space(":");
1613 self.commasep(Inconsistent, &options, |s, &co| {
1614 s.print_string(co, ast::StrStyle::Cooked);
1620 hir::ExprKind::Yield(ref expr, _) => {
1621 self.word_space("yield");
1622 self.print_expr_maybe_paren(&expr, parser::PREC_JUMP);
1624 hir::ExprKind::Err => {
1626 self.s.word("/*ERROR*/");
1630 self.ann.post(self, AnnNode::Expr(expr));
1634 pub fn print_local_decl(&mut self, loc: &hir::Local<'_>) {
1635 self.print_pat(&loc.pat);
1636 if let Some(ref ty) = loc.ty {
1637 self.word_space(":");
1638 self.print_type(&ty);
1642 pub fn print_usize(&mut self, i: usize) {
1643 self.s.word(i.to_string())
1646 pub fn print_name(&mut self, name: Symbol) {
1647 self.print_ident(Ident::with_dummy_span(name))
1650 pub fn print_for_decl(&mut self, loc: &hir::Local<'_>, coll: &hir::Expr<'_>) {
1651 self.print_local_decl(loc);
1653 self.word_space("in");
1654 self.print_expr(coll)
1657 pub fn print_path(&mut self, path: &hir::Path<'_>, colons_before_params: bool) {
1658 self.maybe_print_comment(path.span.lo());
1660 for (i, segment) in path.segments.iter().enumerate() {
1664 if segment.ident.name != kw::PathRoot {
1665 self.print_ident(segment.ident);
1666 self.print_generic_args(
1667 segment.generic_args(),
1669 colons_before_params,
1675 pub fn print_path_segment(&mut self, segment: &hir::PathSegment<'_>) {
1676 if segment.ident.name != kw::PathRoot {
1677 self.print_ident(segment.ident);
1678 self.print_generic_args(segment.generic_args(), segment.infer_args, false);
1682 pub fn print_qpath(&mut self, qpath: &hir::QPath<'_>, colons_before_params: bool) {
1684 hir::QPath::Resolved(None, ref path) => self.print_path(path, colons_before_params),
1685 hir::QPath::Resolved(Some(ref qself), ref path) => {
1687 self.print_type(qself);
1689 self.word_space("as");
1691 for (i, segment) in path.segments[..path.segments.len() - 1].iter().enumerate() {
1695 if segment.ident.name != kw::PathRoot {
1696 self.print_ident(segment.ident);
1697 self.print_generic_args(
1698 segment.generic_args(),
1700 colons_before_params,
1707 let item_segment = path.segments.last().unwrap();
1708 self.print_ident(item_segment.ident);
1709 self.print_generic_args(
1710 item_segment.generic_args(),
1711 item_segment.infer_args,
1712 colons_before_params,
1715 hir::QPath::TypeRelative(ref qself, ref item_segment) => {
1716 // If we've got a compound-qualified-path, let's push an additional pair of angle
1717 // brackets, so that we pretty-print `<<A::B>::C>` as `<A::B>::C`, instead of just
1718 // `A::B::C` (since the latter could be ambiguous to the user)
1719 if let hir::TyKind::Path(hir::QPath::Resolved(None, _)) = &qself.kind {
1720 self.print_type(qself);
1723 self.print_type(qself);
1728 self.print_ident(item_segment.ident);
1729 self.print_generic_args(
1730 item_segment.generic_args(),
1731 item_segment.infer_args,
1732 colons_before_params,
1735 hir::QPath::LangItem(lang_item, span) => {
1736 self.s.word("#[lang = \"");
1737 self.print_ident(Ident::new(lang_item.name(), span));
1743 fn print_generic_args(
1745 generic_args: &hir::GenericArgs<'_>,
1747 colons_before_params: bool,
1749 if generic_args.parenthesized {
1751 self.commasep(Inconsistent, generic_args.inputs(), |s, ty| s.print_type(&ty));
1754 self.space_if_not_bol();
1755 self.word_space("->");
1756 self.print_type(generic_args.bindings[0].ty());
1758 let start = if colons_before_params { "::<" } else { "<" };
1759 let empty = Cell::new(true);
1760 let start_or_comma = |this: &mut Self| {
1765 this.word_space(",")
1769 let mut nonelided_generic_args: bool = false;
1770 let elide_lifetimes = generic_args.args.iter().all(|arg| match arg {
1771 GenericArg::Lifetime(lt) => lt.is_elided(),
1773 nonelided_generic_args = true;
1778 if nonelided_generic_args {
1779 start_or_comma(self);
1783 |s, generic_arg| match generic_arg {
1784 GenericArg::Lifetime(lt) if !elide_lifetimes => s.print_lifetime(lt),
1785 GenericArg::Lifetime(_) => {}
1786 GenericArg::Type(ty) => s.print_type(ty),
1787 GenericArg::Const(ct) => s.print_anon_const(&ct.value),
1792 // FIXME(eddyb): this would leak into error messages (e.g.,
1793 // "non-exhaustive patterns: `Some::<..>(_)` not covered").
1794 if infer_args && false {
1795 start_or_comma(self);
1799 for binding in generic_args.bindings.iter() {
1800 start_or_comma(self);
1801 self.print_ident(binding.ident);
1803 match generic_args.bindings[0].kind {
1804 hir::TypeBindingKind::Equality { ref ty } => {
1805 self.word_space("=");
1806 self.print_type(ty);
1808 hir::TypeBindingKind::Constraint { bounds } => {
1809 self.print_bounds(":", bounds);
1820 pub fn print_pat(&mut self, pat: &hir::Pat<'_>) {
1821 self.maybe_print_comment(pat.span.lo());
1822 self.ann.pre(self, AnnNode::Pat(pat));
1823 // Pat isn't normalized, but the beauty of it
1824 // is that it doesn't matter
1826 PatKind::Wild => self.s.word("_"),
1827 PatKind::Binding(binding_mode, _, ident, ref sub) => {
1828 match binding_mode {
1829 hir::BindingAnnotation::Ref => {
1830 self.word_nbsp("ref");
1831 self.print_mutability(hir::Mutability::Not, false);
1833 hir::BindingAnnotation::RefMut => {
1834 self.word_nbsp("ref");
1835 self.print_mutability(hir::Mutability::Mut, false);
1837 hir::BindingAnnotation::Unannotated => {}
1838 hir::BindingAnnotation::Mutable => {
1839 self.word_nbsp("mut");
1842 self.print_ident(ident);
1843 if let Some(ref p) = *sub {
1848 PatKind::TupleStruct(ref qpath, ref elts, ddpos) => {
1849 self.print_qpath(qpath, true);
1851 if let Some(ddpos) = ddpos {
1852 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p));
1854 self.word_space(",");
1857 if ddpos != elts.len() {
1859 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p));
1862 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p));
1866 PatKind::Path(ref qpath) => {
1867 self.print_qpath(qpath, true);
1869 PatKind::Struct(ref qpath, ref fields, etc) => {
1870 self.print_qpath(qpath, true);
1872 self.word_space("{");
1877 s.cbox(INDENT_UNIT);
1878 if !f.is_shorthand {
1879 s.print_ident(f.ident);
1882 s.print_pat(&f.pat);
1888 if !fields.is_empty() {
1889 self.word_space(",");
1896 PatKind::Or(ref pats) => {
1897 self.strsep("|", true, Inconsistent, &pats[..], |s, p| s.print_pat(&p));
1899 PatKind::Tuple(ref elts, ddpos) => {
1901 if let Some(ddpos) = ddpos {
1902 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p));
1904 self.word_space(",");
1907 if ddpos != elts.len() {
1909 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p));
1912 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p));
1913 if elts.len() == 1 {
1919 PatKind::Box(ref inner) => {
1920 let is_range_inner = match inner.kind {
1921 PatKind::Range(..) => true,
1924 self.s.word("box ");
1928 self.print_pat(&inner);
1933 PatKind::Ref(ref inner, mutbl) => {
1934 let is_range_inner = match inner.kind {
1935 PatKind::Range(..) => true,
1939 self.s.word(mutbl.prefix_str());
1943 self.print_pat(&inner);
1948 PatKind::Lit(ref e) => self.print_expr(&e),
1949 PatKind::Range(ref begin, ref end, ref end_kind) => {
1950 if let Some(expr) = begin {
1951 self.print_expr(expr);
1955 RangeEnd::Included => self.s.word("..."),
1956 RangeEnd::Excluded => self.s.word(".."),
1958 if let Some(expr) = end {
1959 self.print_expr(expr);
1962 PatKind::Slice(ref before, ref slice, ref after) => {
1964 self.commasep(Inconsistent, &before[..], |s, p| s.print_pat(&p));
1965 if let Some(ref p) = *slice {
1966 if !before.is_empty() {
1967 self.word_space(",");
1969 if let PatKind::Wild = p.kind {
1975 if !after.is_empty() {
1976 self.word_space(",");
1979 self.commasep(Inconsistent, &after[..], |s, p| s.print_pat(&p));
1983 self.ann.post(self, AnnNode::Pat(pat))
1986 pub fn print_param(&mut self, arg: &hir::Param<'_>) {
1987 self.print_outer_attributes(&arg.attrs);
1988 self.print_pat(&arg.pat);
1991 pub fn print_arm(&mut self, arm: &hir::Arm<'_>) {
1992 // I have no idea why this check is necessary, but here it
1994 if arm.attrs.is_empty() {
1997 self.cbox(INDENT_UNIT);
1998 self.ann.pre(self, AnnNode::Arm(arm));
2000 self.print_outer_attributes(&arm.attrs);
2001 self.print_pat(&arm.pat);
2003 if let Some(ref g) = arm.guard {
2005 hir::Guard::If(e) => {
2006 self.word_space("if");
2007 self.print_expr(&e);
2012 self.word_space("=>");
2014 match arm.body.kind {
2015 hir::ExprKind::Block(ref blk, opt_label) => {
2016 if let Some(label) = opt_label {
2017 self.print_ident(label.ident);
2018 self.word_space(":");
2020 // the block will close the pattern's ibox
2021 self.print_block_unclosed(&blk);
2023 // If it is a user-provided unsafe block, print a comma after it
2024 if let hir::BlockCheckMode::UnsafeBlock(hir::UnsafeSource::UserProvided) = blk.rules
2030 self.end(); // close the ibox for the pattern
2031 self.print_expr(&arm.body);
2035 self.ann.post(self, AnnNode::Arm(arm));
2036 self.end() // close enclosing cbox
2041 decl: &hir::FnDecl<'_>,
2042 header: hir::FnHeader,
2043 name: Option<Symbol>,
2044 generics: &hir::Generics<'_>,
2045 vis: &hir::Visibility<'_>,
2046 arg_names: &[Ident],
2047 body_id: Option<hir::BodyId>,
2049 self.print_fn_header_info(header, vis);
2051 if let Some(name) = name {
2053 self.print_name(name);
2055 self.print_generic_params(&generics.params);
2059 // Make sure we aren't supplied *both* `arg_names` and `body_id`.
2060 assert!(arg_names.is_empty() || body_id.is_none());
2061 self.commasep(Inconsistent, &decl.inputs, |s, ty| {
2062 s.ibox(INDENT_UNIT);
2063 if let Some(arg_name) = arg_names.get(i) {
2064 s.s.word(arg_name.to_string());
2067 } else if let Some(body_id) = body_id {
2068 s.ann.nested(s, Nested::BodyParamPat(body_id, i));
2076 if decl.c_variadic {
2077 self.s.word(", ...");
2081 self.print_fn_output(decl);
2082 self.print_where_clause(&generics.where_clause)
2085 fn print_closure_params(&mut self, decl: &hir::FnDecl<'_>, body_id: hir::BodyId) {
2088 self.commasep(Inconsistent, &decl.inputs, |s, ty| {
2089 s.ibox(INDENT_UNIT);
2091 s.ann.nested(s, Nested::BodyParamPat(body_id, i));
2094 if let hir::TyKind::Infer = ty.kind {
2105 if let hir::FnRetTy::DefaultReturn(..) = decl.output {
2109 self.space_if_not_bol();
2110 self.word_space("->");
2112 hir::FnRetTy::Return(ref ty) => {
2113 self.print_type(&ty);
2114 self.maybe_print_comment(ty.span.lo())
2116 hir::FnRetTy::DefaultReturn(..) => unreachable!(),
2120 pub fn print_capture_clause(&mut self, capture_clause: hir::CaptureBy) {
2121 match capture_clause {
2122 hir::CaptureBy::Value => self.word_space("move"),
2123 hir::CaptureBy::Ref => {}
2127 pub fn print_bounds<'b>(
2129 prefix: &'static str,
2130 bounds: impl IntoIterator<Item = &'b hir::GenericBound<'b>>,
2132 let mut first = true;
2133 for bound in bounds {
2135 self.s.word(prefix);
2137 if !(first && prefix.is_empty()) {
2143 self.word_space("+");
2147 GenericBound::Trait(tref, modifier) => {
2148 if modifier == &TraitBoundModifier::Maybe {
2151 self.print_poly_trait_ref(tref);
2153 GenericBound::LangItemTrait(lang_item, span, ..) => {
2154 self.s.word("#[lang = \"");
2155 self.print_ident(Ident::new(lang_item.name(), *span));
2158 GenericBound::Outlives(lt) => {
2159 self.print_lifetime(lt);
2165 pub fn print_generic_params(&mut self, generic_params: &[GenericParam<'_>]) {
2166 if !generic_params.is_empty() {
2169 self.commasep(Inconsistent, generic_params, |s, param| s.print_generic_param(param));
2175 pub fn print_generic_param(&mut self, param: &GenericParam<'_>) {
2176 if let GenericParamKind::Const { .. } = param.kind {
2177 self.word_space("const");
2180 self.print_ident(param.name.ident());
2183 GenericParamKind::Lifetime { .. } => {
2185 for bound in param.bounds {
2187 GenericBound::Outlives(ref lt) => {
2189 self.print_lifetime(lt);
2196 GenericParamKind::Type { ref default, .. } => {
2197 self.print_bounds(":", param.bounds);
2198 if let Some(default) = default {
2200 self.word_space("=");
2201 self.print_type(&default)
2204 GenericParamKind::Const { ref ty } => {
2205 self.word_space(":");
2211 pub fn print_lifetime(&mut self, lifetime: &hir::Lifetime) {
2212 self.print_ident(lifetime.name.ident())
2215 pub fn print_where_clause(&mut self, where_clause: &hir::WhereClause<'_>) {
2216 if where_clause.predicates.is_empty() {
2221 self.word_space("where");
2223 for (i, predicate) in where_clause.predicates.iter().enumerate() {
2225 self.word_space(",");
2229 &hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
2230 ref bound_generic_params,
2235 self.print_formal_generic_params(bound_generic_params);
2236 self.print_type(&bounded_ty);
2237 self.print_bounds(":", bounds);
2239 &hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
2244 self.print_lifetime(lifetime);
2247 for (i, bound) in bounds.iter().enumerate() {
2249 GenericBound::Outlives(lt) => {
2250 self.print_lifetime(lt);
2260 &hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
2265 self.print_type(lhs_ty);
2267 self.word_space("=");
2268 self.print_type(rhs_ty);
2274 pub fn print_mutability(&mut self, mutbl: hir::Mutability, print_const: bool) {
2276 hir::Mutability::Mut => self.word_nbsp("mut"),
2277 hir::Mutability::Not => {
2279 self.word_nbsp("const")
2285 pub fn print_mt(&mut self, mt: &hir::MutTy<'_>, print_const: bool) {
2286 self.print_mutability(mt.mutbl, print_const);
2287 self.print_type(&mt.ty)
2290 pub fn print_fn_output(&mut self, decl: &hir::FnDecl<'_>) {
2291 if let hir::FnRetTy::DefaultReturn(..) = decl.output {
2295 self.space_if_not_bol();
2296 self.ibox(INDENT_UNIT);
2297 self.word_space("->");
2299 hir::FnRetTy::DefaultReturn(..) => unreachable!(),
2300 hir::FnRetTy::Return(ref ty) => self.print_type(&ty),
2304 if let hir::FnRetTy::Return(ref output) = decl.output {
2305 self.maybe_print_comment(output.span.lo())
2312 unsafety: hir::Unsafety,
2313 decl: &hir::FnDecl<'_>,
2314 name: Option<Symbol>,
2315 generic_params: &[hir::GenericParam<'_>],
2316 arg_names: &[Ident],
2318 self.ibox(INDENT_UNIT);
2319 if !generic_params.is_empty() {
2321 self.print_generic_params(generic_params);
2323 let generics = hir::Generics {
2325 where_clause: hir::WhereClause { predicates: &[], span: rustc_span::DUMMY_SP },
2326 span: rustc_span::DUMMY_SP,
2333 constness: hir::Constness::NotConst,
2334 asyncness: hir::IsAsync::NotAsync,
2338 &Spanned { span: rustc_span::DUMMY_SP, node: hir::VisibilityKind::Inherited },
2345 pub fn maybe_print_trailing_comment(
2347 span: rustc_span::Span,
2348 next_pos: Option<BytePos>,
2350 if let Some(cmnts) = self.comments() {
2351 if let Some(cmnt) = cmnts.trailing_comment(span, next_pos) {
2352 self.print_comment(&cmnt);
2357 pub fn print_remaining_comments(&mut self) {
2358 // If there aren't any remaining comments, then we need to manually
2359 // make sure there is a line break at the end.
2360 if self.next_comment().is_none() {
2363 while let Some(ref cmnt) = self.next_comment() {
2364 self.print_comment(cmnt)
2368 pub fn print_opt_abi_and_extern_if_nondefault(&mut self, opt_abi: Option<Abi>) {
2370 Some(Abi::Rust) => {}
2372 self.word_nbsp("extern");
2373 self.word_nbsp(abi.to_string())
2379 pub fn print_extern_opt_abi(&mut self, opt_abi: Option<Abi>) {
2380 if let Some(abi) = opt_abi {
2381 self.word_nbsp("extern");
2382 self.word_nbsp(abi.to_string())
2386 pub fn print_fn_header_info(&mut self, header: hir::FnHeader, vis: &hir::Visibility<'_>) {
2387 self.s.word(visibility_qualified(vis, ""));
2389 match header.constness {
2390 hir::Constness::NotConst => {}
2391 hir::Constness::Const => self.word_nbsp("const"),
2394 match header.asyncness {
2395 hir::IsAsync::NotAsync => {}
2396 hir::IsAsync::Async => self.word_nbsp("async"),
2399 self.print_unsafety(header.unsafety);
2401 if header.abi != Abi::Rust {
2402 self.word_nbsp("extern");
2403 self.word_nbsp(header.abi.to_string());
2409 pub fn print_unsafety(&mut self, s: hir::Unsafety) {
2411 hir::Unsafety::Normal => {}
2412 hir::Unsafety::Unsafe => self.word_nbsp("unsafe"),
2416 pub fn print_is_auto(&mut self, s: hir::IsAuto) {
2418 hir::IsAuto::Yes => self.word_nbsp("auto"),
2419 hir::IsAuto::No => {}
2424 /// Does this expression require a semicolon to be treated
2425 /// as a statement? The negation of this: 'can this expression
2426 /// be used as a statement without a semicolon' -- is used
2427 /// as an early-bail-out in the parser so that, for instance,
2428 /// if true {...} else {...}
2430 /// isn't parsed as (if true {...} else {...} | x) | 5
2432 // Duplicated from `parse::classify`, but adapted for the HIR.
2433 fn expr_requires_semi_to_be_stmt(e: &hir::Expr<'_>) -> bool {
2435 hir::ExprKind::Match(..) | hir::ExprKind::Block(..) | hir::ExprKind::Loop(..) => false,
2440 /// This statement requires a semicolon after it.
2441 /// note that in one case (stmt_semi), we've already
2442 /// seen the semicolon, and thus don't need another.
2443 fn stmt_ends_with_semi(stmt: &hir::StmtKind<'_>) -> bool {
2445 hir::StmtKind::Local(_) => true,
2446 hir::StmtKind::Item(_) => false,
2447 hir::StmtKind::Expr(ref e) => expr_requires_semi_to_be_stmt(&e),
2448 hir::StmtKind::Semi(..) => false,
2452 fn bin_op_to_assoc_op(op: hir::BinOpKind) -> AssocOp {
2453 use crate::hir::BinOpKind::*;
2455 Add => AssocOp::Add,
2456 Sub => AssocOp::Subtract,
2457 Mul => AssocOp::Multiply,
2458 Div => AssocOp::Divide,
2459 Rem => AssocOp::Modulus,
2461 And => AssocOp::LAnd,
2464 BitXor => AssocOp::BitXor,
2465 BitAnd => AssocOp::BitAnd,
2466 BitOr => AssocOp::BitOr,
2467 Shl => AssocOp::ShiftLeft,
2468 Shr => AssocOp::ShiftRight,
2470 Eq => AssocOp::Equal,
2471 Lt => AssocOp::Less,
2472 Le => AssocOp::LessEqual,
2473 Ne => AssocOp::NotEqual,
2474 Ge => AssocOp::GreaterEqual,
2475 Gt => AssocOp::Greater,
2479 /// Expressions that syntactically contain an "exterior" struct literal, i.e., not surrounded by any
2480 /// parens or other delimiters, e.g., `X { y: 1 }`, `X { y: 1 }.method()`, `foo == X { y: 1 }` and
2481 /// `X { y: 1 } == foo` all do, but `(X { y: 1 }) == foo` does not.
2482 fn contains_exterior_struct_lit(value: &hir::Expr<'_>) -> bool {
2484 hir::ExprKind::Struct(..) => true,
2486 hir::ExprKind::Assign(ref lhs, ref rhs, _)
2487 | hir::ExprKind::AssignOp(_, ref lhs, ref rhs)
2488 | hir::ExprKind::Binary(_, ref lhs, ref rhs) => {
2489 // `X { y: 1 } + X { y: 2 }`
2490 contains_exterior_struct_lit(&lhs) || contains_exterior_struct_lit(&rhs)
2492 hir::ExprKind::Unary(_, ref x)
2493 | hir::ExprKind::Cast(ref x, _)
2494 | hir::ExprKind::Type(ref x, _)
2495 | hir::ExprKind::Field(ref x, _)
2496 | hir::ExprKind::Index(ref x, _) => {
2497 // `&X { y: 1 }, X { y: 1 }.y`
2498 contains_exterior_struct_lit(&x)
2501 hir::ExprKind::MethodCall(.., ref exprs, _) => {
2502 // `X { y: 1 }.bar(...)`
2503 contains_exterior_struct_lit(&exprs[0])