1 #![recursion_limit = "256"]
4 use rustc_ast::util::parser::{self, AssocOp, Fixity};
5 use rustc_ast_pretty::pp::Breaks::{Consistent, Inconsistent};
6 use rustc_ast_pretty::pp::{self, Breaks};
7 use rustc_ast_pretty::pprust::{Comments, PrintState};
9 use rustc_hir::{GenericArg, GenericParam, GenericParamKind, Node, Term};
10 use rustc_hir::{GenericBound, PatKind, RangeEnd, TraitBoundModifier};
11 use rustc_span::source_map::SourceMap;
12 use rustc_span::symbol::{kw, Ident, IdentPrinter, Symbol};
13 use rustc_span::{self, FileName};
14 use rustc_target::spec::abi::Abi;
19 pub fn id_to_string(map: &dyn rustc_hir::intravisit::Map<'_>, hir_id: hir::HirId) -> String {
20 to_string(&map, |s| s.print_node(map.find(hir_id).unwrap()))
23 pub enum AnnNode<'a> {
25 Block(&'a hir::Block<'a>),
26 Item(&'a hir::Item<'a>),
28 Expr(&'a hir::Expr<'a>),
29 Pat(&'a hir::Pat<'a>),
30 Arm(&'a hir::Arm<'a>),
35 TraitItem(hir::TraitItemId),
36 ImplItem(hir::ImplItemId),
37 ForeignItem(hir::ForeignItemId),
39 BodyParamPat(hir::BodyId, usize),
43 fn nested(&self, _state: &mut State<'_>, _nested: Nested) {}
44 fn pre(&self, _state: &mut State<'_>, _node: AnnNode<'_>) {}
45 fn post(&self, _state: &mut State<'_>, _node: AnnNode<'_>) {}
49 impl PpAnn for NoAnn {}
50 pub const NO_ANN: &dyn PpAnn = &NoAnn;
52 /// Identical to the `PpAnn` implementation for `hir::Crate`,
53 /// except it avoids creating a dependency on the whole crate.
54 impl PpAnn for &dyn rustc_hir::intravisit::Map<'_> {
55 fn nested(&self, state: &mut State<'_>, nested: Nested) {
57 Nested::Item(id) => state.print_item(self.item(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 pub struct State<'a> {
69 comments: Option<Comments<'a>>,
70 attrs: &'a dyn Fn(hir::HirId) -> &'a [ast::Attribute],
71 ann: &'a (dyn PpAnn + 'a),
75 pub fn print_node(&mut self, node: Node<'_>) {
77 Node::Param(a) => self.print_param(&a),
78 Node::Item(a) => self.print_item(&a),
79 Node::ForeignItem(a) => self.print_foreign_item(&a),
80 Node::TraitItem(a) => self.print_trait_item(a),
81 Node::ImplItem(a) => self.print_impl_item(a),
82 Node::Variant(a) => self.print_variant(&a),
83 Node::AnonConst(a) => self.print_anon_const(&a),
84 Node::Expr(a) => self.print_expr(&a),
85 Node::Stmt(a) => self.print_stmt(&a),
86 Node::PathSegment(a) => self.print_path_segment(&a),
87 Node::Ty(a) => self.print_type(&a),
88 Node::TypeBinding(a) => self.print_type_binding(&a),
89 Node::TraitRef(a) => self.print_trait_ref(&a),
90 Node::Binding(a) | Node::Pat(a) => self.print_pat(&a),
91 Node::Arm(a) => self.print_arm(&a),
92 Node::Infer(_) => self.word("_"),
94 // Containing cbox, will be closed by print-block at `}`.
95 self.cbox(INDENT_UNIT);
96 // Head-ibox, will be closed by print-block after `{`.
100 Node::Lifetime(a) => self.print_lifetime(&a),
101 Node::GenericParam(_) => panic!("cannot print Node::GenericParam"),
102 Node::Field(_) => panic!("cannot print Node::Field"),
103 // These cases do not carry enough information in the
104 // `hir_map` to reconstruct their full structure for pretty
106 Node::Ctor(..) => panic!("cannot print isolated Ctor"),
107 Node::Local(a) => self.print_local_decl(&a),
108 Node::Crate(..) => panic!("cannot print Crate"),
113 impl std::ops::Deref for State<'_> {
114 type Target = pp::Printer;
115 fn deref(&self) -> &Self::Target {
120 impl std::ops::DerefMut for State<'_> {
121 fn deref_mut(&mut self) -> &mut Self::Target {
126 impl<'a> PrintState<'a> for State<'a> {
127 fn comments(&mut self) -> &mut Option<Comments<'a>> {
131 fn print_ident(&mut self, ident: Ident) {
132 self.word(IdentPrinter::for_ast_ident(ident, ident.is_raw_guess()).to_string());
133 self.ann.post(self, AnnNode::Name(&ident.name))
136 fn print_generic_args(&mut self, _: &ast::GenericArgs, _colons_before_params: bool) {
137 panic!("AST generic args printed by HIR pretty-printer");
141 pub const INDENT_UNIT: isize = 4;
143 /// Requires you to pass an input filename and reader so that
144 /// it can scan the input text for comments to copy forward.
145 pub fn print_crate<'a>(
147 krate: &hir::Mod<'_>,
150 attrs: &'a dyn Fn(hir::HirId) -> &'a [ast::Attribute],
153 let mut s = State::new_from_input(sm, filename, input, attrs, ann);
155 // When printing the AST, we sometimes need to inject `#[no_std]` here.
156 // Since you can't compile the HIR, it's not necessary.
158 s.print_mod(krate, (*attrs)(hir::CRATE_HIR_ID));
159 s.print_remaining_comments();
164 pub fn new_from_input(
168 attrs: &'a dyn Fn(hir::HirId) -> &'a [ast::Attribute],
172 s: pp::Printer::new(),
173 comments: Some(Comments::new(sm, filename, input)),
179 fn attrs(&self, id: hir::HirId) -> &'a [ast::Attribute] {
184 pub fn to_string<F>(ann: &dyn PpAnn, f: F) -> String
186 F: FnOnce(&mut State<'_>),
188 let mut printer = State { s: pp::Printer::new(), comments: None, attrs: &|_| &[], ann };
193 pub fn generic_params_to_string(generic_params: &[GenericParam<'_>]) -> String {
194 to_string(NO_ANN, |s| s.print_generic_params(generic_params))
197 pub fn bounds_to_string<'b>(bounds: impl IntoIterator<Item = &'b hir::GenericBound<'b>>) -> String {
198 to_string(NO_ANN, |s| s.print_bounds("", bounds))
201 pub fn ty_to_string(ty: &hir::Ty<'_>) -> String {
202 to_string(NO_ANN, |s| s.print_type(ty))
205 pub fn path_segment_to_string(segment: &hir::PathSegment<'_>) -> String {
206 to_string(NO_ANN, |s| s.print_path_segment(segment))
209 pub fn path_to_string(segment: &hir::Path<'_>) -> String {
210 to_string(NO_ANN, |s| s.print_path(segment, false))
214 decl: &hir::FnDecl<'_>,
215 header: hir::FnHeader,
216 name: Option<Symbol>,
217 generics: &hir::Generics<'_>,
219 body_id: Option<hir::BodyId>,
221 to_string(NO_ANN, |s| s.print_fn(decl, header, name, generics, arg_names, body_id))
224 pub fn enum_def_to_string(
225 enum_definition: &hir::EnumDef<'_>,
226 generics: &hir::Generics<'_>,
228 span: rustc_span::Span,
230 to_string(NO_ANN, |s| s.print_enum_def(enum_definition, generics, name, span))
234 pub fn bclose_maybe_open(&mut self, span: rustc_span::Span, close_box: bool) {
235 self.maybe_print_comment(span.hi());
236 self.break_offset_if_not_bol(1, -(INDENT_UNIT as isize));
239 self.end(); // close the outer-box
243 pub fn bclose(&mut self, span: rustc_span::Span) {
244 self.bclose_maybe_open(span, true)
247 pub fn commasep_cmnt<T, F, G>(&mut self, b: Breaks, elts: &[T], mut op: F, mut get_span: G)
249 F: FnMut(&mut State<'_>, &T),
250 G: FnMut(&T) -> rustc_span::Span,
253 let len = elts.len();
256 self.maybe_print_comment(get_span(elt).hi());
261 self.maybe_print_trailing_comment(get_span(elt), Some(get_span(&elts[i]).hi()));
262 self.space_if_not_bol();
268 pub fn commasep_exprs(&mut self, b: Breaks, exprs: &[hir::Expr<'_>]) {
269 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(&e), |e| e.span)
272 pub fn print_mod(&mut self, _mod: &hir::Mod<'_>, attrs: &[ast::Attribute]) {
273 self.print_inner_attributes(attrs);
274 for &item_id in _mod.item_ids {
275 self.ann.nested(self, Nested::Item(item_id));
279 pub fn print_opt_lifetime(&mut self, lifetime: &hir::Lifetime) {
280 if !lifetime.is_elided() {
281 self.print_lifetime(lifetime);
286 pub fn print_type(&mut self, ty: &hir::Ty<'_>) {
287 self.maybe_print_comment(ty.span.lo());
290 hir::TyKind::Slice(ref ty) => {
292 self.print_type(&ty);
295 hir::TyKind::Ptr(ref mt) => {
297 self.print_mt(mt, true);
299 hir::TyKind::Rptr(ref lifetime, ref mt) => {
301 self.print_opt_lifetime(lifetime);
302 self.print_mt(mt, false);
304 hir::TyKind::Never => {
307 hir::TyKind::Tup(ref elts) => {
309 self.commasep(Inconsistent, &elts, |s, ty| s.print_type(&ty));
315 hir::TyKind::BareFn(ref f) => {
325 hir::TyKind::OpaqueDef(..) => self.word("/*impl Trait*/"),
326 hir::TyKind::Path(ref qpath) => self.print_qpath(qpath, false),
327 hir::TyKind::TraitObject(bounds, ref lifetime, syntax) => {
328 if syntax == ast::TraitObjectSyntax::Dyn {
329 self.word_space("dyn");
331 let mut first = true;
332 for bound in bounds {
337 self.word_space("+");
339 self.print_poly_trait_ref(bound);
341 if !lifetime.is_elided() {
343 self.word_space("+");
344 self.print_lifetime(lifetime);
347 hir::TyKind::Array(ref ty, ref length) => {
349 self.print_type(&ty);
351 self.print_array_length(length);
354 hir::TyKind::Typeof(ref e) => {
355 self.word("typeof(");
356 self.print_anon_const(e);
359 hir::TyKind::Err => {
361 self.word("/*ERROR*/");
364 hir::TyKind::Infer => {
371 pub fn print_foreign_item(&mut self, item: &hir::ForeignItem<'_>) {
372 self.hardbreak_if_not_bol();
373 self.maybe_print_comment(item.span.lo());
374 self.print_outer_attributes(self.attrs(item.hir_id()));
376 hir::ForeignItemKind::Fn(ref decl, ref arg_names, ref generics) => {
381 unsafety: hir::Unsafety::Normal,
382 constness: hir::Constness::NotConst,
384 asyncness: hir::IsAsync::NotAsync,
386 Some(item.ident.name),
391 self.end(); // end head-ibox
393 self.end() // end the outer fn box
395 hir::ForeignItemKind::Static(ref t, m) => {
397 if m == hir::Mutability::Mut {
398 self.word_space("mut");
400 self.print_ident(item.ident);
401 self.word_space(":");
404 self.end(); // end the head-ibox
405 self.end() // end the outer cbox
407 hir::ForeignItemKind::Type => {
409 self.print_ident(item.ident);
411 self.end(); // end the head-ibox
412 self.end() // end the outer cbox
417 fn print_associated_const(
421 default: Option<hir::BodyId>,
424 self.word_space("const");
425 self.print_ident(ident);
426 self.word_space(":");
428 if let Some(expr) = default {
430 self.word_space("=");
431 self.ann.nested(self, Nested::Body(expr));
436 fn print_associated_type(
439 generics: &hir::Generics<'_>,
440 bounds: Option<hir::GenericBounds<'_>>,
441 ty: Option<&hir::Ty<'_>>,
443 self.word_space("type");
444 self.print_ident(ident);
445 self.print_generic_params(&generics.params);
446 if let Some(bounds) = bounds {
447 self.print_bounds(":", bounds);
449 self.print_where_clause(generics);
450 if let Some(ty) = ty {
452 self.word_space("=");
460 item: &hir::Item<'_>,
461 generics: &hir::Generics<'_>,
462 inner: impl Fn(&mut Self),
465 self.print_ident(item.ident);
466 self.print_generic_params(&generics.params);
467 self.end(); // end the inner ibox
469 self.print_where_clause(generics);
473 self.end(); // end the outer ibox
476 /// Pretty-print an item
477 pub fn print_item(&mut self, item: &hir::Item<'_>) {
478 self.hardbreak_if_not_bol();
479 self.maybe_print_comment(item.span.lo());
480 let attrs = self.attrs(item.hir_id());
481 self.print_outer_attributes(attrs);
482 self.ann.pre(self, AnnNode::Item(item));
484 hir::ItemKind::ExternCrate(orig_name) => {
485 self.head("extern crate");
486 if let Some(orig_name) = orig_name {
487 self.print_name(orig_name);
492 self.print_ident(item.ident);
494 self.end(); // end inner head-block
495 self.end(); // end outer head-block
497 hir::ItemKind::Use(ref path, kind) => {
499 self.print_path(path, false);
502 hir::UseKind::Single => {
503 if path.segments.last().unwrap().ident != item.ident {
505 self.word_space("as");
506 self.print_ident(item.ident);
510 hir::UseKind::Glob => self.word("::*;"),
511 hir::UseKind::ListStem => self.word("::{};"),
513 self.end(); // end inner head-block
514 self.end(); // end outer head-block
516 hir::ItemKind::Static(ref ty, m, expr) => {
518 if m == hir::Mutability::Mut {
519 self.word_space("mut");
521 self.print_ident(item.ident);
522 self.word_space(":");
523 self.print_type(&ty);
525 self.end(); // end the head-ibox
527 self.word_space("=");
528 self.ann.nested(self, Nested::Body(expr));
530 self.end(); // end the outer cbox
532 hir::ItemKind::Const(ref ty, expr) => {
534 self.print_ident(item.ident);
535 self.word_space(":");
536 self.print_type(&ty);
538 self.end(); // end the head-ibox
540 self.word_space("=");
541 self.ann.nested(self, Nested::Body(expr));
543 self.end(); // end the outer cbox
545 hir::ItemKind::Fn(ref sig, ref param_names, body) => {
550 Some(item.ident.name),
556 self.end(); // need to close a box
557 self.end(); // need to close a box
558 self.ann.nested(self, Nested::Body(body));
560 hir::ItemKind::Macro(ref macro_def, _) => {
561 self.print_mac_def(macro_def, &item.ident, item.span, |_| {});
563 hir::ItemKind::Mod(ref _mod) => {
565 self.print_ident(item.ident);
568 self.print_mod(_mod, attrs);
569 self.bclose(item.span);
571 hir::ItemKind::ForeignMod { abi, items } => {
573 self.word_nbsp(abi.to_string());
575 self.print_inner_attributes(self.attrs(item.hir_id()));
577 self.ann.nested(self, Nested::ForeignItem(item.id));
579 self.bclose(item.span);
581 hir::ItemKind::GlobalAsm(ref asm) => {
582 self.head("global_asm!");
583 self.print_inline_asm(asm);
586 hir::ItemKind::TyAlias(ref ty, ref generics) => {
587 self.print_item_type(item, &generics, |state| {
588 state.word_space("=");
589 state.print_type(&ty);
592 hir::ItemKind::OpaqueTy(ref opaque_ty) => {
593 self.print_item_type(item, &opaque_ty.generics, |state| {
594 let mut real_bounds = Vec::with_capacity(opaque_ty.bounds.len());
595 for b in opaque_ty.bounds.iter() {
596 if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
598 state.word_space("for ?");
599 state.print_trait_ref(&ptr.trait_ref);
604 state.print_bounds("= impl", real_bounds);
607 hir::ItemKind::Enum(ref enum_definition, ref params) => {
608 self.print_enum_def(enum_definition, params, item.ident.name, item.span);
610 hir::ItemKind::Struct(ref struct_def, ref generics) => {
612 self.print_struct(struct_def, generics, item.ident.name, item.span, true);
614 hir::ItemKind::Union(ref struct_def, ref generics) => {
616 self.print_struct(struct_def, generics, item.ident.name, item.span, true);
618 hir::ItemKind::Impl(hir::Impl {
630 self.print_defaultness(*defaultness);
631 self.print_unsafety(*unsafety);
632 self.word_nbsp("impl");
634 if !generics.params.is_empty() {
635 self.print_generic_params(&generics.params);
639 if *constness == hir::Constness::Const {
640 self.word_nbsp("const");
643 if let hir::ImplPolarity::Negative(_) = polarity {
647 if let Some(ref t) = of_trait {
648 self.print_trait_ref(t);
650 self.word_space("for");
653 self.print_type(&self_ty);
654 self.print_where_clause(generics);
658 self.print_inner_attributes(attrs);
659 for impl_item in *items {
660 self.ann.nested(self, Nested::ImplItem(impl_item.id));
662 self.bclose(item.span);
664 hir::ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, trait_items) => {
666 self.print_is_auto(is_auto);
667 self.print_unsafety(unsafety);
668 self.word_nbsp("trait");
669 self.print_ident(item.ident);
670 self.print_generic_params(&generics.params);
671 let mut real_bounds = Vec::with_capacity(bounds.len());
672 for b in bounds.iter() {
673 if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
675 self.word_space("for ?");
676 self.print_trait_ref(&ptr.trait_ref);
681 self.print_bounds(":", real_bounds);
682 self.print_where_clause(generics);
685 for trait_item in trait_items {
686 self.ann.nested(self, Nested::TraitItem(trait_item.id));
688 self.bclose(item.span);
690 hir::ItemKind::TraitAlias(ref generics, ref bounds) => {
692 self.print_ident(item.ident);
693 self.print_generic_params(&generics.params);
694 let mut real_bounds = Vec::with_capacity(bounds.len());
695 // FIXME(durka) this seems to be some quite outdated syntax
696 for b in bounds.iter() {
697 if let GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = *b {
699 self.word_space("for ?");
700 self.print_trait_ref(&ptr.trait_ref);
706 self.print_bounds("=", real_bounds);
707 self.print_where_clause(generics);
709 self.end(); // end inner head-block
710 self.end(); // end outer head-block
713 self.ann.post(self, AnnNode::Item(item))
716 pub fn print_trait_ref(&mut self, t: &hir::TraitRef<'_>) {
717 self.print_path(&t.path, false)
720 fn print_formal_generic_params(&mut self, generic_params: &[hir::GenericParam<'_>]) {
721 if !generic_params.is_empty() {
723 self.print_generic_params(generic_params);
728 fn print_poly_trait_ref(&mut self, t: &hir::PolyTraitRef<'_>) {
729 self.print_formal_generic_params(&t.bound_generic_params);
730 self.print_trait_ref(&t.trait_ref)
733 pub fn print_enum_def(
735 enum_definition: &hir::EnumDef<'_>,
736 generics: &hir::Generics<'_>,
738 span: rustc_span::Span,
741 self.print_name(name);
742 self.print_generic_params(&generics.params);
743 self.print_where_clause(generics);
745 self.print_variants(&enum_definition.variants, span)
748 pub fn print_variants(&mut self, variants: &[hir::Variant<'_>], span: rustc_span::Span) {
751 self.space_if_not_bol();
752 self.maybe_print_comment(v.span.lo());
753 self.print_outer_attributes(self.attrs(v.id));
754 self.ibox(INDENT_UNIT);
755 self.print_variant(v);
758 self.maybe_print_trailing_comment(v.span, None);
763 pub fn print_defaultness(&mut self, defaultness: hir::Defaultness) {
765 hir::Defaultness::Default { .. } => self.word_nbsp("default"),
766 hir::Defaultness::Final => (),
772 struct_def: &hir::VariantData<'_>,
773 generics: &hir::Generics<'_>,
775 span: rustc_span::Span,
776 print_finalizer: bool,
778 self.print_name(name);
779 self.print_generic_params(&generics.params);
781 hir::VariantData::Tuple(..) | hir::VariantData::Unit(..) => {
782 if let hir::VariantData::Tuple(..) = struct_def {
784 self.commasep(Inconsistent, struct_def.fields(), |s, field| {
785 s.maybe_print_comment(field.span.lo());
786 s.print_outer_attributes(s.attrs(field.hir_id));
787 s.print_type(&field.ty)
791 self.print_where_clause(generics);
796 self.end() // close the outer-box
798 hir::VariantData::Struct(..) => {
799 self.print_where_clause(generics);
802 self.hardbreak_if_not_bol();
804 for field in struct_def.fields() {
805 self.hardbreak_if_not_bol();
806 self.maybe_print_comment(field.span.lo());
807 self.print_outer_attributes(self.attrs(field.hir_id));
808 self.print_ident(field.ident);
810 self.print_type(&field.ty);
819 pub fn print_variant(&mut self, v: &hir::Variant<'_>) {
821 let generics = hir::Generics::empty();
822 self.print_struct(&v.data, &generics, v.ident.name, v.span, false);
823 if let Some(ref d) = v.disr_expr {
825 self.word_space("=");
826 self.print_anon_const(d);
829 pub fn print_method_sig(
833 generics: &hir::Generics<'_>,
835 body_id: Option<hir::BodyId>,
837 self.print_fn(&m.decl, m.header, Some(ident.name), generics, arg_names, body_id)
840 pub fn print_trait_item(&mut self, ti: &hir::TraitItem<'_>) {
841 self.ann.pre(self, AnnNode::SubItem(ti.hir_id()));
842 self.hardbreak_if_not_bol();
843 self.maybe_print_comment(ti.span.lo());
844 self.print_outer_attributes(self.attrs(ti.hir_id()));
846 hir::TraitItemKind::Const(ref ty, default) => {
847 self.print_associated_const(ti.ident, &ty, default);
849 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Required(ref arg_names)) => {
850 self.print_method_sig(ti.ident, sig, &ti.generics, arg_names, None);
853 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Provided(body)) => {
855 self.print_method_sig(ti.ident, sig, &ti.generics, &[], Some(body));
857 self.end(); // need to close a box
858 self.end(); // need to close a box
859 self.ann.nested(self, Nested::Body(body));
861 hir::TraitItemKind::Type(ref bounds, ref default) => {
862 self.print_associated_type(
866 default.as_ref().map(|ty| &**ty),
870 self.ann.post(self, AnnNode::SubItem(ti.hir_id()))
873 pub fn print_impl_item(&mut self, ii: &hir::ImplItem<'_>) {
874 self.ann.pre(self, AnnNode::SubItem(ii.hir_id()));
875 self.hardbreak_if_not_bol();
876 self.maybe_print_comment(ii.span.lo());
877 self.print_outer_attributes(self.attrs(ii.hir_id()));
880 hir::ImplItemKind::Const(ref ty, expr) => {
881 self.print_associated_const(ii.ident, &ty, Some(expr));
883 hir::ImplItemKind::Fn(ref sig, body) => {
885 self.print_method_sig(ii.ident, sig, &ii.generics, &[], Some(body));
887 self.end(); // need to close a box
888 self.end(); // need to close a box
889 self.ann.nested(self, Nested::Body(body));
891 hir::ImplItemKind::TyAlias(ref ty) => {
892 self.print_associated_type(ii.ident, &ii.generics, None, Some(ty));
895 self.ann.post(self, AnnNode::SubItem(ii.hir_id()))
898 pub fn print_local(&mut self, init: Option<&hir::Expr<'_>>, decl: impl Fn(&mut Self)) {
899 self.space_if_not_bol();
900 self.ibox(INDENT_UNIT);
901 self.word_nbsp("let");
903 self.ibox(INDENT_UNIT);
907 if let Some(ref init) = init {
909 self.word_space("=");
910 self.print_expr(&init);
915 pub fn print_stmt(&mut self, st: &hir::Stmt<'_>) {
916 self.maybe_print_comment(st.span.lo());
918 hir::StmtKind::Local(ref loc) => {
919 self.print_local(loc.init, |this| this.print_local_decl(&loc));
921 hir::StmtKind::Item(item) => self.ann.nested(self, Nested::Item(item)),
922 hir::StmtKind::Expr(ref expr) => {
923 self.space_if_not_bol();
924 self.print_expr(&expr);
926 hir::StmtKind::Semi(ref expr) => {
927 self.space_if_not_bol();
928 self.print_expr(&expr);
932 if stmt_ends_with_semi(&st.kind) {
935 self.maybe_print_trailing_comment(st.span, None)
938 pub fn print_block(&mut self, blk: &hir::Block<'_>) {
939 self.print_block_with_attrs(blk, &[])
942 pub fn print_block_unclosed(&mut self, blk: &hir::Block<'_>) {
943 self.print_block_maybe_unclosed(blk, &[], false)
946 pub fn print_block_with_attrs(&mut self, blk: &hir::Block<'_>, attrs: &[ast::Attribute]) {
947 self.print_block_maybe_unclosed(blk, attrs, true)
950 pub fn print_block_maybe_unclosed(
952 blk: &hir::Block<'_>,
953 attrs: &[ast::Attribute],
957 hir::BlockCheckMode::UnsafeBlock(..) => self.word_space("unsafe"),
958 hir::BlockCheckMode::DefaultBlock => (),
960 self.maybe_print_comment(blk.span.lo());
961 self.ann.pre(self, AnnNode::Block(blk));
964 self.print_inner_attributes(attrs);
966 for st in blk.stmts {
969 if let Some(ref expr) = blk.expr {
970 self.space_if_not_bol();
971 self.print_expr(&expr);
972 self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi()));
974 self.bclose_maybe_open(blk.span, close_box);
975 self.ann.post(self, AnnNode::Block(blk))
978 fn print_else(&mut self, els: Option<&hir::Expr<'_>>) {
979 if let Some(els_inner) = els {
980 match els_inner.kind {
981 // Another `else if` block.
982 hir::ExprKind::If(ref i, ref then, ref e) => {
983 self.cbox(INDENT_UNIT - 1);
985 self.word(" else if ");
986 self.print_expr_as_cond(&i);
988 self.print_expr(&then);
989 self.print_else(e.as_ref().map(|e| &**e))
991 // Final `else` block.
992 hir::ExprKind::Block(ref b, _) => {
993 self.cbox(INDENT_UNIT - 1);
998 // Constraints would be great here!
1000 panic!("print_if saw if with weird alternative");
1008 test: &hir::Expr<'_>,
1009 blk: &hir::Expr<'_>,
1010 elseopt: Option<&hir::Expr<'_>>,
1013 self.print_expr_as_cond(test);
1015 self.print_expr(blk);
1016 self.print_else(elseopt)
1019 pub fn print_array_length(&mut self, len: &hir::ArrayLen) {
1021 hir::ArrayLen::Infer(_, _) => self.word("_"),
1022 hir::ArrayLen::Body(ct) => self.print_anon_const(ct),
1026 pub fn print_anon_const(&mut self, constant: &hir::AnonConst) {
1027 self.ann.nested(self, Nested::Body(constant.body))
1030 fn print_call_post(&mut self, args: &[hir::Expr<'_>]) {
1032 self.commasep_exprs(Inconsistent, args);
1036 fn print_expr_maybe_paren(&mut self, expr: &hir::Expr<'_>, prec: i8) {
1037 self.print_expr_cond_paren(expr, expr.precedence().order() < prec)
1040 /// Prints an expr using syntax that's acceptable in a condition position, such as the `cond` in
1041 /// `if cond { ... }`.
1042 pub fn print_expr_as_cond(&mut self, expr: &hir::Expr<'_>) {
1043 self.print_expr_cond_paren(expr, Self::cond_needs_par(expr))
1046 /// Prints `expr` or `(expr)` when `needs_par` holds.
1047 fn print_expr_cond_paren(&mut self, expr: &hir::Expr<'_>, needs_par: bool) {
1051 if let hir::ExprKind::DropTemps(ref actual_expr) = expr.kind {
1052 self.print_expr(actual_expr);
1054 self.print_expr(expr);
1061 /// Print a `let pat = expr` expression.
1062 fn print_let(&mut self, pat: &hir::Pat<'_>, ty: Option<&hir::Ty<'_>>, init: &hir::Expr<'_>) {
1063 self.word_space("let");
1064 self.print_pat(pat);
1065 if let Some(ty) = ty {
1066 self.word_space(":");
1067 self.print_type(ty);
1070 self.word_space("=");
1071 let npals = || parser::needs_par_as_let_scrutinee(init.precedence().order());
1072 self.print_expr_cond_paren(init, Self::cond_needs_par(init) || npals())
1075 // Does `expr` need parentheses when printed in a condition position?
1077 // These cases need parens due to the parse error observed in #26461: `if return {}`
1078 // parses as the erroneous construct `if (return {})`, not `if (return) {}`.
1079 fn cond_needs_par(expr: &hir::Expr<'_>) -> bool {
1081 hir::ExprKind::Break(..) | hir::ExprKind::Closure { .. } | hir::ExprKind::Ret(..) => {
1084 _ => contains_exterior_struct_lit(expr),
1088 fn print_expr_vec(&mut self, exprs: &[hir::Expr<'_>]) {
1089 self.ibox(INDENT_UNIT);
1091 self.commasep_exprs(Inconsistent, exprs);
1096 fn print_expr_anon_const(&mut self, anon_const: &hir::AnonConst) {
1097 self.ibox(INDENT_UNIT);
1098 self.word_space("const");
1099 self.print_anon_const(anon_const);
1103 fn print_expr_repeat(&mut self, element: &hir::Expr<'_>, count: &hir::ArrayLen) {
1104 self.ibox(INDENT_UNIT);
1106 self.print_expr(element);
1107 self.word_space(";");
1108 self.print_array_length(count);
1113 fn print_expr_struct(
1115 qpath: &hir::QPath<'_>,
1116 fields: &[hir::ExprField<'_>],
1117 wth: &Option<&hir::Expr<'_>>,
1119 self.print_qpath(qpath, true);
1125 s.ibox(INDENT_UNIT);
1126 if !field.is_shorthand {
1127 s.print_ident(field.ident);
1130 s.print_expr(&field.expr);
1137 self.ibox(INDENT_UNIT);
1138 if !fields.is_empty() {
1143 self.print_expr(&expr);
1147 if !fields.is_empty() {
1155 fn print_expr_tup(&mut self, exprs: &[hir::Expr<'_>]) {
1157 self.commasep_exprs(Inconsistent, exprs);
1158 if exprs.len() == 1 {
1164 fn print_expr_call(&mut self, func: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
1165 let prec = match func.kind {
1166 hir::ExprKind::Field(..) => parser::PREC_FORCE_PAREN,
1167 _ => parser::PREC_POSTFIX,
1170 self.print_expr_maybe_paren(func, prec);
1171 self.print_call_post(args)
1174 fn print_expr_method_call(&mut self, segment: &hir::PathSegment<'_>, args: &[hir::Expr<'_>]) {
1175 let base_args = &args[1..];
1176 self.print_expr_maybe_paren(&args[0], parser::PREC_POSTFIX);
1178 self.print_ident(segment.ident);
1180 let generic_args = segment.args();
1181 if !generic_args.args.is_empty() || !generic_args.bindings.is_empty() {
1182 self.print_generic_args(generic_args, segment.infer_args, true);
1185 self.print_call_post(base_args)
1188 fn print_expr_binary(&mut self, op: hir::BinOp, lhs: &hir::Expr<'_>, rhs: &hir::Expr<'_>) {
1189 let assoc_op = bin_op_to_assoc_op(op.node);
1190 let prec = assoc_op.precedence() as i8;
1191 let fixity = assoc_op.fixity();
1193 let (left_prec, right_prec) = match fixity {
1194 Fixity::Left => (prec, prec + 1),
1195 Fixity::Right => (prec + 1, prec),
1196 Fixity::None => (prec + 1, prec + 1),
1199 let left_prec = match (&lhs.kind, op.node) {
1200 // These cases need parens: `x as i32 < y` has the parser thinking that `i32 < y` is
1201 // the beginning of a path type. It starts trying to parse `x as (i32 < y ...` instead
1202 // of `(x as i32) < ...`. We need to convince it _not_ to do that.
1203 (&hir::ExprKind::Cast { .. }, hir::BinOpKind::Lt | hir::BinOpKind::Shl) => {
1204 parser::PREC_FORCE_PAREN
1206 (&hir::ExprKind::Let { .. }, _) if !parser::needs_par_as_let_scrutinee(prec) => {
1207 parser::PREC_FORCE_PAREN
1212 self.print_expr_maybe_paren(lhs, left_prec);
1214 self.word_space(op.node.as_str());
1215 self.print_expr_maybe_paren(rhs, right_prec)
1218 fn print_expr_unary(&mut self, op: hir::UnOp, expr: &hir::Expr<'_>) {
1219 self.word(op.as_str());
1220 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1223 fn print_expr_addr_of(
1225 kind: hir::BorrowKind,
1226 mutability: hir::Mutability,
1227 expr: &hir::Expr<'_>,
1231 hir::BorrowKind::Ref => self.print_mutability(mutability, false),
1232 hir::BorrowKind::Raw => {
1233 self.word_nbsp("raw");
1234 self.print_mutability(mutability, true);
1237 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1240 fn print_literal(&mut self, lit: &hir::Lit) {
1241 self.maybe_print_comment(lit.span.lo());
1242 self.word(lit.node.to_lit_token().to_string())
1245 fn print_inline_asm(&mut self, asm: &hir::InlineAsm<'_>) {
1248 Operand(&'a hir::InlineAsmOperand<'a>),
1249 Options(ast::InlineAsmOptions),
1253 vec![AsmArg::Template(ast::InlineAsmTemplatePiece::to_string(&asm.template))];
1254 args.extend(asm.operands.iter().map(|(o, _)| AsmArg::Operand(o)));
1255 if !asm.options.is_empty() {
1256 args.push(AsmArg::Options(asm.options));
1260 self.commasep(Consistent, &args, |s, arg| match arg {
1261 AsmArg::Template(template) => s.print_string(&template, ast::StrStyle::Cooked),
1262 AsmArg::Operand(op) => match op {
1263 hir::InlineAsmOperand::In { reg, expr } => {
1266 s.word(format!("{}", reg));
1271 hir::InlineAsmOperand::Out { reg, late, expr } => {
1272 s.word(if *late { "lateout" } else { "out" });
1274 s.word(format!("{}", reg));
1278 Some(expr) => s.print_expr(expr),
1279 None => s.word("_"),
1282 hir::InlineAsmOperand::InOut { reg, late, expr } => {
1283 s.word(if *late { "inlateout" } else { "inout" });
1285 s.word(format!("{}", reg));
1290 hir::InlineAsmOperand::SplitInOut { reg, late, in_expr, out_expr } => {
1291 s.word(if *late { "inlateout" } else { "inout" });
1293 s.word(format!("{}", reg));
1296 s.print_expr(in_expr);
1300 Some(out_expr) => s.print_expr(out_expr),
1301 None => s.word("_"),
1304 hir::InlineAsmOperand::Const { anon_const } => {
1307 s.print_anon_const(anon_const);
1309 hir::InlineAsmOperand::SymFn { anon_const } => {
1312 s.print_anon_const(anon_const);
1314 hir::InlineAsmOperand::SymStatic { path, def_id: _ } => {
1315 s.word("sym_static");
1317 s.print_qpath(path, true);
1320 AsmArg::Options(opts) => {
1323 let mut options = vec![];
1324 if opts.contains(ast::InlineAsmOptions::PURE) {
1325 options.push("pure");
1327 if opts.contains(ast::InlineAsmOptions::NOMEM) {
1328 options.push("nomem");
1330 if opts.contains(ast::InlineAsmOptions::READONLY) {
1331 options.push("readonly");
1333 if opts.contains(ast::InlineAsmOptions::PRESERVES_FLAGS) {
1334 options.push("preserves_flags");
1336 if opts.contains(ast::InlineAsmOptions::NORETURN) {
1337 options.push("noreturn");
1339 if opts.contains(ast::InlineAsmOptions::NOSTACK) {
1340 options.push("nostack");
1342 if opts.contains(ast::InlineAsmOptions::ATT_SYNTAX) {
1343 options.push("att_syntax");
1345 if opts.contains(ast::InlineAsmOptions::RAW) {
1346 options.push("raw");
1348 if opts.contains(ast::InlineAsmOptions::MAY_UNWIND) {
1349 options.push("may_unwind");
1351 s.commasep(Inconsistent, &options, |s, &opt| {
1360 pub fn print_expr(&mut self, expr: &hir::Expr<'_>) {
1361 self.maybe_print_comment(expr.span.lo());
1362 self.print_outer_attributes(self.attrs(expr.hir_id));
1363 self.ibox(INDENT_UNIT);
1364 self.ann.pre(self, AnnNode::Expr(expr));
1366 hir::ExprKind::Box(ref expr) => {
1367 self.word_space("box");
1368 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX);
1370 hir::ExprKind::Array(ref exprs) => {
1371 self.print_expr_vec(exprs);
1373 hir::ExprKind::ConstBlock(ref anon_const) => {
1374 self.print_expr_anon_const(anon_const);
1376 hir::ExprKind::Repeat(ref element, ref count) => {
1377 self.print_expr_repeat(&element, count);
1379 hir::ExprKind::Struct(ref qpath, fields, ref wth) => {
1380 self.print_expr_struct(qpath, fields, wth);
1382 hir::ExprKind::Tup(ref exprs) => {
1383 self.print_expr_tup(exprs);
1385 hir::ExprKind::Call(ref func, ref args) => {
1386 self.print_expr_call(&func, args);
1388 hir::ExprKind::MethodCall(ref segment, ref args, _) => {
1389 self.print_expr_method_call(segment, args);
1391 hir::ExprKind::Binary(op, ref lhs, ref rhs) => {
1392 self.print_expr_binary(op, &lhs, &rhs);
1394 hir::ExprKind::Unary(op, ref expr) => {
1395 self.print_expr_unary(op, &expr);
1397 hir::ExprKind::AddrOf(k, m, ref expr) => {
1398 self.print_expr_addr_of(k, m, &expr);
1400 hir::ExprKind::Lit(ref lit) => {
1401 self.print_literal(&lit);
1403 hir::ExprKind::Cast(ref expr, ref ty) => {
1404 let prec = AssocOp::As.precedence() as i8;
1405 self.print_expr_maybe_paren(&expr, prec);
1407 self.word_space("as");
1408 self.print_type(&ty);
1410 hir::ExprKind::Type(ref expr, ref ty) => {
1411 let prec = AssocOp::Colon.precedence() as i8;
1412 self.print_expr_maybe_paren(&expr, prec);
1413 self.word_space(":");
1414 self.print_type(&ty);
1416 hir::ExprKind::DropTemps(ref init) => {
1418 self.cbox(INDENT_UNIT);
1422 // Print `let _t = $init;`:
1423 let temp = Ident::from_str("_t");
1424 self.print_local(Some(init), |this| this.print_ident(temp));
1428 self.space_if_not_bol();
1429 self.print_ident(temp);
1432 self.bclose_maybe_open(expr.span, true);
1434 hir::ExprKind::Let(hir::Let { pat, ty, init, .. }) => {
1435 self.print_let(pat, *ty, init);
1437 hir::ExprKind::If(ref test, ref blk, ref elseopt) => {
1438 self.print_if(&test, &blk, elseopt.as_ref().map(|e| &**e));
1440 hir::ExprKind::Loop(ref blk, opt_label, _, _) => {
1441 if let Some(label) = opt_label {
1442 self.print_ident(label.ident);
1443 self.word_space(":");
1446 self.print_block(&blk);
1448 hir::ExprKind::Match(ref expr, arms, _) => {
1449 self.cbox(INDENT_UNIT);
1450 self.ibox(INDENT_UNIT);
1451 self.word_nbsp("match");
1452 self.print_expr_as_cond(&expr);
1456 self.print_arm(arm);
1458 self.bclose(expr.span);
1460 hir::ExprKind::Closure {
1467 self.print_capture_clause(capture_clause);
1469 self.print_closure_params(&fn_decl, body);
1472 // This is a bare expression.
1473 self.ann.nested(self, Nested::Body(body));
1474 self.end(); // need to close a box
1476 // A box will be closed by `print_expr`, but we didn't want an overall
1477 // wrapper so we closed the corresponding opening. so create an
1478 // empty box to satisfy the close.
1481 hir::ExprKind::Block(ref blk, opt_label) => {
1482 if let Some(label) = opt_label {
1483 self.print_ident(label.ident);
1484 self.word_space(":");
1486 // containing cbox, will be closed by print-block at `}`
1487 self.cbox(INDENT_UNIT);
1488 // head-box, will be closed by print-block after `{`
1490 self.print_block(&blk);
1492 hir::ExprKind::Assign(ref lhs, ref rhs, _) => {
1493 let prec = AssocOp::Assign.precedence() as i8;
1494 self.print_expr_maybe_paren(&lhs, prec + 1);
1496 self.word_space("=");
1497 self.print_expr_maybe_paren(&rhs, prec);
1499 hir::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
1500 let prec = AssocOp::Assign.precedence() as i8;
1501 self.print_expr_maybe_paren(&lhs, prec + 1);
1503 self.word(op.node.as_str());
1504 self.word_space("=");
1505 self.print_expr_maybe_paren(&rhs, prec);
1507 hir::ExprKind::Field(ref expr, ident) => {
1508 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
1510 self.print_ident(ident);
1512 hir::ExprKind::Index(ref expr, ref index) => {
1513 self.print_expr_maybe_paren(&expr, parser::PREC_POSTFIX);
1515 self.print_expr(&index);
1518 hir::ExprKind::Path(ref qpath) => self.print_qpath(qpath, true),
1519 hir::ExprKind::Break(destination, ref opt_expr) => {
1521 if let Some(label) = destination.label {
1523 self.print_ident(label.ident);
1525 if let Some(ref expr) = *opt_expr {
1527 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
1530 hir::ExprKind::Continue(destination) => {
1531 self.word("continue");
1532 if let Some(label) = destination.label {
1534 self.print_ident(label.ident);
1537 hir::ExprKind::Ret(ref result) => {
1538 self.word("return");
1539 if let Some(ref expr) = *result {
1541 self.print_expr_maybe_paren(&expr, parser::PREC_JUMP);
1544 hir::ExprKind::InlineAsm(ref asm) => {
1546 self.print_inline_asm(asm);
1548 hir::ExprKind::Yield(ref expr, _) => {
1549 self.word_space("yield");
1550 self.print_expr_maybe_paren(&expr, parser::PREC_JUMP);
1552 hir::ExprKind::Err => {
1554 self.word("/*ERROR*/");
1558 self.ann.post(self, AnnNode::Expr(expr));
1562 pub fn print_local_decl(&mut self, loc: &hir::Local<'_>) {
1563 self.print_pat(&loc.pat);
1564 if let Some(ref ty) = loc.ty {
1565 self.word_space(":");
1566 self.print_type(&ty);
1570 pub fn print_name(&mut self, name: Symbol) {
1571 self.print_ident(Ident::with_dummy_span(name))
1574 pub fn print_path(&mut self, path: &hir::Path<'_>, colons_before_params: bool) {
1575 self.maybe_print_comment(path.span.lo());
1577 for (i, segment) in path.segments.iter().enumerate() {
1581 if segment.ident.name != kw::PathRoot {
1582 self.print_ident(segment.ident);
1583 self.print_generic_args(segment.args(), segment.infer_args, colons_before_params);
1588 pub fn print_path_segment(&mut self, segment: &hir::PathSegment<'_>) {
1589 if segment.ident.name != kw::PathRoot {
1590 self.print_ident(segment.ident);
1591 self.print_generic_args(segment.args(), segment.infer_args, false);
1595 pub fn print_qpath(&mut self, qpath: &hir::QPath<'_>, colons_before_params: bool) {
1597 hir::QPath::Resolved(None, ref path) => self.print_path(path, colons_before_params),
1598 hir::QPath::Resolved(Some(ref qself), ref path) => {
1600 self.print_type(qself);
1602 self.word_space("as");
1604 for (i, segment) in path.segments[..path.segments.len() - 1].iter().enumerate() {
1608 if segment.ident.name != kw::PathRoot {
1609 self.print_ident(segment.ident);
1610 self.print_generic_args(
1613 colons_before_params,
1620 let item_segment = path.segments.last().unwrap();
1621 self.print_ident(item_segment.ident);
1622 self.print_generic_args(
1623 item_segment.args(),
1624 item_segment.infer_args,
1625 colons_before_params,
1628 hir::QPath::TypeRelative(ref qself, ref item_segment) => {
1629 // If we've got a compound-qualified-path, let's push an additional pair of angle
1630 // brackets, so that we pretty-print `<<A::B>::C>` as `<A::B>::C`, instead of just
1631 // `A::B::C` (since the latter could be ambiguous to the user)
1632 if let hir::TyKind::Path(hir::QPath::Resolved(None, _)) = &qself.kind {
1633 self.print_type(qself);
1636 self.print_type(qself);
1641 self.print_ident(item_segment.ident);
1642 self.print_generic_args(
1643 item_segment.args(),
1644 item_segment.infer_args,
1645 colons_before_params,
1648 hir::QPath::LangItem(lang_item, span, _) => {
1649 self.word("#[lang = \"");
1650 self.print_ident(Ident::new(lang_item.name(), span));
1656 fn print_generic_args(
1658 generic_args: &hir::GenericArgs<'_>,
1660 colons_before_params: bool,
1662 if generic_args.parenthesized {
1664 self.commasep(Inconsistent, generic_args.inputs(), |s, ty| s.print_type(&ty));
1667 self.space_if_not_bol();
1668 self.word_space("->");
1669 self.print_type(generic_args.bindings[0].ty());
1671 let start = if colons_before_params { "::<" } else { "<" };
1672 let empty = Cell::new(true);
1673 let start_or_comma = |this: &mut Self| {
1678 this.word_space(",")
1682 let mut nonelided_generic_args: bool = false;
1683 let elide_lifetimes = generic_args.args.iter().all(|arg| match arg {
1684 GenericArg::Lifetime(lt) => lt.is_elided(),
1686 nonelided_generic_args = true;
1691 if nonelided_generic_args {
1692 start_or_comma(self);
1696 |s, generic_arg| match generic_arg {
1697 GenericArg::Lifetime(lt) if !elide_lifetimes => s.print_lifetime(lt),
1698 GenericArg::Lifetime(_) => {}
1699 GenericArg::Type(ty) => s.print_type(ty),
1700 GenericArg::Const(ct) => s.print_anon_const(&ct.value),
1701 GenericArg::Infer(_inf) => s.word("_"),
1706 // FIXME(eddyb): this would leak into error messages (e.g.,
1707 // "non-exhaustive patterns: `Some::<..>(_)` not covered").
1708 if infer_args && false {
1709 start_or_comma(self);
1713 for binding in generic_args.bindings.iter() {
1714 start_or_comma(self);
1715 self.print_type_binding(binding);
1724 pub fn print_type_binding(&mut self, binding: &hir::TypeBinding<'_>) {
1725 self.print_ident(binding.ident);
1726 self.print_generic_args(binding.gen_args, false, false);
1728 match binding.kind {
1729 hir::TypeBindingKind::Equality { ref term } => {
1730 self.word_space("=");
1732 Term::Ty(ref ty) => self.print_type(ty),
1733 Term::Const(ref c) => self.print_anon_const(c),
1736 hir::TypeBindingKind::Constraint { bounds } => {
1737 self.print_bounds(":", bounds);
1742 pub fn print_pat(&mut self, pat: &hir::Pat<'_>) {
1743 self.maybe_print_comment(pat.span.lo());
1744 self.ann.pre(self, AnnNode::Pat(pat));
1745 // Pat isn't normalized, but the beauty of it
1746 // is that it doesn't matter
1748 PatKind::Wild => self.word("_"),
1749 PatKind::Binding(binding_mode, _, ident, ref sub) => {
1750 match binding_mode {
1751 hir::BindingAnnotation::Ref => {
1752 self.word_nbsp("ref");
1753 self.print_mutability(hir::Mutability::Not, false);
1755 hir::BindingAnnotation::RefMut => {
1756 self.word_nbsp("ref");
1757 self.print_mutability(hir::Mutability::Mut, false);
1759 hir::BindingAnnotation::Unannotated => {}
1760 hir::BindingAnnotation::Mutable => {
1761 self.word_nbsp("mut");
1764 self.print_ident(ident);
1765 if let Some(ref p) = *sub {
1770 PatKind::TupleStruct(ref qpath, ref elts, ddpos) => {
1771 self.print_qpath(qpath, true);
1773 if let Some(ddpos) = ddpos {
1774 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p));
1776 self.word_space(",");
1779 if ddpos != elts.len() {
1781 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p));
1784 self.commasep(Inconsistent, &elts, |s, p| s.print_pat(&p));
1788 PatKind::Path(ref qpath) => {
1789 self.print_qpath(qpath, true);
1791 PatKind::Struct(ref qpath, ref fields, etc) => {
1792 self.print_qpath(qpath, true);
1795 let empty = fields.is_empty() && !etc;
1803 s.cbox(INDENT_UNIT);
1804 if !f.is_shorthand {
1805 s.print_ident(f.ident);
1808 s.print_pat(&f.pat);
1814 if !fields.is_empty() {
1815 self.word_space(",");
1824 PatKind::Or(ref pats) => {
1825 self.strsep("|", true, Inconsistent, &pats, |s, p| s.print_pat(&p));
1827 PatKind::Tuple(ref elts, ddpos) => {
1829 if let Some(ddpos) = ddpos {
1830 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(&p));
1832 self.word_space(",");
1835 if ddpos != elts.len() {
1837 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(&p));
1840 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(&p));
1841 if elts.len() == 1 {
1847 PatKind::Box(ref inner) => {
1848 let is_range_inner = matches!(inner.kind, PatKind::Range(..));
1853 self.print_pat(&inner);
1858 PatKind::Ref(ref inner, mutbl) => {
1859 let is_range_inner = matches!(inner.kind, PatKind::Range(..));
1861 self.word(mutbl.prefix_str());
1865 self.print_pat(&inner);
1870 PatKind::Lit(ref e) => self.print_expr(&e),
1871 PatKind::Range(ref begin, ref end, ref end_kind) => {
1872 if let Some(expr) = begin {
1873 self.print_expr(expr);
1876 RangeEnd::Included => self.word("..."),
1877 RangeEnd::Excluded => self.word(".."),
1879 if let Some(expr) = end {
1880 self.print_expr(expr);
1883 PatKind::Slice(ref before, ref slice, ref after) => {
1885 self.commasep(Inconsistent, &before, |s, p| s.print_pat(&p));
1886 if let Some(ref p) = *slice {
1887 if !before.is_empty() {
1888 self.word_space(",");
1890 if let PatKind::Wild = p.kind {
1896 if !after.is_empty() {
1897 self.word_space(",");
1900 self.commasep(Inconsistent, &after, |s, p| s.print_pat(&p));
1904 self.ann.post(self, AnnNode::Pat(pat))
1907 pub fn print_param(&mut self, arg: &hir::Param<'_>) {
1908 self.print_outer_attributes(self.attrs(arg.hir_id));
1909 self.print_pat(&arg.pat);
1912 pub fn print_arm(&mut self, arm: &hir::Arm<'_>) {
1913 // I have no idea why this check is necessary, but here it
1915 if self.attrs(arm.hir_id).is_empty() {
1918 self.cbox(INDENT_UNIT);
1919 self.ann.pre(self, AnnNode::Arm(arm));
1921 self.print_outer_attributes(&self.attrs(arm.hir_id));
1922 self.print_pat(&arm.pat);
1924 if let Some(ref g) = arm.guard {
1926 hir::Guard::If(e) => {
1927 self.word_space("if");
1928 self.print_expr(&e);
1931 hir::Guard::IfLet(hir::Let { pat, ty, init, .. }) => {
1932 self.word_nbsp("if");
1933 self.print_let(pat, *ty, init);
1937 self.word_space("=>");
1939 match arm.body.kind {
1940 hir::ExprKind::Block(ref blk, opt_label) => {
1941 if let Some(label) = opt_label {
1942 self.print_ident(label.ident);
1943 self.word_space(":");
1945 // the block will close the pattern's ibox
1946 self.print_block_unclosed(&blk);
1948 // If it is a user-provided unsafe block, print a comma after it
1949 if let hir::BlockCheckMode::UnsafeBlock(hir::UnsafeSource::UserProvided) = blk.rules
1955 self.end(); // close the ibox for the pattern
1956 self.print_expr(&arm.body);
1960 self.ann.post(self, AnnNode::Arm(arm));
1961 self.end() // close enclosing cbox
1966 decl: &hir::FnDecl<'_>,
1967 header: hir::FnHeader,
1968 name: Option<Symbol>,
1969 generics: &hir::Generics<'_>,
1970 arg_names: &[Ident],
1971 body_id: Option<hir::BodyId>,
1973 self.print_fn_header_info(header);
1975 if let Some(name) = name {
1977 self.print_name(name);
1979 self.print_generic_params(&generics.params);
1983 // Make sure we aren't supplied *both* `arg_names` and `body_id`.
1984 assert!(arg_names.is_empty() || body_id.is_none());
1985 self.commasep(Inconsistent, &decl.inputs, |s, ty| {
1986 s.ibox(INDENT_UNIT);
1987 if let Some(arg_name) = arg_names.get(i) {
1988 s.word(arg_name.to_string());
1991 } else if let Some(body_id) = body_id {
1992 s.ann.nested(s, Nested::BodyParamPat(body_id, i));
2000 if decl.c_variadic {
2005 self.print_fn_output(decl);
2006 self.print_where_clause(generics)
2009 fn print_closure_params(&mut self, decl: &hir::FnDecl<'_>, body_id: hir::BodyId) {
2012 self.commasep(Inconsistent, &decl.inputs, |s, ty| {
2013 s.ibox(INDENT_UNIT);
2015 s.ann.nested(s, Nested::BodyParamPat(body_id, i));
2018 if let hir::TyKind::Infer = ty.kind {
2029 if let hir::FnRetTy::DefaultReturn(..) = decl.output {
2033 self.space_if_not_bol();
2034 self.word_space("->");
2036 hir::FnRetTy::Return(ref ty) => {
2037 self.print_type(&ty);
2038 self.maybe_print_comment(ty.span.lo());
2040 hir::FnRetTy::DefaultReturn(..) => unreachable!(),
2044 pub fn print_capture_clause(&mut self, capture_clause: hir::CaptureBy) {
2045 match capture_clause {
2046 hir::CaptureBy::Value => self.word_space("move"),
2047 hir::CaptureBy::Ref => {}
2051 pub fn print_bounds<'b>(
2053 prefix: &'static str,
2054 bounds: impl IntoIterator<Item = &'b hir::GenericBound<'b>>,
2056 let mut first = true;
2057 for bound in bounds {
2061 if !(first && prefix.is_empty()) {
2067 self.word_space("+");
2071 GenericBound::Trait(tref, modifier) => {
2072 if modifier == &TraitBoundModifier::Maybe {
2075 self.print_poly_trait_ref(tref);
2077 GenericBound::LangItemTrait(lang_item, span, ..) => {
2078 self.word("#[lang = \"");
2079 self.print_ident(Ident::new(lang_item.name(), *span));
2082 GenericBound::Outlives(lt) => {
2083 self.print_lifetime(lt);
2089 pub fn print_generic_params(&mut self, generic_params: &[GenericParam<'_>]) {
2090 if !generic_params.is_empty() {
2093 self.commasep(Inconsistent, generic_params, |s, param| s.print_generic_param(param));
2099 pub fn print_generic_param(&mut self, param: &GenericParam<'_>) {
2100 if let GenericParamKind::Const { .. } = param.kind {
2101 self.word_space("const");
2104 self.print_ident(param.name.ident());
2107 GenericParamKind::Lifetime { .. } => {}
2108 GenericParamKind::Type { ref default, .. } => {
2109 if let Some(default) = default {
2111 self.word_space("=");
2112 self.print_type(&default)
2115 GenericParamKind::Const { ref ty, ref default } => {
2116 self.word_space(":");
2117 self.print_type(ty);
2118 if let Some(ref default) = default {
2120 self.word_space("=");
2121 self.print_anon_const(&default)
2127 pub fn print_lifetime(&mut self, lifetime: &hir::Lifetime) {
2128 self.print_ident(lifetime.name.ident())
2131 pub fn print_where_clause(&mut self, generics: &hir::Generics<'_>) {
2132 if generics.predicates.is_empty() {
2137 self.word_space("where");
2139 for (i, predicate) in generics.predicates.iter().enumerate() {
2141 self.word_space(",");
2145 hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
2146 bound_generic_params,
2151 self.print_formal_generic_params(bound_generic_params);
2152 self.print_type(&bounded_ty);
2153 self.print_bounds(":", *bounds);
2155 hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
2160 self.print_lifetime(lifetime);
2163 for (i, bound) in bounds.iter().enumerate() {
2165 GenericBound::Outlives(lt) => {
2166 self.print_lifetime(lt);
2176 hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
2179 self.print_type(lhs_ty);
2181 self.word_space("=");
2182 self.print_type(rhs_ty);
2188 pub fn print_mutability(&mut self, mutbl: hir::Mutability, print_const: bool) {
2190 hir::Mutability::Mut => self.word_nbsp("mut"),
2191 hir::Mutability::Not => {
2193 self.word_nbsp("const")
2199 pub fn print_mt(&mut self, mt: &hir::MutTy<'_>, print_const: bool) {
2200 self.print_mutability(mt.mutbl, print_const);
2201 self.print_type(&mt.ty)
2204 pub fn print_fn_output(&mut self, decl: &hir::FnDecl<'_>) {
2205 if let hir::FnRetTy::DefaultReturn(..) = decl.output {
2209 self.space_if_not_bol();
2210 self.ibox(INDENT_UNIT);
2211 self.word_space("->");
2213 hir::FnRetTy::DefaultReturn(..) => unreachable!(),
2214 hir::FnRetTy::Return(ref ty) => self.print_type(&ty),
2218 if let hir::FnRetTy::Return(ref output) = decl.output {
2219 self.maybe_print_comment(output.span.lo());
2226 unsafety: hir::Unsafety,
2227 decl: &hir::FnDecl<'_>,
2228 name: Option<Symbol>,
2229 generic_params: &[hir::GenericParam<'_>],
2230 arg_names: &[Ident],
2232 self.ibox(INDENT_UNIT);
2233 self.print_formal_generic_params(generic_params);
2234 let generics = hir::Generics::empty();
2240 constness: hir::Constness::NotConst,
2241 asyncness: hir::IsAsync::NotAsync,
2251 pub fn print_fn_header_info(&mut self, header: hir::FnHeader) {
2252 match header.constness {
2253 hir::Constness::NotConst => {}
2254 hir::Constness::Const => self.word_nbsp("const"),
2257 match header.asyncness {
2258 hir::IsAsync::NotAsync => {}
2259 hir::IsAsync::Async => self.word_nbsp("async"),
2262 self.print_unsafety(header.unsafety);
2264 if header.abi != Abi::Rust {
2265 self.word_nbsp("extern");
2266 self.word_nbsp(header.abi.to_string());
2272 pub fn print_unsafety(&mut self, s: hir::Unsafety) {
2274 hir::Unsafety::Normal => {}
2275 hir::Unsafety::Unsafe => self.word_nbsp("unsafe"),
2279 pub fn print_is_auto(&mut self, s: hir::IsAuto) {
2281 hir::IsAuto::Yes => self.word_nbsp("auto"),
2282 hir::IsAuto::No => {}
2287 /// Does this expression require a semicolon to be treated
2288 /// as a statement? The negation of this: 'can this expression
2289 /// be used as a statement without a semicolon' -- is used
2290 /// as an early-bail-out in the parser so that, for instance,
2291 /// if true {...} else {...}
2293 /// isn't parsed as (if true {...} else {...} | x) | 5
2295 // Duplicated from `parse::classify`, but adapted for the HIR.
2296 fn expr_requires_semi_to_be_stmt(e: &hir::Expr<'_>) -> bool {
2299 hir::ExprKind::If(..)
2300 | hir::ExprKind::Match(..)
2301 | hir::ExprKind::Block(..)
2302 | hir::ExprKind::Loop(..)
2306 /// This statement requires a semicolon after it.
2307 /// note that in one case (stmt_semi), we've already
2308 /// seen the semicolon, and thus don't need another.
2309 fn stmt_ends_with_semi(stmt: &hir::StmtKind<'_>) -> bool {
2311 hir::StmtKind::Local(_) => true,
2312 hir::StmtKind::Item(_) => false,
2313 hir::StmtKind::Expr(ref e) => expr_requires_semi_to_be_stmt(&e),
2314 hir::StmtKind::Semi(..) => false,
2318 fn bin_op_to_assoc_op(op: hir::BinOpKind) -> AssocOp {
2319 use crate::hir::BinOpKind::*;
2321 Add => AssocOp::Add,
2322 Sub => AssocOp::Subtract,
2323 Mul => AssocOp::Multiply,
2324 Div => AssocOp::Divide,
2325 Rem => AssocOp::Modulus,
2327 And => AssocOp::LAnd,
2330 BitXor => AssocOp::BitXor,
2331 BitAnd => AssocOp::BitAnd,
2332 BitOr => AssocOp::BitOr,
2333 Shl => AssocOp::ShiftLeft,
2334 Shr => AssocOp::ShiftRight,
2336 Eq => AssocOp::Equal,
2337 Lt => AssocOp::Less,
2338 Le => AssocOp::LessEqual,
2339 Ne => AssocOp::NotEqual,
2340 Ge => AssocOp::GreaterEqual,
2341 Gt => AssocOp::Greater,
2345 /// Expressions that syntactically contain an "exterior" struct literal, i.e., not surrounded by any
2346 /// parens or other delimiters, e.g., `X { y: 1 }`, `X { y: 1 }.method()`, `foo == X { y: 1 }` and
2347 /// `X { y: 1 } == foo` all do, but `(X { y: 1 }) == foo` does not.
2348 fn contains_exterior_struct_lit(value: &hir::Expr<'_>) -> bool {
2350 hir::ExprKind::Struct(..) => true,
2352 hir::ExprKind::Assign(ref lhs, ref rhs, _)
2353 | hir::ExprKind::AssignOp(_, ref lhs, ref rhs)
2354 | hir::ExprKind::Binary(_, ref lhs, ref rhs) => {
2355 // `X { y: 1 } + X { y: 2 }`
2356 contains_exterior_struct_lit(&lhs) || contains_exterior_struct_lit(&rhs)
2358 hir::ExprKind::Unary(_, ref x)
2359 | hir::ExprKind::Cast(ref x, _)
2360 | hir::ExprKind::Type(ref x, _)
2361 | hir::ExprKind::Field(ref x, _)
2362 | hir::ExprKind::Index(ref x, _) => {
2363 // `&X { y: 1 }, X { y: 1 }.y`
2364 contains_exterior_struct_lit(&x)
2367 hir::ExprKind::MethodCall(.., ref exprs, _) => {
2368 // `X { y: 1 }.bar(...)`
2369 contains_exterior_struct_lit(&exprs[0])