1 use rustc_target::spec::abi::Abi;
3 use syntax::source_map::{SourceMap, Spanned};
4 use syntax::print::pp::{self, Breaks};
5 use syntax::print::pp::Breaks::{Consistent, Inconsistent};
6 use syntax::print::pprust::{self, Comments, PrintState};
7 use syntax::sess::ParseSess;
8 use syntax::symbol::kw;
9 use syntax::util::parser::{self, AssocOp, Fixity};
10 use syntax_pos::{self, BytePos, FileName};
13 use crate::hir::{PatKind, GenericBound, TraitBoundModifier, RangeEnd};
14 use crate::hir::{GenericParam, GenericParamKind, GenericArg};
15 use crate::hir::ptr::P;
21 pub enum AnnNode<'a> {
23 Block(&'a hir::Block),
24 Item(&'a hir::Item<'a>),
33 TraitItem(hir::TraitItemId),
34 ImplItem(hir::ImplItemId),
36 BodyParamPat(hir::BodyId, usize)
40 fn nested(&self, _state: &mut State<'_>, _nested: Nested) {
42 fn pre(&self, _state: &mut State<'_>, _node: AnnNode<'_>) {
44 fn post(&self, _state: &mut State<'_>, _node: AnnNode<'_>) {
46 fn try_fetch_item(&self, _: hir::HirId) -> Option<&hir::Item<'_>> {
52 impl PpAnn for NoAnn {}
53 pub const NO_ANN: &dyn PpAnn = &NoAnn;
55 impl PpAnn for hir::Crate<'a> {
56 fn try_fetch_item(&self, item: hir::HirId) -> Option<&hir::Item<'_>> {
59 fn nested(&self, state: &mut State<'_>, nested: Nested) {
61 Nested::Item(id) => state.print_item(self.item(id.id)),
62 Nested::TraitItem(id) => state.print_trait_item(self.trait_item(id)),
63 Nested::ImplItem(id) => state.print_impl_item(self.impl_item(id)),
64 Nested::Body(id) => state.print_expr(&self.body(id).value),
65 Nested::BodyParamPat(id, i) => state.print_pat(&self.body(id).params[i].pat)
70 pub struct State<'a> {
72 comments: Option<Comments<'a>>,
73 ann: &'a (dyn PpAnn + 'a),
76 impl std::ops::Deref for State<'_> {
77 type Target = pp::Printer;
78 fn deref(&self) -> &Self::Target {
83 impl std::ops::DerefMut for State<'_> {
84 fn deref_mut(&mut self) -> &mut Self::Target {
89 impl<'a> PrintState<'a> for State<'a> {
90 fn comments(&mut self) -> &mut Option<Comments<'a>> {
94 fn print_ident(&mut self, ident: ast::Ident) {
95 self.s.word(pprust::ast_ident_to_string(ident, ident.is_raw_guess()));
96 self.ann.post(self, AnnNode::Name(&ident.name))
99 fn print_generic_args(&mut self, args: &ast::GenericArgs, _colons_before_params: bool) {
100 span_bug!(args.span(), "AST generic args printed by HIR pretty-printer");
104 pub const INDENT_UNIT: usize = 4;
106 /// Requires you to pass an input filename and reader so that
107 /// it can scan the input text for comments to copy forward.
108 pub fn print_crate<'a>(cm: &'a SourceMap,
110 krate: &hir::Crate<'a>,
113 ann: &'a dyn PpAnn) -> String {
114 let mut s = State::new_from_input(cm, sess, filename, input, ann);
116 // When printing the AST, we sometimes need to inject `#[no_std]` here.
117 // Since you can't compile the HIR, it's not necessary.
119 s.print_mod(&krate.module, &krate.attrs);
120 s.print_remaining_comments();
125 pub fn new_from_input(cm: &'a SourceMap,
133 comments: Some(Comments::new(cm, sess, filename, input)),
139 pub fn to_string<F>(ann: &dyn PpAnn, f: F) -> String
140 where F: FnOnce(&mut State<'_>)
142 let mut printer = State {
151 pub fn visibility_qualified<S: Into<Cow<'static, str>>>(vis: &hir::Visibility, w: S) -> String {
152 to_string(NO_ANN, |s| {
153 s.print_visibility(vis);
159 pub fn cbox(&mut self, u: usize) {
163 pub fn nbsp(&mut self) {
167 pub fn word_nbsp<S: Into<Cow<'static, str>>>(&mut self, w: S) {
172 pub fn head<S: Into<Cow<'static, str>>>(&mut self, w: S) {
174 // outer-box is consistent
175 self.cbox(INDENT_UNIT);
176 // head-box is inconsistent
177 self.ibox(w.len() + 1);
178 // keyword that starts the head
184 pub fn bopen(&mut self) {
186 self.end(); // close the head-box
189 pub fn bclose_maybe_open(&mut self,
190 span: syntax_pos::Span,
193 self.maybe_print_comment(span.hi());
194 self.break_offset_if_not_bol(1, -(INDENT_UNIT as isize));
197 self.end(); // close the outer-box
201 pub fn bclose(&mut self, span: syntax_pos::Span) {
202 self.bclose_maybe_open(span, true)
205 pub fn space_if_not_bol(&mut self) {
206 if !self.s.is_beginning_of_line() {
211 pub fn break_offset_if_not_bol(&mut self, n: usize, off: isize) {
212 if !self.s.is_beginning_of_line() {
213 self.s.break_offset(n, off)
215 if off != 0 && self.s.last_token().is_hardbreak_tok() {
216 // We do something pretty sketchy here: tuck the nonzero
217 // offset-adjustment we were going to deposit along with the
218 // break into the previous hardbreak.
219 self.s.replace_last_token(pp::Printer::hardbreak_tok_offset(off));
224 // Synthesizes a comment that was not textually present in the original source
226 pub fn synth_comment(&mut self, text: String) {
234 pub fn commasep_cmnt<T, F, G>(&mut self,
239 where F: FnMut(&mut State<'_>, &T),
240 G: FnMut(&T) -> syntax_pos::Span
243 let len = elts.len();
246 self.maybe_print_comment(get_span(elt).hi());
251 self.maybe_print_trailing_comment(get_span(elt), Some(get_span(&elts[i]).hi()));
252 self.space_if_not_bol();
258 pub fn commasep_exprs(&mut self, b: Breaks, exprs: &[hir::Expr]) {
259 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(&e), |e| e.span)
262 pub fn print_mod(&mut self, _mod: &hir::Mod, attrs: &[ast::Attribute]) {
263 self.print_inner_attributes(attrs);
264 for &item_id in &_mod.item_ids {
265 self.ann.nested(self, Nested::Item(item_id));
269 pub fn print_foreign_mod(&mut self,
270 nmod: &hir::ForeignMod,
271 attrs: &[ast::Attribute])
273 self.print_inner_attributes(attrs);
274 for item in &nmod.items {
275 self.print_foreign_item(item);
279 pub fn print_opt_lifetime(&mut self, lifetime: &hir::Lifetime) {
280 if !lifetime.is_elided() {
281 self.print_lifetime(lifetime);
286 pub fn print_type(&mut self, ty: &hir::Ty) {
287 self.maybe_print_comment(ty.span.lo());
290 hir::TyKind::Slice(ref ty) => {
292 self.print_type(&ty);
295 hir::TyKind::Ptr(ref mt) => {
297 self.print_mt(mt, true);
299 hir::TyKind::Rptr(ref lifetime, ref mt) => {
301 self.print_opt_lifetime(lifetime);
302 self.print_mt(mt, false);
304 hir::TyKind::Never => {
307 hir::TyKind::Tup(ref elts) => {
309 self.commasep(Inconsistent, &elts[..], |s, ty| s.print_type(&ty));
315 hir::TyKind::BareFn(ref f) => {
316 self.print_ty_fn(f.abi, f.unsafety, &f.decl, None, &f.generic_params,
319 hir::TyKind::Def(..) => {},
320 hir::TyKind::Path(ref qpath) => {
321 self.print_qpath(qpath, false)
323 hir::TyKind::TraitObject(ref bounds, ref lifetime) => {
324 let mut first = true;
325 for bound in bounds {
330 self.word_space("+");
332 self.print_poly_trait_ref(bound);
334 if !lifetime.is_elided() {
336 self.word_space("+");
337 self.print_lifetime(lifetime);
340 hir::TyKind::Array(ref ty, ref length) => {
342 self.print_type(&ty);
344 self.print_anon_const(length);
347 hir::TyKind::Typeof(ref e) => {
348 self.s.word("typeof(");
349 self.print_anon_const(e);
352 hir::TyKind::Infer => {
355 hir::TyKind::Err => {
357 self.s.word("/*ERROR*/");
364 pub fn print_foreign_item(&mut self, item: &hir::ForeignItem) {
365 self.hardbreak_if_not_bol();
366 self.maybe_print_comment(item.span.lo());
367 self.print_outer_attributes(&item.attrs);
369 hir::ForeignItemKind::Fn(ref decl, ref arg_names, ref generics) => {
373 unsafety: hir::Unsafety::Normal,
374 constness: hir::Constness::NotConst,
376 asyncness: hir::IsAsync::NotAsync,
378 Some(item.ident.name),
383 self.end(); // end head-ibox
385 self.end() // end the outer fn box
387 hir::ForeignItemKind::Static(ref t, m) => {
388 self.head(visibility_qualified(&item.vis, "static"));
389 if m == hir::Mutability::Mut {
390 self.word_space("mut");
392 self.print_ident(item.ident);
393 self.word_space(":");
396 self.end(); // end the head-ibox
397 self.end() // end the outer cbox
399 hir::ForeignItemKind::Type => {
400 self.head(visibility_qualified(&item.vis, "type"));
401 self.print_ident(item.ident);
403 self.end(); // end the head-ibox
404 self.end() // end the outer cbox
409 fn print_associated_const(&mut self,
412 default: Option<hir::BodyId>,
413 vis: &hir::Visibility)
415 self.s.word(visibility_qualified(vis, ""));
416 self.word_space("const");
417 self.print_ident(ident);
418 self.word_space(":");
420 if let Some(expr) = default {
422 self.word_space("=");
423 self.ann.nested(self, Nested::Body(expr));
428 fn print_associated_type(&mut self,
430 bounds: Option<&hir::GenericBounds>,
431 ty: Option<&hir::Ty>)
433 self.word_space("type");
434 self.print_ident(ident);
435 if let Some(bounds) = bounds {
436 self.print_bounds(":", bounds);
438 if let Some(ty) = ty {
440 self.word_space("=");
448 item: &hir::Item<'_>,
449 generics: &hir::Generics,
450 inner: impl Fn(&mut Self),
452 self.head(visibility_qualified(&item.vis, "type"));
453 self.print_ident(item.ident);
454 self.print_generic_params(&generics.params);
455 self.end(); // end the inner ibox
457 self.print_where_clause(&generics.where_clause);
461 self.end(); // end the outer ibox
464 /// Pretty-print an item
465 pub fn print_item(&mut self, item: &hir::Item<'_>) {
466 self.hardbreak_if_not_bol();
467 self.maybe_print_comment(item.span.lo());
468 self.print_outer_attributes(&item.attrs);
469 self.ann.pre(self, AnnNode::Item(item));
471 hir::ItemKind::ExternCrate(orig_name) => {
472 self.head(visibility_qualified(&item.vis, "extern crate"));
473 if let Some(orig_name) = orig_name {
474 self.print_name(orig_name);
479 self.print_ident(item.ident);
481 self.end(); // end inner head-block
482 self.end(); // end outer head-block
484 hir::ItemKind::Use(ref path, kind) => {
485 self.head(visibility_qualified(&item.vis, "use"));
486 self.print_path(path, false);
489 hir::UseKind::Single => {
490 if path.segments.last().unwrap().ident != item.ident {
492 self.word_space("as");
493 self.print_ident(item.ident);
497 hir::UseKind::Glob => self.s.word("::*;"),
498 hir::UseKind::ListStem => self.s.word("::{};")
500 self.end(); // end inner head-block
501 self.end(); // end outer head-block
503 hir::ItemKind::Static(ref ty, m, expr) => {
504 self.head(visibility_qualified(&item.vis, "static"));
505 if m == hir::Mutability::Mut {
506 self.word_space("mut");
508 self.print_ident(item.ident);
509 self.word_space(":");
510 self.print_type(&ty);
512 self.end(); // end the head-ibox
514 self.word_space("=");
515 self.ann.nested(self, Nested::Body(expr));
517 self.end(); // end the outer cbox
519 hir::ItemKind::Const(ref ty, expr) => {
520 self.head(visibility_qualified(&item.vis, "const"));
521 self.print_ident(item.ident);
522 self.word_space(":");
523 self.print_type(&ty);
525 self.end(); // end the head-ibox
527 self.word_space("=");
528 self.ann.nested(self, Nested::Body(expr));
530 self.end(); // end the outer cbox
532 hir::ItemKind::Fn(ref sig, ref param_names, body) => {
534 self.print_fn(&sig.decl,
536 Some(item.ident.name),
542 self.end(); // need to close a box
543 self.end(); // need to close a box
544 self.ann.nested(self, Nested::Body(body));
546 hir::ItemKind::Mod(ref _mod) => {
547 self.head(visibility_qualified(&item.vis, "mod"));
548 self.print_ident(item.ident);
551 self.print_mod(_mod, &item.attrs);
552 self.bclose(item.span);
554 hir::ItemKind::ForeignMod(ref nmod) => {
556 self.word_nbsp(nmod.abi.to_string());
558 self.print_foreign_mod(nmod, &item.attrs);
559 self.bclose(item.span);
561 hir::ItemKind::GlobalAsm(ref ga) => {
562 self.head(visibility_qualified(&item.vis, "global asm"));
563 self.s.word(ga.asm.to_string());
566 hir::ItemKind::TyAlias(ref ty, ref generics) => {
567 self.print_item_type(item, &generics, |state| {
568 state.word_space("=");
569 state.print_type(&ty);
572 hir::ItemKind::OpaqueTy(ref opaque_ty) => {
573 self.print_item_type(item, &opaque_ty.generics, |state| {
574 let mut real_bounds = Vec::with_capacity(opaque_ty.bounds.len());
575 for b in opaque_ty.bounds.iter() {
576 if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
578 state.word_space("for ?");
579 state.print_trait_ref(&ptr.trait_ref);
584 state.print_bounds("= impl", real_bounds);
587 hir::ItemKind::Enum(ref enum_definition, ref params) => {
588 self.print_enum_def(enum_definition, params, item.ident.name, item.span, &item.vis);
590 hir::ItemKind::Struct(ref struct_def, ref generics) => {
591 self.head(visibility_qualified(&item.vis, "struct"));
592 self.print_struct(struct_def, generics, item.ident.name, item.span, true);
594 hir::ItemKind::Union(ref struct_def, ref generics) => {
595 self.head(visibility_qualified(&item.vis, "union"));
596 self.print_struct(struct_def, generics, item.ident.name, item.span, true);
598 hir::ItemKind::Impl(unsafety,
606 self.print_visibility(&item.vis);
607 self.print_defaultness(defaultness);
608 self.print_unsafety(unsafety);
609 self.word_nbsp("impl");
611 if !generics.params.is_empty() {
612 self.print_generic_params(&generics.params);
616 if let hir::ImplPolarity::Negative = polarity {
620 if let Some(ref t) = opt_trait {
621 self.print_trait_ref(t);
623 self.word_space("for");
626 self.print_type(&ty);
627 self.print_where_clause(&generics.where_clause);
631 self.print_inner_attributes(&item.attrs);
632 for impl_item in impl_items {
633 self.ann.nested(self, Nested::ImplItem(impl_item.id));
635 self.bclose(item.span);
637 hir::ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, trait_items) => {
639 self.print_visibility(&item.vis);
640 self.print_is_auto(is_auto);
641 self.print_unsafety(unsafety);
642 self.word_nbsp("trait");
643 self.print_ident(item.ident);
644 self.print_generic_params(&generics.params);
645 let mut real_bounds = Vec::with_capacity(bounds.len());
646 for b in bounds.iter() {
647 if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
649 self.word_space("for ?");
650 self.print_trait_ref(&ptr.trait_ref);
655 self.print_bounds(":", real_bounds);
656 self.print_where_clause(&generics.where_clause);
659 for trait_item in trait_items {
660 self.ann.nested(self, Nested::TraitItem(trait_item.id));
662 self.bclose(item.span);
664 hir::ItemKind::TraitAlias(ref generics, ref bounds) => {
666 self.print_visibility(&item.vis);
667 self.word_nbsp("trait");
668 self.print_ident(item.ident);
669 self.print_generic_params(&generics.params);
670 let mut real_bounds = Vec::with_capacity(bounds.len());
671 // FIXME(durka) this seems to be some quite outdated syntax
672 for b in bounds.iter() {
673 if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
675 self.word_space("for ?");
676 self.print_trait_ref(&ptr.trait_ref);
682 self.print_bounds("=", real_bounds);
683 self.print_where_clause(&generics.where_clause);
687 self.ann.post(self, AnnNode::Item(item))
690 pub fn print_trait_ref(&mut self, t: &hir::TraitRef) {
691 self.print_path(&t.path, false)
694 fn print_formal_generic_params(
696 generic_params: &[hir::GenericParam]
698 if !generic_params.is_empty() {
700 self.print_generic_params(generic_params);
705 fn print_poly_trait_ref(&mut self, t: &hir::PolyTraitRef) {
706 self.print_formal_generic_params(&t.bound_generic_params);
707 self.print_trait_ref(&t.trait_ref)
710 pub fn print_enum_def(&mut self,
711 enum_definition: &hir::EnumDef,
712 generics: &hir::Generics,
714 span: syntax_pos::Span,
715 visibility: &hir::Visibility)
717 self.head(visibility_qualified(visibility, "enum"));
718 self.print_name(name);
719 self.print_generic_params(&generics.params);
720 self.print_where_clause(&generics.where_clause);
722 self.print_variants(&enum_definition.variants, span)
725 pub fn print_variants(&mut self,
726 variants: &[hir::Variant],
727 span: syntax_pos::Span)
731 self.space_if_not_bol();
732 self.maybe_print_comment(v.span.lo());
733 self.print_outer_attributes(&v.attrs);
734 self.ibox(INDENT_UNIT);
735 self.print_variant(v);
738 self.maybe_print_trailing_comment(v.span, None);
743 pub fn print_visibility(&mut self, vis: &hir::Visibility) {
745 hir::VisibilityKind::Public => self.word_nbsp("pub"),
746 hir::VisibilityKind::Crate(ast::CrateSugar::JustCrate) => self.word_nbsp("crate"),
747 hir::VisibilityKind::Crate(ast::CrateSugar::PubCrate) => self.word_nbsp("pub(crate)"),
748 hir::VisibilityKind::Restricted { ref path, .. } => {
750 if path.segments.len() == 1 &&
751 path.segments[0].ident.name == kw::Super {
752 // Special case: `super` can print like `pub(super)`.
753 self.s.word("super");
755 // Everything else requires `in` at present.
756 self.word_nbsp("in");
757 self.print_path(path, false);
761 hir::VisibilityKind::Inherited => ()
765 pub fn print_defaultness(&mut self, defaultness: hir::Defaultness) {
767 hir::Defaultness::Default { .. } => self.word_nbsp("default"),
768 hir::Defaultness::Final => (),
772 pub fn print_struct(&mut self,
773 struct_def: &hir::VariantData,
774 generics: &hir::Generics,
776 span: syntax_pos::Span,
777 print_finalizer: bool)
779 self.print_name(name);
780 self.print_generic_params(&generics.params);
782 hir::VariantData::Tuple(..) | hir::VariantData::Unit(..) => {
783 if let hir::VariantData::Tuple(..) = struct_def {
785 self.commasep(Inconsistent, struct_def.fields(), |s, field| {
786 s.maybe_print_comment(field.span.lo());
787 s.print_outer_attributes(&field.attrs);
788 s.print_visibility(&field.vis);
789 s.print_type(&field.ty)
793 self.print_where_clause(&generics.where_clause);
798 self.end() // close the outer-box
800 hir::VariantData::Struct(..) => {
801 self.print_where_clause(&generics.where_clause);
804 self.hardbreak_if_not_bol();
806 for field in struct_def.fields() {
807 self.hardbreak_if_not_bol();
808 self.maybe_print_comment(field.span.lo());
809 self.print_outer_attributes(&field.attrs);
810 self.print_visibility(&field.vis);
811 self.print_ident(field.ident);
813 self.print_type(&field.ty);
822 pub fn print_variant(&mut self, v: &hir::Variant) {
824 let generics = hir::Generics::empty();
825 self.print_struct(&v.data, &generics, v.ident.name, v.span, false);
826 if let Some(ref d) = v.disr_expr {
828 self.word_space("=");
829 self.print_anon_const(d);
832 pub fn print_method_sig(&mut self,
835 generics: &hir::Generics,
836 vis: &hir::Visibility,
837 arg_names: &[ast::Ident],
838 body_id: Option<hir::BodyId>)
840 self.print_fn(&m.decl,
849 pub fn print_trait_item(&mut self, ti: &hir::TraitItem) {
850 self.ann.pre(self, AnnNode::SubItem(ti.hir_id));
851 self.hardbreak_if_not_bol();
852 self.maybe_print_comment(ti.span.lo());
853 self.print_outer_attributes(&ti.attrs);
855 hir::TraitItemKind::Const(ref ty, default) => {
856 let vis = Spanned { span: syntax_pos::DUMMY_SP,
857 node: hir::VisibilityKind::Inherited };
858 self.print_associated_const(ti.ident, &ty, default, &vis);
860 hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Required(ref arg_names)) => {
861 let vis = Spanned { span: syntax_pos::DUMMY_SP,
862 node: hir::VisibilityKind::Inherited };
863 self.print_method_sig(ti.ident, sig, &ti.generics, &vis, arg_names, None);
866 hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Provided(body)) => {
867 let vis = Spanned { span: syntax_pos::DUMMY_SP,
868 node: hir::VisibilityKind::Inherited };
870 self.print_method_sig(ti.ident, sig, &ti.generics, &vis, &[], Some(body));
872 self.end(); // need to close a box
873 self.end(); // need to close a box
874 self.ann.nested(self, Nested::Body(body));
876 hir::TraitItemKind::Type(ref bounds, ref default) => {
877 self.print_associated_type(ti.ident,
879 default.as_ref().map(|ty| &**ty));
882 self.ann.post(self, AnnNode::SubItem(ti.hir_id))
885 pub fn print_impl_item(&mut self, ii: &hir::ImplItem) {
886 self.ann.pre(self, AnnNode::SubItem(ii.hir_id));
887 self.hardbreak_if_not_bol();
888 self.maybe_print_comment(ii.span.lo());
889 self.print_outer_attributes(&ii.attrs);
890 self.print_defaultness(ii.defaultness);
893 hir::ImplItemKind::Const(ref ty, expr) => {
894 self.print_associated_const(ii.ident, &ty, Some(expr), &ii.vis);
896 hir::ImplItemKind::Method(ref sig, body) => {
898 self.print_method_sig(ii.ident, sig, &ii.generics, &ii.vis, &[], Some(body));
900 self.end(); // need to close a box
901 self.end(); // need to close a box
902 self.ann.nested(self, Nested::Body(body));
904 hir::ImplItemKind::TyAlias(ref ty) => {
905 self.print_associated_type(ii.ident, None, Some(ty));
907 hir::ImplItemKind::OpaqueTy(ref bounds) => {
908 self.word_space("type");
909 self.print_ident(ii.ident);
910 self.print_bounds("= impl", bounds);
914 self.ann.post(self, AnnNode::SubItem(ii.hir_id))
919 init: Option<&hir::Expr>,
920 decl: impl Fn(&mut Self)
922 self.space_if_not_bol();
923 self.ibox(INDENT_UNIT);
924 self.word_nbsp("let");
926 self.ibox(INDENT_UNIT);
930 if let Some(ref init) = init {
932 self.word_space("=");
933 self.print_expr(&init);
938 pub fn print_stmt(&mut self, st: &hir::Stmt) {
939 self.maybe_print_comment(st.span.lo());
941 hir::StmtKind::Local(ref loc) => {
942 self.print_local(loc.init.as_deref(), |this| this.print_local_decl(&loc));
944 hir::StmtKind::Item(item) => {
945 self.ann.nested(self, Nested::Item(item))
947 hir::StmtKind::Expr(ref expr) => {
948 self.space_if_not_bol();
949 self.print_expr(&expr);
951 hir::StmtKind::Semi(ref expr) => {
952 self.space_if_not_bol();
953 self.print_expr(&expr);
957 if stmt_ends_with_semi(&st.kind) {
960 self.maybe_print_trailing_comment(st.span, None)
963 pub fn print_block(&mut self, blk: &hir::Block) {
964 self.print_block_with_attrs(blk, &[])
967 pub fn print_block_unclosed(&mut self, blk: &hir::Block) {
968 self.print_block_maybe_unclosed(blk, &[], false)
971 pub fn print_block_with_attrs(&mut self,
973 attrs: &[ast::Attribute])
975 self.print_block_maybe_unclosed(blk, attrs, true)
978 pub fn print_block_maybe_unclosed(&mut self,
980 attrs: &[ast::Attribute],
984 hir::UnsafeBlock(..) => self.word_space("unsafe"),
985 hir::PushUnsafeBlock(..) => self.word_space("push_unsafe"),
986 hir::PopUnsafeBlock(..) => self.word_space("pop_unsafe"),
987 hir::DefaultBlock => (),
989 self.maybe_print_comment(blk.span.lo());
990 self.ann.pre(self, AnnNode::Block(blk));
993 self.print_inner_attributes(attrs);
995 for st in &blk.stmts {
998 if let Some(ref expr) = blk.expr {
999 self.space_if_not_bol();
1000 self.print_expr(&expr);
1001 self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi()));
1003 self.bclose_maybe_open(blk.span, close_box);
1004 self.ann.post(self, AnnNode::Block(blk))
1007 pub fn print_anon_const(&mut self, constant: &hir::AnonConst) {
1008 self.ann.nested(self, Nested::Body(constant.body))
1011 fn print_call_post(&mut self, args: &[hir::Expr]) {
1013 self.commasep_exprs(Inconsistent, args);
1017 pub fn print_expr_maybe_paren(&mut self, expr: &hir::Expr, prec: i8) {
1018 let needs_par = expr.precedence().order() < prec;
1022 self.print_expr(expr);
1028 /// Print an expr using syntax that's acceptable in a condition position, such as the `cond` in
1029 /// `if cond { ... }`.
1030 pub fn print_expr_as_cond(&mut self, expr: &hir::Expr) {
1031 let needs_par = match expr.kind {
1032 // These cases need parens due to the parse error observed in #26461: `if return {}`
1033 // parses as the erroneous construct `if (return {})`, not `if (return) {}`.
1034 hir::ExprKind::Closure(..) |
1035 hir::ExprKind::Ret(..) |
1036 hir::ExprKind::Break(..) => true,
1038 _ => contains_exterior_struct_lit(expr),
1044 self.print_expr(expr);
1050 fn print_expr_vec(&mut self, exprs: &[hir::Expr]) {
1051 self.ibox(INDENT_UNIT);
1053 self.commasep_exprs(Inconsistent, exprs);
1058 fn print_expr_repeat(&mut self, element: &hir::Expr, count: &hir::AnonConst) {
1059 self.ibox(INDENT_UNIT);
1061 self.print_expr(element);
1062 self.word_space(";");
1063 self.print_anon_const(count);
1068 fn print_expr_struct(&mut self,
1070 fields: &[hir::Field],
1071 wth: &Option<P<hir::Expr>>)
1073 self.print_qpath(qpath, true);
1075 self.commasep_cmnt(Consistent,
1078 s.ibox(INDENT_UNIT);
1079 if !field.is_shorthand {
1080 s.print_ident(field.ident);
1083 s.print_expr(&field.expr);
1089 self.ibox(INDENT_UNIT);
1090 if !fields.is_empty() {
1095 self.print_expr(&expr);
1098 _ => if !fields.is_empty() {
1105 fn print_expr_tup(&mut self, exprs: &[hir::Expr]) {
1107 self.commasep_exprs(Inconsistent, exprs);
1108 if exprs.len() == 1 {
1114 fn print_expr_call(&mut self, func: &hir::Expr, args: &[hir::Expr]) {
1115 let prec = match func.kind {
1116 hir::ExprKind::Field(..) => parser::PREC_FORCE_PAREN,
1117 _ => parser::PREC_POSTFIX,
1120 self.print_expr_maybe_paren(func, prec);
1121 self.print_call_post(args)
1124 fn print_expr_method_call(&mut self,
1125 segment: &hir::PathSegment,
1128 let base_args = &args[1..];
1129 self.print_expr_maybe_paren(&args[0], parser::PREC_POSTFIX);
1131 self.print_ident(segment.ident);
1133 let generic_args = segment.generic_args();
1134 if !generic_args.args.is_empty() || !generic_args.bindings.is_empty() {
1135 self.print_generic_args(generic_args, segment.infer_args, true);
1138 self.print_call_post(base_args)
1141 fn print_expr_binary(&mut self,
1146 let assoc_op = bin_op_to_assoc_op(op.node);
1147 let prec = assoc_op.precedence() as i8;
1148 let fixity = assoc_op.fixity();
1150 let (left_prec, right_prec) = match fixity {
1151 Fixity::Left => (prec, prec + 1),
1152 Fixity::Right => (prec + 1, prec),
1153 Fixity::None => (prec + 1, prec + 1),
1156 let left_prec = match (&lhs.kind, op.node) {
1157 // These cases need parens: `x as i32 < y` has the parser thinking that `i32 < y` is
1158 // the beginning of a path type. It starts trying to parse `x as (i32 < y ...` instead
1159 // of `(x as i32) < ...`. We need to convince it _not_ to do that.
1160 (&hir::ExprKind::Cast { .. }, hir::BinOpKind::Lt) |
1161 (&hir::ExprKind::Cast { .. }, hir::BinOpKind::Shl) => parser::PREC_FORCE_PAREN,
1165 self.print_expr_maybe_paren(lhs, left_prec);
1167 self.word_space(op.node.as_str());
1168 self.print_expr_maybe_paren(rhs, right_prec)
1171 fn print_expr_unary(&mut self, op: hir::UnOp, expr: &hir::Expr) {
1172 self.s.word(op.as_str());
1173 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1176 fn print_expr_addr_of(&mut self,
1177 kind: hir::BorrowKind,
1178 mutability: hir::Mutability,
1183 hir::BorrowKind::Ref => self.print_mutability(mutability, false),
1184 hir::BorrowKind::Raw => {
1185 self.word_nbsp("raw");
1186 self.print_mutability(mutability, true);
1189 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1192 fn print_literal(&mut self, lit: &hir::Lit) {
1193 self.maybe_print_comment(lit.span.lo());
1194 self.word(lit.node.to_lit_token().to_string())
1197 pub fn print_expr(&mut self, expr: &hir::Expr) {
1198 self.maybe_print_comment(expr.span.lo());
1199 self.print_outer_attributes(&expr.attrs);
1200 self.ibox(INDENT_UNIT);
1201 self.ann.pre(self, AnnNode::Expr(expr));
1203 hir::ExprKind::Box(ref expr) => {
1204 self.word_space("box");
1205 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX);
1207 hir::ExprKind::Array(ref exprs) => {
1208 self.print_expr_vec(exprs);
1210 hir::ExprKind::Repeat(ref element, ref count) => {
1211 self.print_expr_repeat(&element, count);
1213 hir::ExprKind::Struct(ref qpath, ref fields, ref wth) => {
1214 self.print_expr_struct(qpath, &fields[..], wth);
1216 hir::ExprKind::Tup(ref exprs) => {
1217 self.print_expr_tup(exprs);
1219 hir::ExprKind::Call(ref func, ref args) => {
1220 self.print_expr_call(&func, args);
1222 hir::ExprKind::MethodCall(ref segment, _, ref args) => {
1223 self.print_expr_method_call(segment, args);
1225 hir::ExprKind::Binary(op, ref lhs, ref rhs) => {
1226 self.print_expr_binary(op, &lhs, &rhs);
1228 hir::ExprKind::Unary(op, ref expr) => {
1229 self.print_expr_unary(op, &expr);
1231 hir::ExprKind::AddrOf(k, m, ref expr) => {
1232 self.print_expr_addr_of(k, m, &expr);
1234 hir::ExprKind::Lit(ref lit) => {
1235 self.print_literal(&lit);
1237 hir::ExprKind::Cast(ref expr, ref ty) => {
1238 let prec = AssocOp::As.precedence() as i8;
1239 self.print_expr_maybe_paren(&expr, prec);
1241 self.word_space("as");
1242 self.print_type(&ty);
1244 hir::ExprKind::Type(ref expr, ref ty) => {
1245 let prec = AssocOp::Colon.precedence() as i8;
1246 self.print_expr_maybe_paren(&expr, prec);
1247 self.word_space(":");
1248 self.print_type(&ty);
1250 hir::ExprKind::DropTemps(ref init) => {
1252 self.cbox(INDENT_UNIT);
1256 // Print `let _t = $init;`:
1257 let temp = ast::Ident::from_str("_t");
1258 self.print_local(Some(init), |this| this.print_ident(temp));
1262 self.space_if_not_bol();
1263 self.print_ident(temp);
1266 self.bclose_maybe_open(expr.span, true);
1268 hir::ExprKind::Loop(ref blk, opt_label, _) => {
1269 if let Some(label) = opt_label {
1270 self.print_ident(label.ident);
1271 self.word_space(":");
1275 self.print_block(&blk);
1277 hir::ExprKind::Match(ref expr, ref arms, _) => {
1278 self.cbox(INDENT_UNIT);
1279 self.ibox(INDENT_UNIT);
1280 self.word_nbsp("match");
1281 self.print_expr_as_cond(&expr);
1285 self.print_arm(arm);
1287 self.bclose(expr.span);
1289 hir::ExprKind::Closure(capture_clause, ref decl, body, _fn_decl_span, _gen) => {
1290 self.print_capture_clause(capture_clause);
1292 self.print_closure_params(&decl, body);
1295 // This is a bare expression.
1296 self.ann.nested(self, Nested::Body(body));
1297 self.end(); // need to close a box
1299 // A box will be closed by `print_expr`, but we didn't want an overall
1300 // wrapper so we closed the corresponding opening. so create an
1301 // empty box to satisfy the close.
1304 hir::ExprKind::Block(ref blk, opt_label) => {
1305 if let Some(label) = opt_label {
1306 self.print_ident(label.ident);
1307 self.word_space(":");
1309 // containing cbox, will be closed by print-block at `}`
1310 self.cbox(INDENT_UNIT);
1311 // head-box, will be closed by print-block after `{`
1313 self.print_block(&blk);
1315 hir::ExprKind::Assign(ref lhs, ref rhs) => {
1316 let prec = AssocOp::Assign.precedence() as i8;
1317 self.print_expr_maybe_paren(&lhs, prec + 1);
1319 self.word_space("=");
1320 self.print_expr_maybe_paren(&rhs, prec);
1322 hir::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
1323 let prec = AssocOp::Assign.precedence() as i8;
1324 self.print_expr_maybe_paren(&lhs, prec + 1);
1326 self.s.word(op.node.as_str());
1327 self.word_space("=");
1328 self.print_expr_maybe_paren(&rhs, prec);
1330 hir::ExprKind::Field(ref expr, ident) => {
1331 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
1333 self.print_ident(ident);
1335 hir::ExprKind::Index(ref expr, ref index) => {
1336 self.print_expr_maybe_paren(&expr, parser::PREC_POSTFIX);
1338 self.print_expr(&index);
1341 hir::ExprKind::Path(ref qpath) => {
1342 self.print_qpath(qpath, true)
1344 hir::ExprKind::Break(destination, ref opt_expr) => {
1345 self.s.word("break");
1347 if let Some(label) = destination.label {
1348 self.print_ident(label.ident);
1351 if let Some(ref expr) = *opt_expr {
1352 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
1356 hir::ExprKind::Continue(destination) => {
1357 self.s.word("continue");
1359 if let Some(label) = destination.label {
1360 self.print_ident(label.ident);
1364 hir::ExprKind::Ret(ref result) => {
1365 self.s.word("return");
1366 if let Some(ref expr) = *result {
1368 self.print_expr_maybe_paren(&expr, parser::PREC_JUMP);
1371 hir::ExprKind::InlineAsm(ref a) => {
1373 self.s.word("asm!");
1375 self.print_string(&i.asm.as_str(), i.asm_str_style);
1376 self.word_space(":");
1378 let mut out_idx = 0;
1379 self.commasep(Inconsistent, &i.outputs, |s, out| {
1380 let constraint = out.constraint.as_str();
1381 let mut ch = constraint.chars();
1383 Some('=') if out.is_rw => {
1384 s.print_string(&format!("+{}", ch.as_str()),
1385 ast::StrStyle::Cooked)
1387 _ => s.print_string(&constraint, ast::StrStyle::Cooked),
1390 s.print_expr(&a.outputs_exprs[out_idx]);
1395 self.word_space(":");
1398 self.commasep(Inconsistent, &i.inputs, |s, co| {
1399 s.print_string(&co.as_str(), ast::StrStyle::Cooked);
1401 s.print_expr(&a.inputs_exprs[in_idx]);
1406 self.word_space(":");
1408 self.commasep(Inconsistent, &i.clobbers, |s, co| {
1409 s.print_string(&co.as_str(), ast::StrStyle::Cooked);
1412 let mut options = vec![];
1414 options.push("volatile");
1417 options.push("alignstack");
1419 if i.dialect == ast::AsmDialect::Intel {
1420 options.push("intel");
1423 if !options.is_empty() {
1425 self.word_space(":");
1426 self.commasep(Inconsistent, &options, |s, &co| {
1427 s.print_string(co, ast::StrStyle::Cooked);
1433 hir::ExprKind::Yield(ref expr, _) => {
1434 self.word_space("yield");
1435 self.print_expr_maybe_paren(&expr, parser::PREC_JUMP);
1437 hir::ExprKind::Err => {
1439 self.s.word("/*ERROR*/");
1443 self.ann.post(self, AnnNode::Expr(expr));
1447 pub fn print_local_decl(&mut self, loc: &hir::Local) {
1448 self.print_pat(&loc.pat);
1449 if let Some(ref ty) = loc.ty {
1450 self.word_space(":");
1451 self.print_type(&ty);
1455 pub fn print_usize(&mut self, i: usize) {
1456 self.s.word(i.to_string())
1459 pub fn print_name(&mut self, name: ast::Name) {
1460 self.print_ident(ast::Ident::with_dummy_span(name))
1463 pub fn print_for_decl(&mut self, loc: &hir::Local, coll: &hir::Expr) {
1464 self.print_local_decl(loc);
1466 self.word_space("in");
1467 self.print_expr(coll)
1470 pub fn print_path(&mut self,
1472 colons_before_params: bool)
1474 self.maybe_print_comment(path.span.lo());
1476 for (i, segment) in path.segments.iter().enumerate() {
1480 if segment.ident.name != kw::PathRoot {
1481 self.print_ident(segment.ident);
1482 self.print_generic_args(segment.generic_args(), segment.infer_args,
1483 colons_before_params);
1488 pub fn print_path_segment(&mut self, segment: &hir::PathSegment) {
1489 if segment.ident.name != kw::PathRoot {
1490 self.print_ident(segment.ident);
1491 self.print_generic_args(segment.generic_args(), segment.infer_args, false);
1495 pub fn print_qpath(&mut self,
1497 colons_before_params: bool)
1500 hir::QPath::Resolved(None, ref path) => {
1501 self.print_path(path, colons_before_params)
1503 hir::QPath::Resolved(Some(ref qself), ref path) => {
1505 self.print_type(qself);
1507 self.word_space("as");
1509 for (i, segment) in path.segments[..path.segments.len() - 1].iter().enumerate() {
1513 if segment.ident.name != kw::PathRoot {
1514 self.print_ident(segment.ident);
1515 self.print_generic_args(segment.generic_args(),
1517 colons_before_params);
1523 let item_segment = path.segments.last().unwrap();
1524 self.print_ident(item_segment.ident);
1525 self.print_generic_args(item_segment.generic_args(),
1526 item_segment.infer_args,
1527 colons_before_params)
1529 hir::QPath::TypeRelative(ref qself, ref item_segment) => {
1530 // If we've got a compound-qualified-path, let's push an additional pair of angle
1531 // brackets, so that we pretty-print `<<A::B>::C>` as `<A::B>::C`, instead of just
1532 // `A::B::C` (since the latter could be ambiguous to the user)
1533 if let hir::TyKind::Path(hir::QPath::Resolved(None, _)) = &qself.kind {
1534 self.print_type(qself);
1537 self.print_type(qself);
1542 self.print_ident(item_segment.ident);
1543 self.print_generic_args(item_segment.generic_args(),
1544 item_segment.infer_args,
1545 colons_before_params)
1550 fn print_generic_args(&mut self,
1551 generic_args: &hir::GenericArgs,
1553 colons_before_params: bool)
1555 if generic_args.parenthesized {
1557 self.commasep(Inconsistent, generic_args.inputs(), |s, ty| s.print_type(&ty));
1560 self.space_if_not_bol();
1561 self.word_space("->");
1562 self.print_type(generic_args.bindings[0].ty());
1564 let start = if colons_before_params { "::<" } else { "<" };
1565 let empty = Cell::new(true);
1566 let start_or_comma = |this: &mut Self| {
1571 this.word_space(",")
1575 let mut nonelided_generic_args: bool = false;
1576 let elide_lifetimes = generic_args.args.iter().all(|arg| match arg {
1577 GenericArg::Lifetime(lt) => lt.is_elided(),
1579 nonelided_generic_args = true;
1584 if nonelided_generic_args {
1585 start_or_comma(self);
1586 self.commasep(Inconsistent, &generic_args.args, |s, generic_arg| {
1588 GenericArg::Lifetime(lt) if !elide_lifetimes => s.print_lifetime(lt),
1589 GenericArg::Lifetime(_) => {},
1590 GenericArg::Type(ty) => s.print_type(ty),
1591 GenericArg::Const(ct) => s.print_anon_const(&ct.value),
1596 // FIXME(eddyb): this would leak into error messages (e.g.,
1597 // "non-exhaustive patterns: `Some::<..>(_)` not covered").
1598 if infer_args && false {
1599 start_or_comma(self);
1603 for binding in generic_args.bindings.iter() {
1604 start_or_comma(self);
1605 self.print_ident(binding.ident);
1607 match generic_args.bindings[0].kind {
1608 hir::TypeBindingKind::Equality { ref ty } => {
1609 self.word_space("=");
1610 self.print_type(ty);
1612 hir::TypeBindingKind::Constraint { ref bounds } => {
1613 self.print_bounds(":", bounds);
1624 pub fn print_pat(&mut self, pat: &hir::Pat) {
1625 self.maybe_print_comment(pat.span.lo());
1626 self.ann.pre(self, AnnNode::Pat(pat));
1627 // Pat isn't normalized, but the beauty of it
1628 // is that it doesn't matter
1630 PatKind::Wild => self.s.word("_"),
1631 PatKind::Binding(binding_mode, _, ident, ref sub) => {
1632 match binding_mode {
1633 hir::BindingAnnotation::Ref => {
1634 self.word_nbsp("ref");
1635 self.print_mutability(hir::Mutability::Not, false);
1637 hir::BindingAnnotation::RefMut => {
1638 self.word_nbsp("ref");
1639 self.print_mutability(hir::Mutability::Mut, false);
1641 hir::BindingAnnotation::Unannotated => {}
1642 hir::BindingAnnotation::Mutable => {
1643 self.word_nbsp("mut");
1646 self.print_ident(ident);
1647 if let Some(ref p) = *sub {
1652 PatKind::TupleStruct(ref qpath, ref elts, ddpos) => {
1653 self.print_qpath(qpath, true);
1655 if let Some(ddpos) = ddpos {
1656 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p));
1658 self.word_space(",");
1661 if ddpos != elts.len() {
1663 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p));
1666 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p));
1670 PatKind::Path(ref qpath) => {
1671 self.print_qpath(qpath, true);
1673 PatKind::Struct(ref qpath, ref fields, etc) => {
1674 self.print_qpath(qpath, true);
1676 self.word_space("{");
1677 self.commasep_cmnt(Consistent,
1680 s.cbox(INDENT_UNIT);
1681 if !f.is_shorthand {
1682 s.print_ident(f.ident);
1685 s.print_pat(&f.pat);
1690 if !fields.is_empty() {
1691 self.word_space(",");
1698 PatKind::Or(ref pats) => {
1699 self.strsep("|", true, Inconsistent, &pats[..], |s, p| s.print_pat(&p));
1701 PatKind::Tuple(ref elts, ddpos) => {
1703 if let Some(ddpos) = ddpos {
1704 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p));
1706 self.word_space(",");
1709 if ddpos != elts.len() {
1711 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p));
1714 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p));
1715 if elts.len() == 1 {
1721 PatKind::Box(ref inner) => {
1722 let is_range_inner = match inner.kind {
1723 PatKind::Range(..) => true,
1726 self.s.word("box ");
1730 self.print_pat(&inner);
1735 PatKind::Ref(ref inner, mutbl) => {
1736 let is_range_inner = match inner.kind {
1737 PatKind::Range(..) => true,
1741 self.s.word(mutbl.prefix_str());
1745 self.print_pat(&inner);
1750 PatKind::Lit(ref e) => self.print_expr(&e),
1751 PatKind::Range(ref begin, ref end, ref end_kind) => {
1752 self.print_expr(&begin);
1755 RangeEnd::Included => self.s.word("..."),
1756 RangeEnd::Excluded => self.s.word(".."),
1758 self.print_expr(&end);
1760 PatKind::Slice(ref before, ref slice, ref after) => {
1762 self.commasep(Inconsistent, &before[..], |s, p| s.print_pat(&p));
1763 if let Some(ref p) = *slice {
1764 if !before.is_empty() {
1765 self.word_space(",");
1767 if let PatKind::Wild = p.kind {
1773 if !after.is_empty() {
1774 self.word_space(",");
1777 self.commasep(Inconsistent, &after[..], |s, p| s.print_pat(&p));
1781 self.ann.post(self, AnnNode::Pat(pat))
1784 pub fn print_param(&mut self, arg: &hir::Param) {
1785 self.print_outer_attributes(&arg.attrs);
1786 self.print_pat(&arg.pat);
1789 pub fn print_arm(&mut self, arm: &hir::Arm) {
1790 // I have no idea why this check is necessary, but here it
1792 if arm.attrs.is_empty() {
1795 self.cbox(INDENT_UNIT);
1796 self.ann.pre(self, AnnNode::Arm(arm));
1798 self.print_outer_attributes(&arm.attrs);
1799 self.print_pat(&arm.pat);
1801 if let Some(ref g) = arm.guard {
1803 hir::Guard::If(e) => {
1804 self.word_space("if");
1805 self.print_expr(&e);
1810 self.word_space("=>");
1812 match arm.body.kind {
1813 hir::ExprKind::Block(ref blk, opt_label) => {
1814 if let Some(label) = opt_label {
1815 self.print_ident(label.ident);
1816 self.word_space(":");
1818 // the block will close the pattern's ibox
1819 self.print_block_unclosed(&blk);
1821 // If it is a user-provided unsafe block, print a comma after it
1822 if let hir::UnsafeBlock(hir::UserProvided) = blk.rules {
1827 self.end(); // close the ibox for the pattern
1828 self.print_expr(&arm.body);
1832 self.ann.post(self, AnnNode::Arm(arm));
1833 self.end() // close enclosing cbox
1836 pub fn print_fn(&mut self,
1838 header: hir::FnHeader,
1839 name: Option<ast::Name>,
1840 generics: &hir::Generics,
1841 vis: &hir::Visibility,
1842 arg_names: &[ast::Ident],
1843 body_id: Option<hir::BodyId>)
1845 self.print_fn_header_info(header, vis);
1847 if let Some(name) = name {
1849 self.print_name(name);
1851 self.print_generic_params(&generics.params);
1855 // Make sure we aren't supplied *both* `arg_names` and `body_id`.
1856 assert!(arg_names.is_empty() || body_id.is_none());
1857 self.commasep(Inconsistent, &decl.inputs, |s, ty| {
1858 s.ibox(INDENT_UNIT);
1859 if let Some(arg_name) = arg_names.get(i) {
1860 s.s.word(arg_name.to_string());
1863 } else if let Some(body_id) = body_id {
1864 s.ann.nested(s, Nested::BodyParamPat(body_id, i));
1872 if decl.c_variadic {
1873 self.s.word(", ...");
1877 self.print_fn_output(decl);
1878 self.print_where_clause(&generics.where_clause)
1881 fn print_closure_params(&mut self, decl: &hir::FnDecl, body_id: hir::BodyId) {
1884 self.commasep(Inconsistent, &decl.inputs, |s, ty| {
1885 s.ibox(INDENT_UNIT);
1887 s.ann.nested(s, Nested::BodyParamPat(body_id, i));
1890 if let hir::TyKind::Infer = ty.kind {
1901 if let hir::DefaultReturn(..) = decl.output {
1905 self.space_if_not_bol();
1906 self.word_space("->");
1908 hir::Return(ref ty) => {
1909 self.print_type(&ty);
1910 self.maybe_print_comment(ty.span.lo())
1912 hir::DefaultReturn(..) => unreachable!(),
1916 pub fn print_capture_clause(&mut self, capture_clause: hir::CaptureBy) {
1917 match capture_clause {
1918 hir::CaptureBy::Value => self.word_space("move"),
1919 hir::CaptureBy::Ref => {},
1923 pub fn print_bounds<'b>(
1925 prefix: &'static str,
1926 bounds: impl IntoIterator<Item = &'b hir::GenericBound>,
1928 let mut first = true;
1929 for bound in bounds {
1931 self.s.word(prefix);
1933 if !(first && prefix.is_empty()) {
1939 self.word_space("+");
1943 GenericBound::Trait(tref, modifier) => {
1944 if modifier == &TraitBoundModifier::Maybe {
1947 self.print_poly_trait_ref(tref);
1949 GenericBound::Outlives(lt) => {
1950 self.print_lifetime(lt);
1956 pub fn print_generic_params(&mut self, generic_params: &[GenericParam]) {
1957 if !generic_params.is_empty() {
1960 self.commasep(Inconsistent, generic_params, |s, param| {
1961 s.print_generic_param(param)
1968 pub fn print_generic_param(&mut self, param: &GenericParam) {
1969 if let GenericParamKind::Const { .. } = param.kind {
1970 self.word_space("const");
1973 self.print_ident(param.name.ident());
1976 GenericParamKind::Lifetime { .. } => {
1978 for bound in ¶m.bounds {
1980 GenericBound::Outlives(lt) => {
1982 self.print_lifetime(lt);
1989 GenericParamKind::Type { ref default, .. } => {
1990 self.print_bounds(":", ¶m.bounds);
1994 self.word_space("=");
1995 self.print_type(&default)
2000 GenericParamKind::Const { ref ty } => {
2001 self.word_space(":");
2007 pub fn print_lifetime(&mut self, lifetime: &hir::Lifetime) {
2008 self.print_ident(lifetime.name.ident())
2011 pub fn print_where_clause(&mut self, where_clause: &hir::WhereClause) {
2012 if where_clause.predicates.is_empty() {
2017 self.word_space("where");
2019 for (i, predicate) in where_clause.predicates.iter().enumerate() {
2021 self.word_space(",");
2025 &hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
2026 ref bound_generic_params,
2031 self.print_formal_generic_params(bound_generic_params);
2032 self.print_type(&bounded_ty);
2033 self.print_bounds(":", bounds);
2035 &hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate{ref lifetime,
2038 self.print_lifetime(lifetime);
2041 for (i, bound) in bounds.iter().enumerate() {
2043 GenericBound::Outlives(lt) => {
2044 self.print_lifetime(lt);
2054 &hir::WherePredicate::EqPredicate(hir::WhereEqPredicate{ref lhs_ty,
2057 self.print_type(lhs_ty);
2059 self.word_space("=");
2060 self.print_type(rhs_ty);
2066 pub fn print_mutability(&mut self, mutbl: hir::Mutability, print_const: bool) {
2068 hir::Mutability::Mut => self.word_nbsp("mut"),
2069 hir::Mutability::Not => if print_const { self.word_nbsp("const") },
2073 pub fn print_mt(&mut self, mt: &hir::MutTy, print_const: bool) {
2074 self.print_mutability(mt.mutbl, print_const);
2075 self.print_type(&mt.ty)
2078 pub fn print_fn_output(&mut self, decl: &hir::FnDecl) {
2079 if let hir::DefaultReturn(..) = decl.output {
2083 self.space_if_not_bol();
2084 self.ibox(INDENT_UNIT);
2085 self.word_space("->");
2087 hir::DefaultReturn(..) => unreachable!(),
2088 hir::Return(ref ty) => self.print_type(&ty),
2093 hir::Return(ref output) => self.maybe_print_comment(output.span.lo()),
2098 pub fn print_ty_fn(&mut self,
2100 unsafety: hir::Unsafety,
2102 name: Option<ast::Name>,
2103 generic_params: &[hir::GenericParam],
2104 arg_names: &[ast::Ident])
2106 self.ibox(INDENT_UNIT);
2107 if !generic_params.is_empty() {
2109 self.print_generic_params(generic_params);
2111 let generics = hir::Generics {
2112 params: hir::HirVec::new(),
2113 where_clause: hir::WhereClause {
2114 predicates: hir::HirVec::new(),
2115 span: syntax_pos::DUMMY_SP,
2117 span: syntax_pos::DUMMY_SP,
2123 constness: hir::Constness::NotConst,
2124 asyncness: hir::IsAsync::NotAsync,
2128 &Spanned { span: syntax_pos::DUMMY_SP,
2129 node: hir::VisibilityKind::Inherited },
2135 pub fn maybe_print_trailing_comment(&mut self,
2136 span: syntax_pos::Span,
2137 next_pos: Option<BytePos>)
2139 if let Some(cmnts) = self.comments() {
2140 if let Some(cmnt) = cmnts.trailing_comment(span, next_pos) {
2141 self.print_comment(&cmnt);
2146 pub fn print_remaining_comments(&mut self) {
2147 // If there aren't any remaining comments, then we need to manually
2148 // make sure there is a line break at the end.
2149 if self.next_comment().is_none() {
2152 while let Some(ref cmnt) = self.next_comment() {
2153 self.print_comment(cmnt)
2157 pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
2158 opt_abi: Option<Abi>)
2161 Some(Abi::Rust) => {},
2163 self.word_nbsp("extern");
2164 self.word_nbsp(abi.to_string())
2170 pub fn print_extern_opt_abi(&mut self, opt_abi: Option<Abi>) {
2173 self.word_nbsp("extern");
2174 self.word_nbsp(abi.to_string())
2180 pub fn print_fn_header_info(&mut self,
2181 header: hir::FnHeader,
2182 vis: &hir::Visibility)
2184 self.s.word(visibility_qualified(vis, ""));
2186 match header.constness {
2187 hir::Constness::NotConst => {}
2188 hir::Constness::Const => self.word_nbsp("const"),
2191 match header.asyncness {
2192 hir::IsAsync::NotAsync => {}
2193 hir::IsAsync::Async => self.word_nbsp("async"),
2196 self.print_unsafety(header.unsafety);
2198 if header.abi != Abi::Rust {
2199 self.word_nbsp("extern");
2200 self.word_nbsp(header.abi.to_string());
2206 pub fn print_unsafety(&mut self, s: hir::Unsafety) {
2208 hir::Unsafety::Normal => {}
2209 hir::Unsafety::Unsafe => self.word_nbsp("unsafe"),
2213 pub fn print_is_auto(&mut self, s: hir::IsAuto) {
2215 hir::IsAuto::Yes => self.word_nbsp("auto"),
2216 hir::IsAuto::No => {},
2221 /// Does this expression require a semicolon to be treated
2222 /// as a statement? The negation of this: 'can this expression
2223 /// be used as a statement without a semicolon' -- is used
2224 /// as an early-bail-out in the parser so that, for instance,
2225 /// if true {...} else {...}
2227 /// isn't parsed as (if true {...} else {...} | x) | 5
2229 // Duplicated from `parse::classify`, but adapted for the HIR.
2230 fn expr_requires_semi_to_be_stmt(e: &hir::Expr) -> bool {
2232 hir::ExprKind::Match(..) |
2233 hir::ExprKind::Block(..) |
2234 hir::ExprKind::Loop(..) => false,
2239 /// This statement requires a semicolon after it.
2240 /// note that in one case (stmt_semi), we've already
2241 /// seen the semicolon, and thus don't need another.
2242 fn stmt_ends_with_semi(stmt: &hir::StmtKind) -> bool {
2244 hir::StmtKind::Local(_) => true,
2245 hir::StmtKind::Item(_) => false,
2246 hir::StmtKind::Expr(ref e) => expr_requires_semi_to_be_stmt(&e),
2247 hir::StmtKind::Semi(..) => false,
2251 fn bin_op_to_assoc_op(op: hir::BinOpKind) -> AssocOp {
2252 use crate::hir::BinOpKind::*;
2254 Add => AssocOp::Add,
2255 Sub => AssocOp::Subtract,
2256 Mul => AssocOp::Multiply,
2257 Div => AssocOp::Divide,
2258 Rem => AssocOp::Modulus,
2260 And => AssocOp::LAnd,
2263 BitXor => AssocOp::BitXor,
2264 BitAnd => AssocOp::BitAnd,
2265 BitOr => AssocOp::BitOr,
2266 Shl => AssocOp::ShiftLeft,
2267 Shr => AssocOp::ShiftRight,
2269 Eq => AssocOp::Equal,
2270 Lt => AssocOp::Less,
2271 Le => AssocOp::LessEqual,
2272 Ne => AssocOp::NotEqual,
2273 Ge => AssocOp::GreaterEqual,
2274 Gt => AssocOp::Greater,
2278 /// Expressions that syntactically contain an "exterior" struct literal, i.e., not surrounded by any
2279 /// parens or other delimiters, e.g., `X { y: 1 }`, `X { y: 1 }.method()`, `foo == X { y: 1 }` and
2280 /// `X { y: 1 } == foo` all do, but `(X { y: 1 }) == foo` does not.
2281 fn contains_exterior_struct_lit(value: &hir::Expr) -> bool {
2283 hir::ExprKind::Struct(..) => true,
2285 hir::ExprKind::Assign(ref lhs, ref rhs) |
2286 hir::ExprKind::AssignOp(_, ref lhs, ref rhs) |
2287 hir::ExprKind::Binary(_, ref lhs, ref rhs) => {
2288 // `X { y: 1 } + X { y: 2 }`
2289 contains_exterior_struct_lit(&lhs) || contains_exterior_struct_lit(&rhs)
2291 hir::ExprKind::Unary(_, ref x) |
2292 hir::ExprKind::Cast(ref x, _) |
2293 hir::ExprKind::Type(ref x, _) |
2294 hir::ExprKind::Field(ref x, _) |
2295 hir::ExprKind::Index(ref x, _) => {
2296 // `&X { y: 1 }, X { y: 1 }.y`
2297 contains_exterior_struct_lit(&x)
2300 hir::ExprKind::MethodCall(.., ref exprs) => {
2301 // `X { y: 1 }.bar(...)`
2302 contains_exterior_struct_lit(&exprs[0])