luars 0.26.2

A library for lua 5.5 runtime implementation in Rust
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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
// Trait-based Userdata system for Lua-rs
//
// Instead of using Lua's traditional metatable-based approach for userdata access,
// we leverage Rust's trait system for direct, type-safe dispatch of field access,
// method calls, and metamethods.
//
// Key design principles:
// 1. Trait-based dispatch (no metatable lookup for known operations)
// 2. Auto-derive from Rust structs via `#[derive(LuaUserData)]`
// 3. Automatic metamethod generation from Rust trait impls (Display → __tostring, Ord → __lt, etc.)
// 4. Backward compatibility via `as_any()` downcasting
// 5. Metatables still work as fallback for Lua-level customization

use std::any::Any;
use std::fmt;

use crate::lua_vm::CFunction;
use crate::{LuaResult, LuaState, LuaUserdata, LuaValue, RefAliveToken};

/// Intermediate value type for userdata field/method returns.
///
/// Since `LuaValue` requires GC-allocated strings, trait methods return `UdValue`
/// which the VM converts to proper `LuaValue` (interning strings as needed).
pub enum UdValue {
    Nil,
    Boolean(bool),
    Integer(i64),
    Number(f64),
    /// A Rust string — will be interned by the VM when converting to LuaValue
    Str(String),
    /// A light C function — used for returning methods from `get_field`
    Function(CFunction),
    /// Borrowed reference to another userdata's inner value (as operand in
    /// arithmetic/comparison). Valid only during the trait method call.
    /// Use [`UdValue::as_userdata_ref`] to safely downcast.
    UserdataRef(*const dyn Any),
    /// Owned userdata value (as return from arithmetic trait methods).
    /// The VM allocates this as a new GC-managed userdata.
    UserdataOwned(Box<dyn UserDataTrait>),
    /// Marker for a sub-reference candidate. Contains a raw pointer to data
    /// inside the parent userdata. The VM layer converts this to a
    /// [`SubRef`](crate::SubRef) by combining it with the parent's sub_guard token.
    SubRef(*const (dyn UserDataTrait + 'static)),
}

impl Clone for UdValue {
    fn clone(&self) -> Self {
        match self {
            UdValue::Nil => UdValue::Nil,
            UdValue::Boolean(b) => UdValue::Boolean(*b),
            UdValue::Integer(i) => UdValue::Integer(*i),
            UdValue::Number(n) => UdValue::Number(*n),
            UdValue::Str(s) => UdValue::Str(s.clone()),
            UdValue::Function(f) => UdValue::Function(*f),
            UdValue::UserdataRef(p) => UdValue::UserdataRef(*p),
            UdValue::UserdataOwned(_) => UdValue::Nil,
            UdValue::SubRef(p) => UdValue::SubRef(*p),
        }
    }
}

impl UdValue {
    #[inline]
    pub fn is_nil(&self) -> bool {
        matches!(self, UdValue::Nil)
    }

    /// Try to downcast a `UserdataRef` operand to a concrete type.
    ///
    /// Returns `Some(&T)` if the operand is a userdata of type `T`.
    /// This is the primary way to access the other operand in arithmetic
    /// trait methods when both operands are userdata.
    ///
    /// # Safety
    /// The returned reference borrows from the GC-managed userdata on the
    /// Lua stack. It is valid for the duration of the trait method call.
    ///
    /// # Example (generated by derive macro)
    /// ```ignore
    /// fn lua_add(&self, other: &UdValue) -> Option<UdValue> {
    ///     if let Some(o) = other.as_userdata_ref::<Vec2>() {
    ///         Some(UdValue::from_userdata(Vec2 { x: self.x + o.x, y: self.y + o.y }))
    ///     } else {
    ///         None
    ///     }
    /// }
    /// ```
    #[inline]
    pub fn as_userdata_ref<T: 'static>(&self) -> Option<&T> {
        match self {
            UdValue::UserdataRef(ptr) => {
                // SAFETY: The pointer originates from a GC-managed userdata that
                // is alive on the Lua stack during this call. The VM guarantees
                // the pointer remains valid for the duration of the trait method.
                let any_ref: &dyn Any = unsafe { &**ptr };
                any_ref.downcast_ref::<T>()
            }
            _ => None,
        }
    }

    /// Wrap a value that implements `UserDataTrait` into an owned `UdValue`.
    ///
    /// Use this as the return value from arithmetic trait methods when the
    /// result is a new userdata (e.g., `Vec2 + Vec2 → Vec2`).
    #[inline]
    pub fn from_userdata<T: UserDataTrait>(value: T) -> Self {
        UdValue::UserdataOwned(Box::new(value))
    }
}

/// Describes how a userdata type can be accessed from Lua.
///
/// This trait provides rich, typed access to struct fields, methods, and standard
/// operations. The `#[derive(LuaUserData)]` macro auto-implements this trait by
/// exposing public fields for structs, or by creating a fieldless userdata facade for
/// enums and tuple/unit structs. Methods are exposed via `#[lua_methods]` attribute macro
/// on impl blocks, which generates static C wrapper functions returned from `get_field`
/// as `UdValue::Function(cfunction)`.
///
/// # Dispatch priority (when Lua accesses `obj.key`):
/// 1. `get_field(key)` — field or method access (fields return value, methods return CFunction)
/// 2. Metatable `__index` — traditional Lua fallback
///
/// # Example (manual implementation)
/// ```ignore
/// struct Point { x: f64, y: f64 }
///
/// impl UserDataTrait for Point {
///     fn type_name(&self) -> &'static str { "Point" }
///
///     fn get_field(&self, key: &str) -> Option<UdValue> {
///         match key {
///             "x" => Some(UdValue::Number(self.x)),
///             "y" => Some(UdValue::Number(self.y)),
///             _ => None,
///         }
///     }
///
///     fn set_field(&mut self, key: &str, value: UdValue) -> Option<Result<(), String>> {
///         match key {
///             "x" => match value {
///                 UdValue::Number(n) => { self.x = n; Some(Ok(())) }
///                 _ => Some(Err("x must be a number".into()))
///             }
///             _ => None,
///         }
///     }
///
///     fn as_any(&self) -> &dyn Any { self }
///     fn as_any_mut(&mut self) -> &mut dyn Any { self }
/// }
/// ```
pub trait UserDataTrait: 'static {
    // ==================== Identity ====================

