1 #![recursion_limit = "256"]
2 #![deny(rustc::untranslatable_diagnostic)]
3 #![deny(rustc::diagnostic_outside_of_impl)]
6 use rustc_ast::util::parser::{self, AssocOp, Fixity};
7 use rustc_ast_pretty::pp::Breaks::{Consistent, Inconsistent};
8 use rustc_ast_pretty::pp::{self, Breaks};
9 use rustc_ast_pretty::pprust::{Comments, PrintState};
11 use rustc_hir::LifetimeParamKind;
12 use rustc_hir::{GenericArg, GenericParam, GenericParamKind, Node, Term};
13 use rustc_hir::{GenericBound, PatKind, RangeEnd, TraitBoundModifier};
14 use rustc_span::source_map::SourceMap;
15 use rustc_span::symbol::{kw, Ident, IdentPrinter, Symbol};
16 use rustc_span::{self, FileName};
17 use rustc_target::spec::abi::Abi;
22 pub fn id_to_string(map: &dyn rustc_hir::intravisit::Map<'_>, hir_id: hir::HirId) -> String {
23 to_string(&map, |s| s.print_node(map.find(hir_id).unwrap()))
26 pub enum AnnNode<'a> {
28 Block(&'a hir::Block<'a>),
29 Item(&'a hir::Item<'a>),
31 Expr(&'a hir::Expr<'a>),
32 Pat(&'a hir::Pat<'a>),
33 Arm(&'a hir::Arm<'a>),
38 TraitItem(hir::TraitItemId),
39 ImplItem(hir::ImplItemId),
40 ForeignItem(hir::ForeignItemId),
42 BodyParamPat(hir::BodyId, usize),
46 fn nested(&self, _state: &mut State<'_>, _nested: Nested) {}
47 fn pre(&self, _state: &mut State<'_>, _node: AnnNode<'_>) {}
48 fn post(&self, _state: &mut State<'_>, _node: AnnNode<'_>) {}
52 impl PpAnn for NoAnn {}
53 pub const NO_ANN: &dyn PpAnn = &NoAnn;
55 /// Identical to the `PpAnn` implementation for `hir::Crate`,
56 /// except it avoids creating a dependency on the whole crate.
57 impl PpAnn for &dyn rustc_hir::intravisit::Map<'_> {
58 fn nested(&self, state: &mut State<'_>, nested: Nested) {
60 Nested::Item(id) => state.print_item(self.item(id)),
61 Nested::TraitItem(id) => state.print_trait_item(self.trait_item(id)),
62 Nested::ImplItem(id) => state.print_impl_item(self.impl_item(id)),
63 Nested::ForeignItem(id) => state.print_foreign_item(self.foreign_item(id)),
64 Nested::Body(id) => state.print_expr(&self.body(id).value),
65 Nested::BodyParamPat(id, i) => state.print_pat(self.body(id).params[i].pat),
70 pub struct State<'a> {
72 comments: Option<Comments<'a>>,
73 attrs: &'a dyn Fn(hir::HirId) -> &'a [ast::Attribute],
74 ann: &'a (dyn PpAnn + 'a),
78 pub fn print_node(&mut self, node: Node<'_>) {
80 Node::Param(a) => self.print_param(a),
81 Node::Item(a) => self.print_item(a),
82 Node::ForeignItem(a) => self.print_foreign_item(a),
83 Node::TraitItem(a) => self.print_trait_item(a),
84 Node::ImplItem(a) => self.print_impl_item(a),
85 Node::Variant(a) => self.print_variant(a),
86 Node::AnonConst(a) => self.print_anon_const(a),
87 Node::Expr(a) => self.print_expr(a),
88 Node::ExprField(a) => self.print_expr_field(&a),
89 Node::Stmt(a) => self.print_stmt(a),
90 Node::PathSegment(a) => self.print_path_segment(a),
91 Node::Ty(a) => self.print_type(a),
92 Node::TypeBinding(a) => self.print_type_binding(a),
93 Node::TraitRef(a) => self.print_trait_ref(a),
94 Node::Pat(a) => self.print_pat(a),
95 Node::PatField(a) => self.print_patfield(&a),
96 Node::Arm(a) => self.print_arm(a),
97 Node::Infer(_) => self.word("_"),
99 // Containing cbox, will be closed by print-block at `}`.
100 self.cbox(INDENT_UNIT);
101 // Head-ibox, will be closed by print-block after `{`.
105 Node::Lifetime(a) => self.print_lifetime(a),
106 Node::GenericParam(_) => panic!("cannot print Node::GenericParam"),
107 Node::Field(_) => panic!("cannot print Node::Field"),
108 // These cases do not carry enough information in the
109 // `hir_map` to reconstruct their full structure for pretty
111 Node::Ctor(..) => panic!("cannot print isolated Ctor"),
112 Node::Local(a) => self.print_local_decl(a),
113 Node::Crate(..) => panic!("cannot print Crate"),
118 impl std::ops::Deref for State<'_> {
119 type Target = pp::Printer;
120 fn deref(&self) -> &Self::Target {
125 impl std::ops::DerefMut for State<'_> {
126 fn deref_mut(&mut self) -> &mut Self::Target {
131 impl<'a> PrintState<'a> for State<'a> {
132 fn comments(&mut self) -> &mut Option<Comments<'a>> {
136 fn print_ident(&mut self, ident: Ident) {
137 self.word(IdentPrinter::for_ast_ident(ident, ident.is_raw_guess()).to_string());
138 self.ann.post(self, AnnNode::Name(&ident.name))
141 fn print_generic_args(&mut self, _: &ast::GenericArgs, _colons_before_params: bool) {
142 panic!("AST generic args printed by HIR pretty-printer");
146 pub const INDENT_UNIT: isize = 4;
148 /// Requires you to pass an input filename and reader so that
149 /// it can scan the input text for comments to copy forward.
150 pub fn print_crate<'a>(
152 krate: &hir::Mod<'_>,
155 attrs: &'a dyn Fn(hir::HirId) -> &'a [ast::Attribute],
158 let mut s = State::new_from_input(sm, filename, input, attrs, ann);
160 // When printing the AST, we sometimes need to inject `#[no_std]` here.
161 // Since you can't compile the HIR, it's not necessary.
163 s.print_mod(krate, (*attrs)(hir::CRATE_HIR_ID));
164 s.print_remaining_comments();
169 pub fn new_from_input(
173 attrs: &'a dyn Fn(hir::HirId) -> &'a [ast::Attribute],
177 s: pp::Printer::new(),
178 comments: Some(Comments::new(sm, filename, input)),
184 fn attrs(&self, id: hir::HirId) -> &'a [ast::Attribute] {
189 pub fn to_string<F>(ann: &dyn PpAnn, f: F) -> String
191 F: FnOnce(&mut State<'_>),
193 let mut printer = State { s: pp::Printer::new(), comments: None, attrs: &|_| &[], ann };
198 pub fn generic_params_to_string(generic_params: &[GenericParam<'_>]) -> String {
199 to_string(NO_ANN, |s| s.print_generic_params(generic_params))
202 pub fn bounds_to_string<'b>(bounds: impl IntoIterator<Item = &'b hir::GenericBound<'b>>) -> String {
203 to_string(NO_ANN, |s| s.print_bounds("", bounds))
206 pub fn ty_to_string(ty: &hir::Ty<'_>) -> String {
207 to_string(NO_ANN, |s| s.print_type(ty))
210 pub fn path_segment_to_string(segment: &hir::PathSegment<'_>) -> String {
211 to_string(NO_ANN, |s| s.print_path_segment(segment))
214 pub fn path_to_string(segment: &hir::Path<'_>) -> String {
215 to_string(NO_ANN, |s| s.print_path(segment, false))
218 pub fn qpath_to_string(segment: &hir::QPath<'_>) -> String {
219 to_string(NO_ANN, |s| s.print_qpath(segment, false))
223 decl: &hir::FnDecl<'_>,
224 header: hir::FnHeader,
225 name: Option<Symbol>,
226 generics: &hir::Generics<'_>,
228 body_id: Option<hir::BodyId>,
230 to_string(NO_ANN, |s| s.print_fn(decl, header, name, generics, arg_names, body_id))
233 pub fn enum_def_to_string(
234 enum_definition: &hir::EnumDef<'_>,
235 generics: &hir::Generics<'_>,
237 span: rustc_span::Span,
239 to_string(NO_ANN, |s| s.print_enum_def(enum_definition, generics, name, span))
243 pub fn bclose_maybe_open(&mut self, span: rustc_span::Span, close_box: bool) {
244 self.maybe_print_comment(span.hi());
245 self.break_offset_if_not_bol(1, -(INDENT_UNIT as isize));
248 self.end(); // close the outer-box
252 pub fn bclose(&mut self, span: rustc_span::Span) {
253 self.bclose_maybe_open(span, true)
256 pub fn commasep_cmnt<T, F, G>(&mut self, b: Breaks, elts: &[T], mut op: F, mut get_span: G)
258 F: FnMut(&mut State<'_>, &T),
259 G: FnMut(&T) -> rustc_span::Span,
262 let len = elts.len();
265 self.maybe_print_comment(get_span(elt).hi());
270 self.maybe_print_trailing_comment(get_span(elt), Some(get_span(&elts[i]).hi()));
271 self.space_if_not_bol();
277 pub fn commasep_exprs(&mut self, b: Breaks, exprs: &[hir::Expr<'_>]) {
278 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(e), |e| e.span);
281 pub fn print_mod(&mut self, _mod: &hir::Mod<'_>, attrs: &[ast::Attribute]) {
282 self.print_inner_attributes(attrs);
283 for &item_id in _mod.item_ids {
284 self.ann.nested(self, Nested::Item(item_id));
288 pub fn print_opt_lifetime(&mut self, lifetime: &hir::Lifetime) {
289 if !lifetime.is_elided() {
290 self.print_lifetime(lifetime);
295 pub fn print_type(&mut self, ty: &hir::Ty<'_>) {
296 self.maybe_print_comment(ty.span.lo());
299 hir::TyKind::Slice(ty) => {
304 hir::TyKind::Ptr(ref mt) => {
306 self.print_mt(mt, true);
308 hir::TyKind::Rptr(ref lifetime, ref mt) => {
310 self.print_opt_lifetime(lifetime);
311 self.print_mt(mt, false);
313 hir::TyKind::Never => {
316 hir::TyKind::Tup(elts) => {
318 self.commasep(Inconsistent, elts, |s, ty| s.print_type(ty));
324 hir::TyKind::BareFn(f) => {
325 self.print_ty_fn(f.abi, f.unsafety, f.decl, None, f.generic_params, f.param_names);
327 hir::TyKind::OpaqueDef(..) => self.word("/*impl Trait*/"),
328 hir::TyKind::Path(ref qpath) => self.print_qpath(qpath, false),
329 hir::TyKind::TraitObject(bounds, ref lifetime, syntax) => {
330 if syntax == ast::TraitObjectSyntax::Dyn {
331 self.word_space("dyn");
333 let mut first = true;
334 for bound in bounds {
339 self.word_space("+");
341 self.print_poly_trait_ref(bound);
343 if !lifetime.is_elided() {
345 self.word_space("+");
346 self.print_lifetime(lifetime);
349 hir::TyKind::Array(ty, ref length) => {
353 self.print_array_length(length);
356 hir::TyKind::Typeof(ref e) => {
357 self.word("typeof(");
358 self.print_anon_const(e);
361 hir::TyKind::Err => {
363 self.word("/*ERROR*/");
366 hir::TyKind::Infer => {
373 pub fn print_foreign_item(&mut self, item: &hir::ForeignItem<'_>) {
374 self.hardbreak_if_not_bol();
375 self.maybe_print_comment(item.span.lo());
376 self.print_outer_attributes(self.attrs(item.hir_id()));
378 hir::ForeignItemKind::Fn(decl, arg_names, generics) => {
383 unsafety: hir::Unsafety::Normal,
384 constness: hir::Constness::NotConst,
386 asyncness: hir::IsAsync::NotAsync,
388 Some(item.ident.name),
393 self.end(); // end head-ibox
395 self.end() // end the outer fn box
397 hir::ForeignItemKind::Static(t, m) => {
399 if m == hir::Mutability::Mut {
400 self.word_space("mut");
402 self.print_ident(item.ident);
403 self.word_space(":");
406 self.end(); // end the head-ibox
407 self.end() // end the outer cbox
409 hir::ForeignItemKind::Type => {
411 self.print_ident(item.ident);
413 self.end(); // end the head-ibox
414 self.end() // end the outer cbox
419 fn print_associated_const(
423 default: Option<hir::BodyId>,
426 self.word_space("const");
427 self.print_ident(ident);
428 self.word_space(":");
430 if let Some(expr) = default {
432 self.word_space("=");
433 self.ann.nested(self, Nested::Body(expr));
438 fn print_associated_type(
441 generics: &hir::Generics<'_>,
442 bounds: Option<hir::GenericBounds<'_>>,
443 ty: Option<&hir::Ty<'_>>,
445 self.word_space("type");
446 self.print_ident(ident);
447 self.print_generic_params(generics.params);
448 if let Some(bounds) = bounds {
449 self.print_bounds(":", bounds);
451 self.print_where_clause(generics);
452 if let Some(ty) = ty {
454 self.word_space("=");
462 item: &hir::Item<'_>,
463 generics: &hir::Generics<'_>,
464 inner: impl Fn(&mut Self),
467 self.print_ident(item.ident);
468 self.print_generic_params(generics.params);
469 self.end(); // end the inner ibox
471 self.print_where_clause(generics);
475 self.end(); // end the outer ibox
478 /// Pretty-print an item
479 pub fn print_item(&mut self, item: &hir::Item<'_>) {
480 self.hardbreak_if_not_bol();
481 self.maybe_print_comment(item.span.lo());
482 let attrs = self.attrs(item.hir_id());
483 self.print_outer_attributes(attrs);
484 self.ann.pre(self, AnnNode::Item(item));
486 hir::ItemKind::ExternCrate(orig_name) => {
487 self.head("extern crate");
488 if let Some(orig_name) = orig_name {
489 self.print_name(orig_name);
494 self.print_ident(item.ident);
496 self.end(); // end inner head-block
497 self.end(); // end outer head-block
499 hir::ItemKind::Use(path, kind) => {
501 self.print_path(path, false);
504 hir::UseKind::Single => {
505 if path.segments.last().unwrap().ident != item.ident {
507 self.word_space("as");
508 self.print_ident(item.ident);
512 hir::UseKind::Glob => self.word("::*;"),
513 hir::UseKind::ListStem => self.word("::{};"),
515 self.end(); // end inner head-block
516 self.end(); // end outer head-block
518 hir::ItemKind::Static(ty, m, expr) => {
520 if m == hir::Mutability::Mut {
521 self.word_space("mut");
523 self.print_ident(item.ident);
524 self.word_space(":");
527 self.end(); // end the head-ibox
529 self.word_space("=");
530 self.ann.nested(self, Nested::Body(expr));
532 self.end(); // end the outer cbox
534 hir::ItemKind::Const(ty, expr) => {
536 self.print_ident(item.ident);
537 self.word_space(":");
540 self.end(); // end the head-ibox
542 self.word_space("=");
543 self.ann.nested(self, Nested::Body(expr));
545 self.end(); // end the outer cbox
547 hir::ItemKind::Fn(ref sig, param_names, body) => {
552 Some(item.ident.name),
558 self.end(); // need to close a box
559 self.end(); // need to close a box
560 self.ann.nested(self, Nested::Body(body));
562 hir::ItemKind::Macro(ref macro_def, _) => {
563 self.print_mac_def(macro_def, &item.ident, item.span, |_| {});
565 hir::ItemKind::Mod(ref _mod) => {
567 self.print_ident(item.ident);
570 self.print_mod(_mod, attrs);
571 self.bclose(item.span);
573 hir::ItemKind::ForeignMod { abi, items } => {
575 self.word_nbsp(abi.to_string());
577 self.print_inner_attributes(self.attrs(item.hir_id()));
579 self.ann.nested(self, Nested::ForeignItem(item.id));
581 self.bclose(item.span);
583 hir::ItemKind::GlobalAsm(asm) => {
584 self.head("global_asm!");
585 self.print_inline_asm(asm);
588 hir::ItemKind::TyAlias(ty, generics) => {
589 self.print_item_type(item, generics, |state| {
590 state.word_space("=");
591 state.print_type(ty);
594 hir::ItemKind::OpaqueTy(ref opaque_ty) => {
595 self.print_item_type(item, opaque_ty.generics, |state| {
596 let mut real_bounds = Vec::with_capacity(opaque_ty.bounds.len());
597 for b in opaque_ty.bounds {
598 if let GenericBound::Trait(ptr, hir::TraitBoundModifier::Maybe) = b {
600 state.word_space("for ?");
601 state.print_trait_ref(&ptr.trait_ref);
606 state.print_bounds("= impl", real_bounds);
609 hir::ItemKind::Enum(ref enum_definition, params) => {
610 self.print_enum_def(enum_definition, params, item.ident.name, item.span);
612 hir::ItemKind::Struct(ref struct_def, generics) => {
614 self.print_struct(struct_def, generics, item.ident.name, item.span, true);
616 hir::ItemKind::Union(ref struct_def, generics) => {
618 self.print_struct(struct_def, generics, item.ident.name, item.span, true);
620 hir::ItemKind::Impl(&hir::Impl {
632 self.print_defaultness(defaultness);
633 self.print_unsafety(unsafety);
634 self.word_nbsp("impl");
636 if !generics.params.is_empty() {
637 self.print_generic_params(generics.params);
641 if constness == hir::Constness::Const {
642 self.word_nbsp("const");
645 if let hir::ImplPolarity::Negative(_) = polarity {
649 if let Some(t) = of_trait {
650 self.print_trait_ref(t);
652 self.word_space("for");
655 self.print_type(self_ty);
656 self.print_where_clause(generics);
660 self.print_inner_attributes(attrs);
661 for impl_item in items {
662 self.ann.nested(self, Nested::ImplItem(impl_item.id));
664 self.bclose(item.span);
666 hir::ItemKind::Trait(is_auto, unsafety, generics, bounds, trait_items) => {
668 self.print_is_auto(is_auto);
669 self.print_unsafety(unsafety);
670 self.word_nbsp("trait");
671 self.print_ident(item.ident);
672 self.print_generic_params(generics.params);
673 let mut real_bounds = Vec::with_capacity(bounds.len());
675 if let GenericBound::Trait(ptr, hir::TraitBoundModifier::Maybe) = b {
677 self.word_space("for ?");
678 self.print_trait_ref(&ptr.trait_ref);
683 self.print_bounds(":", real_bounds);
684 self.print_where_clause(generics);
687 for trait_item in trait_items {
688 self.ann.nested(self, Nested::TraitItem(trait_item.id));
690 self.bclose(item.span);
692 hir::ItemKind::TraitAlias(generics, bounds) => {
694 self.print_ident(item.ident);
695 self.print_generic_params(generics.params);
696 let mut real_bounds = Vec::with_capacity(bounds.len());
697 // FIXME(durka) this seems to be some quite outdated syntax
699 if let GenericBound::Trait(ptr, hir::TraitBoundModifier::Maybe) = b {
701 self.word_space("for ?");
702 self.print_trait_ref(&ptr.trait_ref);
708 self.print_bounds("=", real_bounds);
709 self.print_where_clause(generics);
711 self.end(); // end inner head-block
712 self.end(); // end outer head-block
715 self.ann.post(self, AnnNode::Item(item))
718 pub fn print_trait_ref(&mut self, t: &hir::TraitRef<'_>) {
719 self.print_path(t.path, false);
722 fn print_formal_generic_params(&mut self, generic_params: &[hir::GenericParam<'_>]) {
723 if !generic_params.is_empty() {
725 self.print_generic_params(generic_params);
730 fn print_poly_trait_ref(&mut self, t: &hir::PolyTraitRef<'_>) {
731 self.print_formal_generic_params(t.bound_generic_params);
732 self.print_trait_ref(&t.trait_ref);
735 pub fn print_enum_def(
737 enum_definition: &hir::EnumDef<'_>,
738 generics: &hir::Generics<'_>,
740 span: rustc_span::Span,
743 self.print_name(name);
744 self.print_generic_params(generics.params);
745 self.print_where_clause(generics);
747 self.print_variants(enum_definition.variants, span);
750 pub fn print_variants(&mut self, variants: &[hir::Variant<'_>], span: rustc_span::Span) {
753 self.space_if_not_bol();
754 self.maybe_print_comment(v.span.lo());
755 self.print_outer_attributes(self.attrs(v.id));
756 self.ibox(INDENT_UNIT);
757 self.print_variant(v);
760 self.maybe_print_trailing_comment(v.span, None);
765 pub fn print_defaultness(&mut self, defaultness: hir::Defaultness) {
767 hir::Defaultness::Default { .. } => self.word_nbsp("default"),
768 hir::Defaultness::Final => (),
774 struct_def: &hir::VariantData<'_>,
775 generics: &hir::Generics<'_>,
777 span: rustc_span::Span,
778 print_finalizer: bool,
780 self.print_name(name);
781 self.print_generic_params(generics.params);
783 hir::VariantData::Tuple(..) | hir::VariantData::Unit(..) => {
784 if let hir::VariantData::Tuple(..) = struct_def {
786 self.commasep(Inconsistent, struct_def.fields(), |s, field| {
787 s.maybe_print_comment(field.span.lo());
788 s.print_outer_attributes(s.attrs(field.hir_id));
789 s.print_type(field.ty);
793 self.print_where_clause(generics);
798 self.end() // close the outer-box
800 hir::VariantData::Struct(..) => {
801 self.print_where_clause(generics);
804 self.hardbreak_if_not_bol();
806 for field in struct_def.fields() {
807 self.hardbreak_if_not_bol();
808 self.maybe_print_comment(field.span.lo());
809 self.print_outer_attributes(self.attrs(field.hir_id));
810 self.print_ident(field.ident);
812 self.print_type(field.ty);
821 pub fn print_variant(&mut self, v: &hir::Variant<'_>) {
823 let generics = hir::Generics::empty();
824 self.print_struct(&v.data, generics, v.ident.name, v.span, false);
825 if let Some(ref d) = v.disr_expr {
827 self.word_space("=");
828 self.print_anon_const(d);
831 pub fn print_method_sig(
835 generics: &hir::Generics<'_>,
837 body_id: Option<hir::BodyId>,
839 self.print_fn(m.decl, m.header, Some(ident.name), generics, arg_names, body_id);
842 pub fn print_trait_item(&mut self, ti: &hir::TraitItem<'_>) {
843 self.ann.pre(self, AnnNode::SubItem(ti.hir_id()));
844 self.hardbreak_if_not_bol();
845 self.maybe_print_comment(ti.span.lo());
846 self.print_outer_attributes(self.attrs(ti.hir_id()));
848 hir::TraitItemKind::Const(ty, default) => {
849 self.print_associated_const(ti.ident, ty, default);
851 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Required(arg_names)) => {
852 self.print_method_sig(ti.ident, sig, ti.generics, arg_names, None);
855 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Provided(body)) => {
857 self.print_method_sig(ti.ident, sig, ti.generics, &[], Some(body));
859 self.end(); // need to close a box
860 self.end(); // need to close a box
861 self.ann.nested(self, Nested::Body(body));
863 hir::TraitItemKind::Type(bounds, default) => {
864 self.print_associated_type(ti.ident, ti.generics, Some(bounds), default);
867 self.ann.post(self, AnnNode::SubItem(ti.hir_id()))
870 pub fn print_impl_item(&mut self, ii: &hir::ImplItem<'_>) {
871 self.ann.pre(self, AnnNode::SubItem(ii.hir_id()));
872 self.hardbreak_if_not_bol();
873 self.maybe_print_comment(ii.span.lo());
874 self.print_outer_attributes(self.attrs(ii.hir_id()));
877 hir::ImplItemKind::Const(ty, expr) => {
878 self.print_associated_const(ii.ident, ty, Some(expr));
880 hir::ImplItemKind::Fn(ref sig, body) => {
882 self.print_method_sig(ii.ident, sig, ii.generics, &[], Some(body));
884 self.end(); // need to close a box
885 self.end(); // need to close a box
886 self.ann.nested(self, Nested::Body(body));
888 hir::ImplItemKind::TyAlias(ty) => {
889 self.print_associated_type(ii.ident, ii.generics, None, Some(ty));
892 self.ann.post(self, AnnNode::SubItem(ii.hir_id()))
897 init: Option<&hir::Expr<'_>>,
898 els: Option<&hir::Block<'_>>,
899 decl: impl Fn(&mut Self),
901 self.space_if_not_bol();
902 self.ibox(INDENT_UNIT);
903 self.word_nbsp("let");
905 self.ibox(INDENT_UNIT);
909 if let Some(init) = init {
911 self.word_space("=");
912 self.print_expr(init);
915 if let Some(els) = els {
917 self.word_space("else");
918 // containing cbox, will be closed by print-block at `}`
920 // head-box, will be closed by print-block after `{`
922 self.print_block(els);
928 pub fn print_stmt(&mut self, st: &hir::Stmt<'_>) {
929 self.maybe_print_comment(st.span.lo());
931 hir::StmtKind::Local(loc) => {
932 self.print_local(loc.init, loc.els, |this| this.print_local_decl(loc));
934 hir::StmtKind::Item(item) => self.ann.nested(self, Nested::Item(item)),
935 hir::StmtKind::Expr(expr) => {
936 self.space_if_not_bol();
937 self.print_expr(expr);
939 hir::StmtKind::Semi(expr) => {
940 self.space_if_not_bol();
941 self.print_expr(expr);
945 if stmt_ends_with_semi(&st.kind) {
948 self.maybe_print_trailing_comment(st.span, None)
951 pub fn print_block(&mut self, blk: &hir::Block<'_>) {
952 self.print_block_with_attrs(blk, &[])
955 pub fn print_block_unclosed(&mut self, blk: &hir::Block<'_>) {
956 self.print_block_maybe_unclosed(blk, &[], false)
959 pub fn print_block_with_attrs(&mut self, blk: &hir::Block<'_>, attrs: &[ast::Attribute]) {
960 self.print_block_maybe_unclosed(blk, attrs, true)
963 pub fn print_block_maybe_unclosed(
965 blk: &hir::Block<'_>,
966 attrs: &[ast::Attribute],
970 hir::BlockCheckMode::UnsafeBlock(..) => self.word_space("unsafe"),
971 hir::BlockCheckMode::DefaultBlock => (),
973 self.maybe_print_comment(blk.span.lo());
974 self.ann.pre(self, AnnNode::Block(blk));
977 self.print_inner_attributes(attrs);
979 for st in blk.stmts {
982 if let Some(expr) = blk.expr {
983 self.space_if_not_bol();
984 self.print_expr(expr);
985 self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi()));
987 self.bclose_maybe_open(blk.span, close_box);
988 self.ann.post(self, AnnNode::Block(blk))
991 fn print_else(&mut self, els: Option<&hir::Expr<'_>>) {
992 if let Some(els_inner) = els {
993 match els_inner.kind {
994 // Another `else if` block.
995 hir::ExprKind::If(i, then, e) => {
996 self.cbox(INDENT_UNIT - 1);
998 self.word(" else if ");
999 self.print_expr_as_cond(i);
1001 self.print_expr(then);
1004 // Final `else` block.
1005 hir::ExprKind::Block(b, _) => {
1006 self.cbox(INDENT_UNIT - 1);
1008 self.word(" else ");
1009 self.print_block(b);
1011 // Constraints would be great here!
1013 panic!("print_if saw if with weird alternative");
1021 test: &hir::Expr<'_>,
1022 blk: &hir::Expr<'_>,
1023 elseopt: Option<&hir::Expr<'_>>,
1026 self.print_expr_as_cond(test);
1028 self.print_expr(blk);
1029 self.print_else(elseopt)
1032 pub fn print_array_length(&mut self, len: &hir::ArrayLen) {
1034 hir::ArrayLen::Infer(_, _) => self.word("_"),
1035 hir::ArrayLen::Body(ct) => self.print_anon_const(ct),
1039 pub fn print_anon_const(&mut self, constant: &hir::AnonConst) {
1040 self.ann.nested(self, Nested::Body(constant.body))
1043 fn print_call_post(&mut self, args: &[hir::Expr<'_>]) {
1045 self.commasep_exprs(Inconsistent, args);
1049 fn print_expr_maybe_paren(&mut self, expr: &hir::Expr<'_>, prec: i8) {
1050 self.print_expr_cond_paren(expr, expr.precedence().order() < prec)
1053 /// Prints an expr using syntax that's acceptable in a condition position, such as the `cond` in
1054 /// `if cond { ... }`.
1055 pub fn print_expr_as_cond(&mut self, expr: &hir::Expr<'_>) {
1056 self.print_expr_cond_paren(expr, Self::cond_needs_par(expr))
1059 /// Prints `expr` or `(expr)` when `needs_par` holds.
1060 fn print_expr_cond_paren(&mut self, expr: &hir::Expr<'_>, needs_par: bool) {
1064 if let hir::ExprKind::DropTemps(actual_expr) = expr.kind {
1065 self.print_expr(actual_expr);
1067 self.print_expr(expr);
1074 /// Print a `let pat = expr` expression.
1075 fn print_let(&mut self, pat: &hir::Pat<'_>, ty: Option<&hir::Ty<'_>>, init: &hir::Expr<'_>) {
1076 self.word_space("let");
1077 self.print_pat(pat);
1078 if let Some(ty) = ty {
1079 self.word_space(":");
1080 self.print_type(ty);
1083 self.word_space("=");
1084 let npals = || parser::needs_par_as_let_scrutinee(init.precedence().order());
1085 self.print_expr_cond_paren(init, Self::cond_needs_par(init) || npals())
1088 // Does `expr` need parentheses when printed in a condition position?
1090 // These cases need parens due to the parse error observed in #26461: `if return {}`
1091 // parses as the erroneous construct `if (return {})`, not `if (return) {}`.
1092 fn cond_needs_par(expr: &hir::Expr<'_>) -> bool {
1094 hir::ExprKind::Break(..) | hir::ExprKind::Closure { .. } | hir::ExprKind::Ret(..) => {
1097 _ => contains_exterior_struct_lit(expr),
1101 fn print_expr_vec(&mut self, exprs: &[hir::Expr<'_>]) {
1102 self.ibox(INDENT_UNIT);
1104 self.commasep_exprs(Inconsistent, exprs);
1109 fn print_expr_anon_const(&mut self, anon_const: &hir::AnonConst) {
1110 self.ibox(INDENT_UNIT);
1111 self.word_space("const");
1112 self.print_anon_const(anon_const);
1116 fn print_expr_repeat(&mut self, element: &hir::Expr<'_>, count: &hir::ArrayLen) {
1117 self.ibox(INDENT_UNIT);
1119 self.print_expr(element);
1120 self.word_space(";");
1121 self.print_array_length(count);
1126 fn print_expr_struct(
1128 qpath: &hir::QPath<'_>,
1129 fields: &[hir::ExprField<'_>],
1130 wth: Option<&hir::Expr<'_>>,
1132 self.print_qpath(qpath, true);
1134 self.commasep_cmnt(Consistent, fields, |s, field| s.print_expr_field(field), |f| f.span);
1135 if let Some(expr) = wth {
1136 self.ibox(INDENT_UNIT);
1137 if !fields.is_empty() {
1142 self.print_expr(expr);
1144 } else if !fields.is_empty() {
1151 fn print_expr_field(&mut self, field: &hir::ExprField<'_>) {
1152 if self.attrs(field.hir_id).is_empty() {
1155 self.cbox(INDENT_UNIT);
1156 self.print_outer_attributes(&self.attrs(field.hir_id));
1157 if !field.is_shorthand {
1158 self.print_ident(field.ident);
1159 self.word_space(":");
1161 self.print_expr(&field.expr);
1165 fn print_expr_tup(&mut self, exprs: &[hir::Expr<'_>]) {
1167 self.commasep_exprs(Inconsistent, exprs);
1168 if exprs.len() == 1 {
1174 fn print_expr_call(&mut self, func: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
1175 let prec = match func.kind {
1176 hir::ExprKind::Field(..) => parser::PREC_FORCE_PAREN,
1177 _ => parser::PREC_POSTFIX,
1180 self.print_expr_maybe_paren(func, prec);
1181 self.print_call_post(args)
1184 fn print_expr_method_call(&mut self, segment: &hir::PathSegment<'_>, args: &[hir::Expr<'_>]) {
1185 let base_args = &args[1..];
1186 self.print_expr_maybe_paren(&args[0], parser::PREC_POSTFIX);
1188 self.print_ident(segment.ident);
1190 let generic_args = segment.args();
1191 if !generic_args.args.is_empty() || !generic_args.bindings.is_empty() {
1192 self.print_generic_args(generic_args, segment.infer_args, true);
1195 self.print_call_post(base_args)
1198 fn print_expr_binary(&mut self, op: hir::BinOp, lhs: &hir::Expr<'_>, rhs: &hir::Expr<'_>) {
1199 let assoc_op = bin_op_to_assoc_op(op.node);
1200 let prec = assoc_op.precedence() as i8;
1201 let fixity = assoc_op.fixity();
1203 let (left_prec, right_prec) = match fixity {
1204 Fixity::Left => (prec, prec + 1),
1205 Fixity::Right => (prec + 1, prec),
1206 Fixity::None => (prec + 1, prec + 1),
1209 let left_prec = match (&lhs.kind, op.node) {
1210 // These cases need parens: `x as i32 < y` has the parser thinking that `i32 < y` is
1211 // the beginning of a path type. It starts trying to parse `x as (i32 < y ...` instead
1212 // of `(x as i32) < ...`. We need to convince it _not_ to do that.
1213 (&hir::ExprKind::Cast { .. }, hir::BinOpKind::Lt | hir::BinOpKind::Shl) => {
1214 parser::PREC_FORCE_PAREN
1216 (&hir::ExprKind::Let { .. }, _) if !parser::needs_par_as_let_scrutinee(prec) => {
1217 parser::PREC_FORCE_PAREN
1222 self.print_expr_maybe_paren(lhs, left_prec);
1224 self.word_space(op.node.as_str());
1225 self.print_expr_maybe_paren(rhs, right_prec)
1228 fn print_expr_unary(&mut self, op: hir::UnOp, expr: &hir::Expr<'_>) {
1229 self.word(op.as_str());
1230 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1233 fn print_expr_addr_of(
1235 kind: hir::BorrowKind,
1236 mutability: hir::Mutability,
1237 expr: &hir::Expr<'_>,
1241 hir::BorrowKind::Ref => self.print_mutability(mutability, false),
1242 hir::BorrowKind::Raw => {
1243 self.word_nbsp("raw");
1244 self.print_mutability(mutability, true);
1247 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1250 fn print_literal(&mut self, lit: &hir::Lit) {
1251 self.maybe_print_comment(lit.span.lo());
1252 self.word(lit.node.to_token_lit().to_string())
1255 fn print_inline_asm(&mut self, asm: &hir::InlineAsm<'_>) {
1258 Operand(&'a hir::InlineAsmOperand<'a>),
1259 Options(ast::InlineAsmOptions),
1262 let mut args = vec![AsmArg::Template(ast::InlineAsmTemplatePiece::to_string(asm.template))];
1263 args.extend(asm.operands.iter().map(|(o, _)| AsmArg::Operand(o)));
1264 if !asm.options.is_empty() {
1265 args.push(AsmArg::Options(asm.options));
1269 self.commasep(Consistent, &args, |s, arg| match *arg {
1270 AsmArg::Template(ref template) => s.print_string(template, ast::StrStyle::Cooked),
1271 AsmArg::Operand(op) => match *op {
1272 hir::InlineAsmOperand::In { reg, ref expr } => {
1275 s.word(format!("{}", reg));
1280 hir::InlineAsmOperand::Out { reg, late, ref expr } => {
1281 s.word(if late { "lateout" } else { "out" });
1283 s.word(format!("{}", reg));
1287 Some(expr) => s.print_expr(expr),
1288 None => s.word("_"),
1291 hir::InlineAsmOperand::InOut { reg, late, ref expr } => {
1292 s.word(if late { "inlateout" } else { "inout" });
1294 s.word(format!("{}", reg));
1299 hir::InlineAsmOperand::SplitInOut { reg, late, ref in_expr, ref out_expr } => {
1300 s.word(if late { "inlateout" } else { "inout" });
1302 s.word(format!("{}", reg));
1305 s.print_expr(in_expr);
1309 Some(out_expr) => s.print_expr(out_expr),
1310 None => s.word("_"),
1313 hir::InlineAsmOperand::Const { ref anon_const } => {
1316 s.print_anon_const(anon_const);
1318 hir::InlineAsmOperand::SymFn { ref anon_const } => {
1321 s.print_anon_const(anon_const);
1323 hir::InlineAsmOperand::SymStatic { ref path, def_id: _ } => {
1324 s.word("sym_static");
1326 s.print_qpath(path, true);
1329 AsmArg::Options(opts) => {
1332 let mut options = vec![];
1333 if opts.contains(ast::InlineAsmOptions::PURE) {
1334 options.push("pure");
1336 if opts.contains(ast::InlineAsmOptions::NOMEM) {
1337 options.push("nomem");
1339 if opts.contains(ast::InlineAsmOptions::READONLY) {
1340 options.push("readonly");
1342 if opts.contains(ast::InlineAsmOptions::PRESERVES_FLAGS) {
1343 options.push("preserves_flags");
1345 if opts.contains(ast::InlineAsmOptions::NORETURN) {
1346 options.push("noreturn");
1348 if opts.contains(ast::InlineAsmOptions::NOSTACK) {
1349 options.push("nostack");
1351 if opts.contains(ast::InlineAsmOptions::ATT_SYNTAX) {
1352 options.push("att_syntax");
1354 if opts.contains(ast::InlineAsmOptions::RAW) {
1355 options.push("raw");
1357 if opts.contains(ast::InlineAsmOptions::MAY_UNWIND) {
1358 options.push("may_unwind");
1360 s.commasep(Inconsistent, &options, |s, &opt| {
1369 pub fn print_expr(&mut self, expr: &hir::Expr<'_>) {
1370 self.maybe_print_comment(expr.span.lo());
1371 self.print_outer_attributes(self.attrs(expr.hir_id));
1372 self.ibox(INDENT_UNIT);
1373 self.ann.pre(self, AnnNode::Expr(expr));
1375 hir::ExprKind::Box(expr) => {
1376 self.word_space("box");
1377 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX);
1379 hir::ExprKind::Array(exprs) => {
1380 self.print_expr_vec(exprs);
1382 hir::ExprKind::ConstBlock(ref anon_const) => {
1383 self.print_expr_anon_const(anon_const);
1385 hir::ExprKind::Repeat(element, ref count) => {
1386 self.print_expr_repeat(element, count);
1388 hir::ExprKind::Struct(qpath, fields, wth) => {
1389 self.print_expr_struct(qpath, fields, wth);
1391 hir::ExprKind::Tup(exprs) => {
1392 self.print_expr_tup(exprs);
1394 hir::ExprKind::Call(func, args) => {
1395 self.print_expr_call(func, args);
1397 hir::ExprKind::MethodCall(segment, args, _) => {
1398 self.print_expr_method_call(segment, args);
1400 hir::ExprKind::Binary(op, lhs, rhs) => {
1401 self.print_expr_binary(op, lhs, rhs);
1403 hir::ExprKind::Unary(op, expr) => {
1404 self.print_expr_unary(op, expr);
1406 hir::ExprKind::AddrOf(k, m, expr) => {
1407 self.print_expr_addr_of(k, m, expr);
1409 hir::ExprKind::Lit(ref lit) => {
1410 self.print_literal(lit);
1412 hir::ExprKind::Cast(expr, ty) => {
1413 let prec = AssocOp::As.precedence() as i8;
1414 self.print_expr_maybe_paren(expr, prec);
1416 self.word_space("as");
1417 self.print_type(ty);
1419 hir::ExprKind::Type(expr, ty) => {
1420 let prec = AssocOp::Colon.precedence() as i8;
1421 self.print_expr_maybe_paren(expr, prec);
1422 self.word_space(":");
1423 self.print_type(ty);
1425 hir::ExprKind::DropTemps(init) => {
1427 self.cbox(INDENT_UNIT);
1431 // Print `let _t = $init;`:
1432 let temp = Ident::from_str("_t");
1433 self.print_local(Some(init), None, |this| this.print_ident(temp));
1437 self.space_if_not_bol();
1438 self.print_ident(temp);
1441 self.bclose_maybe_open(expr.span, true);
1443 hir::ExprKind::Let(&hir::Let { pat, ty, init, .. }) => {
1444 self.print_let(pat, ty, init);
1446 hir::ExprKind::If(test, blk, elseopt) => {
1447 self.print_if(test, blk, elseopt);
1449 hir::ExprKind::Loop(blk, opt_label, _, _) => {
1450 if let Some(label) = opt_label {
1451 self.print_ident(label.ident);
1452 self.word_space(":");
1455 self.print_block(blk);
1457 hir::ExprKind::Match(expr, arms, _) => {
1458 self.cbox(INDENT_UNIT);
1459 self.ibox(INDENT_UNIT);
1460 self.word_nbsp("match");
1461 self.print_expr_as_cond(expr);
1465 self.print_arm(arm);
1467 self.bclose(expr.span);
1469 hir::ExprKind::Closure(&hir::Closure {
1472 bound_generic_params,
1478 self.print_closure_binder(binder, bound_generic_params);
1479 self.print_capture_clause(capture_clause);
1481 self.print_closure_params(fn_decl, body);
1484 // This is a bare expression.
1485 self.ann.nested(self, Nested::Body(body));
1486 self.end(); // need to close a box
1488 // A box will be closed by `print_expr`, but we didn't want an overall
1489 // wrapper so we closed the corresponding opening. so create an
1490 // empty box to satisfy the close.
1493 hir::ExprKind::Block(blk, opt_label) => {
1494 if let Some(label) = opt_label {
1495 self.print_ident(label.ident);
1496 self.word_space(":");
1498 // containing cbox, will be closed by print-block at `}`
1499 self.cbox(INDENT_UNIT);
1500 // head-box, will be closed by print-block after `{`
1502 self.print_block(blk);
1504 hir::ExprKind::Assign(lhs, rhs, _) => {
1505 let prec = AssocOp::Assign.precedence() as i8;
1506 self.print_expr_maybe_paren(lhs, prec + 1);
1508 self.word_space("=");
1509 self.print_expr_maybe_paren(rhs, prec);
1511 hir::ExprKind::AssignOp(op, lhs, rhs) => {
1512 let prec = AssocOp::Assign.precedence() as i8;
1513 self.print_expr_maybe_paren(lhs, prec + 1);
1515 self.word(op.node.as_str());
1516 self.word_space("=");
1517 self.print_expr_maybe_paren(rhs, prec);
1519 hir::ExprKind::Field(expr, ident) => {
1520 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
1522 self.print_ident(ident);
1524 hir::ExprKind::Index(expr, index) => {
1525 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
1527 self.print_expr(index);
1530 hir::ExprKind::Path(ref qpath) => self.print_qpath(qpath, true),
1531 hir::ExprKind::Break(destination, opt_expr) => {
1533 if let Some(label) = destination.label {
1535 self.print_ident(label.ident);
1537 if let Some(expr) = opt_expr {
1539 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
1542 hir::ExprKind::Continue(destination) => {
1543 self.word("continue");
1544 if let Some(label) = destination.label {
1546 self.print_ident(label.ident);
1549 hir::ExprKind::Ret(result) => {
1550 self.word("return");
1551 if let Some(expr) = result {
1553 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
1556 hir::ExprKind::InlineAsm(asm) => {
1558 self.print_inline_asm(asm);
1560 hir::ExprKind::Yield(expr, _) => {
1561 self.word_space("yield");
1562 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
1564 hir::ExprKind::Err => {
1566 self.word("/*ERROR*/");
1570 self.ann.post(self, AnnNode::Expr(expr));
1574 pub fn print_local_decl(&mut self, loc: &hir::Local<'_>) {
1575 self.print_pat(loc.pat);
1576 if let Some(ty) = loc.ty {
1577 self.word_space(":");
1578 self.print_type(ty);
1582 pub fn print_name(&mut self, name: Symbol) {
1583 self.print_ident(Ident::with_dummy_span(name))
1586 pub fn print_path(&mut self, path: &hir::Path<'_>, colons_before_params: bool) {
1587 self.maybe_print_comment(path.span.lo());
1589 for (i, segment) in path.segments.iter().enumerate() {
1593 if segment.ident.name != kw::PathRoot {
1594 self.print_ident(segment.ident);
1595 self.print_generic_args(segment.args(), segment.infer_args, colons_before_params);
1600 pub fn print_path_segment(&mut self, segment: &hir::PathSegment<'_>) {
1601 if segment.ident.name != kw::PathRoot {
1602 self.print_ident(segment.ident);
1603 self.print_generic_args(segment.args(), segment.infer_args, false);
1607 pub fn print_qpath(&mut self, qpath: &hir::QPath<'_>, colons_before_params: bool) {
1609 hir::QPath::Resolved(None, path) => self.print_path(path, colons_before_params),
1610 hir::QPath::Resolved(Some(qself), path) => {
1612 self.print_type(qself);
1614 self.word_space("as");
1616 for (i, segment) in path.segments[..path.segments.len() - 1].iter().enumerate() {
1620 if segment.ident.name != kw::PathRoot {
1621 self.print_ident(segment.ident);
1622 self.print_generic_args(
1625 colons_before_params,
1632 let item_segment = path.segments.last().unwrap();
1633 self.print_ident(item_segment.ident);
1634 self.print_generic_args(
1635 item_segment.args(),
1636 item_segment.infer_args,
1637 colons_before_params,
1640 hir::QPath::TypeRelative(qself, item_segment) => {
1641 // If we've got a compound-qualified-path, let's push an additional pair of angle
1642 // brackets, so that we pretty-print `<<A::B>::C>` as `<A::B>::C`, instead of just
1643 // `A::B::C` (since the latter could be ambiguous to the user)
1644 if let hir::TyKind::Path(hir::QPath::Resolved(None, _)) = qself.kind {
1645 self.print_type(qself);
1648 self.print_type(qself);
1653 self.print_ident(item_segment.ident);
1654 self.print_generic_args(
1655 item_segment.args(),
1656 item_segment.infer_args,
1657 colons_before_params,
1660 hir::QPath::LangItem(lang_item, span, _) => {
1661 self.word("#[lang = \"");
1662 self.print_ident(Ident::new(lang_item.name(), span));
1668 fn print_generic_args(
1670 generic_args: &hir::GenericArgs<'_>,
1672 colons_before_params: bool,
1674 if generic_args.parenthesized {
1676 self.commasep(Inconsistent, generic_args.inputs(), |s, ty| s.print_type(ty));
1679 self.space_if_not_bol();
1680 self.word_space("->");
1681 self.print_type(generic_args.bindings[0].ty());
1683 let start = if colons_before_params { "::<" } else { "<" };
1684 let empty = Cell::new(true);
1685 let start_or_comma = |this: &mut Self| {
1690 this.word_space(",")
1694 let mut nonelided_generic_args: bool = false;
1695 let elide_lifetimes = generic_args.args.iter().all(|arg| match arg {
1696 GenericArg::Lifetime(lt) => lt.is_elided(),
1698 nonelided_generic_args = true;
1703 if nonelided_generic_args {
1704 start_or_comma(self);
1708 |s, generic_arg| match generic_arg {
1709 GenericArg::Lifetime(lt) if !elide_lifetimes => s.print_lifetime(lt),
1710 GenericArg::Lifetime(_) => {}
1711 GenericArg::Type(ty) => s.print_type(ty),
1712 GenericArg::Const(ct) => s.print_anon_const(&ct.value),
1713 GenericArg::Infer(_inf) => s.word("_"),
1718 // FIXME(eddyb): this would leak into error messages (e.g.,
1719 // "non-exhaustive patterns: `Some::<..>(_)` not covered").
1720 if infer_args && false {
1721 start_or_comma(self);
1725 for binding in generic_args.bindings {
1726 start_or_comma(self);
1727 self.print_type_binding(binding);
1736 pub fn print_type_binding(&mut self, binding: &hir::TypeBinding<'_>) {
1737 self.print_ident(binding.ident);
1738 self.print_generic_args(binding.gen_args, false, false);
1740 match binding.kind {
1741 hir::TypeBindingKind::Equality { ref term } => {
1742 self.word_space("=");
1744 Term::Ty(ty) => self.print_type(ty),
1745 Term::Const(ref c) => self.print_anon_const(c),
1748 hir::TypeBindingKind::Constraint { bounds } => {
1749 self.print_bounds(":", bounds);
1754 pub fn print_pat(&mut self, pat: &hir::Pat<'_>) {
1755 self.maybe_print_comment(pat.span.lo());
1756 self.ann.pre(self, AnnNode::Pat(pat));
1757 // Pat isn't normalized, but the beauty of it
1758 // is that it doesn't matter
1760 PatKind::Wild => self.word("_"),
1761 PatKind::Binding(binding_mode, _, ident, sub) => {
1762 match binding_mode {
1763 hir::BindingAnnotation::Ref => {
1764 self.word_nbsp("ref");
1765 self.print_mutability(hir::Mutability::Not, false);
1767 hir::BindingAnnotation::RefMut => {
1768 self.word_nbsp("ref");
1769 self.print_mutability(hir::Mutability::Mut, false);
1771 hir::BindingAnnotation::Unannotated => {}
1772 hir::BindingAnnotation::Mutable => {
1773 self.word_nbsp("mut");
1776 self.print_ident(ident);
1777 if let Some(p) = sub {
1782 PatKind::TupleStruct(ref qpath, elts, ddpos) => {
1783 self.print_qpath(qpath, true);
1785 if let Some(ddpos) = ddpos {
1786 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(p));
1788 self.word_space(",");
1791 if ddpos != elts.len() {
1793 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(p));
1796 self.commasep(Inconsistent, elts, |s, p| s.print_pat(p));
1800 PatKind::Path(ref qpath) => {
1801 self.print_qpath(qpath, true);
1803 PatKind::Struct(ref qpath, fields, etc) => {
1804 self.print_qpath(qpath, true);
1807 let empty = fields.is_empty() && !etc;
1811 self.commasep_cmnt(Consistent, &fields, |s, f| s.print_patfield(f), |f| f.pat.span);
1813 if !fields.is_empty() {
1814 self.word_space(",");
1823 PatKind::Or(pats) => {
1824 self.strsep("|", true, Inconsistent, pats, |s, p| s.print_pat(p));
1826 PatKind::Tuple(elts, ddpos) => {
1828 if let Some(ddpos) = ddpos {
1829 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(p));
1831 self.word_space(",");
1834 if ddpos != elts.len() {
1836 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(p));
1839 self.commasep(Inconsistent, elts, |s, p| s.print_pat(p));
1840 if elts.len() == 1 {
1846 PatKind::Box(inner) => {
1847 let is_range_inner = matches!(inner.kind, PatKind::Range(..));
1852 self.print_pat(inner);
1857 PatKind::Ref(inner, mutbl) => {
1858 let is_range_inner = matches!(inner.kind, PatKind::Range(..));
1860 self.word(mutbl.prefix_str());
1864 self.print_pat(inner);
1869 PatKind::Lit(e) => self.print_expr(e),
1870 PatKind::Range(begin, end, end_kind) => {
1871 if let Some(expr) = begin {
1872 self.print_expr(expr);
1875 RangeEnd::Included => self.word("..."),
1876 RangeEnd::Excluded => self.word(".."),
1878 if let Some(expr) = end {
1879 self.print_expr(expr);
1882 PatKind::Slice(before, slice, after) => {
1884 self.commasep(Inconsistent, before, |s, p| s.print_pat(p));
1885 if let Some(p) = slice {
1886 if !before.is_empty() {
1887 self.word_space(",");
1889 if let PatKind::Wild = p.kind {
1895 if !after.is_empty() {
1896 self.word_space(",");
1899 self.commasep(Inconsistent, after, |s, p| s.print_pat(p));
1903 self.ann.post(self, AnnNode::Pat(pat))
1906 pub fn print_patfield(&mut self, field: &hir::PatField<'_>) {
1907 if self.attrs(field.hir_id).is_empty() {
1910 self.cbox(INDENT_UNIT);
1911 self.print_outer_attributes(&self.attrs(field.hir_id));
1912 if !field.is_shorthand {
1913 self.print_ident(field.ident);
1914 self.word_nbsp(":");
1916 self.print_pat(field.pat);
1920 pub fn print_param(&mut self, arg: &hir::Param<'_>) {
1921 self.print_outer_attributes(self.attrs(arg.hir_id));
1922 self.print_pat(arg.pat);
1925 pub fn print_arm(&mut self, arm: &hir::Arm<'_>) {
1926 // I have no idea why this check is necessary, but here it
1928 if self.attrs(arm.hir_id).is_empty() {
1931 self.cbox(INDENT_UNIT);
1932 self.ann.pre(self, AnnNode::Arm(arm));
1934 self.print_outer_attributes(self.attrs(arm.hir_id));
1935 self.print_pat(arm.pat);
1937 if let Some(ref g) = arm.guard {
1939 hir::Guard::If(e) => {
1940 self.word_space("if");
1944 hir::Guard::IfLet(&hir::Let { pat, ty, init, .. }) => {
1945 self.word_nbsp("if");
1946 self.print_let(pat, ty, init);
1950 self.word_space("=>");
1952 match arm.body.kind {
1953 hir::ExprKind::Block(blk, opt_label) => {
1954 if let Some(label) = opt_label {
1955 self.print_ident(label.ident);
1956 self.word_space(":");
1958 // the block will close the pattern's ibox
1959 self.print_block_unclosed(blk);
1961 // If it is a user-provided unsafe block, print a comma after it
1962 if let hir::BlockCheckMode::UnsafeBlock(hir::UnsafeSource::UserProvided) = blk.rules
1968 self.end(); // close the ibox for the pattern
1969 self.print_expr(arm.body);
1973 self.ann.post(self, AnnNode::Arm(arm));
1974 self.end() // close enclosing cbox
1979 decl: &hir::FnDecl<'_>,
1980 header: hir::FnHeader,
1981 name: Option<Symbol>,
1982 generics: &hir::Generics<'_>,
1983 arg_names: &[Ident],
1984 body_id: Option<hir::BodyId>,
1986 self.print_fn_header_info(header);
1988 if let Some(name) = name {
1990 self.print_name(name);
1992 self.print_generic_params(generics.params);
1996 // Make sure we aren't supplied *both* `arg_names` and `body_id`.
1997 assert!(arg_names.is_empty() || body_id.is_none());
1998 self.commasep(Inconsistent, decl.inputs, |s, ty| {
1999 s.ibox(INDENT_UNIT);
2000 if let Some(arg_name) = arg_names.get(i) {
2001 s.word(arg_name.to_string());
2004 } else if let Some(body_id) = body_id {
2005 s.ann.nested(s, Nested::BodyParamPat(body_id, i));
2013 if decl.c_variadic {
2018 self.print_fn_output(decl);
2019 self.print_where_clause(generics)
2022 fn print_closure_params(&mut self, decl: &hir::FnDecl<'_>, body_id: hir::BodyId) {
2025 self.commasep(Inconsistent, decl.inputs, |s, ty| {
2026 s.ibox(INDENT_UNIT);
2028 s.ann.nested(s, Nested::BodyParamPat(body_id, i));
2031 if let hir::TyKind::Infer = ty.kind {
2042 if let hir::FnRetTy::DefaultReturn(..) = decl.output {
2046 self.space_if_not_bol();
2047 self.word_space("->");
2049 hir::FnRetTy::Return(ty) => {
2050 self.print_type(ty);
2051 self.maybe_print_comment(ty.span.lo());
2053 hir::FnRetTy::DefaultReturn(..) => unreachable!(),
2057 pub fn print_capture_clause(&mut self, capture_clause: hir::CaptureBy) {
2058 match capture_clause {
2059 hir::CaptureBy::Value => self.word_space("move"),
2060 hir::CaptureBy::Ref => {}
2064 pub fn print_closure_binder(
2066 binder: hir::ClosureBinder,
2067 generic_params: &[GenericParam<'_>],
2069 let generic_params = generic_params
2075 kind: GenericParamKind::Lifetime { kind: LifetimeParamKind::Explicit },
2080 .collect::<Vec<_>>();
2083 hir::ClosureBinder::Default => {}
2084 // we need to distinguish `|...| {}` from `for<> |...| {}` as `for<>` adds additional restrictions
2085 hir::ClosureBinder::For { .. } if generic_params.is_empty() => self.word("for<>"),
2086 hir::ClosureBinder::For { .. } => {
2090 self.commasep(Inconsistent, &generic_params, |s, param| {
2091 s.print_generic_param(param)
2100 pub fn print_bounds<'b>(
2102 prefix: &'static str,
2103 bounds: impl IntoIterator<Item = &'b hir::GenericBound<'b>>,
2105 let mut first = true;
2106 for bound in bounds {
2110 if !(first && prefix.is_empty()) {
2116 self.word_space("+");
2120 GenericBound::Trait(tref, modifier) => {
2121 if modifier == &TraitBoundModifier::Maybe {
2124 self.print_poly_trait_ref(tref);
2126 GenericBound::LangItemTrait(lang_item, span, ..) => {
2127 self.word("#[lang = \"");
2128 self.print_ident(Ident::new(lang_item.name(), *span));
2131 GenericBound::Outlives(lt) => {
2132 self.print_lifetime(lt);
2138 pub fn print_generic_params(&mut self, generic_params: &[GenericParam<'_>]) {
2139 if !generic_params.is_empty() {
2142 self.commasep(Inconsistent, generic_params, |s, param| s.print_generic_param(param));
2148 pub fn print_generic_param(&mut self, param: &GenericParam<'_>) {
2149 if let GenericParamKind::Const { .. } = param.kind {
2150 self.word_space("const");
2153 self.print_ident(param.name.ident());
2156 GenericParamKind::Lifetime { .. } => {}
2157 GenericParamKind::Type { default, .. } => {
2158 if let Some(default) = default {
2160 self.word_space("=");
2161 self.print_type(default);
2164 GenericParamKind::Const { ty, ref default } => {
2165 self.word_space(":");
2166 self.print_type(ty);
2167 if let Some(default) = default {
2169 self.word_space("=");
2170 self.print_anon_const(default);
2176 pub fn print_lifetime(&mut self, lifetime: &hir::Lifetime) {
2177 self.print_ident(lifetime.name.ident())
2180 pub fn print_where_clause(&mut self, generics: &hir::Generics<'_>) {
2181 if generics.predicates.is_empty() {
2186 self.word_space("where");
2188 for (i, predicate) in generics.predicates.iter().enumerate() {
2190 self.word_space(",");
2194 hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
2195 bound_generic_params,
2200 self.print_formal_generic_params(bound_generic_params);
2201 self.print_type(bounded_ty);
2202 self.print_bounds(":", bounds);
2204 hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
2209 self.print_lifetime(lifetime);
2212 for (i, bound) in bounds.iter().enumerate() {
2214 GenericBound::Outlives(lt) => {
2215 self.print_lifetime(lt);
2225 hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
2228 self.print_type(lhs_ty);
2230 self.word_space("=");
2231 self.print_type(rhs_ty);
2237 pub fn print_mutability(&mut self, mutbl: hir::Mutability, print_const: bool) {
2239 hir::Mutability::Mut => self.word_nbsp("mut"),
2240 hir::Mutability::Not => {
2242 self.word_nbsp("const")
2248 pub fn print_mt(&mut self, mt: &hir::MutTy<'_>, print_const: bool) {
2249 self.print_mutability(mt.mutbl, print_const);
2250 self.print_type(mt.ty);
2253 pub fn print_fn_output(&mut self, decl: &hir::FnDecl<'_>) {
2254 if let hir::FnRetTy::DefaultReturn(..) = decl.output {
2258 self.space_if_not_bol();
2259 self.ibox(INDENT_UNIT);
2260 self.word_space("->");
2262 hir::FnRetTy::DefaultReturn(..) => unreachable!(),
2263 hir::FnRetTy::Return(ty) => self.print_type(ty),
2267 if let hir::FnRetTy::Return(output) = decl.output {
2268 self.maybe_print_comment(output.span.lo());
2275 unsafety: hir::Unsafety,
2276 decl: &hir::FnDecl<'_>,
2277 name: Option<Symbol>,
2278 generic_params: &[hir::GenericParam<'_>],
2279 arg_names: &[Ident],
2281 self.ibox(INDENT_UNIT);
2282 self.print_formal_generic_params(generic_params);
2283 let generics = hir::Generics::empty();
2289 constness: hir::Constness::NotConst,
2290 asyncness: hir::IsAsync::NotAsync,
2300 pub fn print_fn_header_info(&mut self, header: hir::FnHeader) {
2301 match header.constness {
2302 hir::Constness::NotConst => {}
2303 hir::Constness::Const => self.word_nbsp("const"),
2306 match header.asyncness {
2307 hir::IsAsync::NotAsync => {}
2308 hir::IsAsync::Async => self.word_nbsp("async"),
2311 self.print_unsafety(header.unsafety);
2313 if header.abi != Abi::Rust {
2314 self.word_nbsp("extern");
2315 self.word_nbsp(header.abi.to_string());
2321 pub fn print_unsafety(&mut self, s: hir::Unsafety) {
2323 hir::Unsafety::Normal => {}
2324 hir::Unsafety::Unsafe => self.word_nbsp("unsafe"),
2328 pub fn print_is_auto(&mut self, s: hir::IsAuto) {
2330 hir::IsAuto::Yes => self.word_nbsp("auto"),
2331 hir::IsAuto::No => {}
2336 /// Does this expression require a semicolon to be treated
2337 /// as a statement? The negation of this: 'can this expression
2338 /// be used as a statement without a semicolon' -- is used
2339 /// as an early-bail-out in the parser so that, for instance,
2340 /// if true {...} else {...}
2342 /// isn't parsed as (if true {...} else {...} | x) | 5
2344 // Duplicated from `parse::classify`, but adapted for the HIR.
2345 fn expr_requires_semi_to_be_stmt(e: &hir::Expr<'_>) -> bool {
2348 hir::ExprKind::If(..)
2349 | hir::ExprKind::Match(..)
2350 | hir::ExprKind::Block(..)
2351 | hir::ExprKind::Loop(..)
2355 /// This statement requires a semicolon after it.
2356 /// note that in one case (stmt_semi), we've already
2357 /// seen the semicolon, and thus don't need another.
2358 fn stmt_ends_with_semi(stmt: &hir::StmtKind<'_>) -> bool {
2360 hir::StmtKind::Local(_) => true,
2361 hir::StmtKind::Item(_) => false,
2362 hir::StmtKind::Expr(e) => expr_requires_semi_to_be_stmt(e),
2363 hir::StmtKind::Semi(..) => false,
2367 fn bin_op_to_assoc_op(op: hir::BinOpKind) -> AssocOp {
2368 use crate::hir::BinOpKind::*;
2370 Add => AssocOp::Add,
2371 Sub => AssocOp::Subtract,
2372 Mul => AssocOp::Multiply,
2373 Div => AssocOp::Divide,
2374 Rem => AssocOp::Modulus,
2376 And => AssocOp::LAnd,
2379 BitXor => AssocOp::BitXor,
2380 BitAnd => AssocOp::BitAnd,
2381 BitOr => AssocOp::BitOr,
2382 Shl => AssocOp::ShiftLeft,
2383 Shr => AssocOp::ShiftRight,
2385 Eq => AssocOp::Equal,
2386 Lt => AssocOp::Less,
2387 Le => AssocOp::LessEqual,
2388 Ne => AssocOp::NotEqual,
2389 Ge => AssocOp::GreaterEqual,
2390 Gt => AssocOp::Greater,
2394 /// Expressions that syntactically contain an "exterior" struct literal, i.e., not surrounded by any
2395 /// parens or other delimiters, e.g., `X { y: 1 }`, `X { y: 1 }.method()`, `foo == X { y: 1 }` and
2396 /// `X { y: 1 } == foo` all do, but `(X { y: 1 }) == foo` does not.
2397 fn contains_exterior_struct_lit(value: &hir::Expr<'_>) -> bool {
2399 hir::ExprKind::Struct(..) => true,
2401 hir::ExprKind::Assign(lhs, rhs, _)
2402 | hir::ExprKind::AssignOp(_, lhs, rhs)
2403 | hir::ExprKind::Binary(_, lhs, rhs) => {
2404 // `X { y: 1 } + X { y: 2 }`
2405 contains_exterior_struct_lit(lhs) || contains_exterior_struct_lit(rhs)
2407 hir::ExprKind::Unary(_, x)
2408 | hir::ExprKind::Cast(x, _)
2409 | hir::ExprKind::Type(x, _)
2410 | hir::ExprKind::Field(x, _)
2411 | hir::ExprKind::Index(x, _) => {
2412 // `&X { y: 1 }, X { y: 1 }.y`
2413 contains_exterior_struct_lit(x)
2416 hir::ExprKind::MethodCall(.., exprs, _) => {
2417 // `X { y: 1 }.bar(...)`
2418 contains_exterior_struct_lit(&exprs[0])