1 use rustc_span::source_map::{SourceMap, Spanned};
2 use rustc_span::symbol::kw;
3 use rustc_span::{self, BytePos, FileName};
4 use rustc_target::spec::abi::Abi;
6 use syntax::print::pp::Breaks::{Consistent, Inconsistent};
7 use syntax::print::pp::{self, Breaks};
8 use syntax::print::pprust::{self, Comments, PrintState};
9 use syntax::sess::ParseSess;
10 use syntax::util::parser::{self, AssocOp, Fixity};
13 use crate::hir::{GenericArg, GenericParam, GenericParamKind, Node};
14 use crate::hir::{GenericBound, PatKind, RangeEnd, TraitBoundModifier};
20 pub enum AnnNode<'a> {
22 Block(&'a hir::Block<'a>),
23 Item(&'a hir::Item<'a>),
25 Expr(&'a hir::Expr<'a>),
26 Pat(&'a hir::Pat<'a>),
27 Arm(&'a hir::Arm<'a>),
32 TraitItem(hir::TraitItemId),
33 ImplItem(hir::ImplItemId),
35 BodyParamPat(hir::BodyId, usize),
39 fn nested(&self, _state: &mut State<'_>, _nested: Nested) {}
40 fn pre(&self, _state: &mut State<'_>, _node: AnnNode<'_>) {}
41 fn post(&self, _state: &mut State<'_>, _node: AnnNode<'_>) {}
42 fn try_fetch_item(&self, _: hir::HirId) -> Option<&hir::Item<'_>> {
48 impl PpAnn for NoAnn {}
49 pub const NO_ANN: &dyn PpAnn = &NoAnn;
51 impl PpAnn for hir::Crate<'a> {
52 fn try_fetch_item(&self, item: hir::HirId) -> Option<&hir::Item<'_>> {
55 fn nested(&self, state: &mut State<'_>, nested: Nested) {
57 Nested::Item(id) => state.print_item(self.item(id.id)),
58 Nested::TraitItem(id) => state.print_trait_item(self.trait_item(id)),
59 Nested::ImplItem(id) => state.print_impl_item(self.impl_item(id)),
60 Nested::Body(id) => state.print_expr(&self.body(id).value),
61 Nested::BodyParamPat(id, i) => state.print_pat(&self.body(id).params[i].pat),
66 pub struct State<'a> {
68 comments: Option<Comments<'a>>,
69 ann: &'a (dyn PpAnn + 'a),
73 pub fn print_node(&mut self, node: Node<'_>) {
75 Node::Param(a) => self.print_param(&a),
76 Node::Item(a) => self.print_item(&a),
77 Node::ForeignItem(a) => self.print_foreign_item(&a),
78 Node::TraitItem(a) => self.print_trait_item(a),
79 Node::ImplItem(a) => self.print_impl_item(a),
80 Node::Variant(a) => self.print_variant(&a),
81 Node::AnonConst(a) => self.print_anon_const(&a),
82 Node::Expr(a) => self.print_expr(&a),
83 Node::Stmt(a) => self.print_stmt(&a),
84 Node::PathSegment(a) => self.print_path_segment(&a),
85 Node::Ty(a) => self.print_type(&a),
86 Node::TraitRef(a) => self.print_trait_ref(&a),
87 Node::Binding(a) | Node::Pat(a) => self.print_pat(&a),
88 Node::Arm(a) => self.print_arm(&a),
90 // Containing cbox, will be closed by print-block at `}`.
91 self.cbox(INDENT_UNIT);
92 // Head-ibox, will be closed by print-block after `{`.
96 Node::Lifetime(a) => self.print_lifetime(&a),
97 Node::Visibility(a) => self.print_visibility(&a),
98 Node::GenericParam(_) => panic!("cannot print Node::GenericParam"),
99 Node::Field(_) => panic!("cannot print StructField"),
100 // These cases do not carry enough information in the
101 // `hir_map` to reconstruct their full structure for pretty
103 Node::Ctor(..) => panic!("cannot print isolated Ctor"),
104 Node::Local(a) => self.print_local_decl(&a),
105 Node::MacroDef(_) => panic!("cannot print MacroDef"),
106 Node::Crate => panic!("cannot print Crate"),
111 impl std::ops::Deref for State<'_> {
112 type Target = pp::Printer;
113 fn deref(&self) -> &Self::Target {
118 impl std::ops::DerefMut for State<'_> {
119 fn deref_mut(&mut self) -> &mut Self::Target {
124 impl<'a> PrintState<'a> for State<'a> {
125 fn comments(&mut self) -> &mut Option<Comments<'a>> {
129 fn print_ident(&mut self, ident: ast::Ident) {
130 self.s.word(pprust::ast_ident_to_string(ident, ident.is_raw_guess()));
131 self.ann.post(self, AnnNode::Name(&ident.name))
134 fn print_generic_args(&mut self, _: &ast::GenericArgs, _colons_before_params: bool) {
135 panic!("AST generic args printed by HIR pretty-printer");
139 pub const INDENT_UNIT: usize = 4;
141 /// Requires you to pass an input filename and reader so that
142 /// it can scan the input text for comments to copy forward.
143 pub fn print_crate<'a>(
146 krate: &hir::Crate<'_>,
151 let mut s = State::new_from_input(cm, sess, filename, input, ann);
153 // When printing the AST, we sometimes need to inject `#[no_std]` here.
154 // Since you can't compile the HIR, it's not necessary.
156 s.print_mod(&krate.module, &krate.attrs);
157 s.print_remaining_comments();
162 pub fn new_from_input(
169 State { s: pp::mk_printer(), comments: Some(Comments::new(cm, sess, filename, input)), ann }
173 pub fn to_string<F>(ann: &dyn PpAnn, f: F) -> String
175 F: FnOnce(&mut State<'_>),
177 let mut printer = State { s: pp::mk_printer(), comments: None, ann };
182 pub fn visibility_qualified<S: Into<Cow<'static, str>>>(vis: &hir::Visibility<'_>, w: S) -> String {
183 to_string(NO_ANN, |s| {
184 s.print_visibility(vis);
190 pub fn cbox(&mut self, u: usize) {
194 pub fn nbsp(&mut self) {
198 pub fn word_nbsp<S: Into<Cow<'static, str>>>(&mut self, w: S) {
203 pub fn head<S: Into<Cow<'static, str>>>(&mut self, w: S) {
205 // outer-box is consistent
206 self.cbox(INDENT_UNIT);
207 // head-box is inconsistent
208 self.ibox(w.len() + 1);
209 // keyword that starts the head
215 pub fn bopen(&mut self) {
217 self.end(); // close the head-box
220 pub fn bclose_maybe_open(&mut self, span: rustc_span::Span, close_box: bool) {
221 self.maybe_print_comment(span.hi());
222 self.break_offset_if_not_bol(1, -(INDENT_UNIT as isize));
225 self.end(); // close the outer-box
229 pub fn bclose(&mut self, span: rustc_span::Span) {
230 self.bclose_maybe_open(span, true)
233 pub fn space_if_not_bol(&mut self) {
234 if !self.s.is_beginning_of_line() {
239 pub fn break_offset_if_not_bol(&mut self, n: usize, off: isize) {
240 if !self.s.is_beginning_of_line() {
241 self.s.break_offset(n, off)
243 if off != 0 && self.s.last_token().is_hardbreak_tok() {
244 // We do something pretty sketchy here: tuck the nonzero
245 // offset-adjustment we were going to deposit along with the
246 // break into the previous hardbreak.
247 self.s.replace_last_token(pp::Printer::hardbreak_tok_offset(off));
252 // Synthesizes a comment that was not textually present in the original source
254 pub fn synth_comment(&mut self, text: String) {
262 pub fn commasep_cmnt<T, F, G>(&mut self, b: Breaks, elts: &[T], mut op: F, mut get_span: G)
264 F: FnMut(&mut State<'_>, &T),
265 G: FnMut(&T) -> rustc_span::Span,
268 let len = elts.len();
271 self.maybe_print_comment(get_span(elt).hi());
276 self.maybe_print_trailing_comment(get_span(elt), Some(get_span(&elts[i]).hi()));
277 self.space_if_not_bol();
283 pub fn commasep_exprs(&mut self, b: Breaks, exprs: &[hir::Expr<'_>]) {
284 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(&e), |e| e.span)
287 pub fn print_mod(&mut self, _mod: &hir::Mod<'_>, attrs: &[ast::Attribute]) {
288 self.print_inner_attributes(attrs);
289 for &item_id in _mod.item_ids {
290 self.ann.nested(self, Nested::Item(item_id));
294 pub fn print_foreign_mod(&mut self, nmod: &hir::ForeignMod<'_>, attrs: &[ast::Attribute]) {
295 self.print_inner_attributes(attrs);
296 for item in nmod.items {
297 self.print_foreign_item(item);
301 pub fn print_opt_lifetime(&mut self, lifetime: &hir::Lifetime) {
302 if !lifetime.is_elided() {
303 self.print_lifetime(lifetime);
308 pub fn print_type(&mut self, ty: &hir::Ty<'_>) {
309 self.maybe_print_comment(ty.span.lo());
312 hir::TyKind::Slice(ref ty) => {
314 self.print_type(&ty);
317 hir::TyKind::Ptr(ref mt) => {
319 self.print_mt(mt, true);
321 hir::TyKind::Rptr(ref lifetime, ref mt) => {
323 self.print_opt_lifetime(lifetime);
324 self.print_mt(mt, false);
326 hir::TyKind::Never => {
329 hir::TyKind::Tup(ref elts) => {
331 self.commasep(Inconsistent, &elts[..], |s, ty| s.print_type(&ty));
337 hir::TyKind::BareFn(ref f) => {
347 hir::TyKind::Def(..) => {}
348 hir::TyKind::Path(ref qpath) => self.print_qpath(qpath, false),
349 hir::TyKind::TraitObject(bounds, ref lifetime) => {
350 let mut first = true;
351 for bound in bounds {
356 self.word_space("+");
358 self.print_poly_trait_ref(bound);
360 if !lifetime.is_elided() {
362 self.word_space("+");
363 self.print_lifetime(lifetime);
366 hir::TyKind::Array(ref ty, ref length) => {
368 self.print_type(&ty);
370 self.print_anon_const(length);
373 hir::TyKind::Typeof(ref e) => {
374 self.s.word("typeof(");
375 self.print_anon_const(e);
378 hir::TyKind::Infer => {
381 hir::TyKind::Err => {
383 self.s.word("/*ERROR*/");
390 pub fn print_foreign_item(&mut self, item: &hir::ForeignItem<'_>) {
391 self.hardbreak_if_not_bol();
392 self.maybe_print_comment(item.span.lo());
393 self.print_outer_attributes(&item.attrs);
395 hir::ForeignItemKind::Fn(ref decl, ref arg_names, ref generics) => {
400 unsafety: hir::Unsafety::Normal,
401 constness: hir::Constness::NotConst,
403 asyncness: hir::IsAsync::NotAsync,
405 Some(item.ident.name),
411 self.end(); // end head-ibox
413 self.end() // end the outer fn box
415 hir::ForeignItemKind::Static(ref t, m) => {
416 self.head(visibility_qualified(&item.vis, "static"));
417 if m == hir::Mutability::Mut {
418 self.word_space("mut");
420 self.print_ident(item.ident);
421 self.word_space(":");
424 self.end(); // end the head-ibox
425 self.end() // end the outer cbox
427 hir::ForeignItemKind::Type => {
428 self.head(visibility_qualified(&item.vis, "type"));
429 self.print_ident(item.ident);
431 self.end(); // end the head-ibox
432 self.end() // end the outer cbox
437 fn print_associated_const(
441 default: Option<hir::BodyId>,
442 vis: &hir::Visibility<'_>,
444 self.s.word(visibility_qualified(vis, ""));
445 self.word_space("const");
446 self.print_ident(ident);
447 self.word_space(":");
449 if let Some(expr) = default {
451 self.word_space("=");
452 self.ann.nested(self, Nested::Body(expr));
457 fn print_associated_type(
460 bounds: Option<hir::GenericBounds<'_>>,
461 ty: Option<&hir::Ty<'_>>,
463 self.word_space("type");
464 self.print_ident(ident);
465 if let Some(bounds) = bounds {
466 self.print_bounds(":", bounds);
468 if let Some(ty) = ty {
470 self.word_space("=");
478 item: &hir::Item<'_>,
479 generics: &hir::Generics<'_>,
480 inner: impl Fn(&mut Self),
482 self.head(visibility_qualified(&item.vis, "type"));
483 self.print_ident(item.ident);
484 self.print_generic_params(&generics.params);
485 self.end(); // end the inner ibox
487 self.print_where_clause(&generics.where_clause);
491 self.end(); // end the outer ibox
494 /// Pretty-print an item
495 pub fn print_item(&mut self, item: &hir::Item<'_>) {
496 self.hardbreak_if_not_bol();
497 self.maybe_print_comment(item.span.lo());
498 self.print_outer_attributes(&item.attrs);
499 self.ann.pre(self, AnnNode::Item(item));
501 hir::ItemKind::ExternCrate(orig_name) => {
502 self.head(visibility_qualified(&item.vis, "extern crate"));
503 if let Some(orig_name) = orig_name {
504 self.print_name(orig_name);
509 self.print_ident(item.ident);
511 self.end(); // end inner head-block
512 self.end(); // end outer head-block
514 hir::ItemKind::Use(ref path, kind) => {
515 self.head(visibility_qualified(&item.vis, "use"));
516 self.print_path(path, false);
519 hir::UseKind::Single => {
520 if path.segments.last().unwrap().ident != item.ident {
522 self.word_space("as");
523 self.print_ident(item.ident);
527 hir::UseKind::Glob => self.s.word("::*;"),
528 hir::UseKind::ListStem => self.s.word("::{};"),
530 self.end(); // end inner head-block
531 self.end(); // end outer head-block
533 hir::ItemKind::Static(ref ty, m, expr) => {
534 self.head(visibility_qualified(&item.vis, "static"));
535 if m == hir::Mutability::Mut {
536 self.word_space("mut");
538 self.print_ident(item.ident);
539 self.word_space(":");
540 self.print_type(&ty);
542 self.end(); // end the head-ibox
544 self.word_space("=");
545 self.ann.nested(self, Nested::Body(expr));
547 self.end(); // end the outer cbox
549 hir::ItemKind::Const(ref ty, expr) => {
550 self.head(visibility_qualified(&item.vis, "const"));
551 self.print_ident(item.ident);
552 self.word_space(":");
553 self.print_type(&ty);
555 self.end(); // end the head-ibox
557 self.word_space("=");
558 self.ann.nested(self, Nested::Body(expr));
560 self.end(); // end the outer cbox
562 hir::ItemKind::Fn(ref sig, ref param_names, body) => {
567 Some(item.ident.name),
574 self.end(); // need to close a box
575 self.end(); // need to close a box
576 self.ann.nested(self, Nested::Body(body));
578 hir::ItemKind::Mod(ref _mod) => {
579 self.head(visibility_qualified(&item.vis, "mod"));
580 self.print_ident(item.ident);
583 self.print_mod(_mod, &item.attrs);
584 self.bclose(item.span);
586 hir::ItemKind::ForeignMod(ref nmod) => {
588 self.word_nbsp(nmod.abi.to_string());
590 self.print_foreign_mod(nmod, &item.attrs);
591 self.bclose(item.span);
593 hir::ItemKind::GlobalAsm(ref ga) => {
594 self.head(visibility_qualified(&item.vis, "global asm"));
595 self.s.word(ga.asm.to_string());
598 hir::ItemKind::TyAlias(ref ty, ref generics) => {
599 self.print_item_type(item, &generics, |state| {
600 state.word_space("=");
601 state.print_type(&ty);
604 hir::ItemKind::OpaqueTy(ref opaque_ty) => {
605 self.print_item_type(item, &opaque_ty.generics, |state| {
606 let mut real_bounds = Vec::with_capacity(opaque_ty.bounds.len());
607 for b in opaque_ty.bounds.iter() {
608 if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
610 state.word_space("for ?");
611 state.print_trait_ref(&ptr.trait_ref);
616 state.print_bounds("= impl", real_bounds);
619 hir::ItemKind::Enum(ref enum_definition, ref params) => {
620 self.print_enum_def(enum_definition, params, item.ident.name, item.span, &item.vis);
622 hir::ItemKind::Struct(ref struct_def, ref generics) => {
623 self.head(visibility_qualified(&item.vis, "struct"));
624 self.print_struct(struct_def, generics, item.ident.name, item.span, true);
626 hir::ItemKind::Union(ref struct_def, ref generics) => {
627 self.head(visibility_qualified(&item.vis, "union"));
628 self.print_struct(struct_def, generics, item.ident.name, item.span, true);
640 self.print_visibility(&item.vis);
641 self.print_defaultness(defaultness);
642 self.print_unsafety(unsafety);
643 self.word_nbsp("impl");
645 if !generics.params.is_empty() {
646 self.print_generic_params(&generics.params);
650 if let hir::ImplPolarity::Negative = polarity {
654 if let Some(ref t) = opt_trait {
655 self.print_trait_ref(t);
657 self.word_space("for");
660 self.print_type(&ty);
661 self.print_where_clause(&generics.where_clause);
665 self.print_inner_attributes(&item.attrs);
666 for impl_item in impl_items {
667 self.ann.nested(self, Nested::ImplItem(impl_item.id));
669 self.bclose(item.span);
671 hir::ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, trait_items) => {
673 self.print_visibility(&item.vis);
674 self.print_is_auto(is_auto);
675 self.print_unsafety(unsafety);
676 self.word_nbsp("trait");
677 self.print_ident(item.ident);
678 self.print_generic_params(&generics.params);
679 let mut real_bounds = Vec::with_capacity(bounds.len());
680 for b in bounds.iter() {
681 if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
683 self.word_space("for ?");
684 self.print_trait_ref(&ptr.trait_ref);
689 self.print_bounds(":", real_bounds);
690 self.print_where_clause(&generics.where_clause);
693 for trait_item in trait_items {
694 self.ann.nested(self, Nested::TraitItem(trait_item.id));
696 self.bclose(item.span);
698 hir::ItemKind::TraitAlias(ref generics, ref bounds) => {
700 self.print_visibility(&item.vis);
701 self.word_nbsp("trait");
702 self.print_ident(item.ident);
703 self.print_generic_params(&generics.params);
704 let mut real_bounds = Vec::with_capacity(bounds.len());
705 // FIXME(durka) this seems to be some quite outdated syntax
706 for b in bounds.iter() {
707 if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
709 self.word_space("for ?");
710 self.print_trait_ref(&ptr.trait_ref);
716 self.print_bounds("=", real_bounds);
717 self.print_where_clause(&generics.where_clause);
721 self.ann.post(self, AnnNode::Item(item))
724 pub fn print_trait_ref(&mut self, t: &hir::TraitRef<'_>) {
725 self.print_path(&t.path, false)
728 fn print_formal_generic_params(&mut self, generic_params: &[hir::GenericParam<'_>]) {
729 if !generic_params.is_empty() {
731 self.print_generic_params(generic_params);
736 fn print_poly_trait_ref(&mut self, t: &hir::PolyTraitRef<'_>) {
737 self.print_formal_generic_params(&t.bound_generic_params);
738 self.print_trait_ref(&t.trait_ref)
741 pub fn print_enum_def(
743 enum_definition: &hir::EnumDef<'_>,
744 generics: &hir::Generics<'_>,
746 span: rustc_span::Span,
747 visibility: &hir::Visibility<'_>,
749 self.head(visibility_qualified(visibility, "enum"));
750 self.print_name(name);
751 self.print_generic_params(&generics.params);
752 self.print_where_clause(&generics.where_clause);
754 self.print_variants(&enum_definition.variants, span)
757 pub fn print_variants(&mut self, variants: &[hir::Variant<'_>], span: rustc_span::Span) {
760 self.space_if_not_bol();
761 self.maybe_print_comment(v.span.lo());
762 self.print_outer_attributes(&v.attrs);
763 self.ibox(INDENT_UNIT);
764 self.print_variant(v);
767 self.maybe_print_trailing_comment(v.span, None);
772 pub fn print_visibility(&mut self, vis: &hir::Visibility<'_>) {
774 hir::VisibilityKind::Public => self.word_nbsp("pub"),
775 hir::VisibilityKind::Crate(ast::CrateSugar::JustCrate) => self.word_nbsp("crate"),
776 hir::VisibilityKind::Crate(ast::CrateSugar::PubCrate) => self.word_nbsp("pub(crate)"),
777 hir::VisibilityKind::Restricted { ref path, .. } => {
779 if path.segments.len() == 1 && path.segments[0].ident.name == kw::Super {
780 // Special case: `super` can print like `pub(super)`.
781 self.s.word("super");
783 // Everything else requires `in` at present.
784 self.word_nbsp("in");
785 self.print_path(path, false);
789 hir::VisibilityKind::Inherited => (),
793 pub fn print_defaultness(&mut self, defaultness: hir::Defaultness) {
795 hir::Defaultness::Default { .. } => self.word_nbsp("default"),
796 hir::Defaultness::Final => (),
802 struct_def: &hir::VariantData<'_>,
803 generics: &hir::Generics<'_>,
805 span: rustc_span::Span,
806 print_finalizer: bool,
808 self.print_name(name);
809 self.print_generic_params(&generics.params);
811 hir::VariantData::Tuple(..) | hir::VariantData::Unit(..) => {
812 if let hir::VariantData::Tuple(..) = struct_def {
814 self.commasep(Inconsistent, struct_def.fields(), |s, field| {
815 s.maybe_print_comment(field.span.lo());
816 s.print_outer_attributes(&field.attrs);
817 s.print_visibility(&field.vis);
818 s.print_type(&field.ty)
822 self.print_where_clause(&generics.where_clause);
827 self.end() // close the outer-box
829 hir::VariantData::Struct(..) => {
830 self.print_where_clause(&generics.where_clause);
833 self.hardbreak_if_not_bol();
835 for field in struct_def.fields() {
836 self.hardbreak_if_not_bol();
837 self.maybe_print_comment(field.span.lo());
838 self.print_outer_attributes(&field.attrs);
839 self.print_visibility(&field.vis);
840 self.print_ident(field.ident);
842 self.print_type(&field.ty);
851 pub fn print_variant(&mut self, v: &hir::Variant<'_>) {
853 let generics = hir::Generics::empty();
854 self.print_struct(&v.data, &generics, v.ident.name, v.span, false);
855 if let Some(ref d) = v.disr_expr {
857 self.word_space("=");
858 self.print_anon_const(d);
861 pub fn print_method_sig(
865 generics: &hir::Generics<'_>,
866 vis: &hir::Visibility<'_>,
867 arg_names: &[ast::Ident],
868 body_id: Option<hir::BodyId>,
870 self.print_fn(&m.decl, m.header, Some(ident.name), generics, vis, arg_names, body_id)
873 pub fn print_trait_item(&mut self, ti: &hir::TraitItem<'_>) {
874 self.ann.pre(self, AnnNode::SubItem(ti.hir_id));
875 self.hardbreak_if_not_bol();
876 self.maybe_print_comment(ti.span.lo());
877 self.print_outer_attributes(&ti.attrs);
879 hir::TraitItemKind::Const(ref ty, default) => {
881 Spanned { span: rustc_span::DUMMY_SP, node: hir::VisibilityKind::Inherited };
882 self.print_associated_const(ti.ident, &ty, default, &vis);
884 hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Required(ref arg_names)) => {
886 Spanned { span: rustc_span::DUMMY_SP, node: hir::VisibilityKind::Inherited };
887 self.print_method_sig(ti.ident, sig, &ti.generics, &vis, arg_names, None);
890 hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Provided(body)) => {
892 Spanned { span: rustc_span::DUMMY_SP, node: hir::VisibilityKind::Inherited };
894 self.print_method_sig(ti.ident, sig, &ti.generics, &vis, &[], Some(body));
896 self.end(); // need to close a box
897 self.end(); // need to close a box
898 self.ann.nested(self, Nested::Body(body));
900 hir::TraitItemKind::Type(ref bounds, ref default) => {
901 self.print_associated_type(
904 default.as_ref().map(|ty| &**ty),
908 self.ann.post(self, AnnNode::SubItem(ti.hir_id))
911 pub fn print_impl_item(&mut self, ii: &hir::ImplItem<'_>) {
912 self.ann.pre(self, AnnNode::SubItem(ii.hir_id));
913 self.hardbreak_if_not_bol();
914 self.maybe_print_comment(ii.span.lo());
915 self.print_outer_attributes(&ii.attrs);
916 self.print_defaultness(ii.defaultness);
919 hir::ImplItemKind::Const(ref ty, expr) => {
920 self.print_associated_const(ii.ident, &ty, Some(expr), &ii.vis);
922 hir::ImplItemKind::Method(ref sig, body) => {
924 self.print_method_sig(ii.ident, sig, &ii.generics, &ii.vis, &[], Some(body));
926 self.end(); // need to close a box
927 self.end(); // need to close a box
928 self.ann.nested(self, Nested::Body(body));
930 hir::ImplItemKind::TyAlias(ref ty) => {
931 self.print_associated_type(ii.ident, None, Some(ty));
933 hir::ImplItemKind::OpaqueTy(bounds) => {
934 self.word_space("type");
935 self.print_ident(ii.ident);
936 self.print_bounds("= impl", bounds);
940 self.ann.post(self, AnnNode::SubItem(ii.hir_id))
943 pub fn print_local(&mut self, init: Option<&hir::Expr<'_>>, decl: impl Fn(&mut Self)) {
944 self.space_if_not_bol();
945 self.ibox(INDENT_UNIT);
946 self.word_nbsp("let");
948 self.ibox(INDENT_UNIT);
952 if let Some(ref init) = init {
954 self.word_space("=");
955 self.print_expr(&init);
960 pub fn print_stmt(&mut self, st: &hir::Stmt<'_>) {
961 self.maybe_print_comment(st.span.lo());
963 hir::StmtKind::Local(ref loc) => {
964 self.print_local(loc.init.as_deref(), |this| this.print_local_decl(&loc));
966 hir::StmtKind::Item(item) => self.ann.nested(self, Nested::Item(item)),
967 hir::StmtKind::Expr(ref expr) => {
968 self.space_if_not_bol();
969 self.print_expr(&expr);
971 hir::StmtKind::Semi(ref expr) => {
972 self.space_if_not_bol();
973 self.print_expr(&expr);
977 if stmt_ends_with_semi(&st.kind) {
980 self.maybe_print_trailing_comment(st.span, None)
983 pub fn print_block(&mut self, blk: &hir::Block<'_>) {
984 self.print_block_with_attrs(blk, &[])
987 pub fn print_block_unclosed(&mut self, blk: &hir::Block<'_>) {
988 self.print_block_maybe_unclosed(blk, &[], false)
991 pub fn print_block_with_attrs(&mut self, blk: &hir::Block<'_>, attrs: &[ast::Attribute]) {
992 self.print_block_maybe_unclosed(blk, attrs, true)
995 pub fn print_block_maybe_unclosed(
997 blk: &hir::Block<'_>,
998 attrs: &[ast::Attribute],
1002 hir::UnsafeBlock(..) => self.word_space("unsafe"),
1003 hir::PushUnsafeBlock(..) => self.word_space("push_unsafe"),
1004 hir::PopUnsafeBlock(..) => self.word_space("pop_unsafe"),
1005 hir::DefaultBlock => (),
1007 self.maybe_print_comment(blk.span.lo());
1008 self.ann.pre(self, AnnNode::Block(blk));
1011 self.print_inner_attributes(attrs);
1013 for st in blk.stmts {
1014 self.print_stmt(st);
1016 if let Some(ref expr) = blk.expr {
1017 self.space_if_not_bol();
1018 self.print_expr(&expr);
1019 self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi()));
1021 self.bclose_maybe_open(blk.span, close_box);
1022 self.ann.post(self, AnnNode::Block(blk))
1025 pub fn print_anon_const(&mut self, constant: &hir::AnonConst) {
1026 self.ann.nested(self, Nested::Body(constant.body))
1029 fn print_call_post(&mut self, args: &[hir::Expr<'_>]) {
1031 self.commasep_exprs(Inconsistent, args);
1035 pub fn print_expr_maybe_paren(&mut self, expr: &hir::Expr<'_>, prec: i8) {
1036 let needs_par = expr.precedence().order() < prec;
1040 self.print_expr(expr);
1046 /// Print an expr using syntax that's acceptable in a condition position, such as the `cond` in
1047 /// `if cond { ... }`.
1048 pub fn print_expr_as_cond(&mut self, expr: &hir::Expr<'_>) {
1049 let needs_par = match expr.kind {
1050 // These cases need parens due to the parse error observed in #26461: `if return {}`
1051 // parses as the erroneous construct `if (return {})`, not `if (return) {}`.
1052 hir::ExprKind::Closure(..) | hir::ExprKind::Ret(..) | hir::ExprKind::Break(..) => true,
1054 _ => contains_exterior_struct_lit(expr),
1060 self.print_expr(expr);
1066 fn print_expr_vec(&mut self, exprs: &[hir::Expr<'_>]) {
1067 self.ibox(INDENT_UNIT);
1069 self.commasep_exprs(Inconsistent, exprs);
1074 fn print_expr_repeat(&mut self, element: &hir::Expr<'_>, count: &hir::AnonConst) {
1075 self.ibox(INDENT_UNIT);
1077 self.print_expr(element);
1078 self.word_space(";");
1079 self.print_anon_const(count);
1084 fn print_expr_struct(
1086 qpath: &hir::QPath<'_>,
1087 fields: &[hir::Field<'_>],
1088 wth: &Option<&'hir hir::Expr<'_>>,
1090 self.print_qpath(qpath, true);
1096 s.ibox(INDENT_UNIT);
1097 if !field.is_shorthand {
1098 s.print_ident(field.ident);
1101 s.print_expr(&field.expr);
1108 self.ibox(INDENT_UNIT);
1109 if !fields.is_empty() {
1114 self.print_expr(&expr);
1118 if !fields.is_empty() {
1126 fn print_expr_tup(&mut self, exprs: &[hir::Expr<'_>]) {
1128 self.commasep_exprs(Inconsistent, exprs);
1129 if exprs.len() == 1 {
1135 fn print_expr_call(&mut self, func: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
1136 let prec = match func.kind {
1137 hir::ExprKind::Field(..) => parser::PREC_FORCE_PAREN,
1138 _ => parser::PREC_POSTFIX,
1141 self.print_expr_maybe_paren(func, prec);
1142 self.print_call_post(args)
1145 fn print_expr_method_call(&mut self, segment: &hir::PathSegment<'_>, args: &[hir::Expr<'_>]) {
1146 let base_args = &args[1..];
1147 self.print_expr_maybe_paren(&args[0], parser::PREC_POSTFIX);
1149 self.print_ident(segment.ident);
1151 let generic_args = segment.generic_args();
1152 if !generic_args.args.is_empty() || !generic_args.bindings.is_empty() {
1153 self.print_generic_args(generic_args, segment.infer_args, true);
1156 self.print_call_post(base_args)
1159 fn print_expr_binary(&mut self, op: hir::BinOp, lhs: &hir::Expr<'_>, rhs: &hir::Expr<'_>) {
1160 let assoc_op = bin_op_to_assoc_op(op.node);
1161 let prec = assoc_op.precedence() as i8;
1162 let fixity = assoc_op.fixity();
1164 let (left_prec, right_prec) = match fixity {
1165 Fixity::Left => (prec, prec + 1),
1166 Fixity::Right => (prec + 1, prec),
1167 Fixity::None => (prec + 1, prec + 1),
1170 let left_prec = match (&lhs.kind, op.node) {
1171 // These cases need parens: `x as i32 < y` has the parser thinking that `i32 < y` is
1172 // the beginning of a path type. It starts trying to parse `x as (i32 < y ...` instead
1173 // of `(x as i32) < ...`. We need to convince it _not_ to do that.
1174 (&hir::ExprKind::Cast { .. }, hir::BinOpKind::Lt)
1175 | (&hir::ExprKind::Cast { .. }, hir::BinOpKind::Shl) => parser::PREC_FORCE_PAREN,
1179 self.print_expr_maybe_paren(lhs, left_prec);
1181 self.word_space(op.node.as_str());
1182 self.print_expr_maybe_paren(rhs, right_prec)
1185 fn print_expr_unary(&mut self, op: hir::UnOp, expr: &hir::Expr<'_>) {
1186 self.s.word(op.as_str());
1187 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1190 fn print_expr_addr_of(
1192 kind: hir::BorrowKind,
1193 mutability: hir::Mutability,
1194 expr: &hir::Expr<'_>,
1198 hir::BorrowKind::Ref => self.print_mutability(mutability, false),
1199 hir::BorrowKind::Raw => {
1200 self.word_nbsp("raw");
1201 self.print_mutability(mutability, true);
1204 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1207 fn print_literal(&mut self, lit: &hir::Lit) {
1208 self.maybe_print_comment(lit.span.lo());
1209 self.word(lit.node.to_lit_token().to_string())
1212 pub fn print_expr(&mut self, expr: &hir::Expr<'_>) {
1213 self.maybe_print_comment(expr.span.lo());
1214 self.print_outer_attributes(&expr.attrs);
1215 self.ibox(INDENT_UNIT);
1216 self.ann.pre(self, AnnNode::Expr(expr));
1218 hir::ExprKind::Box(ref expr) => {
1219 self.word_space("box");
1220 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX);
1222 hir::ExprKind::Array(ref exprs) => {
1223 self.print_expr_vec(exprs);
1225 hir::ExprKind::Repeat(ref element, ref count) => {
1226 self.print_expr_repeat(&element, count);
1228 hir::ExprKind::Struct(ref qpath, fields, ref wth) => {
1229 self.print_expr_struct(qpath, fields, wth);
1231 hir::ExprKind::Tup(ref exprs) => {
1232 self.print_expr_tup(exprs);
1234 hir::ExprKind::Call(ref func, ref args) => {
1235 self.print_expr_call(&func, args);
1237 hir::ExprKind::MethodCall(ref segment, _, ref args) => {
1238 self.print_expr_method_call(segment, args);
1240 hir::ExprKind::Binary(op, ref lhs, ref rhs) => {
1241 self.print_expr_binary(op, &lhs, &rhs);
1243 hir::ExprKind::Unary(op, ref expr) => {
1244 self.print_expr_unary(op, &expr);
1246 hir::ExprKind::AddrOf(k, m, ref expr) => {
1247 self.print_expr_addr_of(k, m, &expr);
1249 hir::ExprKind::Lit(ref lit) => {
1250 self.print_literal(&lit);
1252 hir::ExprKind::Cast(ref expr, ref ty) => {
1253 let prec = AssocOp::As.precedence() as i8;
1254 self.print_expr_maybe_paren(&expr, prec);
1256 self.word_space("as");
1257 self.print_type(&ty);
1259 hir::ExprKind::Type(ref expr, ref ty) => {
1260 let prec = AssocOp::Colon.precedence() as i8;
1261 self.print_expr_maybe_paren(&expr, prec);
1262 self.word_space(":");
1263 self.print_type(&ty);
1265 hir::ExprKind::DropTemps(ref init) => {
1267 self.cbox(INDENT_UNIT);
1271 // Print `let _t = $init;`:
1272 let temp = ast::Ident::from_str("_t");
1273 self.print_local(Some(init), |this| this.print_ident(temp));
1277 self.space_if_not_bol();
1278 self.print_ident(temp);
1281 self.bclose_maybe_open(expr.span, true);
1283 hir::ExprKind::Loop(ref blk, opt_label, _) => {
1284 if let Some(label) = opt_label {
1285 self.print_ident(label.ident);
1286 self.word_space(":");
1290 self.print_block(&blk);
1292 hir::ExprKind::Match(ref expr, arms, _) => {
1293 self.cbox(INDENT_UNIT);
1294 self.ibox(INDENT_UNIT);
1295 self.word_nbsp("match");
1296 self.print_expr_as_cond(&expr);
1300 self.print_arm(arm);
1302 self.bclose(expr.span);
1304 hir::ExprKind::Closure(capture_clause, ref decl, body, _fn_decl_span, _gen) => {
1305 self.print_capture_clause(capture_clause);
1307 self.print_closure_params(&decl, body);
1310 // This is a bare expression.
1311 self.ann.nested(self, Nested::Body(body));
1312 self.end(); // need to close a box
1314 // A box will be closed by `print_expr`, but we didn't want an overall
1315 // wrapper so we closed the corresponding opening. so create an
1316 // empty box to satisfy the close.
1319 hir::ExprKind::Block(ref blk, opt_label) => {
1320 if let Some(label) = opt_label {
1321 self.print_ident(label.ident);
1322 self.word_space(":");
1324 // containing cbox, will be closed by print-block at `}`
1325 self.cbox(INDENT_UNIT);
1326 // head-box, will be closed by print-block after `{`
1328 self.print_block(&blk);
1330 hir::ExprKind::Assign(ref lhs, ref rhs, _) => {
1331 let prec = AssocOp::Assign.precedence() as i8;
1332 self.print_expr_maybe_paren(&lhs, prec + 1);
1334 self.word_space("=");
1335 self.print_expr_maybe_paren(&rhs, prec);
1337 hir::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
1338 let prec = AssocOp::Assign.precedence() as i8;
1339 self.print_expr_maybe_paren(&lhs, prec + 1);
1341 self.s.word(op.node.as_str());
1342 self.word_space("=");
1343 self.print_expr_maybe_paren(&rhs, prec);
1345 hir::ExprKind::Field(ref expr, ident) => {
1346 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
1348 self.print_ident(ident);
1350 hir::ExprKind::Index(ref expr, ref index) => {
1351 self.print_expr_maybe_paren(&expr, parser::PREC_POSTFIX);
1353 self.print_expr(&index);
1356 hir::ExprKind::Path(ref qpath) => self.print_qpath(qpath, true),
1357 hir::ExprKind::Break(destination, ref opt_expr) => {
1358 self.s.word("break");
1360 if let Some(label) = destination.label {
1361 self.print_ident(label.ident);
1364 if let Some(ref expr) = *opt_expr {
1365 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
1369 hir::ExprKind::Continue(destination) => {
1370 self.s.word("continue");
1372 if let Some(label) = destination.label {
1373 self.print_ident(label.ident);
1377 hir::ExprKind::Ret(ref result) => {
1378 self.s.word("return");
1379 if let Some(ref expr) = *result {
1381 self.print_expr_maybe_paren(&expr, parser::PREC_JUMP);
1384 hir::ExprKind::InlineAsm(ref a) => {
1386 self.s.word("asm!");
1388 self.print_string(&i.asm.as_str(), i.asm_str_style);
1389 self.word_space(":");
1391 let mut out_idx = 0;
1392 self.commasep(Inconsistent, &i.outputs, |s, out| {
1393 let constraint = out.constraint.as_str();
1394 let mut ch = constraint.chars();
1396 Some('=') if out.is_rw => {
1397 s.print_string(&format!("+{}", ch.as_str()), ast::StrStyle::Cooked)
1399 _ => s.print_string(&constraint, ast::StrStyle::Cooked),
1402 s.print_expr(&a.outputs_exprs[out_idx]);
1407 self.word_space(":");
1410 self.commasep(Inconsistent, &i.inputs, |s, co| {
1411 s.print_string(&co.as_str(), ast::StrStyle::Cooked);
1413 s.print_expr(&a.inputs_exprs[in_idx]);
1418 self.word_space(":");
1420 self.commasep(Inconsistent, &i.clobbers, |s, co| {
1421 s.print_string(&co.as_str(), ast::StrStyle::Cooked);
1424 let mut options = vec![];
1426 options.push("volatile");
1429 options.push("alignstack");
1431 if i.dialect == ast::AsmDialect::Intel {
1432 options.push("intel");
1435 if !options.is_empty() {
1437 self.word_space(":");
1438 self.commasep(Inconsistent, &options, |s, &co| {
1439 s.print_string(co, ast::StrStyle::Cooked);
1445 hir::ExprKind::Yield(ref expr, _) => {
1446 self.word_space("yield");
1447 self.print_expr_maybe_paren(&expr, parser::PREC_JUMP);
1449 hir::ExprKind::Err => {
1451 self.s.word("/*ERROR*/");
1455 self.ann.post(self, AnnNode::Expr(expr));
1459 pub fn print_local_decl(&mut self, loc: &hir::Local<'_>) {
1460 self.print_pat(&loc.pat);
1461 if let Some(ref ty) = loc.ty {
1462 self.word_space(":");
1463 self.print_type(&ty);
1467 pub fn print_usize(&mut self, i: usize) {
1468 self.s.word(i.to_string())
1471 pub fn print_name(&mut self, name: ast::Name) {
1472 self.print_ident(ast::Ident::with_dummy_span(name))
1475 pub fn print_for_decl(&mut self, loc: &hir::Local<'_>, coll: &hir::Expr<'_>) {
1476 self.print_local_decl(loc);
1478 self.word_space("in");
1479 self.print_expr(coll)
1482 pub fn print_path(&mut self, path: &hir::Path<'_>, colons_before_params: bool) {
1483 self.maybe_print_comment(path.span.lo());
1485 for (i, segment) in path.segments.iter().enumerate() {
1489 if segment.ident.name != kw::PathRoot {
1490 self.print_ident(segment.ident);
1491 self.print_generic_args(
1492 segment.generic_args(),
1494 colons_before_params,
1500 pub fn print_path_segment(&mut self, segment: &hir::PathSegment<'_>) {
1501 if segment.ident.name != kw::PathRoot {
1502 self.print_ident(segment.ident);
1503 self.print_generic_args(segment.generic_args(), segment.infer_args, false);
1507 pub fn print_qpath(&mut self, qpath: &hir::QPath<'_>, colons_before_params: bool) {
1509 hir::QPath::Resolved(None, ref path) => self.print_path(path, colons_before_params),
1510 hir::QPath::Resolved(Some(ref qself), ref path) => {
1512 self.print_type(qself);
1514 self.word_space("as");
1516 for (i, segment) in path.segments[..path.segments.len() - 1].iter().enumerate() {
1520 if segment.ident.name != kw::PathRoot {
1521 self.print_ident(segment.ident);
1522 self.print_generic_args(
1523 segment.generic_args(),
1525 colons_before_params,
1532 let item_segment = path.segments.last().unwrap();
1533 self.print_ident(item_segment.ident);
1534 self.print_generic_args(
1535 item_segment.generic_args(),
1536 item_segment.infer_args,
1537 colons_before_params,
1540 hir::QPath::TypeRelative(ref qself, ref item_segment) => {
1541 // If we've got a compound-qualified-path, let's push an additional pair of angle
1542 // brackets, so that we pretty-print `<<A::B>::C>` as `<A::B>::C`, instead of just
1543 // `A::B::C` (since the latter could be ambiguous to the user)
1544 if let hir::TyKind::Path(hir::QPath::Resolved(None, _)) = &qself.kind {
1545 self.print_type(qself);
1548 self.print_type(qself);
1553 self.print_ident(item_segment.ident);
1554 self.print_generic_args(
1555 item_segment.generic_args(),
1556 item_segment.infer_args,
1557 colons_before_params,
1563 fn print_generic_args(
1565 generic_args: &hir::GenericArgs<'_>,
1567 colons_before_params: bool,
1569 if generic_args.parenthesized {
1571 self.commasep(Inconsistent, generic_args.inputs(), |s, ty| s.print_type(&ty));
1574 self.space_if_not_bol();
1575 self.word_space("->");
1576 self.print_type(generic_args.bindings[0].ty());
1578 let start = if colons_before_params { "::<" } else { "<" };
1579 let empty = Cell::new(true);
1580 let start_or_comma = |this: &mut Self| {
1585 this.word_space(",")
1589 let mut nonelided_generic_args: bool = false;
1590 let elide_lifetimes = generic_args.args.iter().all(|arg| match arg {
1591 GenericArg::Lifetime(lt) => lt.is_elided(),
1593 nonelided_generic_args = true;
1598 if nonelided_generic_args {
1599 start_or_comma(self);
1603 |s, generic_arg| match generic_arg {
1604 GenericArg::Lifetime(lt) if !elide_lifetimes => s.print_lifetime(lt),
1605 GenericArg::Lifetime(_) => {}
1606 GenericArg::Type(ty) => s.print_type(ty),
1607 GenericArg::Const(ct) => s.print_anon_const(&ct.value),
1612 // FIXME(eddyb): this would leak into error messages (e.g.,
1613 // "non-exhaustive patterns: `Some::<..>(_)` not covered").
1614 if infer_args && false {
1615 start_or_comma(self);
1619 for binding in generic_args.bindings.iter() {
1620 start_or_comma(self);
1621 self.print_ident(binding.ident);
1623 match generic_args.bindings[0].kind {
1624 hir::TypeBindingKind::Equality { ref ty } => {
1625 self.word_space("=");
1626 self.print_type(ty);
1628 hir::TypeBindingKind::Constraint { bounds } => {
1629 self.print_bounds(":", bounds);
1640 pub fn print_pat(&mut self, pat: &hir::Pat<'_>) {
1641 self.maybe_print_comment(pat.span.lo());
1642 self.ann.pre(self, AnnNode::Pat(pat));
1643 // Pat isn't normalized, but the beauty of it
1644 // is that it doesn't matter
1646 PatKind::Wild => self.s.word("_"),
1647 PatKind::Binding(binding_mode, _, ident, ref sub) => {
1648 match binding_mode {
1649 hir::BindingAnnotation::Ref => {
1650 self.word_nbsp("ref");
1651 self.print_mutability(hir::Mutability::Not, false);
1653 hir::BindingAnnotation::RefMut => {
1654 self.word_nbsp("ref");
1655 self.print_mutability(hir::Mutability::Mut, false);
1657 hir::BindingAnnotation::Unannotated => {}
1658 hir::BindingAnnotation::Mutable => {
1659 self.word_nbsp("mut");
1662 self.print_ident(ident);
1663 if let Some(ref p) = *sub {
1668 PatKind::TupleStruct(ref qpath, ref elts, ddpos) => {
1669 self.print_qpath(qpath, true);
1671 if let Some(ddpos) = ddpos {
1672 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p));
1674 self.word_space(",");
1677 if ddpos != elts.len() {
1679 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p));
1682 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p));
1686 PatKind::Path(ref qpath) => {
1687 self.print_qpath(qpath, true);
1689 PatKind::Struct(ref qpath, ref fields, etc) => {
1690 self.print_qpath(qpath, true);
1692 self.word_space("{");
1697 s.cbox(INDENT_UNIT);
1698 if !f.is_shorthand {
1699 s.print_ident(f.ident);
1702 s.print_pat(&f.pat);
1708 if !fields.is_empty() {
1709 self.word_space(",");
1716 PatKind::Or(ref pats) => {
1717 self.strsep("|", true, Inconsistent, &pats[..], |s, p| s.print_pat(&p));
1719 PatKind::Tuple(ref elts, ddpos) => {
1721 if let Some(ddpos) = ddpos {
1722 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p));
1724 self.word_space(",");
1727 if ddpos != elts.len() {
1729 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p));
1732 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p));
1733 if elts.len() == 1 {
1739 PatKind::Box(ref inner) => {
1740 let is_range_inner = match inner.kind {
1741 PatKind::Range(..) => true,
1744 self.s.word("box ");
1748 self.print_pat(&inner);
1753 PatKind::Ref(ref inner, mutbl) => {
1754 let is_range_inner = match inner.kind {
1755 PatKind::Range(..) => true,
1759 self.s.word(mutbl.prefix_str());
1763 self.print_pat(&inner);
1768 PatKind::Lit(ref e) => self.print_expr(&e),
1769 PatKind::Range(ref begin, ref end, ref end_kind) => {
1770 if let Some(expr) = begin {
1771 self.print_expr(expr);
1775 RangeEnd::Included => self.s.word("..."),
1776 RangeEnd::Excluded => self.s.word(".."),
1778 if let Some(expr) = end {
1779 self.print_expr(expr);
1782 PatKind::Slice(ref before, ref slice, ref after) => {
1784 self.commasep(Inconsistent, &before[..], |s, p| s.print_pat(&p));
1785 if let Some(ref p) = *slice {
1786 if !before.is_empty() {
1787 self.word_space(",");
1789 if let PatKind::Wild = p.kind {
1795 if !after.is_empty() {
1796 self.word_space(",");
1799 self.commasep(Inconsistent, &after[..], |s, p| s.print_pat(&p));
1803 self.ann.post(self, AnnNode::Pat(pat))
1806 pub fn print_param(&mut self, arg: &hir::Param<'_>) {
1807 self.print_outer_attributes(&arg.attrs);
1808 self.print_pat(&arg.pat);
1811 pub fn print_arm(&mut self, arm: &hir::Arm<'_>) {
1812 // I have no idea why this check is necessary, but here it
1814 if arm.attrs.is_empty() {
1817 self.cbox(INDENT_UNIT);
1818 self.ann.pre(self, AnnNode::Arm(arm));
1820 self.print_outer_attributes(&arm.attrs);
1821 self.print_pat(&arm.pat);
1823 if let Some(ref g) = arm.guard {
1825 hir::Guard::If(e) => {
1826 self.word_space("if");
1827 self.print_expr(&e);
1832 self.word_space("=>");
1834 match arm.body.kind {
1835 hir::ExprKind::Block(ref blk, opt_label) => {
1836 if let Some(label) = opt_label {
1837 self.print_ident(label.ident);
1838 self.word_space(":");
1840 // the block will close the pattern's ibox
1841 self.print_block_unclosed(&blk);
1843 // If it is a user-provided unsafe block, print a comma after it
1844 if let hir::UnsafeBlock(hir::UserProvided) = blk.rules {
1849 self.end(); // close the ibox for the pattern
1850 self.print_expr(&arm.body);
1854 self.ann.post(self, AnnNode::Arm(arm));
1855 self.end() // close enclosing cbox
1860 decl: &hir::FnDecl<'_>,
1861 header: hir::FnHeader,
1862 name: Option<ast::Name>,
1863 generics: &hir::Generics<'_>,
1864 vis: &hir::Visibility<'_>,
1865 arg_names: &[ast::Ident],
1866 body_id: Option<hir::BodyId>,
1868 self.print_fn_header_info(header, vis);
1870 if let Some(name) = name {
1872 self.print_name(name);
1874 self.print_generic_params(&generics.params);
1878 // Make sure we aren't supplied *both* `arg_names` and `body_id`.
1879 assert!(arg_names.is_empty() || body_id.is_none());
1880 self.commasep(Inconsistent, &decl.inputs, |s, ty| {
1881 s.ibox(INDENT_UNIT);
1882 if let Some(arg_name) = arg_names.get(i) {
1883 s.s.word(arg_name.to_string());
1886 } else if let Some(body_id) = body_id {
1887 s.ann.nested(s, Nested::BodyParamPat(body_id, i));
1895 if decl.c_variadic {
1896 self.s.word(", ...");
1900 self.print_fn_output(decl);
1901 self.print_where_clause(&generics.where_clause)
1904 fn print_closure_params(&mut self, decl: &hir::FnDecl<'_>, body_id: hir::BodyId) {
1907 self.commasep(Inconsistent, &decl.inputs, |s, ty| {
1908 s.ibox(INDENT_UNIT);
1910 s.ann.nested(s, Nested::BodyParamPat(body_id, i));
1913 if let hir::TyKind::Infer = ty.kind {
1924 if let hir::DefaultReturn(..) = decl.output {
1928 self.space_if_not_bol();
1929 self.word_space("->");
1931 hir::Return(ref ty) => {
1932 self.print_type(&ty);
1933 self.maybe_print_comment(ty.span.lo())
1935 hir::DefaultReturn(..) => unreachable!(),
1939 pub fn print_capture_clause(&mut self, capture_clause: hir::CaptureBy) {
1940 match capture_clause {
1941 hir::CaptureBy::Value => self.word_space("move"),
1942 hir::CaptureBy::Ref => {}
1946 pub fn print_bounds<'b>(
1948 prefix: &'static str,
1949 bounds: impl IntoIterator<Item = &'b hir::GenericBound<'b>>,
1951 let mut first = true;
1952 for bound in bounds {
1954 self.s.word(prefix);
1956 if !(first && prefix.is_empty()) {
1962 self.word_space("+");
1966 GenericBound::Trait(tref, modifier) => {
1967 if modifier == &TraitBoundModifier::Maybe {
1970 self.print_poly_trait_ref(tref);
1972 GenericBound::Outlives(lt) => {
1973 self.print_lifetime(lt);
1979 pub fn print_generic_params(&mut self, generic_params: &[GenericParam<'_>]) {
1980 if !generic_params.is_empty() {
1983 self.commasep(Inconsistent, generic_params, |s, param| s.print_generic_param(param));
1989 pub fn print_generic_param(&mut self, param: &GenericParam<'_>) {
1990 if let GenericParamKind::Const { .. } = param.kind {
1991 self.word_space("const");
1994 self.print_ident(param.name.ident());
1997 GenericParamKind::Lifetime { .. } => {
1999 for bound in param.bounds {
2001 GenericBound::Outlives(ref lt) => {
2003 self.print_lifetime(lt);
2010 GenericParamKind::Type { ref default, .. } => {
2011 self.print_bounds(":", param.bounds);
2015 self.word_space("=");
2016 self.print_type(&default)
2021 GenericParamKind::Const { ref ty } => {
2022 self.word_space(":");
2028 pub fn print_lifetime(&mut self, lifetime: &hir::Lifetime) {
2029 self.print_ident(lifetime.name.ident())
2032 pub fn print_where_clause(&mut self, where_clause: &hir::WhereClause<'_>) {
2033 if where_clause.predicates.is_empty() {
2038 self.word_space("where");
2040 for (i, predicate) in where_clause.predicates.iter().enumerate() {
2042 self.word_space(",");
2046 &hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
2047 ref bound_generic_params,
2052 self.print_formal_generic_params(bound_generic_params);
2053 self.print_type(&bounded_ty);
2054 self.print_bounds(":", bounds);
2056 &hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
2061 self.print_lifetime(lifetime);
2064 for (i, bound) in bounds.iter().enumerate() {
2066 GenericBound::Outlives(lt) => {
2067 self.print_lifetime(lt);
2077 &hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
2082 self.print_type(lhs_ty);
2084 self.word_space("=");
2085 self.print_type(rhs_ty);
2091 pub fn print_mutability(&mut self, mutbl: hir::Mutability, print_const: bool) {
2093 hir::Mutability::Mut => self.word_nbsp("mut"),
2094 hir::Mutability::Not => {
2096 self.word_nbsp("const")
2102 pub fn print_mt(&mut self, mt: &hir::MutTy<'_>, print_const: bool) {
2103 self.print_mutability(mt.mutbl, print_const);
2104 self.print_type(&mt.ty)
2107 pub fn print_fn_output(&mut self, decl: &hir::FnDecl<'_>) {
2108 if let hir::DefaultReturn(..) = decl.output {
2112 self.space_if_not_bol();
2113 self.ibox(INDENT_UNIT);
2114 self.word_space("->");
2116 hir::DefaultReturn(..) => unreachable!(),
2117 hir::Return(ref ty) => self.print_type(&ty),
2122 hir::Return(ref output) => self.maybe_print_comment(output.span.lo()),
2130 unsafety: hir::Unsafety,
2131 decl: &hir::FnDecl<'_>,
2132 name: Option<ast::Name>,
2133 generic_params: &[hir::GenericParam<'_>],
2134 arg_names: &[ast::Ident],
2136 self.ibox(INDENT_UNIT);
2137 if !generic_params.is_empty() {
2139 self.print_generic_params(generic_params);
2141 let generics = hir::Generics {
2143 where_clause: hir::WhereClause { predicates: &[], span: rustc_span::DUMMY_SP },
2144 span: rustc_span::DUMMY_SP,
2151 constness: hir::Constness::NotConst,
2152 asyncness: hir::IsAsync::NotAsync,
2156 &Spanned { span: rustc_span::DUMMY_SP, node: hir::VisibilityKind::Inherited },
2163 pub fn maybe_print_trailing_comment(
2165 span: rustc_span::Span,
2166 next_pos: Option<BytePos>,
2168 if let Some(cmnts) = self.comments() {
2169 if let Some(cmnt) = cmnts.trailing_comment(span, next_pos) {
2170 self.print_comment(&cmnt);
2175 pub fn print_remaining_comments(&mut self) {
2176 // If there aren't any remaining comments, then we need to manually
2177 // make sure there is a line break at the end.
2178 if self.next_comment().is_none() {
2181 while let Some(ref cmnt) = self.next_comment() {
2182 self.print_comment(cmnt)
2186 pub fn print_opt_abi_and_extern_if_nondefault(&mut self, opt_abi: Option<Abi>) {
2188 Some(Abi::Rust) => {}
2190 self.word_nbsp("extern");
2191 self.word_nbsp(abi.to_string())
2197 pub fn print_extern_opt_abi(&mut self, opt_abi: Option<Abi>) {
2200 self.word_nbsp("extern");
2201 self.word_nbsp(abi.to_string())
2207 pub fn print_fn_header_info(&mut self, header: hir::FnHeader, vis: &hir::Visibility<'_>) {
2208 self.s.word(visibility_qualified(vis, ""));
2210 match header.constness {
2211 hir::Constness::NotConst => {}
2212 hir::Constness::Const => self.word_nbsp("const"),
2215 match header.asyncness {
2216 hir::IsAsync::NotAsync => {}
2217 hir::IsAsync::Async => self.word_nbsp("async"),
2220 self.print_unsafety(header.unsafety);
2222 if header.abi != Abi::Rust {
2223 self.word_nbsp("extern");
2224 self.word_nbsp(header.abi.to_string());
2230 pub fn print_unsafety(&mut self, s: hir::Unsafety) {
2232 hir::Unsafety::Normal => {}
2233 hir::Unsafety::Unsafe => self.word_nbsp("unsafe"),
2237 pub fn print_is_auto(&mut self, s: hir::IsAuto) {
2239 hir::IsAuto::Yes => self.word_nbsp("auto"),
2240 hir::IsAuto::No => {}
2245 /// Does this expression require a semicolon to be treated
2246 /// as a statement? The negation of this: 'can this expression
2247 /// be used as a statement without a semicolon' -- is used
2248 /// as an early-bail-out in the parser so that, for instance,
2249 /// if true {...} else {...}
2251 /// isn't parsed as (if true {...} else {...} | x) | 5
2253 // Duplicated from `parse::classify`, but adapted for the HIR.
2254 fn expr_requires_semi_to_be_stmt(e: &hir::Expr<'_>) -> bool {
2256 hir::ExprKind::Match(..) | hir::ExprKind::Block(..) | hir::ExprKind::Loop(..) => false,
2261 /// This statement requires a semicolon after it.
2262 /// note that in one case (stmt_semi), we've already
2263 /// seen the semicolon, and thus don't need another.
2264 fn stmt_ends_with_semi(stmt: &hir::StmtKind<'_>) -> bool {
2266 hir::StmtKind::Local(_) => true,
2267 hir::StmtKind::Item(_) => false,
2268 hir::StmtKind::Expr(ref e) => expr_requires_semi_to_be_stmt(&e),
2269 hir::StmtKind::Semi(..) => false,
2273 fn bin_op_to_assoc_op(op: hir::BinOpKind) -> AssocOp {
2274 use crate::hir::BinOpKind::*;
2276 Add => AssocOp::Add,
2277 Sub => AssocOp::Subtract,
2278 Mul => AssocOp::Multiply,
2279 Div => AssocOp::Divide,
2280 Rem => AssocOp::Modulus,
2282 And => AssocOp::LAnd,
2285 BitXor => AssocOp::BitXor,
2286 BitAnd => AssocOp::BitAnd,
2287 BitOr => AssocOp::BitOr,
2288 Shl => AssocOp::ShiftLeft,
2289 Shr => AssocOp::ShiftRight,
2291 Eq => AssocOp::Equal,
2292 Lt => AssocOp::Less,
2293 Le => AssocOp::LessEqual,
2294 Ne => AssocOp::NotEqual,
2295 Ge => AssocOp::GreaterEqual,
2296 Gt => AssocOp::Greater,
2300 /// Expressions that syntactically contain an "exterior" struct literal, i.e., not surrounded by any
2301 /// parens or other delimiters, e.g., `X { y: 1 }`, `X { y: 1 }.method()`, `foo == X { y: 1 }` and
2302 /// `X { y: 1 } == foo` all do, but `(X { y: 1 }) == foo` does not.
2303 fn contains_exterior_struct_lit(value: &hir::Expr<'_>) -> bool {
2305 hir::ExprKind::Struct(..) => true,
2307 hir::ExprKind::Assign(ref lhs, ref rhs, _)
2308 | hir::ExprKind::AssignOp(_, ref lhs, ref rhs)
2309 | hir::ExprKind::Binary(_, ref lhs, ref rhs) => {
2310 // `X { y: 1 } + X { y: 2 }`
2311 contains_exterior_struct_lit(&lhs) || contains_exterior_struct_lit(&rhs)
2313 hir::ExprKind::Unary(_, ref x)
2314 | hir::ExprKind::Cast(ref x, _)
2315 | hir::ExprKind::Type(ref x, _)
2316 | hir::ExprKind::Field(ref x, _)
2317 | hir::ExprKind::Index(ref x, _) => {
2318 // `&X { y: 1 }, X { y: 1 }.y`
2319 contains_exterior_struct_lit(&x)
2322 hir::ExprKind::MethodCall(.., ref exprs) => {
2323 // `X { y: 1 }.bar(...)`
2324 contains_exterior_struct_lit(&exprs[0])