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),
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 {
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,
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) => {
298 hir::Mutability::Mutable => self.word_nbsp("mut"),
299 hir::Mutability::Immutable => self.word_nbsp("const"),
301 self.print_type(&mt.ty);
303 hir::TyKind::Rptr(ref lifetime, ref mt) => {
305 self.print_opt_lifetime(lifetime);
308 hir::TyKind::Never => {
311 hir::TyKind::Tup(ref elts) => {
313 self.commasep(Inconsistent, &elts[..], |s, ty| s.print_type(&ty));
319 hir::TyKind::BareFn(ref f) => {
320 self.print_ty_fn(f.abi, f.unsafety, &f.decl, None, &f.generic_params,
323 hir::TyKind::Def(..) => {},
324 hir::TyKind::Path(ref qpath) => {
325 self.print_qpath(qpath, false)
327 hir::TyKind::TraitObject(ref bounds, ref lifetime) => {
328 let mut first = true;
329 for bound in bounds {
334 self.word_space("+");
336 self.print_poly_trait_ref(bound);
338 if !lifetime.is_elided() {
340 self.word_space("+");
341 self.print_lifetime(lifetime);
344 hir::TyKind::Array(ref ty, ref length) => {
346 self.print_type(&ty);
348 self.print_anon_const(length);
351 hir::TyKind::Typeof(ref e) => {
352 self.s.word("typeof(");
353 self.print_anon_const(e);
356 hir::TyKind::Infer => {
359 hir::TyKind::Err => {
361 self.s.word("/*ERROR*/");
368 pub fn print_foreign_item(&mut self, item: &hir::ForeignItem) {
369 self.hardbreak_if_not_bol();
370 self.maybe_print_comment(item.span.lo());
371 self.print_outer_attributes(&item.attrs);
373 hir::ForeignItemKind::Fn(ref decl, ref arg_names, ref generics) => {
377 unsafety: hir::Unsafety::Normal,
378 constness: hir::Constness::NotConst,
380 asyncness: hir::IsAsync::NotAsync,
382 Some(item.ident.name),
387 self.end(); // end head-ibox
389 self.end() // end the outer fn box
391 hir::ForeignItemKind::Static(ref t, m) => {
392 self.head(visibility_qualified(&item.vis, "static"));
393 if m == hir::Mutability::Mutable {
394 self.word_space("mut");
396 self.print_ident(item.ident);
397 self.word_space(":");
400 self.end(); // end the head-ibox
401 self.end() // end the outer cbox
403 hir::ForeignItemKind::Type => {
404 self.head(visibility_qualified(&item.vis, "type"));
405 self.print_ident(item.ident);
407 self.end(); // end the head-ibox
408 self.end() // end the outer cbox
413 fn print_associated_const(&mut self,
416 default: Option<hir::BodyId>,
417 vis: &hir::Visibility)
419 self.s.word(visibility_qualified(vis, ""));
420 self.word_space("const");
421 self.print_ident(ident);
422 self.word_space(":");
424 if let Some(expr) = default {
426 self.word_space("=");
427 self.ann.nested(self, Nested::Body(expr));
432 fn print_associated_type(&mut self,
434 bounds: Option<&hir::GenericBounds>,
435 ty: Option<&hir::Ty>)
437 self.word_space("type");
438 self.print_ident(ident);
439 if let Some(bounds) = bounds {
440 self.print_bounds(":", bounds);
442 if let Some(ty) = ty {
444 self.word_space("=");
453 generics: &hir::Generics,
454 inner: impl Fn(&mut Self),
456 self.head(visibility_qualified(&item.vis, "type"));
457 self.print_ident(item.ident);
458 self.print_generic_params(&generics.params);
459 self.end(); // end the inner ibox
461 self.print_where_clause(&generics.where_clause);
465 self.end(); // end the outer ibox
468 /// Pretty-print an item
469 pub fn print_item(&mut self, item: &hir::Item) {
470 self.hardbreak_if_not_bol();
471 self.maybe_print_comment(item.span.lo());
472 self.print_outer_attributes(&item.attrs);
473 self.ann.pre(self, AnnNode::Item(item));
475 hir::ItemKind::ExternCrate(orig_name) => {
476 self.head(visibility_qualified(&item.vis, "extern crate"));
477 if let Some(orig_name) = orig_name {
478 self.print_name(orig_name);
483 self.print_ident(item.ident);
485 self.end(); // end inner head-block
486 self.end(); // end outer head-block
488 hir::ItemKind::Use(ref path, kind) => {
489 self.head(visibility_qualified(&item.vis, "use"));
490 self.print_path(path, false);
493 hir::UseKind::Single => {
494 if path.segments.last().unwrap().ident != item.ident {
496 self.word_space("as");
497 self.print_ident(item.ident);
501 hir::UseKind::Glob => self.s.word("::*;"),
502 hir::UseKind::ListStem => self.s.word("::{};")
504 self.end(); // end inner head-block
505 self.end(); // end outer head-block
507 hir::ItemKind::Static(ref ty, m, expr) => {
508 self.head(visibility_qualified(&item.vis, "static"));
509 if m == hir::Mutability::Mutable {
510 self.word_space("mut");
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::Const(ref ty, expr) => {
524 self.head(visibility_qualified(&item.vis, "const"));
525 self.print_ident(item.ident);
526 self.word_space(":");
527 self.print_type(&ty);
529 self.end(); // end the head-ibox
531 self.word_space("=");
532 self.ann.nested(self, Nested::Body(expr));
534 self.end(); // end the outer cbox
536 hir::ItemKind::Fn(ref sig, ref param_names, body) => {
538 self.print_fn(&sig.decl,
540 Some(item.ident.name),
546 self.end(); // need to close a box
547 self.end(); // need to close a box
548 self.ann.nested(self, Nested::Body(body));
550 hir::ItemKind::Mod(ref _mod) => {
551 self.head(visibility_qualified(&item.vis, "mod"));
552 self.print_ident(item.ident);
555 self.print_mod(_mod, &item.attrs);
556 self.bclose(item.span);
558 hir::ItemKind::ForeignMod(ref nmod) => {
560 self.word_nbsp(nmod.abi.to_string());
562 self.print_foreign_mod(nmod, &item.attrs);
563 self.bclose(item.span);
565 hir::ItemKind::GlobalAsm(ref ga) => {
566 self.head(visibility_qualified(&item.vis, "global asm"));
567 self.s.word(ga.asm.to_string());
570 hir::ItemKind::TyAlias(ref ty, ref generics) => {
571 self.print_item_type(item, &generics, |state| {
572 state.word_space("=");
573 state.print_type(&ty);
576 hir::ItemKind::OpaqueTy(ref opaque_ty) => {
577 self.print_item_type(item, &opaque_ty.generics, |state| {
578 let mut real_bounds = Vec::with_capacity(opaque_ty.bounds.len());
579 for b in opaque_ty.bounds.iter() {
580 if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
582 state.word_space("for ?");
583 state.print_trait_ref(&ptr.trait_ref);
588 state.print_bounds("= impl", real_bounds);
591 hir::ItemKind::Enum(ref enum_definition, ref params) => {
592 self.print_enum_def(enum_definition, params, item.ident.name, item.span, &item.vis);
594 hir::ItemKind::Struct(ref struct_def, ref generics) => {
595 self.head(visibility_qualified(&item.vis, "struct"));
596 self.print_struct(struct_def, generics, item.ident.name, item.span, true);
598 hir::ItemKind::Union(ref struct_def, ref generics) => {
599 self.head(visibility_qualified(&item.vis, "union"));
600 self.print_struct(struct_def, generics, item.ident.name, item.span, true);
602 hir::ItemKind::Impl(unsafety,
610 self.print_visibility(&item.vis);
611 self.print_defaultness(defaultness);
612 self.print_unsafety(unsafety);
613 self.word_nbsp("impl");
615 if !generics.params.is_empty() {
616 self.print_generic_params(&generics.params);
620 if let hir::ImplPolarity::Negative = polarity {
624 if let Some(ref t) = opt_trait {
625 self.print_trait_ref(t);
627 self.word_space("for");
630 self.print_type(&ty);
631 self.print_where_clause(&generics.where_clause);
635 self.print_inner_attributes(&item.attrs);
636 for impl_item in impl_items {
637 self.ann.nested(self, Nested::ImplItem(impl_item.id));
639 self.bclose(item.span);
641 hir::ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref trait_items) => {
643 self.print_visibility(&item.vis);
644 self.print_is_auto(is_auto);
645 self.print_unsafety(unsafety);
646 self.word_nbsp("trait");
647 self.print_ident(item.ident);
648 self.print_generic_params(&generics.params);
649 let mut real_bounds = Vec::with_capacity(bounds.len());
650 for b in bounds.iter() {
651 if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
653 self.word_space("for ?");
654 self.print_trait_ref(&ptr.trait_ref);
659 self.print_bounds(":", real_bounds);
660 self.print_where_clause(&generics.where_clause);
663 for trait_item in trait_items {
664 self.ann.nested(self, Nested::TraitItem(trait_item.id));
666 self.bclose(item.span);
668 hir::ItemKind::TraitAlias(ref generics, ref bounds) => {
670 self.print_visibility(&item.vis);
671 self.word_nbsp("trait");
672 self.print_ident(item.ident);
673 self.print_generic_params(&generics.params);
674 let mut real_bounds = Vec::with_capacity(bounds.len());
675 // FIXME(durka) this seems to be some quite outdated syntax
676 for b in bounds.iter() {
677 if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
679 self.word_space("for ?");
680 self.print_trait_ref(&ptr.trait_ref);
686 self.print_bounds("=", real_bounds);
687 self.print_where_clause(&generics.where_clause);
691 self.ann.post(self, AnnNode::Item(item))
694 pub fn print_trait_ref(&mut self, t: &hir::TraitRef) {
695 self.print_path(&t.path, false)
698 fn print_formal_generic_params(
700 generic_params: &[hir::GenericParam]
702 if !generic_params.is_empty() {
704 self.print_generic_params(generic_params);
709 fn print_poly_trait_ref(&mut self, t: &hir::PolyTraitRef) {
710 self.print_formal_generic_params(&t.bound_generic_params);
711 self.print_trait_ref(&t.trait_ref)
714 pub fn print_enum_def(&mut self,
715 enum_definition: &hir::EnumDef,
716 generics: &hir::Generics,
718 span: syntax_pos::Span,
719 visibility: &hir::Visibility)
721 self.head(visibility_qualified(visibility, "enum"));
722 self.print_name(name);
723 self.print_generic_params(&generics.params);
724 self.print_where_clause(&generics.where_clause);
726 self.print_variants(&enum_definition.variants, span)
729 pub fn print_variants(&mut self,
730 variants: &[hir::Variant],
731 span: syntax_pos::Span)
735 self.space_if_not_bol();
736 self.maybe_print_comment(v.span.lo());
737 self.print_outer_attributes(&v.attrs);
738 self.ibox(INDENT_UNIT);
739 self.print_variant(v);
742 self.maybe_print_trailing_comment(v.span, None);
747 pub fn print_visibility(&mut self, vis: &hir::Visibility) {
749 hir::VisibilityKind::Public => self.word_nbsp("pub"),
750 hir::VisibilityKind::Crate(ast::CrateSugar::JustCrate) => self.word_nbsp("crate"),
751 hir::VisibilityKind::Crate(ast::CrateSugar::PubCrate) => self.word_nbsp("pub(crate)"),
752 hir::VisibilityKind::Restricted { ref path, .. } => {
754 if path.segments.len() == 1 &&
755 path.segments[0].ident.name == kw::Super {
756 // Special case: `super` can print like `pub(super)`.
757 self.s.word("super");
759 // Everything else requires `in` at present.
760 self.word_nbsp("in");
761 self.print_path(path, false);
765 hir::VisibilityKind::Inherited => ()
769 pub fn print_defaultness(&mut self, defaultness: hir::Defaultness) {
771 hir::Defaultness::Default { .. } => self.word_nbsp("default"),
772 hir::Defaultness::Final => (),
776 pub fn print_struct(&mut self,
777 struct_def: &hir::VariantData,
778 generics: &hir::Generics,
780 span: syntax_pos::Span,
781 print_finalizer: bool)
783 self.print_name(name);
784 self.print_generic_params(&generics.params);
786 hir::VariantData::Tuple(..) | hir::VariantData::Unit(..) => {
787 if let hir::VariantData::Tuple(..) = struct_def {
789 self.commasep(Inconsistent, struct_def.fields(), |s, field| {
790 s.maybe_print_comment(field.span.lo());
791 s.print_outer_attributes(&field.attrs);
792 s.print_visibility(&field.vis);
793 s.print_type(&field.ty)
797 self.print_where_clause(&generics.where_clause);
802 self.end() // close the outer-box
804 hir::VariantData::Struct(..) => {
805 self.print_where_clause(&generics.where_clause);
808 self.hardbreak_if_not_bol();
810 for field in struct_def.fields() {
811 self.hardbreak_if_not_bol();
812 self.maybe_print_comment(field.span.lo());
813 self.print_outer_attributes(&field.attrs);
814 self.print_visibility(&field.vis);
815 self.print_ident(field.ident);
817 self.print_type(&field.ty);
826 pub fn print_variant(&mut self, v: &hir::Variant) {
828 let generics = hir::Generics::empty();
829 self.print_struct(&v.data, &generics, v.ident.name, v.span, false);
830 if let Some(ref d) = v.disr_expr {
832 self.word_space("=");
833 self.print_anon_const(d);
836 pub fn print_method_sig(&mut self,
839 generics: &hir::Generics,
840 vis: &hir::Visibility,
841 arg_names: &[ast::Ident],
842 body_id: Option<hir::BodyId>)
844 self.print_fn(&m.decl,
853 pub fn print_trait_item(&mut self, ti: &hir::TraitItem) {
854 self.ann.pre(self, AnnNode::SubItem(ti.hir_id));
855 self.hardbreak_if_not_bol();
856 self.maybe_print_comment(ti.span.lo());
857 self.print_outer_attributes(&ti.attrs);
859 hir::TraitItemKind::Const(ref ty, default) => {
860 let vis = Spanned { span: syntax_pos::DUMMY_SP,
861 node: hir::VisibilityKind::Inherited };
862 self.print_associated_const(ti.ident, &ty, default, &vis);
864 hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Required(ref arg_names)) => {
865 let vis = Spanned { span: syntax_pos::DUMMY_SP,
866 node: hir::VisibilityKind::Inherited };
867 self.print_method_sig(ti.ident, sig, &ti.generics, &vis, arg_names, None);
870 hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Provided(body)) => {
871 let vis = Spanned { span: syntax_pos::DUMMY_SP,
872 node: hir::VisibilityKind::Inherited };
874 self.print_method_sig(ti.ident, sig, &ti.generics, &vis, &[], Some(body));
876 self.end(); // need to close a box
877 self.end(); // need to close a box
878 self.ann.nested(self, Nested::Body(body));
880 hir::TraitItemKind::Type(ref bounds, ref default) => {
881 self.print_associated_type(ti.ident,
883 default.as_ref().map(|ty| &**ty));
886 self.ann.post(self, AnnNode::SubItem(ti.hir_id))
889 pub fn print_impl_item(&mut self, ii: &hir::ImplItem) {
890 self.ann.pre(self, AnnNode::SubItem(ii.hir_id));
891 self.hardbreak_if_not_bol();
892 self.maybe_print_comment(ii.span.lo());
893 self.print_outer_attributes(&ii.attrs);
894 self.print_defaultness(ii.defaultness);
897 hir::ImplItemKind::Const(ref ty, expr) => {
898 self.print_associated_const(ii.ident, &ty, Some(expr), &ii.vis);
900 hir::ImplItemKind::Method(ref sig, body) => {
902 self.print_method_sig(ii.ident, sig, &ii.generics, &ii.vis, &[], Some(body));
904 self.end(); // need to close a box
905 self.end(); // need to close a box
906 self.ann.nested(self, Nested::Body(body));
908 hir::ImplItemKind::TyAlias(ref ty) => {
909 self.print_associated_type(ii.ident, None, Some(ty));
911 hir::ImplItemKind::OpaqueTy(ref bounds) => {
912 self.word_space("type");
913 self.print_ident(ii.ident);
914 self.print_bounds("= impl", bounds);
918 self.ann.post(self, AnnNode::SubItem(ii.hir_id))
923 init: Option<&hir::Expr>,
924 decl: impl Fn(&mut Self)
926 self.space_if_not_bol();
927 self.ibox(INDENT_UNIT);
928 self.word_nbsp("let");
930 self.ibox(INDENT_UNIT);
934 if let Some(ref init) = init {
936 self.word_space("=");
937 self.print_expr(&init);
942 pub fn print_stmt(&mut self, st: &hir::Stmt) {
943 self.maybe_print_comment(st.span.lo());
945 hir::StmtKind::Local(ref loc) => {
946 self.print_local(loc.init.as_deref(), |this| this.print_local_decl(&loc));
948 hir::StmtKind::Item(item) => {
949 self.ann.nested(self, Nested::Item(item))
951 hir::StmtKind::Expr(ref expr) => {
952 self.space_if_not_bol();
953 self.print_expr(&expr);
955 hir::StmtKind::Semi(ref expr) => {
956 self.space_if_not_bol();
957 self.print_expr(&expr);
961 if stmt_ends_with_semi(&st.kind) {
964 self.maybe_print_trailing_comment(st.span, None)
967 pub fn print_block(&mut self, blk: &hir::Block) {
968 self.print_block_with_attrs(blk, &[])
971 pub fn print_block_unclosed(&mut self, blk: &hir::Block) {
972 self.print_block_maybe_unclosed(blk, &[], false)
975 pub fn print_block_with_attrs(&mut self,
977 attrs: &[ast::Attribute])
979 self.print_block_maybe_unclosed(blk, attrs, true)
982 pub fn print_block_maybe_unclosed(&mut self,
984 attrs: &[ast::Attribute],
988 hir::UnsafeBlock(..) => self.word_space("unsafe"),
989 hir::PushUnsafeBlock(..) => self.word_space("push_unsafe"),
990 hir::PopUnsafeBlock(..) => self.word_space("pop_unsafe"),
991 hir::DefaultBlock => (),
993 self.maybe_print_comment(blk.span.lo());
994 self.ann.pre(self, AnnNode::Block(blk));
997 self.print_inner_attributes(attrs);
999 for st in &blk.stmts {
1000 self.print_stmt(st);
1002 if let Some(ref expr) = blk.expr {
1003 self.space_if_not_bol();
1004 self.print_expr(&expr);
1005 self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi()));
1007 self.bclose_maybe_open(blk.span, close_box);
1008 self.ann.post(self, AnnNode::Block(blk))
1011 pub fn print_anon_const(&mut self, constant: &hir::AnonConst) {
1012 self.ann.nested(self, Nested::Body(constant.body))
1015 fn print_call_post(&mut self, args: &[hir::Expr]) {
1017 self.commasep_exprs(Inconsistent, args);
1021 pub fn print_expr_maybe_paren(&mut self, expr: &hir::Expr, prec: i8) {
1022 let needs_par = expr.precedence().order() < prec;
1026 self.print_expr(expr);
1032 /// Print an expr using syntax that's acceptable in a condition position, such as the `cond` in
1033 /// `if cond { ... }`.
1034 pub fn print_expr_as_cond(&mut self, expr: &hir::Expr) {
1035 let needs_par = match expr.kind {
1036 // These cases need parens due to the parse error observed in #26461: `if return {}`
1037 // parses as the erroneous construct `if (return {})`, not `if (return) {}`.
1038 hir::ExprKind::Closure(..) |
1039 hir::ExprKind::Ret(..) |
1040 hir::ExprKind::Break(..) => true,
1042 _ => contains_exterior_struct_lit(expr),
1048 self.print_expr(expr);
1054 fn print_expr_vec(&mut self, exprs: &[hir::Expr]) {
1055 self.ibox(INDENT_UNIT);
1057 self.commasep_exprs(Inconsistent, exprs);
1062 fn print_expr_repeat(&mut self, element: &hir::Expr, count: &hir::AnonConst) {
1063 self.ibox(INDENT_UNIT);
1065 self.print_expr(element);
1066 self.word_space(";");
1067 self.print_anon_const(count);
1072 fn print_expr_struct(&mut self,
1074 fields: &[hir::Field],
1075 wth: &Option<P<hir::Expr>>)
1077 self.print_qpath(qpath, true);
1079 self.commasep_cmnt(Consistent,
1082 s.ibox(INDENT_UNIT);
1083 if !field.is_shorthand {
1084 s.print_ident(field.ident);
1087 s.print_expr(&field.expr);
1093 self.ibox(INDENT_UNIT);
1094 if !fields.is_empty() {
1099 self.print_expr(&expr);
1102 _ => if !fields.is_empty() {
1109 fn print_expr_tup(&mut self, exprs: &[hir::Expr]) {
1111 self.commasep_exprs(Inconsistent, exprs);
1112 if exprs.len() == 1 {
1118 fn print_expr_call(&mut self, func: &hir::Expr, args: &[hir::Expr]) {
1119 let prec = match func.kind {
1120 hir::ExprKind::Field(..) => parser::PREC_FORCE_PAREN,
1121 _ => parser::PREC_POSTFIX,
1124 self.print_expr_maybe_paren(func, prec);
1125 self.print_call_post(args)
1128 fn print_expr_method_call(&mut self,
1129 segment: &hir::PathSegment,
1132 let base_args = &args[1..];
1133 self.print_expr_maybe_paren(&args[0], parser::PREC_POSTFIX);
1135 self.print_ident(segment.ident);
1137 let generic_args = segment.generic_args();
1138 if !generic_args.args.is_empty() || !generic_args.bindings.is_empty() {
1139 self.print_generic_args(generic_args, segment.infer_args, true);
1142 self.print_call_post(base_args)
1145 fn print_expr_binary(&mut self,
1150 let assoc_op = bin_op_to_assoc_op(op.node);
1151 let prec = assoc_op.precedence() as i8;
1152 let fixity = assoc_op.fixity();
1154 let (left_prec, right_prec) = match fixity {
1155 Fixity::Left => (prec, prec + 1),
1156 Fixity::Right => (prec + 1, prec),
1157 Fixity::None => (prec + 1, prec + 1),
1160 let left_prec = match (&lhs.kind, op.node) {
1161 // These cases need parens: `x as i32 < y` has the parser thinking that `i32 < y` is
1162 // the beginning of a path type. It starts trying to parse `x as (i32 < y ...` instead
1163 // of `(x as i32) < ...`. We need to convince it _not_ to do that.
1164 (&hir::ExprKind::Cast { .. }, hir::BinOpKind::Lt) |
1165 (&hir::ExprKind::Cast { .. }, hir::BinOpKind::Shl) => parser::PREC_FORCE_PAREN,
1169 self.print_expr_maybe_paren(lhs, left_prec);
1171 self.word_space(op.node.as_str());
1172 self.print_expr_maybe_paren(rhs, right_prec)
1175 fn print_expr_unary(&mut self, op: hir::UnOp, expr: &hir::Expr) {
1176 self.s.word(op.as_str());
1177 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1180 fn print_expr_addr_of(&mut self,
1181 mutability: hir::Mutability,
1185 self.print_mutability(mutability);
1186 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1189 fn print_literal(&mut self, lit: &hir::Lit) {
1190 self.maybe_print_comment(lit.span.lo());
1191 self.word(lit.node.to_lit_token().to_string())
1194 pub fn print_expr(&mut self, expr: &hir::Expr) {
1195 self.maybe_print_comment(expr.span.lo());
1196 self.print_outer_attributes(&expr.attrs);
1197 self.ibox(INDENT_UNIT);
1198 self.ann.pre(self, AnnNode::Expr(expr));
1200 hir::ExprKind::Box(ref expr) => {
1201 self.word_space("box");
1202 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX);
1204 hir::ExprKind::Array(ref exprs) => {
1205 self.print_expr_vec(exprs);
1207 hir::ExprKind::Repeat(ref element, ref count) => {
1208 self.print_expr_repeat(&element, count);
1210 hir::ExprKind::Struct(ref qpath, ref fields, ref wth) => {
1211 self.print_expr_struct(qpath, &fields[..], wth);
1213 hir::ExprKind::Tup(ref exprs) => {
1214 self.print_expr_tup(exprs);
1216 hir::ExprKind::Call(ref func, ref args) => {
1217 self.print_expr_call(&func, args);
1219 hir::ExprKind::MethodCall(ref segment, _, ref args) => {
1220 self.print_expr_method_call(segment, args);
1222 hir::ExprKind::Binary(op, ref lhs, ref rhs) => {
1223 self.print_expr_binary(op, &lhs, &rhs);
1225 hir::ExprKind::Unary(op, ref expr) => {
1226 self.print_expr_unary(op, &expr);
1228 hir::ExprKind::AddrOf(m, ref expr) => {
1229 self.print_expr_addr_of(m, &expr);
1231 hir::ExprKind::Lit(ref lit) => {
1232 self.print_literal(&lit);
1234 hir::ExprKind::Cast(ref expr, ref ty) => {
1235 let prec = AssocOp::As.precedence() as i8;
1236 self.print_expr_maybe_paren(&expr, prec);
1238 self.word_space("as");
1239 self.print_type(&ty);
1241 hir::ExprKind::Type(ref expr, ref ty) => {
1242 let prec = AssocOp::Colon.precedence() as i8;
1243 self.print_expr_maybe_paren(&expr, prec);
1244 self.word_space(":");
1245 self.print_type(&ty);
1247 hir::ExprKind::DropTemps(ref init) => {
1249 self.cbox(INDENT_UNIT);
1253 // Print `let _t = $init;`:
1254 let temp = ast::Ident::from_str("_t");
1255 self.print_local(Some(init), |this| this.print_ident(temp));
1259 self.space_if_not_bol();
1260 self.print_ident(temp);
1263 self.bclose_maybe_open(expr.span, true);
1265 hir::ExprKind::Loop(ref blk, opt_label, _) => {
1266 if let Some(label) = opt_label {
1267 self.print_ident(label.ident);
1268 self.word_space(":");
1272 self.print_block(&blk);
1274 hir::ExprKind::Match(ref expr, ref arms, _) => {
1275 self.cbox(INDENT_UNIT);
1276 self.ibox(INDENT_UNIT);
1277 self.word_nbsp("match");
1278 self.print_expr_as_cond(&expr);
1282 self.print_arm(arm);
1284 self.bclose(expr.span);
1286 hir::ExprKind::Closure(capture_clause, ref decl, body, _fn_decl_span, _gen) => {
1287 self.print_capture_clause(capture_clause);
1289 self.print_closure_params(&decl, body);
1292 // This is a bare expression.
1293 self.ann.nested(self, Nested::Body(body));
1294 self.end(); // need to close a box
1296 // A box will be closed by `print_expr`, but we didn't want an overall
1297 // wrapper so we closed the corresponding opening. so create an
1298 // empty box to satisfy the close.
1301 hir::ExprKind::Block(ref blk, opt_label) => {
1302 if let Some(label) = opt_label {
1303 self.print_ident(label.ident);
1304 self.word_space(":");
1306 // containing cbox, will be closed by print-block at `}`
1307 self.cbox(INDENT_UNIT);
1308 // head-box, will be closed by print-block after `{`
1310 self.print_block(&blk);
1312 hir::ExprKind::Assign(ref lhs, ref rhs) => {
1313 let prec = AssocOp::Assign.precedence() as i8;
1314 self.print_expr_maybe_paren(&lhs, prec + 1);
1316 self.word_space("=");
1317 self.print_expr_maybe_paren(&rhs, prec);
1319 hir::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
1320 let prec = AssocOp::Assign.precedence() as i8;
1321 self.print_expr_maybe_paren(&lhs, prec + 1);
1323 self.s.word(op.node.as_str());
1324 self.word_space("=");
1325 self.print_expr_maybe_paren(&rhs, prec);
1327 hir::ExprKind::Field(ref expr, ident) => {
1328 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
1330 self.print_ident(ident);
1332 hir::ExprKind::Index(ref expr, ref index) => {
1333 self.print_expr_maybe_paren(&expr, parser::PREC_POSTFIX);
1335 self.print_expr(&index);
1338 hir::ExprKind::Path(ref qpath) => {
1339 self.print_qpath(qpath, true)
1341 hir::ExprKind::Break(destination, ref opt_expr) => {
1342 self.s.word("break");
1344 if let Some(label) = destination.label {
1345 self.print_ident(label.ident);
1348 if let Some(ref expr) = *opt_expr {
1349 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
1353 hir::ExprKind::Continue(destination) => {
1354 self.s.word("continue");
1356 if let Some(label) = destination.label {
1357 self.print_ident(label.ident);
1361 hir::ExprKind::Ret(ref result) => {
1362 self.s.word("return");
1363 if let Some(ref expr) = *result {
1365 self.print_expr_maybe_paren(&expr, parser::PREC_JUMP);
1368 hir::ExprKind::InlineAsm(ref a, ref outputs, ref inputs) => {
1369 self.s.word("asm!");
1371 self.print_string(&a.asm.as_str(), a.asm_str_style);
1372 self.word_space(":");
1374 let mut out_idx = 0;
1375 self.commasep(Inconsistent, &a.outputs, |s, out| {
1376 let constraint = out.constraint.as_str();
1377 let mut ch = constraint.chars();
1379 Some('=') if out.is_rw => {
1380 s.print_string(&format!("+{}", ch.as_str()),
1381 ast::StrStyle::Cooked)
1383 _ => s.print_string(&constraint, ast::StrStyle::Cooked),
1386 s.print_expr(&outputs[out_idx]);
1391 self.word_space(":");
1394 self.commasep(Inconsistent, &a.inputs, |s, co| {
1395 s.print_string(&co.as_str(), ast::StrStyle::Cooked);
1397 s.print_expr(&inputs[in_idx]);
1402 self.word_space(":");
1404 self.commasep(Inconsistent, &a.clobbers, |s, co| {
1405 s.print_string(&co.as_str(), ast::StrStyle::Cooked);
1408 let mut options = vec![];
1410 options.push("volatile");
1413 options.push("alignstack");
1415 if a.dialect == ast::AsmDialect::Intel {
1416 options.push("intel");
1419 if !options.is_empty() {
1421 self.word_space(":");
1422 self.commasep(Inconsistent, &options, |s, &co| {
1423 s.print_string(co, ast::StrStyle::Cooked);
1429 hir::ExprKind::Yield(ref expr, _) => {
1430 self.word_space("yield");
1431 self.print_expr_maybe_paren(&expr, parser::PREC_JUMP);
1433 hir::ExprKind::Err => {
1435 self.s.word("/*ERROR*/");
1439 self.ann.post(self, AnnNode::Expr(expr));
1443 pub fn print_local_decl(&mut self, loc: &hir::Local) {
1444 self.print_pat(&loc.pat);
1445 if let Some(ref ty) = loc.ty {
1446 self.word_space(":");
1447 self.print_type(&ty);
1451 pub fn print_usize(&mut self, i: usize) {
1452 self.s.word(i.to_string())
1455 pub fn print_name(&mut self, name: ast::Name) {
1456 self.print_ident(ast::Ident::with_dummy_span(name))
1459 pub fn print_for_decl(&mut self, loc: &hir::Local, coll: &hir::Expr) {
1460 self.print_local_decl(loc);
1462 self.word_space("in");
1463 self.print_expr(coll)
1466 pub fn print_path(&mut self,
1468 colons_before_params: bool)
1470 self.maybe_print_comment(path.span.lo());
1472 for (i, segment) in path.segments.iter().enumerate() {
1476 if segment.ident.name != kw::PathRoot {
1477 self.print_ident(segment.ident);
1478 self.print_generic_args(segment.generic_args(), segment.infer_args,
1479 colons_before_params);
1484 pub fn print_path_segment(&mut self, segment: &hir::PathSegment) {
1485 if segment.ident.name != kw::PathRoot {
1486 self.print_ident(segment.ident);
1487 self.print_generic_args(segment.generic_args(), segment.infer_args, false);
1491 pub fn print_qpath(&mut self,
1493 colons_before_params: bool)
1496 hir::QPath::Resolved(None, ref path) => {
1497 self.print_path(path, colons_before_params)
1499 hir::QPath::Resolved(Some(ref qself), ref path) => {
1501 self.print_type(qself);
1503 self.word_space("as");
1505 for (i, segment) in path.segments[..path.segments.len() - 1].iter().enumerate() {
1509 if segment.ident.name != kw::PathRoot {
1510 self.print_ident(segment.ident);
1511 self.print_generic_args(segment.generic_args(),
1513 colons_before_params);
1519 let item_segment = path.segments.last().unwrap();
1520 self.print_ident(item_segment.ident);
1521 self.print_generic_args(item_segment.generic_args(),
1522 item_segment.infer_args,
1523 colons_before_params)
1525 hir::QPath::TypeRelative(ref qself, ref item_segment) => {
1526 // If we've got a compound-qualified-path, let's push an additional pair of angle
1527 // brackets, so that we pretty-print `<<A::B>::C>` as `<A::B>::C`, instead of just
1528 // `A::B::C` (since the latter could be ambiguous to the user)
1529 if let hir::TyKind::Path(hir::QPath::Resolved(None, _)) = &qself.kind {
1530 self.print_type(qself);
1533 self.print_type(qself);
1538 self.print_ident(item_segment.ident);
1539 self.print_generic_args(item_segment.generic_args(),
1540 item_segment.infer_args,
1541 colons_before_params)
1546 fn print_generic_args(&mut self,
1547 generic_args: &hir::GenericArgs,
1549 colons_before_params: bool)
1551 if generic_args.parenthesized {
1553 self.commasep(Inconsistent, generic_args.inputs(), |s, ty| s.print_type(&ty));
1556 self.space_if_not_bol();
1557 self.word_space("->");
1558 self.print_type(generic_args.bindings[0].ty());
1560 let start = if colons_before_params { "::<" } else { "<" };
1561 let empty = Cell::new(true);
1562 let start_or_comma = |this: &mut Self| {
1567 this.word_space(",")
1571 let mut nonelided_generic_args: bool = false;
1572 let elide_lifetimes = generic_args.args.iter().all(|arg| match arg {
1573 GenericArg::Lifetime(lt) => lt.is_elided(),
1575 nonelided_generic_args = true;
1580 if nonelided_generic_args {
1581 start_or_comma(self);
1582 self.commasep(Inconsistent, &generic_args.args, |s, generic_arg| {
1584 GenericArg::Lifetime(lt) if !elide_lifetimes => s.print_lifetime(lt),
1585 GenericArg::Lifetime(_) => {},
1586 GenericArg::Type(ty) => s.print_type(ty),
1587 GenericArg::Const(ct) => s.print_anon_const(&ct.value),
1592 // FIXME(eddyb): this would leak into error messages (e.g.,
1593 // "non-exhaustive patterns: `Some::<..>(_)` not covered").
1594 if infer_args && false {
1595 start_or_comma(self);
1599 for binding in generic_args.bindings.iter() {
1600 start_or_comma(self);
1601 self.print_ident(binding.ident);
1603 match generic_args.bindings[0].kind {
1604 hir::TypeBindingKind::Equality { ref ty } => {
1605 self.word_space("=");
1606 self.print_type(ty);
1608 hir::TypeBindingKind::Constraint { ref bounds } => {
1609 self.print_bounds(":", bounds);
1620 pub fn print_pat(&mut self, pat: &hir::Pat) {
1621 self.maybe_print_comment(pat.span.lo());
1622 self.ann.pre(self, AnnNode::Pat(pat));
1623 // Pat isn't normalized, but the beauty of it
1624 // is that it doesn't matter
1626 PatKind::Wild => self.s.word("_"),
1627 PatKind::Binding(binding_mode, _, ident, ref sub) => {
1628 match binding_mode {
1629 hir::BindingAnnotation::Ref => {
1630 self.word_nbsp("ref");
1631 self.print_mutability(hir::Mutability::Immutable);
1633 hir::BindingAnnotation::RefMut => {
1634 self.word_nbsp("ref");
1635 self.print_mutability(hir::Mutability::Mutable);
1637 hir::BindingAnnotation::Unannotated => {}
1638 hir::BindingAnnotation::Mutable => {
1639 self.word_nbsp("mut");
1642 self.print_ident(ident);
1643 if let Some(ref p) = *sub {
1648 PatKind::TupleStruct(ref qpath, ref elts, ddpos) => {
1649 self.print_qpath(qpath, true);
1651 if let Some(ddpos) = ddpos {
1652 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p));
1654 self.word_space(",");
1657 if ddpos != elts.len() {
1659 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p));
1662 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p));
1666 PatKind::Path(ref qpath) => {
1667 self.print_qpath(qpath, true);
1669 PatKind::Struct(ref qpath, ref fields, etc) => {
1670 self.print_qpath(qpath, true);
1672 self.word_space("{");
1673 self.commasep_cmnt(Consistent,
1676 s.cbox(INDENT_UNIT);
1677 if !f.is_shorthand {
1678 s.print_ident(f.ident);
1681 s.print_pat(&f.pat);
1686 if !fields.is_empty() {
1687 self.word_space(",");
1694 PatKind::Or(ref pats) => {
1695 self.strsep("|", true, Inconsistent, &pats[..], |s, p| s.print_pat(&p));
1697 PatKind::Tuple(ref elts, ddpos) => {
1699 if let Some(ddpos) = ddpos {
1700 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p));
1702 self.word_space(",");
1705 if ddpos != elts.len() {
1707 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p));
1710 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p));
1711 if elts.len() == 1 {
1717 PatKind::Box(ref inner) => {
1718 let is_range_inner = match inner.kind {
1719 PatKind::Range(..) => true,
1722 self.s.word("box ");
1726 self.print_pat(&inner);
1731 PatKind::Ref(ref inner, mutbl) => {
1732 let is_range_inner = match inner.kind {
1733 PatKind::Range(..) => true,
1737 self.s.word(mutbl.prefix_str());
1741 self.print_pat(&inner);
1746 PatKind::Lit(ref e) => self.print_expr(&e),
1747 PatKind::Range(ref begin, ref end, ref end_kind) => {
1748 self.print_expr(&begin);
1751 RangeEnd::Included => self.s.word("..."),
1752 RangeEnd::Excluded => self.s.word(".."),
1754 self.print_expr(&end);
1756 PatKind::Slice(ref before, ref slice, ref after) => {
1758 self.commasep(Inconsistent, &before[..], |s, p| s.print_pat(&p));
1759 if let Some(ref p) = *slice {
1760 if !before.is_empty() {
1761 self.word_space(",");
1763 if let PatKind::Wild = p.kind {
1769 if !after.is_empty() {
1770 self.word_space(",");
1773 self.commasep(Inconsistent, &after[..], |s, p| s.print_pat(&p));
1777 self.ann.post(self, AnnNode::Pat(pat))
1780 pub fn print_param(&mut self, arg: &hir::Param) {
1781 self.print_outer_attributes(&arg.attrs);
1782 self.print_pat(&arg.pat);
1785 pub fn print_arm(&mut self, arm: &hir::Arm) {
1786 // I have no idea why this check is necessary, but here it
1788 if arm.attrs.is_empty() {
1791 self.cbox(INDENT_UNIT);
1792 self.ann.pre(self, AnnNode::Arm(arm));
1794 self.print_outer_attributes(&arm.attrs);
1795 self.print_pat(&arm.pat);
1797 if let Some(ref g) = arm.guard {
1799 hir::Guard::If(e) => {
1800 self.word_space("if");
1801 self.print_expr(&e);
1806 self.word_space("=>");
1808 match arm.body.kind {
1809 hir::ExprKind::Block(ref blk, opt_label) => {
1810 if let Some(label) = opt_label {
1811 self.print_ident(label.ident);
1812 self.word_space(":");
1814 // the block will close the pattern's ibox
1815 self.print_block_unclosed(&blk);
1817 // If it is a user-provided unsafe block, print a comma after it
1818 if let hir::UnsafeBlock(hir::UserProvided) = blk.rules {
1823 self.end(); // close the ibox for the pattern
1824 self.print_expr(&arm.body);
1828 self.ann.post(self, AnnNode::Arm(arm));
1829 self.end() // close enclosing cbox
1832 pub fn print_fn(&mut self,
1834 header: hir::FnHeader,
1835 name: Option<ast::Name>,
1836 generics: &hir::Generics,
1837 vis: &hir::Visibility,
1838 arg_names: &[ast::Ident],
1839 body_id: Option<hir::BodyId>)
1841 self.print_fn_header_info(header, vis);
1843 if let Some(name) = name {
1845 self.print_name(name);
1847 self.print_generic_params(&generics.params);
1851 // Make sure we aren't supplied *both* `arg_names` and `body_id`.
1852 assert!(arg_names.is_empty() || body_id.is_none());
1853 self.commasep(Inconsistent, &decl.inputs, |s, ty| {
1854 s.ibox(INDENT_UNIT);
1855 if let Some(arg_name) = arg_names.get(i) {
1856 s.s.word(arg_name.to_string());
1859 } else if let Some(body_id) = body_id {
1860 s.ann.nested(s, Nested::BodyParamPat(body_id, i));
1868 if decl.c_variadic {
1869 self.s.word(", ...");
1873 self.print_fn_output(decl);
1874 self.print_where_clause(&generics.where_clause)
1877 fn print_closure_params(&mut self, decl: &hir::FnDecl, body_id: hir::BodyId) {
1880 self.commasep(Inconsistent, &decl.inputs, |s, ty| {
1881 s.ibox(INDENT_UNIT);
1883 s.ann.nested(s, Nested::BodyParamPat(body_id, i));
1886 if let hir::TyKind::Infer = ty.kind {
1897 if let hir::DefaultReturn(..) = decl.output {
1901 self.space_if_not_bol();
1902 self.word_space("->");
1904 hir::Return(ref ty) => {
1905 self.print_type(&ty);
1906 self.maybe_print_comment(ty.span.lo())
1908 hir::DefaultReturn(..) => unreachable!(),
1912 pub fn print_capture_clause(&mut self, capture_clause: hir::CaptureBy) {
1913 match capture_clause {
1914 hir::CaptureBy::Value => self.word_space("move"),
1915 hir::CaptureBy::Ref => {},
1919 pub fn print_bounds<'b>(
1921 prefix: &'static str,
1922 bounds: impl IntoIterator<Item = &'b hir::GenericBound>,
1924 let mut first = true;
1925 for bound in bounds {
1927 self.s.word(prefix);
1929 if !(first && prefix.is_empty()) {
1935 self.word_space("+");
1939 GenericBound::Trait(tref, modifier) => {
1940 if modifier == &TraitBoundModifier::Maybe {
1943 self.print_poly_trait_ref(tref);
1945 GenericBound::Outlives(lt) => {
1946 self.print_lifetime(lt);
1952 pub fn print_generic_params(&mut self, generic_params: &[GenericParam]) {
1953 if !generic_params.is_empty() {
1956 self.commasep(Inconsistent, generic_params, |s, param| {
1957 s.print_generic_param(param)
1964 pub fn print_generic_param(&mut self, param: &GenericParam) {
1965 if let GenericParamKind::Const { .. } = param.kind {
1966 self.word_space("const");
1969 self.print_ident(param.name.ident());
1972 GenericParamKind::Lifetime { .. } => {
1974 for bound in ¶m.bounds {
1976 GenericBound::Outlives(lt) => {
1978 self.print_lifetime(lt);
1985 GenericParamKind::Type { ref default, .. } => {
1986 self.print_bounds(":", ¶m.bounds);
1990 self.word_space("=");
1991 self.print_type(&default)
1996 GenericParamKind::Const { ref ty } => {
1997 self.word_space(":");
2003 pub fn print_lifetime(&mut self, lifetime: &hir::Lifetime) {
2004 self.print_ident(lifetime.name.ident())
2007 pub fn print_where_clause(&mut self, where_clause: &hir::WhereClause) {
2008 if where_clause.predicates.is_empty() {
2013 self.word_space("where");
2015 for (i, predicate) in where_clause.predicates.iter().enumerate() {
2017 self.word_space(",");
2021 &hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
2022 ref bound_generic_params,
2027 self.print_formal_generic_params(bound_generic_params);
2028 self.print_type(&bounded_ty);
2029 self.print_bounds(":", bounds);
2031 &hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate{ref lifetime,
2034 self.print_lifetime(lifetime);
2037 for (i, bound) in bounds.iter().enumerate() {
2039 GenericBound::Outlives(lt) => {
2040 self.print_lifetime(lt);
2050 &hir::WherePredicate::EqPredicate(hir::WhereEqPredicate{ref lhs_ty,
2053 self.print_type(lhs_ty);
2055 self.word_space("=");
2056 self.print_type(rhs_ty);
2062 pub fn print_mutability(&mut self, mutbl: hir::Mutability) {
2064 hir::Mutability::Mutable => self.word_nbsp("mut"),
2065 hir::Mutability::Immutable => {},
2069 pub fn print_mt(&mut self, mt: &hir::MutTy) {
2070 self.print_mutability(mt.mutbl);
2071 self.print_type(&mt.ty)
2074 pub fn print_fn_output(&mut self, decl: &hir::FnDecl) {
2075 if let hir::DefaultReturn(..) = decl.output {
2079 self.space_if_not_bol();
2080 self.ibox(INDENT_UNIT);
2081 self.word_space("->");
2083 hir::DefaultReturn(..) => unreachable!(),
2084 hir::Return(ref ty) => self.print_type(&ty),
2089 hir::Return(ref output) => self.maybe_print_comment(output.span.lo()),
2094 pub fn print_ty_fn(&mut self,
2096 unsafety: hir::Unsafety,
2098 name: Option<ast::Name>,
2099 generic_params: &[hir::GenericParam],
2100 arg_names: &[ast::Ident])
2102 self.ibox(INDENT_UNIT);
2103 if !generic_params.is_empty() {
2105 self.print_generic_params(generic_params);
2107 let generics = hir::Generics {
2108 params: hir::HirVec::new(),
2109 where_clause: hir::WhereClause {
2110 predicates: hir::HirVec::new(),
2111 span: syntax_pos::DUMMY_SP,
2113 span: syntax_pos::DUMMY_SP,
2119 constness: hir::Constness::NotConst,
2120 asyncness: hir::IsAsync::NotAsync,
2124 &Spanned { span: syntax_pos::DUMMY_SP,
2125 node: hir::VisibilityKind::Inherited },
2131 pub fn maybe_print_trailing_comment(&mut self,
2132 span: syntax_pos::Span,
2133 next_pos: Option<BytePos>)
2135 if let Some(cmnts) = self.comments() {
2136 if let Some(cmnt) = cmnts.trailing_comment(span, next_pos) {
2137 self.print_comment(&cmnt);
2142 pub fn print_remaining_comments(&mut self) {
2143 // If there aren't any remaining comments, then we need to manually
2144 // make sure there is a line break at the end.
2145 if self.next_comment().is_none() {
2148 while let Some(ref cmnt) = self.next_comment() {
2149 self.print_comment(cmnt)
2153 pub fn print_opt_abi_and_extern_if_nondefault(&mut self,
2154 opt_abi: Option<Abi>)
2157 Some(Abi::Rust) => {},
2159 self.word_nbsp("extern");
2160 self.word_nbsp(abi.to_string())
2166 pub fn print_extern_opt_abi(&mut self, opt_abi: Option<Abi>) {
2169 self.word_nbsp("extern");
2170 self.word_nbsp(abi.to_string())
2176 pub fn print_fn_header_info(&mut self,
2177 header: hir::FnHeader,
2178 vis: &hir::Visibility)
2180 self.s.word(visibility_qualified(vis, ""));
2182 match header.constness {
2183 hir::Constness::NotConst => {}
2184 hir::Constness::Const => self.word_nbsp("const"),
2187 match header.asyncness {
2188 hir::IsAsync::NotAsync => {}
2189 hir::IsAsync::Async => self.word_nbsp("async"),
2192 self.print_unsafety(header.unsafety);
2194 if header.abi != Abi::Rust {
2195 self.word_nbsp("extern");
2196 self.word_nbsp(header.abi.to_string());
2202 pub fn print_unsafety(&mut self, s: hir::Unsafety) {
2204 hir::Unsafety::Normal => {}
2205 hir::Unsafety::Unsafe => self.word_nbsp("unsafe"),
2209 pub fn print_is_auto(&mut self, s: hir::IsAuto) {
2211 hir::IsAuto::Yes => self.word_nbsp("auto"),
2212 hir::IsAuto::No => {},
2217 /// Does this expression require a semicolon to be treated
2218 /// as a statement? The negation of this: 'can this expression
2219 /// be used as a statement without a semicolon' -- is used
2220 /// as an early-bail-out in the parser so that, for instance,
2221 /// if true {...} else {...}
2223 /// isn't parsed as (if true {...} else {...} | x) | 5
2225 // Duplicated from `parse::classify`, but adapted for the HIR.
2226 fn expr_requires_semi_to_be_stmt(e: &hir::Expr) -> bool {
2228 hir::ExprKind::Match(..) |
2229 hir::ExprKind::Block(..) |
2230 hir::ExprKind::Loop(..) => false,
2235 /// This statement requires a semicolon after it.
2236 /// note that in one case (stmt_semi), we've already
2237 /// seen the semicolon, and thus don't need another.
2238 fn stmt_ends_with_semi(stmt: &hir::StmtKind) -> bool {
2240 hir::StmtKind::Local(_) => true,
2241 hir::StmtKind::Item(_) => false,
2242 hir::StmtKind::Expr(ref e) => expr_requires_semi_to_be_stmt(&e),
2243 hir::StmtKind::Semi(..) => false,
2247 fn bin_op_to_assoc_op(op: hir::BinOpKind) -> AssocOp {
2248 use crate::hir::BinOpKind::*;
2250 Add => AssocOp::Add,
2251 Sub => AssocOp::Subtract,
2252 Mul => AssocOp::Multiply,
2253 Div => AssocOp::Divide,
2254 Rem => AssocOp::Modulus,
2256 And => AssocOp::LAnd,
2259 BitXor => AssocOp::BitXor,
2260 BitAnd => AssocOp::BitAnd,
2261 BitOr => AssocOp::BitOr,
2262 Shl => AssocOp::ShiftLeft,
2263 Shr => AssocOp::ShiftRight,
2265 Eq => AssocOp::Equal,
2266 Lt => AssocOp::Less,
2267 Le => AssocOp::LessEqual,
2268 Ne => AssocOp::NotEqual,
2269 Ge => AssocOp::GreaterEqual,
2270 Gt => AssocOp::Greater,
2274 /// Expressions that syntactically contain an "exterior" struct literal, i.e., not surrounded by any
2275 /// parens or other delimiters, e.g., `X { y: 1 }`, `X { y: 1 }.method()`, `foo == X { y: 1 }` and
2276 /// `X { y: 1 } == foo` all do, but `(X { y: 1 }) == foo` does not.
2277 fn contains_exterior_struct_lit(value: &hir::Expr) -> bool {
2279 hir::ExprKind::Struct(..) => true,
2281 hir::ExprKind::Assign(ref lhs, ref rhs) |
2282 hir::ExprKind::AssignOp(_, ref lhs, ref rhs) |
2283 hir::ExprKind::Binary(_, ref lhs, ref rhs) => {
2284 // `X { y: 1 } + X { y: 2 }`
2285 contains_exterior_struct_lit(&lhs) || contains_exterior_struct_lit(&rhs)
2287 hir::ExprKind::Unary(_, ref x) |
2288 hir::ExprKind::Cast(ref x, _) |
2289 hir::ExprKind::Type(ref x, _) |
2290 hir::ExprKind::Field(ref x, _) |
2291 hir::ExprKind::Index(ref x, _) => {
2292 // `&X { y: 1 }, X { y: 1 }.y`
2293 contains_exterior_struct_lit(&x)
2296 hir::ExprKind::MethodCall(.., ref exprs) => {
2297 // `X { y: 1 }.bar(...)`
2298 contains_exterior_struct_lit(&exprs[0])