1 use rustc_target::spec::abi::Abi;
3 use syntax::print::pp::Breaks::{Consistent, Inconsistent};
4 use syntax::print::pp::{self, Breaks};
5 use syntax::print::pprust::{self, Comments, PrintState};
6 use syntax::sess::ParseSess;
7 use syntax::source_map::{SourceMap, Spanned};
8 use syntax::symbol::kw;
9 use syntax::util::parser::{self, AssocOp, Fixity};
10 use syntax_pos::{self, BytePos, FileName};
13 use crate::hir::{GenericArg, GenericParam, GenericParamKind};
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),
72 impl std::ops::Deref for State<'_> {
73 type Target = pp::Printer;
74 fn deref(&self) -> &Self::Target {
79 impl std::ops::DerefMut for State<'_> {
80 fn deref_mut(&mut self) -> &mut Self::Target {
85 impl<'a> PrintState<'a> for State<'a> {
86 fn comments(&mut self) -> &mut Option<Comments<'a>> {
90 fn print_ident(&mut self, ident: ast::Ident) {
91 self.s.word(pprust::ast_ident_to_string(ident, ident.is_raw_guess()));
92 self.ann.post(self, AnnNode::Name(&ident.name))
95 fn print_generic_args(&mut self, args: &ast::GenericArgs, _colons_before_params: bool) {
96 span_bug!(args.span(), "AST generic args printed by HIR pretty-printer");
100 pub const INDENT_UNIT: usize = 4;
102 /// Requires you to pass an input filename and reader so that
103 /// it can scan the input text for comments to copy forward.
104 pub fn print_crate<'a>(
107 krate: &hir::Crate<'_>,
112 let mut s = State::new_from_input(cm, sess, filename, input, ann);
114 // When printing the AST, we sometimes need to inject `#[no_std]` here.
115 // Since you can't compile the HIR, it's not necessary.
117 s.print_mod(&krate.module, &krate.attrs);
118 s.print_remaining_comments();
123 pub fn new_from_input(
130 State { s: pp::mk_printer(), comments: Some(Comments::new(cm, sess, filename, input)), ann }
134 pub fn to_string<F>(ann: &dyn PpAnn, f: F) -> String
136 F: FnOnce(&mut State<'_>),
138 let mut printer = State { s: pp::mk_printer(), comments: None, ann };
143 pub fn visibility_qualified<S: Into<Cow<'static, str>>>(vis: &hir::Visibility<'_>, w: S) -> String {
144 to_string(NO_ANN, |s| {
145 s.print_visibility(vis);
151 pub fn cbox(&mut self, u: usize) {
155 pub fn nbsp(&mut self) {
159 pub fn word_nbsp<S: Into<Cow<'static, str>>>(&mut self, w: S) {
164 pub fn head<S: Into<Cow<'static, str>>>(&mut self, w: S) {
166 // outer-box is consistent
167 self.cbox(INDENT_UNIT);
168 // head-box is inconsistent
169 self.ibox(w.len() + 1);
170 // keyword that starts the head
176 pub fn bopen(&mut self) {
178 self.end(); // close the head-box
181 pub fn bclose_maybe_open(&mut self, span: syntax_pos::Span, close_box: bool) {
182 self.maybe_print_comment(span.hi());
183 self.break_offset_if_not_bol(1, -(INDENT_UNIT as isize));
186 self.end(); // close the outer-box
190 pub fn bclose(&mut self, span: syntax_pos::Span) {
191 self.bclose_maybe_open(span, true)
194 pub fn space_if_not_bol(&mut self) {
195 if !self.s.is_beginning_of_line() {
200 pub fn break_offset_if_not_bol(&mut self, n: usize, off: isize) {
201 if !self.s.is_beginning_of_line() {
202 self.s.break_offset(n, off)
204 if off != 0 && self.s.last_token().is_hardbreak_tok() {
205 // We do something pretty sketchy here: tuck the nonzero
206 // offset-adjustment we were going to deposit along with the
207 // break into the previous hardbreak.
208 self.s.replace_last_token(pp::Printer::hardbreak_tok_offset(off));
213 // Synthesizes a comment that was not textually present in the original source
215 pub fn synth_comment(&mut self, text: String) {
223 pub fn commasep_cmnt<T, F, G>(&mut self, b: Breaks, elts: &[T], mut op: F, mut get_span: G)
225 F: FnMut(&mut State<'_>, &T),
226 G: FnMut(&T) -> syntax_pos::Span,
229 let len = elts.len();
232 self.maybe_print_comment(get_span(elt).hi());
237 self.maybe_print_trailing_comment(get_span(elt), Some(get_span(&elts[i]).hi()));
238 self.space_if_not_bol();
244 pub fn commasep_exprs(&mut self, b: Breaks, exprs: &[hir::Expr<'_>]) {
245 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(&e), |e| e.span)
248 pub fn print_mod(&mut self, _mod: &hir::Mod<'_>, attrs: &[ast::Attribute]) {
249 self.print_inner_attributes(attrs);
250 for &item_id in _mod.item_ids {
251 self.ann.nested(self, Nested::Item(item_id));
255 pub fn print_foreign_mod(&mut self, nmod: &hir::ForeignMod<'_>, attrs: &[ast::Attribute]) {
256 self.print_inner_attributes(attrs);
257 for item in nmod.items {
258 self.print_foreign_item(item);
262 pub fn print_opt_lifetime(&mut self, lifetime: &hir::Lifetime) {
263 if !lifetime.is_elided() {
264 self.print_lifetime(lifetime);
269 pub fn print_type(&mut self, ty: &hir::Ty<'_>) {
270 self.maybe_print_comment(ty.span.lo());
273 hir::TyKind::Slice(ref ty) => {
275 self.print_type(&ty);
278 hir::TyKind::Ptr(ref mt) => {
280 self.print_mt(mt, true);
282 hir::TyKind::Rptr(ref lifetime, ref mt) => {
284 self.print_opt_lifetime(lifetime);
285 self.print_mt(mt, false);
287 hir::TyKind::Never => {
290 hir::TyKind::Tup(ref elts) => {
292 self.commasep(Inconsistent, &elts[..], |s, ty| s.print_type(&ty));
298 hir::TyKind::BareFn(ref f) => {
308 hir::TyKind::Def(..) => {}
309 hir::TyKind::Path(ref qpath) => self.print_qpath(qpath, false),
310 hir::TyKind::TraitObject(ref bounds, ref lifetime) => {
311 let mut first = true;
312 for bound in bounds {
317 self.word_space("+");
319 self.print_poly_trait_ref(bound);
321 if !lifetime.is_elided() {
323 self.word_space("+");
324 self.print_lifetime(lifetime);
327 hir::TyKind::Array(ref ty, ref length) => {
329 self.print_type(&ty);
331 self.print_anon_const(length);
334 hir::TyKind::Typeof(ref e) => {
335 self.s.word("typeof(");
336 self.print_anon_const(e);
339 hir::TyKind::Infer => {
342 hir::TyKind::Err => {
344 self.s.word("/*ERROR*/");
351 pub fn print_foreign_item(&mut self, item: &hir::ForeignItem<'_>) {
352 self.hardbreak_if_not_bol();
353 self.maybe_print_comment(item.span.lo());
354 self.print_outer_attributes(&item.attrs);
356 hir::ForeignItemKind::Fn(ref decl, ref arg_names, ref generics) => {
361 unsafety: hir::Unsafety::Normal,
362 constness: hir::Constness::NotConst,
364 asyncness: hir::IsAsync::NotAsync,
366 Some(item.ident.name),
372 self.end(); // end head-ibox
374 self.end() // end the outer fn box
376 hir::ForeignItemKind::Static(ref t, m) => {
377 self.head(visibility_qualified(&item.vis, "static"));
378 if m == hir::Mutability::Mut {
379 self.word_space("mut");
381 self.print_ident(item.ident);
382 self.word_space(":");
385 self.end(); // end the head-ibox
386 self.end() // end the outer cbox
388 hir::ForeignItemKind::Type => {
389 self.head(visibility_qualified(&item.vis, "type"));
390 self.print_ident(item.ident);
392 self.end(); // end the head-ibox
393 self.end() // end the outer cbox
398 fn print_associated_const(
402 default: Option<hir::BodyId>,
403 vis: &hir::Visibility<'_>,
405 self.s.word(visibility_qualified(vis, ""));
406 self.word_space("const");
407 self.print_ident(ident);
408 self.word_space(":");
410 if let Some(expr) = default {
412 self.word_space("=");
413 self.ann.nested(self, Nested::Body(expr));
418 fn print_associated_type(
421 bounds: Option<&hir::GenericBounds<'_>>,
422 ty: Option<&hir::Ty<'_>>,
424 self.word_space("type");
425 self.print_ident(ident);
426 if let Some(bounds) = bounds {
427 self.print_bounds(":", bounds);
429 if let Some(ty) = ty {
431 self.word_space("=");
439 item: &hir::Item<'_>,
440 generics: &hir::Generics<'_>,
441 inner: impl Fn(&mut Self),
443 self.head(visibility_qualified(&item.vis, "type"));
444 self.print_ident(item.ident);
445 self.print_generic_params(&generics.params);
446 self.end(); // end the inner ibox
448 self.print_where_clause(&generics.where_clause);
452 self.end(); // end the outer ibox
455 /// Pretty-print an item
456 pub fn print_item(&mut self, item: &hir::Item<'_>) {
457 self.hardbreak_if_not_bol();
458 self.maybe_print_comment(item.span.lo());
459 self.print_outer_attributes(&item.attrs);
460 self.ann.pre(self, AnnNode::Item(item));
462 hir::ItemKind::ExternCrate(orig_name) => {
463 self.head(visibility_qualified(&item.vis, "extern crate"));
464 if let Some(orig_name) = orig_name {
465 self.print_name(orig_name);
470 self.print_ident(item.ident);
472 self.end(); // end inner head-block
473 self.end(); // end outer head-block
475 hir::ItemKind::Use(ref path, kind) => {
476 self.head(visibility_qualified(&item.vis, "use"));
477 self.print_path(path, false);
480 hir::UseKind::Single => {
481 if path.segments.last().unwrap().ident != item.ident {
483 self.word_space("as");
484 self.print_ident(item.ident);
488 hir::UseKind::Glob => self.s.word("::*;"),
489 hir::UseKind::ListStem => self.s.word("::{};"),
491 self.end(); // end inner head-block
492 self.end(); // end outer head-block
494 hir::ItemKind::Static(ref ty, m, expr) => {
495 self.head(visibility_qualified(&item.vis, "static"));
496 if m == hir::Mutability::Mut {
497 self.word_space("mut");
499 self.print_ident(item.ident);
500 self.word_space(":");
501 self.print_type(&ty);
503 self.end(); // end the head-ibox
505 self.word_space("=");
506 self.ann.nested(self, Nested::Body(expr));
508 self.end(); // end the outer cbox
510 hir::ItemKind::Const(ref ty, expr) => {
511 self.head(visibility_qualified(&item.vis, "const"));
512 self.print_ident(item.ident);
513 self.word_space(":");
514 self.print_type(&ty);
516 self.end(); // end the head-ibox
518 self.word_space("=");
519 self.ann.nested(self, Nested::Body(expr));
521 self.end(); // end the outer cbox
523 hir::ItemKind::Fn(ref sig, ref param_names, body) => {
528 Some(item.ident.name),
535 self.end(); // need to close a box
536 self.end(); // need to close a box
537 self.ann.nested(self, Nested::Body(body));
539 hir::ItemKind::Mod(ref _mod) => {
540 self.head(visibility_qualified(&item.vis, "mod"));
541 self.print_ident(item.ident);
544 self.print_mod(_mod, &item.attrs);
545 self.bclose(item.span);
547 hir::ItemKind::ForeignMod(ref nmod) => {
549 self.word_nbsp(nmod.abi.to_string());
551 self.print_foreign_mod(nmod, &item.attrs);
552 self.bclose(item.span);
554 hir::ItemKind::GlobalAsm(ref ga) => {
555 self.head(visibility_qualified(&item.vis, "global asm"));
556 self.s.word(ga.asm.to_string());
559 hir::ItemKind::TyAlias(ref ty, ref generics) => {
560 self.print_item_type(item, &generics, |state| {
561 state.word_space("=");
562 state.print_type(&ty);
565 hir::ItemKind::OpaqueTy(ref opaque_ty) => {
566 self.print_item_type(item, &opaque_ty.generics, |state| {
567 let mut real_bounds = Vec::with_capacity(opaque_ty.bounds.len());
568 for b in opaque_ty.bounds.iter() {
569 if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
571 state.word_space("for ?");
572 state.print_trait_ref(&ptr.trait_ref);
577 state.print_bounds("= impl", real_bounds);
580 hir::ItemKind::Enum(ref enum_definition, ref params) => {
581 self.print_enum_def(enum_definition, params, item.ident.name, item.span, &item.vis);
583 hir::ItemKind::Struct(ref struct_def, ref generics) => {
584 self.head(visibility_qualified(&item.vis, "struct"));
585 self.print_struct(struct_def, generics, item.ident.name, item.span, true);
587 hir::ItemKind::Union(ref struct_def, ref generics) => {
588 self.head(visibility_qualified(&item.vis, "union"));
589 self.print_struct(struct_def, generics, item.ident.name, item.span, true);
601 self.print_visibility(&item.vis);
602 self.print_defaultness(defaultness);
603 self.print_unsafety(unsafety);
604 self.word_nbsp("impl");
606 if !generics.params.is_empty() {
607 self.print_generic_params(&generics.params);
611 if let hir::ImplPolarity::Negative = polarity {
615 if let Some(ref t) = opt_trait {
616 self.print_trait_ref(t);
618 self.word_space("for");
621 self.print_type(&ty);
622 self.print_where_clause(&generics.where_clause);
626 self.print_inner_attributes(&item.attrs);
627 for impl_item in impl_items {
628 self.ann.nested(self, Nested::ImplItem(impl_item.id));
630 self.bclose(item.span);
632 hir::ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, trait_items) => {
634 self.print_visibility(&item.vis);
635 self.print_is_auto(is_auto);
636 self.print_unsafety(unsafety);
637 self.word_nbsp("trait");
638 self.print_ident(item.ident);
639 self.print_generic_params(&generics.params);
640 let mut real_bounds = Vec::with_capacity(bounds.len());
641 for b in bounds.iter() {
642 if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
644 self.word_space("for ?");
645 self.print_trait_ref(&ptr.trait_ref);
650 self.print_bounds(":", real_bounds);
651 self.print_where_clause(&generics.where_clause);
654 for trait_item in trait_items {
655 self.ann.nested(self, Nested::TraitItem(trait_item.id));
657 self.bclose(item.span);
659 hir::ItemKind::TraitAlias(ref generics, ref bounds) => {
661 self.print_visibility(&item.vis);
662 self.word_nbsp("trait");
663 self.print_ident(item.ident);
664 self.print_generic_params(&generics.params);
665 let mut real_bounds = Vec::with_capacity(bounds.len());
666 // FIXME(durka) this seems to be some quite outdated syntax
667 for b in bounds.iter() {
668 if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
670 self.word_space("for ?");
671 self.print_trait_ref(&ptr.trait_ref);
677 self.print_bounds("=", real_bounds);
678 self.print_where_clause(&generics.where_clause);
682 self.ann.post(self, AnnNode::Item(item))
685 pub fn print_trait_ref(&mut self, t: &hir::TraitRef<'_>) {
686 self.print_path(&t.path, false)
689 fn print_formal_generic_params(&mut self, generic_params: &[hir::GenericParam<'_>]) {
690 if !generic_params.is_empty() {
692 self.print_generic_params(generic_params);
697 fn print_poly_trait_ref(&mut self, t: &hir::PolyTraitRef<'_>) {
698 self.print_formal_generic_params(&t.bound_generic_params);
699 self.print_trait_ref(&t.trait_ref)
702 pub fn print_enum_def(
704 enum_definition: &hir::EnumDef<'_>,
705 generics: &hir::Generics<'_>,
707 span: syntax_pos::Span,
708 visibility: &hir::Visibility<'_>,
710 self.head(visibility_qualified(visibility, "enum"));
711 self.print_name(name);
712 self.print_generic_params(&generics.params);
713 self.print_where_clause(&generics.where_clause);
715 self.print_variants(&enum_definition.variants, span)
718 pub fn print_variants(&mut self, variants: &[hir::Variant<'_>], span: syntax_pos::Span) {
721 self.space_if_not_bol();
722 self.maybe_print_comment(v.span.lo());
723 self.print_outer_attributes(&v.attrs);
724 self.ibox(INDENT_UNIT);
725 self.print_variant(v);
728 self.maybe_print_trailing_comment(v.span, None);
733 pub fn print_visibility(&mut self, vis: &hir::Visibility<'_>) {
735 hir::VisibilityKind::Public => self.word_nbsp("pub"),
736 hir::VisibilityKind::Crate(ast::CrateSugar::JustCrate) => self.word_nbsp("crate"),
737 hir::VisibilityKind::Crate(ast::CrateSugar::PubCrate) => self.word_nbsp("pub(crate)"),
738 hir::VisibilityKind::Restricted { ref path, .. } => {
740 if path.segments.len() == 1 && path.segments[0].ident.name == kw::Super {
741 // Special case: `super` can print like `pub(super)`.
742 self.s.word("super");
744 // Everything else requires `in` at present.
745 self.word_nbsp("in");
746 self.print_path(path, false);
750 hir::VisibilityKind::Inherited => (),
754 pub fn print_defaultness(&mut self, defaultness: hir::Defaultness) {
756 hir::Defaultness::Default { .. } => self.word_nbsp("default"),
757 hir::Defaultness::Final => (),
763 struct_def: &hir::VariantData<'_>,
764 generics: &hir::Generics<'_>,
766 span: syntax_pos::Span,
767 print_finalizer: bool,
769 self.print_name(name);
770 self.print_generic_params(&generics.params);
772 hir::VariantData::Tuple(..) | hir::VariantData::Unit(..) => {
773 if let hir::VariantData::Tuple(..) = struct_def {
775 self.commasep(Inconsistent, struct_def.fields(), |s, field| {
776 s.maybe_print_comment(field.span.lo());
777 s.print_outer_attributes(&field.attrs);
778 s.print_visibility(&field.vis);
779 s.print_type(&field.ty)
783 self.print_where_clause(&generics.where_clause);
788 self.end() // close the outer-box
790 hir::VariantData::Struct(..) => {
791 self.print_where_clause(&generics.where_clause);
794 self.hardbreak_if_not_bol();
796 for field in struct_def.fields() {
797 self.hardbreak_if_not_bol();
798 self.maybe_print_comment(field.span.lo());
799 self.print_outer_attributes(&field.attrs);
800 self.print_visibility(&field.vis);
801 self.print_ident(field.ident);
803 self.print_type(&field.ty);
812 pub fn print_variant(&mut self, v: &hir::Variant<'_>) {
814 let generics = hir::Generics::empty();
815 self.print_struct(&v.data, &generics, v.ident.name, v.span, false);
816 if let Some(ref d) = v.disr_expr {
818 self.word_space("=");
819 self.print_anon_const(d);
822 pub fn print_method_sig(
826 generics: &hir::Generics<'_>,
827 vis: &hir::Visibility<'_>,
828 arg_names: &[ast::Ident],
829 body_id: Option<hir::BodyId>,
831 self.print_fn(&m.decl, m.header, Some(ident.name), generics, vis, arg_names, body_id)
834 pub fn print_trait_item(&mut self, ti: &hir::TraitItem<'_>) {
835 self.ann.pre(self, AnnNode::SubItem(ti.hir_id));
836 self.hardbreak_if_not_bol();
837 self.maybe_print_comment(ti.span.lo());
838 self.print_outer_attributes(&ti.attrs);
840 hir::TraitItemKind::Const(ref ty, default) => {
842 Spanned { span: syntax_pos::DUMMY_SP, node: hir::VisibilityKind::Inherited };
843 self.print_associated_const(ti.ident, &ty, default, &vis);
845 hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Required(ref arg_names)) => {
847 Spanned { span: syntax_pos::DUMMY_SP, node: hir::VisibilityKind::Inherited };
848 self.print_method_sig(ti.ident, sig, &ti.generics, &vis, arg_names, None);
851 hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Provided(body)) => {
853 Spanned { span: syntax_pos::DUMMY_SP, node: hir::VisibilityKind::Inherited };
855 self.print_method_sig(ti.ident, sig, &ti.generics, &vis, &[], Some(body));
857 self.end(); // need to close a box
858 self.end(); // need to close a box
859 self.ann.nested(self, Nested::Body(body));
861 hir::TraitItemKind::Type(ref bounds, ref default) => {
862 self.print_associated_type(
865 default.as_ref().map(|ty| &**ty),
869 self.ann.post(self, AnnNode::SubItem(ti.hir_id))
872 pub fn print_impl_item(&mut self, ii: &hir::ImplItem<'_>) {
873 self.ann.pre(self, AnnNode::SubItem(ii.hir_id));
874 self.hardbreak_if_not_bol();
875 self.maybe_print_comment(ii.span.lo());
876 self.print_outer_attributes(&ii.attrs);
877 self.print_defaultness(ii.defaultness);
880 hir::ImplItemKind::Const(ref ty, expr) => {
881 self.print_associated_const(ii.ident, &ty, Some(expr), &ii.vis);
883 hir::ImplItemKind::Method(ref sig, body) => {
885 self.print_method_sig(ii.ident, sig, &ii.generics, &ii.vis, &[], Some(body));
887 self.end(); // need to close a box
888 self.end(); // need to close a box
889 self.ann.nested(self, Nested::Body(body));
891 hir::ImplItemKind::TyAlias(ref ty) => {
892 self.print_associated_type(ii.ident, None, Some(ty));
894 hir::ImplItemKind::OpaqueTy(ref bounds) => {
895 self.word_space("type");
896 self.print_ident(ii.ident);
897 self.print_bounds("= impl", bounds);
901 self.ann.post(self, AnnNode::SubItem(ii.hir_id))
904 pub fn print_local(&mut self, init: Option<&hir::Expr<'_>>, decl: impl Fn(&mut Self)) {
905 self.space_if_not_bol();
906 self.ibox(INDENT_UNIT);
907 self.word_nbsp("let");
909 self.ibox(INDENT_UNIT);
913 if let Some(ref init) = init {
915 self.word_space("=");
916 self.print_expr(&init);
921 pub fn print_stmt(&mut self, st: &hir::Stmt<'_>) {
922 self.maybe_print_comment(st.span.lo());
924 hir::StmtKind::Local(ref loc) => {
925 self.print_local(loc.init.as_deref(), |this| this.print_local_decl(&loc));
927 hir::StmtKind::Item(item) => self.ann.nested(self, Nested::Item(item)),
928 hir::StmtKind::Expr(ref expr) => {
929 self.space_if_not_bol();
930 self.print_expr(&expr);
932 hir::StmtKind::Semi(ref expr) => {
933 self.space_if_not_bol();
934 self.print_expr(&expr);
938 if stmt_ends_with_semi(&st.kind) {
941 self.maybe_print_trailing_comment(st.span, None)
944 pub fn print_block(&mut self, blk: &hir::Block<'_>) {
945 self.print_block_with_attrs(blk, &[])
948 pub fn print_block_unclosed(&mut self, blk: &hir::Block<'_>) {
949 self.print_block_maybe_unclosed(blk, &[], false)
952 pub fn print_block_with_attrs(&mut self, blk: &hir::Block<'_>, attrs: &[ast::Attribute]) {
953 self.print_block_maybe_unclosed(blk, attrs, true)
956 pub fn print_block_maybe_unclosed(
958 blk: &hir::Block<'_>,
959 attrs: &[ast::Attribute],
963 hir::UnsafeBlock(..) => self.word_space("unsafe"),
964 hir::PushUnsafeBlock(..) => self.word_space("push_unsafe"),
965 hir::PopUnsafeBlock(..) => self.word_space("pop_unsafe"),
966 hir::DefaultBlock => (),
968 self.maybe_print_comment(blk.span.lo());
969 self.ann.pre(self, AnnNode::Block(blk));
972 self.print_inner_attributes(attrs);
974 for st in blk.stmts {
977 if let Some(ref expr) = blk.expr {
978 self.space_if_not_bol();
979 self.print_expr(&expr);
980 self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi()));
982 self.bclose_maybe_open(blk.span, close_box);
983 self.ann.post(self, AnnNode::Block(blk))
986 pub fn print_anon_const(&mut self, constant: &hir::AnonConst) {
987 self.ann.nested(self, Nested::Body(constant.body))
990 fn print_call_post(&mut self, args: &[hir::Expr<'_>]) {
992 self.commasep_exprs(Inconsistent, args);
996 pub fn print_expr_maybe_paren(&mut self, expr: &hir::Expr<'_>, prec: i8) {
997 let needs_par = expr.precedence().order() < prec;
1001 self.print_expr(expr);
1007 /// Print an expr using syntax that's acceptable in a condition position, such as the `cond` in
1008 /// `if cond { ... }`.
1009 pub fn print_expr_as_cond(&mut self, expr: &hir::Expr<'_>) {
1010 let needs_par = match expr.kind {
1011 // These cases need parens due to the parse error observed in #26461: `if return {}`
1012 // parses as the erroneous construct `if (return {})`, not `if (return) {}`.
1013 hir::ExprKind::Closure(..) | hir::ExprKind::Ret(..) | hir::ExprKind::Break(..) => true,
1015 _ => contains_exterior_struct_lit(expr),
1021 self.print_expr(expr);
1027 fn print_expr_vec(&mut self, exprs: &[hir::Expr<'_>]) {
1028 self.ibox(INDENT_UNIT);
1030 self.commasep_exprs(Inconsistent, exprs);
1035 fn print_expr_repeat(&mut self, element: &hir::Expr<'_>, count: &hir::AnonConst) {
1036 self.ibox(INDENT_UNIT);
1038 self.print_expr(element);
1039 self.word_space(";");
1040 self.print_anon_const(count);
1045 fn print_expr_struct(
1047 qpath: &hir::QPath<'_>,
1048 fields: &[hir::Field<'_>],
1049 wth: &Option<&'hir hir::Expr<'_>>,
1051 self.print_qpath(qpath, true);
1057 s.ibox(INDENT_UNIT);
1058 if !field.is_shorthand {
1059 s.print_ident(field.ident);
1062 s.print_expr(&field.expr);
1069 self.ibox(INDENT_UNIT);
1070 if !fields.is_empty() {
1075 self.print_expr(&expr);
1079 if !fields.is_empty() {
1087 fn print_expr_tup(&mut self, exprs: &[hir::Expr<'_>]) {
1089 self.commasep_exprs(Inconsistent, exprs);
1090 if exprs.len() == 1 {
1096 fn print_expr_call(&mut self, func: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
1097 let prec = match func.kind {
1098 hir::ExprKind::Field(..) => parser::PREC_FORCE_PAREN,
1099 _ => parser::PREC_POSTFIX,
1102 self.print_expr_maybe_paren(func, prec);
1103 self.print_call_post(args)
1106 fn print_expr_method_call(&mut self, segment: &hir::PathSegment<'_>, args: &[hir::Expr<'_>]) {
1107 let base_args = &args[1..];
1108 self.print_expr_maybe_paren(&args[0], parser::PREC_POSTFIX);
1110 self.print_ident(segment.ident);
1112 let generic_args = segment.generic_args();
1113 if !generic_args.args.is_empty() || !generic_args.bindings.is_empty() {
1114 self.print_generic_args(generic_args, segment.infer_args, true);
1117 self.print_call_post(base_args)
1120 fn print_expr_binary(&mut self, op: hir::BinOp, lhs: &hir::Expr<'_>, rhs: &hir::Expr<'_>) {
1121 let assoc_op = bin_op_to_assoc_op(op.node);
1122 let prec = assoc_op.precedence() as i8;
1123 let fixity = assoc_op.fixity();
1125 let (left_prec, right_prec) = match fixity {
1126 Fixity::Left => (prec, prec + 1),
1127 Fixity::Right => (prec + 1, prec),
1128 Fixity::None => (prec + 1, prec + 1),
1131 let left_prec = match (&lhs.kind, op.node) {
1132 // These cases need parens: `x as i32 < y` has the parser thinking that `i32 < y` is
1133 // the beginning of a path type. It starts trying to parse `x as (i32 < y ...` instead
1134 // of `(x as i32) < ...`. We need to convince it _not_ to do that.
1135 (&hir::ExprKind::Cast { .. }, hir::BinOpKind::Lt)
1136 | (&hir::ExprKind::Cast { .. }, hir::BinOpKind::Shl) => parser::PREC_FORCE_PAREN,
1140 self.print_expr_maybe_paren(lhs, left_prec);
1142 self.word_space(op.node.as_str());
1143 self.print_expr_maybe_paren(rhs, right_prec)
1146 fn print_expr_unary(&mut self, op: hir::UnOp, expr: &hir::Expr<'_>) {
1147 self.s.word(op.as_str());
1148 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1151 fn print_expr_addr_of(
1153 kind: hir::BorrowKind,
1154 mutability: hir::Mutability,
1155 expr: &hir::Expr<'_>,
1159 hir::BorrowKind::Ref => self.print_mutability(mutability, false),
1160 hir::BorrowKind::Raw => {
1161 self.word_nbsp("raw");
1162 self.print_mutability(mutability, true);
1165 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1168 fn print_literal(&mut self, lit: &hir::Lit) {
1169 self.maybe_print_comment(lit.span.lo());
1170 self.word(lit.node.to_lit_token().to_string())
1173 pub fn print_expr(&mut self, expr: &hir::Expr<'_>) {
1174 self.maybe_print_comment(expr.span.lo());
1175 self.print_outer_attributes(&expr.attrs);
1176 self.ibox(INDENT_UNIT);
1177 self.ann.pre(self, AnnNode::Expr(expr));
1179 hir::ExprKind::Box(ref expr) => {
1180 self.word_space("box");
1181 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX);
1183 hir::ExprKind::Array(ref exprs) => {
1184 self.print_expr_vec(exprs);
1186 hir::ExprKind::Repeat(ref element, ref count) => {
1187 self.print_expr_repeat(&element, count);
1189 hir::ExprKind::Struct(ref qpath, fields, ref wth) => {
1190 self.print_expr_struct(qpath, fields, wth);
1192 hir::ExprKind::Tup(ref exprs) => {
1193 self.print_expr_tup(exprs);
1195 hir::ExprKind::Call(ref func, ref args) => {
1196 self.print_expr_call(&func, args);
1198 hir::ExprKind::MethodCall(ref segment, _, ref args) => {
1199 self.print_expr_method_call(segment, args);
1201 hir::ExprKind::Binary(op, ref lhs, ref rhs) => {
1202 self.print_expr_binary(op, &lhs, &rhs);
1204 hir::ExprKind::Unary(op, ref expr) => {
1205 self.print_expr_unary(op, &expr);
1207 hir::ExprKind::AddrOf(k, m, ref expr) => {
1208 self.print_expr_addr_of(k, m, &expr);
1210 hir::ExprKind::Lit(ref lit) => {
1211 self.print_literal(&lit);
1213 hir::ExprKind::Cast(ref expr, ref ty) => {
1214 let prec = AssocOp::As.precedence() as i8;
1215 self.print_expr_maybe_paren(&expr, prec);
1217 self.word_space("as");
1218 self.print_type(&ty);
1220 hir::ExprKind::Type(ref expr, ref ty) => {
1221 let prec = AssocOp::Colon.precedence() as i8;
1222 self.print_expr_maybe_paren(&expr, prec);
1223 self.word_space(":");
1224 self.print_type(&ty);
1226 hir::ExprKind::DropTemps(ref init) => {
1228 self.cbox(INDENT_UNIT);
1232 // Print `let _t = $init;`:
1233 let temp = ast::Ident::from_str("_t");
1234 self.print_local(Some(init), |this| this.print_ident(temp));
1238 self.space_if_not_bol();
1239 self.print_ident(temp);
1242 self.bclose_maybe_open(expr.span, true);
1244 hir::ExprKind::Loop(ref blk, opt_label, _) => {
1245 if let Some(label) = opt_label {
1246 self.print_ident(label.ident);
1247 self.word_space(":");
1251 self.print_block(&blk);
1253 hir::ExprKind::Match(ref expr, arms, _) => {
1254 self.cbox(INDENT_UNIT);
1255 self.ibox(INDENT_UNIT);
1256 self.word_nbsp("match");
1257 self.print_expr_as_cond(&expr);
1261 self.print_arm(arm);
1263 self.bclose(expr.span);
1265 hir::ExprKind::Closure(capture_clause, ref decl, body, _fn_decl_span, _gen) => {
1266 self.print_capture_clause(capture_clause);
1268 self.print_closure_params(&decl, body);
1271 // This is a bare expression.
1272 self.ann.nested(self, Nested::Body(body));
1273 self.end(); // need to close a box
1275 // A box will be closed by `print_expr`, but we didn't want an overall
1276 // wrapper so we closed the corresponding opening. so create an
1277 // empty box to satisfy the close.
1280 hir::ExprKind::Block(ref blk, opt_label) => {
1281 if let Some(label) = opt_label {
1282 self.print_ident(label.ident);
1283 self.word_space(":");
1285 // containing cbox, will be closed by print-block at `}`
1286 self.cbox(INDENT_UNIT);
1287 // head-box, will be closed by print-block after `{`
1289 self.print_block(&blk);
1291 hir::ExprKind::Assign(ref lhs, ref rhs, _) => {
1292 let prec = AssocOp::Assign.precedence() as i8;
1293 self.print_expr_maybe_paren(&lhs, prec + 1);
1295 self.word_space("=");
1296 self.print_expr_maybe_paren(&rhs, prec);
1298 hir::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
1299 let prec = AssocOp::Assign.precedence() as i8;
1300 self.print_expr_maybe_paren(&lhs, prec + 1);
1302 self.s.word(op.node.as_str());
1303 self.word_space("=");
1304 self.print_expr_maybe_paren(&rhs, prec);
1306 hir::ExprKind::Field(ref expr, ident) => {
1307 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
1309 self.print_ident(ident);
1311 hir::ExprKind::Index(ref expr, ref index) => {
1312 self.print_expr_maybe_paren(&expr, parser::PREC_POSTFIX);
1314 self.print_expr(&index);
1317 hir::ExprKind::Path(ref qpath) => self.print_qpath(qpath, true),
1318 hir::ExprKind::Break(destination, ref opt_expr) => {
1319 self.s.word("break");
1321 if let Some(label) = destination.label {
1322 self.print_ident(label.ident);
1325 if let Some(ref expr) = *opt_expr {
1326 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
1330 hir::ExprKind::Continue(destination) => {
1331 self.s.word("continue");
1333 if let Some(label) = destination.label {
1334 self.print_ident(label.ident);
1338 hir::ExprKind::Ret(ref result) => {
1339 self.s.word("return");
1340 if let Some(ref expr) = *result {
1342 self.print_expr_maybe_paren(&expr, parser::PREC_JUMP);
1345 hir::ExprKind::InlineAsm(ref a) => {
1347 self.s.word("asm!");
1349 self.print_string(&i.asm.as_str(), i.asm_str_style);
1350 self.word_space(":");
1352 let mut out_idx = 0;
1353 self.commasep(Inconsistent, &i.outputs, |s, out| {
1354 let constraint = out.constraint.as_str();
1355 let mut ch = constraint.chars();
1357 Some('=') if out.is_rw => {
1358 s.print_string(&format!("+{}", ch.as_str()), ast::StrStyle::Cooked)
1360 _ => s.print_string(&constraint, ast::StrStyle::Cooked),
1363 s.print_expr(&a.outputs_exprs[out_idx]);
1368 self.word_space(":");
1371 self.commasep(Inconsistent, &i.inputs, |s, co| {
1372 s.print_string(&co.as_str(), ast::StrStyle::Cooked);
1374 s.print_expr(&a.inputs_exprs[in_idx]);
1379 self.word_space(":");
1381 self.commasep(Inconsistent, &i.clobbers, |s, co| {
1382 s.print_string(&co.as_str(), ast::StrStyle::Cooked);
1385 let mut options = vec![];
1387 options.push("volatile");
1390 options.push("alignstack");
1392 if i.dialect == ast::AsmDialect::Intel {
1393 options.push("intel");
1396 if !options.is_empty() {
1398 self.word_space(":");
1399 self.commasep(Inconsistent, &options, |s, &co| {
1400 s.print_string(co, ast::StrStyle::Cooked);
1406 hir::ExprKind::Yield(ref expr, _) => {
1407 self.word_space("yield");
1408 self.print_expr_maybe_paren(&expr, parser::PREC_JUMP);
1410 hir::ExprKind::Err => {
1412 self.s.word("/*ERROR*/");
1416 self.ann.post(self, AnnNode::Expr(expr));
1420 pub fn print_local_decl(&mut self, loc: &hir::Local<'_>) {
1421 self.print_pat(&loc.pat);
1422 if let Some(ref ty) = loc.ty {
1423 self.word_space(":");
1424 self.print_type(&ty);
1428 pub fn print_usize(&mut self, i: usize) {
1429 self.s.word(i.to_string())
1432 pub fn print_name(&mut self, name: ast::Name) {
1433 self.print_ident(ast::Ident::with_dummy_span(name))
1436 pub fn print_for_decl(&mut self, loc: &hir::Local<'_>, coll: &hir::Expr<'_>) {
1437 self.print_local_decl(loc);
1439 self.word_space("in");
1440 self.print_expr(coll)
1443 pub fn print_path(&mut self, path: &hir::Path<'_>, colons_before_params: bool) {
1444 self.maybe_print_comment(path.span.lo());
1446 for (i, segment) in path.segments.iter().enumerate() {
1450 if segment.ident.name != kw::PathRoot {
1451 self.print_ident(segment.ident);
1452 self.print_generic_args(
1453 segment.generic_args(),
1455 colons_before_params,
1461 pub fn print_path_segment(&mut self, segment: &hir::PathSegment<'_>) {
1462 if segment.ident.name != kw::PathRoot {
1463 self.print_ident(segment.ident);
1464 self.print_generic_args(segment.generic_args(), segment.infer_args, false);
1468 pub fn print_qpath(&mut self, qpath: &hir::QPath<'_>, colons_before_params: bool) {
1470 hir::QPath::Resolved(None, ref path) => self.print_path(path, colons_before_params),
1471 hir::QPath::Resolved(Some(ref qself), ref path) => {
1473 self.print_type(qself);
1475 self.word_space("as");
1477 for (i, segment) in path.segments[..path.segments.len() - 1].iter().enumerate() {
1481 if segment.ident.name != kw::PathRoot {
1482 self.print_ident(segment.ident);
1483 self.print_generic_args(
1484 segment.generic_args(),
1486 colons_before_params,
1493 let item_segment = path.segments.last().unwrap();
1494 self.print_ident(item_segment.ident);
1495 self.print_generic_args(
1496 item_segment.generic_args(),
1497 item_segment.infer_args,
1498 colons_before_params,
1501 hir::QPath::TypeRelative(ref qself, ref item_segment) => {
1502 // If we've got a compound-qualified-path, let's push an additional pair of angle
1503 // brackets, so that we pretty-print `<<A::B>::C>` as `<A::B>::C`, instead of just
1504 // `A::B::C` (since the latter could be ambiguous to the user)
1505 if let hir::TyKind::Path(hir::QPath::Resolved(None, _)) = &qself.kind {
1506 self.print_type(qself);
1509 self.print_type(qself);
1514 self.print_ident(item_segment.ident);
1515 self.print_generic_args(
1516 item_segment.generic_args(),
1517 item_segment.infer_args,
1518 colons_before_params,
1524 fn print_generic_args(
1526 generic_args: &hir::GenericArgs<'_>,
1528 colons_before_params: bool,
1530 if generic_args.parenthesized {
1532 self.commasep(Inconsistent, generic_args.inputs(), |s, ty| s.print_type(&ty));
1535 self.space_if_not_bol();
1536 self.word_space("->");
1537 self.print_type(generic_args.bindings[0].ty());
1539 let start = if colons_before_params { "::<" } else { "<" };
1540 let empty = Cell::new(true);
1541 let start_or_comma = |this: &mut Self| {
1546 this.word_space(",")
1550 let mut nonelided_generic_args: bool = false;
1551 let elide_lifetimes = generic_args.args.iter().all(|arg| match arg {
1552 GenericArg::Lifetime(lt) => lt.is_elided(),
1554 nonelided_generic_args = true;
1559 if nonelided_generic_args {
1560 start_or_comma(self);
1564 |s, generic_arg| match generic_arg {
1565 GenericArg::Lifetime(lt) if !elide_lifetimes => s.print_lifetime(lt),
1566 GenericArg::Lifetime(_) => {}
1567 GenericArg::Type(ty) => s.print_type(ty),
1568 GenericArg::Const(ct) => s.print_anon_const(&ct.value),
1573 // FIXME(eddyb): this would leak into error messages (e.g.,
1574 // "non-exhaustive patterns: `Some::<..>(_)` not covered").
1575 if infer_args && false {
1576 start_or_comma(self);
1580 for binding in generic_args.bindings.iter() {
1581 start_or_comma(self);
1582 self.print_ident(binding.ident);
1584 match generic_args.bindings[0].kind {
1585 hir::TypeBindingKind::Equality { ref ty } => {
1586 self.word_space("=");
1587 self.print_type(ty);
1589 hir::TypeBindingKind::Constraint { ref bounds } => {
1590 self.print_bounds(":", bounds);
1601 pub fn print_pat(&mut self, pat: &hir::Pat<'_>) {
1602 self.maybe_print_comment(pat.span.lo());
1603 self.ann.pre(self, AnnNode::Pat(pat));
1604 // Pat isn't normalized, but the beauty of it
1605 // is that it doesn't matter
1607 PatKind::Wild => self.s.word("_"),
1608 PatKind::Binding(binding_mode, _, ident, ref sub) => {
1609 match binding_mode {
1610 hir::BindingAnnotation::Ref => {
1611 self.word_nbsp("ref");
1612 self.print_mutability(hir::Mutability::Not, false);
1614 hir::BindingAnnotation::RefMut => {
1615 self.word_nbsp("ref");
1616 self.print_mutability(hir::Mutability::Mut, false);
1618 hir::BindingAnnotation::Unannotated => {}
1619 hir::BindingAnnotation::Mutable => {
1620 self.word_nbsp("mut");
1623 self.print_ident(ident);
1624 if let Some(ref p) = *sub {
1629 PatKind::TupleStruct(ref qpath, ref elts, ddpos) => {
1630 self.print_qpath(qpath, true);
1632 if let Some(ddpos) = ddpos {
1633 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p));
1635 self.word_space(",");
1638 if ddpos != elts.len() {
1640 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p));
1643 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p));
1647 PatKind::Path(ref qpath) => {
1648 self.print_qpath(qpath, true);
1650 PatKind::Struct(ref qpath, ref fields, etc) => {
1651 self.print_qpath(qpath, true);
1653 self.word_space("{");
1658 s.cbox(INDENT_UNIT);
1659 if !f.is_shorthand {
1660 s.print_ident(f.ident);
1663 s.print_pat(&f.pat);
1669 if !fields.is_empty() {
1670 self.word_space(",");
1677 PatKind::Or(ref pats) => {
1678 self.strsep("|", true, Inconsistent, &pats[..], |s, p| s.print_pat(&p));
1680 PatKind::Tuple(ref elts, ddpos) => {
1682 if let Some(ddpos) = ddpos {
1683 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p));
1685 self.word_space(",");
1688 if ddpos != elts.len() {
1690 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p));
1693 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p));
1694 if elts.len() == 1 {
1700 PatKind::Box(ref inner) => {
1701 let is_range_inner = match inner.kind {
1702 PatKind::Range(..) => true,
1705 self.s.word("box ");
1709 self.print_pat(&inner);
1714 PatKind::Ref(ref inner, mutbl) => {
1715 let is_range_inner = match inner.kind {
1716 PatKind::Range(..) => true,
1720 self.s.word(mutbl.prefix_str());
1724 self.print_pat(&inner);
1729 PatKind::Lit(ref e) => self.print_expr(&e),
1730 PatKind::Range(ref begin, ref end, ref end_kind) => {
1731 self.print_expr(&begin);
1734 RangeEnd::Included => self.s.word("..."),
1735 RangeEnd::Excluded => self.s.word(".."),
1737 self.print_expr(&end);
1739 PatKind::Slice(ref before, ref slice, ref after) => {
1741 self.commasep(Inconsistent, &before[..], |s, p| s.print_pat(&p));
1742 if let Some(ref p) = *slice {
1743 if !before.is_empty() {
1744 self.word_space(",");
1746 if let PatKind::Wild = p.kind {
1752 if !after.is_empty() {
1753 self.word_space(",");
1756 self.commasep(Inconsistent, &after[..], |s, p| s.print_pat(&p));
1760 self.ann.post(self, AnnNode::Pat(pat))
1763 pub fn print_param(&mut self, arg: &hir::Param<'_>) {
1764 self.print_outer_attributes(&arg.attrs);
1765 self.print_pat(&arg.pat);
1768 pub fn print_arm(&mut self, arm: &hir::Arm<'_>) {
1769 // I have no idea why this check is necessary, but here it
1771 if arm.attrs.is_empty() {
1774 self.cbox(INDENT_UNIT);
1775 self.ann.pre(self, AnnNode::Arm(arm));
1777 self.print_outer_attributes(&arm.attrs);
1778 self.print_pat(&arm.pat);
1780 if let Some(ref g) = arm.guard {
1782 hir::Guard::If(e) => {
1783 self.word_space("if");
1784 self.print_expr(&e);
1789 self.word_space("=>");
1791 match arm.body.kind {
1792 hir::ExprKind::Block(ref blk, opt_label) => {
1793 if let Some(label) = opt_label {
1794 self.print_ident(label.ident);
1795 self.word_space(":");
1797 // the block will close the pattern's ibox
1798 self.print_block_unclosed(&blk);
1800 // If it is a user-provided unsafe block, print a comma after it
1801 if let hir::UnsafeBlock(hir::UserProvided) = blk.rules {
1806 self.end(); // close the ibox for the pattern
1807 self.print_expr(&arm.body);
1811 self.ann.post(self, AnnNode::Arm(arm));
1812 self.end() // close enclosing cbox
1817 decl: &hir::FnDecl<'_>,
1818 header: hir::FnHeader,
1819 name: Option<ast::Name>,
1820 generics: &hir::Generics<'_>,
1821 vis: &hir::Visibility<'_>,
1822 arg_names: &[ast::Ident],
1823 body_id: Option<hir::BodyId>,
1825 self.print_fn_header_info(header, vis);
1827 if let Some(name) = name {
1829 self.print_name(name);
1831 self.print_generic_params(&generics.params);
1835 // Make sure we aren't supplied *both* `arg_names` and `body_id`.
1836 assert!(arg_names.is_empty() || body_id.is_none());
1837 self.commasep(Inconsistent, &decl.inputs, |s, ty| {
1838 s.ibox(INDENT_UNIT);
1839 if let Some(arg_name) = arg_names.get(i) {
1840 s.s.word(arg_name.to_string());
1843 } else if let Some(body_id) = body_id {
1844 s.ann.nested(s, Nested::BodyParamPat(body_id, i));
1852 if decl.c_variadic {
1853 self.s.word(", ...");
1857 self.print_fn_output(decl);
1858 self.print_where_clause(&generics.where_clause)
1861 fn print_closure_params(&mut self, decl: &hir::FnDecl<'_>, body_id: hir::BodyId) {
1864 self.commasep(Inconsistent, &decl.inputs, |s, ty| {
1865 s.ibox(INDENT_UNIT);
1867 s.ann.nested(s, Nested::BodyParamPat(body_id, i));
1870 if let hir::TyKind::Infer = ty.kind {
1881 if let hir::DefaultReturn(..) = decl.output {
1885 self.space_if_not_bol();
1886 self.word_space("->");
1888 hir::Return(ref ty) => {
1889 self.print_type(&ty);
1890 self.maybe_print_comment(ty.span.lo())
1892 hir::DefaultReturn(..) => unreachable!(),
1896 pub fn print_capture_clause(&mut self, capture_clause: hir::CaptureBy) {
1897 match capture_clause {
1898 hir::CaptureBy::Value => self.word_space("move"),
1899 hir::CaptureBy::Ref => {}
1903 pub fn print_bounds<'b>(
1905 prefix: &'static str,
1906 bounds: impl IntoIterator<Item = &'b hir::GenericBound<'b>>,
1908 let mut first = true;
1909 for bound in bounds {
1911 self.s.word(prefix);
1913 if !(first && prefix.is_empty()) {
1919 self.word_space("+");
1923 GenericBound::Trait(tref, modifier) => {
1924 if modifier == &TraitBoundModifier::Maybe {
1927 self.print_poly_trait_ref(tref);
1929 GenericBound::Outlives(lt) => {
1930 self.print_lifetime(lt);
1936 pub fn print_generic_params(&mut self, generic_params: &[GenericParam<'_>]) {
1937 if !generic_params.is_empty() {
1940 self.commasep(Inconsistent, generic_params, |s, param| s.print_generic_param(param));
1946 pub fn print_generic_param(&mut self, param: &GenericParam<'_>) {
1947 if let GenericParamKind::Const { .. } = param.kind {
1948 self.word_space("const");
1951 self.print_ident(param.name.ident());
1954 GenericParamKind::Lifetime { .. } => {
1956 for bound in ¶m.bounds {
1958 GenericBound::Outlives(lt) => {
1960 self.print_lifetime(lt);
1967 GenericParamKind::Type { ref default, .. } => {
1968 self.print_bounds(":", ¶m.bounds);
1972 self.word_space("=");
1973 self.print_type(&default)
1978 GenericParamKind::Const { ref ty } => {
1979 self.word_space(":");
1985 pub fn print_lifetime(&mut self, lifetime: &hir::Lifetime) {
1986 self.print_ident(lifetime.name.ident())
1989 pub fn print_where_clause(&mut self, where_clause: &hir::WhereClause<'_>) {
1990 if where_clause.predicates.is_empty() {
1995 self.word_space("where");
1997 for (i, predicate) in where_clause.predicates.iter().enumerate() {
1999 self.word_space(",");
2003 &hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
2004 ref bound_generic_params,
2009 self.print_formal_generic_params(bound_generic_params);
2010 self.print_type(&bounded_ty);
2011 self.print_bounds(":", bounds);
2013 &hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
2018 self.print_lifetime(lifetime);
2021 for (i, bound) in bounds.iter().enumerate() {
2023 GenericBound::Outlives(lt) => {
2024 self.print_lifetime(lt);
2034 &hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
2039 self.print_type(lhs_ty);
2041 self.word_space("=");
2042 self.print_type(rhs_ty);
2048 pub fn print_mutability(&mut self, mutbl: hir::Mutability, print_const: bool) {
2050 hir::Mutability::Mut => self.word_nbsp("mut"),
2051 hir::Mutability::Not => {
2053 self.word_nbsp("const")
2059 pub fn print_mt(&mut self, mt: &hir::MutTy<'_>, print_const: bool) {
2060 self.print_mutability(mt.mutbl, print_const);
2061 self.print_type(&mt.ty)
2064 pub fn print_fn_output(&mut self, decl: &hir::FnDecl<'_>) {
2065 if let hir::DefaultReturn(..) = decl.output {
2069 self.space_if_not_bol();
2070 self.ibox(INDENT_UNIT);
2071 self.word_space("->");
2073 hir::DefaultReturn(..) => unreachable!(),
2074 hir::Return(ref ty) => self.print_type(&ty),
2079 hir::Return(ref output) => self.maybe_print_comment(output.span.lo()),
2087 unsafety: hir::Unsafety,
2088 decl: &hir::FnDecl<'_>,
2089 name: Option<ast::Name>,
2090 generic_params: &[hir::GenericParam<'_>],
2091 arg_names: &[ast::Ident],
2093 self.ibox(INDENT_UNIT);
2094 if !generic_params.is_empty() {
2096 self.print_generic_params(generic_params);
2098 let generics = hir::Generics {
2099 params: hir::HirVec::new(),
2100 where_clause: hir::WhereClause {
2101 predicates: hir::HirVec::new(),
2102 span: syntax_pos::DUMMY_SP,
2104 span: syntax_pos::DUMMY_SP,
2111 constness: hir::Constness::NotConst,
2112 asyncness: hir::IsAsync::NotAsync,
2116 &Spanned { span: syntax_pos::DUMMY_SP, node: hir::VisibilityKind::Inherited },
2123 pub fn maybe_print_trailing_comment(
2125 span: syntax_pos::Span,
2126 next_pos: Option<BytePos>,
2128 if let Some(cmnts) = self.comments() {
2129 if let Some(cmnt) = cmnts.trailing_comment(span, next_pos) {
2130 self.print_comment(&cmnt);
2135 pub fn print_remaining_comments(&mut self) {
2136 // If there aren't any remaining comments, then we need to manually
2137 // make sure there is a line break at the end.
2138 if self.next_comment().is_none() {
2141 while let Some(ref cmnt) = self.next_comment() {
2142 self.print_comment(cmnt)
2146 pub fn print_opt_abi_and_extern_if_nondefault(&mut self, opt_abi: Option<Abi>) {
2148 Some(Abi::Rust) => {}
2150 self.word_nbsp("extern");
2151 self.word_nbsp(abi.to_string())
2157 pub fn print_extern_opt_abi(&mut self, opt_abi: Option<Abi>) {
2160 self.word_nbsp("extern");
2161 self.word_nbsp(abi.to_string())
2167 pub fn print_fn_header_info(&mut self, header: hir::FnHeader, vis: &hir::Visibility<'_>) {
2168 self.s.word(visibility_qualified(vis, ""));
2170 match header.constness {
2171 hir::Constness::NotConst => {}
2172 hir::Constness::Const => self.word_nbsp("const"),
2175 match header.asyncness {
2176 hir::IsAsync::NotAsync => {}
2177 hir::IsAsync::Async => self.word_nbsp("async"),
2180 self.print_unsafety(header.unsafety);
2182 if header.abi != Abi::Rust {
2183 self.word_nbsp("extern");
2184 self.word_nbsp(header.abi.to_string());
2190 pub fn print_unsafety(&mut self, s: hir::Unsafety) {
2192 hir::Unsafety::Normal => {}
2193 hir::Unsafety::Unsafe => self.word_nbsp("unsafe"),
2197 pub fn print_is_auto(&mut self, s: hir::IsAuto) {
2199 hir::IsAuto::Yes => self.word_nbsp("auto"),
2200 hir::IsAuto::No => {}
2205 /// Does this expression require a semicolon to be treated
2206 /// as a statement? The negation of this: 'can this expression
2207 /// be used as a statement without a semicolon' -- is used
2208 /// as an early-bail-out in the parser so that, for instance,
2209 /// if true {...} else {...}
2211 /// isn't parsed as (if true {...} else {...} | x) | 5
2213 // Duplicated from `parse::classify`, but adapted for the HIR.
2214 fn expr_requires_semi_to_be_stmt(e: &hir::Expr<'_>) -> bool {
2216 hir::ExprKind::Match(..) | hir::ExprKind::Block(..) | hir::ExprKind::Loop(..) => false,
2221 /// This statement requires a semicolon after it.
2222 /// note that in one case (stmt_semi), we've already
2223 /// seen the semicolon, and thus don't need another.
2224 fn stmt_ends_with_semi(stmt: &hir::StmtKind<'_>) -> bool {
2226 hir::StmtKind::Local(_) => true,
2227 hir::StmtKind::Item(_) => false,
2228 hir::StmtKind::Expr(ref e) => expr_requires_semi_to_be_stmt(&e),
2229 hir::StmtKind::Semi(..) => false,
2233 fn bin_op_to_assoc_op(op: hir::BinOpKind) -> AssocOp {
2234 use crate::hir::BinOpKind::*;
2236 Add => AssocOp::Add,
2237 Sub => AssocOp::Subtract,
2238 Mul => AssocOp::Multiply,
2239 Div => AssocOp::Divide,
2240 Rem => AssocOp::Modulus,
2242 And => AssocOp::LAnd,
2245 BitXor => AssocOp::BitXor,
2246 BitAnd => AssocOp::BitAnd,
2247 BitOr => AssocOp::BitOr,
2248 Shl => AssocOp::ShiftLeft,
2249 Shr => AssocOp::ShiftRight,
2251 Eq => AssocOp::Equal,
2252 Lt => AssocOp::Less,
2253 Le => AssocOp::LessEqual,
2254 Ne => AssocOp::NotEqual,
2255 Ge => AssocOp::GreaterEqual,
2256 Gt => AssocOp::Greater,
2260 /// Expressions that syntactically contain an "exterior" struct literal, i.e., not surrounded by any
2261 /// parens or other delimiters, e.g., `X { y: 1 }`, `X { y: 1 }.method()`, `foo == X { y: 1 }` and
2262 /// `X { y: 1 } == foo` all do, but `(X { y: 1 }) == foo` does not.
2263 fn contains_exterior_struct_lit(value: &hir::Expr<'_>) -> bool {
2265 hir::ExprKind::Struct(..) => true,
2267 hir::ExprKind::Assign(ref lhs, ref rhs, _)
2268 | hir::ExprKind::AssignOp(_, ref lhs, ref rhs)
2269 | hir::ExprKind::Binary(_, ref lhs, ref rhs) => {
2270 // `X { y: 1 } + X { y: 2 }`
2271 contains_exterior_struct_lit(&lhs) || contains_exterior_struct_lit(&rhs)
2273 hir::ExprKind::Unary(_, ref x)
2274 | hir::ExprKind::Cast(ref x, _)
2275 | hir::ExprKind::Type(ref x, _)
2276 | hir::ExprKind::Field(ref x, _)
2277 | hir::ExprKind::Index(ref x, _) => {
2278 // `&X { y: 1 }, X { y: 1 }.y`
2279 contains_exterior_struct_lit(&x)
2282 hir::ExprKind::MethodCall(.., ref exprs) => {
2283 // `X { y: 1 }.bar(...)`
2284 contains_exterior_struct_lit(&exprs[0])