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;
13 BindingAnnotation, ByRef, GenericArg, GenericParam, GenericParamKind, Mutability, Node, Term,
15 use rustc_hir::{GenericBound, PatKind, RangeEnd, TraitBoundModifier};
16 use rustc_span::source_map::SourceMap;
17 use rustc_span::symbol::{kw, Ident, IdentPrinter, Symbol};
18 use rustc_span::{self, FileName};
19 use rustc_target::spec::abi::Abi;
24 pub fn id_to_string(map: &dyn rustc_hir::intravisit::Map<'_>, hir_id: hir::HirId) -> String {
25 to_string(&map, |s| s.print_node(map.find(hir_id).unwrap()))
28 pub enum AnnNode<'a> {
30 Block(&'a hir::Block<'a>),
31 Item(&'a hir::Item<'a>),
33 Expr(&'a hir::Expr<'a>),
34 Pat(&'a hir::Pat<'a>),
35 Arm(&'a hir::Arm<'a>),
40 TraitItem(hir::TraitItemId),
41 ImplItem(hir::ImplItemId),
42 ForeignItem(hir::ForeignItemId),
44 BodyParamPat(hir::BodyId, usize),
48 fn nested(&self, _state: &mut State<'_>, _nested: Nested) {}
49 fn pre(&self, _state: &mut State<'_>, _node: AnnNode<'_>) {}
50 fn post(&self, _state: &mut State<'_>, _node: AnnNode<'_>) {}
54 impl PpAnn for NoAnn {}
55 pub const NO_ANN: &dyn PpAnn = &NoAnn;
57 /// Identical to the `PpAnn` implementation for `hir::Crate`,
58 /// except it avoids creating a dependency on the whole crate.
59 impl PpAnn for &dyn rustc_hir::intravisit::Map<'_> {
60 fn nested(&self, state: &mut State<'_>, nested: Nested) {
62 Nested::Item(id) => state.print_item(self.item(id)),
63 Nested::TraitItem(id) => state.print_trait_item(self.trait_item(id)),
64 Nested::ImplItem(id) => state.print_impl_item(self.impl_item(id)),
65 Nested::ForeignItem(id) => state.print_foreign_item(self.foreign_item(id)),
66 Nested::Body(id) => state.print_expr(&self.body(id).value),
67 Nested::BodyParamPat(id, i) => state.print_pat(self.body(id).params[i].pat),
72 pub struct State<'a> {
74 comments: Option<Comments<'a>>,
75 attrs: &'a dyn Fn(hir::HirId) -> &'a [ast::Attribute],
76 ann: &'a (dyn PpAnn + 'a),
80 pub fn print_node(&mut self, node: Node<'_>) {
82 Node::Param(a) => self.print_param(a),
83 Node::Item(a) => self.print_item(a),
84 Node::ForeignItem(a) => self.print_foreign_item(a),
85 Node::TraitItem(a) => self.print_trait_item(a),
86 Node::ImplItem(a) => self.print_impl_item(a),
87 Node::Variant(a) => self.print_variant(a),
88 Node::AnonConst(a) => self.print_anon_const(a),
89 Node::Expr(a) => self.print_expr(a),
90 Node::ExprField(a) => self.print_expr_field(&a),
91 Node::Stmt(a) => self.print_stmt(a),
92 Node::PathSegment(a) => self.print_path_segment(a),
93 Node::Ty(a) => self.print_type(a),
94 Node::TypeBinding(a) => self.print_type_binding(a),
95 Node::TraitRef(a) => self.print_trait_ref(a),
96 Node::Pat(a) => self.print_pat(a),
97 Node::PatField(a) => self.print_patfield(&a),
98 Node::Arm(a) => self.print_arm(a),
99 Node::Infer(_) => self.word("_"),
101 // Containing cbox, will be closed by print-block at `}`.
102 self.cbox(INDENT_UNIT);
103 // Head-ibox, will be closed by print-block after `{`.
107 Node::Lifetime(a) => self.print_lifetime(a),
108 Node::GenericParam(_) => panic!("cannot print Node::GenericParam"),
109 Node::Field(_) => panic!("cannot print Node::Field"),
110 // These cases do not carry enough information in the
111 // `hir_map` to reconstruct their full structure for pretty
113 Node::Ctor(..) => panic!("cannot print isolated Ctor"),
114 Node::Local(a) => self.print_local_decl(a),
115 Node::Crate(..) => panic!("cannot print Crate"),
120 impl std::ops::Deref for State<'_> {
121 type Target = pp::Printer;
122 fn deref(&self) -> &Self::Target {
127 impl std::ops::DerefMut for State<'_> {
128 fn deref_mut(&mut self) -> &mut Self::Target {
133 impl<'a> PrintState<'a> for State<'a> {
134 fn comments(&mut self) -> &mut Option<Comments<'a>> {
138 fn print_ident(&mut self, ident: Ident) {
139 self.word(IdentPrinter::for_ast_ident(ident, ident.is_raw_guess()).to_string());
140 self.ann.post(self, AnnNode::Name(&ident.name))
143 fn print_generic_args(&mut self, _: &ast::GenericArgs, _colons_before_params: bool) {
144 panic!("AST generic args printed by HIR pretty-printer");
148 pub const INDENT_UNIT: isize = 4;
150 /// Requires you to pass an input filename and reader so that
151 /// it can scan the input text for comments to copy forward.
152 pub fn print_crate<'a>(
154 krate: &hir::Mod<'_>,
157 attrs: &'a dyn Fn(hir::HirId) -> &'a [ast::Attribute],
160 let mut s = State::new_from_input(sm, filename, input, attrs, ann);
162 // When printing the AST, we sometimes need to inject `#[no_std]` here.
163 // Since you can't compile the HIR, it's not necessary.
165 s.print_mod(krate, (*attrs)(hir::CRATE_HIR_ID));
166 s.print_remaining_comments();
171 pub fn new_from_input(
175 attrs: &'a dyn Fn(hir::HirId) -> &'a [ast::Attribute],
179 s: pp::Printer::new(),
180 comments: Some(Comments::new(sm, filename, input)),
186 fn attrs(&self, id: hir::HirId) -> &'a [ast::Attribute] {
191 pub fn to_string<F>(ann: &dyn PpAnn, f: F) -> String
193 F: FnOnce(&mut State<'_>),
195 let mut printer = State { s: pp::Printer::new(), comments: None, attrs: &|_| &[], ann };
200 pub fn generic_params_to_string(generic_params: &[GenericParam<'_>]) -> String {
201 to_string(NO_ANN, |s| s.print_generic_params(generic_params))
204 pub fn bounds_to_string<'b>(bounds: impl IntoIterator<Item = &'b hir::GenericBound<'b>>) -> String {
205 to_string(NO_ANN, |s| s.print_bounds("", bounds))
208 pub fn ty_to_string(ty: &hir::Ty<'_>) -> String {
209 to_string(NO_ANN, |s| s.print_type(ty))
212 pub fn path_segment_to_string(segment: &hir::PathSegment<'_>) -> String {
213 to_string(NO_ANN, |s| s.print_path_segment(segment))
216 pub fn path_to_string(segment: &hir::Path<'_>) -> String {
217 to_string(NO_ANN, |s| s.print_path(segment, false))
220 pub fn qpath_to_string(segment: &hir::QPath<'_>) -> String {
221 to_string(NO_ANN, |s| s.print_qpath(segment, false))
225 decl: &hir::FnDecl<'_>,
226 header: hir::FnHeader,
227 name: Option<Symbol>,
228 generics: &hir::Generics<'_>,
230 body_id: Option<hir::BodyId>,
232 to_string(NO_ANN, |s| s.print_fn(decl, header, name, generics, arg_names, body_id))
235 pub fn enum_def_to_string(
236 enum_definition: &hir::EnumDef<'_>,
237 generics: &hir::Generics<'_>,
239 span: rustc_span::Span,
241 to_string(NO_ANN, |s| s.print_enum_def(enum_definition, generics, name, span))
245 pub fn bclose_maybe_open(&mut self, span: rustc_span::Span, close_box: bool) {
246 self.maybe_print_comment(span.hi());
247 self.break_offset_if_not_bol(1, -(INDENT_UNIT as isize));
250 self.end(); // close the outer-box
254 pub fn bclose(&mut self, span: rustc_span::Span) {
255 self.bclose_maybe_open(span, true)
258 pub fn commasep_cmnt<T, F, G>(&mut self, b: Breaks, elts: &[T], mut op: F, mut get_span: G)
260 F: FnMut(&mut State<'_>, &T),
261 G: FnMut(&T) -> rustc_span::Span,
264 let len = elts.len();
267 self.maybe_print_comment(get_span(elt).hi());
272 self.maybe_print_trailing_comment(get_span(elt), Some(get_span(&elts[i]).hi()));
273 self.space_if_not_bol();
279 pub fn commasep_exprs(&mut self, b: Breaks, exprs: &[hir::Expr<'_>]) {
280 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(e), |e| e.span);
283 pub fn print_mod(&mut self, _mod: &hir::Mod<'_>, attrs: &[ast::Attribute]) {
284 self.print_inner_attributes(attrs);
285 for &item_id in _mod.item_ids {
286 self.ann.nested(self, Nested::Item(item_id));
290 pub fn print_opt_lifetime(&mut self, lifetime: &hir::Lifetime) {
291 if !lifetime.is_elided() {
292 self.print_lifetime(lifetime);
297 pub fn print_type(&mut self, ty: &hir::Ty<'_>) {
298 self.maybe_print_comment(ty.span.lo());
301 hir::TyKind::Slice(ty) => {
306 hir::TyKind::Ptr(ref mt) => {
308 self.print_mt(mt, true);
310 hir::TyKind::Rptr(ref lifetime, ref mt) => {
312 self.print_opt_lifetime(lifetime);
313 self.print_mt(mt, false);
315 hir::TyKind::Never => {
318 hir::TyKind::Tup(elts) => {
320 self.commasep(Inconsistent, elts, |s, ty| s.print_type(ty));
326 hir::TyKind::BareFn(f) => {
327 self.print_ty_fn(f.abi, f.unsafety, f.decl, None, f.generic_params, f.param_names);
329 hir::TyKind::OpaqueDef(..) => self.word("/*impl Trait*/"),
330 hir::TyKind::Path(ref qpath) => self.print_qpath(qpath, false),
331 hir::TyKind::TraitObject(bounds, ref lifetime, syntax) => {
332 if syntax == ast::TraitObjectSyntax::Dyn {
333 self.word_space("dyn");
335 let mut first = true;
336 for bound in bounds {
341 self.word_space("+");
343 self.print_poly_trait_ref(bound);
345 if !lifetime.is_elided() {
347 self.word_space("+");
348 self.print_lifetime(lifetime);
351 hir::TyKind::Array(ty, ref length) => {
355 self.print_array_length(length);
358 hir::TyKind::Typeof(ref e) => {
359 self.word("typeof(");
360 self.print_anon_const(e);
363 hir::TyKind::Err => {
365 self.word("/*ERROR*/");
368 hir::TyKind::Infer => {
375 pub fn print_foreign_item(&mut self, item: &hir::ForeignItem<'_>) {
376 self.hardbreak_if_not_bol();
377 self.maybe_print_comment(item.span.lo());
378 self.print_outer_attributes(self.attrs(item.hir_id()));
380 hir::ForeignItemKind::Fn(decl, arg_names, generics) => {
385 unsafety: hir::Unsafety::Normal,
386 constness: hir::Constness::NotConst,
388 asyncness: hir::IsAsync::NotAsync,
390 Some(item.ident.name),
395 self.end(); // end head-ibox
397 self.end() // end the outer fn box
399 hir::ForeignItemKind::Static(t, m) => {
401 if m == hir::Mutability::Mut {
402 self.word_space("mut");
404 self.print_ident(item.ident);
405 self.word_space(":");
408 self.end(); // end the head-ibox
409 self.end() // end the outer cbox
411 hir::ForeignItemKind::Type => {
413 self.print_ident(item.ident);
415 self.end(); // end the head-ibox
416 self.end() // end the outer cbox
421 fn print_associated_const(
425 default: Option<hir::BodyId>,
428 self.word_space("const");
429 self.print_ident(ident);
430 self.word_space(":");
432 if let Some(expr) = default {
434 self.word_space("=");
435 self.ann.nested(self, Nested::Body(expr));
440 fn print_associated_type(
443 generics: &hir::Generics<'_>,
444 bounds: Option<hir::GenericBounds<'_>>,
445 ty: Option<&hir::Ty<'_>>,
447 self.word_space("type");
448 self.print_ident(ident);
449 self.print_generic_params(generics.params);
450 if let Some(bounds) = bounds {
451 self.print_bounds(":", bounds);
453 self.print_where_clause(generics);
454 if let Some(ty) = ty {
456 self.word_space("=");
464 item: &hir::Item<'_>,
465 generics: &hir::Generics<'_>,
466 inner: impl Fn(&mut Self),
469 self.print_ident(item.ident);
470 self.print_generic_params(generics.params);
471 self.end(); // end the inner ibox
473 self.print_where_clause(generics);
477 self.end(); // end the outer ibox
480 /// Pretty-print an item
481 pub fn print_item(&mut self, item: &hir::Item<'_>) {
482 self.hardbreak_if_not_bol();
483 self.maybe_print_comment(item.span.lo());
484 let attrs = self.attrs(item.hir_id());
485 self.print_outer_attributes(attrs);
486 self.ann.pre(self, AnnNode::Item(item));
488 hir::ItemKind::ExternCrate(orig_name) => {
489 self.head("extern crate");
490 if let Some(orig_name) = orig_name {
491 self.print_name(orig_name);
496 self.print_ident(item.ident);
498 self.end(); // end inner head-block
499 self.end(); // end outer head-block
501 hir::ItemKind::Use(path, kind) => {
503 self.print_path(path, false);
506 hir::UseKind::Single => {
507 if path.segments.last().unwrap().ident != item.ident {
509 self.word_space("as");
510 self.print_ident(item.ident);
514 hir::UseKind::Glob => self.word("::*;"),
515 hir::UseKind::ListStem => self.word("::{};"),
517 self.end(); // end inner head-block
518 self.end(); // end outer head-block
520 hir::ItemKind::Static(ty, m, expr) => {
522 if m == hir::Mutability::Mut {
523 self.word_space("mut");
525 self.print_ident(item.ident);
526 self.word_space(":");
529 self.end(); // end the head-ibox
531 self.word_space("=");
532 self.ann.nested(self, Nested::Body(expr));
534 self.end(); // end the outer cbox
536 hir::ItemKind::Const(ty, expr) => {
538 self.print_ident(item.ident);
539 self.word_space(":");
542 self.end(); // end the head-ibox
544 self.word_space("=");
545 self.ann.nested(self, Nested::Body(expr));
547 self.end(); // end the outer cbox
549 hir::ItemKind::Fn(ref sig, param_names, body) => {
554 Some(item.ident.name),
560 self.end(); // need to close a box
561 self.end(); // need to close a box
562 self.ann.nested(self, Nested::Body(body));
564 hir::ItemKind::Macro(ref macro_def, _) => {
565 self.print_mac_def(macro_def, &item.ident, item.span, |_| {});
567 hir::ItemKind::Mod(ref _mod) => {
569 self.print_ident(item.ident);
572 self.print_mod(_mod, attrs);
573 self.bclose(item.span);
575 hir::ItemKind::ForeignMod { abi, items } => {
577 self.word_nbsp(abi.to_string());
579 self.print_inner_attributes(self.attrs(item.hir_id()));
581 self.ann.nested(self, Nested::ForeignItem(item.id));
583 self.bclose(item.span);
585 hir::ItemKind::GlobalAsm(asm) => {
586 self.head("global_asm!");
587 self.print_inline_asm(asm);
590 hir::ItemKind::TyAlias(ty, generics) => {
591 self.print_item_type(item, generics, |state| {
592 state.word_space("=");
593 state.print_type(ty);
596 hir::ItemKind::OpaqueTy(ref opaque_ty) => {
597 self.print_item_type(item, opaque_ty.generics, |state| {
598 let mut real_bounds = Vec::with_capacity(opaque_ty.bounds.len());
599 for b in opaque_ty.bounds {
600 if let GenericBound::Trait(ptr, hir::TraitBoundModifier::Maybe) = b {
602 state.word_space("for ?");
603 state.print_trait_ref(&ptr.trait_ref);
608 state.print_bounds("= impl", real_bounds);
611 hir::ItemKind::Enum(ref enum_definition, params) => {
612 self.print_enum_def(enum_definition, params, item.ident.name, item.span);
614 hir::ItemKind::Struct(ref struct_def, generics) => {
616 self.print_struct(struct_def, generics, item.ident.name, item.span, true);
618 hir::ItemKind::Union(ref struct_def, generics) => {
620 self.print_struct(struct_def, generics, item.ident.name, item.span, true);
622 hir::ItemKind::Impl(&hir::Impl {
634 self.print_defaultness(defaultness);
635 self.print_unsafety(unsafety);
636 self.word_nbsp("impl");
638 if !generics.params.is_empty() {
639 self.print_generic_params(generics.params);
643 if constness == hir::Constness::Const {
644 self.word_nbsp("const");
647 if let hir::ImplPolarity::Negative(_) = polarity {
651 if let Some(t) = of_trait {
652 self.print_trait_ref(t);
654 self.word_space("for");
657 self.print_type(self_ty);
658 self.print_where_clause(generics);
662 self.print_inner_attributes(attrs);
663 for impl_item in items {
664 self.ann.nested(self, Nested::ImplItem(impl_item.id));
666 self.bclose(item.span);
668 hir::ItemKind::Trait(is_auto, unsafety, generics, bounds, trait_items) => {
670 self.print_is_auto(is_auto);
671 self.print_unsafety(unsafety);
672 self.word_nbsp("trait");
673 self.print_ident(item.ident);
674 self.print_generic_params(generics.params);
675 let mut real_bounds = Vec::with_capacity(bounds.len());
677 if let GenericBound::Trait(ptr, hir::TraitBoundModifier::Maybe) = b {
679 self.word_space("for ?");
680 self.print_trait_ref(&ptr.trait_ref);
685 self.print_bounds(":", real_bounds);
686 self.print_where_clause(generics);
689 for trait_item in trait_items {
690 self.ann.nested(self, Nested::TraitItem(trait_item.id));
692 self.bclose(item.span);
694 hir::ItemKind::TraitAlias(generics, bounds) => {
696 self.print_ident(item.ident);
697 self.print_generic_params(generics.params);
698 let mut real_bounds = Vec::with_capacity(bounds.len());
699 // FIXME(durka) this seems to be some quite outdated syntax
701 if let GenericBound::Trait(ptr, hir::TraitBoundModifier::Maybe) = b {
703 self.word_space("for ?");
704 self.print_trait_ref(&ptr.trait_ref);
710 self.print_bounds("=", real_bounds);
711 self.print_where_clause(generics);
713 self.end(); // end inner head-block
714 self.end(); // end outer head-block
717 self.ann.post(self, AnnNode::Item(item))
720 pub fn print_trait_ref(&mut self, t: &hir::TraitRef<'_>) {
721 self.print_path(t.path, false);
724 fn print_formal_generic_params(&mut self, generic_params: &[hir::GenericParam<'_>]) {
725 if !generic_params.is_empty() {
727 self.print_generic_params(generic_params);
732 fn print_poly_trait_ref(&mut self, t: &hir::PolyTraitRef<'_>) {
733 self.print_formal_generic_params(t.bound_generic_params);
734 self.print_trait_ref(&t.trait_ref);
737 pub fn print_enum_def(
739 enum_definition: &hir::EnumDef<'_>,
740 generics: &hir::Generics<'_>,
742 span: rustc_span::Span,
745 self.print_name(name);
746 self.print_generic_params(generics.params);
747 self.print_where_clause(generics);
749 self.print_variants(enum_definition.variants, span);
752 pub fn print_variants(&mut self, variants: &[hir::Variant<'_>], span: rustc_span::Span) {
755 self.space_if_not_bol();
756 self.maybe_print_comment(v.span.lo());
757 self.print_outer_attributes(self.attrs(v.id));
758 self.ibox(INDENT_UNIT);
759 self.print_variant(v);
762 self.maybe_print_trailing_comment(v.span, None);
767 pub fn print_defaultness(&mut self, defaultness: hir::Defaultness) {
769 hir::Defaultness::Default { .. } => self.word_nbsp("default"),
770 hir::Defaultness::Final => (),
776 struct_def: &hir::VariantData<'_>,
777 generics: &hir::Generics<'_>,
779 span: rustc_span::Span,
780 print_finalizer: bool,
782 self.print_name(name);
783 self.print_generic_params(generics.params);
785 hir::VariantData::Tuple(..) | hir::VariantData::Unit(..) => {
786 if let hir::VariantData::Tuple(..) = struct_def {
788 self.commasep(Inconsistent, struct_def.fields(), |s, field| {
789 s.maybe_print_comment(field.span.lo());
790 s.print_outer_attributes(s.attrs(field.hir_id));
791 s.print_type(field.ty);
795 self.print_where_clause(generics);
800 self.end() // close the outer-box
802 hir::VariantData::Struct(..) => {
803 self.print_where_clause(generics);
806 self.hardbreak_if_not_bol();
808 for field in struct_def.fields() {
809 self.hardbreak_if_not_bol();
810 self.maybe_print_comment(field.span.lo());
811 self.print_outer_attributes(self.attrs(field.hir_id));
812 self.print_ident(field.ident);
814 self.print_type(field.ty);
823 pub fn print_variant(&mut self, v: &hir::Variant<'_>) {
825 let generics = hir::Generics::empty();
826 self.print_struct(&v.data, generics, v.ident.name, v.span, false);
827 if let Some(ref d) = v.disr_expr {
829 self.word_space("=");
830 self.print_anon_const(d);
833 pub fn print_method_sig(
837 generics: &hir::Generics<'_>,
839 body_id: Option<hir::BodyId>,
841 self.print_fn(m.decl, m.header, Some(ident.name), generics, arg_names, body_id);
844 pub fn print_trait_item(&mut self, ti: &hir::TraitItem<'_>) {
845 self.ann.pre(self, AnnNode::SubItem(ti.hir_id()));
846 self.hardbreak_if_not_bol();
847 self.maybe_print_comment(ti.span.lo());
848 self.print_outer_attributes(self.attrs(ti.hir_id()));
850 hir::TraitItemKind::Const(ty, default) => {
851 self.print_associated_const(ti.ident, ty, default);
853 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Required(arg_names)) => {
854 self.print_method_sig(ti.ident, sig, ti.generics, arg_names, None);
857 hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Provided(body)) => {
859 self.print_method_sig(ti.ident, sig, ti.generics, &[], Some(body));
861 self.end(); // need to close a box
862 self.end(); // need to close a box
863 self.ann.nested(self, Nested::Body(body));
865 hir::TraitItemKind::Type(bounds, default) => {
866 self.print_associated_type(ti.ident, ti.generics, Some(bounds), default);
869 self.ann.post(self, AnnNode::SubItem(ti.hir_id()))
872 pub fn print_impl_item(&mut self, ii: &hir::ImplItem<'_>) {
873 self.ann.pre(self, AnnNode::SubItem(ii.hir_id()));
874 self.hardbreak_if_not_bol();
875 self.maybe_print_comment(ii.span.lo());
876 self.print_outer_attributes(self.attrs(ii.hir_id()));
879 hir::ImplItemKind::Const(ty, expr) => {
880 self.print_associated_const(ii.ident, ty, Some(expr));
882 hir::ImplItemKind::Fn(ref sig, body) => {
884 self.print_method_sig(ii.ident, sig, ii.generics, &[], Some(body));
886 self.end(); // need to close a box
887 self.end(); // need to close a box
888 self.ann.nested(self, Nested::Body(body));
890 hir::ImplItemKind::TyAlias(ty) => {
891 self.print_associated_type(ii.ident, ii.generics, None, Some(ty));
894 self.ann.post(self, AnnNode::SubItem(ii.hir_id()))
899 init: Option<&hir::Expr<'_>>,
900 els: Option<&hir::Block<'_>>,
901 decl: impl Fn(&mut Self),
903 self.space_if_not_bol();
904 self.ibox(INDENT_UNIT);
905 self.word_nbsp("let");
907 self.ibox(INDENT_UNIT);
911 if let Some(init) = init {
913 self.word_space("=");
914 self.print_expr(init);
917 if let Some(els) = els {
919 self.word_space("else");
920 // containing cbox, will be closed by print-block at `}`
922 // head-box, will be closed by print-block after `{`
924 self.print_block(els);
930 pub fn print_stmt(&mut self, st: &hir::Stmt<'_>) {
931 self.maybe_print_comment(st.span.lo());
933 hir::StmtKind::Local(loc) => {
934 self.print_local(loc.init, loc.els, |this| this.print_local_decl(loc));
936 hir::StmtKind::Item(item) => self.ann.nested(self, Nested::Item(item)),
937 hir::StmtKind::Expr(expr) => {
938 self.space_if_not_bol();
939 self.print_expr(expr);
941 hir::StmtKind::Semi(expr) => {
942 self.space_if_not_bol();
943 self.print_expr(expr);
947 if stmt_ends_with_semi(&st.kind) {
950 self.maybe_print_trailing_comment(st.span, None)
953 pub fn print_block(&mut self, blk: &hir::Block<'_>) {
954 self.print_block_with_attrs(blk, &[])
957 pub fn print_block_unclosed(&mut self, blk: &hir::Block<'_>) {
958 self.print_block_maybe_unclosed(blk, &[], false)
961 pub fn print_block_with_attrs(&mut self, blk: &hir::Block<'_>, attrs: &[ast::Attribute]) {
962 self.print_block_maybe_unclosed(blk, attrs, true)
965 pub fn print_block_maybe_unclosed(
967 blk: &hir::Block<'_>,
968 attrs: &[ast::Attribute],
972 hir::BlockCheckMode::UnsafeBlock(..) => self.word_space("unsafe"),
973 hir::BlockCheckMode::DefaultBlock => (),
975 self.maybe_print_comment(blk.span.lo());
976 self.ann.pre(self, AnnNode::Block(blk));
979 self.print_inner_attributes(attrs);
981 for st in blk.stmts {
984 if let Some(expr) = blk.expr {
985 self.space_if_not_bol();
986 self.print_expr(expr);
987 self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi()));
989 self.bclose_maybe_open(blk.span, close_box);
990 self.ann.post(self, AnnNode::Block(blk))
993 fn print_else(&mut self, els: Option<&hir::Expr<'_>>) {
994 if let Some(els_inner) = els {
995 match els_inner.kind {
996 // Another `else if` block.
997 hir::ExprKind::If(i, then, e) => {
998 self.cbox(INDENT_UNIT - 1);
1000 self.word(" else if ");
1001 self.print_expr_as_cond(i);
1003 self.print_expr(then);
1006 // Final `else` block.
1007 hir::ExprKind::Block(b, _) => {
1008 self.cbox(INDENT_UNIT - 1);
1010 self.word(" else ");
1011 self.print_block(b);
1013 // Constraints would be great here!
1015 panic!("print_if saw if with weird alternative");
1023 test: &hir::Expr<'_>,
1024 blk: &hir::Expr<'_>,
1025 elseopt: Option<&hir::Expr<'_>>,
1028 self.print_expr_as_cond(test);
1030 self.print_expr(blk);
1031 self.print_else(elseopt)
1034 pub fn print_array_length(&mut self, len: &hir::ArrayLen) {
1036 hir::ArrayLen::Infer(_, _) => self.word("_"),
1037 hir::ArrayLen::Body(ct) => self.print_anon_const(ct),
1041 pub fn print_anon_const(&mut self, constant: &hir::AnonConst) {
1042 self.ann.nested(self, Nested::Body(constant.body))
1045 fn print_call_post(&mut self, args: &[hir::Expr<'_>]) {
1047 self.commasep_exprs(Inconsistent, args);
1051 fn print_expr_maybe_paren(&mut self, expr: &hir::Expr<'_>, prec: i8) {
1052 self.print_expr_cond_paren(expr, expr.precedence().order() < prec)
1055 /// Prints an expr using syntax that's acceptable in a condition position, such as the `cond` in
1056 /// `if cond { ... }`.
1057 pub fn print_expr_as_cond(&mut self, expr: &hir::Expr<'_>) {
1058 self.print_expr_cond_paren(expr, Self::cond_needs_par(expr))
1061 /// Prints `expr` or `(expr)` when `needs_par` holds.
1062 fn print_expr_cond_paren(&mut self, expr: &hir::Expr<'_>, needs_par: bool) {
1066 if let hir::ExprKind::DropTemps(actual_expr) = expr.kind {
1067 self.print_expr(actual_expr);
1069 self.print_expr(expr);
1076 /// Print a `let pat = expr` expression.
1077 fn print_let(&mut self, pat: &hir::Pat<'_>, ty: Option<&hir::Ty<'_>>, init: &hir::Expr<'_>) {
1078 self.word_space("let");
1079 self.print_pat(pat);
1080 if let Some(ty) = ty {
1081 self.word_space(":");
1082 self.print_type(ty);
1085 self.word_space("=");
1086 let npals = || parser::needs_par_as_let_scrutinee(init.precedence().order());
1087 self.print_expr_cond_paren(init, Self::cond_needs_par(init) || npals())
1090 // Does `expr` need parentheses when printed in a condition position?
1092 // These cases need parens due to the parse error observed in #26461: `if return {}`
1093 // parses as the erroneous construct `if (return {})`, not `if (return) {}`.
1094 fn cond_needs_par(expr: &hir::Expr<'_>) -> bool {
1096 hir::ExprKind::Break(..) | hir::ExprKind::Closure { .. } | hir::ExprKind::Ret(..) => {
1099 _ => contains_exterior_struct_lit(expr),
1103 fn print_expr_vec(&mut self, exprs: &[hir::Expr<'_>]) {
1104 self.ibox(INDENT_UNIT);
1106 self.commasep_exprs(Inconsistent, exprs);
1111 fn print_expr_anon_const(&mut self, anon_const: &hir::AnonConst) {
1112 self.ibox(INDENT_UNIT);
1113 self.word_space("const");
1114 self.print_anon_const(anon_const);
1118 fn print_expr_repeat(&mut self, element: &hir::Expr<'_>, count: &hir::ArrayLen) {
1119 self.ibox(INDENT_UNIT);
1121 self.print_expr(element);
1122 self.word_space(";");
1123 self.print_array_length(count);
1128 fn print_expr_struct(
1130 qpath: &hir::QPath<'_>,
1131 fields: &[hir::ExprField<'_>],
1132 wth: Option<&hir::Expr<'_>>,
1134 self.print_qpath(qpath, true);
1136 self.commasep_cmnt(Consistent, fields, |s, field| s.print_expr_field(field), |f| f.span);
1137 if let Some(expr) = wth {
1138 self.ibox(INDENT_UNIT);
1139 if !fields.is_empty() {
1144 self.print_expr(expr);
1146 } else if !fields.is_empty() {
1153 fn print_expr_field(&mut self, field: &hir::ExprField<'_>) {
1154 if self.attrs(field.hir_id).is_empty() {
1157 self.cbox(INDENT_UNIT);
1158 self.print_outer_attributes(&self.attrs(field.hir_id));
1159 if !field.is_shorthand {
1160 self.print_ident(field.ident);
1161 self.word_space(":");
1163 self.print_expr(&field.expr);
1167 fn print_expr_tup(&mut self, exprs: &[hir::Expr<'_>]) {
1169 self.commasep_exprs(Inconsistent, exprs);
1170 if exprs.len() == 1 {
1176 fn print_expr_call(&mut self, func: &hir::Expr<'_>, args: &[hir::Expr<'_>]) {
1177 let prec = match func.kind {
1178 hir::ExprKind::Field(..) => parser::PREC_FORCE_PAREN,
1179 _ => parser::PREC_POSTFIX,
1182 self.print_expr_maybe_paren(func, prec);
1183 self.print_call_post(args)
1186 fn print_expr_method_call(
1188 segment: &hir::PathSegment<'_>,
1189 receiver: &hir::Expr<'_>,
1190 args: &[hir::Expr<'_>],
1192 let base_args = args;
1193 self.print_expr_maybe_paren(&receiver, parser::PREC_POSTFIX);
1195 self.print_ident(segment.ident);
1197 let generic_args = segment.args();
1198 if !generic_args.args.is_empty() || !generic_args.bindings.is_empty() {
1199 self.print_generic_args(generic_args, true);
1202 self.print_call_post(base_args)
1205 fn print_expr_binary(&mut self, op: hir::BinOp, lhs: &hir::Expr<'_>, rhs: &hir::Expr<'_>) {
1206 let assoc_op = bin_op_to_assoc_op(op.node);
1207 let prec = assoc_op.precedence() as i8;
1208 let fixity = assoc_op.fixity();
1210 let (left_prec, right_prec) = match fixity {
1211 Fixity::Left => (prec, prec + 1),
1212 Fixity::Right => (prec + 1, prec),
1213 Fixity::None => (prec + 1, prec + 1),
1216 let left_prec = match (&lhs.kind, op.node) {
1217 // These cases need parens: `x as i32 < y` has the parser thinking that `i32 < y` is
1218 // the beginning of a path type. It starts trying to parse `x as (i32 < y ...` instead
1219 // of `(x as i32) < ...`. We need to convince it _not_ to do that.
1220 (&hir::ExprKind::Cast { .. }, hir::BinOpKind::Lt | hir::BinOpKind::Shl) => {
1221 parser::PREC_FORCE_PAREN
1223 (&hir::ExprKind::Let { .. }, _) if !parser::needs_par_as_let_scrutinee(prec) => {
1224 parser::PREC_FORCE_PAREN
1229 self.print_expr_maybe_paren(lhs, left_prec);
1231 self.word_space(op.node.as_str());
1232 self.print_expr_maybe_paren(rhs, right_prec)
1235 fn print_expr_unary(&mut self, op: hir::UnOp, expr: &hir::Expr<'_>) {
1236 self.word(op.as_str());
1237 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1240 fn print_expr_addr_of(
1242 kind: hir::BorrowKind,
1243 mutability: hir::Mutability,
1244 expr: &hir::Expr<'_>,
1248 hir::BorrowKind::Ref => self.print_mutability(mutability, false),
1249 hir::BorrowKind::Raw => {
1250 self.word_nbsp("raw");
1251 self.print_mutability(mutability, true);
1254 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1257 fn print_literal(&mut self, lit: &hir::Lit) {
1258 self.maybe_print_comment(lit.span.lo());
1259 self.word(lit.node.to_token_lit().to_string())
1262 fn print_inline_asm(&mut self, asm: &hir::InlineAsm<'_>) {
1265 Operand(&'a hir::InlineAsmOperand<'a>),
1266 Options(ast::InlineAsmOptions),
1269 let mut args = vec![AsmArg::Template(ast::InlineAsmTemplatePiece::to_string(asm.template))];
1270 args.extend(asm.operands.iter().map(|(o, _)| AsmArg::Operand(o)));
1271 if !asm.options.is_empty() {
1272 args.push(AsmArg::Options(asm.options));
1276 self.commasep(Consistent, &args, |s, arg| match *arg {
1277 AsmArg::Template(ref template) => s.print_string(template, ast::StrStyle::Cooked),
1278 AsmArg::Operand(op) => match *op {
1279 hir::InlineAsmOperand::In { reg, ref expr } => {
1282 s.word(format!("{}", reg));
1287 hir::InlineAsmOperand::Out { reg, late, ref expr } => {
1288 s.word(if late { "lateout" } else { "out" });
1290 s.word(format!("{}", reg));
1294 Some(expr) => s.print_expr(expr),
1295 None => s.word("_"),
1298 hir::InlineAsmOperand::InOut { reg, late, ref expr } => {
1299 s.word(if late { "inlateout" } else { "inout" });
1301 s.word(format!("{}", reg));
1306 hir::InlineAsmOperand::SplitInOut { reg, late, ref in_expr, ref out_expr } => {
1307 s.word(if late { "inlateout" } else { "inout" });
1309 s.word(format!("{}", reg));
1312 s.print_expr(in_expr);
1316 Some(out_expr) => s.print_expr(out_expr),
1317 None => s.word("_"),
1320 hir::InlineAsmOperand::Const { ref anon_const } => {
1323 s.print_anon_const(anon_const);
1325 hir::InlineAsmOperand::SymFn { ref anon_const } => {
1328 s.print_anon_const(anon_const);
1330 hir::InlineAsmOperand::SymStatic { ref path, def_id: _ } => {
1331 s.word("sym_static");
1333 s.print_qpath(path, true);
1336 AsmArg::Options(opts) => {
1339 let mut options = vec![];
1340 if opts.contains(ast::InlineAsmOptions::PURE) {
1341 options.push("pure");
1343 if opts.contains(ast::InlineAsmOptions::NOMEM) {
1344 options.push("nomem");
1346 if opts.contains(ast::InlineAsmOptions::READONLY) {
1347 options.push("readonly");
1349 if opts.contains(ast::InlineAsmOptions::PRESERVES_FLAGS) {
1350 options.push("preserves_flags");
1352 if opts.contains(ast::InlineAsmOptions::NORETURN) {
1353 options.push("noreturn");
1355 if opts.contains(ast::InlineAsmOptions::NOSTACK) {
1356 options.push("nostack");
1358 if opts.contains(ast::InlineAsmOptions::ATT_SYNTAX) {
1359 options.push("att_syntax");
1361 if opts.contains(ast::InlineAsmOptions::RAW) {
1362 options.push("raw");
1364 if opts.contains(ast::InlineAsmOptions::MAY_UNWIND) {
1365 options.push("may_unwind");
1367 s.commasep(Inconsistent, &options, |s, &opt| {
1376 pub fn print_expr(&mut self, expr: &hir::Expr<'_>) {
1377 self.maybe_print_comment(expr.span.lo());
1378 self.print_outer_attributes(self.attrs(expr.hir_id));
1379 self.ibox(INDENT_UNIT);
1380 self.ann.pre(self, AnnNode::Expr(expr));
1382 hir::ExprKind::Box(expr) => {
1383 self.word_space("box");
1384 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX);
1386 hir::ExprKind::Array(exprs) => {
1387 self.print_expr_vec(exprs);
1389 hir::ExprKind::ConstBlock(ref anon_const) => {
1390 self.print_expr_anon_const(anon_const);
1392 hir::ExprKind::Repeat(element, ref count) => {
1393 self.print_expr_repeat(element, count);
1395 hir::ExprKind::Struct(qpath, fields, wth) => {
1396 self.print_expr_struct(qpath, fields, wth);
1398 hir::ExprKind::Tup(exprs) => {
1399 self.print_expr_tup(exprs);
1401 hir::ExprKind::Call(func, args) => {
1402 self.print_expr_call(func, args);
1404 hir::ExprKind::MethodCall(segment, receiver, args, _) => {
1405 self.print_expr_method_call(segment, receiver, args);
1407 hir::ExprKind::Binary(op, lhs, rhs) => {
1408 self.print_expr_binary(op, lhs, rhs);
1410 hir::ExprKind::Unary(op, expr) => {
1411 self.print_expr_unary(op, expr);
1413 hir::ExprKind::AddrOf(k, m, expr) => {
1414 self.print_expr_addr_of(k, m, expr);
1416 hir::ExprKind::Lit(ref lit) => {
1417 self.print_literal(lit);
1419 hir::ExprKind::Cast(expr, ty) => {
1420 let prec = AssocOp::As.precedence() as i8;
1421 self.print_expr_maybe_paren(expr, prec);
1423 self.word_space("as");
1424 self.print_type(ty);
1426 hir::ExprKind::Type(expr, ty) => {
1427 let prec = AssocOp::Colon.precedence() as i8;
1428 self.print_expr_maybe_paren(expr, prec);
1429 self.word_space(":");
1430 self.print_type(ty);
1432 hir::ExprKind::DropTemps(init) => {
1434 self.cbox(INDENT_UNIT);
1438 // Print `let _t = $init;`:
1439 let temp = Ident::from_str("_t");
1440 self.print_local(Some(init), None, |this| this.print_ident(temp));
1444 self.space_if_not_bol();
1445 self.print_ident(temp);
1448 self.bclose_maybe_open(expr.span, true);
1450 hir::ExprKind::Let(&hir::Let { pat, ty, init, .. }) => {
1451 self.print_let(pat, ty, init);
1453 hir::ExprKind::If(test, blk, elseopt) => {
1454 self.print_if(test, blk, elseopt);
1456 hir::ExprKind::Loop(blk, opt_label, _, _) => {
1457 if let Some(label) = opt_label {
1458 self.print_ident(label.ident);
1459 self.word_space(":");
1462 self.print_block(blk);
1464 hir::ExprKind::Match(expr, arms, _) => {
1465 self.cbox(INDENT_UNIT);
1466 self.ibox(INDENT_UNIT);
1467 self.word_nbsp("match");
1468 self.print_expr_as_cond(expr);
1472 self.print_arm(arm);
1474 self.bclose(expr.span);
1476 hir::ExprKind::Closure(&hir::Closure {
1479 bound_generic_params,
1485 self.print_closure_binder(binder, bound_generic_params);
1486 self.print_capture_clause(capture_clause);
1488 self.print_closure_params(fn_decl, body);
1491 // This is a bare expression.
1492 self.ann.nested(self, Nested::Body(body));
1493 self.end(); // need to close a box
1495 // A box will be closed by `print_expr`, but we didn't want an overall
1496 // wrapper so we closed the corresponding opening. so create an
1497 // empty box to satisfy the close.
1500 hir::ExprKind::Block(blk, opt_label) => {
1501 if let Some(label) = opt_label {
1502 self.print_ident(label.ident);
1503 self.word_space(":");
1505 // containing cbox, will be closed by print-block at `}`
1506 self.cbox(INDENT_UNIT);
1507 // head-box, will be closed by print-block after `{`
1509 self.print_block(blk);
1511 hir::ExprKind::Assign(lhs, rhs, _) => {
1512 let prec = AssocOp::Assign.precedence() as i8;
1513 self.print_expr_maybe_paren(lhs, prec + 1);
1515 self.word_space("=");
1516 self.print_expr_maybe_paren(rhs, prec);
1518 hir::ExprKind::AssignOp(op, lhs, rhs) => {
1519 let prec = AssocOp::Assign.precedence() as i8;
1520 self.print_expr_maybe_paren(lhs, prec + 1);
1522 self.word(op.node.as_str());
1523 self.word_space("=");
1524 self.print_expr_maybe_paren(rhs, prec);
1526 hir::ExprKind::Field(expr, ident) => {
1527 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
1529 self.print_ident(ident);
1531 hir::ExprKind::Index(expr, index) => {
1532 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
1534 self.print_expr(index);
1537 hir::ExprKind::Path(ref qpath) => self.print_qpath(qpath, true),
1538 hir::ExprKind::Break(destination, opt_expr) => {
1540 if let Some(label) = destination.label {
1542 self.print_ident(label.ident);
1544 if let Some(expr) = opt_expr {
1546 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
1549 hir::ExprKind::Continue(destination) => {
1550 self.word("continue");
1551 if let Some(label) = destination.label {
1553 self.print_ident(label.ident);
1556 hir::ExprKind::Ret(result) => {
1557 self.word("return");
1558 if let Some(expr) = result {
1560 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
1563 hir::ExprKind::InlineAsm(asm) => {
1565 self.print_inline_asm(asm);
1567 hir::ExprKind::Yield(expr, _) => {
1568 self.word_space("yield");
1569 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
1571 hir::ExprKind::Err => {
1573 self.word("/*ERROR*/");
1577 self.ann.post(self, AnnNode::Expr(expr));
1581 pub fn print_local_decl(&mut self, loc: &hir::Local<'_>) {
1582 self.print_pat(loc.pat);
1583 if let Some(ty) = loc.ty {
1584 self.word_space(":");
1585 self.print_type(ty);
1589 pub fn print_name(&mut self, name: Symbol) {
1590 self.print_ident(Ident::with_dummy_span(name))
1593 pub fn print_path(&mut self, path: &hir::Path<'_>, colons_before_params: bool) {
1594 self.maybe_print_comment(path.span.lo());
1596 for (i, segment) in path.segments.iter().enumerate() {
1600 if segment.ident.name != kw::PathRoot {
1601 self.print_ident(segment.ident);
1602 self.print_generic_args(segment.args(), colons_before_params);
1607 pub fn print_path_segment(&mut self, segment: &hir::PathSegment<'_>) {
1608 if segment.ident.name != kw::PathRoot {
1609 self.print_ident(segment.ident);
1610 self.print_generic_args(segment.args(), false);
1614 pub fn print_qpath(&mut self, qpath: &hir::QPath<'_>, colons_before_params: bool) {
1616 hir::QPath::Resolved(None, path) => self.print_path(path, colons_before_params),
1617 hir::QPath::Resolved(Some(qself), path) => {
1619 self.print_type(qself);
1621 self.word_space("as");
1623 for (i, segment) in path.segments[..path.segments.len() - 1].iter().enumerate() {
1627 if segment.ident.name != kw::PathRoot {
1628 self.print_ident(segment.ident);
1629 self.print_generic_args(segment.args(), colons_before_params);
1635 let item_segment = path.segments.last().unwrap();
1636 self.print_ident(item_segment.ident);
1637 self.print_generic_args(item_segment.args(), colons_before_params)
1639 hir::QPath::TypeRelative(qself, item_segment) => {
1640 // If we've got a compound-qualified-path, let's push an additional pair of angle
1641 // brackets, so that we pretty-print `<<A::B>::C>` as `<A::B>::C`, instead of just
1642 // `A::B::C` (since the latter could be ambiguous to the user)
1643 if let hir::TyKind::Path(hir::QPath::Resolved(None, _)) = qself.kind {
1644 self.print_type(qself);
1647 self.print_type(qself);
1652 self.print_ident(item_segment.ident);
1653 self.print_generic_args(item_segment.args(), colons_before_params)
1655 hir::QPath::LangItem(lang_item, span, _) => {
1656 self.word("#[lang = \"");
1657 self.print_ident(Ident::new(lang_item.name(), span));
1663 fn print_generic_args(
1665 generic_args: &hir::GenericArgs<'_>,
1666 colons_before_params: bool,
1668 if generic_args.parenthesized {
1670 self.commasep(Inconsistent, generic_args.inputs(), |s, ty| s.print_type(ty));
1673 self.space_if_not_bol();
1674 self.word_space("->");
1675 self.print_type(generic_args.bindings[0].ty());
1677 let start = if colons_before_params { "::<" } else { "<" };
1678 let empty = Cell::new(true);
1679 let start_or_comma = |this: &mut Self| {
1684 this.word_space(",")
1688 let mut nonelided_generic_args: bool = false;
1689 let elide_lifetimes = generic_args.args.iter().all(|arg| match arg {
1690 GenericArg::Lifetime(lt) => lt.is_elided(),
1692 nonelided_generic_args = true;
1697 if nonelided_generic_args {
1698 start_or_comma(self);
1702 |s, generic_arg| match generic_arg {
1703 GenericArg::Lifetime(lt) if !elide_lifetimes => s.print_lifetime(lt),
1704 GenericArg::Lifetime(_) => {}
1705 GenericArg::Type(ty) => s.print_type(ty),
1706 GenericArg::Const(ct) => s.print_anon_const(&ct.value),
1707 GenericArg::Infer(_inf) => s.word("_"),
1712 for binding in generic_args.bindings {
1713 start_or_comma(self);
1714 self.print_type_binding(binding);
1723 pub fn print_type_binding(&mut self, binding: &hir::TypeBinding<'_>) {
1724 self.print_ident(binding.ident);
1725 self.print_generic_args(binding.gen_args, false);
1727 match binding.kind {
1728 hir::TypeBindingKind::Equality { ref term } => {
1729 self.word_space("=");
1731 Term::Ty(ty) => self.print_type(ty),
1732 Term::Const(ref c) => self.print_anon_const(c),
1735 hir::TypeBindingKind::Constraint { bounds } => {
1736 self.print_bounds(":", bounds);
1741 pub fn print_pat(&mut self, pat: &hir::Pat<'_>) {
1742 self.maybe_print_comment(pat.span.lo());
1743 self.ann.pre(self, AnnNode::Pat(pat));
1744 // Pat isn't normalized, but the beauty of it
1745 // is that it doesn't matter
1747 PatKind::Wild => self.word("_"),
1748 PatKind::Binding(BindingAnnotation(by_ref, mutbl), _, ident, sub) => {
1749 if by_ref == ByRef::Yes {
1750 self.word_nbsp("ref");
1752 if mutbl == Mutability::Mut {
1753 self.word_nbsp("mut");
1755 self.print_ident(ident);
1756 if let Some(p) = sub {
1761 PatKind::TupleStruct(ref qpath, elts, ddpos) => {
1762 self.print_qpath(qpath, true);
1764 if let Some(ddpos) = ddpos.as_opt_usize() {
1765 let ddpos = ddpos as usize;
1766 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(p));
1768 self.word_space(",");
1771 if ddpos != elts.len() {
1773 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(p));
1776 self.commasep(Inconsistent, elts, |s, p| s.print_pat(p));
1780 PatKind::Path(ref qpath) => {
1781 self.print_qpath(qpath, true);
1783 PatKind::Struct(ref qpath, fields, etc) => {
1784 self.print_qpath(qpath, true);
1787 let empty = fields.is_empty() && !etc;
1791 self.commasep_cmnt(Consistent, &fields, |s, f| s.print_patfield(f), |f| f.pat.span);
1793 if !fields.is_empty() {
1794 self.word_space(",");
1803 PatKind::Or(pats) => {
1804 self.strsep("|", true, Inconsistent, pats, |s, p| s.print_pat(p));
1806 PatKind::Tuple(elts, ddpos) => {
1808 if let Some(ddpos) = ddpos.as_opt_usize() {
1809 self.commasep(Inconsistent, &elts[..ddpos], |s, p| s.print_pat(p));
1811 self.word_space(",");
1814 if ddpos != elts.len() {
1816 self.commasep(Inconsistent, &elts[ddpos..], |s, p| s.print_pat(p));
1819 self.commasep(Inconsistent, elts, |s, p| s.print_pat(p));
1820 if elts.len() == 1 {
1826 PatKind::Box(inner) => {
1827 let is_range_inner = matches!(inner.kind, PatKind::Range(..));
1832 self.print_pat(inner);
1837 PatKind::Ref(inner, mutbl) => {
1838 let is_range_inner = matches!(inner.kind, PatKind::Range(..));
1840 self.word(mutbl.prefix_str());
1844 self.print_pat(inner);
1849 PatKind::Lit(e) => self.print_expr(e),
1850 PatKind::Range(begin, end, end_kind) => {
1851 if let Some(expr) = begin {
1852 self.print_expr(expr);
1855 RangeEnd::Included => self.word("..."),
1856 RangeEnd::Excluded => self.word(".."),
1858 if let Some(expr) = end {
1859 self.print_expr(expr);
1862 PatKind::Slice(before, slice, after) => {
1864 self.commasep(Inconsistent, before, |s, p| s.print_pat(p));
1865 if let Some(p) = slice {
1866 if !before.is_empty() {
1867 self.word_space(",");
1869 if let PatKind::Wild = p.kind {
1875 if !after.is_empty() {
1876 self.word_space(",");
1879 self.commasep(Inconsistent, after, |s, p| s.print_pat(p));
1883 self.ann.post(self, AnnNode::Pat(pat))
1886 pub fn print_patfield(&mut self, field: &hir::PatField<'_>) {
1887 if self.attrs(field.hir_id).is_empty() {
1890 self.cbox(INDENT_UNIT);
1891 self.print_outer_attributes(&self.attrs(field.hir_id));
1892 if !field.is_shorthand {
1893 self.print_ident(field.ident);
1894 self.word_nbsp(":");
1896 self.print_pat(field.pat);
1900 pub fn print_param(&mut self, arg: &hir::Param<'_>) {
1901 self.print_outer_attributes(self.attrs(arg.hir_id));
1902 self.print_pat(arg.pat);
1905 pub fn print_arm(&mut self, arm: &hir::Arm<'_>) {
1906 // I have no idea why this check is necessary, but here it
1908 if self.attrs(arm.hir_id).is_empty() {
1911 self.cbox(INDENT_UNIT);
1912 self.ann.pre(self, AnnNode::Arm(arm));
1914 self.print_outer_attributes(self.attrs(arm.hir_id));
1915 self.print_pat(arm.pat);
1917 if let Some(ref g) = arm.guard {
1919 hir::Guard::If(e) => {
1920 self.word_space("if");
1924 hir::Guard::IfLet(&hir::Let { pat, ty, init, .. }) => {
1925 self.word_nbsp("if");
1926 self.print_let(pat, ty, init);
1930 self.word_space("=>");
1932 match arm.body.kind {
1933 hir::ExprKind::Block(blk, opt_label) => {
1934 if let Some(label) = opt_label {
1935 self.print_ident(label.ident);
1936 self.word_space(":");
1938 // the block will close the pattern's ibox
1939 self.print_block_unclosed(blk);
1941 // If it is a user-provided unsafe block, print a comma after it
1942 if let hir::BlockCheckMode::UnsafeBlock(hir::UnsafeSource::UserProvided) = blk.rules
1948 self.end(); // close the ibox for the pattern
1949 self.print_expr(arm.body);
1953 self.ann.post(self, AnnNode::Arm(arm));
1954 self.end() // close enclosing cbox
1959 decl: &hir::FnDecl<'_>,
1960 header: hir::FnHeader,
1961 name: Option<Symbol>,
1962 generics: &hir::Generics<'_>,
1963 arg_names: &[Ident],
1964 body_id: Option<hir::BodyId>,
1966 self.print_fn_header_info(header);
1968 if let Some(name) = name {
1970 self.print_name(name);
1972 self.print_generic_params(generics.params);
1976 // Make sure we aren't supplied *both* `arg_names` and `body_id`.
1977 assert!(arg_names.is_empty() || body_id.is_none());
1978 self.commasep(Inconsistent, decl.inputs, |s, ty| {
1979 s.ibox(INDENT_UNIT);
1980 if let Some(arg_name) = arg_names.get(i) {
1981 s.word(arg_name.to_string());
1984 } else if let Some(body_id) = body_id {
1985 s.ann.nested(s, Nested::BodyParamPat(body_id, i));
1993 if decl.c_variadic {
1998 self.print_fn_output(decl);
1999 self.print_where_clause(generics)
2002 fn print_closure_params(&mut self, decl: &hir::FnDecl<'_>, body_id: hir::BodyId) {
2005 self.commasep(Inconsistent, decl.inputs, |s, ty| {
2006 s.ibox(INDENT_UNIT);
2008 s.ann.nested(s, Nested::BodyParamPat(body_id, i));
2011 if let hir::TyKind::Infer = ty.kind {
2022 if let hir::FnRetTy::DefaultReturn(..) = decl.output {
2026 self.space_if_not_bol();
2027 self.word_space("->");
2029 hir::FnRetTy::Return(ty) => {
2030 self.print_type(ty);
2031 self.maybe_print_comment(ty.span.lo());
2033 hir::FnRetTy::DefaultReturn(..) => unreachable!(),
2037 pub fn print_capture_clause(&mut self, capture_clause: hir::CaptureBy) {
2038 match capture_clause {
2039 hir::CaptureBy::Value => self.word_space("move"),
2040 hir::CaptureBy::Ref => {}
2044 pub fn print_closure_binder(
2046 binder: hir::ClosureBinder,
2047 generic_params: &[GenericParam<'_>],
2049 let generic_params = generic_params
2055 kind: GenericParamKind::Lifetime { kind: LifetimeParamKind::Explicit },
2060 .collect::<Vec<_>>();
2063 hir::ClosureBinder::Default => {}
2064 // we need to distinguish `|...| {}` from `for<> |...| {}` as `for<>` adds additional restrictions
2065 hir::ClosureBinder::For { .. } if generic_params.is_empty() => self.word("for<>"),
2066 hir::ClosureBinder::For { .. } => {
2070 self.commasep(Inconsistent, &generic_params, |s, param| {
2071 s.print_generic_param(param)
2080 pub fn print_bounds<'b>(
2082 prefix: &'static str,
2083 bounds: impl IntoIterator<Item = &'b hir::GenericBound<'b>>,
2085 let mut first = true;
2086 for bound in bounds {
2090 if !(first && prefix.is_empty()) {
2096 self.word_space("+");
2100 GenericBound::Trait(tref, modifier) => {
2101 if modifier == &TraitBoundModifier::Maybe {
2104 self.print_poly_trait_ref(tref);
2106 GenericBound::LangItemTrait(lang_item, span, ..) => {
2107 self.word("#[lang = \"");
2108 self.print_ident(Ident::new(lang_item.name(), *span));
2111 GenericBound::Outlives(lt) => {
2112 self.print_lifetime(lt);
2118 pub fn print_generic_params(&mut self, generic_params: &[GenericParam<'_>]) {
2119 if !generic_params.is_empty() {
2122 self.commasep(Inconsistent, generic_params, |s, param| s.print_generic_param(param));
2128 pub fn print_generic_param(&mut self, param: &GenericParam<'_>) {
2129 if let GenericParamKind::Const { .. } = param.kind {
2130 self.word_space("const");
2133 self.print_ident(param.name.ident());
2136 GenericParamKind::Lifetime { .. } => {}
2137 GenericParamKind::Type { default, .. } => {
2138 if let Some(default) = default {
2140 self.word_space("=");
2141 self.print_type(default);
2144 GenericParamKind::Const { ty, ref default } => {
2145 self.word_space(":");
2146 self.print_type(ty);
2147 if let Some(default) = default {
2149 self.word_space("=");
2150 self.print_anon_const(default);
2156 pub fn print_lifetime(&mut self, lifetime: &hir::Lifetime) {
2157 self.print_ident(lifetime.name.ident())
2160 pub fn print_where_clause(&mut self, generics: &hir::Generics<'_>) {
2161 if generics.predicates.is_empty() {
2166 self.word_space("where");
2168 for (i, predicate) in generics.predicates.iter().enumerate() {
2170 self.word_space(",");
2174 hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
2175 bound_generic_params,
2180 self.print_formal_generic_params(bound_generic_params);
2181 self.print_type(bounded_ty);
2182 self.print_bounds(":", bounds);
2184 hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
2189 self.print_lifetime(lifetime);
2192 for (i, bound) in bounds.iter().enumerate() {
2194 GenericBound::Outlives(lt) => {
2195 self.print_lifetime(lt);
2205 hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
2208 self.print_type(lhs_ty);
2210 self.word_space("=");
2211 self.print_type(rhs_ty);
2217 pub fn print_mutability(&mut self, mutbl: hir::Mutability, print_const: bool) {
2219 hir::Mutability::Mut => self.word_nbsp("mut"),
2220 hir::Mutability::Not => {
2222 self.word_nbsp("const")
2228 pub fn print_mt(&mut self, mt: &hir::MutTy<'_>, print_const: bool) {
2229 self.print_mutability(mt.mutbl, print_const);
2230 self.print_type(mt.ty);
2233 pub fn print_fn_output(&mut self, decl: &hir::FnDecl<'_>) {
2234 if let hir::FnRetTy::DefaultReturn(..) = decl.output {
2238 self.space_if_not_bol();
2239 self.ibox(INDENT_UNIT);
2240 self.word_space("->");
2242 hir::FnRetTy::DefaultReturn(..) => unreachable!(),
2243 hir::FnRetTy::Return(ty) => self.print_type(ty),
2247 if let hir::FnRetTy::Return(output) = decl.output {
2248 self.maybe_print_comment(output.span.lo());
2255 unsafety: hir::Unsafety,
2256 decl: &hir::FnDecl<'_>,
2257 name: Option<Symbol>,
2258 generic_params: &[hir::GenericParam<'_>],
2259 arg_names: &[Ident],
2261 self.ibox(INDENT_UNIT);
2262 self.print_formal_generic_params(generic_params);
2263 let generics = hir::Generics::empty();
2269 constness: hir::Constness::NotConst,
2270 asyncness: hir::IsAsync::NotAsync,
2280 pub fn print_fn_header_info(&mut self, header: hir::FnHeader) {
2281 match header.constness {
2282 hir::Constness::NotConst => {}
2283 hir::Constness::Const => self.word_nbsp("const"),
2286 match header.asyncness {
2287 hir::IsAsync::NotAsync => {}
2288 hir::IsAsync::Async => self.word_nbsp("async"),
2291 self.print_unsafety(header.unsafety);
2293 if header.abi != Abi::Rust {
2294 self.word_nbsp("extern");
2295 self.word_nbsp(header.abi.to_string());
2301 pub fn print_unsafety(&mut self, s: hir::Unsafety) {
2303 hir::Unsafety::Normal => {}
2304 hir::Unsafety::Unsafe => self.word_nbsp("unsafe"),
2308 pub fn print_is_auto(&mut self, s: hir::IsAuto) {
2310 hir::IsAuto::Yes => self.word_nbsp("auto"),
2311 hir::IsAuto::No => {}
2316 /// Does this expression require a semicolon to be treated
2317 /// as a statement? The negation of this: 'can this expression
2318 /// be used as a statement without a semicolon' -- is used
2319 /// as an early-bail-out in the parser so that, for instance,
2320 /// if true {...} else {...}
2322 /// isn't parsed as (if true {...} else {...} | x) | 5
2324 // Duplicated from `parse::classify`, but adapted for the HIR.
2325 fn expr_requires_semi_to_be_stmt(e: &hir::Expr<'_>) -> bool {
2328 hir::ExprKind::If(..)
2329 | hir::ExprKind::Match(..)
2330 | hir::ExprKind::Block(..)
2331 | hir::ExprKind::Loop(..)
2335 /// This statement requires a semicolon after it.
2336 /// note that in one case (stmt_semi), we've already
2337 /// seen the semicolon, and thus don't need another.
2338 fn stmt_ends_with_semi(stmt: &hir::StmtKind<'_>) -> bool {
2340 hir::StmtKind::Local(_) => true,
2341 hir::StmtKind::Item(_) => false,
2342 hir::StmtKind::Expr(e) => expr_requires_semi_to_be_stmt(e),
2343 hir::StmtKind::Semi(..) => false,
2347 fn bin_op_to_assoc_op(op: hir::BinOpKind) -> AssocOp {
2348 use crate::hir::BinOpKind::*;
2350 Add => AssocOp::Add,
2351 Sub => AssocOp::Subtract,
2352 Mul => AssocOp::Multiply,
2353 Div => AssocOp::Divide,
2354 Rem => AssocOp::Modulus,
2356 And => AssocOp::LAnd,
2359 BitXor => AssocOp::BitXor,
2360 BitAnd => AssocOp::BitAnd,
2361 BitOr => AssocOp::BitOr,
2362 Shl => AssocOp::ShiftLeft,
2363 Shr => AssocOp::ShiftRight,
2365 Eq => AssocOp::Equal,
2366 Lt => AssocOp::Less,
2367 Le => AssocOp::LessEqual,
2368 Ne => AssocOp::NotEqual,
2369 Ge => AssocOp::GreaterEqual,
2370 Gt => AssocOp::Greater,
2374 /// Expressions that syntactically contain an "exterior" struct literal, i.e., not surrounded by any
2375 /// parens or other delimiters, e.g., `X { y: 1 }`, `X { y: 1 }.method()`, `foo == X { y: 1 }` and
2376 /// `X { y: 1 } == foo` all do, but `(X { y: 1 }) == foo` does not.
2377 fn contains_exterior_struct_lit(value: &hir::Expr<'_>) -> bool {
2379 hir::ExprKind::Struct(..) => true,
2381 hir::ExprKind::Assign(lhs, rhs, _)
2382 | hir::ExprKind::AssignOp(_, lhs, rhs)
2383 | hir::ExprKind::Binary(_, lhs, rhs) => {
2384 // `X { y: 1 } + X { y: 2 }`
2385 contains_exterior_struct_lit(lhs) || contains_exterior_struct_lit(rhs)
2387 hir::ExprKind::Unary(_, x)
2388 | hir::ExprKind::Cast(x, _)
2389 | hir::ExprKind::Type(x, _)
2390 | hir::ExprKind::Field(x, _)
2391 | hir::ExprKind::Index(x, _) => {
2392 // `&X { y: 1 }, X { y: 1 }.y`
2393 contains_exterior_struct_lit(x)
2396 hir::ExprKind::MethodCall(_, receiver, ..) => {
2397 // `X { y: 1 }.bar(...)`
2398 contains_exterior_struct_lit(receiver)