1 #![feature(or_patterns)]
2 #![recursion_limit = "256"]
5 use rustc_ast::util::parser::{self, AssocOp, Fixity};
6 use rustc_ast_pretty::pp::Breaks::{Consistent, Inconsistent};
7 use rustc_ast_pretty::pp::{self, Breaks};
8 use rustc_ast_pretty::pprust::{Comments, PrintState};
10 use rustc_hir::{GenericArg, GenericParam, GenericParamKind, Node};
11 use rustc_hir::{GenericBound, PatKind, RangeEnd, TraitBoundModifier};
12 use rustc_span::source_map::{SourceMap, Spanned};
13 use rustc_span::symbol::{kw, Ident, IdentPrinter, Symbol};
14 use rustc_span::{self, BytePos, FileName};
15 use rustc_target::spec::abi::Abi;
21 pub fn id_to_string(map: &dyn rustc_hir::intravisit::Map<'_>, hir_id: hir::HirId) -> String {
22 to_string(&map, |s| s.print_node(map.find(hir_id).unwrap()))
25 pub enum AnnNode<'a> {
27 Block(&'a hir::Block<'a>),
28 Item(&'a hir::Item<'a>),
30 Expr(&'a hir::Expr<'a>),
31 Pat(&'a hir::Pat<'a>),
32 Arm(&'a hir::Arm<'a>),
37 TraitItem(hir::TraitItemId),
38 ImplItem(hir::ImplItemId),
39 ForeignItem(hir::ForeignItemId),
41 BodyParamPat(hir::BodyId, usize),
45 fn nested(&self, _state: &mut State<'_>, _nested: Nested) {}
46 fn pre(&self, _state: &mut State<'_>, _node: AnnNode<'_>) {}
47 fn post(&self, _state: &mut State<'_>, _node: AnnNode<'_>) {}
51 impl PpAnn for NoAnn {}
52 pub const NO_ANN: &dyn PpAnn = &NoAnn;
54 impl PpAnn for hir::Crate<'_> {
55 fn nested(&self, state: &mut State<'_>, nested: Nested) {
57 Nested::Item(id) => state.print_item(self.item(id.id)),
58 Nested::TraitItem(id) => state.print_trait_item(self.trait_item(id)),
59 Nested::ImplItem(id) => state.print_impl_item(self.impl_item(id)),
60 Nested::ForeignItem(id) => state.print_foreign_item(self.foreign_item(id)),
61 Nested::Body(id) => state.print_expr(&self.body(id).value),
62 Nested::BodyParamPat(id, i) => state.print_pat(&self.body(id).params[i].pat),
67 /// Identical to the `PpAnn` implementation for `hir::Crate`,
68 /// except it avoids creating a dependency on the whole crate.
69 impl PpAnn for &dyn rustc_hir::intravisit::Map<'_> {
70 fn nested(&self, state: &mut State<'_>, nested: Nested) {
72 Nested::Item(id) => state.print_item(self.item(id.id)),
73 Nested::TraitItem(id) => state.print_trait_item(self.trait_item(id)),
74 Nested::ImplItem(id) => state.print_impl_item(self.impl_item(id)),
75 Nested::ForeignItem(id) => state.print_foreign_item(self.foreign_item(id)),
76 Nested::Body(id) => state.print_expr(&self.body(id).value),
77 Nested::BodyParamPat(id, i) => state.print_pat(&self.body(id).params[i].pat),
82 pub struct State<'a> {
84 comments: Option<Comments<'a>>,
85 ann: &'a (dyn PpAnn + 'a),
89 pub fn print_node(&mut self, node: Node<'_>) {
91 Node::Param(a) => self.print_param(&a),
92 Node::Item(a) => self.print_item(&a),
93 Node::ForeignItem(a) => self.print_foreign_item(&a),
94 Node::TraitItem(a) => self.print_trait_item(a),
95 Node::ImplItem(a) => self.print_impl_item(a),
96 Node::Variant(a) => self.print_variant(&a),
97 Node::AnonConst(a) => self.print_anon_const(&a),
98 Node::Expr(a) => self.print_expr(&a),
99 Node::Stmt(a) => self.print_stmt(&a),
100 Node::PathSegment(a) => self.print_path_segment(&a),
101 Node::Ty(a) => self.print_type(&a),
102 Node::TraitRef(a) => self.print_trait_ref(&a),
103 Node::Binding(a) | Node::Pat(a) => self.print_pat(&a),
104 Node::Arm(a) => self.print_arm(&a),
106 // Containing cbox, will be closed by print-block at `}`.
107 self.cbox(INDENT_UNIT);
108 // Head-ibox, will be closed by print-block after `{`.
112 Node::Lifetime(a) => self.print_lifetime(&a),
113 Node::Visibility(a) => self.print_visibility(&a),
114 Node::GenericParam(_) => panic!("cannot print Node::GenericParam"),
115 Node::Field(_) => panic!("cannot print StructField"),
116 // These cases do not carry enough information in the
117 // `hir_map` to reconstruct their full structure for pretty
119 Node::Ctor(..) => panic!("cannot print isolated Ctor"),
120 Node::Local(a) => self.print_local_decl(&a),
121 Node::MacroDef(_) => panic!("cannot print MacroDef"),
122 Node::Crate(..) => panic!("cannot print Crate"),
127 impl std::ops::Deref for State<'_> {
128 type Target = pp::Printer;
129 fn deref(&self) -> &Self::Target {
134 impl std::ops::DerefMut for State<'_> {
135 fn deref_mut(&mut self) -> &mut Self::Target {
140 impl<'a> PrintState<'a> for State<'a> {
141 fn insert_extra_parens(&self) -> bool {
144 fn comments(&mut self) -> &mut Option<Comments<'a>> {
148 fn print_ident(&mut self, ident: Ident) {
149 self.s.word(IdentPrinter::for_ast_ident(ident, ident.is_raw_guess()).to_string());
150 self.ann.post(self, AnnNode::Name(&ident.name))
153 fn print_generic_args(&mut self, _: &ast::GenericArgs, _colons_before_params: bool) {
154 panic!("AST generic args printed by HIR pretty-printer");
158 pub const INDENT_UNIT: usize = 4;
160 /// Requires you to pass an input filename and reader so that
161 /// it can scan the input text for comments to copy forward.
162 pub fn print_crate<'a>(
164 krate: &hir::Crate<'_>,
169 let mut s = State::new_from_input(sm, filename, input, ann);
171 // When printing the AST, we sometimes need to inject `#[no_std]` here.
172 // Since you can't compile the HIR, it's not necessary.
174 s.print_mod(&krate.item.module, &krate.item.attrs);
175 s.print_remaining_comments();
180 pub fn new_from_input(
186 State { s: pp::mk_printer(), comments: Some(Comments::new(sm, filename, input)), ann }
190 pub fn to_string<F>(ann: &dyn PpAnn, f: F) -> String
192 F: FnOnce(&mut State<'_>),
194 let mut printer = State { s: pp::mk_printer(), comments: None, ann };
199 pub fn visibility_qualified<S: Into<Cow<'static, str>>>(vis: &hir::Visibility<'_>, w: S) -> String {
200 to_string(NO_ANN, |s| {
201 s.print_visibility(vis);
206 pub fn generic_params_to_string(generic_params: &[GenericParam<'_>]) -> String {
207 to_string(NO_ANN, |s| s.print_generic_params(generic_params))
210 pub fn bounds_to_string<'b>(bounds: impl IntoIterator<Item = &'b hir::GenericBound<'b>>) -> String {
211 to_string(NO_ANN, |s| s.print_bounds("", bounds))
214 pub fn param_to_string(arg: &hir::Param<'_>) -> String {
215 to_string(NO_ANN, |s| s.print_param(arg))
218 pub fn ty_to_string(ty: &hir::Ty<'_>) -> String {
219 to_string(NO_ANN, |s| s.print_type(ty))
222 pub fn path_segment_to_string(segment: &hir::PathSegment<'_>) -> String {
223 to_string(NO_ANN, |s| s.print_path_segment(segment))
226 pub fn path_to_string(segment: &hir::Path<'_>) -> String {
227 to_string(NO_ANN, |s| s.print_path(segment, false))
231 decl: &hir::FnDecl<'_>,
232 header: hir::FnHeader,
233 name: Option<Symbol>,
234 generics: &hir::Generics<'_>,
235 vis: &hir::Visibility<'_>,
237 body_id: Option<hir::BodyId>,
239 to_string(NO_ANN, |s| s.print_fn(decl, header, name, generics, vis, arg_names, body_id))
242 pub fn enum_def_to_string(
243 enum_definition: &hir::EnumDef<'_>,
244 generics: &hir::Generics<'_>,
246 span: rustc_span::Span,
247 visibility: &hir::Visibility<'_>,
249 to_string(NO_ANN, |s| s.print_enum_def(enum_definition, generics, name, span, visibility))
253 pub fn cbox(&mut self, u: usize) {
257 pub fn nbsp(&mut self) {
261 pub fn word_nbsp<S: Into<Cow<'static, str>>>(&mut self, w: S) {
266 pub fn head<S: Into<Cow<'static, str>>>(&mut self, w: S) {
268 // outer-box is consistent
269 self.cbox(INDENT_UNIT);
270 // head-box is inconsistent
271 self.ibox(w.len() + 1);
272 // keyword that starts the head
278 pub fn bopen(&mut self) {
280 self.end(); // close the head-box
283 pub fn bclose_maybe_open(&mut self, span: rustc_span::Span, close_box: bool) {
284 self.maybe_print_comment(span.hi());
285 self.break_offset_if_not_bol(1, -(INDENT_UNIT as isize));
288 self.end(); // close the outer-box
292 pub fn bclose(&mut self, span: rustc_span::Span) {
293 self.bclose_maybe_open(span, true)
296 pub fn space_if_not_bol(&mut self) {
297 if !self.s.is_beginning_of_line() {
302 pub fn break_offset_if_not_bol(&mut self, n: usize, off: isize) {
303 if !self.s.is_beginning_of_line() {
304 self.s.break_offset(n, off)
305 } else if off != 0 && self.s.last_token().is_hardbreak_tok() {
306 // We do something pretty sketchy here: tuck the nonzero
307 // offset-adjustment we were going to deposit along with the
308 // break into the previous hardbreak.
309 self.s.replace_last_token(pp::Printer::hardbreak_tok_offset(off));
313 // Synthesizes a comment that was not textually present in the original source
315 pub fn synth_comment(&mut self, text: String) {
323 pub fn commasep_cmnt<T, F, G>(&mut self, b: Breaks, elts: &[T], mut op: F, mut get_span: G)
325 F: FnMut(&mut State<'_>, &T),
326 G: FnMut(&T) -> rustc_span::Span,
329 let len = elts.len();
332 self.maybe_print_comment(get_span(elt).hi());
337 self.maybe_print_trailing_comment(get_span(elt), Some(get_span(&elts[i]).hi()));
338 self.space_if_not_bol();
344 pub fn commasep_exprs(&mut self, b: Breaks, exprs: &[hir::Expr<'_>]) {
345 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(&e), |e| e.span)
348 pub fn print_mod(&mut self, _mod: &hir::Mod<'_>, attrs: &[ast::Attribute]) {
349 self.print_inner_attributes(attrs);
350 for &item_id in _mod.item_ids {
351 self.ann.nested(self, Nested::Item(item_id));
355 pub fn print_opt_lifetime(&mut self, lifetime: &hir::Lifetime) {
356 if !lifetime.is_elided() {
357 self.print_lifetime(lifetime);
362 pub fn print_type(&mut self, ty: &hir::Ty<'_>) {
363 self.maybe_print_comment(ty.span.lo());
366 hir::TyKind::Slice(ref ty) => {
368 self.print_type(&ty);
371 hir::TyKind::Ptr(ref mt) => {
373 self.print_mt(mt, true);
375 hir::TyKind::Rptr(ref lifetime, ref mt) => {
377 self.print_opt_lifetime(lifetime);
378 self.print_mt(mt, false);
380 hir::TyKind::Never => {
383 hir::TyKind::Tup(ref elts) => {
385 self.commasep(Inconsistent, &elts[..], |s, ty| s.print_type(&ty));
391 hir::TyKind::BareFn(ref f) => {
401 hir::TyKind::OpaqueDef(..) => self.s.word("/*impl Trait*/"),
402 hir::TyKind::Path(ref qpath) => self.print_qpath(qpath, false),
403 hir::TyKind::TraitObject(bounds, ref lifetime) => {
404 let mut first = true;
405 for bound in bounds {
410 self.word_space("+");
412 self.print_poly_trait_ref(bound);
414 if !lifetime.is_elided() {
416 self.word_space("+");
417 self.print_lifetime(lifetime);
420 hir::TyKind::Array(ref ty, ref length) => {
422 self.print_type(&ty);
424 self.print_anon_const(length);
427 hir::TyKind::Typeof(ref e) => {
428 self.s.word("typeof(");
429 self.print_anon_const(e);
432 hir::TyKind::Infer => {
435 hir::TyKind::Err => {
437 self.s.word("/*ERROR*/");
444 pub fn print_foreign_item(&mut self, item: &hir::ForeignItem<'_>) {
445 self.hardbreak_if_not_bol();
446 self.maybe_print_comment(item.span.lo());
447 self.print_outer_attributes(&item.attrs);
449 hir::ForeignItemKind::Fn(ref decl, ref arg_names, ref generics) => {
454 unsafety: hir::Unsafety::Normal,
455 constness: hir::Constness::NotConst,
457 asyncness: hir::IsAsync::NotAsync,
459 Some(item.ident.name),
465 self.end(); // end head-ibox
467 self.end() // end the outer fn box
469 hir::ForeignItemKind::Static(ref t, m) => {
470 self.head(visibility_qualified(&item.vis, "static"));
471 if m == hir::Mutability::Mut {
472 self.word_space("mut");
474 self.print_ident(item.ident);
475 self.word_space(":");
478 self.end(); // end the head-ibox
479 self.end() // end the outer cbox
481 hir::ForeignItemKind::Type => {
482 self.head(visibility_qualified(&item.vis, "type"));
483 self.print_ident(item.ident);
485 self.end(); // end the head-ibox
486 self.end() // end the outer cbox
491 fn print_associated_const(
495 default: Option<hir::BodyId>,
496 vis: &hir::Visibility<'_>,
498 self.s.word(visibility_qualified(vis, ""));
499 self.word_space("const");
500 self.print_ident(ident);
501 self.word_space(":");
503 if let Some(expr) = default {
505 self.word_space("=");
506 self.ann.nested(self, Nested::Body(expr));
511 fn print_associated_type(
514 generics: &hir::Generics<'_>,
515 bounds: Option<hir::GenericBounds<'_>>,
516 ty: Option<&hir::Ty<'_>>,
518 self.word_space("type");
519 self.print_ident(ident);
520 self.print_generic_params(&generics.params);
521 if let Some(bounds) = bounds {
522 self.print_bounds(":", bounds);
524 self.print_where_clause(&generics.where_clause);
525 if let Some(ty) = ty {
527 self.word_space("=");
535 item: &hir::Item<'_>,
536 generics: &hir::Generics<'_>,
537 inner: impl Fn(&mut Self),
539 self.head(visibility_qualified(&item.vis, "type"));
540 self.print_ident(item.ident);
541 self.print_generic_params(&generics.params);
542 self.end(); // end the inner ibox
544 self.print_where_clause(&generics.where_clause);
548 self.end(); // end the outer ibox
551 /// Pretty-print an item
552 pub fn print_item(&mut self, item: &hir::Item<'_>) {
553 self.hardbreak_if_not_bol();
554 self.maybe_print_comment(item.span.lo());
555 self.print_outer_attributes(&item.attrs);
556 self.ann.pre(self, AnnNode::Item(item));
558 hir::ItemKind::ExternCrate(orig_name) => {
559 self.head(visibility_qualified(&item.vis, "extern crate"));
560 if let Some(orig_name) = orig_name {
561 self.print_name(orig_name);
566 self.print_ident(item.ident);
568 self.end(); // end inner head-block
569 self.end(); // end outer head-block
571 hir::ItemKind::Use(ref path, kind) => {
572 self.head(visibility_qualified(&item.vis, "use"));
573 self.print_path(path, false);
576 hir::UseKind::Single => {
577 if path.segments.last().unwrap().ident != item.ident {
579 self.word_space("as");
580 self.print_ident(item.ident);
584 hir::UseKind::Glob => self.s.word("::*;"),
585 hir::UseKind::ListStem => self.s.word("::{};"),
587 self.end(); // end inner head-block
588 self.end(); // end outer head-block
590 hir::ItemKind::Static(ref ty, m, expr) => {
591 self.head(visibility_qualified(&item.vis, "static"));
592 if m == hir::Mutability::Mut {
593 self.word_space("mut");
595 self.print_ident(item.ident);
596 self.word_space(":");
597 self.print_type(&ty);
599 self.end(); // end the head-ibox
601 self.word_space("=");
602 self.ann.nested(self, Nested::Body(expr));
604 self.end(); // end the outer cbox
606 hir::ItemKind::Const(ref ty, expr) => {
607 self.head(visibility_qualified(&item.vis, "const"));
608 self.print_ident(item.ident);
609 self.word_space(":");
610 self.print_type(&ty);
612 self.end(); // end the head-ibox
614 self.word_space("=");
615 self.ann.nested(self, Nested::Body(expr));
617 self.end(); // end the outer cbox
619 hir::ItemKind::Fn(ref sig, ref param_names, body) => {
624 Some(item.ident.name),
631 self.end(); // need to close a box
632 self.end(); // need to close a box
633 self.ann.nested(self, Nested::Body(body));
635 hir::ItemKind::Mod(ref _mod) => {
636 self.head(visibility_qualified(&item.vis, "mod"));
637 self.print_ident(item.ident);
640 self.print_mod(_mod, &item.attrs);
641 self.bclose(item.span);
643 hir::ItemKind::ForeignMod { abi, items } => {
645 self.word_nbsp(abi.to_string());
647 self.print_inner_attributes(item.attrs);
649 self.ann.nested(self, Nested::ForeignItem(item.id));
651 self.bclose(item.span);
653 hir::ItemKind::GlobalAsm(ref ga) => {
654 self.head(visibility_qualified(&item.vis, "global asm"));
655 self.s.word(ga.asm.to_string());
658 hir::ItemKind::TyAlias(ref ty, ref generics) => {
659 self.print_item_type(item, &generics, |state| {
660 state.word_space("=");
661 state.print_type(&ty);
664 hir::ItemKind::OpaqueTy(ref opaque_ty) => {
665 self.print_item_type(item, &opaque_ty.generics, |state| {
666 let mut real_bounds = Vec::with_capacity(opaque_ty.bounds.len());
667 for b in opaque_ty.bounds.iter() {
668 if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
670 state.word_space("for ?");
671 state.print_trait_ref(&ptr.trait_ref);
676 state.print_bounds("= impl", real_bounds);
679 hir::ItemKind::Enum(ref enum_definition, ref params) => {
680 self.print_enum_def(enum_definition, params, item.ident.name, item.span, &item.vis);
682 hir::ItemKind::Struct(ref struct_def, ref generics) => {
683 self.head(visibility_qualified(&item.vis, "struct"));
684 self.print_struct(struct_def, generics, item.ident.name, item.span, true);
686 hir::ItemKind::Union(ref struct_def, ref generics) => {
687 self.head(visibility_qualified(&item.vis, "union"));
688 self.print_struct(struct_def, generics, item.ident.name, item.span, true);
690 hir::ItemKind::Impl {
702 self.print_visibility(&item.vis);
703 self.print_defaultness(defaultness);
704 self.print_unsafety(unsafety);
705 self.word_nbsp("impl");
707 if !generics.params.is_empty() {
708 self.print_generic_params(&generics.params);
712 if constness == hir::Constness::Const {
713 self.word_nbsp("const");
716 if let hir::ImplPolarity::Negative(_) = polarity {
720 if let Some(ref t) = of_trait {
721 self.print_trait_ref(t);
723 self.word_space("for");
726 self.print_type(&self_ty);
727 self.print_where_clause(&generics.where_clause);
731 self.print_inner_attributes(&item.attrs);
732 for impl_item in items {
733 self.ann.nested(self, Nested::ImplItem(impl_item.id));
735 self.bclose(item.span);
737 hir::ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, trait_items) => {
739 self.print_visibility(&item.vis);
740 self.print_is_auto(is_auto);
741 self.print_unsafety(unsafety);
742 self.word_nbsp("trait");
743 self.print_ident(item.ident);
744 self.print_generic_params(&generics.params);
745 let mut real_bounds = Vec::with_capacity(bounds.len());
746 for b in bounds.iter() {
747 if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
749 self.word_space("for ?");
750 self.print_trait_ref(&ptr.trait_ref);
755 self.print_bounds(":", real_bounds);
756 self.print_where_clause(&generics.where_clause);
759 for trait_item in trait_items {
760 self.ann.nested(self, Nested::TraitItem(trait_item.id));
762 self.bclose(item.span);
764 hir::ItemKind::TraitAlias(ref generics, ref bounds) => {
766 self.print_visibility(&item.vis);
767 self.word_nbsp("trait");
768 self.print_ident(item.ident);
769 self.print_generic_params(&generics.params);
770 let mut real_bounds = Vec::with_capacity(bounds.len());
771 // FIXME(durka) this seems to be some quite outdated syntax
772 for b in bounds.iter() {
773 if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
775 self.word_space("for ?");
776 self.print_trait_ref(&ptr.trait_ref);
782 self.print_bounds("=", real_bounds);
783 self.print_where_clause(&generics.where_clause);
787 self.ann.post(self, AnnNode::Item(item))
790 pub fn print_trait_ref(&mut self, t: &hir::TraitRef<'_>) {
791 self.print_path(&t.path, false)
794 fn print_formal_generic_params(&mut self, generic_params: &[hir::GenericParam<'_>]) {
795 if !generic_params.is_empty() {
797 self.print_generic_params(generic_params);
802 fn print_poly_trait_ref(&mut self, t: &hir::PolyTraitRef<'_>) {
803 self.print_formal_generic_params(&t.bound_generic_params);
804 self.print_trait_ref(&t.trait_ref)
807 pub fn print_enum_def(
809 enum_definition: &hir::EnumDef<'_>,
810 generics: &hir::Generics<'_>,
812 span: rustc_span::Span,
813 visibility: &hir::Visibility<'_>,
815 self.head(visibility_qualified(visibility, "enum"));
816 self.print_name(name);
817 self.print_generic_params(&generics.params);
818 self.print_where_clause(&generics.where_clause);
820 self.print_variants(&enum_definition.variants, span)
823 pub fn print_variants(&mut self, variants: &[hir::Variant<'_>], span: rustc_span::Span) {
826 self.space_if_not_bol();
827 self.maybe_print_comment(v.span.lo());
828 self.print_outer_attributes(&v.attrs);
829 self.ibox(INDENT_UNIT);
830 self.print_variant(v);
833 self.maybe_print_trailing_comment(v.span, None);
838 pub fn print_visibility(&mut self, vis: &hir::Visibility<'_>) {
840 hir::VisibilityKind::Public => self.word_nbsp("pub"),
841 hir::VisibilityKind::Crate(ast::CrateSugar::JustCrate) => self.word_nbsp("crate"),
842 hir::VisibilityKind::Crate(ast::CrateSugar::PubCrate) => self.word_nbsp("pub(crate)"),
843 hir::VisibilityKind::Restricted { ref path, .. } => {
845 if path.segments.len() == 1 && path.segments[0].ident.name == kw::Super {
846 // Special case: `super` can print like `pub(super)`.
847 self.s.word("super");
849 // Everything else requires `in` at present.
850 self.word_nbsp("in");
851 self.print_path(path, false);
855 hir::VisibilityKind::Inherited => (),
859 pub fn print_defaultness(&mut self, defaultness: hir::Defaultness) {
861 hir::Defaultness::Default { .. } => self.word_nbsp("default"),
862 hir::Defaultness::Final => (),
868 struct_def: &hir::VariantData<'_>,
869 generics: &hir::Generics<'_>,
871 span: rustc_span::Span,
872 print_finalizer: bool,
874 self.print_name(name);
875 self.print_generic_params(&generics.params);
877 hir::VariantData::Tuple(..) | hir::VariantData::Unit(..) => {
878 if let hir::VariantData::Tuple(..) = struct_def {
880 self.commasep(Inconsistent, struct_def.fields(), |s, field| {
881 s.maybe_print_comment(field.span.lo());
882 s.print_outer_attributes(&field.attrs);
883 s.print_visibility(&field.vis);
884 s.print_type(&field.ty)
888 self.print_where_clause(&generics.where_clause);
893 self.end() // close the outer-box
895 hir::VariantData::Struct(..) => {
896 self.print_where_clause(&generics.where_clause);
899 self.hardbreak_if_not_bol();
901 for field in struct_def.fields() {
902 self.hardbreak_if_not_bol();
903 self.maybe_print_comment(field.span.lo());
904 self.print_outer_attributes(&field.attrs);
905 self.print_visibility(&field.vis);
906 self.print_ident(field.ident);
908 self.print_type(&field.ty);
917 pub fn print_variant(&mut self, v: &hir::Variant<'_>) {
919 let generics = hir::Generics::empty();
920 self.print_struct(&v.data, &generics, v.ident.name, v.span, false);
921 if let Some(ref d) = v.disr_expr {
923 self.word_space("=");
924 self.print_anon_const(d);
927 pub fn print_method_sig(
931 generics: &hir::Generics<'_>,
932 vis: &hir::Visibility<'_>,
934 body_id: Option<hir::BodyId>,
936 self.print_fn(&m.decl, m.header, Some(ident.name), generics, vis, arg_names, body_id)
939 pub fn print_trait_item(&mut self, ti: &hir::TraitItem<'_>) {
940 self.ann.pre(self, AnnNode::SubItem(ti.hir_id));
941 self.hardbreak_if_not_bol();
942 self.maybe_print_comment(ti.span.lo());
943 self.print_outer_attributes(&ti.attrs);
945 hir::TraitItemKind::Const(ref ty, default) => {
947 Spanned { span: rustc_span::DUMMY_SP, node: hir::VisibilityKind::Inherited };
948 self.print_associated_const(ti.ident, &ty, default, &vis);
950 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Required(ref arg_names)) => {
952 Spanned { span: rustc_span::DUMMY_SP, node: hir::VisibilityKind::Inherited };
953 self.print_method_sig(ti.ident, sig, &ti.generics, &vis, arg_names, None);
956 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Provided(body)) => {
958 Spanned { span: rustc_span::DUMMY_SP, node: hir::VisibilityKind::Inherited };
960 self.print_method_sig(ti.ident, sig, &ti.generics, &vis, &[], Some(body));
962 self.end(); // need to close a box
963 self.end(); // need to close a box
964 self.ann.nested(self, Nested::Body(body));
966 hir::TraitItemKind::Type(ref bounds, ref default) => {
967 self.print_associated_type(
971 default.as_ref().map(|ty| &**ty),
975 self.ann.post(self, AnnNode::SubItem(ti.hir_id))
978 pub fn print_impl_item(&mut self, ii: &hir::ImplItem<'_>) {
979 self.ann.pre(self, AnnNode::SubItem(ii.hir_id));
980 self.hardbreak_if_not_bol();
981 self.maybe_print_comment(ii.span.lo());
982 self.print_outer_attributes(&ii.attrs);
983 self.print_defaultness(ii.defaultness);
986 hir::ImplItemKind::Const(ref ty, expr) => {
987 self.print_associated_const(ii.ident, &ty, Some(expr), &ii.vis);
989 hir::ImplItemKind::Fn(ref sig, body) => {
991 self.print_method_sig(ii.ident, sig, &ii.generics, &ii.vis, &[], Some(body));
993 self.end(); // need to close a box
994 self.end(); // need to close a box
995 self.ann.nested(self, Nested::Body(body));
997 hir::ImplItemKind::TyAlias(ref ty) => {
998 self.print_associated_type(ii.ident, &ii.generics, None, Some(ty));
1001 self.ann.post(self, AnnNode::SubItem(ii.hir_id))
1004 pub fn print_local(&mut self, init: Option<&hir::Expr<'_>>, decl: impl Fn(&mut Self)) {
1005 self.space_if_not_bol();
1006 self.ibox(INDENT_UNIT);
1007 self.word_nbsp("let");
1009 self.ibox(INDENT_UNIT);
1013 if let Some(ref init) = init {
1015 self.word_space("=");
1016 self.print_expr(&init);
1021 pub fn print_stmt(&mut self, st: &hir::Stmt<'_>) {
1022 self.maybe_print_comment(st.span.lo());
1024 hir::StmtKind::Local(ref loc) => {
1025 self.print_local(loc.init.as_deref(), |this| this.print_local_decl(&loc));
1027 hir::StmtKind::Item(item) => self.ann.nested(self, Nested::Item(item)),
1028 hir::StmtKind::Expr(ref expr) => {
1029 self.space_if_not_bol();
1030 self.print_expr(&expr);
1032 hir::StmtKind::Semi(ref expr) => {
1033 self.space_if_not_bol();
1034 self.print_expr(&expr);
1038 if stmt_ends_with_semi(&st.kind) {
1041 self.maybe_print_trailing_comment(st.span, None)
1044 pub fn print_block(&mut self, blk: &hir::Block<'_>) {
1045 self.print_block_with_attrs(blk, &[])
1048 pub fn print_block_unclosed(&mut self, blk: &hir::Block<'_>) {
1049 self.print_block_maybe_unclosed(blk, &[], false)
1052 pub fn print_block_with_attrs(&mut self, blk: &hir::Block<'_>, attrs: &[ast::Attribute]) {
1053 self.print_block_maybe_unclosed(blk, attrs, true)
1056 pub fn print_block_maybe_unclosed(
1058 blk: &hir::Block<'_>,
1059 attrs: &[ast::Attribute],
1063 hir::BlockCheckMode::UnsafeBlock(..) => self.word_space("unsafe"),
1064 hir::BlockCheckMode::PushUnsafeBlock(..) => self.word_space("push_unsafe"),
1065 hir::BlockCheckMode::PopUnsafeBlock(..) => self.word_space("pop_unsafe"),
1066 hir::BlockCheckMode::DefaultBlock => (),
1068 self.maybe_print_comment(blk.span.lo());
1069 self.ann.pre(self, AnnNode::Block(blk));
1072 self.print_inner_attributes(attrs);
1074 for st in blk.stmts {
1075 self.print_stmt(st);
1077 if let Some(ref expr) = blk.expr {
1078 self.space_if_not_bol();
1079 self.print_expr(&expr);
1080 self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi()));
1082 self.bclose_maybe_open(blk.span, close_box);
1083 self.ann.post(self, AnnNode::Block(blk))
1086 pub fn print_anon_const(&mut self, constant: &hir::AnonConst) {
1087 self.ann.nested(self, Nested::Body(constant.body))
1090 fn print_call_post(&mut self, args: &[hir::Expr<'_>]) {
1092 self.commasep_exprs(Inconsistent, args);
1096 pub fn print_expr_maybe_paren(&mut self, expr: &hir::Expr<'_>, prec: i8) {
1097 let needs_par = expr.precedence().order() < prec;
1101 self.print_expr(expr);
1107 /// Print an expr using syntax that's acceptable in a condition position, such as the `cond` in
1108 /// `if cond { ... }`.
1109 pub fn print_expr_as_cond(&mut self, expr: &hir::Expr<'_>) {
1110 let needs_par = match expr.kind {
1111 // These cases need parens due to the parse error observed in #26461: `if return {}`
1112 // parses as the erroneous construct `if (return {})`, not `if (return) {}`.
1113 hir::ExprKind::Closure(..) | hir::ExprKind::Ret(..) | hir::ExprKind::Break(..) => true,
1115 _ => contains_exterior_struct_lit(expr),
1121 self.print_expr(expr);
1127 fn print_expr_vec(&mut self, exprs: &[hir::Expr<'_>]) {
1128 self.ibox(INDENT_UNIT);
1130 self.commasep_exprs(Inconsistent, exprs);
1135 fn print_expr_anon_const(&mut self, anon_const: &hir::AnonConst) {
1136 self.ibox(INDENT_UNIT);
1137 self.s.word_space("const");
1138 self.print_anon_const(anon_const);
1142 fn print_expr_repeat(&mut self, element: &hir::Expr<'_>, count: &hir::AnonConst) {
1143 self.ibox(INDENT_UNIT);
1145 self.print_expr(element);
1146 self.word_space(";");
1147 self.print_anon_const(count);
1152 fn print_expr_struct(
1154 qpath: &hir::QPath<'_>,
1155 fields: &[hir::Field<'_>],
1156 wth: &Option<&hir::Expr<'_>>,
1158 self.print_qpath(qpath, true);
1164 s.ibox(INDENT_UNIT);
1165 if !field.is_shorthand {
1166 s.print_ident(field.ident);
1169 s.print_expr(&field.expr);
1176 self.ibox(INDENT_UNIT);
1177 if !fields.is_empty() {
1182 self.print_expr(&expr);
1186 if !fields.is_empty() {
1194 fn print_expr_tup(&mut self, exprs: &[hir::Expr<'_>]) {
1196 self.commasep_exprs(Inconsistent, exprs);
1197 if exprs.len() == 1 {
1203 fn print_expr_call(&mut self, func: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
1204 let prec = match func.kind {
1205 hir::ExprKind::Field(..) => parser::PREC_FORCE_PAREN,
1206 _ => parser::PREC_POSTFIX,
1209 self.print_expr_maybe_paren(func, prec);
1210 self.print_call_post(args)
1213 fn print_expr_method_call(&mut self, segment: &hir::PathSegment<'_>, args: &[hir::Expr<'_>]) {
1214 let base_args = &args[1..];
1215 self.print_expr_maybe_paren(&args[0], parser::PREC_POSTFIX);
1217 self.print_ident(segment.ident);
1219 let generic_args = segment.generic_args();
1220 if !generic_args.args.is_empty() || !generic_args.bindings.is_empty() {
1221 self.print_generic_args(generic_args, segment.infer_args, true);
1224 self.print_call_post(base_args)
1227 fn print_expr_binary(&mut self, op: hir::BinOp, lhs: &hir::Expr<'_>, rhs: &hir::Expr<'_>) {
1228 let assoc_op = bin_op_to_assoc_op(op.node);
1229 let prec = assoc_op.precedence() as i8;
1230 let fixity = assoc_op.fixity();
1232 let (left_prec, right_prec) = match fixity {
1233 Fixity::Left => (prec, prec + 1),
1234 Fixity::Right => (prec + 1, prec),
1235 Fixity::None => (prec + 1, prec + 1),
1238 let left_prec = match (&lhs.kind, op.node) {
1239 // These cases need parens: `x as i32 < y` has the parser thinking that `i32 < y` is
1240 // the beginning of a path type. It starts trying to parse `x as (i32 < y ...` instead
1241 // of `(x as i32) < ...`. We need to convince it _not_ to do that.
1242 (&hir::ExprKind::Cast { .. }, hir::BinOpKind::Lt | hir::BinOpKind::Shl) => {
1243 parser::PREC_FORCE_PAREN
1248 self.print_expr_maybe_paren(lhs, left_prec);
1250 self.word_space(op.node.as_str());
1251 self.print_expr_maybe_paren(rhs, right_prec)
1254 fn print_expr_unary(&mut self, op: hir::UnOp, expr: &hir::Expr<'_>) {
1255 self.s.word(op.as_str());
1256 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1259 fn print_expr_addr_of(
1261 kind: hir::BorrowKind,
1262 mutability: hir::Mutability,
1263 expr: &hir::Expr<'_>,
1267 hir::BorrowKind::Ref => self.print_mutability(mutability, false),
1268 hir::BorrowKind::Raw => {
1269 self.word_nbsp("raw");
1270 self.print_mutability(mutability, true);
1273 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1276 fn print_literal(&mut self, lit: &hir::Lit) {
1277 self.maybe_print_comment(lit.span.lo());
1278 self.word(lit.node.to_lit_token().to_string())
1281 pub fn print_expr(&mut self, expr: &hir::Expr<'_>) {
1282 self.maybe_print_comment(expr.span.lo());
1283 self.print_outer_attributes(&expr.attrs);
1284 self.ibox(INDENT_UNIT);
1285 self.ann.pre(self, AnnNode::Expr(expr));
1287 hir::ExprKind::Box(ref expr) => {
1288 self.word_space("box");
1289 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX);
1291 hir::ExprKind::Array(ref exprs) => {
1292 self.print_expr_vec(exprs);
1294 hir::ExprKind::ConstBlock(ref anon_const) => {
1295 self.print_expr_anon_const(anon_const);
1297 hir::ExprKind::Repeat(ref element, ref count) => {
1298 self.print_expr_repeat(&element, count);
1300 hir::ExprKind::Struct(ref qpath, fields, ref wth) => {
1301 self.print_expr_struct(qpath, fields, wth);
1303 hir::ExprKind::Tup(ref exprs) => {
1304 self.print_expr_tup(exprs);
1306 hir::ExprKind::Call(ref func, ref args) => {
1307 self.print_expr_call(&func, args);
1309 hir::ExprKind::MethodCall(ref segment, _, ref args, _) => {
1310 self.print_expr_method_call(segment, args);
1312 hir::ExprKind::Binary(op, ref lhs, ref rhs) => {
1313 self.print_expr_binary(op, &lhs, &rhs);
1315 hir::ExprKind::Unary(op, ref expr) => {
1316 self.print_expr_unary(op, &expr);
1318 hir::ExprKind::AddrOf(k, m, ref expr) => {
1319 self.print_expr_addr_of(k, m, &expr);
1321 hir::ExprKind::Lit(ref lit) => {
1322 self.print_literal(&lit);
1324 hir::ExprKind::Cast(ref expr, ref ty) => {
1325 let prec = AssocOp::As.precedence() as i8;
1326 self.print_expr_maybe_paren(&expr, prec);
1328 self.word_space("as");
1329 self.print_type(&ty);
1331 hir::ExprKind::Type(ref expr, ref ty) => {
1332 let prec = AssocOp::Colon.precedence() as i8;
1333 self.print_expr_maybe_paren(&expr, prec);
1334 self.word_space(":");
1335 self.print_type(&ty);
1337 hir::ExprKind::DropTemps(ref init) => {
1339 self.cbox(INDENT_UNIT);
1343 // Print `let _t = $init;`:
1344 let temp = Ident::from_str("_t");
1345 self.print_local(Some(init), |this| this.print_ident(temp));
1349 self.space_if_not_bol();
1350 self.print_ident(temp);
1353 self.bclose_maybe_open(expr.span, true);
1355 hir::ExprKind::Loop(ref blk, opt_label, _) => {
1356 if let Some(label) = opt_label {
1357 self.print_ident(label.ident);
1358 self.word_space(":");
1362 self.print_block(&blk);
1364 hir::ExprKind::Match(ref expr, arms, _) => {
1365 self.cbox(INDENT_UNIT);
1366 self.ibox(INDENT_UNIT);
1367 self.word_nbsp("match");
1368 self.print_expr_as_cond(&expr);
1372 self.print_arm(arm);
1374 self.bclose(expr.span);
1376 hir::ExprKind::Closure(capture_clause, ref decl, body, _fn_decl_span, _gen) => {
1377 self.print_capture_clause(capture_clause);
1379 self.print_closure_params(&decl, body);
1382 // This is a bare expression.
1383 self.ann.nested(self, Nested::Body(body));
1384 self.end(); // need to close a box
1386 // A box will be closed by `print_expr`, but we didn't want an overall
1387 // wrapper so we closed the corresponding opening. so create an
1388 // empty box to satisfy the close.
1391 hir::ExprKind::Block(ref blk, opt_label) => {
1392 if let Some(label) = opt_label {
1393 self.print_ident(label.ident);
1394 self.word_space(":");
1396 // containing cbox, will be closed by print-block at `}`
1397 self.cbox(INDENT_UNIT);
1398 // head-box, will be closed by print-block after `{`
1400 self.print_block(&blk);
1402 hir::ExprKind::Assign(ref lhs, ref rhs, _) => {
1403 let prec = AssocOp::Assign.precedence() as i8;
1404 self.print_expr_maybe_paren(&lhs, prec + 1);
1406 self.word_space("=");
1407 self.print_expr_maybe_paren(&rhs, prec);
1409 hir::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
1410 let prec = AssocOp::Assign.precedence() as i8;
1411 self.print_expr_maybe_paren(&lhs, prec + 1);
1413 self.s.word(op.node.as_str());
1414 self.word_space("=");
1415 self.print_expr_maybe_paren(&rhs, prec);
1417 hir::ExprKind::Field(ref expr, ident) => {
1418 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
1420 self.print_ident(ident);
1422 hir::ExprKind::Index(ref expr, ref index) => {
1423 self.print_expr_maybe_paren(&expr, parser::PREC_POSTFIX);
1425 self.print_expr(&index);
1428 hir::ExprKind::Path(ref qpath) => self.print_qpath(qpath, true),
1429 hir::ExprKind::Break(destination, ref opt_expr) => {
1430 self.s.word("break");
1432 if let Some(label) = destination.label {
1433 self.print_ident(label.ident);
1436 if let Some(ref expr) = *opt_expr {
1437 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
1441 hir::ExprKind::Continue(destination) => {
1442 self.s.word("continue");
1444 if let Some(label) = destination.label {
1445 self.print_ident(label.ident);
1449 hir::ExprKind::Ret(ref result) => {
1450 self.s.word("return");
1451 if let Some(ref expr) = *result {
1453 self.print_expr_maybe_paren(&expr, parser::PREC_JUMP);
1456 hir::ExprKind::InlineAsm(ref a) => {
1459 Operand(&'a hir::InlineAsmOperand<'a>),
1460 Options(ast::InlineAsmOptions),
1463 let mut args = vec![];
1464 args.push(AsmArg::Template(ast::InlineAsmTemplatePiece::to_string(&a.template)));
1465 args.extend(a.operands.iter().map(|o| AsmArg::Operand(o)));
1466 if !a.options.is_empty() {
1467 args.push(AsmArg::Options(a.options));
1472 self.commasep(Consistent, &args, |s, arg| match arg {
1473 AsmArg::Template(template) => s.print_string(&template, ast::StrStyle::Cooked),
1474 AsmArg::Operand(op) => match op {
1475 hir::InlineAsmOperand::In { reg, expr } => {
1478 s.word(format!("{}", reg));
1483 hir::InlineAsmOperand::Out { reg, late, expr } => {
1484 s.word(if *late { "lateout" } else { "out" });
1486 s.word(format!("{}", reg));
1490 Some(expr) => s.print_expr(expr),
1491 None => s.word("_"),
1494 hir::InlineAsmOperand::InOut { reg, late, expr } => {
1495 s.word(if *late { "inlateout" } else { "inout" });
1497 s.word(format!("{}", reg));
1502 hir::InlineAsmOperand::SplitInOut { reg, late, in_expr, out_expr } => {
1503 s.word(if *late { "inlateout" } else { "inout" });
1505 s.word(format!("{}", reg));
1508 s.print_expr(in_expr);
1512 Some(out_expr) => s.print_expr(out_expr),
1513 None => s.word("_"),
1516 hir::InlineAsmOperand::Const { expr } => {
1521 hir::InlineAsmOperand::Sym { expr } => {
1527 AsmArg::Options(opts) => {
1530 let mut options = vec![];
1531 if opts.contains(ast::InlineAsmOptions::PURE) {
1532 options.push("pure");
1534 if opts.contains(ast::InlineAsmOptions::NOMEM) {
1535 options.push("nomem");
1537 if opts.contains(ast::InlineAsmOptions::READONLY) {
1538 options.push("readonly");
1540 if opts.contains(ast::InlineAsmOptions::PRESERVES_FLAGS) {
1541 options.push("preserves_flags");
1543 if opts.contains(ast::InlineAsmOptions::NORETURN) {
1544 options.push("noreturn");
1546 if opts.contains(ast::InlineAsmOptions::NOSTACK) {
1547 options.push("nostack");
1549 if opts.contains(ast::InlineAsmOptions::ATT_SYNTAX) {
1550 options.push("att_syntax");
1552 s.commasep(Inconsistent, &options, |s, &opt| {
1560 hir::ExprKind::LlvmInlineAsm(ref a) => {
1562 self.s.word("llvm_asm!");
1564 self.print_symbol(i.asm, i.asm_str_style);
1565 self.word_space(":");
1567 let mut out_idx = 0;
1568 self.commasep(Inconsistent, &i.outputs, |s, out| {
1569 let constraint = out.constraint.as_str();
1570 let mut ch = constraint.chars();
1572 Some('=') if out.is_rw => {
1573 s.print_string(&format!("+{}", ch.as_str()), ast::StrStyle::Cooked)
1575 _ => s.print_string(&constraint, ast::StrStyle::Cooked),
1578 s.print_expr(&a.outputs_exprs[out_idx]);
1583 self.word_space(":");
1586 self.commasep(Inconsistent, &i.inputs, |s, &co| {
1587 s.print_symbol(co, ast::StrStyle::Cooked);
1589 s.print_expr(&a.inputs_exprs[in_idx]);
1594 self.word_space(":");
1596 self.commasep(Inconsistent, &i.clobbers, |s, &co| {
1597 s.print_symbol(co, ast::StrStyle::Cooked);
1600 let mut options = vec![];
1602 options.push("volatile");
1605 options.push("alignstack");
1607 if i.dialect == ast::LlvmAsmDialect::Intel {
1608 options.push("intel");
1611 if !options.is_empty() {
1613 self.word_space(":");
1614 self.commasep(Inconsistent, &options, |s, &co| {
1615 s.print_string(co, ast::StrStyle::Cooked);
1621 hir::ExprKind::Yield(ref expr, _) => {
1622 self.word_space("yield");
1623 self.print_expr_maybe_paren(&expr, parser::PREC_JUMP);
1625 hir::ExprKind::Err => {
1627 self.s.word("/*ERROR*/");
1631 self.ann.post(self, AnnNode::Expr(expr));
1635 pub fn print_local_decl(&mut self, loc: &hir::Local<'_>) {
1636 self.print_pat(&loc.pat);
1637 if let Some(ref ty) = loc.ty {
1638 self.word_space(":");
1639 self.print_type(&ty);
1643 pub fn print_usize(&mut self, i: usize) {
1644 self.s.word(i.to_string())
1647 pub fn print_name(&mut self, name: Symbol) {
1648 self.print_ident(Ident::with_dummy_span(name))
1651 pub fn print_for_decl(&mut self, loc: &hir::Local<'_>, coll: &hir::Expr<'_>) {
1652 self.print_local_decl(loc);
1654 self.word_space("in");
1655 self.print_expr(coll)
1658 pub fn print_path(&mut self, path: &hir::Path<'_>, colons_before_params: bool) {
1659 self.maybe_print_comment(path.span.lo());
1661 for (i, segment) in path.segments.iter().enumerate() {
1665 if segment.ident.name != kw::PathRoot {
1666 self.print_ident(segment.ident);
1667 self.print_generic_args(
1668 segment.generic_args(),
1670 colons_before_params,
1676 pub fn print_path_segment(&mut self, segment: &hir::PathSegment<'_>) {
1677 if segment.ident.name != kw::PathRoot {
1678 self.print_ident(segment.ident);
1679 self.print_generic_args(segment.generic_args(), segment.infer_args, false);
1683 pub fn print_qpath(&mut self, qpath: &hir::QPath<'_>, colons_before_params: bool) {
1685 hir::QPath::Resolved(None, ref path) => self.print_path(path, colons_before_params),
1686 hir::QPath::Resolved(Some(ref qself), ref path) => {
1688 self.print_type(qself);
1690 self.word_space("as");
1692 for (i, segment) in path.segments[..path.segments.len() - 1].iter().enumerate() {
1696 if segment.ident.name != kw::PathRoot {
1697 self.print_ident(segment.ident);
1698 self.print_generic_args(
1699 segment.generic_args(),
1701 colons_before_params,
1708 let item_segment = path.segments.last().unwrap();
1709 self.print_ident(item_segment.ident);
1710 self.print_generic_args(
1711 item_segment.generic_args(),
1712 item_segment.infer_args,
1713 colons_before_params,
1716 hir::QPath::TypeRelative(ref qself, ref item_segment) => {
1717 // If we've got a compound-qualified-path, let's push an additional pair of angle
1718 // brackets, so that we pretty-print `<<A::B>::C>` as `<A::B>::C`, instead of just
1719 // `A::B::C` (since the latter could be ambiguous to the user)
1720 if let hir::TyKind::Path(hir::QPath::Resolved(None, _)) = &qself.kind {
1721 self.print_type(qself);
1724 self.print_type(qself);
1729 self.print_ident(item_segment.ident);
1730 self.print_generic_args(
1731 item_segment.generic_args(),
1732 item_segment.infer_args,
1733 colons_before_params,
1736 hir::QPath::LangItem(lang_item, span) => {
1737 self.s.word("#[lang = \"");
1738 self.print_ident(Ident::new(lang_item.name(), span));
1744 fn print_generic_args(
1746 generic_args: &hir::GenericArgs<'_>,
1748 colons_before_params: bool,
1750 if generic_args.parenthesized {
1752 self.commasep(Inconsistent, generic_args.inputs(), |s, ty| s.print_type(&ty));
1755 self.space_if_not_bol();
1756 self.word_space("->");
1757 self.print_type(generic_args.bindings[0].ty());
1759 let start = if colons_before_params { "::<" } else { "<" };
1760 let empty = Cell::new(true);
1761 let start_or_comma = |this: &mut Self| {
1766 this.word_space(",")
1770 let mut nonelided_generic_args: bool = false;
1771 let elide_lifetimes = generic_args.args.iter().all(|arg| match arg {
1772 GenericArg::Lifetime(lt) => lt.is_elided(),
1774 nonelided_generic_args = true;
1779 if nonelided_generic_args {
1780 start_or_comma(self);
1784 |s, generic_arg| match generic_arg {
1785 GenericArg::Lifetime(lt) if !elide_lifetimes => s.print_lifetime(lt),
1786 GenericArg::Lifetime(_) => {}
1787 GenericArg::Type(ty) => s.print_type(ty),
1788 GenericArg::Const(ct) => s.print_anon_const(&ct.value),
1793 // FIXME(eddyb): this would leak into error messages (e.g.,
1794 // "non-exhaustive patterns: `Some::<..>(_)` not covered").
1795 if infer_args && false {
1796 start_or_comma(self);
1800 for binding in generic_args.bindings.iter() {
1801 start_or_comma(self);
1802 self.print_ident(binding.ident);
1804 match generic_args.bindings[0].kind {
1805 hir::TypeBindingKind::Equality { ref ty } => {
1806 self.word_space("=");
1807 self.print_type(ty);
1809 hir::TypeBindingKind::Constraint { bounds } => {
1810 self.print_bounds(":", bounds);
1821 pub fn print_pat(&mut self, pat: &hir::Pat<'_>) {
1822 self.maybe_print_comment(pat.span.lo());
1823 self.ann.pre(self, AnnNode::Pat(pat));
1824 // Pat isn't normalized, but the beauty of it
1825 // is that it doesn't matter
1827 PatKind::Wild => self.s.word("_"),
1828 PatKind::Binding(binding_mode, _, ident, ref sub) => {
1829 match binding_mode {
1830 hir::BindingAnnotation::Ref => {
1831 self.word_nbsp("ref");
1832 self.print_mutability(hir::Mutability::Not, false);
1834 hir::BindingAnnotation::RefMut => {
1835 self.word_nbsp("ref");
1836 self.print_mutability(hir::Mutability::Mut, false);
1838 hir::BindingAnnotation::Unannotated => {}
1839 hir::BindingAnnotation::Mutable => {
1840 self.word_nbsp("mut");
1843 self.print_ident(ident);
1844 if let Some(ref p) = *sub {
1849 PatKind::TupleStruct(ref qpath, ref elts, ddpos) => {
1850 self.print_qpath(qpath, true);
1852 if let Some(ddpos) = ddpos {
1853 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p));
1855 self.word_space(",");
1858 if ddpos != elts.len() {
1860 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p));
1863 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p));
1867 PatKind::Path(ref qpath) => {
1868 self.print_qpath(qpath, true);
1870 PatKind::Struct(ref qpath, ref fields, etc) => {
1871 self.print_qpath(qpath, true);
1873 self.word_space("{");
1878 s.cbox(INDENT_UNIT);
1879 if !f.is_shorthand {
1880 s.print_ident(f.ident);
1883 s.print_pat(&f.pat);
1889 if !fields.is_empty() {
1890 self.word_space(",");
1897 PatKind::Or(ref pats) => {
1898 self.strsep("|", true, Inconsistent, &pats[..], |s, p| s.print_pat(&p));
1900 PatKind::Tuple(ref elts, ddpos) => {
1902 if let Some(ddpos) = ddpos {
1903 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p));
1905 self.word_space(",");
1908 if ddpos != elts.len() {
1910 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p));
1913 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p));
1914 if elts.len() == 1 {
1920 PatKind::Box(ref inner) => {
1921 let is_range_inner = matches!(inner.kind, PatKind::Range(..));
1922 self.s.word("box ");
1926 self.print_pat(&inner);
1931 PatKind::Ref(ref inner, mutbl) => {
1932 let is_range_inner = matches!(inner.kind, PatKind::Range(..));
1934 self.s.word(mutbl.prefix_str());
1938 self.print_pat(&inner);
1943 PatKind::Lit(ref e) => self.print_expr(&e),
1944 PatKind::Range(ref begin, ref end, ref end_kind) => {
1945 if let Some(expr) = begin {
1946 self.print_expr(expr);
1950 RangeEnd::Included => self.s.word("..."),
1951 RangeEnd::Excluded => self.s.word(".."),
1953 if let Some(expr) = end {
1954 self.print_expr(expr);
1957 PatKind::Slice(ref before, ref slice, ref after) => {
1959 self.commasep(Inconsistent, &before[..], |s, p| s.print_pat(&p));
1960 if let Some(ref p) = *slice {
1961 if !before.is_empty() {
1962 self.word_space(",");
1964 if let PatKind::Wild = p.kind {
1970 if !after.is_empty() {
1971 self.word_space(",");
1974 self.commasep(Inconsistent, &after[..], |s, p| s.print_pat(&p));
1978 self.ann.post(self, AnnNode::Pat(pat))
1981 pub fn print_param(&mut self, arg: &hir::Param<'_>) {
1982 self.print_outer_attributes(&arg.attrs);
1983 self.print_pat(&arg.pat);
1986 pub fn print_arm(&mut self, arm: &hir::Arm<'_>) {
1987 // I have no idea why this check is necessary, but here it
1989 if arm.attrs.is_empty() {
1992 self.cbox(INDENT_UNIT);
1993 self.ann.pre(self, AnnNode::Arm(arm));
1995 self.print_outer_attributes(&arm.attrs);
1996 self.print_pat(&arm.pat);
1998 if let Some(ref g) = arm.guard {
2000 hir::Guard::If(e) => {
2001 self.word_space("if");
2002 self.print_expr(&e);
2007 self.word_space("=>");
2009 match arm.body.kind {
2010 hir::ExprKind::Block(ref blk, opt_label) => {
2011 if let Some(label) = opt_label {
2012 self.print_ident(label.ident);
2013 self.word_space(":");
2015 // the block will close the pattern's ibox
2016 self.print_block_unclosed(&blk);
2018 // If it is a user-provided unsafe block, print a comma after it
2019 if let hir::BlockCheckMode::UnsafeBlock(hir::UnsafeSource::UserProvided) = blk.rules
2025 self.end(); // close the ibox for the pattern
2026 self.print_expr(&arm.body);
2030 self.ann.post(self, AnnNode::Arm(arm));
2031 self.end() // close enclosing cbox
2036 decl: &hir::FnDecl<'_>,
2037 header: hir::FnHeader,
2038 name: Option<Symbol>,
2039 generics: &hir::Generics<'_>,
2040 vis: &hir::Visibility<'_>,
2041 arg_names: &[Ident],
2042 body_id: Option<hir::BodyId>,
2044 self.print_fn_header_info(header, vis);
2046 if let Some(name) = name {
2048 self.print_name(name);
2050 self.print_generic_params(&generics.params);
2054 // Make sure we aren't supplied *both* `arg_names` and `body_id`.
2055 assert!(arg_names.is_empty() || body_id.is_none());
2056 self.commasep(Inconsistent, &decl.inputs, |s, ty| {
2057 s.ibox(INDENT_UNIT);
2058 if let Some(arg_name) = arg_names.get(i) {
2059 s.s.word(arg_name.to_string());
2062 } else if let Some(body_id) = body_id {
2063 s.ann.nested(s, Nested::BodyParamPat(body_id, i));
2071 if decl.c_variadic {
2072 self.s.word(", ...");
2076 self.print_fn_output(decl);
2077 self.print_where_clause(&generics.where_clause)
2080 fn print_closure_params(&mut self, decl: &hir::FnDecl<'_>, body_id: hir::BodyId) {
2083 self.commasep(Inconsistent, &decl.inputs, |s, ty| {
2084 s.ibox(INDENT_UNIT);
2086 s.ann.nested(s, Nested::BodyParamPat(body_id, i));
2089 if let hir::TyKind::Infer = ty.kind {
2100 if let hir::FnRetTy::DefaultReturn(..) = decl.output {
2104 self.space_if_not_bol();
2105 self.word_space("->");
2107 hir::FnRetTy::Return(ref ty) => {
2108 self.print_type(&ty);
2109 self.maybe_print_comment(ty.span.lo())
2111 hir::FnRetTy::DefaultReturn(..) => unreachable!(),
2115 pub fn print_capture_clause(&mut self, capture_clause: hir::CaptureBy) {
2116 match capture_clause {
2117 hir::CaptureBy::Value => self.word_space("move"),
2118 hir::CaptureBy::Ref => {}
2122 pub fn print_bounds<'b>(
2124 prefix: &'static str,
2125 bounds: impl IntoIterator<Item = &'b hir::GenericBound<'b>>,
2127 let mut first = true;
2128 for bound in bounds {
2130 self.s.word(prefix);
2132 if !(first && prefix.is_empty()) {
2138 self.word_space("+");
2142 GenericBound::Trait(tref, modifier) => {
2143 if modifier == &TraitBoundModifier::Maybe {
2146 self.print_poly_trait_ref(tref);
2148 GenericBound::LangItemTrait(lang_item, span, ..) => {
2149 self.s.word("#[lang = \"");
2150 self.print_ident(Ident::new(lang_item.name(), *span));
2153 GenericBound::Outlives(lt) => {
2154 self.print_lifetime(lt);
2160 pub fn print_generic_params(&mut self, generic_params: &[GenericParam<'_>]) {
2161 if !generic_params.is_empty() {
2164 self.commasep(Inconsistent, generic_params, |s, param| s.print_generic_param(param));
2170 pub fn print_generic_param(&mut self, param: &GenericParam<'_>) {
2171 if let GenericParamKind::Const { .. } = param.kind {
2172 self.word_space("const");
2175 self.print_ident(param.name.ident());
2178 GenericParamKind::Lifetime { .. } => {
2180 for bound in param.bounds {
2182 GenericBound::Outlives(ref lt) => {
2184 self.print_lifetime(lt);
2191 GenericParamKind::Type { ref default, .. } => {
2192 self.print_bounds(":", param.bounds);
2193 if let Some(default) = default {
2195 self.word_space("=");
2196 self.print_type(&default)
2199 GenericParamKind::Const { ref ty } => {
2200 self.word_space(":");
2206 pub fn print_lifetime(&mut self, lifetime: &hir::Lifetime) {
2207 self.print_ident(lifetime.name.ident())
2210 pub fn print_where_clause(&mut self, where_clause: &hir::WhereClause<'_>) {
2211 if where_clause.predicates.is_empty() {
2216 self.word_space("where");
2218 for (i, predicate) in where_clause.predicates.iter().enumerate() {
2220 self.word_space(",");
2224 &hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
2225 ref bound_generic_params,
2230 self.print_formal_generic_params(bound_generic_params);
2231 self.print_type(&bounded_ty);
2232 self.print_bounds(":", bounds);
2234 &hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
2239 self.print_lifetime(lifetime);
2242 for (i, bound) in bounds.iter().enumerate() {
2244 GenericBound::Outlives(lt) => {
2245 self.print_lifetime(lt);
2255 &hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
2260 self.print_type(lhs_ty);
2262 self.word_space("=");
2263 self.print_type(rhs_ty);
2269 pub fn print_mutability(&mut self, mutbl: hir::Mutability, print_const: bool) {
2271 hir::Mutability::Mut => self.word_nbsp("mut"),
2272 hir::Mutability::Not => {
2274 self.word_nbsp("const")
2280 pub fn print_mt(&mut self, mt: &hir::MutTy<'_>, print_const: bool) {
2281 self.print_mutability(mt.mutbl, print_const);
2282 self.print_type(&mt.ty)
2285 pub fn print_fn_output(&mut self, decl: &hir::FnDecl<'_>) {
2286 if let hir::FnRetTy::DefaultReturn(..) = decl.output {
2290 self.space_if_not_bol();
2291 self.ibox(INDENT_UNIT);
2292 self.word_space("->");
2294 hir::FnRetTy::DefaultReturn(..) => unreachable!(),
2295 hir::FnRetTy::Return(ref ty) => self.print_type(&ty),
2299 if let hir::FnRetTy::Return(ref output) = decl.output {
2300 self.maybe_print_comment(output.span.lo())
2307 unsafety: hir::Unsafety,
2308 decl: &hir::FnDecl<'_>,
2309 name: Option<Symbol>,
2310 generic_params: &[hir::GenericParam<'_>],
2311 arg_names: &[Ident],
2313 self.ibox(INDENT_UNIT);
2314 if !generic_params.is_empty() {
2316 self.print_generic_params(generic_params);
2318 let generics = hir::Generics {
2320 where_clause: hir::WhereClause { predicates: &[], span: rustc_span::DUMMY_SP },
2321 span: rustc_span::DUMMY_SP,
2328 constness: hir::Constness::NotConst,
2329 asyncness: hir::IsAsync::NotAsync,
2333 &Spanned { span: rustc_span::DUMMY_SP, node: hir::VisibilityKind::Inherited },
2340 pub fn maybe_print_trailing_comment(
2342 span: rustc_span::Span,
2343 next_pos: Option<BytePos>,
2345 if let Some(cmnts) = self.comments() {
2346 if let Some(cmnt) = cmnts.trailing_comment(span, next_pos) {
2347 self.print_comment(&cmnt);
2352 pub fn print_remaining_comments(&mut self) {
2353 // If there aren't any remaining comments, then we need to manually
2354 // make sure there is a line break at the end.
2355 if self.next_comment().is_none() {
2358 while let Some(ref cmnt) = self.next_comment() {
2359 self.print_comment(cmnt)
2363 pub fn print_opt_abi_and_extern_if_nondefault(&mut self, opt_abi: Option<Abi>) {
2365 Some(Abi::Rust) => {}
2367 self.word_nbsp("extern");
2368 self.word_nbsp(abi.to_string())
2374 pub fn print_extern_opt_abi(&mut self, opt_abi: Option<Abi>) {
2375 if let Some(abi) = opt_abi {
2376 self.word_nbsp("extern");
2377 self.word_nbsp(abi.to_string())
2381 pub fn print_fn_header_info(&mut self, header: hir::FnHeader, vis: &hir::Visibility<'_>) {
2382 self.s.word(visibility_qualified(vis, ""));
2384 match header.constness {
2385 hir::Constness::NotConst => {}
2386 hir::Constness::Const => self.word_nbsp("const"),
2389 match header.asyncness {
2390 hir::IsAsync::NotAsync => {}
2391 hir::IsAsync::Async => self.word_nbsp("async"),
2394 self.print_unsafety(header.unsafety);
2396 if header.abi != Abi::Rust {
2397 self.word_nbsp("extern");
2398 self.word_nbsp(header.abi.to_string());
2404 pub fn print_unsafety(&mut self, s: hir::Unsafety) {
2406 hir::Unsafety::Normal => {}
2407 hir::Unsafety::Unsafe => self.word_nbsp("unsafe"),
2411 pub fn print_is_auto(&mut self, s: hir::IsAuto) {
2413 hir::IsAuto::Yes => self.word_nbsp("auto"),
2414 hir::IsAuto::No => {}
2419 /// Does this expression require a semicolon to be treated
2420 /// as a statement? The negation of this: 'can this expression
2421 /// be used as a statement without a semicolon' -- is used
2422 /// as an early-bail-out in the parser so that, for instance,
2423 /// if true {...} else {...}
2425 /// isn't parsed as (if true {...} else {...} | x) | 5
2427 // Duplicated from `parse::classify`, but adapted for the HIR.
2428 fn expr_requires_semi_to_be_stmt(e: &hir::Expr<'_>) -> bool {
2429 !matches!(e.kind, hir::ExprKind::Match(..) | hir::ExprKind::Block(..) | hir::ExprKind::Loop(..))
2432 /// This statement requires a semicolon after it.
2433 /// note that in one case (stmt_semi), we've already
2434 /// seen the semicolon, and thus don't need another.
2435 fn stmt_ends_with_semi(stmt: &hir::StmtKind<'_>) -> bool {
2437 hir::StmtKind::Local(_) => true,
2438 hir::StmtKind::Item(_) => false,
2439 hir::StmtKind::Expr(ref e) => expr_requires_semi_to_be_stmt(&e),
2440 hir::StmtKind::Semi(..) => false,
2444 fn bin_op_to_assoc_op(op: hir::BinOpKind) -> AssocOp {
2445 use crate::hir::BinOpKind::*;
2447 Add => AssocOp::Add,
2448 Sub => AssocOp::Subtract,
2449 Mul => AssocOp::Multiply,
2450 Div => AssocOp::Divide,
2451 Rem => AssocOp::Modulus,
2453 And => AssocOp::LAnd,
2456 BitXor => AssocOp::BitXor,
2457 BitAnd => AssocOp::BitAnd,
2458 BitOr => AssocOp::BitOr,
2459 Shl => AssocOp::ShiftLeft,
2460 Shr => AssocOp::ShiftRight,
2462 Eq => AssocOp::Equal,
2463 Lt => AssocOp::Less,
2464 Le => AssocOp::LessEqual,
2465 Ne => AssocOp::NotEqual,
2466 Ge => AssocOp::GreaterEqual,
2467 Gt => AssocOp::Greater,
2471 /// Expressions that syntactically contain an "exterior" struct literal, i.e., not surrounded by any
2472 /// parens or other delimiters, e.g., `X { y: 1 }`, `X { y: 1 }.method()`, `foo == X { y: 1 }` and
2473 /// `X { y: 1 } == foo` all do, but `(X { y: 1 }) == foo` does not.
2474 fn contains_exterior_struct_lit(value: &hir::Expr<'_>) -> bool {
2476 hir::ExprKind::Struct(..) => true,
2478 hir::ExprKind::Assign(ref lhs, ref rhs, _)
2479 | hir::ExprKind::AssignOp(_, ref lhs, ref rhs)
2480 | hir::ExprKind::Binary(_, ref lhs, ref rhs) => {
2481 // `X { y: 1 } + X { y: 2 }`
2482 contains_exterior_struct_lit(&lhs) || contains_exterior_struct_lit(&rhs)
2484 hir::ExprKind::Unary(_, ref x)
2485 | hir::ExprKind::Cast(ref x, _)
2486 | hir::ExprKind::Type(ref x, _)
2487 | hir::ExprKind::Field(ref x, _)
2488 | hir::ExprKind::Index(ref x, _) => {
2489 // `&X { y: 1 }, X { y: 1 }.y`
2490 contains_exterior_struct_lit(&x)
2493 hir::ExprKind::MethodCall(.., ref exprs, _) => {
2494 // `X { y: 1 }.bar(...)`
2495 contains_exterior_struct_lit(&exprs[0])