lua-rs-derive 0.0.17

Derive macros for the lua-rs embedding API (LuaUserData, lua_methods).
Documentation
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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
//! Derive macros for the lua-rs embedding API.
//!
//! - `#[derive(LuaUserData)]` on a struct generates the `UserData` impl. Rust
//!   visibility is the scriptability boundary: **public** named fields are
//!   auto-exposed to Lua (`obj.field` reads/writes); private fields stay
//!   encapsulated unless force-exposed with `#[lua(field)]`. Tuple/newtype and
//!   unit structs (`struct Handle(App);`) expose no fields and become opaque
//!   userdata handles — ready for `#[lua(methods)]` and metamethods. Field
//!   attributes: `#[lua(skip)]`, `#[lua(readonly)]`, `#[lua(name = "...")]`,
//!   `#[lua(field)]` (force-expose a private field). `IntoLua` comes for free
//!   from the runtime's blanket `impl<T: UserData> IntoLua for T`.
//! - Struct attribute `#[lua_impl(Display, PartialEq, PartialOrd)]` wires the matching
//!   metamethods (`__tostring`, `__eq`, `__lt`/`__le`) from the type's Rust trait impls.
//! - Struct attribute `#[lua(methods)]` makes the generated `UserData` also register the
//!   methods declared by `#[lua_methods]` on an `impl` block.
//! - `#[lua_methods]` on an `impl` block exposes each `pub fn(&self/&mut self, ...)` to
//!   Lua as `obj:method(args)`.

use proc_macro::TokenStream;
use quote::quote;
use syn::{
    parse_macro_input, Data, DeriveInput, Fields, FnArg, ImplItem, ItemImpl, LitStr, ReturnType,
    Type,
};

// ---------------------------------------------------------------------------
// #[derive(LuaUserData)]
// ---------------------------------------------------------------------------

struct FieldCfg {
    ident: syn::Ident,
    ty: Type,
    lua_name: String,
    skip: bool,
    readonly: bool,
    force_field: bool,
}

fn parse_field_cfg(field: &syn::Field) -> syn::Result<FieldCfg> {
    let ident = field
        .ident
        .clone()
        .ok_or_else(|| syn::Error::new_spanned(field, "LuaUserData requires named fields"))?;
    let mut cfg = FieldCfg {
        lua_name: ident.to_string(),
        ident,
        ty: field.ty.clone(),
        skip: false,
        readonly: false,
        force_field: false,
    };
    for attr in &field.attrs {
        if !attr.path().is_ident("lua") {
            continue;
        }
        attr.parse_nested_meta(|meta| {
            if meta.path.is_ident("skip") {
                cfg.skip = true;
                Ok(())
            } else if meta.path.is_ident("readonly") {
                cfg.readonly = true;
                Ok(())
            } else if meta.path.is_ident("field") {
                cfg.force_field = true;
                Ok(())
            } else if meta.path.is_ident("name") {
                let lit: LitStr = meta.value()?.parse()?;
                cfg.lua_name = lit.value();
                Ok(())
            } else {
                Err(meta.error(
                    "unknown #[lua(...)] attribute; expected skip, readonly, field, or name",
                ))
            }
        })?;
    }
    Ok(cfg)
}

/// Struct-level configuration from `#[lua(methods)]` and `#[lua_impl(...)]`.
struct StructCfg {
    register_methods: bool,
    impl_display: bool,
    impl_partial_eq: bool,
    impl_partial_ord: bool,
}

fn parse_struct_cfg(input: &DeriveInput) -> syn::Result<StructCfg> {
    let mut cfg = StructCfg {
        register_methods: false,
        impl_display: false,
        impl_partial_eq: false,
        impl_partial_ord: false,
    };
    for attr in &input.attrs {
        if attr.path().is_ident("lua") {
            attr.parse_nested_meta(|meta| {
                if meta.path.is_ident("methods") {
                    cfg.register_methods = true;
                    Ok(())
                } else {
                    Err(meta.error("unknown #[lua(...)] attribute on struct; expected methods"))
                }
            })?;
        } else if attr.path().is_ident("lua_impl") {
            attr.parse_nested_meta(|meta| {
                if meta.path.is_ident("Display") {
                    cfg.impl_display = true;
                    Ok(())
                } else if meta.path.is_ident("PartialEq") {
                    cfg.impl_partial_eq = true;
                    Ok(())
                } else if meta.path.is_ident("PartialOrd") {
                    cfg.impl_partial_ord = true;
                    Ok(())
                } else {
                    Err(meta.error(
                        "unknown #[lua_impl(...)] trait; expected Display, PartialEq, or PartialOrd",
                    ))
                }
            })?;
        }
    }
    Ok(cfg)
}

/// Derive `UserData` for a struct: field access plus optional methods/metamethods.
#[proc_macro_derive(LuaUserData, attributes(lua, lua_impl))]
pub fn derive_lua_user_data(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    expand_derive(input).unwrap_or_else(|e| e.to_compile_error().into())
}

