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
use std::cell::RefCell;
use std::ffi::CStr;
use std::marker::PhantomData;
use std::result::Result as StdResult;
use std::{fmt, mem, ptr};

use libc::{c_char, c_int};
use nvim_types::{LuaRef, Object, ObjectKind};
use serde::{de, ser};

use super::{ffi::*, LuaPoppable, LuaPushable};
use crate::object::{FromObject, ToObject};
use crate::Result;

/// Handle to a Lua function either created from Rust or deserialized from Lua.
#[derive(Clone, Eq, PartialEq, Hash)]
pub struct Function<A, R>(pub(crate) LuaRef, PhantomData<A>, PhantomData<R>);

impl<A, R> fmt::Debug for Function<A, R> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_tuple("Function").field(&self.0).finish()
    }
}

impl<A, R> From<Function<A, R>> for Object {
    fn from(fun: Function<A, R>) -> Self {
        Self::new_luaref(fun.0)
    }
}

impl<A, R> ToObject for Function<A, R> {
    fn to_obj(self) -> Result<Object> {
        Ok(self.into())
    }
}

impl<A, R> FromObject for Function<A, R> {
    fn from_obj(obj: Object) -> Result<Function<A, R>> {
        match obj.kind() {
            ObjectKind::LuaRef => {
                let luaref = unsafe { obj.as_luaref_unchecked() };
                Ok(Self(luaref, PhantomData, PhantomData))
            },
            _ => todo!(),
        }
    }
}

impl<'de, A, R> de::Deserialize<'de> for Function<A, R> {
    fn deserialize<D>(deserializer: D) -> StdResult<Self, D::Error>
    where
        D: de::Deserializer<'de>,
    {
        struct FunctionVisitor<A, R>(PhantomData<A>, PhantomData<R>);

        impl<'de, A, R> de::Visitor<'de> for FunctionVisitor<A, R> {
            type Value = Function<A, R>;

            fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
                f.write_str("an f32 representing a Lua reference")
            }

            fn visit_f32<E>(self, value: f32) -> StdResult<Self::Value, E>
            where
                E: de::Error,
            {
                Ok(Function(value as i32, PhantomData, PhantomData))
            }
        }

        deserializer.deserialize_f32(FunctionVisitor(PhantomData, PhantomData))
    }
}

impl<A, R> ser::Serialize for Function<A, R> {
    fn serialize<S>(&self, serializer: S) -> StdResult<S::Ok, S::Error>
    where
        S: ser::Serializer,
    {
        serializer.serialize_f32(self.0 as f32)
    }
}

impl<A, R> Function<A, R> {
    pub fn from_fn<F>(fun: F) -> Self
    where
        A: LuaPoppable,
        R: LuaPushable,
        F: Fn(A) -> Result<R> + 'static,
    {
        type Cb = Box<dyn Fn(*mut lua_State) -> Result<c_int> + 'static>;

        unsafe extern "C" fn c_fun(lstate: *mut lua_State) -> c_int {
            let fun = {
                let idx = lua_upvalueindex(1);
                let upv = lua_touserdata(lstate, idx) as *mut Cb;
                &**upv
            };

            fun(lstate).unwrap_or_else(|err| handle_error(lstate, err))
        }

        let r#ref = super::with_state(move |lstate| unsafe {
            let fun = Box::new(move |l| fun(A::pop(l)?)?.push(l));
            let ud = lua_newuserdata(lstate, mem::size_of::<Cb>());
            ptr::write(ud as *mut Cb, fun);
            lua_pushcclosure(lstate, c_fun, 1);
            luaL_ref(lstate, LUA_REGISTRYINDEX)
        });

        Self(r#ref, PhantomData, PhantomData)
    }

    pub fn from_fn_mut<F>(fun: F) -> Self
    where
        A: LuaPoppable,
        R: LuaPushable,
        F: FnMut(A) -> Result<R> + 'static,
    {
        let fun = RefCell::new(fun);
        Self::from_fn(move |args| {
            fun.try_borrow_mut()
                .map_err(|_| crate::Error::LuaFunMutRecursiveCallback)?(
                args
            )
        })
    }

    pub fn from_fn_once<F>(fun: F) -> Self
    where
        A: LuaPoppable,
        R: LuaPushable,
        F: FnOnce(A) -> Result<R> + 'static,
    {
        let fun = RefCell::new(Some(fun));
        Self::from_fn(move |args| {
            fun.try_borrow_mut()
                .ok()
                .and_then(|mut fun| fun.take())
                .ok_or_else(|| crate::Error::LuaFunOnceMoreThanOnce)?(
                args
            )
        })
    }

    /// Calls the function, passing `args` as function arguments.
    pub fn call(&self, args: A) -> Result<R>
    where
        A: LuaPushable,
        R: LuaPoppable,
    {
        super::with_state(move |lstate| unsafe {
            lua_rawgeti(lstate, LUA_REGISTRYINDEX, self.0);
            let nargs = args.push(lstate)?;

            match lua_pcall(lstate, nargs, R::N, 0) {
                LUA_OK => R::pop(lstate),

                err_code => {
                    let msg = CStr::from_ptr(lua_tostring(lstate, -1))
                        .to_string_lossy()
                        .to_string();

                    lua_pop(lstate, 1);

                    match err_code {
                        LUA_ERRRUN => Err(crate::Error::LuaRuntimeError(msg)),

                        LUA_ERRMEM => Err(crate::Error::LuaMemoryError(msg)),

                        LUA_ERRERR => {
                            panic!("errorfunc is 0, this never happens!")
                        },

                        _ => unreachable!(),
                    }
                },
            }
        })
    }

    /// Consumes the `Function`, removing the reference stored in the Lua
    /// registry.
    pub(crate) fn unref(self) {
        super::with_state(move |lstate| unsafe {
            luaL_unref(lstate, LUA_REGISTRYINDEX, self.0);
        })
    }
}

unsafe fn handle_error(lstate: *mut lua_State, err: crate::Error) -> ! {
    let msg = err.to_string();
    lua_pushlstring(lstate, msg.as_ptr() as *const c_char, msg.len());
    lua_error(lstate);
}