    /// Returns the type name displayed in error messages and `type()` calls.
    /// For derive macro: uses the struct name.
    fn type_name(&self) -> &'static str;

    // ==================== Field Access ====================

    /// Get a field value by name.
    /// Returns `Some(value)` if the field exists, `None` to fall through to metatable.
    fn get_field(&self, _key: &str) -> Option<UdValue> {
        None
    }

    /// Set a field value by name.
    /// Returns:
    /// - `Some(Ok(()))` — field was set successfully
    /// - `Some(Err(msg))` — field exists but value is invalid (type mismatch, etc.)
    /// - `None` — field not found, fall through to metatable `__newindex`
    fn set_field(&mut self, _key: &str, _value: UdValue) -> Option<Result<(), String>> {
        None
    }

    // ==================== Metamethods ====================
    // These are auto-generated by the derive macro when the struct
    // implements the corresponding Rust trait. Return None = not supported.

    /// `__tostring`: String representation.
    /// Auto-generated when struct implements `Display`.
    fn lua_tostring(&self) -> Option<String> {
        None
    }

    /// `__eq`: Equality comparison.
    /// Auto-generated when struct implements `PartialEq`.
    /// `other` is guaranteed to be a `&dyn UserDataTrait` — downcast via `as_any()`.
    fn lua_eq(&self, _other: &dyn UserDataTrait) -> Option<bool> {
        None
    }

    /// `__lt`: Less-than comparison.
    /// Auto-generated when struct implements `PartialOrd`.
    fn lua_lt(&self, _other: &dyn UserDataTrait) -> Option<bool> {
        None
    }

    /// `__le`: Less-or-equal comparison.
    /// Auto-generated when struct implements `PartialOrd`.
    fn lua_le(&self, _other: &dyn UserDataTrait) -> Option<bool> {
        None
    }

    /// `__len`: Length operator (`#obj`).
    /// Auto-generated when struct has a `.len()` method.
    fn lua_len(&self) -> Option<UdValue> {
        None
    }

    /// `__unm`: Unary minus (`-obj`).
    /// Auto-generated when struct implements `Neg`.
    fn lua_unm(&self) -> Option<UdValue> {
        None
    }

