usertypes.hpp 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  1. /* Luwra
  2. * Minimal-overhead Lua wrapper for C++
  3. *
  4. * Copyright (C) 2015, Ole Krüger <ole@vprsm.de>
  5. */
  6. #ifndef LUWRA_USERTYPES_H_
  7. #define LUWRA_USERTYPES_H_
  8. #include "common.hpp"
  9. #include "types.hpp"
  10. #include "stack.hpp"
  11. #include "functions.hpp"
  12. #include <map>
  13. LUWRA_NS_BEGIN
  14. namespace internal {
  15. using UserTypeID = const void*;
  16. template <typename T>
  17. using StripUserType = std::remove_cv_t<T>;
  18. /**
  19. * User type identifier
  20. */
  21. template <typename T> extern
  22. const UserTypeID user_type_id = (void*) INTPTR_MAX;
  23. /**
  24. * Registry name for a metatable which is associated with a user type
  25. */
  26. template <typename T> extern
  27. const std::string user_type_reg_name =
  28. "UD#" + std::to_string(uintptr_t(&user_type_id<StripUserType<T>>));
  29. /**
  30. * Register a new metatable for a user type T.
  31. */
  32. template <typename U> static inline
  33. void new_user_type_metatable(State* state) {
  34. using T = StripUserType<U>;
  35. luaL_newmetatable(state, user_type_reg_name<T>.c_str());
  36. }
  37. /**
  38. * Check if the value at the given index if a user type T.
  39. */
  40. template <typename U> static inline
  41. StripUserType<U>* check_user_type(State* state, int index) {
  42. using T = StripUserType<U>;
  43. return static_cast<T*>(luaL_checkudata(state, index, user_type_reg_name<T>.c_str()));
  44. }
  45. /**
  46. * Apply U's metatable for the value at the top of the stack.
  47. */
  48. template <typename U> static inline
  49. void apply_user_type_meta_table(State* state) {
  50. using T = StripUserType<U>;
  51. luaL_getmetatable(state, user_type_reg_name<T>.c_str());
  52. lua_setmetatable(state, -2);
  53. }
  54. /**
  55. * Lua C function to construct a user type T with parameters A
  56. */
  57. template <typename U, typename... A> static inline
  58. int construct_user_type(State* state) {
  59. return internal::Layout<int(A...)>::direct(
  60. state,
  61. 1,
  62. &Value<StripUserType<U>&>::template push<A...>,
  63. state
  64. );
  65. }
  66. /**
  67. * Lua C function to destruct a user type T
  68. */
  69. template <typename U> static inline
  70. int destruct_user_type(State* state) {
  71. using T = StripUserType<U>;
  72. if (!lua_islightuserdata(state, 1))
  73. Value<T&>::read(state, 1).~T();
  74. return 0;
  75. }
  76. /**
  77. * Create a string representation for user type T.
  78. */
  79. template <typename U> static
  80. int stringify_user_type(State* state) {
  81. using T = StripUserType<U>;
  82. return Value<std::string>::push(
  83. state,
  84. internal::user_type_reg_name<T>
  85. + "@"
  86. + std::to_string(uintptr_t(Value<T*>::read(state, 1)))
  87. );
  88. }
  89. /**
  90. * Helper struct for wrapping user type fields
  91. */
  92. template <typename U, typename R>
  93. struct FieldWrapper {
  94. using T = StripUserType<U>;
  95. template <R T::* field_pointer> static inline
  96. int invoke(State* state) {
  97. if (lua_gettop(state) > 1) {
  98. // Setter
  99. Value<T*>::read(state, 1)->*field_pointer = Value<R>::read(state, 2);
  100. return 0;
  101. } else {
  102. // Getter
  103. return push(state, Value<T*>::read(state, 1)->*field_pointer);
  104. }
  105. }
  106. };
  107. // 'const'-qualified fields
  108. template <typename U, typename R>
  109. struct FieldWrapper<U, const R> {
  110. using T = StripUserType<U>;
  111. template <const R T::* field_pointer> static inline
  112. int invoke(State* state) {
  113. return push(state, Value<T*>::read(state, 1)->*field_pointer);
  114. }
  115. };
  116. /**
  117. * Helper struct for wrapping user type methods
  118. */
  119. template <typename T, typename S>
  120. struct MethodWrapper {
  121. static_assert(
  122. sizeof(T) == -1,
  123. "Undefined template MethodWrapper"
  124. );
  125. };
  126. // 'const volatile'-qualified methods
  127. template <typename T, typename R, typename... A>
  128. struct MethodWrapper<const volatile T, R(A...)> {
  129. using MethodPointerType = R (T::*)(A...) const volatile;
  130. using FunctionSignature = R (const volatile T*, A...);
  131. template <MethodPointerType method_pointer> static inline
  132. R call(const volatile T* parent, A... args) {
  133. return (parent->*method_pointer)(std::forward<A>(args)...);
  134. }
  135. };
  136. // 'const'-qualified methods
  137. template <typename T, typename R, typename... A>
  138. struct MethodWrapper<const T, R(A...)> {
  139. using MethodPointerType = R (T::*)(A...) const;
  140. using FunctionSignature = R (const T*, A...);
  141. template <MethodPointerType method_pointer> static inline
  142. R call(const T* parent, A... args) {
  143. return (parent->*method_pointer)(std::forward<A>(args)...);
  144. }
  145. };
  146. // 'volatile'-qualified methods
  147. template <typename T, typename R, typename... A>
  148. struct MethodWrapper<volatile T, R(A...)> {
  149. using MethodPointerType = R (T::*)(A...) volatile;
  150. using FunctionSignature = R (volatile T*, A...);
  151. template <MethodPointerType method_pointer> static inline
  152. R call(volatile T* parent, A... args) {
  153. return (parent->*method_pointer)(std::forward<A>(args)...);
  154. }
  155. };
  156. // unqualified methods
  157. template <typename T, typename R, typename... A>
  158. struct MethodWrapper<T, R(A...)> {
  159. using MethodPointerType = R (T::*)(A...);
  160. using FunctionSignature = R (T*, A...);
  161. template <MethodPointerType method_pointer> static inline
  162. R call(T* parent, A... args) {
  163. return (parent->*method_pointer)(std::forward<A>(args)...);
  164. }
  165. };
  166. }
  167. /**
  168. * User type T.
  169. * Instances created using this specialization are allocated and constructed as full user data
  170. * types in Lua. The default garbage-collecting hook will destruct the user type, once it has
  171. * been marked.
  172. */
  173. template <typename U>
  174. struct Value<U&> {
  175. using T = internal::StripUserType<U>;
  176. static inline
  177. U& read(State* state, int n) {
  178. // T is unqualified, therefore conversion from T& to U& is allowed
  179. return *internal::check_user_type<T>(state, n);
  180. }
  181. template <typename... A> static inline
  182. int push(State* state, A&&... args) {
  183. void* mem = lua_newuserdata(state, sizeof(T));
  184. if (!mem) {
  185. luaL_error(state, "Failed to allocate user type");
  186. return -1;
  187. }
  188. // Construct
  189. new (mem) T(std::forward<A>(args)...);
  190. // Apply metatable for unqualified type T
  191. internal::apply_user_type_meta_table<T>(state);
  192. return 1;
  193. }
  194. };
  195. /**
  196. * User type T.
  197. * Instances created using this specialization are allocated as light user data in Lua.
  198. * The default garbage-collector does not destruct light user data types.
  199. */
  200. template <typename U>
  201. struct Value<U*> {
  202. using T = internal::StripUserType<U>;
  203. static inline
  204. U* read(State* state, int n) {
  205. // T is unqualified, therefore conversion from T* to U* is allowed
  206. return internal::check_user_type<T>(state, n);
  207. }
  208. static inline
  209. int push(State* state, T* instance) {
  210. if (instance == nullptr)
  211. return 0;
  212. // Push instance as light user data
  213. lua_pushlightuserdata(state, instance);
  214. // Apply metatable for unqualified type T
  215. internal::apply_user_type_meta_table<T>(state);
  216. return 1;
  217. }
  218. };
  219. /**
  220. * Constructor function for a type `T`. Variadic arguments must be used to specify which parameters
  221. * to use during construction.
  222. */
  223. template <typename T, typename... A>
  224. constexpr CFunction wrap_constructor =
  225. &internal::construct_user_type<internal::StripUserType<T>, A...>;
  226. /**
  227. * Works similiar to `wrap_function`. Given a class or struct declaration as follows:
  228. *
  229. * struct T {
  230. * R my_method(A0, A1 ... An);
  231. * };
  232. *
  233. * You might wrap this method easily:
  234. *
  235. * CFunction wrapped_meth = wrap_method<T, R(A0, A1 ... An), &T::my_method>;
  236. *
  237. * In Lua, assuming `instance` is a userdata instance of type `T`, x0, x1 ... xn are instances
  238. * of A0, A1 ... An, and the method has been bound as `my_method`; it is possible to invoke the
  239. * method like so:
  240. *
  241. * instance:my_method(x0, x1 ... xn)
  242. */
  243. template <
  244. typename T,
  245. typename S,
  246. typename internal::MethodWrapper<T, S>::MethodPointerType method_pointer
  247. >
  248. constexpr CFunction wrap_method =
  249. wrap_function<
  250. typename internal::MethodWrapper<T, S>::FunctionSignature,
  251. internal::MethodWrapper<T, S>::template call<method_pointer>
  252. >;
  253. /**
  254. * Property accessor method
  255. *
  256. * struct T {
  257. * R my_property;
  258. * };
  259. *
  260. * The wrapped property accessor is also a function:
  261. *
  262. * CFunction wrapped_property = wrap_field<T, R, &T::my_property>;
  263. */
  264. template <
  265. typename T,
  266. typename R,
  267. R T::* field_pointer
  268. >
  269. constexpr CFunction wrap_field =
  270. &internal::FieldWrapper<T, R>::template invoke<field_pointer>;
  271. /**
  272. * Register the metatable for user type `T`. This function allows you to register methods
  273. * which are shared across all instances of this type. A garbage-collector hook is also inserted.
  274. * Meta-methods can be added and/or overwritten aswell.
  275. */
  276. template <typename U> static inline
  277. void register_user_type(
  278. State* state,
  279. const std::map<const char*, CFunction>& methods,
  280. const std::map<const char*, CFunction>& meta_methods = std::map<const char*, CFunction>()
  281. ) {
  282. using T = internal::StripUserType<U>;
  283. // Setup an appropriate metatable name
  284. internal::new_user_type_metatable<T>(state);
  285. // Register methods
  286. if (methods.size() > 0 && meta_methods.count("__index") == 0) {
  287. push(state, "__index");
  288. lua_newtable(state);
  289. for (auto& method: methods) {
  290. push(state, method.first);
  291. push(state, method.second);
  292. lua_rawset(state, -3);
  293. }
  294. lua_rawset(state, -3);
  295. }
  296. // Register garbage-collection hook
  297. if (meta_methods.count("__gc") == 0) {
  298. push(state, "__gc");
  299. push(state, &internal::destruct_user_type<T>);
  300. lua_rawset(state, -3);
  301. }
  302. // Register string representation function
  303. if (meta_methods.count("__tostring") == 0) {
  304. push(state, "__tostring");
  305. push(state, &internal::stringify_user_type<T>);
  306. lua_rawset(state, -3);
  307. }
  308. // Insert meta methods
  309. for (const auto& metamethod: meta_methods) {
  310. push(state, metamethod.first);
  311. push(state, metamethod.second);
  312. lua_rawset(state, -3);
  313. }
  314. // Pop metatable off the stack
  315. lua_pop(state, -1);
  316. }
  317. LUWRA_NS_END
  318. #endif