fn expand_derive(input: DeriveInput) -> syn::Result<TokenStream> {
    let name = &input.ident;

    if !input.generics.params.is_empty() {
        return Err(syn::Error::new_spanned(
            &input.generics,
            "LuaUserData does not yet support generic types",
        ));
    }

    let scfg = parse_struct_cfg(&input)?;

    let fields: Vec<&syn::Field> = match &input.data {
        Data::Struct(s) => match &s.fields {
            Fields::Named(named) => named.named.iter().collect(),
            // Tuple/newtype and unit structs have no named fields, so there is
            // nothing to auto-expose. The struct still becomes an opaque
            // `UserData` handle (type name, methods, metamethods) — the common
            // `struct Handle(App);` engine/resource-wrapper case. (issue #57)
            Fields::Unnamed(_) | Fields::Unit => Vec::new(),
        },
        _ => {
            return Err(syn::Error::new_spanned(
                &input.ident,
                "LuaUserData currently supports only structs",
            ))
        }
    };

    let mut field_regs = Vec::new();
    for field in fields {
        let cfg = parse_field_cfg(field)?;
        // Rust visibility is the scriptability boundary: public fields are
        // auto-exposed; private fields stay encapsulated unless the author
        // force-exposes one with `#[lua(field)]`. This lets a struct hold a
        // non-`Clone`/non-marshalable private field (e.g. `app: App`) and
        // still derive cleanly, since unexposed fields get no getter/setter
        // and so pick up no `Clone`/`IntoLua`/`FromLua` bound. (issue #56)
        let is_pub = matches!(field.vis, syn::Visibility::Public(_));
        if cfg.skip || (!is_pub && !cfg.force_field) {
            continue;
        }
        let ident = &cfg.ident;
        let ty = &cfg.ty;
        let lua_name = &cfg.lua_name;
        field_regs.push(quote! {
            __m.add_field_method_get(#lua_name, |_, __this| {
                ::core::result::Result::Ok(::core::clone::Clone::clone(&__this.#ident))
            });
        });
        if !cfg.readonly {
            field_regs.push(quote! {
                __m.add_field_method_set(#lua_name, |_, __this, __value: #ty| {
                    __this.#ident = __value;
                    ::core::result::Result::Ok(())
                });
            });
        }
    }

    let methods_call = if scfg.register_methods {
        quote! { <Self>::__lua_register_methods(__m); }
    } else {
        quote! {}
    };

    let mut meta_regs = Vec::new();
    if scfg.impl_display {
        meta_regs.push(quote! {
            __m.add_meta_method(::lua_rs_runtime::MetaMethod::ToString, |_, __this, ()| {
                ::core::result::Result::Ok(::std::string::ToString::to_string(__this))
            });
        });
    }
    if scfg.impl_partial_eq {
        meta_regs.push(quote! {
            __m.add_meta_method(
                ::lua_rs_runtime::MetaMethod::Eq,
                |_, __this, __other: ::lua_rs_runtime::Value| {
                    if let ::lua_rs_runtime::Value::UserData(__ud) = __other {
                        if let ::core::result::Result::Ok(__o) = __ud.borrow::<#name>() {
                            return ::core::result::Result::Ok(*__this == *__o);
                        }
                    }
                    ::core::result::Result::Ok(false)
                },
            );
        });
    }
    if scfg.impl_partial_ord {
        meta_regs.push(quote! {
            __m.add_meta_method(
                ::lua_rs_runtime::MetaMethod::Lt,
                |_, __this, __other: ::lua_rs_runtime::Value| {
                    if let ::lua_rs_runtime::Value::UserData(__ud) = __other {
                        if let ::core::result::Result::Ok(__o) = __ud.borrow::<#name>() {
                            return ::core::result::Result::Ok(*__this < *__o);
                        }
                    }
                    ::core::result::Result::Ok(false)
                },
            );
            __m.add_meta_method(
                ::lua_rs_runtime::MetaMethod::Le,
                |_, __this, __other: ::lua_rs_runtime::Value| {
                    if let ::lua_rs_runtime::Value::UserData(__ud) = __other {
                        if let ::core::result::Result::Ok(__o) = __ud.borrow::<#name>() {
                            return ::core::result::Result::Ok(*__this <= *__o);
                        }
                    }
                    ::core::result::Result::Ok(false)
                },
            );
        });
    }

    let add_meta_methods = if meta_regs.is_empty() {
        quote! {}
    } else {
        quote! {
            fn add_meta_methods<__M: ::lua_rs_runtime::UserDataMethods<Self>>(__m: &mut __M) {
                #(#meta_regs)*
            }
        }
    };

    let expanded = quote! {
        impl ::lua_rs_runtime::UserData for #name {
            fn add_methods<__M: ::lua_rs_runtime::UserDataMethods<Self>>(__m: &mut __M) {
                #(#field_regs)*
                #methods_call
            }
            #add_meta_methods
        }
    };

    Ok(expanded.into())
}