    /// `__bnot`: Bitwise NOT (`~obj`).
    fn lua_bnot(&self) -> Option<UdValue> {
        None
    }

    /// `__add`: Addition (`obj + other`).
    /// Auto-generated when struct implements `Add`.
    fn lua_add(&self, _other: &UdValue) -> Option<UdValue> {
        None
    }

    /// `__sub`: Subtraction (`obj - other`).
    /// Auto-generated when struct implements `Sub`.
    fn lua_sub(&self, _other: &UdValue) -> Option<UdValue> {
        None
    }

    /// `__mul`: Multiplication (`obj * other`).
    /// Auto-generated when struct implements `Mul`.
    fn lua_mul(&self, _other: &UdValue) -> Option<UdValue> {
        None
    }

    /// `__div`: Division (`obj / other`).
    /// Auto-generated when struct implements `Div`.
    fn lua_div(&self, _other: &UdValue) -> Option<UdValue> {
        None
    }

    /// `__mod`: Modulo (`obj % other`).
    /// Auto-generated when struct implements `Rem`.
    fn lua_mod(&self, _other: &UdValue) -> Option<UdValue> {
        None
    }

    /// `__pow`: Exponentiation (`obj ^ other`).
    fn lua_pow(&self, _other: &UdValue) -> Option<UdValue> {
        None
    }

    /// `__idiv`: Integer division (`obj // other`).
    fn lua_idiv(&self, _other: &UdValue) -> Option<UdValue> {
        None
    }

    /// `__band`: Bitwise AND (`obj & other`).
    fn lua_band(&self, _other: &UdValue) -> Option<UdValue> {
        None
    }

    /// `__bor`: Bitwise OR (`obj | other`).
    fn lua_bor(&self, _other: &UdValue) -> Option<UdValue> {
        None
    }

    /// `__bxor`: Bitwise XOR (`obj ~ other`).
    fn lua_bxor(&self, _other: &UdValue) -> Option<UdValue> {
        None
    }

    /// `__shl`: Left shift (`obj << other`).
    fn lua_shl(&self, _other: &UdValue) -> Option<UdValue> {
        None
    }

    /// `__shr`: Right shift (`obj >> other`).
    fn lua_shr(&self, _other: &UdValue) -> Option<UdValue> {
        None
    }

    /// `__concat`: Concatenation (`obj .. other`).
    fn lua_concat(&self, _other: &UdValue) -> Option<UdValue> {
        None
    }

    /// `__close`: Called when a to-be-closed variable goes out of scope.
    fn lua_close(&mut self) {}

    /// `__call`: Makes the userdata callable like a function.
    ///
    /// Return `Some(cfunction)` to make `obj(args...)` work from Lua.
    /// The CFunction receives `self` (the userdata) as arg 1, followed by
    /// the caller's arguments.
    ///
    /// This is checked before the metatable `__call` fallback.
    ///
    /// # Example
    /// ```ignore
    /// fn lua_call(&self) -> Option<CFunction> {
    ///     fn call_impl(l: &mut LuaState) -> LuaResult<usize> {
    ///         let ud = l.get_arg(1).unwrap();
    ///         let x = l.get_arg(2).and_then(|v| v.as_integer()).unwrap_or(0);
    ///         l.push_value(LuaValue::integer(x * 2))?;
    ///         Ok(1)
    ///     }
    ///     Some(call_impl)
    /// }
    /// ```
    fn lua_call(&self) -> Option<CFunction> {
        None
    }

    // ==================== Iteration ====================

    /// Stateless iterator: given the current control variable, return the next
    /// `(control, value)` pair, or `None` to stop.
    ///
    /// This follows Lua's generic-for protocol:
    /// ```lua
    /// for k, v in pairs(ud) do ... end
    /// ```
    ///
    /// The control variable starts as `UdValue::Nil`. Implementors decide
    /// what it represents (e.g., an integer index for sequences).
    ///
    /// # Example (Vec-like)
    /// ```ignore
    /// fn lua_next(&self, control: &UdValue) -> Option<(UdValue, UdValue)> {
    ///     let idx = match control {
    ///         UdValue::Nil => 0,
    ///         UdValue::Integer(i) => *i as usize,
    ///         _ => return None,
    ///     };
    ///     self.items.get(idx).map(|v| (
    ///         UdValue::Integer((idx + 1) as i64),
    ///         UdValue::Integer(*v as i64),
    ///     ))
    /// }
    /// ```
    fn lua_next(&self, _control: &UdValue) -> Option<(UdValue, UdValue)> {
        None
    }

