Skip to main content

rustc_ast_pretty/pprust/state/
item.rs

1use ast::StaticItem;
2use itertools::{Itertools, Position};
3use rustc_ast::{self as ast, EiiImpl, ModKind, Safety, TraitAlias};
4use rustc_span::Ident;
5
6use crate::pp::BoxMarker;
7use crate::pp::Breaks::Inconsistent;
8use crate::pprust::state::fixup::FixupContext;
9use crate::pprust::state::{AnnNode, INDENT_UNIT, PrintState, State};
10
11enum DelegationKind<'a> {
12    Single,
13    List(&'a [(Ident, Option<Ident>)]),
14    Glob,
15}
16
17fn visibility_qualified(vis: &ast::Visibility, s: &str) -> String {
18    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}{1}",
                State::to_string(|s| s.print_visibility(vis)), s))
    })format!("{}{}", State::to_string(|s| s.print_visibility(vis)), s)
19}
20
21impl<'a> State<'a> {
22    fn print_foreign_mod(&mut self, nmod: &ast::ForeignMod, attrs: &[ast::Attribute]) {
23        self.print_inner_attributes(attrs);
24        for item in &nmod.items {
25            self.print_foreign_item(item);
26        }
27    }
28
29    pub(crate) fn print_foreign_item(&mut self, item: &ast::ForeignItem) {
30        let ast::Item { id, span, ref attrs, ref kind, ref vis, tokens: _ } = *item;
31        self.ann.pre(self, AnnNode::SubItem(id));
32        self.hardbreak_if_not_bol();
33        self.maybe_print_comment(span.lo());
34        self.print_outer_attributes(attrs);
35        match kind {
36            ast::ForeignItemKind::Fn(func) => {
37                self.print_fn_full(vis, attrs, &*func);
38            }
39            ast::ForeignItemKind::Static(box ast::StaticItem {
40                ident,
41                ty,
42                mutability,
43                expr,
44                safety,
45                define_opaque,
46                eii_impls,
47            }) => self.print_item_const(
48                *ident,
49                Some(*mutability),
50                &ast::Generics::default(),
51                ty,
52                expr.as_deref(),
53                vis,
54                *safety,
55                ast::Defaultness::Implicit,
56                define_opaque.as_deref(),
57                eii_impls,
58            ),
59            ast::ForeignItemKind::TyAlias(box ast::TyAlias {
60                defaultness,
61                ident,
62                generics,
63                after_where_clause,
64                bounds,
65                ty,
66            }) => {
67                self.print_associated_type(
68                    *ident,
69                    generics,
70                    after_where_clause,
71                    bounds,
72                    ty.as_deref(),
73                    vis,
74                    *defaultness,
75                );
76            }
77            ast::ForeignItemKind::MacCall(m) => {
78                self.print_mac(m);
79                if m.args.need_semicolon() {
80                    self.word(";");
81                }
82            }
83        }
84        self.ann.post(self, AnnNode::SubItem(id))
85    }
86
87    fn print_item_const(
88        &mut self,
89        ident: Ident,
90        mutbl: Option<ast::Mutability>,
91        generics: &ast::Generics,
92        ty: &ast::Ty,
93        body: Option<&ast::Expr>,
94        vis: &ast::Visibility,
95        safety: ast::Safety,
96        defaultness: ast::Defaultness,
97        define_opaque: Option<&[(ast::NodeId, ast::Path)]>,
98        eii_impls: &[EiiImpl],
99    ) {
100        self.print_define_opaques(define_opaque);
101        for eii_impl in eii_impls {
102            self.print_eii_impl(eii_impl);
103        }
104        let (cb, ib) = self.head("");
105        self.print_visibility(vis);
106        self.print_safety(safety);
107        self.print_defaultness(defaultness);
108        let leading = match mutbl {
109            None => "const",
110            Some(ast::Mutability::Not) => "static",
111            Some(ast::Mutability::Mut) => "static mut",
112        };
113        self.word_space(leading);
114        self.print_ident(ident);
115        self.print_generic_params(&generics.params);
116        self.word_space(":");
117        self.print_type(ty);
118        if body.is_some() {
119            self.space();
120        }
121        self.end(ib);
122        if let Some(body) = body {
123            self.word_space("=");
124            self.print_expr(body, FixupContext::default());
125        }
126        self.print_where_clause(&generics.where_clause);
127        self.word(";");
128        self.end(cb);
129    }
130
131    fn print_associated_type(
132        &mut self,
133        ident: Ident,
134        generics: &ast::Generics,
135        after_where_clause: &ast::WhereClause,
136        bounds: &ast::GenericBounds,
137        ty: Option<&ast::Ty>,
138        vis: &ast::Visibility,
139        defaultness: ast::Defaultness,
140    ) {
141        let (cb, ib) = self.head("");
142        self.print_visibility(vis);
143        self.print_defaultness(defaultness);
144        self.word_space("type");
145        self.print_ident(ident);
146        self.print_generic_params(&generics.params);
147        if !bounds.is_empty() {
148            self.word_nbsp(":");
149            self.print_type_bounds(bounds);
150        }
151        self.print_where_clause(&generics.where_clause);
152        if let Some(ty) = ty {
153            self.space();
154            self.word_space("=");
155            self.print_type(ty);
156        }
157        self.print_where_clause(&after_where_clause);
158        self.word(";");
159        self.end(ib);
160        self.end(cb);
161    }
162
163    /// Pretty-prints an item.
164    pub(crate) fn print_item(&mut self, item: &ast::Item) {
165        if self.is_sdylib_interface && item.span.is_dummy() {
166            // Do not print prelude for interface files.
167            return;
168        }
169        self.hardbreak_if_not_bol();
170        self.maybe_print_comment(item.span.lo());
171        self.print_outer_attributes(&item.attrs);
172        self.ann.pre(self, AnnNode::Item(item));
173        match &item.kind {
174            ast::ItemKind::ExternCrate(orig_name, ident) => {
175                let (cb, ib) = self.head(visibility_qualified(&item.vis, "extern crate"));
176                if let &Some(orig_name) = orig_name {
177                    self.print_name(orig_name);
178                    self.space();
179                    self.word("as");
180                    self.space();
181                }
182                self.print_ident(*ident);
183                self.word(";");
184                self.end(ib);
185                self.end(cb);
186            }
187            ast::ItemKind::Use(tree) => {
188                self.print_visibility(&item.vis);
189                self.word_nbsp("use");
190                self.print_use_tree(tree);
191                self.word(";");
192            }
193            ast::ItemKind::Static(box StaticItem {
194                ident,
195                ty,
196                safety,
197                mutability: mutbl,
198                expr: body,
199                define_opaque,
200                eii_impls,
201            }) => {
202                self.print_safety(*safety);
203                self.print_item_const(
204                    *ident,
205                    Some(*mutbl),
206                    &ast::Generics::default(),
207                    ty,
208                    body.as_deref(),
209                    &item.vis,
210                    ast::Safety::Default,
211                    ast::Defaultness::Implicit,
212                    define_opaque.as_deref(),
213                    eii_impls,
214                );
215            }
216            ast::ItemKind::ConstBlock(ast::ConstBlockItem { id: _, span: _, block }) => {
217                let ib = self.ibox(INDENT_UNIT);
218                self.word("const");
219                self.nbsp();
220                {
221                    let cb = self.cbox(0);
222                    let ib = self.ibox(0);
223                    self.print_block_with_attrs(block, &[], cb, ib);
224                }
225                self.end(ib);
226            }
227            ast::ItemKind::Const(box ast::ConstItem {
228                defaultness,
229                ident,
230                generics,
231                ty,
232                rhs_kind,
233                define_opaque,
234            }) => {
235                self.print_item_const(
236                    *ident,
237                    None,
238                    generics,
239                    ty,
240                    rhs_kind.expr(),
241                    &item.vis,
242                    ast::Safety::Default,
243                    *defaultness,
244                    define_opaque.as_deref(),
245                    &[],
246                );
247            }
248            ast::ItemKind::Fn(func) => {
249                self.print_fn_full(&item.vis, &item.attrs, &*func);
250            }
251            ast::ItemKind::Mod(safety, ident, mod_kind) => {
252                let (cb, ib) = self.head(Self::to_string(|s| {
253                    s.print_visibility(&item.vis);
254                    s.print_safety(*safety);
255                    s.word("mod");
256                }));
257                self.print_ident(*ident);
258
259                match mod_kind {
260                    ModKind::Loaded(items, ..) => {
261                        self.nbsp();
262                        self.bopen(ib);
263                        self.print_inner_attributes(&item.attrs);
264                        for item in items {
265                            self.print_item(item);
266                        }
267                        let empty = item.attrs.is_empty() && items.is_empty();
268                        self.bclose(item.span, empty, cb);
269                    }
270                    ModKind::Unloaded => {
271                        self.word(";");
272                        self.end(ib);
273                        self.end(cb);
274                    }
275                }
276            }
277            ast::ItemKind::ForeignMod(nmod) => {
278                let (cb, ib) = self.head(Self::to_string(|s| {
279                    s.print_safety(nmod.safety);
280                    s.word("extern");
281                }));
282                if let Some(abi) = nmod.abi {
283                    self.print_token_literal(abi.as_token_lit(), abi.span);
284                    self.nbsp();
285                }
286                self.bopen(ib);
287                self.print_foreign_mod(nmod, &item.attrs);
288                let empty = item.attrs.is_empty() && nmod.items.is_empty();
289                self.bclose(item.span, empty, cb);
290            }
291            ast::ItemKind::GlobalAsm(asm) => {
292                // FIXME: Print `builtin # global_asm` once macro `global_asm` uses `builtin_syntax`.
293                let (cb, ib) = self.head(visibility_qualified(&item.vis, "global_asm!"));
294                self.print_inline_asm(asm);
295                self.word(";");
296                self.end(ib);
297                self.end(cb);
298            }
299            ast::ItemKind::TyAlias(box ast::TyAlias {
300                defaultness,
301                ident,
302                generics,
303                after_where_clause,
304                bounds,
305                ty,
306            }) => {
307                self.print_associated_type(
308                    *ident,
309                    generics,
310                    after_where_clause,
311                    bounds,
312                    ty.as_deref(),
313                    &item.vis,
314                    *defaultness,
315                );
316            }
317            ast::ItemKind::Enum(ident, generics, enum_definition) => {
318                self.print_enum_def(enum_definition, generics, *ident, item.span, &item.vis);
319            }
320            ast::ItemKind::Struct(ident, generics, struct_def) => {
321                let (cb, ib) = self.head(visibility_qualified(&item.vis, "struct"));
322                self.print_struct(struct_def, generics, *ident, item.span, true, cb, ib);
323            }
324            ast::ItemKind::Union(ident, generics, struct_def) => {
325                let (cb, ib) = self.head(visibility_qualified(&item.vis, "union"));
326                self.print_struct(struct_def, generics, *ident, item.span, true, cb, ib);
327            }
328            ast::ItemKind::Impl(ast::Impl { generics, of_trait, self_ty, items, constness }) => {
329                let (cb, ib) = self.head("");
330                self.print_visibility(&item.vis);
331
332                let impl_generics = |this: &mut Self| {
333                    this.word("impl");
334
335                    if generics.params.is_empty() {
336                        this.nbsp();
337                    } else {
338                        this.print_generic_params(&generics.params);
339                        this.space();
340                    }
341                };
342
343                if let Some(box of_trait) = of_trait {
344                    let ast::TraitImplHeader { defaultness, safety, polarity, ref trait_ref } =
345                        *of_trait;
346                    self.print_defaultness(defaultness);
347                    self.print_safety(safety);
348                    impl_generics(self);
349                    self.print_constness(*constness);
350                    if let ast::ImplPolarity::Negative(_) = polarity {
351                        self.word("!");
352                    }
353                    self.print_trait_ref(trait_ref);
354                    self.space();
355                    self.word_space("for");
356                } else {
357                    self.print_constness(*constness);
358                    impl_generics(self);
359                }
360
361                self.print_type(self_ty);
362                self.print_where_clause(&generics.where_clause);
363
364                self.space();
365                self.bopen(ib);
366                self.print_inner_attributes(&item.attrs);
367                for impl_item in items {
368                    self.print_assoc_item(impl_item);
369                }
370                let empty = item.attrs.is_empty() && items.is_empty();
371                self.bclose(item.span, empty, cb);
372            }
373            ast::ItemKind::Trait(box ast::Trait {
374                constness,
375                safety,
376                is_auto,
377                impl_restriction,
378                ident,
379                generics,
380                bounds,
381                items,
382            }) => {
383                let (cb, ib) = self.head("");
384                self.print_visibility(&item.vis);
385                self.print_constness(*constness);
386                self.print_safety(*safety);
387                self.print_is_auto(*is_auto);
388                self.print_impl_restriction(impl_restriction);
389                self.word_nbsp("trait");
390                self.print_ident(*ident);
391                self.print_generic_params(&generics.params);
392                if !bounds.is_empty() {
393                    self.word_nbsp(":");
394                    self.print_type_bounds(bounds);
395                }
396                self.print_where_clause(&generics.where_clause);
397                self.word(" ");
398                self.bopen(ib);
399                self.print_inner_attributes(&item.attrs);
400                for trait_item in items {
401                    self.print_assoc_item(trait_item);
402                }
403                let empty = item.attrs.is_empty() && items.is_empty();
404                self.bclose(item.span, empty, cb);
405            }
406            ast::ItemKind::TraitAlias(box TraitAlias { constness, ident, generics, bounds }) => {
407                let (cb, ib) = self.head("");
408                self.print_visibility(&item.vis);
409                self.print_constness(*constness);
410                self.word_nbsp("trait");
411                self.print_ident(*ident);
412                self.print_generic_params(&generics.params);
413                self.nbsp();
414                if !bounds.is_empty() {
415                    self.word_nbsp("=");
416                    self.print_type_bounds(bounds);
417                }
418                self.print_where_clause(&generics.where_clause);
419                self.word(";");
420                self.end(ib);
421                self.end(cb);
422            }
423            ast::ItemKind::MacCall(mac) => {
424                self.print_mac(mac);
425                if mac.args.need_semicolon() {
426                    self.word(";");
427                }
428            }
429            ast::ItemKind::MacroDef(ident, macro_def) => {
430                self.print_mac_def(macro_def, &ident, item.span, |state| {
431                    state.print_visibility(&item.vis)
432                });
433            }
434            ast::ItemKind::Delegation(deleg) => self.print_delegation(
435                &item.attrs,
436                &item.vis,
437                &deleg.qself,
438                &deleg.path,
439                DelegationKind::Single,
440                &deleg.body,
441            ),
442            ast::ItemKind::DelegationMac(deleg) => self.print_delegation(
443                &item.attrs,
444                &item.vis,
445                &deleg.qself,
446                &deleg.prefix,
447                deleg.suffixes.as_ref().map_or(DelegationKind::Glob, |s| DelegationKind::List(s)),
448                &deleg.body,
449            ),
450        }
451        self.ann.post(self, AnnNode::Item(item))
452    }
453
454    fn print_enum_def(
455        &mut self,
456        enum_definition: &ast::EnumDef,
457        generics: &ast::Generics,
458        ident: Ident,
459        span: rustc_span::Span,
460        visibility: &ast::Visibility,
461    ) {
462        let (cb, ib) = self.head(visibility_qualified(visibility, "enum"));
463        self.print_ident(ident);
464        self.print_generic_params(&generics.params);
465        self.print_where_clause(&generics.where_clause);
466        self.space();
467        self.bopen(ib);
468        for v in enum_definition.variants.iter() {
469            self.space_if_not_bol();
470            self.maybe_print_comment(v.span.lo());
471            self.print_outer_attributes(&v.attrs);
472            let ib = self.ibox(0);
473            self.print_variant(v);
474            self.word(",");
475            self.end(ib);
476            self.maybe_print_trailing_comment(v.span, None);
477        }
478        let empty = enum_definition.variants.is_empty();
479        self.bclose(span, empty, cb)
480    }
481
482    pub(crate) fn print_visibility(&mut self, vis: &ast::Visibility) {
483        match &vis.kind {
484            ast::VisibilityKind::Public => self.word_nbsp("pub"),
485            ast::VisibilityKind::Restricted { path, shorthand, .. } => {
486                let path = Self::to_string(|s| s.print_path(path, false, 0));
487                if *shorthand && (path == "crate" || path == "self" || path == "super") {
488                    self.word_nbsp(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("pub({0})", path))
    })format!("pub({path})"))
489                } else {
490                    self.word_nbsp(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("pub(in {0})", path))
    })format!("pub(in {path})"))
