rune_macros/
const_value.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
use core::fmt;

use proc_macro2::{Span, TokenStream};
use quote::{quote, ToTokens};
use syn::parse::{Parse, ParseStream};
use syn::spanned::Spanned;
use syn::DeriveInput;

use crate::context::{Context, Tokens};

/// An internal call to the macro.
pub(super) struct Derive {
    input: DeriveInput,
}

impl Parse for Derive {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        Ok(Self {
            input: input.parse()?,
        })
    }
}

pub(super) struct ConstBuilder<T> {
    ident: T,
    tokens: Tokens,
    body: TokenStream,
    variables: Vec<syn::Ident>,
    members: Vec<syn::Member>,
    from_const_fields: Vec<TokenStream>,
    from_value_fields: Vec<TokenStream>,
}

impl Derive {
    pub(super) fn into_builder(self, cx: &Context) -> Result<ConstBuilder<syn::Ident>, ()> {
        let attr = cx.const_value_type_attrs(&self.input.attrs);
        let tokens = cx.tokens_with_module(attr.module.as_ref());
        let body;

        let Tokens {
            const_value,
            from_const_value_t,
            to_const_value_t,
            type_hash_t,
            from_value,
            value,
            ..
        } = &tokens;

        let mut variables = Vec::new();
        let mut members = Vec::new();
        let mut from_const_fields = Vec::new();
        let mut from_value_fields = Vec::new();

        match self.input.data {
            syn::Data::Struct(data) => {
                let mut fields = Vec::new();

                for (index, field) in data.fields.iter().enumerate() {
                    let attr = cx.const_value_field_attrs(&field.attrs);

                    let member = match &field.ident {
                        Some(ident) => syn::Member::Named(ident.clone()),
                        None => syn::Member::Unnamed(syn::Index::from(index)),
                    };

                    let ty = &field.ty;

                    let var = syn::Ident::new(&format!("v{index}"), Span::call_site());

                    if let Some(path) = &attr.with {
                        let to_const_value: syn::Path =
                            syn::parse_quote_spanned!(path.span() => #path::to_const_value);
                        let from_const_value: syn::Path =
                            syn::parse_quote_spanned!(path.span() => #path::from_const_value);
                        let from_value: syn::Path =
                            syn::parse_quote_spanned!(path.span() => #path::from_value);

                        fields.push(quote!(#to_const_value(self.#member)?));
                        from_const_fields.push(quote!(#from_const_value(#var)?));
                        from_value_fields.push(quote!(#from_value(#value::take(#var))?));
                    } else {
                        fields.push(quote! {
                            <#ty as #to_const_value_t>::to_const_value(self.#member)?
                        });

                        from_const_fields.push(quote! {
                            <#ty as #from_const_value_t>::from_const_value(#var)?
                        });

                        from_value_fields.push(quote! {
                            <#ty as #from_value>::from_value(#value::take(#var))?
                        });
                    }

                    variables.push(var);
                    members.push(member);
                }

                body = quote! {
                    #const_value::for_struct(<Self as #type_hash_t>::HASH, [#(#fields),*])
                };
            }
            syn::Data::Enum(..) => {
                cx.error(syn::Error::new(
                    Span::call_site(),
                    "ToConstValue: enums are not supported",
                ));
                return Err(());
            }
            syn::Data::Union(..) => {
                cx.error(syn::Error::new(
                    Span::call_site(),
                    "ToConstValue: unions are not supported",
                ));
                return Err(());
            }
        }

        Ok(ConstBuilder {
            ident: self.input.ident,
            tokens,
            body,
            variables,
            members,
            from_const_fields,
            from_value_fields,
        })
    }
}

impl<T> ConstBuilder<T>
where
    T: ToTokens + fmt::Display,
{
    pub(super) fn expand(self) -> TokenStream {
        let Tokens {
            arc,
            const_construct_t,
            const_value,
            option,
            result,
            runtime_error,
            to_const_value_t,
            value,
            ..
        } = &self.tokens;

        let ident = self.ident;
        let construct = syn::Ident::new(&format!("{ident}Construct"), Span::call_site());
        let body = self.body;
        let members = &self.members;
        let variables = &self.variables;
        let from_const_fields = &self.from_const_fields;
        let from_value_fields = &self.from_value_fields;

        let expected = self.members.len();

        quote! {
            #[automatically_derived]
            impl #to_const_value_t for #ident {
                #[inline]
                fn to_const_value(self) -> #result<#const_value, #runtime_error> {
                    #body
                }

                #[inline]
                fn construct() -> #option<#arc<dyn #const_construct_t>> {
                    struct #construct;

                    impl #const_construct_t for #construct {
                        #[inline]
                        fn const_construct(&self, values: &[#const_value]) -> #result<#value, #runtime_error> {
                            let [#(#variables),*] = values else {
                                return #result::Err(#runtime_error::bad_argument_count(values.len(), #expected));
                            };

                            let value = #ident {
                                #(#members: #from_const_fields,)*
                            };

                            #result::Ok(#value::new(value)?)
                        }

                        #[inline]
                        fn runtime_construct(&self, values: &mut [#value]) -> #result<#value, #runtime_error> {
                            let [#(#variables),*] = values else {
                                return #result::Err(#runtime_error::bad_argument_count(values.len(), #expected));
                            };

                            let value = #ident {
                                #(#members: #from_value_fields,)*
                            };

                            #result::Ok(#value::new(value)?)
                        }
                    }

                    #option::Some(#arc::new(#construct))
                }
            }
        }
    }
}