    // ==================== Reflection ====================

    /// List available field names (for debugging, iteration, auto-completion).
    fn field_names(&self) -> &'static [&'static str] {
        &[]
    }

    // ==================== Downcasting ====================
    // Required for backward compatibility and type-specific access.
    // The derive macro auto-generates these.

    /// Downcast to `&dyn Any` for type-specific access.
    fn as_any(&self) -> &dyn Any;

    /// Downcast to `&mut dyn Any` for mutable type-specific access.
    fn as_any_mut(&mut self) -> &mut dyn Any;
}

// ==================== UdValue ↔ Rust type conversions ====================

impl From<bool> for UdValue {
    fn from(b: bool) -> Self {
        UdValue::Boolean(b)
    }
}

impl From<i64> for UdValue {
    fn from(i: i64) -> Self {
        UdValue::Integer(i)
    }
}

impl From<i32> for UdValue {
    fn from(i: i32) -> Self {
        UdValue::Integer(i as i64)
    }
}

impl From<f64> for UdValue {
    fn from(n: f64) -> Self {
        UdValue::Number(n)
    }
}

impl From<f32> for UdValue {
    fn from(n: f32) -> Self {
        UdValue::Number(n as f64)
    }
}

impl From<String> for UdValue {
    fn from(s: String) -> Self {
        UdValue::Str(s)
    }
}

impl From<&str> for UdValue {
    fn from(s: &str) -> Self {
        UdValue::Str(s.to_owned())
    }
}

impl<T: Into<UdValue>> From<Option<T>> for UdValue {
    fn from(opt: Option<T>) -> Self {
        match opt {
            Some(v) => v.into(),
            None => UdValue::Nil,
        }
    }
}

// ==================== UdValue → Rust type extraction ====================

impl UdValue {
    /// Extract as bool. Follows Lua truthiness: nil and false are false, everything else is true.
    pub fn to_bool(&self) -> bool {
        match self {
            UdValue::Nil => false,
            UdValue::Boolean(b) => *b,
            _ => true,
        }
    }

    /// Extract as i64 (with optional float→int coercion).
    pub fn to_integer(&self) -> Option<i64> {
        match self {
            UdValue::Integer(i) => Some(*i),
            UdValue::Number(n) => {
                let i = *n as i64;
                if (i as f64) == *n { Some(i) } else { None }
            }
            _ => None,
        }
    }

    /// Extract as f64 (with optional int→float coercion).
    pub fn to_number(&self) -> Option<f64> {
        match self {
            UdValue::Number(n) => Some(*n),
            UdValue::Integer(i) => Some(*i as f64),
            _ => None,
        }
    }

    /// Extract as string reference.
    pub fn to_str(&self) -> Option<&str> {
        match self {
            UdValue::Str(s) => Some(s.as_str()),
            _ => None,
        }
    }
}

impl fmt::Debug for UdValue {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            UdValue::Nil => write!(f, "Nil"),
            UdValue::Boolean(b) => write!(f, "Boolean({})", b),
            UdValue::Integer(i) => write!(f, "Integer({})", i),
            UdValue::Number(n) => write!(f, "Number({})", n),
            UdValue::Str(s) => write!(f, "Str({:?})", s),
            UdValue::Function(_) => write!(f, "Function(<cfunction>)"),
            UdValue::UserdataRef(_) => write!(f, "UserdataRef(<ptr>)"),
            UdValue::UserdataOwned(ud) => write!(f, "UserdataOwned({})", ud.type_name()),
            UdValue::SubRef(_) => write!(f, "SubRef(<ptr>)"),
        }
    }
}

impl fmt::Display for UdValue {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            UdValue::Nil => write!(f, "nil"),
            UdValue::Boolean(b) => write!(f, "{}", b),
            UdValue::Integer(i) => write!(f, "{}", i),
            UdValue::Number(n) => write!(f, "{}", n),
            UdValue::Str(s) => write!(f, "{}", s),
            UdValue::Function(_) => write!(f, "function"),
            UdValue::UserdataRef(_) => write!(f, "userdata"),
            UdValue::UserdataOwned(ud) => write!(f, "{}", ud.type_name()),
            UdValue::SubRef(_) => write!(f, "userdata"),
        }
    }
}

