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
use std::ffi::CStr;
use std::marker::PhantomData;
use std::mem::MaybeUninit;

use sealed::sealed;
use thiserror::Error;

use crate::class::ClassKind;
use crate::repr::{FromRepr, IntoRepr, NativeRepr};
use crate::types::{
    CName, Class, Function, FunctionFlags, FunctionHandler, GlobalFunction, IScriptable, Method,
    PoolRef, Ref, StackArg, StackFrame, StaticMethod,
};
use crate::{ScriptClass, VoidPtr};

/// An error returned when invoking a function fails.
#[derive(Debug, Error)]
pub enum InvokeError {
    #[error("function could not be found by full name '{0}'")]
    FunctionNotFound(&'static str),
    #[error("class could not be found by name '{0}'")]
    ClassNotFound(&'static str),
    #[error(
        "method could not be found by full name '{0}', available options: {}",
        .1.iter()
            .fold(String::new() ,|mut acc, el| {
                if !acc.is_empty() {
                    acc.push_str(", ");
                }
                acc.push('\'');
                acc.push_str(el.as_str());
                acc.push('\'');
                acc
            })
    )]
    MethodNotFound(&'static str, Box<[CName]>),
    #[error("invalid number of arguments, expected {expected} for {function}")]
    InvalidArgCount {
        function: &'static str,
        expected: u32,
    },
    #[error("expected '{expected}' argument type at index {index} for '{function}'")]
    ArgMismatch {
        function: &'static str,
        expected: &'static str,
        index: usize,
    },
    #[error("return type mismatch, expected '{expected}' for '{function}'")]
    ReturnMismatch {
        function: &'static str,
        expected: &'static str,
    },
    #[error("could not resolve type {0}")]
    UnresolvedType(&'static str),
    #[error("execution of '{0}' has failed")]
    ExecutionFailed(&'static str),
    #[error("the 'this' pointer for class '{0}' was null")]
    NullReceiver(&'static str),
}

impl InvokeError {
    #[doc(hidden)]
    #[cold]
    pub fn new_method_not_found<'a>(
        name: &'static str,
        options: impl IntoIterator<Item = &'a Method>,
    ) -> InvokeError {
        let options = options
            .into_iter()
            .map(|m| m.as_function().name())
            .collect();
        InvokeError::MethodNotFound(name, options)
    }
}

/// A trait for functions that can be exported as global functions.
#[sealed]
pub trait GlobalInvocable<A, R> {
    const FN_TYPE: FunctionType;

    fn invoke(self, ctx: &IScriptable, frame: &mut StackFrame, ret: &mut MaybeUninit<R>);
}

macro_rules! impl_global_invocable {
    ($( ($( $types:ident ),*) ),*) => {
        $(
            #[allow(non_snake_case, unused_variables)]
            #[sealed]
            impl<$($types,)* R, FN> GlobalInvocable<($($types,)*), R::Repr> for FN
            where
                FN: Fn($($types,)*) -> R,
                $($types: FromRepr, $types::Repr: Default,)*
                R: IntoRepr
            {
                const FN_TYPE: FunctionType = FunctionType {
                    args: &[$(CName::new($types::Repr::NAME),)*],
                    ret: CName::new(R::Repr::NAME)
                };

                #[inline]
                fn invoke(self, _ctx: &IScriptable, frame: &mut StackFrame, ret: &mut MaybeUninit<R::Repr>) {
                    $(let $types = unsafe { frame.get_arg::<$types>() };)*
                    let res = self($($types,)*);
                    unsafe { ret.as_mut_ptr().write(res.into_repr()) }
                }
            }
        )*
    };
}

impl_global_invocable!(
    (),
    (A),
    (A, B),
    (A, B, C),
    (A, B, C, D),
    (A, B, C, D, E),
    (A, B, C, D, E, F),
    (A, B, C, D, E, F, G)
);

/// A trait for functions that can be exported as class methods.
#[sealed]
pub trait MethodInvocable<Ctx, A, R> {
    const FN_TYPE: FunctionType;

    fn invoke(self, ctx: &Ctx, frame: &mut StackFrame, ret: &mut MaybeUninit<R>);
}

macro_rules! impl_method_invocable {
    ($( ($( $types:ident ),*) ),*) => {
        $(
            #[allow(non_snake_case, unused_variables)]
            #[sealed]
            impl<Ctx, $($types,)* R, FN> MethodInvocable<Ctx, ($($types,)*), R::Repr> for FN
            where
                FN: Fn(&Ctx, $($types,)*) -> R,
                $($types: FromRepr, $types::Repr: Default,)*
                R: IntoRepr
            {
                const FN_TYPE: FunctionType = FunctionType {
                    args: &[$(CName::new($types::Repr::NAME),)*],
                    ret: CName::new(R::Repr::NAME)
                };

                #[inline]
                fn invoke(self, ctx: &Ctx, frame: &mut StackFrame, ret: &mut MaybeUninit<R::Repr>) {
                    $(let $types = unsafe { frame.get_arg::<$types>() };)*
                    let res = self(ctx, $($types,)*);
                    unsafe { ret.as_mut_ptr().write(res.into_repr()) }
                }
            }
        )*
    };
}

impl_method_invocable!(
    (),
    (A),
    (A, B),
    (A, B, C),
    (A, B, C, D),
    (A, B, C, D, E),
    (A, B, C, D, E, F),
    (A, B, C, D, E, F, G)
);

/// A representation of a function type, including its arguments and return type.
#[derive(Debug)]
pub struct FunctionType {
    args: &'static [CName],
    ret: CName,
}

impl FunctionType {
    fn initialize_func(&self, func: &mut Function) {
        for &arg in self.args {
            func.add_param(arg, c"", false, false);
        }
        func.set_return_type(self.ret);
    }
}

/// A representation of a global function, including its name, a function handler, and its type.
#[derive(Debug)]
pub struct GlobalMetadata {
    name: &'static CStr,
    func: FunctionHandler<IScriptable, VoidPtr>,
    typ: FunctionType,
}

impl GlobalMetadata {
    #[doc(hidden)]
    #[inline]
    pub const fn new<F: GlobalInvocable<A, R>, A, R>(
        name: &'static CStr,
        func: FunctionHandler<IScriptable, VoidPtr>,
        _f: &F,
    ) -> Self {
        Self {
            name,
            func,
            typ: F::FN_TYPE,
        }
    }

    /// Converts this metadata into a [`GlobalFunction`] instance, which can be registered with
    /// [RttiSystemMut](crate::RttiSystemMut).
    pub fn to_rtti(&self) -> PoolRef<GlobalFunction> {
        let mut flags = FunctionFlags::default();
        flags.set_is_native(true);
        flags.set_is_final(true);
        flags.set_is_static(true);
        let mut func = GlobalFunction::new(self.name, self.name, self.func, flags);
        self.typ.initialize_func(func.as_function_mut());
        func
    }

    /// Converts this metadata into a [`StaticMethod`] instance, which can be registered with
    /// [RttiSystemMut](crate::RttiSystemMut).
    pub fn to_rtti_static_method(&self, class: &Class) -> PoolRef<StaticMethod> {
        let mut flags = FunctionFlags::default();
        flags.set_is_native(true);
        flags.set_is_final(true);
        flags.set_is_static(true);

        let mut func = StaticMethod::new(self.name, self.name, class, self.func, flags);
        self.typ.initialize_func(func.as_function_mut());
        func
    }
}

/// A representation of a class method, including its name, a function handler, and its type.
#[derive(Debug)]
pub struct MethodMetadata<Ctx> {
    name: &'static CStr,
    func: FunctionHandler<Ctx, VoidPtr>,
    typ: FunctionType,
    parent: PhantomData<fn() -> *const Ctx>,
    is_event: bool,
    is_final: bool,
}

impl<Ctx: ScriptClass> MethodMetadata<Ctx> {
    #[doc(hidden)]
    #[inline]
    pub const fn new<F: MethodInvocable<Ctx, A, R>, A, R>(
        name: &'static CStr,
        ptr: FunctionHandler<Ctx, VoidPtr>,
        _f: &F,
    ) -> Self {
        Self {
            name,
            func: ptr,
            typ: F::FN_TYPE,
            parent: PhantomData,
            is_event: false,
            is_final: false,
        }
    }

    /// Configures this method as an event handler (called `cb` in REDscript).
    pub const fn with_is_event(mut self) -> Self {
        self.is_event = true;
        self
    }

    /// Configures this method as final (cannot be overridden).
    pub const fn with_is_final(mut self) -> Self {
        self.is_final = true;
        self
    }

    /// Converts this metadata into a [`Method`] instance, which can be registered with
    /// the [RttiSystemMut](crate::RttiSystemMut).
    pub fn to_rtti(&self, class: &Class) -> PoolRef<Method> {
        let mut flags = FunctionFlags::default();
        flags.set_is_native(true);
        flags.set_is_event(self.is_event);
        flags.set_is_final(self.is_final);

        let mut func = Method::new(self.name, self.name, class, self.func, flags);
        self.typ.initialize_func(func.as_function_mut());
        func
    }
}

/// A macro for defining global functions. Usually used in conjunction with the
/// [`exports!`](crate::exports) macro.
///
/// # Example
/// ```rust
/// use red4ext_rs::{global, GlobalInvocable, GlobalMetadata};
///
/// fn my_global() -> GlobalMetadata {
///     global!(c"Adder", adder)
/// }
///
/// fn adder(a: i32, b: i32) -> i32 {
///     a + b
/// }
/// ```
#[macro_export]
macro_rules! global {
    ($name:literal, $fun:expr) => {{
        extern "C" fn native_impl(
            ctx: &$crate::types::IScriptable,
            frame: &mut $crate::types::StackFrame,
            ret: $crate::VoidPtr,
            _unk: i64,
        ) {
            let out = unsafe { std::mem::transmute(ret) };
            $crate::GlobalInvocable::invoke($fun, ctx, frame, out);
            unsafe { frame.step() };
        }

        $crate::GlobalMetadata::new($name, native_impl, &$fun)
    }};
}

/// A macro for defining class methods. Usually used in conjunction with the
/// [`methods!`](crate::methods) macro.
#[macro_export]
macro_rules! method {
    ($name:literal, $ty:ident::$id:ident $($mods:ident)*) => {{
        extern "C" fn native_impl(
            ctx: &$ty,
            frame: &mut $crate::types::StackFrame,
            ret: $crate::VoidPtr,
            _unk: i64,
        ) {
            let out = unsafe { ::std::mem::transmute(ret) };
            $crate::MethodInvocable::invoke($ty::$id, ctx, frame, out);
            unsafe { frame.step() };
        }

        $crate::MethodMetadata::new($name, native_impl, &$ty::$id)
            $(.$mods())?
    }};
    (event $name:literal, $ty:ident::$id:ident $($mods:ident)*) => {
        $crate::method!($name, $ty::$id with_is_event $($mods)*)
    };
    (final $name:literal, $ty:ident::$id:ident $($mods:ident)*) => {
        $crate::method!($name, $ty::$id with_is_final $($mods)*)
    }
}

/// A macro for conveniently calling functions and methods.
/// If you're calling a method, the first argument should be the instance of the class.
/// The next argument should be a full function name, which might have to include mangled names of
/// the parameter types.
///
/// # Example
/// ```rust
/// use red4ext_rs::{call, types::{IScriptable, Ref, CName}};
///
/// fn method_example(inst: Ref<IScriptable>) -> CName {
///    call!(inst, "GetClassName" () -> CName).unwrap()
/// }
///
/// fn global_example() -> i32 {
///    call!("OperatorAdd;Int32Int32;Int32" (1i32, 2i32) -> i32).unwrap()
/// }
///
/// fn static_example() -> f32 {
///    call!("PlayerPuppet"::"GetCriticalHealthThreshold;" () -> f32).unwrap()
/// }
/// ```
#[macro_export]
macro_rules! call {
    ($cls_name:literal :: $fn_name:literal ($( $args:expr ),*) -> $rett:ty) => {
        (|| {
            let rtti = $crate::RttiSystem::get();
            let ctx = rtti
                .resolve_static_context($crate::types::CName::new($cls_name))
                .ok_or($crate::InvokeError::ClassNotFound($cls_name))?;
            rtti
                .resolve_static_method_by_full_name(::std::concat!($cls_name, "::", $fn_name))
                .ok_or($crate::InvokeError::FunctionNotFound($fn_name))?
                .execute::<_, $rett>(
                    unsafe { ctx.instance() }.map(::std::convert::AsRef::as_ref),
                    ($( $crate::IntoRepr::into_repr($args), )*)
                )
        })()
    };
    ($fn_name:literal ($( $args:expr ),*) -> $rett:ty) => {
        (|| {
            $crate::RttiSystem::get()
                .get_function($crate::types::CName::new($fn_name))
                .ok_or($crate::InvokeError::FunctionNotFound($fn_name))?
                .execute::<_, $rett>(None, ($( $crate::IntoRepr::into_repr($args), )*))
        })()
    };
    ($this:expr, $fn_name:literal ($( $args:expr ),*) -> $rett:ty) => {
        (|| {
            let receiver = $crate::AsReceiver::as_receiver(&$this)?;
            $crate::types::IScriptable::class(receiver)
                .get_method($crate::types::CName::new($fn_name))
                .map_err(|err| $crate::InvokeError::new_method_not_found($fn_name, err))?
                .as_function()
                .execute::<_, $rett>(
                    Some(receiver),
                    ($( $crate::IntoRepr::into_repr($args), )*)
                )
        })()
    };
}

/// A trait for types that can be used as the receiver of a method call.
#[sealed]
pub trait AsReceiver {
    #[doc(hidden)]
    fn as_receiver(&self) -> Result<&IScriptable, InvokeError>;
}

#[sealed]
impl<T: AsRef<IScriptable>> AsReceiver for T {
    #[inline]
    fn as_receiver(&self) -> Result<&IScriptable, InvokeError> {
        Ok(self.as_ref())
    }
}

#[sealed]
impl<T: ScriptClass> AsReceiver for Ref<T>
where
    <T::Kind as ClassKind<T>>::NativeType: AsRef<IScriptable>,
{
    #[inline]
    fn as_receiver(&self) -> Result<&IScriptable, InvokeError> {
        unsafe { self.instance() }
            .map(AsRef::as_ref)
            .ok_or(InvokeError::NullReceiver(T::NAME))
    }
}

#[sealed]
impl<T: ScriptClass> AsReceiver for &Ref<T>
where
    <T::Kind as ClassKind<T>>::NativeType: AsRef<IScriptable>,
{
    #[inline]
    fn as_receiver(&self) -> Result<&IScriptable, InvokeError> {
        <Ref<T> as AsReceiver>::as_receiver(*self)
    }
}

#[sealed]
#[doc(hidden)]
pub trait Args {
    type Array<'a>: AsRef<[StackArg<'a>]>
    where
        Self: 'a;

    fn to_array(&mut self) -> Result<Self::Array<'_>, InvokeError>;
}

macro_rules! impl_args {
    ($( ($( $ids:ident ),*) ),*) => {
        $(
            #[allow(unused_parens, non_snake_case)]
            #[sealed]
            impl <$($ids: NativeRepr),*> Args for ($($ids,)*) {
                type Array<'a> = [StackArg<'a>; count_args!($($ids)*)] where Self: 'a;

                #[inline]
                fn to_array(&mut self) -> Result<Self::Array<'_>, InvokeError> {
                    let ($($ids,)*) = self;
                    Ok([$(
                        StackArg::new($ids).ok_or_else(||
                            InvokeError::UnresolvedType($ids::NAME)
                        )?),*
                    ])
                }
            }
        )*
    };
}

macro_rules! count_args {
    ($id:ident $( $t:tt )*) => {
        1 + count_args!($($t)*)
    };
    () => { 0 }
}

impl_args!(
    (),
    (A),
    (A, B),
    (A, B, C),
    (A, B, C, D),
    (A, B, C, D, E),
    (A, B, C, D, E, F),
    (A, B, C, D, E, F, G)
);