ombre-derive/src/lib.rs 9.7 KiB raw
1
//! Derive macros for the ombre crate.
2
use proc_macro::TokenStream;
3
use quote::quote;
4
use syn::{Data, DeriveInput, Error, Fields, parse_macro_input};
5
6
/// Derives the `VertexAttributes` trait for structs.
7
///
8
/// Fields can be renamed in the shader using `#[attrib(name = "...")]`.
9
#[proc_macro_derive(VertexAttributes, attributes(attrib))]
10
pub fn derive_vertex_attributes(input: TokenStream) -> TokenStream {
11
    let ast = parse_macro_input!(input as DeriveInput);
12
    let name = &ast.ident;
13
14
    // Only allow structs with named fields
15
    let fields = match &ast.data {
16
        Data::Struct(data) => match &data.fields {
17
            Fields::Named(fields) => &fields.named,
18
            _ => {
19
                return syn::Error::new_spanned(
20
                    name,
21
                    "`VertexAttributes` can only be derived for structs with named fields",
22
                )
23
                .to_compile_error()
24
                .into();
25
            }
26
        },
27
        _ => {
28
            return syn::Error::new_spanned(
29
                name,
30
                "`VertexAttributes` can only be derived for structs",
31
            )
32
            .to_compile_error()
33
            .into();
34
        }
35
    };
36
37
    // Generate attribute descriptors for each field
38
    let attrs = fields.iter().map(|field| {
39
        let field_name = field.ident.as_ref().unwrap();
40
        let ty = &field.ty;
41
42
        // Check for shader name override.
43
        let shader_name = field
44
            .attrs
45
            .iter()
46
            .find(|attr| attr.path.is_ident("attrib"))
47
            .and_then(|attr| {
48
                attr.parse_args_with(|input: syn::parse::ParseStream| {
49
                    let key: syn::Ident = input.parse()?;
50
                    if key != "name" {
51
                        return Err(syn::Error::new(
52
                            key.span(),
53
                            "unknown attribute key, only `name` is valid",
54
                        ));
55
                    }
56
                    input.parse::<syn::Token![=]>()?;
57
                    input.parse::<syn::LitStr>()
58
                })
59
                .ok()
60
            })
61
            .map(|lit| lit.value())
62
            .unwrap_or_else(|| field_name.to_string());
63
64
        quote! {
65
            ombre::gfx::VertexAttribute {
66
                name: #shader_name,
67
                format: <#ty as ombre::gfx::ToVertexFormat>::FORMAT,
68
            }
69
        }
70
    });
71
72
    let packed = packed_impl(&ast);
73
    let expanded = quote! {
74
        impl ombre::gfx::VertexAttributes for #name {
75
            fn attributes() -> &'static [ombre::gfx::VertexAttribute] {
76
                static ATTRS: &[ombre::gfx::VertexAttribute] = &[#(#attrs),*];
77
                ATTRS
78
            }
79
        }
80
        #packed
81
    };
82
    TokenStream::from(expanded)
83
}
84
85
/// Derive macro for implementing the `UniformBlock` trait.
86
#[proc_macro_derive(UniformBlock, attributes(uniform))]
87
pub fn derive_uniform_block(input: TokenStream) -> TokenStream {
88
    let ast = parse_macro_input!(input as DeriveInput);
89
    let name = &ast.ident;
90
91
    // Only allow structs with named fields
92
    let fields = match &ast.data {
93
        Data::Struct(data) => match &data.fields {
94
            Fields::Named(fields) => &fields.named,
95
            _ => {
96
                return Error::new_spanned(
97
                    name,
98
                    "`UniformBlock` can only be derived for structs with named fields",
99
                )
100
                .to_compile_error()
101
                .into();
102
            }
103
        },
104
        _ => {
105
            return Error::new_spanned(name, "`UniformBlock` can only be derived for structs")
106
                .to_compile_error()
107
                .into();
108
        }
109
    };
110
111
    // Generate uniform descriptors for each field.
112
    let descriptors = fields.iter().map(|field| {
113
        let field_ident = field.ident.as_ref().unwrap();
114
        let ty = &field.ty;
115
116
        // Check for shader name override
117
        let uniform_name = field
118
            .attrs
119
            .iter()
120
            .find(|attr| attr.path.is_ident("uniform"))
121
            .and_then(|attr| {
122
                attr.parse_args_with(|input: syn::parse::ParseStream| {
123
                    let key: syn::Ident = input.parse()?;
124
                    if key != "name" {
125
                        return Err(syn::Error::new(
126
                            key.span(),
127
                            "unknown uniform attribute key, only `name` is valid",
128
                        ));
129
                    }
130
                    input.parse::<syn::Token![=]>()?;
131
                    input.parse::<syn::LitStr>()
132
                })
133
                .ok()
134
            })
135
            .map(|lit| lit.value())
136
            .unwrap_or_else(|| field_ident.to_string());
137
138
        quote! {
139
            ombre::gfx::UniformDescriptor {
140
                name: #uniform_name,
141
                kind: <#ty as ombre::gfx::ToUniformKind>::KIND,
142
                arity: <#ty as ombre::gfx::ToUniformKind>::ARITY,
143
            }
144
        }
145
    });
146
147
    let (_, ty_generics, where_clause) = ast.generics.split_for_impl();
148
    let const_params = ast.generics.const_params().collect::<Vec<_>>();
149
    let lifetime_params = ast.generics.lifetimes().collect::<Vec<_>>();
150
151
    let packed = packed_impl(&ast);
152
    let expanded = quote! {
153
        impl<'block, #(#lifetime_params,)* #(#const_params,)*> ombre::gfx::UniformBlock<'block>
154
        for #name #ty_generics #where_clause {
155
            fn layout() -> ombre::gfx::UniformBlockLayout<'block> {
156
                let uniforms = &[#(#descriptors),*];
157
                ombre::gfx::UniformBlockLayout {
158
                    uniforms
159
                }
160
            }
161
        }
162
        #packed
163
    };