// ==================== UdValue ↔ LuaValue conversion ====================

/// Convert a `UdValue` to a `LuaValue`.
///
/// Most variants are zero-cost. `UdValue::Str` requires GC allocation via `LuaState`.
/// This is the bridge between trait-based dispatch (which returns `UdValue`) and the
/// VM's internal representation (`LuaValue`).
pub fn udvalue_to_lua_value(lua_state: &mut LuaState, udv: UdValue) -> LuaResult<LuaValue> {
    match udv {
        UdValue::Nil => Ok(LuaValue::nil()),
        UdValue::Boolean(b) => Ok(LuaValue::boolean(b)),
        UdValue::Integer(i) => Ok(LuaValue::integer(i)),
        UdValue::Number(n) => Ok(LuaValue::float(n)),
        UdValue::Str(s) => lua_state.create_string(&s),
        UdValue::Function(f) => Ok(LuaValue::cfunction(f)),
        UdValue::UserdataRef(_) => Ok(LuaValue::nil()),
        UdValue::UserdataOwned(ud) => {
            let userdata = LuaUserdata::from_boxed(ud);
            lua_state.create_userdata(userdata)
        }
        UdValue::SubRef(_) => {
            // SubRef without a parent token is an error — the caller must use
            // udvalue_to_lua_value_with_token
            panic!("UdValue::SubRef requires parent token; use udvalue_to_lua_value_with_token")
        }
    }
}

/// Convert a `UdValue` to a `LuaValue`, with an optional parent sub-ref token.
///
/// If `udv` is `UdValue::SubRef(ptr)` and `parent_token` is `Some`, creates a
/// [`SubRefRaw`](crate::lua_value::sub_ref::SubRefRaw) wrapper linked to the parent.
/// Otherwise delegates to [`udvalue_to_lua_value`].
pub fn udvalue_to_lua_value_with_token(
    lua_state: &mut LuaState,
    udv: UdValue,
    parent_token: RefAliveToken,
) -> LuaResult<LuaValue> {
    if let UdValue::SubRef(ptr) = udv {
        let userdata = LuaUserdata::from_trait_ptr(ptr, parent_token);
        return lua_state.create_userdata(userdata);
    }
    udvalue_to_lua_value(lua_state, udv)
}

/// Convert a `LuaValue` to a `UdValue`.
///
/// Lossless for nil, bool, int, float, string. Other types (table, function, etc.)
/// become `UdValue::Nil` since they can't be represented in the trait world.
pub fn lua_value_to_udvalue(value: &LuaValue) -> UdValue {
    if value.is_nil() {
        UdValue::Nil
    } else if let Some(b) = value.as_boolean() {
        UdValue::Boolean(b)
    } else if let Some(i) = value.as_integer() {
        UdValue::Integer(i)
    } else if let Some(n) = value.as_float() {
        UdValue::Number(n)
    } else if let Some(s) = value.as_str() {
        UdValue::Str(s.to_owned())
    } else if let Some(ud) = value.as_userdata_mut() {
        // Carry userdata reference so arithmetic trait methods can downcast
        {
            let trait_obj = match ud.get_trait() {
                Ok(t) => t,
                Err(_) => return UdValue::Nil,
            };
            UdValue::UserdataRef(trait_obj.as_any() as *const dyn Any)
        }
    } else {
        UdValue::Nil
    }
}

// ==================== Convenience macro for simple types ====================

/// Implement `UserDataTrait` for types that only need type name and downcast support.
/// These types use metatables for their Lua-visible API (e.g., IO file handles).
///
/// ```ignore
/// impl_simple_userdata!(LuaFile, "FILE*");
/// ```
#[macro_export]
macro_rules! impl_simple_userdata {
    ($ty:ty, $name:expr) => {
        impl $crate::lua_value::userdata_trait::UserDataTrait for $ty {
            fn type_name(&self) -> &'static str {
                $name
            }

            fn as_any(&self) -> &dyn std::any::Any {
                self
            }

            fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
                self
            }
        }
    };
}

// ==================== Method Provider ====================

