rustc_macros/
print_attribute.rs

1use proc_macro2::TokenStream;
2use quote::{format_ident, quote, quote_spanned};
3use syn::spanned::Spanned;
4use syn::{Data, Fields, Ident};
5use synstructure::Structure;
6
7fn print_fields(name: &Ident, fields: &Fields) -> (TokenStream, TokenStream) {
8    let string_name = name.to_string();
9    let mut disps = vec![quote! {let mut __printed_anything = false;}];
10
11    match fields {
12        Fields::Named(fields_named) => {
13            let mut field_names = Vec::new();
14
15            for field in &fields_named.named {
16                let name = field.ident.as_ref().unwrap();
17                let string_name = name.to_string();
18                disps.push(quote! {
19                    if #name.should_render() {
20                        if __printed_anything {
21                            __p.word_space(",");
22                        }
23                        __p.word(#string_name);
24                        __p.word(":");
25                        __p.nbsp();
26                        __printed_anything = true;
27                    }
28                    #name.print_attribute(__p);
29                });
30                field_names.push(name);
31            }
32
33            (
34                quote! { {#(#field_names),*} },
35                quote! {
36                    __p.word(#string_name);
37                    if true #(&& !#field_names.should_render())* {
38                        return;
39                    }
40
41                    __p.nbsp();
42                    __p.word("{");
43                    #(#disps)*
44                    __p.word("}");
45                },
46            )
47        }
48        Fields::Unnamed(fields_unnamed) => {
49            let mut field_names = Vec::new();
50
51            for idx in 0..fields_unnamed.unnamed.len() {
52                let name = format_ident!("f{idx}");
53                disps.push(quote! {
54                    if #name.should_render() {
55                        if __printed_anything {
56                            __p.word_space(",");
57                        }
58                        __printed_anything = true;
59                    }
60                    #name.print_attribute(__p);
61                });
62                field_names.push(name);
63            }
64
65            (
66                quote! { (#(#field_names),*) },
67                quote! {
68                    __p.word(#string_name);
69
70                    if true #(&& !#field_names.should_render())* {
71                        return;
72                    }
73
74                    __p.popen();
75                    #(#disps)*
76                    __p.pclose();
77                },
78            )
79        }
80        Fields::Unit => (quote! {}, quote! { __p.word(#string_name) }),
81    }
82}
83
84pub(crate) fn print_attribute(input: Structure<'_>) -> TokenStream {
85    let span_error = |span, message: &str| {
86        quote_spanned! { span => const _: () = ::core::compile_error!(#message); }
87    };
88
89    // Must be applied to an enum type.
90    let code = match &input.ast().data {
91        Data::Enum(e) => {
92            let arms = e
93                .variants
94                .iter()
95                .map(|x| {
96                    let ident = &x.ident;
97                    let (pat, code) = print_fields(ident, &x.fields);
98
99                    quote! {
100                        Self::#ident #pat => {#code}
101                    }
102                })
103                .collect::<Vec<_>>();
104
105            quote! {
106                match self {
107                    #(#arms)*
108                }
109            }
110        }
111        Data::Struct(s) => {
112            let (pat, code) = print_fields(&input.ast().ident, &s.fields);
113            quote! {
114                let Self #pat = self;
115                #code
116            }
117        }
118        Data::Union(u) => {
119            return span_error(u.union_token.span(), "can't derive PrintAttribute on unions");
120        }
121    };
122
123    #[allow(keyword_idents_2024)]
124    input.gen_impl(quote! {
125        #[allow(unused)]
126        gen impl PrintAttribute for @Self {
127            fn should_render(&self) -> bool { true }
128            fn print_attribute(&self, __p: &mut rustc_ast_pretty::pp::Printer) { #code }
129        }
130    })
131}