164
165
    TokenStream::from(expanded)
166
}
167
168
/// Derive macro for generating lens types for struct fields.
169
#[proc_macro_derive(Lenses, attributes(lens))]
170
pub fn derive_lenses(input: TokenStream) -> TokenStream {
171
    let ast = parse_macro_input!(input as DeriveInput);
172
    let name = &ast.ident;
173
174
    // Only allow structs with named fields
175
    let fields = match &ast.data {
176
        Data::Struct(data) => match &data.fields {
177
            Fields::Named(fields) => &fields.named,
178
            _ => {
179
                return Error::new_spanned(
180
                    name,
181
                    "`Lenses` can only be derived for structs with named fields",
182
                )
183
                .to_compile_error()
184
                .into();
185
            }
186
        },
187
        _ => {
188
            return Error::new_spanned(name, "`Lenses` can only be derived for structs")
189
                .to_compile_error()
190
                .into();
191
        }
192
    };
193
194
    // Generate lens implementations for fields with #[lens] attribute
195
    let lens_impls = fields.iter().filter_map(|field| {
196
        if field.attrs.iter().any(|attr| attr.path.is_ident("lens")) {
197
            let field_name = &field.ident.as_ref().unwrap();
198
            let field_type = &field.ty;
199
            let lens_name = quote::format_ident!("{}Lens", field_name);
200
            let lens_doc = format!(
201
                "Lens for accessing the `{field_name}` field of [`{name}`].\n\n\
202
                This lens allows you to get and modify the `{field_name}` field.",
203
            );
204
            let const_doc = format!(
205
                "A lens for the `{field_name}` field of [`{name}`].\n\n\
206
                Use this constant to access or modify the `{field_name}` field.",
207
            );
208
209
            Some(quote! {
210
                #[doc = #lens_doc]
211
                #[allow(non_camel_case_types)]
212
                #[derive(Debug, Clone, Copy)]
213
                pub struct #lens_name;
214
215
                impl Lens<#name, #field_type> for #lens_name {
216
                    fn with<V, F: FnOnce(&#field_type) -> V>(&self, data: &#name, f: F) -> V {
217
                        f(&data.#field_name)
218
                    }
219
220
                    fn with_mut<V, F: FnOnce(&mut #field_type) -> V>(&self, data: &mut #name, f: F) -> V {
221
                        f(&mut data.#field_name)
222
                    }
223
                }
224
225
                impl #name {
226
                    #[doc = #const_doc]
227
                    #[allow(non_upper_case_globals)]
228
                    pub const #field_name: #lens_name = #lens_name;
229
                }
230
            })
231
        } else {
232
            None
233
        }
234
    });
235
236
    TokenStream::from(quote!(#(#lens_impls)*))
237
}
238
239
/// Derive macro for implementing the `Packed` trait.
240
#[proc_macro_derive(Packed)]
241
pub fn derive_packed(input: TokenStream) -> TokenStream {
242
    let ast = parse_macro_input!(input as DeriveInput);
243
    if !matches!(ast.data, Data::Struct(_)) {
244
        return Error::new_spanned(&ast, "`Packed` can only be derived for structs")
245
            .to_compile_error()
246
            .into();
247
    }
248
    let packed = packed_impl(&ast);
249
    quote!(#packed).into()
250
}
251
252
/// Generate a checked byte layout for a struct.
253
fn packed_impl(ast: &DeriveInput) -> impl quote::ToTokens {
254
    let name = &ast.ident;
255
    let Data::Struct(data) = &ast.data else {
256
        unreachable!("packed_impl requires a struct");
257
    };
258
    let field_types: Vec<_> = data.fields.iter().map(|field| &field.ty).collect();
259
    let mut generics = ast.generics.clone();
260
    for ty in &field_types {
261
        generics
262
            .make_where_clause()
263
            .predicates
264
            .push(syn::parse_quote!(#ty: ombre::bytes::Packed));
265
    }
266
    let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
267
268
    quote! {
269
        unsafe impl #impl_generics ombre::bytes::Packed for #name #ty_generics #where_clause {
270
            const VALID_LAYOUT: () = {
271
                #(let () = <#field_types as ombre::bytes::Packed>::VALID_LAYOUT;)*
272
                assert!(
273
                    ::std::mem::size_of::<Self>() == 0usize #(+ ::std::mem::size_of::<#field_types>())*,
274
                    "Packed type contains padding"
275
                );
276
            };
277
        }
278
    }
279
}