491                }
492            }
493            ast::VisibilityKind::Inherited => {}
494        }
495    }
496
497    pub(crate) fn print_impl_restriction(&mut self, impl_restriction: &ast::ImplRestriction) {
498        match &impl_restriction.kind {
499            ast::RestrictionKind::Restricted { path, shorthand, .. } => {
500                let path = Self::to_string(|s| s.print_path(path, false, 0));
501                if *shorthand {
502                    self.word_nbsp(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("impl({0})", path))
    })format!("impl({path})"))
503                } else {
504                    self.word_nbsp(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("impl(in {0})", path))
    })format!("impl(in {path})"))
505                }
506            }
507            ast::RestrictionKind::Unrestricted => {}
508        }
509    }
510
511    fn print_defaultness(&mut self, defaultness: ast::Defaultness) {
512        if let ast::Defaultness::Default(_) = defaultness {
513            self.word_nbsp("default");
514        }
515    }
516
517    fn print_struct(
518        &mut self,
519        struct_def: &ast::VariantData,
520        generics: &ast::Generics,
521        ident: Ident,
522        span: rustc_span::Span,
523        print_finalizer: bool,
524        cb: BoxMarker,
525        ib: BoxMarker,
526    ) {
527        self.print_ident(ident);
528        self.print_generic_params(&generics.params);
529        match &struct_def {
530            ast::VariantData::Tuple(..) | ast::VariantData::Unit(..) => {
531                if let ast::VariantData::Tuple(..) = struct_def {
532                    self.popen();
533                    self.commasep(Inconsistent, struct_def.fields(), |s, field| {
534                        s.maybe_print_comment(field.span.lo());
535                        s.print_outer_attributes(&field.attrs);
536                        s.print_visibility(&field.vis);
537                        s.print_type(&field.ty)
538                    });
539                    self.pclose();
540                }
541                self.print_where_clause(&generics.where_clause);
542                if print_finalizer {
543                    self.word(";");
544                }
545                self.end(ib);
546                self.end(cb);
547            }
548            ast::VariantData::Struct { fields, .. } => {
549                self.print_where_clause(&generics.where_clause);
550                self.nbsp();
551                self.bopen(ib);
552
553                let empty = fields.is_empty();
554                if !empty {
555                    self.hardbreak_if_not_bol();
556
557                    for field in fields {
558                        self.hardbreak_if_not_bol();
559                        self.maybe_print_comment(field.span.lo());
560                        self.print_outer_attributes(&field.attrs);
561                        self.print_visibility(&field.vis);
562                        self.print_ident(field.ident.unwrap());
563                        self.word_nbsp(":");
564                        self.print_type(&field.ty);
565                        self.word(",");
566                    }
567                }
568
569                self.bclose(span, empty, cb);
570            }
571        }
572    }
573
574    pub(crate) fn print_variant(&mut self, v: &ast::Variant) {
575        let (cb, ib) = self.head("");
576        self.print_visibility(&v.vis);
577        let generics = ast::Generics::default();
578        self.print_struct(&v.data, &generics, v.ident, v.span, false, cb, ib);
579        if let Some(d) = &v.disr_expr {
580            self.space();
581            self.word_space("=");
582            self.print_expr(&d.value, FixupContext::default())
583        }
584    }
585
586    pub(crate) fn print_assoc_item(&mut self, item: &ast::AssocItem) {
587        let ast::Item { id, span, ref attrs, ref kind, ref vis, tokens: _ } = *item;
588        self.ann.pre(self, AnnNode::SubItem(id));
589        self.hardbreak_if_not_bol();
590        self.maybe_print_comment(span.lo());
591        self.print_outer_attributes(attrs);
592        match kind {
593            ast::AssocItemKind::Fn(func) => {
594                self.print_fn_full(vis, attrs, &*func);
595            }
596            ast::AssocItemKind::Const(box ast::ConstItem {
597                defaultness,
598                ident,
599                generics,
600                ty,
601                rhs_kind,
602                define_opaque,
603            }) => {
604                self.print_item_const(
605                    *ident,
606                    None,
607                    generics,
608                    ty,
609                    rhs_kind.expr(),
610                    vis,
611                    ast::Safety::Default,
612                    *defaultness,
613                    define_opaque.as_deref(),
614                    &[],
615                );
616            }
617            ast::AssocItemKind::Type(box ast::TyAlias {
618                defaultness,
619                ident,
620                generics,
621                after_where_clause,
622                bounds,
623                ty,
624            }) => {
625                self.print_associated_type(
626                    *ident,
627                    generics,
628                    after_where_clause,
629                    bounds,
630                    ty.as_deref(),
631                    vis,
632                    *defaultness,
633                );
634            }
635            ast::AssocItemKind::MacCall(m) => {
636                self.print_mac(m);
637                if m.args.need_semicolon() {
638                    self.word(";");
639                }
640            }
641            ast::AssocItemKind::Delegation(deleg) => self.print_delegation(
642                &item.attrs,
643                vis,
644                &deleg.qself,
645                &deleg.path,
646                DelegationKind::Single,
647                &deleg.body,
648            ),
649            ast::AssocItemKind::DelegationMac(deleg) => self.print_delegation(
650                &item.attrs,
651                vis,
652                &deleg.qself,
653                &deleg.prefix,
654                deleg.suffixes.as_ref().map_or(DelegationKind::Glob, |s| DelegationKind::List(s)),
655                &deleg.body,
656            ),
657        }
658        self.ann.post(self, AnnNode::SubItem(id))
659    }
660
661    fn print_delegation(
662        &mut self,
663        attrs: &[ast::Attribute],
664        vis: &ast::Visibility,
665        qself: &Option<Box<ast::QSelf>>,
666        path: &ast::Path,
667        kind: DelegationKind<'_>,
668        body: &Option<Box<ast::Block>>,
669    ) {
670        let body_cb_ib = body.as_ref().map(|body| (body, self.head("")));
671        self.print_visibility(vis);
672        self.word_nbsp("reuse");
673
674        if let Some(qself) = qself {
675            self.print_qpath(path, qself, false);
676        } else {
677            self.print_path(path, false, 0);
678        }
679        match kind {
680            DelegationKind::Single => {}
681            DelegationKind::List(suffixes) => {
682                self.word("::");
683                self.word("{");
684                for (i, (ident, rename)) in suffixes.iter().enumerate() {
685                    self.print_ident(*ident);
686                    if let Some(rename) = rename {
687                        self.nbsp();
688                        self.word_nbsp("as");
689                        self.print_ident(*rename);
690                    }
691                    if i != suffixes.len() - 1 {
692                        self.word_space(",");
693                    }
694                }
695                self.word("}");
696            }
697            DelegationKind::Glob => {
698                self.word("::");
699                self.word("*");
700            }
701        }
702        if let Some((body, (cb, ib))) = body_cb_ib {
703            self.nbsp();
704            self.print_block_with_attrs(body, attrs, cb, ib);
705        } else {
706            self.word(";");
707        }
708    }
709
710    fn print_fn_full(&mut self, vis: &ast::Visibility, attrs: &[ast::Attribute], func: &ast::Fn) {
711        let ast::Fn { defaultness, ident, generics, sig, contract, body, define_opaque, eii_impls } =
712            func;
713
714        self.print_define_opaques(define_opaque.as_deref());
715
716        for eii_impl in eii_impls {
717            self.print_eii_impl(eii_impl);
718        }
719
720        let body_cb_ib = body.as_ref().map(|body| (body, self.head("")));
721
722        self.print_visibility(vis);
723        self.print_defaultness(*defaultness);
724        self.print_fn(&sig.decl, sig.header, Some(*ident), generics);
725        if let Some(contract) = &contract {
726            self.nbsp();
727            self.print_contract(contract);
728        }
729        if let Some((body, (cb, ib))) = body_cb_ib {
730            if self.is_sdylib_interface {
731                self.word(";");
732                self.end(ib); // end inner head-block
733                self.end(cb); // end outer head-block
734                return;
735            }
736
737            self.nbsp();
738            self.print_block_with_attrs(body, attrs, cb, ib);
739        } else {
740            self.word(";");
741        }
742    }
743
744    fn print_eii_impl(&mut self, eii: &ast::EiiImpl) {
745        self.word("#[");
746        if let Safety::Unsafe(..) = eii.impl_safety {
747            self.word("unsafe");
748            self.popen();
749        }
750        self.print_path(&eii.eii_macro_path, false, 0);
751        if let Safety::Unsafe(..) = eii.impl_safety {
752            self.pclose();
753        }
754        self.word("]");
755        self.hardbreak();
756    }
757
758    fn print_define_opaques(&mut self, define_opaque: Option<&[(ast::NodeId, ast::Path)]>) {
759        if let Some(define_opaque) = define_opaque {
760            self.word("#[define_opaque(");
761            for (i, (_, path)) in define_opaque.iter().enumerate() {
762                if i != 0 {
763                    self.word_space(",");
764                }
765
766                self.print_path(path, false, 0);
767            }
768            self.word(")]");
769        }
770        self.hardbreak_if_not_bol();
771    }
772
773    fn print_contract(&mut self, contract: &ast::FnContract) {
774        if let Some(pred) = &contract.requires {
775            self.word("rustc_requires");
776            self.popen();
777            self.print_expr(pred, FixupContext::default());
778            self.pclose();
779        }
780        if let Some(pred) = &contract.ensures {
781            self.word("rustc_ensures");
782            self.popen();
783            self.print_expr(pred, FixupContext::default());
784            self.pclose();
785        }
786    }
787
788    pub(crate) fn print_fn(
789        &mut self,
790        decl: &ast::FnDecl,
791        header: ast::FnHeader,
792        ident: Option<Ident>,
793        generics: &ast::Generics,
794    ) {
795        self.print_fn_header_info(header);
796        if let Some(ident) = ident {
797            self.nbsp();
798            self.print_ident(ident);
799        }
800        self.print_generic_params(&generics.params);
801        self.print_fn_params_and_ret(decl, false);
802        self.print_where_clause(&generics.where_clause);
803    }
804
805    pub(crate) fn print_fn_params_and_ret(&mut self, decl: &ast::FnDecl, is_closure: bool) {
806        let (open, close) = if is_closure { ("|", "|") } else { ("(", ")") };
807        self.word(open);
808        self.commasep(Inconsistent, &decl.inputs, |s, param| s.print_param(param, is_closure));
809        self.word(close);
810        self.print_fn_ret_ty(&decl.output)
811    }
812
813    fn print_where_clause(&mut self, where_clause: &ast::WhereClause) {
814        let ast::WhereClause { has_where_token, ref predicates, span: _ } = *where_clause;
815        if predicates.is_empty() && !has_where_token {
816            return;
817        }
818
819        self.space();
820        self.word_space("where");
821
822        for (i, predicate) in predicates.iter().enumerate() {
823            if i != 0 {
824                self.word_space(",");
825            }
826
827            self.print_where_predicate(predicate);
828        }
829    }
830
831    pub fn print_where_predicate(&mut self, predicate: &ast::WherePredicate) {
832        let ast::WherePredicate { attrs, kind, id: _, span: _, is_placeholder: _ } = predicate;
833        self.print_outer_attributes(attrs);
834        match kind {
835            ast::WherePredicateKind::BoundPredicate(where_bound_predicate) => {
836                self.print_where_bound_predicate(where_bound_predicate);
837            }
838            ast::WherePredicateKind::RegionPredicate(ast::WhereRegionPredicate {
839                lifetime,
840                bounds,
841                ..
842            }) => {
843                self.print_lifetime(*lifetime);
844                self.word(":");
845                if !bounds.is_empty() {
846                    self.nbsp();
847                    self.print_lifetime_bounds(bounds);
848                }
849            }
850            ast::WherePredicateKind::EqPredicate(ast::WhereEqPredicate {
851                lhs_ty, rhs_ty, ..
852            }) => {
853                self.print_type(lhs_ty);
854                self.space();
855                self.word_space("=");
856                self.print_type(rhs_ty);
857            }
858        }
859    }
860
861    pub(crate) fn print_where_bound_predicate(
862        &mut self,
863        where_bound_predicate: &ast::WhereBoundPredicate,
864    ) {
865        self.print_formal_generic_params(&where_bound_predicate.bound_generic_params);
866        self.print_type(&where_bound_predicate.bounded_ty);
867        self.word(":");
868        if !where_bound_predicate.bounds.is_empty() {
869            self.nbsp();
870            self.print_type_bounds(&where_bound_predicate.bounds);
871        }
872    }
873
874    fn print_use_tree(&mut self, tree: &ast::UseTree) {
875        match &tree.kind {
876            ast::UseTreeKind::Simple(rename) => {
877                self.print_path(&tree.prefix, false, 0);
878                if let &Some(rename) = rename {
879                    self.nbsp();
880                    self.word_nbsp("as");
881                    self.print_ident(rename);
882                }
883            }
884            ast::UseTreeKind::Glob(_) => {
885                if !tree.prefix.segments.is_empty() {
886                    self.print_path(&tree.prefix, false, 0);
887                    self.word("::");
888                }
889                self.word("*");
890            }
891            ast::UseTreeKind::Nested { items, .. } => {
892                if !tree.prefix.segments.is_empty() {
893                    self.print_path(&tree.prefix, false, 0);
894                    self.word("::");
895                }
896                if items.is_empty() {
897                    self.word("{}");
898                } else if let [(item, _)] = items.as_slice()
899                    && !item
900                        .prefix
901                        .segments
902                        .first()
903                        .is_some_and(|seg| seg.ident.name == rustc_span::symbol::kw::SelfLower)
904                {
905                    self.print_use_tree(item);
906                } else {
907                    let cb = self.cbox(INDENT_UNIT);
908                    self.word("{");
909                    self.zerobreak();
910                    let ib = self.ibox(0);
911                    for (pos, use_tree) in items.iter().with_position() {
912                        let is_last = #[allow(non_exhaustive_omitted_patterns)] match pos {
    Position::Last | Position::Only => true,
    _ => false,
}matches!(pos, Position::Last | Position::Only);
913                        self.print_use_tree(&use_tree.0);
914                        if !is_last {
915                            self.word(",");
916                            if let ast::UseTreeKind::Nested { .. } = use_tree.0.kind {
917                                self.hardbreak();
918                            } else {
919                                self.space();
920                            }
921                        }
922                    }
923                    self.end(ib);
924                    self.trailing_comma();
925                    self.offset(-INDENT_UNIT);
926                    self.word("}");
927                    self.end(cb);
928                }
929            }
930        }
931    }
932}