Pioneer
LuaObject.h
Go to the documentation of this file.
1 // Copyright © 2008-2021 Pioneer Developers. See AUTHORS.txt for details
2 // Licensed under the terms of the GPL v3. See licenses/GPL-3.txt
3 
4 #ifndef _LUAOBJECT_H
5 #define _LUAOBJECT_H
6 
7 #include "DeleteEmitter.h"
8 #include "Lua.h"
9 #include "LuaPushPull.h"
10 #include "LuaRef.h"
11 #include "LuaUtils.h"
12 #include "LuaWrappable.h"
13 #include "RefCounted.h"
14 #include "galaxy/SystemPath.h"
15 #include <tuple>
16 #include <typeinfo>
17 
18 //
19 // LuaObject provides proxy objects and tracking facilities to safely get
20 // objects in and out of lua. the basic idea is that for every class you want
21 // to expose to lua, you define LuaObject wrapper class that defines the
22 // lua name lua name, methods and metamethods for that class. you then call
23 // methods on this class to push and pull objects to and from the lua stack
24 //
25 // Push an object to the Lua stack:
26 //
27 // // C++-owned, still responsible for deletion
28 // Ship *s = new Ship("wave");
29 // LuaObject<Ship>::PushToLua(s);
30 //
31 // // RefCounted, Lua will take a reference
32 // StarSystem *s = Pi::GetGalaxy()->GetStarSystem(SystemPath(0,0,0,0));
33 // LuaObject<StarSystem>::PushToLua(s);
34 //
35 // // Heap-allocated, Lua will get a copy
36 // SystemPath path(0,0,0,0,1);
37 // LuaObject<SystemPath>::PushToLua(path);
38 //
39 // Get an object from the Lua stack at index n. Causes a Lua exception if the
40 // object doesn't exist or the types don't match.
41 //
42 // Ship *s = LuaObject<Ship>::CheckFromLua(1);
43 //
44 // Or alternatively, get it and return 0 on failure.
45 //
46 // Ship *s = LuaObject<Ship>::GetFromLua(1);
47 //
48 //
49 // If you need to expose a new class to Lua:
50 //
51 // - Have it inherit from LuaWrappable
52 //
53 // - Have it either:
54 // - inherit from DeleteEmitter
55 // - inherit from RefCounted
56 // - implement a copy constructor
57 //
58 // - Arrange for the wrapper class RegisterClass() method to be called in
59 // LuaInit in Pi.cpp
60 //
61 // - Make a new file LuaWhatever.cpp implement RegisterClass() and any
62 // methods, metamethods and attribute methods you want. Copy from one of the
63 // other files to get the idea
64 //
65 // - Add the new file to the build system
66 //
67 
68 // type for promotion test callbacks
69 typedef bool (*PromotionTest)(LuaWrappable *o);
70 
71 // type for serializer function pair
73  typedef std::string (*Serializer)(LuaWrappable *o);
74  typedef bool (*Deserializer)(const char *stream, const char **next);
75 
76  typedef void (*ToJson)(Json &out, LuaWrappable *o);
77  typedef bool (*FromJson)(const Json &obj);
78 
80  serialize(nullptr),
81  deserialize(nullptr),
82  to_json(nullptr),
83  from_json(nullptr)
84  {}
85 
87  Serializer serialize_, Deserializer deserialize_,
88  ToJson to_json_, FromJson from_json_) :
89  serialize(serialize_),
90  deserialize(deserialize_),
91  to_json(to_json_),
92  from_json(from_json_)
93  {}
94 
99 };
100 
101 class PropertyMap;
102 class LuaMetaTypeBase;
103 
104 // wrapper baseclass, and extra bits for getting at certain parts of the
105 // LuaObject layer
107  friend class LuaSerializer;
108 
109 public:
110  // creates a single "typeless" object and attaches the listed methods,
111  // attributes and metamethods to it. leaves the created object on the
112  // stack
113  static void CreateObject(const luaL_Reg *methods, const luaL_Reg *attrs, const luaL_Reg *meta, bool protect = false);
114 
115  // Creates a single "typeless" object and attaches the given metatype
116  // to it. Leaves the created object on the stack.
117  static void CreateObject(LuaMetaTypeBase *metaType);
118 
119  // Checks if the object at the stack position is a PropertiedObject and returns a pointer to
120  // its PropertyMap. Returns nullptr on failure.
121  static PropertyMap *GetPropertiesFromObject(lua_State *l, int object);
122 
123 protected:
124  // base class constructor, called by the wrapper Push* methods
125  LuaObjectBase(const char *type) :
126  m_type(type){};
127  virtual ~LuaObjectBase() {}
128 
129  // creates a class in the lua vm with the given name and attaches the
130  // listed methods to it and the listed metamethods to its metaclass. if
131  // attributes extra magic is added to the metaclass to make them work as
132  // expected
133  static void CreateClass(const char *type, const char *parent, const luaL_Reg *methods, const luaL_Reg *attrs, const luaL_Reg *meta);
134 
135  // Creates a class in the lua vm with the given name and attaches the
136  // listed metatype to it. All method, attribute, and metamethod handling
137  // is contained in the metatype.
138  static void CreateClass(LuaMetaTypeBase *metaType);
139 
140  // push an already-registered object onto the lua stack. the object is
141  // looked up in the lua registry, if it exists its userdata its userdata
142  // is pushed onto the lua stack. returns true if the object exists and was
143  // pushed, false otherwise
144  static bool PushRegistered(LuaWrappable *o);
145 
146  // adds an object->wrapper mapping to the registry for the given wrapper
147  // object. the wrapper's corresponding userdata should be on the top of
148  // the stack
149  static void Register(LuaObjectBase *lo);
150 
151  // remove the object->wrapper from the registry. checks to make sure the
152  // the mapping matches first, to protect against memory being reused
153  static void Deregister(LuaObjectBase *lo);
154 
155  // pulls an object off the lua stack and returns its associated c++
156  // object. type is the lua type string of the object. a lua exception is
157  // triggered if the object on the stack is not of this type
158  static LuaWrappable *CheckFromLua(int index, const char *type);
159 
160  // does exactly the same as Check without triggering exceptions
161  static LuaWrappable *GetFromLua(int index, const char *type);
162 
163  // register a promotion test. when an object with lua type base_type is
164  // pushed, test_fn will be called. if it returns true then the created lua
165  // object will be of target_type
166  static void RegisterPromotion(const char *base_type, const char *target_type, PromotionTest test_fn);
167 
168  static void RegisterSerializer(const char *type, SerializerPair pair);
169 
170  std::string Serialize();
171  static bool Deserialize(const char *stream, const char **next);
172 
173  void ToJson(Json &out);
174  static bool FromJson(const Json &obj);
175 
176  // allocate n bytes from Lua memory and leave it an associated userdata on
177  // the stack. this is a wrapper around lua_newuserdata
178  static void *Allocate(size_t n);
179 
180  // get a pointer to the underlying object
181  virtual LuaWrappable *GetObject() const = 0;
182 
183  const char *GetType() const { return m_type; }
184 
185 private:
186  LuaObjectBase() {}
187  LuaObjectBase(const LuaObjectBase &) {}
188 
189  // Lua-side helper functionality, declared in LuaObject.cpp
190  friend class LuaObjectHelpers;
191 
192  // determine if the object has a class in its ancestry
193  bool Isa(const char *base) const;
194 
195  // lua type (ie method/metatable name)
196  const char *m_type;
197 };
198 
199 // templated portion of the wrapper baseclass
200 template <typename T>
201 class LuaObject : public LuaObjectBase {
202 public:
203  // registers the class with the lua vm
204  static void RegisterClass();
205 
206  // wrap an object and push it onto the stack. these create a wrapper
207  // object that knows how to deal with the type of object
208  static inline void PushToLua(DeleteEmitter *o); // LuaCoreObject
209  static inline void PushToLua(RefCounted *o); // LuaSharedObject
210  static inline void PushToLua(const T &o); // LuaCopyObject
211 
212  template <typename Ret, typename Key, typename... Args>
213  static inline Ret CallMethod(T *o, const Key &key, const Args &... args);
214  template <typename Key, typename... Args>
215  static inline void CallMethod(T *o, const Key &key, const Args &... args)
216  {
217  CallMethod<bool>(o, key, args...);
218  }
219 
220  template <typename Ret1, typename Ret2, typename... Ret, typename Key, typename... Args>
221  static inline std::tuple<Ret1, Ret2, Ret...> CallMethod(T *o, const Key &key, const Args &... args);
222 
223  // pull an object off the stack, unwrap and return it
224  // if not found or doesn't match the type, throws a lua exception
225  static inline T *CheckFromLua(int idx)
226  {
227 #ifdef __clang__
228 #pragma clang diagnostic push
229 #pragma clang diagnostic ignored "-Wundefined-var-template"
230 #endif
231  return dynamic_cast<T *>(LuaObjectBase::CheckFromLua(idx, s_type));
232 #ifdef __clang__
233 #pragma clang diagnostic pop
234 #endif
235  }
236 
237  // same but without error checks. returns 0 on failure
238  static inline T *GetFromLua(int idx)
239  {
240 #ifdef __clang__
241 #pragma clang diagnostic push
242 #pragma clang diagnostic ignored "-Wundefined-var-template"
243 #endif
244  return dynamic_cast<T *>(LuaObjectBase::GetFromLua(idx, s_type));
245 #ifdef __clang__
246 #pragma clang diagnostic pop
247 #endif
248  }
249 
250  // standard cast promotion test for convenience
251  static inline bool DynamicCastPromotionTest(LuaWrappable *o)
252  {
253  return dynamic_cast<T *>(o);
254  }
255 
256 protected:
257 #ifdef __clang__
258 #pragma clang diagnostic push
259 #pragma clang diagnostic ignored "-Wundefined-var-template"
260 #endif
262  LuaObjectBase(s_type)
263  {}
264 #ifdef __clang__
265 #pragma clang diagnostic pop
266 #endif
267 
268 private:
269  // initial lua type string. defined in a specialisation in the appropriate
270  // .cpp file
271  static const char *s_type;
272 };
273 
274 // wrapper for a "core" object - one owned by c++ (eg Body).
275 // Lua needs to know when the object is deleted so that it can handle
276 // requests for it appropriately (ie with an exception, or exists())
277 template <typename T>
278 class LuaCoreObject : public LuaObject<T> {
279 public:
281  m_object(o)
282  {
283  m_deleteConnection = m_object->DeleteEmitter::onDelete.connect(sigc::mem_fun(this, &LuaCoreObject::OnDelete));
284  }
285 
287  {
288  if (m_deleteConnection.connected())
289  m_deleteConnection.disconnect();
290  }
291 
293  {
294  return m_object;
295  }
296 
297 private:
298  void OnDelete()
299  {
301  m_object = 0;
302  }
303 
304  T *m_object;
305  sigc::connection m_deleteConnection;
306 };
307 
308 // wrapper for a "shared" object - one that can comfortably exist in both
309 // environments. usually for long-lived (StarSystem) or standalone (UI
310 // widget) objects
311 // Lua simply needs to keep a reference to these
312 template <typename T>
313 class LuaSharedObject : public LuaObject<T> {
314 public:
316  m_object(o) {}
317 
319  {
320  return m_object.Get();
321  }
322 
323 private:
324  RefCountedPtr<T> m_object;
325 };
326 
327 // wrapper for a "copied" object. a new one is created via the copy
328 // constructor and fully owned by Lua. good for lightweight POD-style objects
329 // (eg SystemPath)
330 template <typename T>
331 class LuaCopyObject : public LuaObject<T> {
332 public:
333  LuaCopyObject(const T &o)
334  {
335  lua_State *l = Lua::manager->GetLuaState();
336  m_object = new (LuaObjectBase::Allocate(sizeof(T))) T(o);
337  m_ref = LuaRef(l, -1);
338  lua_pop(l, 1);
339  }
340 
342  {
343  m_object->~T();
344  m_object = 0;
345  }
346 
348  {
349  return m_object;
350  }
351 
352 private:
353  T *m_object;
354  LuaRef m_ref;
355 };
356 
357 // push methods, create wrappers if necessary
358 // wrappers are allocated from Lua memory
359 template <typename T>
361 {
362  if (!PushRegistered(o))
363  Register(new (LuaObjectBase::Allocate(sizeof(LuaCoreObject<T>))) LuaCoreObject<T>(static_cast<T *>(o)));
364 }
365 
366 template <typename T>
368 {
369  if (!PushRegistered(o))
370  Register(new (LuaObjectBase::Allocate(sizeof(LuaSharedObject<T>))) LuaSharedObject<T>(static_cast<T *>(o)));
371 }
372 
373 template <typename T>
374 inline void LuaObject<T>::PushToLua(const T &o)
375 {
377 }
378 
379 template <typename T>
380 template <typename Ret, typename Key, typename... Args>
381 inline Ret LuaObject<T>::CallMethod(T *o, const Key &key, const Args &... args)
382 {
383  lua_State *l = Lua::manager->GetLuaState();
384  LUA_DEBUG_START(l);
385  Ret return_value;
386 
387  lua_checkstack(l, sizeof...(args) + 5);
388  PushToLua(o);
389  pi_lua_generic_push(l, key);
390  lua_gettable(l, -2);
391  lua_pushvalue(l, -2);
392  lua_remove(l, -3);
393  pi_lua_multiple_push(l, args...);
394  pi_lua_protected_call(l, sizeof...(args) + 1, 1);
395  pi_lua_generic_pull(l, -1, return_value);
396  lua_pop(l, 1);
397  LUA_DEBUG_END(l, 0);
398  return return_value;
399 }
400 
401 template <typename T>
402 template <typename Ret1, typename Ret2, typename... Ret, typename Key, typename... Args>
403 inline std::tuple<Ret1, Ret2, Ret...> LuaObject<T>::CallMethod(T *o, const Key &key, const Args &... args)
404 {
405  lua_State *l = Lua::manager->GetLuaState();
406 
407  LUA_DEBUG_START(l);
408  lua_checkstack(l, sizeof...(args) + 5);
409  PushToLua(o);
410  pi_lua_generic_push(l, key);
411  lua_gettable(l, -2);
412  lua_pushvalue(l, -2);
413  lua_remove(l, -3);
414  pi_lua_multiple_push(l, args...);
415  pi_lua_protected_call(l, sizeof...(args) + 1, 2 + sizeof...(Ret));
416  auto ret_values = pi_lua_multiple_pull<Ret1, Ret2, Ret...>(l, -2 - static_cast<int>(sizeof...(Ret)));
417  lua_pop(l, 2 + static_cast<int>(sizeof...(Ret)));
418  LUA_DEBUG_END(l, 0);
419  return ret_values;
420 }
421 
422 // specialise for SystemPath, which needs custom machinery to deduplicate system paths
423 class SystemPath;
424 template <>
426 
427 inline void pi_lua_generic_pull(lua_State *l, int index, SystemPath &out)
428 {
429  assert(l == Lua::manager->GetLuaState());
431 }
432 
433 inline void pi_lua_generic_push(lua_State *l, const SystemPath &value)
434 {
435  assert(l == Lua::manager->GetLuaState());
437 }
438 
439 // LuaPushPull stuff.
440 template <class T>
441 void pi_lua_generic_pull(lua_State *l, int index, T *&out)
442 {
443  assert(l == Lua::manager->GetLuaState());
445 }
446 
447 template <class T>
448 bool pi_lua_strict_pull(lua_State *l, int index, T *&out)
449 {
450  assert(l == Lua::manager->GetLuaState());
452  return out != 0;
453 }
454 
455 template <class T>
456 void pi_lua_generic_push(lua_State *l, T *value)
457 {
458  assert(l == Lua::manager->GetLuaState());
459  if (value)
461  else
462  lua_pushnil(l);
463 }
464 
465 #endif
nlohmann::json Json
Definition: Json.h:8
void pi_lua_generic_pull(lua_State *l, int index, SystemPath &out)
Definition: LuaObject.h:427
bool(* PromotionTest)(LuaWrappable *o)
Definition: LuaObject.h:69
void pi_lua_generic_push(lua_State *l, const SystemPath &value)
Definition: LuaObject.h:433
bool pi_lua_strict_pull(lua_State *l, int index, T *&out)
Definition: LuaObject.h:448
std::tuple< Types... > pi_lua_multiple_pull(lua_State *l, int beg)
Definition: LuaPushPull.h:215
void pi_lua_multiple_push(lua_State *l, Types... args)
#define LUA_DEBUG_START(luaptr)
Definition: LuaUtils.h:100
#define LUA_DEBUG_END(luaptr, expectedStackDiff)
Definition: LuaUtils.h:101
void pi_lua_protected_call(lua_State *L, int nargs, int nresults)
Definition: Sandbox.cpp:170
Definition: DeleteEmitter.h:16
Definition: LuaObject.h:331
LuaCopyObject(const T &o)
Definition: LuaObject.h:333
LuaWrappable * GetObject() const
Definition: LuaObject.h:347
~LuaCopyObject()
Definition: LuaObject.h:341
Definition: LuaObject.h:278
LuaCoreObject(T *o)
Definition: LuaObject.h:280
~LuaCoreObject()
Definition: LuaObject.h:286
LuaWrappable * GetObject() const
Definition: LuaObject.h:292
lua_State * GetLuaState()
Definition: LuaManager.h:14
Definition: LuaMetaType.h:12
Definition: LuaObject.h:106
static void CreateObject(const luaL_Reg *methods, const luaL_Reg *attrs, const luaL_Reg *meta, bool protect=false)
Definition: LuaObject.cpp:288
static void * Allocate(size_t n)
Definition: LuaObject.cpp:743
const char * GetType() const
Definition: LuaObject.h:183
virtual LuaWrappable * GetObject() const =0
static bool Deserialize(const char *stream, const char **next)
Definition: LuaObject.cpp:692
static LuaWrappable * CheckFromLua(int index, const char *type)
Definition: LuaObject.cpp:589
void ToJson(Json &out)
Definition: LuaObject.cpp:713
LuaObjectBase(const char *type)
Definition: LuaObject.h:125
static PropertyMap * GetPropertiesFromObject(lua_State *l, int object)
Definition: LuaObject.cpp:239
static LuaWrappable * GetFromLua(int index, const char *type)
Definition: LuaObject.cpp:609
static void RegisterPromotion(const char *base_type, const char *target_type, PromotionTest test_fn)
Definition: LuaObject.cpp:665
static void CreateClass(const char *type, const char *parent, const luaL_Reg *methods, const luaL_Reg *attrs, const luaL_Reg *meta)
Definition: LuaObject.cpp:347
virtual ~LuaObjectBase()
Definition: LuaObject.h:127
static bool PushRegistered(LuaWrappable *o)
Definition: LuaObject.cpp:453
static void Register(LuaObjectBase *lo)
Definition: LuaObject.cpp:487
std::string Serialize()
Definition: LuaObject.cpp:675
static void RegisterSerializer(const char *type, SerializerPair pair)
Definition: LuaObject.cpp:670
static bool FromJson(const Json &obj)
Definition: LuaObject.cpp:729
static void Deregister(LuaObjectBase *lo)
Definition: LuaObject.cpp:567
Definition: LuaObject.cpp:96
Definition: LuaObject.h:201
static void CallMethod(T *o, const Key &key, const Args &... args)
Definition: LuaObject.h:215
static void PushToLua(DeleteEmitter *o)
Definition: LuaObject.h:360
static T * CheckFromLua(int idx)
Definition: LuaObject.h:225
LuaObject()
Definition: LuaObject.h:261
static bool DynamicCastPromotionTest(LuaWrappable *o)
Definition: LuaObject.h:251
static T * GetFromLua(int idx)
Definition: LuaObject.h:238
static Ret CallMethod(T *o, const Key &key, const Args &... args)
Definition: LuaObject.h:381
static void RegisterClass()
Definition: LuaRef.h:12
Definition: LuaSerializer.h:12
Definition: LuaObject.h:313
LuaSharedObject(T *o)
Definition: LuaObject.h:315
LuaWrappable * GetObject() const
Definition: LuaObject.h:318
Definition: LuaWrappable.h:13
Definition: PropertyMap.h:11
Definition: RefCounted.h:36
Definition: RefCounted.h:11
Definition: SystemPath.h:13
const Color4ub * GetFromLua(lua_State *L, int idx)
Definition: LuaColor.cpp:303
void PushToLua(lua_State *L, const Color4ub &v)
Definition: LuaColor.h:14
Color4ub * CheckFromLua(lua_State *L, int idx)
Definition: LuaColor.cpp:308
void Register(lua_State *L)
Definition: LuaColor.cpp:273
LuaManager * manager
Definition: Lua.cpp:43
Definition: GeomTree.h:9
Definition: LuaObject.h:72
ToJson to_json
Definition: LuaObject.h:97
FromJson from_json
Definition: LuaObject.h:98
bool(* FromJson)(const Json &obj)
Definition: LuaObject.h:77
SerializerPair()
Definition: LuaObject.h:79
Serializer serialize
Definition: LuaObject.h:95
Deserializer deserialize
Definition: LuaObject.h:96
bool(* Deserializer)(const char *stream, const char **next)
Definition: LuaObject.h:74
void(* ToJson)(Json &out, LuaWrappable *o)
Definition: LuaObject.h:76
SerializerPair(Serializer serialize_, Deserializer deserialize_, ToJson to_json_, FromJson from_json_)
Definition: LuaObject.h:86