/// Blanket trait providing a default no-op method lookup.
///
/// When `#[lua_methods]` attribute macro is used on an impl block,
/// it generates an inherent `__lua_lookup_method` function on the type
/// that shadows this trait's default. The derive macro's `get_field`
/// calls `Self::__lua_lookup_method(key)` which resolves to the
/// inherent method (if defined) or falls back to this default.
pub trait LuaMethodProvider {
    fn __lua_lookup_method(_key: &str) -> Option<CFunction> {
        None
    }
}

impl<T> LuaMethodProvider for T {}

// ==================== Type Registration ====================

/// Blanket trait providing a default empty static methods list.
///
/// When `#[lua_methods]` is used on an impl block that contains associated
/// functions (no `self`), it generates an inherent `__lua_static_methods()`
/// function on the type that shadows this trait's default.
///
/// Used by `LuaState::register_type::<T>(name)` to populate the class table.
pub trait LuaStaticMethodProvider {
    fn __lua_static_methods() -> &'static [(&'static str, CFunction)] {
        &[]
    }
}

impl<T> LuaStaticMethodProvider for T {}

/// Trait for types that can be registered with Lua via `register_type_of::<T>`.
///
/// This trait is explicitly implemented by `#[lua_methods]` (no blanket impl),
/// so `T::lua_static_methods()` dispatches to the actual generated methods.
///
/// Unlike `LuaStaticMethodProvider` (which has a blanket impl that always
/// returns `&[]`), this trait guarantees that the type has real method info.
pub trait LuaRegistrable {
    /// Return all static (associated) methods for type registration.
    fn lua_static_methods() -> &'static [(&'static str, CFunction)];
}

// ==================== Enum Export ====================

/// Trait for Rust enums that can be exported to Lua as a table of constants.
///
/// Automatically implemented by `#[derive(LuaUserData)]` on C-like enums
/// (enums with no data fields). Each variant becomes a key-value pair in
/// a Lua table.
///
/// # Example
///
/// ```ignore
/// #[derive(LuaUserData)]
/// enum Color {
///     Red,    // 0
///     Green,  // 1
///     Blue,   // 2
/// }
///
/// // With explicit discriminants:
/// #[derive(LuaUserData)]
/// enum HttpStatus {
///     Ok = 200,
///     NotFound = 404,
///     ServerError = 500,
/// }
///
/// // Register in Lua:
/// vm.register_enum::<Color>("Color")?;
/// // Lua: Color.Red == 0, Color.Green == 1, Color.Blue == 2
/// ```
pub trait LuaEnum {
    /// Return variant name-value pairs for Lua table construction.
    fn variants() -> &'static [(&'static str, i64)];

    /// Return the enum's type name.
    fn enum_name() -> &'static str;
}

// ==================== OpaqueUserData ====================

/// Wraps any `T: 'static` as an opaque Lua userdata.
///
/// No fields, methods, or metamethods are exposed — the value is a "black box"
/// in Lua. From Rust you can recover the original type via `downcast_ref::<T>()`.
///
/// Use [`GlobalState::create_any`](crate::GlobalState::create_any) to create one conveniently.
///
/// # Example
///
/// ```ignore
/// // Third-party type you don't control
/// let client = reqwest::Client::new();
/// let ud = vm.push_any(client)?;
/// vm.set_global("http_client", ud)?;
///
/// // Later, in a Rust callback:
/// let client = ud_value.downcast_ref::<reqwest::Client>().unwrap();
/// ```
pub struct OpaqueUserData<T: 'static> {
    value: T,
}

impl<T: 'static> OpaqueUserData<T> {
    /// Wrap a value.
    pub fn new(value: T) -> Self {
        OpaqueUserData { value }
    }

    /// Get a reference to the inner value.
    pub fn inner(&self) -> &T {
        &self.value
    }

    /// Get a mutable reference to the inner value.
    pub fn inner_mut(&mut self) -> &mut T {
        &mut self.value
    }
}

impl<T: 'static> UserDataTrait for OpaqueUserData<T> {
    fn type_name(&self) -> &'static str {
        std::any::type_name::<T>()
    }

    fn as_any(&self) -> &dyn Any {
        // Downcast to T (not OpaqueUserData<T>) for ergonomic access
        &self.value
    }

    fn as_any_mut(&mut self) -> &mut dyn Any {
        &mut self.value
    }
}