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(
1186 segment: &hir::PathSegment<'_>,
1187 receiver: &hir::Expr<'_>,
1188 args: &[hir::Expr<'_>],
1190 let base_args = args;
1191 self.print_expr_maybe_paren(&receiver, parser::PREC_POSTFIX);
1193 self.print_ident(segment.ident);
1195 let generic_args = segment.args();
1196 if !generic_args.args.is_empty() || !generic_args.bindings.is_empty() {
1197 self.print_generic_args(generic_args, true);
1200 self.print_call_post(base_args)
1203 fn print_expr_binary(&mut self, op: hir::BinOp, lhs: &hir::Expr<'_>, rhs: &hir::Expr<'_>) {
1204 let assoc_op = bin_op_to_assoc_op(op.node);
1205 let prec = assoc_op.precedence() as i8;
1206 let fixity = assoc_op.fixity();
1208 let (left_prec, right_prec) = match fixity {
1209 Fixity::Left => (prec, prec + 1),
1210 Fixity::Right => (prec + 1, prec),
1211 Fixity::None => (prec + 1, prec + 1),
1214 let left_prec = match (&lhs.kind, op.node) {
1215 // These cases need parens: `x as i32 < y` has the parser thinking that `i32 < y` is
1216 // the beginning of a path type. It starts trying to parse `x as (i32 < y ...` instead
1217 // of `(x as i32) < ...`. We need to convince it _not_ to do that.
1218 (&hir::ExprKind::Cast { .. }, hir::BinOpKind::Lt | hir::BinOpKind::Shl) => {
1219 parser::PREC_FORCE_PAREN
1221 (&hir::ExprKind::Let { .. }, _) if !parser::needs_par_as_let_scrutinee(prec) => {
1222 parser::PREC_FORCE_PAREN
1227 self.print_expr_maybe_paren(lhs, left_prec);
1229 self.word_space(op.node.as_str());
1230 self.print_expr_maybe_paren(rhs, right_prec)
1233 fn print_expr_unary(&mut self, op: hir::UnOp, expr: &hir::Expr<'_>) {
1234 self.word(op.as_str());
1235 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1238 fn print_expr_addr_of(
1240 kind: hir::BorrowKind,
1241 mutability: hir::Mutability,
1242 expr: &hir::Expr<'_>,
1246 hir::BorrowKind::Ref => self.print_mutability(mutability, false),
1247 hir::BorrowKind::Raw => {
1248 self.word_nbsp("raw");
1249 self.print_mutability(mutability, true);
1252 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1255 fn print_literal(&mut self, lit: &hir::Lit) {
1256 self.maybe_print_comment(lit.span.lo());
1257 self.word(lit.node.to_token_lit().to_string())
1260 fn print_inline_asm(&mut self, asm: &hir::InlineAsm<'_>) {
1263 Operand(&'a hir::InlineAsmOperand<'a>),
1264 Options(ast::InlineAsmOptions),
1267 let mut args = vec![AsmArg::Template(ast::InlineAsmTemplatePiece::to_string(asm.template))];
1268 args.extend(asm.operands.iter().map(|(o, _)| AsmArg::Operand(o)));
1269 if !asm.options.is_empty() {
1270 args.push(AsmArg::Options(asm.options));
1274 self.commasep(Consistent, &args, |s, arg| match *arg {
1275 AsmArg::Template(ref template) => s.print_string(template, ast::StrStyle::Cooked),
1276 AsmArg::Operand(op) => match *op {
1277 hir::InlineAsmOperand::In { reg, ref expr } => {
1280 s.word(format!("{}", reg));
1285 hir::InlineAsmOperand::Out { reg, late, ref expr } => {
1286 s.word(if late { "lateout" } else { "out" });
1288 s.word(format!("{}", reg));
1292 Some(expr) => s.print_expr(expr),
1293 None => s.word("_"),
1296 hir::InlineAsmOperand::InOut { reg, late, ref expr } => {
1297 s.word(if late { "inlateout" } else { "inout" });
1299 s.word(format!("{}", reg));
1304 hir::InlineAsmOperand::SplitInOut { reg, late, ref in_expr, ref out_expr } => {
1305 s.word(if late { "inlateout" } else { "inout" });
1307 s.word(format!("{}", reg));
1310 s.print_expr(in_expr);
1314 Some(out_expr) => s.print_expr(out_expr),
1315 None => s.word("_"),
1318 hir::InlineAsmOperand::Const { ref anon_const } => {
1321 s.print_anon_const(anon_const);
1323 hir::InlineAsmOperand::SymFn { ref anon_const } => {
1326 s.print_anon_const(anon_const);
1328 hir::InlineAsmOperand::SymStatic { ref path, def_id: _ } => {
1329 s.word("sym_static");
1331 s.print_qpath(path, true);
1334 AsmArg::Options(opts) => {
1337 let mut options = vec![];
1338 if opts.contains(ast::InlineAsmOptions::PURE) {
1339 options.push("pure");
1341 if opts.contains(ast::InlineAsmOptions::NOMEM) {
1342 options.push("nomem");
1344 if opts.contains(ast::InlineAsmOptions::READONLY) {
1345 options.push("readonly");
1347 if opts.contains(ast::InlineAsmOptions::PRESERVES_FLAGS) {
1348 options.push("preserves_flags");
1350 if opts.contains(ast::InlineAsmOptions::NORETURN) {
1351 options.push("noreturn");
1353 if opts.contains(ast::InlineAsmOptions::NOSTACK) {
1354 options.push("nostack");
1356 if opts.contains(ast::InlineAsmOptions::ATT_SYNTAX) {
1357 options.push("att_syntax");
1359 if opts.contains(ast::InlineAsmOptions::RAW) {
1360 options.push("raw");
1362 if opts.contains(ast::InlineAsmOptions::MAY_UNWIND) {
1363 options.push("may_unwind");
1365 s.commasep(Inconsistent, &options, |s, &opt| {
1374 pub fn print_expr(&mut self, expr: &hir::Expr<'_>) {
1375 self.maybe_print_comment(expr.span.lo());
1376 self.print_outer_attributes(self.attrs(expr.hir_id));
1377 self.ibox(INDENT_UNIT);
1378 self.ann.pre(self, AnnNode::Expr(expr));
1380 hir::ExprKind::Box(expr) => {
1381 self.word_space("box");
1382 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX);
1384 hir::ExprKind::Array(exprs) => {
1385 self.print_expr_vec(exprs);
1387 hir::ExprKind::ConstBlock(ref anon_const) => {
1388 self.print_expr_anon_const(anon_const);
1390 hir::ExprKind::Repeat(element, ref count) => {
1391 self.print_expr_repeat(element, count);
1393 hir::ExprKind::Struct(qpath, fields, wth) => {
1394 self.print_expr_struct(qpath, fields, wth);
1396 hir::ExprKind::Tup(exprs) => {
1397 self.print_expr_tup(exprs);
1399 hir::ExprKind::Call(func, args) => {
1400 self.print_expr_call(func, args);
1402 hir::ExprKind::MethodCall(segment, receiver, args, _) => {
1403 self.print_expr_method_call(segment, receiver, args);
1405 hir::ExprKind::Binary(op, lhs, rhs) => {
1406 self.print_expr_binary(op, lhs, rhs);
1408 hir::ExprKind::Unary(op, expr) => {
1409 self.print_expr_unary(op, expr);
1411 hir::ExprKind::AddrOf(k, m, expr) => {
1412 self.print_expr_addr_of(k, m, expr);
1414 hir::ExprKind::Lit(ref lit) => {
1415 self.print_literal(lit);
1417 hir::ExprKind::Cast(expr, ty) => {
1418 let prec = AssocOp::As.precedence() as i8;
1419 self.print_expr_maybe_paren(expr, prec);
1421 self.word_space("as");
1422 self.print_type(ty);
1424 hir::ExprKind::Type(expr, ty) => {
1425 let prec = AssocOp::Colon.precedence() as i8;
1426 self.print_expr_maybe_paren(expr, prec);
1427 self.word_space(":");
1428 self.print_type(ty);
1430 hir::ExprKind::DropTemps(init) => {
1432 self.cbox(INDENT_UNIT);
1436 // Print `let _t = $init;`:
1437 let temp = Ident::from_str("_t");
1438 self.print_local(Some(init), None, |this| this.print_ident(temp));
1442 self.space_if_not_bol();
1443 self.print_ident(temp);
1446 self.bclose_maybe_open(expr.span, true);
1448 hir::ExprKind::Let(&hir::Let { pat, ty, init, .. }) => {
1449 self.print_let(pat, ty, init);
1451 hir::ExprKind::If(test, blk, elseopt) => {
1452 self.print_if(test, blk, elseopt);
1454 hir::ExprKind::Loop(blk, opt_label, _, _) => {
1455 if let Some(label) = opt_label {
1456 self.print_ident(label.ident);
1457 self.word_space(":");
1460 self.print_block(blk);
1462 hir::ExprKind::Match(expr, arms, _) => {
1463 self.cbox(INDENT_UNIT);
1464 self.ibox(INDENT_UNIT);
1465 self.word_nbsp("match");
1466 self.print_expr_as_cond(expr);
1470 self.print_arm(arm);
1472 self.bclose(expr.span);
1474 hir::ExprKind::Closure(&hir::Closure {
1477 bound_generic_params,
1483 self.print_closure_binder(binder, bound_generic_params);
1484 self.print_capture_clause(capture_clause);
1486 self.print_closure_params(fn_decl, body);
1489 // This is a bare expression.
1490 self.ann.nested(self, Nested::Body(body));
1491 self.end(); // need to close a box
1493 // A box will be closed by `print_expr`, but we didn't want an overall
1494 // wrapper so we closed the corresponding opening. so create an
1495 // empty box to satisfy the close.
1498 hir::ExprKind::Block(blk, opt_label) => {
1499 if let Some(label) = opt_label {
1500 self.print_ident(label.ident);
1501 self.word_space(":");
1503 // containing cbox, will be closed by print-block at `}`
1504 self.cbox(INDENT_UNIT);
1505 // head-box, will be closed by print-block after `{`
1507 self.print_block(blk);
1509 hir::ExprKind::Assign(lhs, rhs, _) => {
1510 let prec = AssocOp::Assign.precedence() as i8;
1511 self.print_expr_maybe_paren(lhs, prec + 1);
1513 self.word_space("=");
1514 self.print_expr_maybe_paren(rhs, prec);
1516 hir::ExprKind::AssignOp(op, lhs, rhs) => {
1517 let prec = AssocOp::Assign.precedence() as i8;
1518 self.print_expr_maybe_paren(lhs, prec + 1);
1520 self.word(op.node.as_str());
1521 self.word_space("=");
1522 self.print_expr_maybe_paren(rhs, prec);
1524 hir::ExprKind::Field(expr, ident) => {
1525 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
1527 self.print_ident(ident);
1529 hir::ExprKind::Index(expr, index) => {
1530 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
1532 self.print_expr(index);
1535 hir::ExprKind::Path(ref qpath) => self.print_qpath(qpath, true),
1536 hir::ExprKind::Break(destination, opt_expr) => {
1538 if let Some(label) = destination.label {
1540 self.print_ident(label.ident);
1542 if let Some(expr) = opt_expr {
1544 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
1547 hir::ExprKind::Continue(destination) => {
1548 self.word("continue");
1549 if let Some(label) = destination.label {
1551 self.print_ident(label.ident);
1554 hir::ExprKind::Ret(result) => {
1555 self.word("return");
1556 if let Some(expr) = result {
1558 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
1561 hir::ExprKind::InlineAsm(asm) => {
1563 self.print_inline_asm(asm);
1565 hir::ExprKind::Yield(expr, _) => {
1566 self.word_space("yield");
1567 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
1569 hir::ExprKind::Err => {
1571 self.word("/*ERROR*/");
1575 self.ann.post(self, AnnNode::Expr(expr));
1579 pub fn print_local_decl(&mut self, loc: &hir::Local<'_>) {
1580 self.print_pat(loc.pat);
1581 if let Some(ty) = loc.ty {
1582 self.word_space(":");
1583 self.print_type(ty);
1587 pub fn print_name(&mut self, name: Symbol) {
1588 self.print_ident(Ident::with_dummy_span(name))
1591 pub fn print_path(&mut self, path: &hir::Path<'_>, colons_before_params: bool) {
1592 self.maybe_print_comment(path.span.lo());
1594 for (i, segment) in path.segments.iter().enumerate() {
1598 if segment.ident.name != kw::PathRoot {
1599 self.print_ident(segment.ident);
1600 self.print_generic_args(segment.args(), colons_before_params);
1605 pub fn print_path_segment(&mut self, segment: &hir::PathSegment<'_>) {
1606 if segment.ident.name != kw::PathRoot {
1607 self.print_ident(segment.ident);
1608 self.print_generic_args(segment.args(), false);
1612 pub fn print_qpath(&mut self, qpath: &hir::QPath<'_>, colons_before_params: bool) {
1614 hir::QPath::Resolved(None, path) => self.print_path(path, colons_before_params),
1615 hir::QPath::Resolved(Some(qself), path) => {
1617 self.print_type(qself);
1619 self.word_space("as");
1621 for (i, segment) in path.segments[..path.segments.len() - 1].iter().enumerate() {
1625 if segment.ident.name != kw::PathRoot {
1626 self.print_ident(segment.ident);
1627 self.print_generic_args(segment.args(), colons_before_params);
1633 let item_segment = path.segments.last().unwrap();
1634 self.print_ident(item_segment.ident);
1635 self.print_generic_args(item_segment.args(), colons_before_params)
1637 hir::QPath::TypeRelative(qself, item_segment) => {
1638 // If we've got a compound-qualified-path, let's push an additional pair of angle
1639 // brackets, so that we pretty-print `<<A::B>::C>` as `<A::B>::C`, instead of just
1640 // `A::B::C` (since the latter could be ambiguous to the user)
1641 if let hir::TyKind::Path(hir::QPath::Resolved(None, _)) = qself.kind {
1642 self.print_type(qself);
1645 self.print_type(qself);
1650 self.print_ident(item_segment.ident);
1651 self.print_generic_args(item_segment.args(), colons_before_params)
1653 hir::QPath::LangItem(lang_item, span, _) => {
1654 self.word("#[lang = \"");
1655 self.print_ident(Ident::new(lang_item.name(), span));
1661 fn print_generic_args(
1663 generic_args: &hir::GenericArgs<'_>,
1664 colons_before_params: bool,
1666 if generic_args.parenthesized {
1668 self.commasep(Inconsistent, generic_args.inputs(), |s, ty| s.print_type(ty));
1671 self.space_if_not_bol();
1672 self.word_space("->");
1673 self.print_type(generic_args.bindings[0].ty());
1675 let start = if colons_before_params { "::<" } else { "<" };
1676 let empty = Cell::new(true);
1677 let start_or_comma = |this: &mut Self| {
1682 this.word_space(",")
1686 let mut nonelided_generic_args: bool = false;
1687 let elide_lifetimes = generic_args.args.iter().all(|arg| match arg {
1688 GenericArg::Lifetime(lt) => lt.is_elided(),
1690 nonelided_generic_args = true;
1695 if nonelided_generic_args {
1696 start_or_comma(self);
1700 |s, generic_arg| match generic_arg {
1701 GenericArg::Lifetime(lt) if !elide_lifetimes => s.print_lifetime(lt),
1702 GenericArg::Lifetime(_) => {}
1703 GenericArg::Type(ty) => s.print_type(ty),
1704 GenericArg::Const(ct) => s.print_anon_const(&ct.value),
1705 GenericArg::Infer(_inf) => s.word("_"),
1710 for binding in generic_args.bindings {
1711 start_or_comma(self);
1712 self.print_type_binding(binding);
1721 pub fn print_type_binding(&mut self, binding: &hir::TypeBinding<'_>) {
1722 self.print_ident(binding.ident);
1723 self.print_generic_args(binding.gen_args, false);
1725 match binding.kind {
1726 hir::TypeBindingKind::Equality { ref term } => {
1727 self.word_space("=");
1729 Term::Ty(ty) => self.print_type(ty),
1730 Term::Const(ref c) => self.print_anon_const(c),
1733 hir::TypeBindingKind::Constraint { bounds } => {
1734 self.print_bounds(":", bounds);
1739 pub fn print_pat(&mut self, pat: &hir::Pat<'_>) {
1740 self.maybe_print_comment(pat.span.lo());
1741 self.ann.pre(self, AnnNode::Pat(pat));
1742 // Pat isn't normalized, but the beauty of it
1743 // is that it doesn't matter
1745 PatKind::Wild => self.word("_"),
1746 PatKind::Binding(binding_mode, _, ident, sub) => {
1747 match binding_mode {
1748 hir::BindingAnnotation::Ref => {
1749 self.word_nbsp("ref");
1750 self.print_mutability(hir::Mutability::Not, false);
1752 hir::BindingAnnotation::RefMut => {
1753 self.word_nbsp("ref");
1754 self.print_mutability(hir::Mutability::Mut, false);
1756 hir::BindingAnnotation::Unannotated => {}
1757 hir::BindingAnnotation::Mutable => {
1758 self.word_nbsp("mut");
1761 self.print_ident(ident);
1762 if let Some(p) = sub {
1767 PatKind::TupleStruct(ref qpath, elts, ddpos) => {
1768 self.print_qpath(qpath, true);
1770 if let Some(ddpos) = ddpos {
1771 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(p));
1773 self.word_space(",");
1776 if ddpos != elts.len() {
1778 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(p));
1781 self.commasep(Inconsistent, elts, |s, p| s.print_pat(p));
1785 PatKind::Path(ref qpath) => {
1786 self.print_qpath(qpath, true);
1788 PatKind::Struct(ref qpath, fields, etc) => {
1789 self.print_qpath(qpath, true);
1792 let empty = fields.is_empty() && !etc;
1796 self.commasep_cmnt(Consistent, &fields, |s, f| s.print_patfield(f), |f| f.pat.span);
1798 if !fields.is_empty() {
1799 self.word_space(",");
1808 PatKind::Or(pats) => {
1809 self.strsep("|", true, Inconsistent, pats, |s, p| s.print_pat(p));
1811 PatKind::Tuple(elts, ddpos) => {
1813 if let Some(ddpos) = ddpos {
1814 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(p));
1816 self.word_space(",");
1819 if ddpos != elts.len() {
1821 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(p));
1824 self.commasep(Inconsistent, elts, |s, p| s.print_pat(p));
1825 if elts.len() == 1 {
1831 PatKind::Box(inner) => {
1832 let is_range_inner = matches!(inner.kind, PatKind::Range(..));
1837 self.print_pat(inner);
1842 PatKind::Ref(inner, mutbl) => {
1843 let is_range_inner = matches!(inner.kind, PatKind::Range(..));
1845 self.word(mutbl.prefix_str());
1849 self.print_pat(inner);
1854 PatKind::Lit(e) => self.print_expr(e),
1855 PatKind::Range(begin, end, end_kind) => {
1856 if let Some(expr) = begin {
1857 self.print_expr(expr);
1860 RangeEnd::Included => self.word("..."),
1861 RangeEnd::Excluded => self.word(".."),
1863 if let Some(expr) = end {
1864 self.print_expr(expr);
1867 PatKind::Slice(before, slice, after) => {
1869 self.commasep(Inconsistent, before, |s, p| s.print_pat(p));
1870 if let Some(p) = slice {
1871 if !before.is_empty() {
1872 self.word_space(",");
1874 if let PatKind::Wild = p.kind {
1880 if !after.is_empty() {
1881 self.word_space(",");
1884 self.commasep(Inconsistent, after, |s, p| s.print_pat(p));
1888 self.ann.post(self, AnnNode::Pat(pat))
1891 pub fn print_patfield(&mut self, field: &hir::PatField<'_>) {
1892 if self.attrs(field.hir_id).is_empty() {
1895 self.cbox(INDENT_UNIT);
1896 self.print_outer_attributes(&self.attrs(field.hir_id));
1897 if !field.is_shorthand {
1898 self.print_ident(field.ident);
1899 self.word_nbsp(":");
1901 self.print_pat(field.pat);
1905 pub fn print_param(&mut self, arg: &hir::Param<'_>) {
1906 self.print_outer_attributes(self.attrs(arg.hir_id));
1907 self.print_pat(arg.pat);
1910 pub fn print_arm(&mut self, arm: &hir::Arm<'_>) {
1911 // I have no idea why this check is necessary, but here it
1913 if self.attrs(arm.hir_id).is_empty() {
1916 self.cbox(INDENT_UNIT);
1917 self.ann.pre(self, AnnNode::Arm(arm));
1919 self.print_outer_attributes(self.attrs(arm.hir_id));
1920 self.print_pat(arm.pat);
1922 if let Some(ref g) = arm.guard {
1924 hir::Guard::If(e) => {
1925 self.word_space("if");
1929 hir::Guard::IfLet(&hir::Let { pat, ty, init, .. }) => {
1930 self.word_nbsp("if");
1931 self.print_let(pat, ty, init);
1935 self.word_space("=>");
1937 match arm.body.kind {
1938 hir::ExprKind::Block(blk, opt_label) => {
1939 if let Some(label) = opt_label {
1940 self.print_ident(label.ident);
1941 self.word_space(":");
1943 // the block will close the pattern's ibox
1944 self.print_block_unclosed(blk);
1946 // If it is a user-provided unsafe block, print a comma after it
1947 if let hir::BlockCheckMode::UnsafeBlock(hir::UnsafeSource::UserProvided) = blk.rules
1953 self.end(); // close the ibox for the pattern
1954 self.print_expr(arm.body);
1958 self.ann.post(self, AnnNode::Arm(arm));
1959 self.end() // close enclosing cbox
1964 decl: &hir::FnDecl<'_>,
1965 header: hir::FnHeader,
1966 name: Option<Symbol>,
1967 generics: &hir::Generics<'_>,
1968 arg_names: &[Ident],
1969 body_id: Option<hir::BodyId>,
1971 self.print_fn_header_info(header);
1973 if let Some(name) = name {
1975 self.print_name(name);
1977 self.print_generic_params(generics.params);
1981 // Make sure we aren't supplied *both* `arg_names` and `body_id`.
1982 assert!(arg_names.is_empty() || body_id.is_none());
1983 self.commasep(Inconsistent, decl.inputs, |s, ty| {
1984 s.ibox(INDENT_UNIT);
1985 if let Some(arg_name) = arg_names.get(i) {
1986 s.word(arg_name.to_string());
1989 } else if let Some(body_id) = body_id {
1990 s.ann.nested(s, Nested::BodyParamPat(body_id, i));
1998 if decl.c_variadic {
2003 self.print_fn_output(decl);
2004 self.print_where_clause(generics)
2007 fn print_closure_params(&mut self, decl: &hir::FnDecl<'_>, body_id: hir::BodyId) {
2010 self.commasep(Inconsistent, decl.inputs, |s, ty| {
2011 s.ibox(INDENT_UNIT);
2013 s.ann.nested(s, Nested::BodyParamPat(body_id, i));
2016 if let hir::TyKind::Infer = ty.kind {
2027 if let hir::FnRetTy::DefaultReturn(..) = decl.output {
2031 self.space_if_not_bol();
2032 self.word_space("->");
2034 hir::FnRetTy::Return(ty) => {
2035 self.print_type(ty);
2036 self.maybe_print_comment(ty.span.lo());
2038 hir::FnRetTy::DefaultReturn(..) => unreachable!(),
2042 pub fn print_capture_clause(&mut self, capture_clause: hir::CaptureBy) {
2043 match capture_clause {
2044 hir::CaptureBy::Value => self.word_space("move"),
2045 hir::CaptureBy::Ref => {}
2049 pub fn print_closure_binder(
2051 binder: hir::ClosureBinder,
2052 generic_params: &[GenericParam<'_>],
2054 let generic_params = generic_params
2060 kind: GenericParamKind::Lifetime { kind: LifetimeParamKind::Explicit },
2065 .collect::<Vec<_>>();
2068 hir::ClosureBinder::Default => {}
2069 // we need to distinguish `|...| {}` from `for<> |...| {}` as `for<>` adds additional restrictions
2070 hir::ClosureBinder::For { .. } if generic_params.is_empty() => self.word("for<>"),
2071 hir::ClosureBinder::For { .. } => {
2075 self.commasep(Inconsistent, &generic_params, |s, param| {
2076 s.print_generic_param(param)
2085 pub fn print_bounds<'b>(
2087 prefix: &'static str,
2088 bounds: impl IntoIterator<Item = &'b hir::GenericBound<'b>>,
2090 let mut first = true;
2091 for bound in bounds {
2095 if !(first && prefix.is_empty()) {
2101 self.word_space("+");
2105 GenericBound::Trait(tref, modifier) => {
2106 if modifier == &TraitBoundModifier::Maybe {
2109 self.print_poly_trait_ref(tref);
2111 GenericBound::LangItemTrait(lang_item, span, ..) => {
2112 self.word("#[lang = \"");
2113 self.print_ident(Ident::new(lang_item.name(), *span));
2116 GenericBound::Outlives(lt) => {
2117 self.print_lifetime(lt);
2123 pub fn print_generic_params(&mut self, generic_params: &[GenericParam<'_>]) {
2124 if !generic_params.is_empty() {
2127 self.commasep(Inconsistent, generic_params, |s, param| s.print_generic_param(param));
2133 pub fn print_generic_param(&mut self, param: &GenericParam<'_>) {
2134 if let GenericParamKind::Const { .. } = param.kind {
2135 self.word_space("const");
2138 self.print_ident(param.name.ident());
2141 GenericParamKind::Lifetime { .. } => {}
2142 GenericParamKind::Type { default, .. } => {
2143 if let Some(default) = default {
2145 self.word_space("=");
2146 self.print_type(default);
2149 GenericParamKind::Const { ty, ref default } => {
2150 self.word_space(":");
2151 self.print_type(ty);
2152 if let Some(default) = default {
2154 self.word_space("=");
2155 self.print_anon_const(default);
2161 pub fn print_lifetime(&mut self, lifetime: &hir::Lifetime) {
2162 self.print_ident(lifetime.name.ident())
2165 pub fn print_where_clause(&mut self, generics: &hir::Generics<'_>) {
2166 if generics.predicates.is_empty() {
2171 self.word_space("where");
2173 for (i, predicate) in generics.predicates.iter().enumerate() {
2175 self.word_space(",");
2179 hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
2180 bound_generic_params,
2185 self.print_formal_generic_params(bound_generic_params);
2186 self.print_type(bounded_ty);
2187 self.print_bounds(":", bounds);
2189 hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
2194 self.print_lifetime(lifetime);
2197 for (i, bound) in bounds.iter().enumerate() {
2199 GenericBound::Outlives(lt) => {
2200 self.print_lifetime(lt);
2210 hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
2213 self.print_type(lhs_ty);
2215 self.word_space("=");
2216 self.print_type(rhs_ty);
2222 pub fn print_mutability(&mut self, mutbl: hir::Mutability, print_const: bool) {
2224 hir::Mutability::Mut => self.word_nbsp("mut"),
2225 hir::Mutability::Not => {
2227 self.word_nbsp("const")
2233 pub fn print_mt(&mut self, mt: &hir::MutTy<'_>, print_const: bool) {
2234 self.print_mutability(mt.mutbl, print_const);
2235 self.print_type(mt.ty);
2238 pub fn print_fn_output(&mut self, decl: &hir::FnDecl<'_>) {
2239 if let hir::FnRetTy::DefaultReturn(..) = decl.output {
2243 self.space_if_not_bol();
2244 self.ibox(INDENT_UNIT);
2245 self.word_space("->");
2247 hir::FnRetTy::DefaultReturn(..) => unreachable!(),
2248 hir::FnRetTy::Return(ty) => self.print_type(ty),
2252 if let hir::FnRetTy::Return(output) = decl.output {
2253 self.maybe_print_comment(output.span.lo());
2260 unsafety: hir::Unsafety,
2261 decl: &hir::FnDecl<'_>,
2262 name: Option<Symbol>,
2263 generic_params: &[hir::GenericParam<'_>],
2264 arg_names: &[Ident],
2266 self.ibox(INDENT_UNIT);
2267 self.print_formal_generic_params(generic_params);
2268 let generics = hir::Generics::empty();
2274 constness: hir::Constness::NotConst,
2275 asyncness: hir::IsAsync::NotAsync,
2285 pub fn print_fn_header_info(&mut self, header: hir::FnHeader) {
2286 match header.constness {
2287 hir::Constness::NotConst => {}
2288 hir::Constness::Const => self.word_nbsp("const"),
2291 match header.asyncness {
2292 hir::IsAsync::NotAsync => {}
2293 hir::IsAsync::Async => self.word_nbsp("async"),
2296 self.print_unsafety(header.unsafety);
2298 if header.abi != Abi::Rust {
2299 self.word_nbsp("extern");
2300 self.word_nbsp(header.abi.to_string());
2306 pub fn print_unsafety(&mut self, s: hir::Unsafety) {
2308 hir::Unsafety::Normal => {}
2309 hir::Unsafety::Unsafe => self.word_nbsp("unsafe"),
2313 pub fn print_is_auto(&mut self, s: hir::IsAuto) {
2315 hir::IsAuto::Yes => self.word_nbsp("auto"),
2316 hir::IsAuto::No => {}
2321 /// Does this expression require a semicolon to be treated
2322 /// as a statement? The negation of this: 'can this expression
2323 /// be used as a statement without a semicolon' -- is used
2324 /// as an early-bail-out in the parser so that, for instance,
2325 /// if true {...} else {...}
2327 /// isn't parsed as (if true {...} else {...} | x) | 5
2329 // Duplicated from `parse::classify`, but adapted for the HIR.
2330 fn expr_requires_semi_to_be_stmt(e: &hir::Expr<'_>) -> bool {
2333 hir::ExprKind::If(..)
2334 | hir::ExprKind::Match(..)
2335 | hir::ExprKind::Block(..)
2336 | hir::ExprKind::Loop(..)
2340 /// This statement requires a semicolon after it.
2341 /// note that in one case (stmt_semi), we've already
2342 /// seen the semicolon, and thus don't need another.
2343 fn stmt_ends_with_semi(stmt: &hir::StmtKind<'_>) -> bool {
2345 hir::StmtKind::Local(_) => true,
2346 hir::StmtKind::Item(_) => false,
2347 hir::StmtKind::Expr(e) => expr_requires_semi_to_be_stmt(e),
2348 hir::StmtKind::Semi(..) => false,
2352 fn bin_op_to_assoc_op(op: hir::BinOpKind) -> AssocOp {
2353 use crate::hir::BinOpKind::*;
2355 Add => AssocOp::Add,
2356 Sub => AssocOp::Subtract,
2357 Mul => AssocOp::Multiply,
2358 Div => AssocOp::Divide,
2359 Rem => AssocOp::Modulus,
2361 And => AssocOp::LAnd,
2364 BitXor => AssocOp::BitXor,
2365 BitAnd => AssocOp::BitAnd,
2366 BitOr => AssocOp::BitOr,
2367 Shl => AssocOp::ShiftLeft,
2368 Shr => AssocOp::ShiftRight,
2370 Eq => AssocOp::Equal,
2371 Lt => AssocOp::Less,
2372 Le => AssocOp::LessEqual,
2373 Ne => AssocOp::NotEqual,
2374 Ge => AssocOp::GreaterEqual,
2375 Gt => AssocOp::Greater,
2379 /// Expressions that syntactically contain an "exterior" struct literal, i.e., not surrounded by any
2380 /// parens or other delimiters, e.g., `X { y: 1 }`, `X { y: 1 }.method()`, `foo == X { y: 1 }` and
2381 /// `X { y: 1 } == foo` all do, but `(X { y: 1 }) == foo` does not.
2382 fn contains_exterior_struct_lit(value: &hir::Expr<'_>) -> bool {
2384 hir::ExprKind::Struct(..) => true,
2386 hir::ExprKind::Assign(lhs, rhs, _)
2387 | hir::ExprKind::AssignOp(_, lhs, rhs)
2388 | hir::ExprKind::Binary(_, lhs, rhs) => {
2389 // `X { y: 1 } + X { y: 2 }`
2390 contains_exterior_struct_lit(lhs) || contains_exterior_struct_lit(rhs)
2392 hir::ExprKind::Unary(_, x)
2393 | hir::ExprKind::Cast(x, _)
2394 | hir::ExprKind::Type(x, _)
2395 | hir::ExprKind::Field(x, _)
2396 | hir::ExprKind::Index(x, _) => {
2397 // `&X { y: 1 }, X { y: 1 }.y`
2398 contains_exterior_struct_lit(x)
2401 hir::ExprKind::MethodCall(_, receiver, ..) => {
2402 // `X { y: 1 }.bar(...)`
2403 contains_exterior_struct_lit(receiver)