Fix some compilation errors on Mac OS X
[lsnes.git] / include / library / lua-class.hpp
blob4e02d867d696dce8212b16995f045c426d329992
1 #ifndef _library__lua_class__hpp__included__
2 #define _library__lua_class__hpp__included__
4 #include "lua-base.hpp"
5 #include "lua-pin.hpp"
7 namespace lua
9 class class_base;
10 class parameters;
12 /**
13 * Group of classes.
15 class class_group
17 public:
18 /**
19 * Create a group.
21 class_group();
22 /**
23 * Destroy a group.
25 ~class_group();
26 /**
27 * Add a class to group.
29 void do_register(const std::string& name, class_base& fun);
30 /**
31 * Drop a class from group.
33 void do_unregister(const std::string& name, class_base& fun);
34 /**
35 * Request callbacks on all currently registered functions.
37 void request_callback(std::function<void(std::string, class_base*)> cb);
38 /**
39 * Bind a callback.
41 * Callbacks for all registered functions are immediately called.
43 int add_callback(std::function<void(std::string, class_base*)> cb,
44 std::function<void(class_group*)> dcb);
45 /**
46 * Unbind a calback.
48 void drop_callback(int handle);
49 private:
50 char dummy;
53 struct class_ops
55 bool (*is)(state& _state, int index);
56 const std::string& (*name)();
57 std::string (*print)(state& _state, int index);
60 std::list<class_ops>& userdata_recogn_fns();
61 std::string try_recognize_userdata(state& _state, int index);
62 std::string try_print_userdata(state& _state, int index);
63 std::unordered_map<std::type_index, void*>& class_types();
65 /**
66 * Helper class containing binding data for Lua class call.
68 template<class T> struct class_binding
70 /**
71 * The pointer to call.
73 int (T::*fn)(state& lstate, lua::parameters& P);
74 /**
75 * The state to call it in.
77 state* _state;
78 /**
79 * The name of the method to pass.
81 char fname[];
84 /**
85 * Helper class containing binding data for Lua static class call.
87 struct static_binding
89 /**
90 * The pointer to call.
92 int (*fn)(state& lstate, parameters& P);
93 /**
94 * The state to call it in.
96 state* _state;
97 /**
98 * The name of the method to pass.
100 char fname[];
103 template<class T> class _class;
106 * Function to obtain class object for given Lua class.
108 template<class T> _class<T>& objclass()
110 auto& type = typeid(T);
111 if(!class_types().count(type))
112 throw std::runtime_error("Internal error: Lua class not found!");
113 return *reinterpret_cast<_class<T>*>(class_types()[type]);
117 * A class method.
119 template<class T> struct class_method
122 * Name.
124 const char* name;
126 * Function.
128 int (T::*fn)(state& LS, lua::parameters& P);
132 * A static class method.
134 struct static_method
137 * Name.
139 const char* name;
141 * Function.
143 int (*fn)(state& LS, parameters& P);
147 * Virtual base of Lua classes
149 class class_base
151 public:
153 * Create a new Lua class.
155 * Parameter _group: The group the class will be in.
156 * Parameter _name: The name of the class.
158 class_base(class_group& _group, const std::string& _name);
160 * Dtor.
162 virtual ~class_base() throw();
164 * Lookup by name in given Lua state.
166 * Parameter _L: The Lua state to look in.
167 * Parameter _name: The name of the class.
168 * Returns: The class instance, or NULL if no match.
170 static class_base* lookup(state& L, const std::string& _name);
172 * Push class table to stack.
174 static bool lookup_and_push(state& L, const std::string& _name);
176 * Get set of all classes.
178 static std::set<std::string> all_classes(state& L);
180 * Register in given Lua state.
182 virtual void register_state(state& L) = 0;
184 * Lookup static methods in class.
186 virtual std::list<static_method> static_methods() = 0;
188 * Lookup class methods in class.
190 virtual std::set<std::string> class_methods() = 0;
192 * Get name of class.
194 const std::string& get_name() { return name; }
195 protected:
196 void delayed_register();
197 void register_static(state& L);
198 private:
199 class_group& group;
200 std::string name;
201 bool registered;
204 static const size_t overcommit_std_align = 32;
207 * Align a overcommit pointer.
209 template<typename T, typename U> U* align_overcommit(T* th)
211 size_t ptr = reinterpret_cast<size_t>(th) + sizeof(T);
212 return reinterpret_cast<U*>(ptr + (overcommit_std_align - ptr % overcommit_std_align) % overcommit_std_align);
216 * The type of Lua classes.
218 template<class T> class _class : public class_base
220 template<typename... U> T* _create(state& _state, U... args)
222 size_t overcommit = T::overcommit(args...);
223 void* obj = _state.newuserdata(sizeof(T) + overcommit);
224 load_metatable(_state);
225 _state.setmetatable(-2);
226 T* _obj = reinterpret_cast<T*>(obj);
227 new(_obj) T(_state, args...);
228 return _obj;
231 static int class_bind_trampoline(lua_State* LS)
233 try {
234 class_binding<T>* b = (class_binding<T>*)lua_touserdata(LS, lua_upvalueindex(1));
235 state L(*b->_state, LS);
236 T* p = _class<T>::get(L, 1, b->fname);
237 lua::parameters P(L, b->fname);
238 return (p->*(b->fn))(L, P);
239 } catch(std::exception& e) {
240 std::string err = e.what();
241 lua_pushlstring(LS, err.c_str(), err.length());
242 lua_error(LS);
244 return 0; //NOTREACHED
247 T* _get(state& _state, int arg, const std::string& fname, bool optional = false)
249 if(_state.type(arg) == LUA_TNONE || _state.type(arg) == LUA_TNIL) {
250 if(optional)
251 return NULL;
252 else
253 goto badtype;
255 load_metatable(_state);
256 if(!_state.getmetatable(arg))
257 goto badtype;
258 if(!_state.rawequal(-1, -2))
259 goto badtype;
260 _state.pop(2);
261 return reinterpret_cast<T*>(_state.touserdata(arg));
262 badtype:
263 (stringfmt() << "argument #" << arg << " to " << fname << " must be " << name).throwex();
264 return NULL; //Never reached.
267 bool _is(state& _state, int arg)
269 if(_state.type(arg) != LUA_TUSERDATA)
270 return false;
271 load_metatable(_state);
272 if(!_state.getmetatable(arg)) {
273 _state.pop(1);
274 return false;
276 bool ret = _state.rawequal(-1, -2);
277 _state.pop(2);
278 return ret;
281 objpin<T> _pin(state& _state, int arg, const std::string& fname)
283 T* obj = get(_state, arg, fname);
284 _state.pushvalue(arg);
285 objpin<T> t(_state, obj);
286 _state.pop(1);
287 return t;
290 void bind(state& _state, const char* keyname, int (T::*fn)(state& LS, lua::parameters& P))
292 load_metatable(_state);
293 _state.pushstring(keyname);
294 std::string fname = name + std::string("::") + keyname;
295 void* ptr = _state.newuserdata(sizeof(class_binding<T>) + fname.length() + 1);
296 class_binding<T>* bdata = reinterpret_cast<class_binding<T>*>(ptr);
297 bdata->fn = fn;
298 bdata->_state = &_state.get_master();
299 std::copy(fname.begin(), fname.end(), bdata->fname);
300 bdata->fname[fname.length()] = 0;
301 _state.pushcclosure(class_bind_trampoline, 1);
302 _state.rawset(-3);
303 _state.pop(1);
305 protected:
306 void register_state(state& L)
308 static char once_key;
309 register_static(L);
310 if(L.do_once(&once_key))
311 for(auto i : cmethods)
312 bind(L, i.name, i.fn);
314 public:
316 * Create a new Lua class.
318 * Parameter _group: The group the class will be in.
319 * Parameter _name: The name of the class.
320 * Parameter _smethods: Static methods of the class.
321 * Parameter _cmethods: Class methods of the class.
322 * Parameter _print: The print method.
324 _class(class_group& _group, const std::string& _name, std::initializer_list<static_method> _smethods,
325 std::initializer_list<class_method<T>> _cmethods = {}, std::string (T::*_print)() = NULL)
326 : class_base(_group, _name), smethods(_smethods), cmethods(_cmethods)
328 name = _name;
329 class_ops m;
330 printmeth = _print;
331 m.is = _class<T>::is;
332 m.name = _class<T>::get_name;
333 m.print = _class<T>::print;
334 userdata_recogn_fns().push_back(m);
335 auto& type = typeid(T);
336 class_types()[type] = this;
337 delayed_register();
340 * Dtor
342 ~_class() throw()
344 auto& type = typeid(T);
345 class_types().erase(type);
346 auto& fns = userdata_recogn_fns();
347 for(auto i = fns.begin(); i != fns.end(); i++) {
348 if(i->is == _class<T>::is) {
349 fns.erase(i);
350 break;
355 * Create a new instance of object.
357 * Parameter _state: The Lua state to create the object in.
358 * Parameter args: The arguments to pass to class constructor.
360 template<typename... U> static T* create(state& _state, U... args)
362 return objclass<T>()._create(_state, args...);
366 * Get a pointer to the object.
368 * Parameter _state: The Lua state.
369 * Parameter arg: Argument index.
370 * Parameter fname: The name of function for error messages.
371 * Parameter optional: If true and argument is NIL or none, return NULL.
372 * Throws std::runtime_error: Wrong type.
374 static T* get(state& _state, int arg, const std::string& fname, bool optional = false)
375 throw(std::bad_alloc, std::runtime_error)
377 return objclass<T>()._get(_state, arg, fname, optional);
381 * Identify if object is of this type.
383 * Parameter _state: The Lua state.
384 * Parameter arg: Argument index.
385 * Returns: True if object is of specified type, false if not.
387 static bool is(state& _state, int arg) throw()
389 try {
390 return objclass<T>()._is(_state, arg);
391 } catch(...) {
392 return false;
396 * Get name of class.
398 static const std::string& get_name()
400 try {
401 return objclass<T>().name;
402 } catch(...) {
403 static std::string foo = "???";
404 return foo;
408 * Format instance of this class as string.
410 static std::string print(state& _state, int index)
412 T* obj = get(_state, index, "__internal_print");
413 try {
414 auto pmeth = objclass<T>().printmeth;
415 if(pmeth)
416 return (obj->*pmeth)();
417 else
418 return "";
419 } catch(...) {
420 return "";
424 * Get a pin of object against Lua GC.
426 * Parameter _state: The Lua state.
427 * Parameter arg: Argument index.
428 * Parameter fname: Name of function for error message purposes.
429 * Throws std::runtime_error: Wrong type.
431 static objpin<T> pin(state& _state, int arg, const std::string& fname) throw(std::bad_alloc,
432 std::runtime_error)
434 return objclass<T>()._pin(_state, arg, fname);
437 * Lookup static methods.
439 std::list<static_method> static_methods()
441 return smethods;
444 * Lookup class methods.
446 std::set<std::string> class_methods()
448 std::set<std::string> r;
449 for(auto& i : cmethods)
450 r.insert(i.name);
451 return r;
453 private:
454 static int dogc(lua_State* LS)
456 T* obj = reinterpret_cast<T*>(lua_touserdata(LS, 1));
457 obj->~T();
458 return 0;
461 static int newindex(lua_State* LS)
463 lua_pushstring(LS, "Writing metatables of classes is not allowed");
464 lua_error(LS);
465 return 0;
468 static int index(lua_State* LS)
470 lua_getmetatable(LS, 1);
471 lua_pushvalue(LS, 2);
472 lua_rawget(LS, -2);
473 if(lua_type(LS, -1) == LUA_TNIL) {
474 std::string err = std::string("Class '") + lua_tostring(LS, lua_upvalueindex(1)) +
475 "' does not have class method '" + lua_tostring(LS, 2) + "'";
476 lua_pushstring(LS, err.c_str());
477 lua_error(LS);
479 return 1;
482 void load_metatable(state& _state)
484 again:
485 _state.pushlightuserdata(this);
486 _state.rawget(LUA_REGISTRYINDEX);
487 if(_state.type(-1) == LUA_TNIL) {
488 _state.pop(1);
489 _state.pushlightuserdata(this);
490 _state.newtable();
491 _state.pushvalue(-1);
492 _state.setmetatable(-2);
493 _state.pushstring("__gc");
494 _state.pushcfunction(&_class<T>::dogc);
495 _state.rawset(-3);
496 _state.pushstring("__newindex");
497 _state.pushcfunction(&_class<T>::newindex);
498 _state.rawset(-3);
499 _state.pushstring("__index");
500 _state.pushlstring(name);
501 _state.pushcclosure(&_class<T>::index, 1);
502 _state.rawset(-3);
503 _state.rawset(LUA_REGISTRYINDEX);
504 goto again;
507 std::string name;
508 std::list<static_method> smethods;
509 std::list<class_method<T>> cmethods;
510 std::string (T::*printmeth)();
511 _class(const _class<T>&);
512 _class& operator=(const _class<T>&);
516 #endif