// ---------------------------------------------------------------------------
// #[lua_methods]
// ---------------------------------------------------------------------------

/// Expose an `impl` block's public methods to Lua as `obj:method(args)`.
#[proc_macro_attribute]
pub fn lua_methods(_attr: TokenStream, item: TokenStream) -> TokenStream {
    let item = parse_macro_input!(item as ItemImpl);
    expand_methods(item).unwrap_or_else(|e| e.to_compile_error().into())
}

fn expand_methods(item: ItemImpl) -> syn::Result<TokenStream> {
    let self_ty = &item.self_ty;
    let mut regs = Vec::new();

    for impl_item in &item.items {
        let ImplItem::Fn(method) = impl_item else {
            continue;
        };
        if !matches!(method.vis, syn::Visibility::Public(_)) {
            continue;
        }

        // Must have a self receiver to be callable as obj:method(...).
        let receiver = method.sig.inputs.first().and_then(|arg| match arg {
            FnArg::Receiver(r) => Some(r),
            _ => None,
        });
        let Some(receiver) = receiver else {
            continue;
        };
        let is_mut = receiver.mutability.is_some();

        let name = &method.sig.ident;
        let lua_name = name.to_string();

        // Collect the non-self arguments: names + types.
        let mut arg_names = Vec::new();
        let mut arg_types = Vec::new();
        for (i, arg) in method.sig.inputs.iter().enumerate().skip(1) {
            let FnArg::Typed(pat) = arg else {
                return Err(syn::Error::new_spanned(
                    arg,
                    "#[lua_methods] does not support a second receiver",
                ));
            };
            let ident = syn::Ident::new(&format!("__a{i}"), proc_macro2::Span::call_site());
            arg_names.push(ident);
            arg_types.push((*pat.ty).clone());
        }

        // Closure argument binding: () for none, `name: T` for one, `(..): (..)` for many.
        let arg_binding = match arg_names.len() {
            0 => quote! { () },
            1 => {
                let n = &arg_names[0];
                let t = &arg_types[0];
                quote! { #n: #t }
            }
            _ => {
                quote! { ( #(#arg_names),* ): ( #(#arg_types),* ) }
            }
        };

        // A method that returns a reference can't be marshaled as a Lua value;
        // instead it names a sub-object reachable from `self`. Register it as
        // an `add_function` that builds a delegate (a live sub-reference,
        // re-borrowed from the parent per call). `&mut T` returns become a
        // mutable delegate, `&T` returns a read-only one.
        if let ReturnType::Type(_, ty) = &method.sig.output {
            if let Type::Reference(r) = &**ty {
                let referent = &*r.elem;
                let ret_is_mut = r.mutability.is_some();
                if !ret_is_mut && is_mut {
                    return Err(syn::Error::new_spanned(
                        &method.sig,
                        "#[lua_methods]: a method returning `&T` must take `&self`; \
                         use `-> &mut T` to expose a mutable delegate",
                    ));
                }
                let func_binding = if arg_names.is_empty() {
                    quote! { __ud: ::lua_rs_runtime::AnyUserData }
                } else {
                    quote! {
                        ( __ud #(, #arg_names)* ):
                            ( ::lua_rs_runtime::AnyUserData #(, #arg_types)* )
                    }
                };
                let accessor = quote! { move |__this| <#self_ty>::#name(__this #(, #arg_names)*) };
                let reg = if ret_is_mut {
                    quote! {
                        __m.add_function(#lua_name, |__lua, #func_binding| {
                            __ud.delegate::<Self, #referent, _>(__lua, #accessor)
                        });
                    }
                } else {
                    quote! {
                        __m.add_function(#lua_name, |__lua, #func_binding| {
                            __ud.delegate_ref::<Self, #referent, _>(__lua, #accessor)
                        });
                    }
                };
                regs.push(reg);
                continue;
            }
        }

        let call = quote! { <#self_ty>::#name(__this #(, #arg_names)*) };
        let returns_unit = matches!(&method.sig.output, ReturnType::Default)
            || matches!(&method.sig.output, ReturnType::Type(_, ty) if is_unit_type(ty));
        let body = if returns_unit {
            quote! { { #call; ::core::result::Result::Ok(()) } }
        } else {
            quote! { ::core::result::Result::Ok(#call) }
        };

        if is_mut {
            regs.push(quote! {
                __m.add_method_mut(#lua_name, |_, __this, #arg_binding| #body);
            });
        } else {
            regs.push(quote! {
                __m.add_method(#lua_name, |_, __this, #arg_binding| #body);
            });
        }
    }

    let expanded = quote! {
        #item

        impl #self_ty {
            #[doc(hidden)]
            fn __lua_register_methods<__M: ::lua_rs_runtime::UserDataMethods<Self>>(__m: &mut __M) {
                #(#regs)*
            }
        }
    };

    Ok(expanded.into())
}

fn is_unit_type(ty: &Type) -> bool {
    matches!(ty, Type::Tuple(t) if t.elems.is_empty())
}