1/*
2 * Copyright (c) 2010-2017 OTClient <https://github.com/edubart/otclient>
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a copy
5 * of this software and associated documentation files (the "Software"), to deal
6 * in the Software without restriction, including without limitation the rights
7 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 * copies of the Software, and to permit persons to whom the Software is
9 * furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice shall be included in
12 * all copies or substantial portions of the Software.
13 *
14 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 * THE SOFTWARE.
21 */
22
23#ifndef LUABINDER_H
24#define LUABINDER_H
25
26// this file is and must be included only from luainterface.h
27#include "luainterface.h"
28#include "luaexception.h"
29
30#include <framework/stdext/traits.h>
31#include <tuple>
32
33/// This namespace contains some dirty metaprogamming that uses a lot of C++0x features
34/// The purpose here is to create templates that can bind any function from C++
35/// and expose in lua environment. This is done combining variadic templates,
36/// lambdas, tuples and some type traits features from the new C++0x standard to create
37/// templates that can detect functions's arguments and then generate lambdas. These lambdas
38/// pops arguments from lua stack, call the bound C++ function and then
39/// pushes the result to lua.
40namespace luabinder
41{
42 /// Pack arguments from lua stack into a tuple recursively
43 template<int N>
44 struct pack_values_into_tuple {
45 template<typename Tuple>
46 static void call(Tuple& tuple, LuaInterface* lua) {
47 typedef typename std::tuple_element<N-1, Tuple>::type ValueType;
48 std::get<N-1>(tuple) = lua->polymorphicPop<ValueType>();
49 pack_values_into_tuple<N-1>::call(tuple, lua);
50 }
51 };
52 template<>
53 struct pack_values_into_tuple<0> {
54 template<typename Tuple>
55 static void call(Tuple& tuple, LuaInterface* lua) { }
56 };
57
58 /// C++ function caller that can push results to lua
59 template<typename Ret, typename F, typename... Args>
60 typename std::enable_if<!std::is_void<Ret>::value, int>::type
61 call_fun_and_push_result(const F& f, LuaInterface* lua, const Args&... args) {
62 Ret ret = f(args...);
63 int numRets = lua->polymorphicPush(ret);
64 return numRets;
65 }
66
67 /// C++ void function caller
68 template<typename Ret, typename F, typename... Args>
69 typename std::enable_if<std::is_void<Ret>::value, int>::type
70 call_fun_and_push_result(const F& f, LuaInterface* lua, const Args&... args) {
71 f(args...);
72 return 0;
73 }
74
75 /// Expand arguments from tuple for later calling the C++ function
76 template<int N, typename Ret>
77 struct expand_fun_arguments {
78 template<typename Tuple, typename F, typename... Args>
79 static int call(const Tuple& tuple, const F& f, LuaInterface* lua, const Args&... args) {
80 return expand_fun_arguments<N-1,Ret>::call(tuple, f, lua, std::get<N-1>(tuple), args...);
81 }
82 };
83 template<typename Ret>
84 struct expand_fun_arguments<0,Ret> {
85 template<typename Tuple, typename F, typename... Args>
86 static int call(const Tuple& tuple, const F& f, LuaInterface* lua, const Args&... args) {
87 return call_fun_and_push_result<Ret>(f, lua, args...);
88 }
89 };
90
91 /// Bind different types of functions generating a lambda
92 template<typename Ret, typename F, typename Tuple>
93 LuaCppFunction bind_fun_specializer(const F& f) {
94 enum { N = std::tuple_size<Tuple>::value };
95 return [=](LuaInterface* lua) -> int {
96 while(lua->stackSize() != N) {
97 if(lua->stackSize() < N)
98 g_lua.pushNil();
99 else
100 g_lua.pop();
101 }
102 Tuple tuple;
103 pack_values_into_tuple<N>::call(tuple, lua);
104 return expand_fun_arguments<N,Ret>::call(tuple, f, lua);
105 };
106 }
107
108 /// Bind a customized function
109 inline
110 LuaCppFunction bind_fun(const std::function<int(LuaInterface*)>& f) {
111 return f;
112 }
113
114 /// Bind a std::function
115 template<typename Ret, typename... Args>
116 LuaCppFunction bind_fun(const std::function<Ret(Args...)>& f) {
117 typedef typename std::tuple<typename stdext::remove_const_ref<Args>::type...> Tuple;
118 return bind_fun_specializer<typename stdext::remove_const_ref<Ret>::type,
119 decltype(f),
120 Tuple>(f);
121 }
122
123 /// Specialization for lambdas
124 template<typename F>
125 struct bind_lambda_fun;
126
127 template<typename Lambda, typename Ret, typename... Args>
128 struct bind_lambda_fun<Ret(Lambda::*)(Args...) const> {
129 static LuaCppFunction call(const Lambda& f) {
130 typedef typename std::tuple<typename stdext::remove_const_ref<Args>::type...> Tuple;
131 return bind_fun_specializer<typename stdext::remove_const_ref<Ret>::type,
132 decltype(f),
133 Tuple>(f);
134
135 }
136 };
137
138 template<typename Lambda>
139 typename std::enable_if<std::is_constructible<decltype(&Lambda::operator())>::value, LuaCppFunction>::type bind_fun(const Lambda& f) {
140 typedef decltype(&Lambda::operator()) F;
141 return bind_lambda_fun<F>::call(f);
142 }
143
144 /// Convert to C++ functions pointers to std::function then bind
145 template<typename Ret, typename... Args>
146 LuaCppFunction bind_fun(Ret (*f)(Args...)) {
147 return bind_fun(std::function<Ret(Args...)>(f));
148 }
149
150 /// Create member function lambdas
151 template<typename Ret, typename C, typename... Args>
152 std::function<Ret(const stdext::shared_object_ptr<C>&, const Args&...)> make_mem_func(Ret (C::* f)(Args...)) {
153 auto mf = std::mem_fn(f);
154 return [=](const stdext::shared_object_ptr<C>& obj, const Args&... args) mutable -> Ret {
155 if(!obj)
156 throw LuaException("failed to call a member function because the passed object is nil");
157 return mf(obj.get(), args...);
158 };
159 }
160 template<typename C, typename... Args>
161 std::function<void(const stdext::shared_object_ptr<C>&, const Args&...)> make_mem_func(void (C::* f)(Args...)) {
162 auto mf = std::mem_fn(f);
163 return [=](const stdext::shared_object_ptr<C>& obj, const Args&... args) mutable -> void {
164 if(!obj)
165 throw LuaException("failed to call a member function because the passed object is nil");
166 mf(obj.get(), args...);
167 };
168 }
169
170 /// Create member function lambdas for singleton classes
171 template<typename Ret, typename C, typename... Args>
172 std::function<Ret(const Args&...)> make_mem_func_singleton(Ret (C::* f)(Args...), C* instance) {
173 auto mf = std::mem_fn(f);
174 return [=](Args... args) mutable -> Ret { return mf(instance, args...); };
175 }
176 template<typename C, typename... Args>
177 std::function<void(const Args&...)> make_mem_func_singleton(void (C::* f)(Args...), C* instance) {
178 auto mf = std::mem_fn(f);
179 return [=](Args... args) mutable -> void { mf(instance, args...); };
180 }
181
182
183 /// Bind member functions
184 template<typename C, typename Ret, class FC, typename... Args>
185 LuaCppFunction bind_mem_fun(Ret (FC::* f)(Args...)) {
186 typedef typename std::tuple<stdext::shared_object_ptr<FC>, typename stdext::remove_const_ref<Args>::type...> Tuple;
187 auto lambda = make_mem_func<Ret,FC>(f);
188 return bind_fun_specializer<typename stdext::remove_const_ref<Ret>::type,
189 decltype(lambda),
190 Tuple>(lambda);
191 }
192
193 /// Bind singleton member functions
194 template<typename C, typename Ret, class FC, typename... Args>
195 LuaCppFunction bind_singleton_mem_fun(Ret (FC::*f)(Args...), C *instance) {
196 typedef typename std::tuple<typename stdext::remove_const_ref<Args>::type...> Tuple;
197 VALIDATE(instance);
198 auto lambda = make_mem_func_singleton<Ret,FC>(f, static_cast<FC*>(instance));
199 return bind_fun_specializer<typename stdext::remove_const_ref<Ret>::type,
200 decltype(lambda),
201 Tuple>(lambda);
202 }
203
204 /// Bind customized member functions
205 template<typename C>
206 LuaCppFunction bind_mem_fun(int (C::*f)(LuaInterface*)) {
207 auto mf = std::mem_fn(f);
208 return [=](LuaInterface* lua) mutable -> int {
209 auto obj = lua->castValue<stdext::shared_object_ptr<C>>(1);
210 lua->remove(1);
211 return mf(obj, lua);
212 };
213 }
214}
215
216#endif
217