Debian Codegraph @

lupa/lua54.pyx

raw
1 ####### DO NOT EDIT - BUILD TIME COPY OF "_lupa.pyx" #######
2
3 # cython: embedsignature=True, binding=True, language_level=3str
4
5 """
6 A fast Python wrapper around Lua and LuaJIT2.
7 """
8
9 from __future__ import absolute_import
10
11 cimport cython
12
13 from libc.string cimport strlen, strchr
14 from libc.stdlib cimport malloc, free, realloc
15 from libc.stdio cimport fprintf, stderr, fflush
16 from . cimport luaapi as lua
17 from .luaapi cimport lua_State
18
19 cimport cpython.ref
20 cimport cpython.tuple
21 cimport cpython.float
22 cimport cpython.long
23 from cpython.ref cimport PyObject
24 from cpython.method cimport (
25 PyMethod_Check, PyMethod_GET_SELF, PyMethod_GET_FUNCTION)
26 from cpython.bytes cimport PyBytes_FromFormat
27
28 #from libc.stdint cimport uintptr_t
29 cdef extern from "stdint.h":
30 ctypedef size_t uintptr_t
31 cdef const Py_ssize_t PY_SSIZE_T_MAX
32 cdef const char CHAR_MIN, CHAR_MAX
33 cdef const short SHRT_MIN, SHRT_MAX
34 cdef const int INT_MIN, INT_MAX
35 cdef const long LONG_MIN, LONG_MAX
36 cdef const long long PY_LLONG_MIN, PY_LLONG_MAX
37
38 cdef object exc_info
39 from sys import exc_info
40
41 cdef object Mapping
42 cdef object Sequence
43 from collections.abc import Mapping, Sequence
44
45 cdef object wraps
46 from functools import wraps
47
48
49 __all__ = ['LUA_VERSION', 'LUA_MAXINTEGER', 'LUA_MININTEGER',
50 'LuaRuntime', 'LuaError', 'LuaSyntaxError', 'LuaMemoryError',
51 'as_itemgetter', 'as_attrgetter', 'lua_type',
52 'unpacks_lua_table', 'unpacks_lua_table_method']
53
54 cdef object builtins
55 try:
56 import __builtin__ as builtins
57 except ImportError:
58 import builtins
59
60 DEF POBJECT = b"POBJECT" # as used by LunaticPython
61 DEF LUPAOFH = b"LUPA_NUMBER_OVERFLOW_CALLBACK_FUNCTION"
62 DEF PYREFST = b"LUPA_PYTHON_REFERENCES_TABLE"
63
64 cdef enum WrappedObjectFlags:
65 # flags that determine the behaviour of a wrapped object:
66 OBJ_AS_INDEX = 1 # prefers the getitem protocol (over getattr)
67 OBJ_UNPACK_TUPLE = 2 # unpacks into separate values if it is a tuple
68 OBJ_ENUMERATOR = 4 # iteration uses native enumerate() implementation
69
70 cdef struct py_object:
71 PyObject* obj
72 PyObject* runtime
73 int type_flags # or-ed set of WrappedObjectFlags
74
75
76 include "lock.pxi"
77
78
79 cdef int _LUA_VERSION = lua.read_lua_version(NULL)
80 LUA_VERSION = (_LUA_VERSION // 100, _LUA_VERSION % 100)
81
82
83 if lua.LUA_MAXINTEGER > 0:
84 LUA_MININTEGER, LUA_MAXINTEGER = (lua.LUA_MININTEGER, lua.LUA_MAXINTEGER)
85 elif sizeof(lua.lua_Integer) >= sizeof(long long): # probably not larger
86 LUA_MININTEGER, LUA_MAXINTEGER = (PY_LLONG_MIN, PY_LLONG_MAX)
87 elif sizeof(lua.lua_Integer) >= sizeof(long):
88 LUA_MININTEGER, LUA_MAXINTEGER = (LONG_MIN, LONG_MAX)
89 elif sizeof(lua.lua_Integer) >= sizeof(int):
90 LUA_MININTEGER, LUA_MAXINTEGER = (INT_MIN, INT_MAX)
91 elif sizeof(lua.lua_Integer) >= sizeof(short):
92 LUA_MININTEGER, LUA_MAXINTEGER = (SHRT_MIN, SHRT_MAX)
93 else: # probably not smaller
94 LUA_MININTEGER, LUA_MAXINTEGER = (CHAR_MIN, CHAR_MAX)
95
96
97 cdef struct MemoryStatus:
98 size_t used
99 size_t base_usage
100 size_t limit
101
102
103 class LuaError(Exception):
104 """Base class for errors in the Lua runtime.
105 """
106
107
108 class LuaSyntaxError(LuaError):
109 """Syntax error in Lua code.
110 """
111
112
113 class LuaMemoryError(LuaError, MemoryError):
114 """Memory error in Lua code.
115 """
116
117
118 def lua_type(obj):
119 """
120 Return the Lua type name of a wrapped object as string, as provided
121 by Lua's type() function.
122
123 For non-wrapper objects (i.e. normal Python objects), returns None.
124 """
125 if not isinstance(obj, _LuaObject):
126 return None
127 lua_object = <_LuaObject>obj
128 assert lua_object._runtime is not None
129 assert lua_object._runtime._state is not NULL
130 lock_runtime(lua_object._runtime)
131 L = lua_object._state
132 old_top = lua.lua_gettop(L)
133 cdef const char* lua_type_name
134 try:
135 check_lua_stack(L, 1)
136 lua_object.push_lua_object(L)
137 ltype = lua.lua_type(L, -1)
138 if ltype == lua.LUA_TTABLE:
139 return 'table'
140 elif ltype == lua.LUA_TFUNCTION:
141 return 'function'
142 elif ltype == lua.LUA_TTHREAD:
143 return 'thread'
144 elif ltype in (lua.LUA_TUSERDATA, lua.LUA_TLIGHTUSERDATA):
145 return 'userdata'
146 else:
147 lua_type_name = lua.lua_typename(L, ltype)
148 return lua_type_name.decode('ascii')
149 finally:
150 lua.lua_settop(L, old_top)
151 unlock_runtime(lua_object._runtime)
152
153 cdef inline int _len_as_int(Py_ssize_t obj) except -1:
154 if obj > <Py_ssize_t>INT_MAX:
155 raise OverflowError
156 return <int>obj
157
158 @cython.no_gc_clear
159 cdef class LuaRuntime:
160 """The main entry point to the Lua runtime.
161
162 Available options:
163
164 * ``encoding``: the string encoding, defaulting to UTF-8. If set
165 to ``None``, all string values will be returned as byte strings.
166 Otherwise, they will be decoded to unicode strings on the way
167 from Lua to Python and unicode strings will be encoded on the
168 way to Lua. Note that ``str()`` calls on Lua objects will
169 always return a unicode object.
170
171 * ``source_encoding``: the encoding used for Lua code, defaulting to
172 the string encoding or UTF-8 if the string encoding is ``None``.
173
174 * ``attribute_filter``: filter function for attribute access
175 (get/set). Must have the signature ``func(obj, attr_name,
176 is_setting)``, where ``is_setting`` is True when the attribute
177 is being set. If provided, the function will be called for all
178 Python object attributes that are being accessed from Lua code.
179 Normally, it should return an attribute name that will then be
180 used for the lookup. If it wants to prevent access, it should
181 raise an ``AttributeError``. Note that Lua does not guarantee
182 that the names will be strings. (New in Lupa 0.20)
183
184 * ``attribute_handlers``: like ``attribute_filter`` above, but
185 handles the getting/setting itself rather than giving hints
186 to the LuaRuntime. This must be a 2-tuple, ``(getter, setter)``
187 where ``getter`` has the signature ``func(obj, attr_name)``
188 and either returns the value for ``obj.attr_name`` or raises an
189 ``AttributeError`` The function ``setter`` has the signature
190 ``func(obj, attr_name, value)`` and may raise an ``AttributeError``.
191 The return value of the setter is unused. (New in Lupa 1.0)
192
193 * ``register_eval``: should Python's ``eval()`` function be available
194 to Lua code as ``python.eval()``? Note that this does not remove it
195 from the builtins. Use an ``attribute_filter`` function for that.
196 (default: True)
197
198 * ``register_builtins``: should Python's builtins be available to Lua
199 code as ``python.builtins.*``? Note that this does not prevent access
200 to the globals available as special Python function attributes, for
201 example. Use an ``attribute_filter`` function for that.
202 (default: True, new in Lupa 1.2)
203
204 * ``unpack_returned_tuples``: should Python tuples be unpacked in Lua?
205 If ``py_fun()`` returns ``(1, 2, 3)``, then does ``a, b, c = py_fun()``
206 give ``a == 1 and b == 2 and c == 3`` or does it give
207 ``a == (1,2,3), b == nil, c == nil``? ``unpack_returned_tuples=True``
208 gives the former.
209 (default: False, new in Lupa 0.21)
210
211 * ``overflow_handler``: function for handling Python integers overflowing
212 Lua integers. Must have the signature ``func(obj)``. If provided, the
213 function will be called when a Python integer (possibly of arbitrary
214 precision type) is too large to fit in a fixed-precision Lua integer.
215 Normally, it should return the now well-behaved object that can be
216 converted/wrapped to a Lua type. If the object cannot be precisely
217 represented in Lua, it should raise an ``OverflowError``.
218
219 * ``max_memory``: max memory usage this LuaRuntime can use in bytes.
220 If max_memory is None, the default lua allocator is used and calls to
221 ``set_max_memory(limit)`` will fail with a ``LuaMemoryError``.
222 Note: Not supported on 64bit LuaJIT.
223 (default: None, i.e. no limitation. New in Lupa 2.0)
224
225 Example usage::
226
227 >>> from lupa import LuaRuntime
228 >>> lua = LuaRuntime()
229
230 >>> lua.eval('1+1')
231 2
232
233 >>> lua_func = lua.eval('function(f, n) return f(n) end')
234
235 >>> def py_add1(n): return n+1
236 >>> lua_func(py_add1, 2)
237 3
238 """
239 cdef lua_State *_state
240 cdef FastRLock _lock
241 cdef dict _pyrefs_in_lua
242 cdef tuple _raised_exception
243 cdef list _pending_unrefs
244 cdef bytes _encoding
245 cdef bytes _source_encoding
246 cdef object _attribute_filter
247 cdef object _attribute_getter
248 cdef object _attribute_setter
249 cdef bint _unpack_returned_tuples
250 cdef MemoryStatus _memory_status
251
252 def __cinit__(self, encoding='UTF-8', source_encoding=None,
253 attribute_filter=None, attribute_handlers=None,
254 bint register_eval=True, bint unpack_returned_tuples=False,
255 bint register_builtins=True, overflow_handler=None,
256 max_memory=None):
257 cdef lua_State* L
258
259 if max_memory is None:
260 L = lua.luaL_newstate()
261 self._memory_status.limit = <size_t> -1
262 else:
263 L = lua.lua_newstate(<lua.lua_Alloc>&_lua_alloc_restricted, <void*>&self._memory_status)
264 if L is NULL:
265 raise LuaError("Failed to initialise Lua runtime")
266
267 self._state = L
268 self._lock = FastRLock()
269 self._pyrefs_in_lua = {}
270 self._encoding = _asciiOrNone(encoding)
271 self._source_encoding = _asciiOrNone(source_encoding) or self._encoding or b'UTF-8'
272 if attribute_filter is not None and not callable(attribute_filter):
273 raise ValueError("attribute_filter must be callable")
274 self._attribute_filter = attribute_filter
275 self._unpack_returned_tuples = unpack_returned_tuples
276
277 if attribute_handlers:
278 raise_error = False
279 try:
280 getter, setter = attribute_handlers
281 except (ValueError, TypeError):
282 raise_error = True
283 else:
284 if (getter is not None and not callable(getter) or
285 setter is not None and not callable(setter)):
286 raise_error = True
287 if raise_error:
288 raise ValueError("attribute_handlers must be a sequence of two callables")
289 if attribute_filter and (getter is not None or setter is not None):
290 raise ValueError("attribute_filter and attribute_handlers are mutually exclusive")
291 self._attribute_getter, self._attribute_setter = getter, setter
292
293 lua.lua_atpanic(L, &_lua_panic)
294 lua.luaL_openlibs(L)
295 self.init_python_lib(register_eval, register_builtins)
296
297 self.set_overflow_handler(overflow_handler)
298
299 # lupa init done, set real limit
300 if max_memory is not None:
301 self._memory_status.base_usage = self._memory_status.used
302 if max_memory > 0:
303 self._memory_status.limit = self._memory_status.base_usage + <size_t>max_memory
304 # Prevent accidental (or deliberate) usage of our special value.
305 if self._memory_status.limit == <size_t> -1:
306 self._memory_status.limit -= 1
307
308 @cython.final
309 cdef void add_pending_unref(self, int ref) noexcept:
310 pyval: object = ref
311 if self._pending_unrefs is None:
312 self._pending_unrefs = [pyval]
313 else:
314 self._pending_unrefs.append(pyval)
315
316 @cython.final
317 cdef int clean_up_pending_unrefs(self) except -1:
318 if self._pending_unrefs is None or self._state is NULL:
319 return 0
320
321 pending_unrefs = self._pending_unrefs
322 self._pending_unrefs = None
323
324 cdef int ref
325 L = self._state
326 for ref in pending_unrefs:
327 lua.luaL_unref(L, lua.LUA_REGISTRYINDEX, ref)
328 return 0
329
330 def __dealloc__(self):
331 if self._state is not NULL:
332 lua.lua_close(self._state)
333 self._state = NULL
334
335 def get_max_memory(self, total=False):
336 """
337 Maximum memory allowed to be used by this LuaRuntime.
338 0 indicates no limit meanwhile None indicates that the default lua
339 allocator is being used and ``set_max_memory()`` cannot be used.
340
341 If ``total`` is True, the base memory used by the lua runtime
342 will be included in the limit.
343 """
344 if self._memory_status.limit == <size_t> -1:
345 return None
346 elif total:
347 return self._memory_status.limit
348 return self._memory_status.limit - self._memory_status.base_usage
349
350 def get_memory_used(self, total=False):
351 """
352 Memory currently in use.
353 This is None if the default lua allocator is used and 0 if
354 ``max_memory`` is 0.
355
356 If ``total`` is True, the base memory used by the lua runtime
357 will be included.
358 """
359 if self._memory_status.limit == <size_t> -1:
360 return None
361 elif total:
362 return self._memory_status.used
363 return self._memory_status.used - self._memory_status.base_usage
364
365 @property
366 def lua_version(self):
367 """
368 The Lua runtime/language version as tuple, e.g. (5, 3) for Lua 5.3.
369 """
370 assert self._state is not NULL
371 cdef int version = lua.read_lua_version(self._state)
372 return (version // 100, version % 100)
373
374 @property
375 def lua_implementation(self):
376 """
377 The Lua implementation version string, e.g. "Lua 5.3" or "LuaJIT 2.0.1".
378 May execute Lua code.
379 """
380 return self.eval(
381 "(function () "
382 " if type(jit) == 'table' then return jit.version else return _VERSION end "
383 "end)()"
384 )
385
386 @cython.final
387 cdef int reraise_on_exception(self) except -1:
388 if self._raised_exception is not None:
389 exception = self._raised_exception
390 self._raised_exception = None
391 raise exception[0], exception[1], exception[2]
392 return 0
393
394 @cython.final
395 cdef int store_raised_exception(self, lua_State* L, bytes lua_error_msg) except -1:
396 try:
397 self._raised_exception = tuple(exc_info())
398 py_to_lua(self, L, self._raised_exception[1])
399 except:
400 lua.lua_pushlstring(L, lua_error_msg, len(lua_error_msg))
401 raise
402 return 0
403
404 @cython.final
405 cdef bytes _source_encode(self, string):
406 if isinstance(string, unicode):
407 return (<unicode>string).encode(self._source_encoding)
408 elif isinstance(string, bytes):
409 return <bytes> string
410 elif isinstance(string, bytearray):
411 return bytes(string)
412
413 raise TypeError(f"Expected string, got {type(string)}")
414
415 def eval(self, lua_code, *args, name=None, mode=None):
416 """Evaluate a Lua expression passed in a string.
417
418 The 'name' argument can be used to override the name printed in error messages.
419
420 The 'mode' argument specifies the input type. By default, both source code and
421 pre-compiled byte code is allowed (mode='bt'). It can be restricted to source
422 code with mode='t' and to byte code with mode='b'. This has no effect on Lua 5.1.
423 """
424 assert self._state is not NULL
425 name_b = self._source_encode(name) if name is not None else None
426 mode_b = _asciiOrNone(mode)
427 return run_lua(self, b'return ' + self._source_encode(lua_code), name_b, mode_b, args)
428
429 def execute(self, lua_code, *args, name=None, mode=None):
430 """Execute a Lua program passed in a string.
431
432 The 'name' argument can be used to override the name printed in error messages.
433
434 The 'mode' argument specifies the input type. By default, both source code and
435 pre-compiled byte code is allowed (mode='bt'). It can be restricted to source
436 code with mode='t' and to byte code with mode='b'. This has no effect on Lua 5.1.
437 """
438 assert self._state is not NULL
439 name_b = self._source_encode(name) if name is not None else None
440 mode_b = _asciiOrNone(mode)
441 return run_lua(self, self._source_encode(lua_code), name_b, mode_b, args)
442
443 def compile(self, lua_code, name=None, mode=None):
444 """Compile a Lua program into a callable Lua function.
445
446 The 'name' argument can be used to override the name printed in error messages.
447
448 The 'mode' argument specifies the input type. By default, both source code and
449 pre-compiled byte code is allowed (mode='bt'). It can be restricted to source
450 code with mode='t' and to byte code with mode='b'. This has no effect on Lua 5.1.
451 """
452 assert self._state is not NULL
453 cdef const char * c_name = b'<python>'
454 cdef const char * c_mode = NULL
455
456 lua_code_bytes = self._source_encode(lua_code)
457 if name is not None:
458 name_b = self._source_encode(name)
459 c_name = name_b
460 if mode is not None:
461 mode_b = _asciiOrNone(mode)
462 c_mode = mode_b
463
464 L = self._state
465 lock_runtime(self)
466 old_top = lua.lua_gettop(L)
467 cdef size_t size
468 cdef const char *err
469 try:
470 check_lua_stack(L, 1)
471 status = lua.luaL_loadbufferx(L, lua_code_bytes, len(lua_code_bytes), c_name, c_mode)
472 if status == 0:
473 return py_from_lua(self, L, -1)
474 else:
475 err = lua.lua_tolstring(L, -1, &size)
476 if self._encoding is None:
477 error = err[:size] # bytes
478 is_memory_error = b"not enough memory" in error
479 else:
480 error = err[:size].decode(self._encoding)
481 is_memory_error = u"not enough memory" in error
482 if is_memory_error:
483 raise LuaMemoryError(error)
484 raise LuaSyntaxError(error)
485 finally:
486 lua.lua_settop(L, old_top)
487 unlock_runtime(self)
488
489 def require(self, modulename):
490 """Load a Lua library into the runtime.
491 """
492 assert self._state is not NULL
493 cdef lua_State *L = self._state
494 if not isinstance(modulename, (bytes, unicode)):
495 raise TypeError("modulename must be a string")
496 lock_runtime(self)
497 old_top = lua.lua_gettop(L)
498 try:
499 check_lua_stack(L, 1)
500 lua.lua_getglobal(L, 'require')
501 if lua.lua_isnil(L, -1):
502 raise LuaError("require is not defined")
503 return call_lua(self, L, (modulename,))
504 finally:
505 lua.lua_settop(L, old_top)
506 unlock_runtime(self)
507
508 def globals(self):
509 """Return the globals defined in this Lua runtime as a Lua
510 table.
511 """
512 assert self._state is not NULL
513 cdef lua_State *L = self._state
514 lock_runtime(self)
515 old_top = lua.lua_gettop(L)
516 try:
517 check_lua_stack(L, 1)
518 lua.lua_pushglobaltable(L)
519 return py_from_lua(self, L, -1)
520 finally:
521 lua.lua_settop(L, old_top)
522 unlock_runtime(self)
523
524 def table(self, *items, **kwargs):
525 """Create a new table with the provided items. Positional
526 arguments are placed in the table in order, keyword arguments
527 are set as key-value pairs.
528 """
529 return self.table_from(items, kwargs)
530
531 def table_from(self, *args, bint recursive=False):
532 """Create a new table from Python mapping or iterable.
533
534 table_from() accepts either a dict/mapping or an iterable with items.
535 Items from dicts are set as key-value pairs; items from iterables
536 are placed in the table in order.
537
538 Nested mappings / iterables are passed to Lua as userdata
539 (wrapped Python objects) by default. If `recursive` is True,
540 they are converted to Lua tables recursively, handling loops
541 and duplicates via identity de-duplication.
542 """
543 assert self._state is not NULL
544 cdef lua_State *L = self._state
545 lock_runtime(self)
546 try:
547 return py_to_lua_table(self, L, args, recursive=recursive)
548 finally:
549 unlock_runtime(self)
550
551 def nogc(self):
552 """
553 Return a context manager that temporarily disables the Lua garbage collector.
554 """
555 return _LuaNoGC(self)
556
557 def gccollect(self):
558 """
559 Run a full pass of the Lua garbage collector.
560 """
561 assert self._state is not NULL
562 cdef lua_State *L = self._state
563 lock_runtime(self)
564 # Pass third argument for compatibility with Lua 5.[123].
565 lua.lua_gc(L, lua.LUA_GCCOLLECT, <int> 0)
566 unlock_runtime(self)
567
568 def set_max_memory(self, size_t max_memory, total=False):
569 """Set maximum allowed memory for this LuaRuntime.
570
571 If `max_memory` is 0, there will be no limit.
572 If ``total`` is True, the base memory used by the LuaRuntime itself
573 will be included in the memory limit.
574
575 If max_memory was set to None during creation, this will raise a
576 RuntimeError.
577 """
578 cdef size_t used
579 if self._memory_status.limit == <size_t> -1:
580 raise RuntimeError("max_memory must be set on LuaRuntime creation")
581 elif max_memory == 0:
582 self._memory_status.limit = 0
583 elif total:
584 self._memory_status.limit = max_memory
585 else:
586 self._memory_status.limit = self._memory_status.base_usage + max_memory
587 # Prevent accidental (or deliberate) usage of our special value.
588 if self._memory_status.limit == <size_t> -1:
589 self._memory_status.limit -= 1
590
591 def set_overflow_handler(self, overflow_handler):
592 """Set the overflow handler function that is called on failures to pass large numbers to Lua.
593 """
594 assert self._state is not NULL
595 cdef lua_State *L = self._state
596 if overflow_handler is not None and not callable(overflow_handler):
597 raise ValueError("overflow_handler must be callable")
598 lock_runtime(self)
599 old_top = lua.lua_gettop(L)
600 try:
601 check_lua_stack(L, 2)
602 lua.lua_pushlstring(L, LUPAOFH, len(LUPAOFH)) # key
603 if not py_to_lua(self, L, overflow_handler): # key value
604 raise LuaError("failed to convert overflow_handler")
605 lua.lua_rawset(L, lua.LUA_REGISTRYINDEX) #
606 finally:
607 lua.lua_settop(L, old_top)
608 unlock_runtime(self)
609
610 @cython.final
611 cdef int register_py_object(self, bytes cname, bytes pyname, object obj) except -1:
612 """Register Python object 'obj' in the registry with cname and
613 in the library on top of the stack with pyname
614 Preconditions:
615 runtime must be locked
616 """
617 cdef lua_State *L = self._state
618 old_top = lua.lua_gettop(L)
619 try:
620 check_lua_stack(L, 4) # tbl
621 lua.lua_pushlstring(L, cname, len(cname)) # tbl cname
622 py_to_lua_custom(self, L, obj, 0) # tbl cname obj
623 lua.lua_pushlstring(L, pyname, len(pyname)) # tbl cname obj pyname
624 lua.lua_pushvalue(L, -2) # tbl cname obj pyname obj
625 lua.lua_rawset(L, -5) # tbl cname obj
626 lua.lua_rawset(L, lua.LUA_REGISTRYINDEX) # tbl
627 return 0
628 finally:
629 lua.lua_settop(L, old_top)
630
631 @cython.final
632 cdef int init_python_lib(self, bint register_eval, bint register_builtins) except -1:
633 cdef lua_State *L = self._state
634
635 # create 'python' lib
636 luaL_openlib(L, "python", py_lib, 0) # lib
637 lua.lua_pushlightuserdata(L, <void*>self) # lib udata
638 lua.lua_pushcclosure(L, py_args, 1) # lib function
639 lua.lua_setfield(L, -2, "args") # lib
640
641 # register our own object metatable
642 lua.luaL_newmetatable(L, POBJECT) # lib metatbl
643 luaL_openlib(L, NULL, py_object_lib, 0)
644 lua.lua_pop(L, 1) # lib
645
646 # create and store the python references table
647 lua.lua_newtable(L) # lib tbl
648 lua.lua_createtable(L, 0, 1) # lib tbl metatbl
649 lua.lua_pushlstring(L, "v", 1) # lib tbl metatbl "v"
650 lua.lua_setfield(L, -2, "__mode") # lib tbl metatbl
651 lua.lua_setmetatable(L, -2) # lib tbl
652 lua.lua_setfield(L, lua.LUA_REGISTRYINDEX, PYREFST) # lib
653
654 # register global names in the module
655 self.register_py_object(b'Py_None', b'none', None)
656 if register_eval:
657 self.register_py_object(b'eval', b'eval', eval)
658 if register_builtins:
659 self.register_py_object(b'builtins', b'builtins', builtins)
660
661 # pop 'python' lib
662 lua.lua_pop(L, 1)
663
664 return 0 # nothing left to return on the stack
665
666
667 @cython.internal
668 cdef class _LuaNoGC:
669 """
670 A context manager that temporarily disables the Lua garbage collector.
671 """
672 cdef LuaRuntime _runtime
673
674 def __cinit__(self, LuaRuntime runtime not None):
675 self._runtime = runtime
676
677 def __enter__(self):
678 if self._runtime is None:
679 return # e.g. system teardown
680 assert self._runtime._state is not NULL
681 cdef lua_State *L = self._runtime._state
682 lock_runtime(self._runtime)
683 # Pass third argument for compatibility with Lua 5.[123].
684 lua.lua_gc(L, lua.LUA_GCSTOP, <int> 0)
685 unlock_runtime(self._runtime)
686
687 def __exit__(self, *exc):
688 if self._runtime is None:
689 return # e.g. system teardown
690 assert self._runtime._state is not NULL
691 cdef lua_State *L = self._runtime._state
692 lock_runtime(self._runtime)
693 # Pass third argument for compatibility with Lua 5.[123].
694 lua.lua_gc(L, lua.LUA_GCRESTART, <int> 0)
695 unlock_runtime(self._runtime)
696
697
698 ################################################################################
699 # decorators for calling Python functions with keyword (named) arguments
700 # from Lua scripts
701
702 def unpacks_lua_table(func):
703 """
704 A decorator to make the decorated function receive kwargs
705 when it is called from Lua with a single Lua table argument.
706
707 Python functions wrapped in this decorator can be called from Lua code
708 as ``func(foo, bar)``, ``func{foo=foo, bar=bar}`` and ``func{foo, bar=bar}``.
709
710 See also: http://lua-users.org/wiki/NamedParameters
711
712 WARNING: avoid using this decorator for functions where the
713 first argument can be a Lua table.
714
715 WARNING: be careful with ``nil`` values. Depending on the context,
716 passing ``nil`` as a parameter can mean either "omit a parameter"
717 or "pass None". This even depends on the Lua version. It is
718 possible to use ``python.none`` instead of ``nil`` to pass None values
719 robustly.
720 """
721 @wraps(func)
722 def wrapper(*args):
723 args, kwargs = _fix_args_kwargs(args)
724 return func(*args, **kwargs)
725 return wrapper
726
727
728 def unpacks_lua_table_method(meth):
729 """
730 This is :func:`unpacks_lua_table` for methods
731 (i.e. it knows about the 'self' argument).
732 """
733 @wraps(meth)
734 def wrapper(self, *args):
735 args, kwargs = _fix_args_kwargs(args)
736 return meth(self, *args, **kwargs)
737 return wrapper
738
739
740 cdef int check_lua_stack(lua_State* L, int extra) except -1:
741 """Wrapper around lua_checkstack.
742 On failure, a MemoryError is raised.
743 """
744 assert extra >= 0
745 if not lua.lua_checkstack(L, extra):
746 raise LuaMemoryError
747 return 0
748
749
750 cdef int get_object_length_from_lua(lua_State* L) noexcept nogil:
751 cdef size_t length = lua.lua_objlen(L, lua.lua_upvalueindex(1))
752 lua.lua_pushlightuserdata(L, <void*>length)
753 return 1
754
755
756 cdef Py_ssize_t get_object_length(LuaRuntime runtime, lua_State* L, int index) except -1:
757 """Obtains the length of the object at the given valid index.
758 Preconditions:
759 runtime must be locked
760 index must be valid
761 Exceptions:
762 LuaError if Lua raises an error
763 OverflowError if length doesn't fit in a Py_ssize_t
764 """
765 cdef int result
766 cdef size_t length
767 check_lua_stack(L, 1)
768 lua.lua_pushvalue(L, index) # value
769 lua.lua_pushcclosure(L, get_object_length_from_lua, 1) # closure
770 result = lua.lua_pcall(L, 0, 1, 0)
771 if result: # err
772 raise_lua_error(runtime, L, result) #
773 length = <size_t>lua.lua_touserdata(L, -1) # length
774 lua.lua_pop(L, 1) #
775 if length > <size_t> PY_SSIZE_T_MAX:
776 raise OverflowError(f"Size too large to represent: {length}")
777 return <Py_ssize_t>length
778
779
780 cdef tuple unpack_lua_table(LuaRuntime runtime, lua_State* L):
781 """Unpacks the table at the top of the stack into a tuple of positional arguments
782 and a dictionary of keyword arguments.
783 Preconditions:
784 runtime must be locked
785 """
786 assert runtime is not None
787 cdef tuple args
788 cdef dict kwargs = {}
789 cdef bytes source_encoding = runtime._source_encoding
790 cdef int old_top
791 cdef Py_ssize_t index, length
792 check_lua_stack(L, 2)
793 old_top = lua.lua_gettop(L)
794 try:
795 length = get_object_length(runtime, L, -1)
796 args = cpython.tuple.PyTuple_New(length)
797 lua.lua_pushnil(L) # nil (first key)
798 while lua.lua_next(L, -2): # key value
799 key = py_from_lua(runtime, L, -2)
800 value = py_from_lua(runtime, L, -1)
801 if isinstance(key, int) and not isinstance(key, bool):
802 index = <Py_ssize_t>key
803 if index < 1 or index > length:
804 raise IndexError("table index out of range")
805 cpython.ref.Py_INCREF(value)
806 cpython.tuple.PyTuple_SET_ITEM(args, index-1, value)
807 elif isinstance(key, bytes):
808 kwargs[(<bytes>key).decode(source_encoding)] = value
809 elif isinstance(key, unicode):
810 kwargs[key] = value
811 else:
812 raise TypeError("table key is neither an integer nor a string")
813 lua.lua_pop(L, 1) # key
814 finally:
815 lua.lua_settop(L, old_top)
816 return args, kwargs
817
818
819 cdef tuple _fix_args_kwargs(tuple args):
820 """
821 Extract named arguments from args passed to a Python function by Lua
822 script. Arguments are processed only if a single argument is passed and
823 it is a table.
824 """
825 if len(args) != 1:
826 return args, {}
827
828 arg = args[0]
829 if not isinstance(arg, _LuaTable):
830 return args, {}
831
832 cdef _LuaTable table = <_LuaTable>arg
833 assert table._runtime is not None
834 assert table._runtime._state is not NULL
835 cdef LuaRuntime runtime = table._runtime
836 cdef lua_State* L = table._state
837 lock_runtime(runtime)
838 old_top = lua.lua_gettop(L)
839 try:
840 check_lua_stack(L, 1)
841 table.push_lua_object(L)
842 return unpack_lua_table(runtime, L)
843 finally:
844 lua.lua_settop(L, old_top)
845 unlock_runtime(runtime)
846
847
848 ################################################################################
849 # fast, re-entrant runtime locking
850
851 cdef inline bint lock_runtime(LuaRuntime runtime, bint blocking=True) noexcept with gil:
852 return lock_lock(runtime._lock, pythread.PyThread_get_thread_ident(), blocking=blocking)
853
854 cdef inline void unlock_runtime(LuaRuntime runtime) noexcept nogil:
855 unlock_lock(runtime._lock)
856
857
858 ################################################################################
859 # Lua object wrappers
860
861 @cython.internal
862 @cython.no_gc_clear
863 @cython.freelist(16)
864 cdef class _LuaObject:
865 """A wrapper around a Lua object such as a table or function.
866 """
867 cdef LuaRuntime _runtime
868 cdef lua_State* _state
869 cdef int _ref
870
871 def __cinit__(self):
872 self._ref = lua.LUA_NOREF
873
874 def __init__(self):
875 raise TypeError("Type cannot be instantiated manually")
876
877 def __dealloc__(self):
878 if self._runtime is None:
879 return
880 runtime = self._runtime
881 self._runtime = None
882 ref = self._ref
883 if ref == lua.LUA_NOREF:
884 return
885 self._ref = lua.LUA_NOREF
886 cdef lua_State* L = self._state
887 if L is not NULL:
888 locked = lock_runtime(runtime, blocking=False)
889 if locked:
890 lua.luaL_unref(L, lua.LUA_REGISTRYINDEX, ref)
891 runtime.clean_up_pending_unrefs() # just in case
892 unlock_runtime(runtime)
893 return
894 runtime.add_pending_unref(ref)
895
896 @cython.final
897 cdef inline int push_lua_object(self, lua_State* L) except -1:
898 """Pushes Lua object onto the stack
899 Preconditions:
900 1 extra slot in the Lua stack
901 LuaRuntime is locked
902 Postconditions:
903 Lua object (not nil) is pushed onto of the stack
904 """
905 if self._ref == lua.LUA_NOREF:
906 raise LuaError("lost reference")
907 lua.lua_rawgeti(L, lua.LUA_REGISTRYINDEX, self._ref)
908 if lua.lua_isnil(L, -1):
909 lua.lua_pop(L, 1)
910 raise LuaError("lost reference")
911 return 1
912
913 def __call__(self, *args):
914 assert self._runtime is not None
915 cdef lua_State* L = self._state
916 if not lock_runtime(self._runtime):
917 raise RuntimeError("failed to acquire thread lock")
918 try:
919 lua.lua_settop(L, 0)
920 self.push_lua_object(L)
921 return call_lua(self._runtime, L, args)
922 finally:
923 lua.lua_settop(L, 0)
924 unlock_runtime(self._runtime)
925
926 def __len__(self):
927 return self._len()
928
929 @cython.final
930 cdef Py_ssize_t _len(self) except -1:
931 assert self._runtime is not None
932 cdef lua_State* L = self._state
933 lock_runtime(self._runtime)
934 old_top = lua.lua_gettop(L)
935 try:
936 check_lua_stack(L, 1)
937 self.push_lua_object(L)
938 return get_object_length(self._runtime, L, -1)
939 finally:
940 lua.lua_settop(L, old_top)
941 unlock_runtime(self._runtime)
942
943 def __nonzero__(self):
944 return True
945
946 def __iter__(self):
947 # if not provided, iteration will try item access and call into Lua
948 raise TypeError("iteration is only supported for tables")
949
950 def __repr__(self):
951 assert self._runtime is not None
952 cdef lua_State* L = self._state
953 cdef bytes encoding = self._runtime._encoding or b'UTF-8'
954 lock_runtime(self._runtime)
955 old_top = lua.lua_gettop(L)
956 try:
957 check_lua_stack(L, 1)
958 self.push_lua_object(L)
959 return lua_object_repr(L, encoding)
960 finally:
961 lua.lua_settop(L, old_top)
962 unlock_runtime(self._runtime)
963
964 def __str__(self):
965 assert self._runtime is not None
966 cdef lua_State* L = self._state
967 cdef const char *string
968 cdef size_t size = 0
969 cdef bytes encoding = self._runtime._encoding or b'UTF-8'
970 lock_runtime(self._runtime)
971 old_top = lua.lua_gettop(L)
972 try:
973 check_lua_stack(L, 2)
974 self.push_lua_object(L) # obj
975 if lua.luaL_getmetafield(L, -1, "__tostring"): # obj tostr
976 lua.lua_insert(L, -2) # tostr obj
977 status = lua.lua_pcall(L, 1, 1, 0)
978 if status == 0: # str
979 string = lua.lua_tolstring(L, -1, &size)
980 if string is NULL:
981 raise TypeError("__tostring returned non-string object")
982 try:
983 return string[:size].decode(encoding)
984 except UnicodeDecodeError:
985 return string[:size].decode('ISO-8859-1')
986 else:
987 raise_lua_error(self._runtime, L, status)
988 else:
989 return lua_object_repr(L, encoding)
990 finally:
991 lua.lua_settop(L, old_top)
992 unlock_runtime(self._runtime)
993
994 def __getattr__(self, name):
995 assert self._runtime is not None
996 if isinstance(name, unicode):
997 if (<unicode>name).startswith(u'__') and (<unicode>name).endswith(u'__'):
998 return object.__getattr__(self, name)
999 name = (<unicode>name).encode(self._runtime._source_encoding)
1000 elif isinstance(name, bytes):
1001 if (<bytes>name).startswith(b'__') and (<bytes>name).endswith(b'__'):
1002 return object.__getattr__(self, name)
1003 return self._getitem(name, is_attr_access=True)
1004
1005 def __getitem__(self, index_or_name):
1006 return self._getitem(index_or_name, is_attr_access=False)
1007
1008 @cython.final
1009 cdef _getitem(self, name, bint is_attr_access):
1010 assert self._runtime is not None
1011 cdef lua_State* L = self._state
1012 lock_runtime(self._runtime)
1013 old_top = lua.lua_gettop(L)
1014 try:
1015 check_lua_stack(L, 3)
1016 lua.lua_pushcfunction(L, get_from_lua_table) # func
1017 self.push_lua_object(L) # func obj
1018 lua_type = lua.lua_type(L, -1)
1019 if lua_type == lua.LUA_TFUNCTION or lua_type == lua.LUA_TTHREAD:
1020 raise (AttributeError if is_attr_access else TypeError)(
1021 "item/attribute access not supported on functions")
1022 # table[nil] fails, so map None -> python.none for Lua tables
1023 py_to_lua(self._runtime, L, name, wrap_none=(lua_type == lua.LUA_TTABLE)) # func obj key
1024 return execute_lua_call(self._runtime, L, 2) # obj[key]
1025 finally:
1026 lua.lua_settop(L, old_top) #
1027 unlock_runtime(self._runtime)
1028
1029
1030 cdef _LuaObject new_lua_object(LuaRuntime runtime, lua_State* L, int n):
1031 cdef _LuaObject obj = _LuaObject.__new__(_LuaObject)
1032 init_lua_object(obj, runtime, L, n)
1033 return obj
1034
1035 cdef void init_lua_object(_LuaObject obj, LuaRuntime runtime, lua_State* L, int n) noexcept:
1036 obj._runtime = runtime
1037 obj._state = L
1038 lua.lua_pushvalue(L, n)
1039 obj._ref = lua.luaL_ref(L, lua.LUA_REGISTRYINDEX)
1040
1041 cdef object lua_object_repr(lua_State* L, bytes encoding):
1042 cdef bytes py_bytes
1043 lua_type = lua.lua_type(L, -1)
1044 if lua_type in (lua.LUA_TTABLE, lua.LUA_TFUNCTION):
1045 ptr = <void*>lua.lua_topointer(L, -1)
1046 elif lua_type in (lua.LUA_TUSERDATA, lua.LUA_TLIGHTUSERDATA):
1047 ptr = <void*>lua.lua_touserdata(L, -1)
1048 elif lua_type == lua.LUA_TTHREAD:
1049 ptr = <void*>lua.lua_tothread(L, -1)
1050 else:
1051 ptr = NULL
1052 if ptr:
1053 py_bytes = PyBytes_FromFormat(
1054 "<Lua %s at %p>", lua.lua_typename(L, lua_type), ptr)
1055 else:
1056 py_bytes = PyBytes_FromFormat(
1057 "<Lua %s>", lua.lua_typename(L, lua_type))
1058 try:
1059 return py_bytes.decode(encoding)
1060 except UnicodeDecodeError:
1061 # safe 'decode'
1062 return py_bytes.decode('ISO-8859-1')
1063
1064
1065 @cython.final
1066 @cython.internal
1067 @cython.no_gc_clear
1068 cdef class _LuaTable(_LuaObject):
1069 def __iter__(self):
1070 return _LuaIter(self, KEYS)
1071
1072 def keys(self):
1073 """Returns an iterator over the keys of a table that this
1074 object represents. Same as iter(obj).
1075 """
1076 return _LuaIter(self, KEYS)
1077
1078 def values(self):
1079 """Returns an iterator over the values of a table that this
1080 object represents.
1081 """
1082 return _LuaIter(self, VALUES)
1083
1084 def items(self):
1085 """Returns an iterator over the key-value pairs of a table
1086 that this object represents.
1087 """
1088 return _LuaIter(self, ITEMS)
1089
1090 def __setattr__(self, name, value):
1091 assert self._runtime is not None
1092 if isinstance(name, unicode):
1093 if (<unicode>name).startswith(u'__') and (<unicode>name).endswith(u'__'):
1094 object.__setattr__(self, name, value)
1095 return
1096 name = (<unicode>name).encode(self._runtime._source_encoding)
1097 elif isinstance(name, bytes) and (<bytes>name).startswith(b'__') and (<bytes>name).endswith(b'__'):
1098 object.__setattr__(self, name, value)
1099 return
1100 self._setitem(name, value)
1101
1102 def __setitem__(self, index_or_name, value):
1103 self._setitem(index_or_name, value)
1104
1105 @cython.final
1106 cdef int _setitem(self, name, value) except -1:
1107 assert self._runtime is not None
1108 cdef lua_State* L = self._state
1109 lock_runtime(self._runtime)
1110 old_top = lua.lua_gettop(L)
1111 try:
1112 check_lua_stack(L, 3)
1113 self.push_lua_object(L)
1114 # table[nil] fails, so map None -> python.none for Lua tables
1115 py_to_lua(self._runtime, L, name, wrap_none=True)
1116 py_to_lua(self._runtime, L, value)
1117 lua.lua_settable(L, -3)
1118 finally:
1119 lua.lua_settop(L, old_top)
1120 unlock_runtime(self._runtime)
1121 return 0
1122
1123 def __delattr__(self, item):
1124 assert self._runtime is not None
1125 if isinstance(item, unicode):
1126 if (<unicode>item).startswith(u'__') and (<unicode>item).endswith(u'__'):
1127 object.__delattr__(self, item)
1128 return
1129 item = (<unicode>item).encode(self._runtime._source_encoding)
1130 elif isinstance(item, bytes) and (<bytes>item).startswith(b'__') and (<bytes>item).endswith(b'__'):
1131 object.__delattr__(self, item)
1132 return
1133 self._delitem(item)
1134
1135 def __delitem__(self, key):
1136 self._delitem(key)
1137
1138 @cython.final
1139 cdef _delitem(self, name):
1140 assert self._runtime is not None
1141 cdef lua_State* L = self._state
1142 lock_runtime(self._runtime)
1143 old_top = lua.lua_gettop(L)
1144 try:
1145 check_lua_stack(L, 3)
1146 self.push_lua_object(L)
1147 py_to_lua(self._runtime, L, name, wrap_none=True)
1148 lua.lua_pushnil(L)
1149 lua.lua_settable(L, -3)
1150 finally:
1151 lua.lua_settop(L, old_top)
1152 unlock_runtime(self._runtime)
1153
1154
1155 cdef _LuaTable new_lua_table(LuaRuntime runtime, lua_State* L, int n):
1156 cdef _LuaTable obj = _LuaTable.__new__(_LuaTable)
1157 init_lua_object(obj, runtime, L, n)
1158 return obj
1159
1160
1161 @cython.internal
1162 @cython.no_gc_clear
1163 cdef class _LuaFunction(_LuaObject):
1164 """A Lua function (which may become a coroutine).
1165 """
1166 def coroutine(self, *args):
1167 """Create a Lua coroutine from a Lua function and call it with
1168 the passed parameters to start it up.
1169 """
1170 assert self._runtime is not None
1171 cdef lua_State* L = self._state
1172 cdef lua_State* co
1173 cdef _LuaThread thread
1174 lock_runtime(self._runtime)
1175 old_top = lua.lua_gettop(L)
1176 try:
1177 check_lua_stack(L, 3)
1178 self.push_lua_object(L)
1179 if not lua.lua_isfunction(L, -1) or lua.lua_iscfunction(L, -1):
1180 raise TypeError("Lua object is not a function")
1181 # create thread stack and push the function on it
1182 co = lua.lua_newthread(L)
1183 lua.lua_pushvalue(L, 1)
1184 lua.lua_xmove(L, co, 1)
1185 # create the coroutine object and initialise it
1186 assert lua.lua_isthread(L, -1)
1187 thread = new_lua_thread(self._runtime, L, -1)
1188 thread._arguments = args # always a tuple, not None !
1189 return thread
1190 finally:
1191 lua.lua_settop(L, old_top)
1192 unlock_runtime(self._runtime)
1193
1194 cdef _LuaFunction new_lua_function(LuaRuntime runtime, lua_State* L, int n):
1195 cdef _LuaFunction obj = _LuaFunction.__new__(_LuaFunction)
1196 init_lua_object(obj, runtime, L, n)
1197 return obj
1198
1199
1200 @cython.final
1201 @cython.internal
1202 @cython.no_gc_clear
1203 cdef class _LuaCoroutineFunction(_LuaFunction):
1204 """A function that returns a new coroutine when called.
1205 """
1206 def __call__(self, *args):
1207 return self.coroutine(*args)
1208
1209 cdef _LuaCoroutineFunction new_lua_coroutine_function(LuaRuntime runtime, lua_State* L, int n):
1210 cdef _LuaCoroutineFunction obj = _LuaCoroutineFunction.__new__(_LuaCoroutineFunction)
1211 init_lua_object(obj, runtime, L, n)
1212 return obj
1213
1214
1215 @cython.final
1216 @cython.internal
1217 @cython.no_gc_clear # FIXME: get rid if this
1218 cdef class _LuaThread(_LuaObject):
1219 """A Lua thread (coroutine).
1220 """
1221 cdef lua_State* _co_state
1222 cdef tuple _arguments
1223 def __iter__(self):
1224 return self
1225
1226 def __next__(self):
1227 assert self._runtime is not None
1228 cdef tuple args = self._arguments
1229 if args is not None:
1230 self._arguments = None
1231 return resume_lua_thread(self, args)
1232
1233 def send(self, value):
1234 """Send a value into the coroutine. If the value is a tuple,
1235 send the unpacked elements.
1236 """
1237 if value is not None:
1238 if self._arguments is not None:
1239 raise TypeError("can't send non-None value to a just-started generator")
1240 if not isinstance(value, tuple):
1241 value = (value,)
1242 elif self._arguments is not None:
1243 value = self._arguments
1244 self._arguments = None
1245 return resume_lua_thread(self, <tuple>value)
1246
1247 def __bool__(self):
1248 cdef lua.lua_Debug dummy
1249 assert self._runtime is not None
1250 cdef int status = lua.lua_status(self._co_state)
1251 if status == lua.LUA_YIELD:
1252 return True
1253 if status == 0:
1254 # copied from Lua code: check for frames
1255 if lua.lua_getstack(self._co_state, 0, &dummy) > 0:
1256 return True # currently running
1257 elif lua.lua_gettop(self._co_state) > 0:
1258 return True # not started yet
1259 return False
1260
1261 cdef _LuaThread new_lua_thread(LuaRuntime runtime, lua_State* L, int n):
1262 cdef _LuaThread obj = _LuaThread.__new__(_LuaThread)
1263 init_lua_object(obj, runtime, L, n)
1264 obj._co_state = lua.lua_tothread(L, n)
1265 return obj
1266
1267
1268 cdef _LuaObject new_lua_thread_or_function(LuaRuntime runtime, lua_State* L, int n):
1269 # this is special - we replace a new (unstarted) thread by its
1270 # underlying function to better follow Python's own generator
1271 # protocol
1272 cdef lua_State* co = lua.lua_tothread(L, n)
1273 assert co is not NULL
1274 if lua.lua_status(co) == 0 and lua.lua_gettop(co) == 1:
1275 # not started yet => get the function and return that
1276 lua.lua_pushvalue(co, 1)
1277 lua.lua_xmove(co, L, 1)
1278 try:
1279 return new_lua_coroutine_function(runtime, L, -1)
1280 finally:
1281 lua.lua_pop(L, 1)
1282 else:
1283 # already started => wrap the thread
1284 return new_lua_thread(runtime, L, n)
1285
1286
1287 cdef object resume_lua_thread(_LuaThread thread, tuple args):
1288 cdef lua_State* co = thread._co_state
1289 cdef lua_State* L = thread._state
1290 cdef int status, i, nargs = 0, nres = 0
1291 assert thread._runtime is not None
1292 lock_runtime(thread._runtime)
1293 old_top = lua.lua_gettop(L)
1294 try:
1295 check_lua_stack(L, 1)
1296 if lua.lua_status(co) == 0 and lua.lua_gettop(co) == 0:
1297 # already terminated
1298 raise StopIteration
1299 if args:
1300 nargs = _len_as_int(len(args))
1301 push_lua_arguments(thread._runtime, co, args)
1302 with nogil:
1303 status = lua.lua_resume(co, L, nargs, &nres)
1304 if status != lua.LUA_YIELD:
1305 if status == 0:
1306 # terminated
1307 if nres == 0:
1308 # no values left to return
1309 raise StopIteration
1310 else:
1311 raise_lua_error(thread._runtime, co, status)
1312
1313 # Move yielded values to the main state before unpacking.
1314 # This is what Lua's internal auxresume function is doing;
1315 # it affects wrapped Lua functions returned to Python.
1316 lua.lua_xmove(co, L, nres)
1317 return unpack_lua_results(thread._runtime, L)
1318 finally:
1319 # FIXME: check that coroutine state is OK in case of errors?
1320 lua.lua_settop(L, old_top)
1321 unlock_runtime(thread._runtime)
1322
1323
1324 cdef enum:
1325 KEYS = 1
1326 VALUES = 2
1327 ITEMS = 3
1328
1329
1330 @cython.final
1331 @cython.internal
1332 @cython.no_gc_clear
1333 cdef class _LuaIter:
1334 cdef LuaRuntime _runtime
1335 cdef _LuaObject _obj
1336 cdef lua_State* _state
1337 cdef int _refiter
1338 cdef char _what
1339
1340 def __cinit__(self, _LuaObject obj not None, int what):
1341 self._state = NULL
1342 assert obj._runtime is not None
1343 self._runtime = obj._runtime
1344 self._obj = obj
1345 self._state = obj._state
1346 self._refiter = lua.LUA_REFNIL
1347 self._what = what
1348
1349 def __dealloc__(self):
1350 if self._runtime is None:
1351 return
1352 runtime = self._runtime
1353 self._runtime = None
1354 ref = self._refiter
1355 if ref == lua.LUA_NOREF:
1356 return
1357 self._refiter = lua.LUA_NOREF
1358 cdef lua_State* L = self._state
1359 if L is not NULL:
1360 locked = lock_runtime(runtime, blocking=False)
1361 if locked:
1362 lua.luaL_unref(L, lua.LUA_REGISTRYINDEX, ref)
1363 runtime.clean_up_pending_unrefs() # just in case
1364 unlock_runtime(runtime)
1365 return
1366 runtime.add_pending_unref(ref)
1367
1368 def __repr__(self):
1369 return u"LuaIter(%r)" % (self._obj)
1370
1371 def __iter__(self):
1372 return self
1373
1374 def __next__(self):
1375 if self._obj is None:
1376 raise StopIteration
1377 cdef lua_State* L = self._obj._state
1378 assert self._runtime is not None
1379 lock_runtime(self._runtime)
1380 old_top = lua.lua_gettop(L)
1381 try:
1382 check_lua_stack(L, 3)
1383 if self._obj is None:
1384 raise StopIteration
1385 # iterable object
1386 self._obj.push_lua_object(L)
1387 if not lua.lua_istable(L, -1):
1388 raise TypeError("cannot iterate over non-table (found %r)" % self._obj)
1389 if self._refiter == lua.LUA_NOREF:
1390 # no key
1391 raise StopIteration
1392 elif self._refiter == lua.LUA_REFNIL:
1393 # initial key
1394 lua.lua_pushnil(L)
1395 else:
1396 # last key
1397 lua.lua_rawgeti(L, lua.LUA_REGISTRYINDEX, self._refiter)
1398 if lua.lua_next(L, -2):
1399 try:
1400 if self._what == KEYS:
1401 retval = py_from_lua(self._runtime, L, -2)
1402 elif self._what == VALUES:
1403 retval = py_from_lua(self._runtime, L, -1)
1404 else: # ITEMS
1405 retval = (py_from_lua(self._runtime, L, -2), py_from_lua(self._runtime, L, -1))
1406 finally:
1407 # pop value
1408 lua.lua_pop(L, 1)
1409 # pop and store key
1410 if self._refiter == lua.LUA_REFNIL:
1411 self._refiter = lua.luaL_ref(L, lua.LUA_REGISTRYINDEX)
1412 else:
1413 lua.lua_rawseti(L, lua.LUA_REGISTRYINDEX, self._refiter)
1414 return retval
1415 # iteration done, clean up
1416 if self._refiter != lua.LUA_REFNIL:
1417 lua.luaL_unref(L, lua.LUA_REGISTRYINDEX, self._refiter)
1418 self._refiter = lua.LUA_NOREF
1419 self._obj = None
1420 finally:
1421 lua.lua_settop(L, old_top)
1422 unlock_runtime(self._runtime)
1423 raise StopIteration
1424
1425 # type conversions and protocol adaptations
1426
1427 cdef int py_asfunc_call(lua_State *L) noexcept nogil:
1428 if (lua.lua_gettop(L) == 1 and lua.lua_islightuserdata(L, 1)
1429 and lua.lua_topointer(L, 1) == <void*>unpack_wrapped_pyfunction):
1430 # special case: unpack_python_argument_or_jump() calls this to find out the Python object
1431 lua.lua_pushvalue(L, lua.lua_upvalueindex(1))
1432 return 1
1433 lua.lua_pushvalue(L, lua.lua_upvalueindex(1))
1434 lua.lua_insert(L, 1)
1435 return py_object_call(L)
1436
1437 cdef py_object* unpack_wrapped_pyfunction(lua_State* L, int n) noexcept nogil:
1438 cdef lua.lua_CFunction cfunction = lua.lua_tocfunction(L, n)
1439 if cfunction is <lua.lua_CFunction>py_asfunc_call:
1440 lua.lua_pushvalue(L, n)
1441 lua.lua_pushlightuserdata(L, <void*>unpack_wrapped_pyfunction)
1442 if lua.lua_pcall(L, 1, 1, 0) == 0:
1443 return unpack_userdata(L, -1)
1444 return NULL
1445
1446
1447 @cython.final
1448 @cython.internal
1449 @cython.freelist(8)
1450 cdef class _PyProtocolWrapper:
1451 cdef object _obj
1452 cdef int _type_flags
1453 def __cinit__(self):
1454 self._type_flags = 0
1455 def __init__(self):
1456 raise TypeError("Type cannot be instantiated from Python")
1457
1458
1459 def as_attrgetter(obj):
1460 cdef _PyProtocolWrapper wrap = _PyProtocolWrapper.__new__(_PyProtocolWrapper)
1461 wrap._obj = obj
1462 wrap._type_flags = 0
1463 return wrap
1464
1465 def as_itemgetter(obj):
1466 cdef _PyProtocolWrapper wrap = _PyProtocolWrapper.__new__(_PyProtocolWrapper)
1467 wrap._obj = obj
1468 wrap._type_flags = OBJ_AS_INDEX
1469 return wrap
1470
1471 cdef object py_from_lua(LuaRuntime runtime, lua_State *L, int n):
1472 """Convert a Lua object to a Python object by either mapping, wrapping or unwrapping it.
1473 Preconditions:
1474 Index n is valid
1475 """
1476 cdef size_t size = 0
1477 cdef const char *s
1478 cdef lua.lua_Number number
1479 cdef lua.lua_Integer integer
1480 cdef py_object* py_obj
1481 cdef int lua_type = lua.lua_type(L, n)
1482
1483 if lua_type == lua.LUA_TNIL:
1484 return None
1485 elif lua_type == lua.LUA_TNUMBER:
1486 if lua.LUA_VERSION_NUM >= 503:
1487 if lua.lua_isinteger(L, n):
1488 return lua.lua_tointeger(L, n)
1489 else:
1490 return lua.lua_tonumber(L, n)
1491 else:
1492 number = lua.lua_tonumber(L, n)
1493 integer = <lua.lua_Integer>number
1494 if number == integer:
1495 return integer
1496 else:
1497 return number
1498 elif lua_type == lua.LUA_TSTRING:
1499 s = lua.lua_tolstring(L, n, &size)
1500 if runtime._encoding is not None:
1501 return s[:size].decode(runtime._encoding)
1502 else:
1503 return s[:size]
1504 elif lua_type == lua.LUA_TBOOLEAN:
1505 return lua.lua_toboolean(L, n)
1506 elif lua_type == lua.LUA_TUSERDATA:
1507 py_obj = unpack_userdata(L, n)
1508 if py_obj:
1509 if not py_obj.obj:
1510 raise ReferenceError("deleted python object")
1511 return <object>py_obj.obj
1512 elif lua_type == lua.LUA_TTABLE:
1513 return new_lua_table(runtime, L, n)
1514 elif lua_type == lua.LUA_TTHREAD:
1515 return new_lua_thread_or_function(runtime, L, n)
1516 elif lua_type == lua.LUA_TFUNCTION:
1517 py_obj = unpack_wrapped_pyfunction(L, n)
1518 if py_obj:
1519 if not py_obj.obj:
1520 raise ReferenceError("deleted python object")
1521 return <object>py_obj.obj
1522 return new_lua_function(runtime, L, n)
1523 return new_lua_object(runtime, L, n)
1524
1525 cdef py_object* unpack_userdata(lua_State *L, int n) noexcept nogil:
1526 """
1527 Like luaL_checkudata(), unpacks a userdata object and validates that
1528 it's a wrapped Python object. Returns NULL on failure.
1529 """
1530 if not lua.lua_checkstack(L, 2):
1531 return NULL
1532 p = lua.lua_touserdata(L, n)
1533 if p and lua.lua_getmetatable(L, n):
1534 # found userdata with metatable - the one we expect?
1535 lua.luaL_getmetatable(L, POBJECT)
1536 if lua.lua_rawequal(L, -1, -2):
1537 lua.lua_pop(L, 2)
1538 return <py_object*>p
1539 lua.lua_pop(L, 2)
1540 return NULL
1541
1542 cdef int py_function_result_to_lua(LuaRuntime runtime, lua_State *L, object o) except -1:
1543 if runtime._unpack_returned_tuples and isinstance(o, tuple):
1544 push_lua_arguments(runtime, L, <tuple>o)
1545 return _len_as_int(len(<tuple>o))
1546 check_lua_stack(L, 1)
1547 return py_to_lua(runtime, L, o)
1548
1549 cdef int py_to_lua_handle_overflow(LuaRuntime runtime, lua_State *L, object o) except -1:
1550 """Converts Python object to Lua via overflow handler
1551 Preconditions:
1552 Lua runtime is locked
1553 Postconditions:
1554 Returns 0 if cannot convert Python object to Lua (handler not registered or failed)
1555 Returns 1 if the Python object was converted successfully and pushed onto the stack
1556 """
1557 check_lua_stack(L, 2)
1558 old_top = lua.lua_gettop(L)
1559 try:
1560 lua.lua_pushlstring(L, LUPAOFH, len(LUPAOFH))
1561 lua.lua_rawget(L, lua.LUA_REGISTRYINDEX)
1562 if lua.lua_isnil(L, -1):
1563 lua.lua_pop(L, 1)
1564 return 0
1565 py_to_lua_custom(runtime, L, o, 0)
1566 if lua.lua_pcall(L, 1, 1, 0):
1567 lua.lua_pop(L, 1)
1568 return 0
1569 return 1
1570 except:
1571 lua.lua_settop(L, old_top)
1572 raise
1573
1574 cdef int py_to_lua(LuaRuntime runtime, lua_State *L, object o, bint wrap_none=False, bint recursive=False, dict mapped_tables=None) except -1:
1575 """Converts Python object to Lua
1576 Preconditions:
1577 1 extra slot in the Lua stack
1578 runtime is locked
1579 Postconditions:
1580 Returns 0 if cannot convert Python object to Lua
1581 Returns 1 if the Python object was converted successfully and pushed onto the stack
1582 """
1583 cdef int pushed_values_count = 0
1584 cdef int type_flags = 0
1585
1586 if o is None:
1587 if wrap_none:
1588 lua.lua_pushlstring(L, "Py_None", 7)
1589 lua.lua_rawget(L, lua.LUA_REGISTRYINDEX)
1590 if lua.lua_isnil(L, -1):
1591 lua.lua_pop(L, 1)
1592 return 0
1593 pushed_values_count = 1
1594 else:
1595 # Not really needed, but this way we may check for errors
1596 # with pushed_values_count == 0.
1597 lua.lua_pushnil(L)
1598 pushed_values_count = 1
1599 elif o is True or o is False:
1600 lua.lua_pushboolean(L, <bint>o)
1601 pushed_values_count = 1
1602 elif type(o) is float:
1603 lua.lua_pushnumber(L, <lua.lua_Number>cpython.float.PyFloat_AS_DOUBLE(o))
1604 pushed_values_count = 1
1605 elif isinstance(o, int):
1606 try:
1607 lua.lua_pushinteger(L, <lua.lua_Integer>o)
1608 pushed_values_count = 1
1609 except OverflowError:
1610 pushed_values_count = py_to_lua_handle_overflow(runtime, L, o)
1611 if pushed_values_count <= 0:
1612 raise
1613 elif isinstance(o, bytes):
1614 lua.lua_pushlstring(L, <char*>(<bytes>o), len(<bytes>o))
1615 pushed_values_count = 1
1616 elif isinstance(o, unicode) and runtime._encoding is not None:
1617 pushed_values_count = push_encoded_unicode_string(runtime, L, <unicode>o)
1618 elif isinstance(o, _LuaObject):
1619 if (<_LuaObject>o)._runtime is not runtime:
1620 raise LuaError("cannot mix objects from different Lua runtimes")
1621 (<_LuaObject>o).push_lua_object(L)
1622 pushed_values_count = 1
1623 elif isinstance(o, float):
1624 lua.lua_pushnumber(L, <lua.lua_Number><double>o)
1625 pushed_values_count = 1
1626 elif isinstance(o, _PyProtocolWrapper):
1627 type_flags = (<_PyProtocolWrapper> o)._type_flags
1628 o = (<_PyProtocolWrapper> o)._obj
1629 pushed_values_count = py_to_lua_custom(runtime, L, o, type_flags)
1630 elif recursive and isinstance(o, (list, dict, Sequence, Mapping)):
1631 if mapped_tables is None:
1632 mapped_tables = {}
1633 table = py_to_lua_table(runtime, L, (o,), recursive=recursive, mapped_tables=mapped_tables)
1634 (<_LuaObject> table).push_lua_object(L)
1635 pushed_values_count = 1
1636 else:
1637 # prefer __getitem__ over __getattr__ by default
1638 type_flags = OBJ_AS_INDEX if hasattr(o, '__getitem__') else 0
1639 pushed_values_count = py_to_lua_custom(runtime, L, o, type_flags)
1640 return pushed_values_count
1641
1642
1643 cdef int push_encoded_unicode_string(LuaRuntime runtime, lua_State *L, unicode ustring) except -1:
1644 cdef bytes bytes_string = ustring.encode(runtime._encoding)
1645 lua.lua_pushlstring(L, <char*>bytes_string, len(bytes_string))
1646 return 1
1647
1648
1649 cdef inline tuple build_pyref_key(PyObject* o, int type_flags):
1650 return (<object><uintptr_t>o, <object>type_flags)
1651
1652
1653 cdef bint py_to_lua_custom(LuaRuntime runtime, lua_State *L, object o, int type_flags) except -1:
1654 """Wrap Python object into a Lua userdatum with certain type flags
1655 Preconditions:
1656 LuaRuntime is locked
1657 Postconditions:
1658 Pushes wrapped Python object and returns 1
1659 """
1660 cdef py_object* py_obj
1661 refkey = build_pyref_key(<PyObject*>o, type_flags)
1662 cdef _PyReference pyref
1663 check_lua_stack(L, 3)
1664 old_top = lua.lua_gettop(L)
1665 try:
1666 # check if Python object is already referenced in Lua
1667 lua.lua_getfield(L, lua.LUA_REGISTRYINDEX, PYREFST) # tbl
1668 if refkey in runtime._pyrefs_in_lua:
1669 pyref = <_PyReference>runtime._pyrefs_in_lua[refkey]
1670 lua.lua_rawgeti(L, -1, pyref._ref) # tbl udata
1671 py_obj = <py_object*>lua.lua_touserdata(L, -1)
1672 if py_obj:
1673 lua.lua_remove(L, -2) # udata
1674 return 1 # values pushed
1675 lua.lua_pop(L, 1) # tbl
1676
1677 # create new wrapper for Python object
1678 py_obj = <py_object*>lua.lua_newuserdata(L, sizeof(py_object))
1679 py_obj.obj = <PyObject*>o # tbl udata
1680 py_obj.runtime = <PyObject*>runtime
1681 py_obj.type_flags = type_flags
1682 lua.luaL_getmetatable(L, POBJECT) # tbl udata metatbl
1683 lua.lua_setmetatable(L, -2) # tbl udata
1684 lua.lua_pushvalue(L, -1) # tbl udata udata
1685 pyref = _PyReference.__new__(_PyReference)
1686 pyref._ref = lua.luaL_ref(L, -3) # tbl udata
1687 pyref._obj = o
1688 lua.lua_remove(L, -2) # udata
1689
1690 # originally, we just used:
1691 #cpython.ref.Py_INCREF(o)
1692 # now, we store an owned reference in "runtime._pyrefs_in_lua" to keep it visible to Python
1693 # and a borrowed reference in "py_obj.obj" for access from Lua
1694 runtime._pyrefs_in_lua[refkey] = pyref
1695 except:
1696 lua.lua_settop(L, old_top)
1697 raise
1698
1699 return 1 # values pushed
1700
1701
1702 cdef _LuaTable py_to_lua_table(LuaRuntime runtime, lua_State* L, tuple items, bint recursive=False, dict mapped_tables=None):
1703 """
1704 Create a new Lua table and add different kinds of values from the sequence 'items' to it.
1705
1706 Dicts, Mappings and Lua tables are unpacked into key-value pairs.
1707 Everything else is considered a sequence of plain values that get appended to the table.
1708 """
1709 cdef int i = 1
1710 check_lua_stack(L, 5)
1711 old_top = lua.lua_gettop(L)
1712 lua.lua_newtable(L)
1713 # FIXME: handle allocation errors
1714 cdef int lua_table_ref = lua.lua_gettop(L) # the index of the lua table which we are filling
1715 if recursive and mapped_tables is None:
1716 mapped_tables = {}
1717 try:
1718 for obj in items:
1719 if recursive:
1720 if id(obj) not in mapped_tables:
1721 # this object is never seen before, we should cache it
1722 mapped_tables[id(obj)] = lua_table_ref
1723 else:
1724 # this object has been cached, just get the corresponding lua table's index
1725 idx = mapped_tables[id(obj)]
1726 return new_lua_table(runtime, L, <int>idx)
1727 if isinstance(obj, dict):
1728 for key, value in (<dict>obj).items():
1729 py_to_lua(runtime, L, key, wrap_none=True, recursive=recursive, mapped_tables=mapped_tables)
1730 py_to_lua(runtime, L, value, wrap_none=False, recursive=recursive, mapped_tables=mapped_tables)
1731 lua.lua_rawset(L, -3)
1732
1733 elif isinstance(obj, _LuaTable):
1734 # Stack: # tbl
1735 (<_LuaObject> obj).push_lua_object(L) # tbl, obj
1736 lua.lua_pushnil(L) # tbl, obj, nil // iterate over obj (-2)
1737 while lua.lua_next(L, -2): # tbl, obj, k, v
1738 lua.lua_pushvalue(L, -2) # tbl, obj, k, v, k // copy key (because
1739 lua.lua_insert(L, -2) # tbl, obj, k, k, v // lua_next needs a key for iteration)
1740 lua.lua_settable(L, -5) # tbl, obj, k // tbl[k] = v
1741 lua.lua_pop(L, 1) # tbl // remove obj from stack
1742
1743 elif isinstance(obj, Mapping):
1744 for key in obj:
1745 value = obj[key]
1746 py_to_lua(runtime, L, key, wrap_none=True, recursive=recursive, mapped_tables=mapped_tables)
1747 py_to_lua(runtime, L, value, wrap_none=False, recursive=recursive, mapped_tables=mapped_tables)
1748 lua.lua_rawset(L, -3)
1749
1750 else:
1751 for arg in obj:
1752 py_to_lua(runtime, L, arg, wrap_none=False, recursive=recursive, mapped_tables=mapped_tables)
1753 lua.lua_rawseti(L, -2, i)
1754 i += 1
1755
1756 return new_lua_table(runtime, L, -1)
1757 finally:
1758 lua.lua_settop(L, old_top)
1759
1760
1761 cdef inline int _isascii(unsigned char* s) noexcept:
1762 cdef unsigned char c = 0
1763 while s[0]:
1764 c |= s[0]
1765 s += 1
1766 return c & 0x80 == 0
1767
1768
1769 cdef bytes _asciiOrNone(s):
1770 if s is None:
1771 return s
1772 elif isinstance(s, unicode):
1773 return (<unicode>s).encode('ascii')
1774 elif isinstance(s, bytearray):
1775 s = bytes(s)
1776 elif not isinstance(s, bytes):
1777 raise ValueError("expected string, got %s" % type(s))
1778 if not _isascii(<bytes>s):
1779 raise ValueError("byte string input has unknown encoding, only ASCII is allowed")
1780 return <bytes>s
1781
1782
1783 # error handling
1784
1785 cdef int raise_lua_error(LuaRuntime runtime, lua_State* L, int result) except -1:
1786 if result == 0:
1787 return 0
1788 elif result == lua.LUA_ERRMEM:
1789 raise LuaMemoryError()
1790 else:
1791 error_message = build_lua_error_message(runtime, L)
1792 if u"not enough memory" in error_message:
1793 raise LuaMemoryError(error_message)
1794 raise LuaError(error_message)
1795
1796
1797 cdef bint _looks_like_traceback_line(unicode line) except -1:
1798 # Lua tracebacks look like this (using tabs as indentation):
1799 # stack traceback:
1800 # [C]: in function 'error'
1801 # [string "<python>"]:1: in main chunk
1802 cdef Py_UCS4 ch
1803 cdef bint indentation_seen = False
1804 for ch in line:
1805 if ch.isspace():
1806 indentation_seen = True
1807 else:
1808 return indentation_seen and ch == u"["
1809 return False
1810
1811
1812 cdef unicode _reorder_lua_stack_trace(unicode error_message):
1813 # Lua tracebacks look like this (using tabs as indentation):
1814 # stack traceback:
1815 # [C]: in function 'error'
1816 # [string "<python>"]:1: in main chunk
1817 cdef Py_ssize_t i, traceback_start = 0
1818 lines = []
1819 for i, line in enumerate(error_message.splitlines(), 1):
1820 if traceback_start > 0 and _looks_like_traceback_line(line):
1821 lines.insert(traceback_start, line)
1822 else:
1823 traceback_start = i if line == u"stack traceback:" else 0
1824 lines.append(line)
1825
1826 if traceback_start > 0 and len(lines) > traceback_start + 1:
1827 error_message = u"\n".join(lines)
1828 return error_message
1829
1830
1831 cdef build_lua_error_message(LuaRuntime runtime, lua_State* L, int stack_index=-1):
1832 """Removes the string at the given stack index ``n`` to build an error message.
1833 """
1834 cdef size_t size = 0
1835 cdef const char *s = lua.lua_tolstring(L, stack_index, &size)
1836 if runtime._encoding is not None:
1837 try:
1838 py_ustring = s[:size].decode(runtime._encoding)
1839 except UnicodeDecodeError:
1840 py_ustring = s[:size].decode('ISO-8859-1') # safe 'fake' decoding
1841 else:
1842 py_ustring = s[:size].decode('ISO-8859-1')
1843 lua.lua_remove(L, stack_index)
1844
1845 if u"stack traceback:" in py_ustring:
1846 py_ustring = _reorder_lua_stack_trace(py_ustring)
1847
1848 return py_ustring
1849
1850
1851 # calling into Lua
1852
1853 cdef run_lua(LuaRuntime runtime, bytes lua_code, bytes name, bytes mode, tuple args):
1854 """Run Lua code with arguments"""
1855 cdef lua_State* L = runtime._state
1856 cdef const char* c_name = b'<python>'
1857 cdef const char* c_mode = NULL
1858 if name is not None:
1859 c_name = name
1860 if mode is not None:
1861 c_mode = mode
1862
1863 lock_runtime(runtime)
1864 old_top = lua.lua_gettop(L)
1865 try:
1866 check_lua_stack(L, 1)
1867 if lua.luaL_loadbufferx(L, lua_code, len(lua_code), c_name, c_mode):
1868 error = build_lua_error_message(runtime, L)
1869 if error.startswith("not enough memory"):
1870 raise LuaMemoryError(error)
1871 raise LuaSyntaxError(u"error loading code: " + error)
1872 return call_lua(runtime, L, args)
1873 finally:
1874 lua.lua_settop(L, old_top)
1875 unlock_runtime(runtime)
1876
1877 cdef call_lua(LuaRuntime runtime, lua_State *L, tuple args):
1878 """Call function on top of the stack with args
1879 Preconditions:
1880 Function is on top of the stack
1881 LuaRuntime must be locked
1882 Postconditions:
1883 Pops function from the stack and pushes results
1884 """
1885 push_lua_arguments(runtime, L, args)
1886 return execute_lua_call(runtime, L, len(args))
1887
1888 cdef object execute_lua_call(LuaRuntime runtime, lua_State *L, Py_ssize_t nargs):
1889 cdef int result_status
1890 cdef object result
1891 # call into Lua
1892 cdef bint has_lua_traceback_func = False
1893 with nogil:
1894 lua.lua_getglobal(L, "debug")
1895 if not lua.lua_istable(L, -1):
1896 lua.lua_pop(L, 1)
1897 else:
1898 lua.lua_getfield(L, -1, "traceback")
1899 if not lua.lua_isfunction(L, -1):
1900 lua.lua_pop(L, 2)
1901 else:
1902 lua.lua_replace(L, -2)
1903 lua.lua_insert(L, 1)
1904 has_lua_traceback_func = True
1905 result_status = lua.lua_pcall(L, <int>nargs, lua.LUA_MULTRET, has_lua_traceback_func)
1906 if has_lua_traceback_func:
1907 lua.lua_remove(L, 1)
1908 runtime.clean_up_pending_unrefs()
1909 results = unpack_lua_results(runtime, L)
1910 if result_status:
1911 if isinstance(results, BaseException):
1912 runtime.reraise_on_exception()
1913 raise_lua_error(runtime, L, result_status)
1914 return results
1915
1916 cdef int push_lua_arguments(LuaRuntime runtime, lua_State *L,
1917 tuple args, bint first_may_be_nil=True) except -1:
1918 """Push Python objects in tuple into Lua stack
1919 Preconditions:
1920 LuaRuntime is locked
1921 Postconditions:
1922 Pushes each value of the Python tuple into the Lua stack
1923 Returns number of pushed values
1924 """
1925 cdef int i, n
1926 cdef Py_ssize_t nargs
1927 cdef bint wrap_none = not first_may_be_nil
1928 if args:
1929 nargs = len(args)
1930 if nargs > INT_MAX:
1931 raise OverflowError("tuple too large to unpack")
1932 n = <int>nargs
1933 check_lua_stack(L, n)
1934 old_top = lua.lua_gettop(L)
1935 try:
1936 for i, arg in enumerate(args):
1937 if not py_to_lua(runtime, L, arg, wrap_none=wrap_none):
1938 raise TypeError("failed to convert argument at index %d" % i)
1939 wrap_none = False
1940 return n
1941 except:
1942 lua.lua_settop(L, old_top)
1943 raise
1944 else:
1945 return 0
1946
1947 cdef inline object unpack_lua_results(LuaRuntime runtime, lua_State *L):
1948 cdef int nargs = lua.lua_gettop(L)
1949 if nargs == 1:
1950 return py_from_lua(runtime, L, 1)
1951 if nargs == 0:
1952 return None
1953 return unpack_multiple_lua_results(runtime, L, nargs)
1954
1955 cdef tuple unpack_multiple_lua_results(LuaRuntime runtime, lua_State *L, int nargs):
1956 cdef tuple args = cpython.tuple.PyTuple_New(nargs)
1957 cdef int i
1958 for i in range(nargs):
1959 arg = py_from_lua(runtime, L, i+1)
1960 cpython.ref.Py_INCREF(arg)
1961 cpython.tuple.PyTuple_SET_ITEM(args, i, arg)
1962 return args
1963
1964
1965 # bounded memory allocation
1966
1967 cdef void* _lua_alloc_restricted(void* ud, void* ptr, size_t old_size, size_t new_size) noexcept nogil:
1968 # adapted from https://stackoverflow.com/a/9672205
1969 # print(<size_t>ud, <size_t>ptr, old_size, new_size)
1970 cdef MemoryStatus* memory_status = <MemoryStatus*>ud
1971 # print(" ", memory_status.used, memory_status.base_usage, memory_status.limit)
1972
1973 if ptr is NULL:
1974 # <http://www.lua.org/manual/5.2/manual.html#lua_Alloc>:
1975 # When ptr is NULL, old_size encodes the kind of object that Lua is allocating.
1976 # Since we don’t care about that, just mark it as 0.
1977 old_size = 0
1978
1979 cdef void* new_ptr
1980 if new_size == 0:
1981 free(ptr)
1982 memory_status.used -= old_size # add deallocated old size to available memory
1983 return NULL
1984 elif new_size == old_size:
1985 return ptr
1986
1987 if memory_status.limit > 0 and new_size > old_size and memory_status.limit <= memory_status.used + new_size - old_size: # reached the limit
1988 # print("REACHED LIMIT")
1989 return NULL
1990 # print(" realloc()...")
1991 new_ptr = realloc(ptr, new_size)
1992 # print(" ", memory_status.used, new_size - old_size, memory_status.used + new_size - old_size)
1993 if new_ptr is not NULL:
1994 memory_status.used += new_size - old_size
1995 return new_ptr
1996
1997 cdef int _lua_panic(lua_State *L) noexcept nogil:
1998 cdef const char* msg = lua.lua_tostring(L, -1)
1999 if msg == NULL:
2000 msg = "error object is not a string"
2001 cdef char* message = "PANIC: unprotected error in call to Lua API (%s)\n"
2002 fprintf(stderr, message, msg)
2003 fflush(stderr)
2004 return 0 # return to Lua to abort
2005
2006
2007 ################################################################################
2008 # Python support in Lua
2009
2010 ## The rules:
2011 ##
2012 ## Each of the following blocks of functions represents the view on a
2013 ## specific Python feature from Lua code. As they are called from
2014 ## Lua, the entry points are 'nogil' functions that do not hold the
2015 ## GIL. They do the basic error checking and argument unpacking and
2016 ## then hand over to a 'with gil' function that acquires the GIL on
2017 ## entry and holds it during its lifetime. This function does the
2018 ## actual mapping of the Python feature or object to Lua.
2019 ##
2020 ## Lua's C level error handling is different from that of Python. It
2021 ## uses long jumps instead of returning from an error function. The
2022 ## places where this can happen are marked with a comment. Note that
2023 ## this only never happen inside of a 'nogil' function, as a long jump
2024 ## out of a function that handles Python objects would kill their
2025 ## reference counting.
2026
2027
2028 # ref-counting support for Python objects
2029
2030 @cython.final
2031 @cython.internal
2032 @cython.freelist(8)
2033 cdef class _PyReference:
2034 cdef object _obj
2035 cdef int _ref
2036
2037
2038 cdef int py_object_gc_with_gil(py_object *py_obj, lua_State* L) noexcept with gil:
2039 cdef _PyReference pyref
2040 # originally, we just used:
2041 #cpython.ref.Py_XDECREF(py_obj.obj)
2042 # now, we keep Python object references in Lua visible to Python in a dict
2043 runtime = <LuaRuntime>py_obj.runtime
2044 try:
2045 refkey = build_pyref_key(py_obj.obj, py_obj.type_flags)
2046 pyref = <_PyReference>runtime._pyrefs_in_lua.pop(refkey)
2047 except (TypeError, KeyError):
2048 return 0 # runtime was already cleared during GC, nothing left to do
2049 except:
2050 try: runtime.store_raised_exception(L, b'error while cleaning up a Python object')
2051 finally: return -1
2052 else:
2053 lua.lua_getfield(L, lua.LUA_REGISTRYINDEX, PYREFST) # tbl
2054 lua.luaL_unref(L, -1, pyref._ref) # tbl
2055 return 0
2056 finally:
2057 py_obj.obj = NULL
2058
2059 cdef int py_object_gc(lua_State* L) noexcept nogil:
2060 if not lua.lua_isuserdata(L, 1):
2061 return 0
2062 py_obj = unpack_userdata(L, 1)
2063 if py_obj is not NULL and py_obj.obj is not NULL:
2064 if py_object_gc_with_gil(py_obj, L):
2065 return lua.lua_error(L) # never returns!
2066 return 0
2067
2068 # calling Python objects
2069
2070 cdef bint call_python(LuaRuntime runtime, lua_State *L, py_object* py_obj) except -1:
2071 # Callers must assure that py_obj.obj is not NULL, i.e. it points to a valid Python object.
2072 cdef int i, nargs = lua.lua_gettop(L) - 1
2073 cdef tuple args
2074 cdef dict kwargs
2075
2076 f = <object>py_obj.obj
2077
2078 if nargs == 0:
2079 lua.lua_settop(L, 0) # FIXME
2080 result = f()
2081 else:
2082 args = ()
2083 kwargs = {}
2084
2085 for i in range(nargs):
2086 arg = py_from_lua(runtime, L, i+2)
2087 if isinstance(arg, _PyArguments):
2088 args += (<_PyArguments>arg).args
2089 kwargs = dict(**kwargs, **(<_PyArguments>arg).kwargs)
2090 else:
2091 args += (arg, )
2092
2093 if args and PyMethod_Check(f) and (<PyObject*>args[0]) is PyMethod_GET_SELF(f):
2094 # Calling a bound method and self is already the first argument.
2095 # Lua x:m(a, b) => Python as x.m(x, a, b) but should be x.m(a, b)
2096 #
2097 # Lua syntax is sensitive to method calls vs function lookups, while
2098 # Python's syntax is not. In a way, we are leaking Python semantics
2099 # into Lua by duplicating the first argument from method calls.
2100 #
2101 # The method wrapper would only prepend self to the tuple again,
2102 # so we just call the underlying function directly instead.
2103 f = <object>PyMethod_GET_FUNCTION(f)
2104
2105 lua.lua_settop(L, 0) # FIXME
2106 result = f(*args, **kwargs)
2107
2108 runtime.clean_up_pending_unrefs()
2109 return py_function_result_to_lua(runtime, L, result)
2110
2111 cdef int py_call_with_gil(lua_State* L, py_object *py_obj) noexcept with gil:
2112 cdef LuaRuntime runtime = None
2113 cdef lua_State* stored_state = NULL
2114
2115 try:
2116 runtime = <LuaRuntime?>py_obj.runtime
2117 if runtime._state is not L:
2118 stored_state = runtime._state
2119 runtime._state = L
2120 return call_python(runtime, L, py_obj)
2121 except:
2122 try: runtime.store_raised_exception(L, b'error during Python call')
2123 finally: return -1
2124 finally:
2125 if stored_state is not NULL:
2126 runtime._state = stored_state
2127
2128 cdef int py_object_call(lua_State* L) noexcept nogil:
2129 cdef py_object* py_obj = unpack_python_argument_or_jump(L, 1) # may not return on error!
2130 result = py_call_with_gil(L, py_obj)
2131 if result < 0:
2132 return lua.lua_error(L) # never returns!
2133 return result
2134
2135 # str() support for Python objects
2136
2137 cdef int py_str_with_gil(lua_State* L, py_object* py_obj) noexcept with gil:
2138 cdef LuaRuntime runtime
2139 try:
2140 runtime = <LuaRuntime?>py_obj.runtime
2141 s = str(<object>py_obj.obj)
2142 if isinstance(s, unicode):
2143 if runtime._encoding is None:
2144 s = (<unicode>s).encode('UTF-8')
2145 else:
2146 s = (<unicode>s).encode(runtime._encoding)
2147 else:
2148 assert isinstance(s, bytes)
2149 lua.lua_pushlstring(L, <bytes>s, len(<bytes>s))
2150 return 1 # returning 1 value
2151 except:
2152 try: runtime.store_raised_exception(L, b'error during Python str() call')
2153 finally: return -1
2154
2155 cdef int py_object_str(lua_State* L) noexcept nogil:
2156 cdef py_object* py_obj = unpack_python_argument_or_jump(L, 1) # may not return on error!
2157 result = py_str_with_gil(L, py_obj)
2158 if result < 0:
2159 return lua.lua_error(L) # never returns!
2160 return result
2161
2162 # item access for Python objects
2163 #
2164 # Behavior is:
2165 #
2166 # If setting attribute_handlers flag has been set in LuaRuntime object
2167 # use those handlers.
2168 #
2169 # Else if wrapped by python.as_attrgetter() or python.as_itemgetter()
2170 # from the Lua side, user getitem or getattr respsectively.
2171 #
2172 # Else If object has __getitem__, use that
2173 #
2174 # Else use getattr()
2175 #
2176 # Note that when getattr() is used, attribute_filter from LuaRuntime
2177 # may mediate access. attribute_filter does not come into play when
2178 # using the getitem method of access.
2179
2180 cdef int getitem_for_lua(LuaRuntime runtime, lua_State* L, py_object* py_obj, int key_n) except -1:
2181 return py_to_lua(runtime, L,
2182 (<object>py_obj.obj)[ py_from_lua(runtime, L, key_n) ])
2183
2184 cdef int setitem_for_lua(LuaRuntime runtime, lua_State* L, py_object* py_obj, int key_n, int value_n) except -1:
2185 (<object>py_obj.obj)[ py_from_lua(runtime, L, key_n) ] = py_from_lua(runtime, L, value_n)
2186 return 0
2187
2188 cdef int getattr_for_lua(LuaRuntime runtime, lua_State* L, py_object* py_obj, int key_n) except -1:
2189 obj = <object>py_obj.obj
2190 attr_name = py_from_lua(runtime, L, key_n)
2191 if runtime._attribute_getter is not None:
2192 value = runtime._attribute_getter(obj, attr_name)
2193 return py_to_lua(runtime, L, value)
2194 if runtime._attribute_filter is not None:
2195 attr_name = runtime._attribute_filter(obj, attr_name, False)
2196 if isinstance(attr_name, bytes):
2197 attr_name = (<bytes>attr_name).decode(runtime._source_encoding)
2198 return py_to_lua(runtime, L, getattr(obj, attr_name))
2199
2200 cdef int setattr_for_lua(LuaRuntime runtime, lua_State* L, py_object* py_obj, int key_n, int value_n) except -1:
2201 obj = <object>py_obj.obj
2202 attr_name = py_from_lua(runtime, L, key_n)
2203 attr_value = py_from_lua(runtime, L, value_n)
2204 if runtime._attribute_setter is not None:
2205 runtime._attribute_setter(obj, attr_name, attr_value)
2206 else:
2207 if runtime._attribute_filter is not None:
2208 attr_name = runtime._attribute_filter(obj, attr_name, True)
2209 if isinstance(attr_name, bytes):
2210 attr_name = (<bytes>attr_name).decode(runtime._source_encoding)
2211 setattr(obj, attr_name, attr_value)
2212 return 0
2213
2214
2215 cdef int py_object_getindex_with_gil(lua_State* L, py_object* py_obj) noexcept with gil:
2216 cdef LuaRuntime runtime
2217 try:
2218 runtime = <LuaRuntime?>py_obj.runtime
2219 if (py_obj.type_flags & OBJ_AS_INDEX) and not runtime._attribute_getter:
2220 return getitem_for_lua(runtime, L, py_obj, 2)
2221 else:
2222 return getattr_for_lua(runtime, L, py_obj, 2)
2223 except:
2224 try: runtime.store_raised_exception(L, b'error reading Python attribute/item')
2225 finally: return -1
2226
2227 cdef int py_object_getindex(lua_State* L) noexcept nogil:
2228 cdef py_object* py_obj = unpack_python_argument_or_jump(L, 1) # may not return on error!
2229 result = py_object_getindex_with_gil(L, py_obj)
2230 if result < 0:
2231 return lua.lua_error(L) # never returns!
2232 return result
2233
2234
2235 cdef int py_object_setindex_with_gil(lua_State* L, py_object* py_obj) noexcept with gil:
2236 cdef LuaRuntime runtime
2237 try:
2238 runtime = <LuaRuntime?>py_obj.runtime
2239 if (py_obj.type_flags & OBJ_AS_INDEX) and not runtime._attribute_setter:
2240 return setitem_for_lua(runtime, L, py_obj, 2, 3)
2241 else:
2242 return setattr_for_lua(runtime, L, py_obj, 2, 3)
2243 except:
2244 try: runtime.store_raised_exception(L, b'error writing Python attribute/item')
2245 finally: return -1
2246
2247 cdef int py_object_setindex(lua_State* L) noexcept nogil:
2248 cdef py_object* py_obj = unpack_python_argument_or_jump(L, 1) # may not return on error!
2249 result = py_object_setindex_with_gil(L, py_obj)
2250 if result < 0:
2251 return lua.lua_error(L) # never returns!
2252 return result
2253
2254 # special methods for Lua wrapped Python objects
2255
2256 cdef lua.luaL_Reg *py_object_lib = [
2257 lua.luaL_Reg(name = "__call", func = <lua.lua_CFunction> py_object_call),
2258 lua.luaL_Reg(name = "__index", func = <lua.lua_CFunction> py_object_getindex),
2259 lua.luaL_Reg(name = "__newindex", func = <lua.lua_CFunction> py_object_setindex),
2260 lua.luaL_Reg(name = "__tostring", func = <lua.lua_CFunction> py_object_str),
2261 lua.luaL_Reg(name = "__gc", func = <lua.lua_CFunction> py_object_gc),
2262 lua.luaL_Reg(name = NULL, func = NULL),
2263 ]
2264
2265 ## # Python helper functions for Lua
2266
2267 cdef inline py_object* unpack_single_python_argument_or_jump(lua_State* L) noexcept nogil:
2268 if lua.lua_gettop(L) > 1:
2269 lua.luaL_argerror(L, 2, "invalid arguments") # never returns!
2270 return unpack_python_argument_or_jump(L, 1)
2271
2272 cdef inline py_object* unpack_python_argument_or_jump(lua_State* L, int n) noexcept nogil:
2273 cdef py_object* py_obj
2274
2275 if lua.lua_isuserdata(L, n):
2276 py_obj = unpack_userdata(L, n)
2277 else:
2278 py_obj = unpack_wrapped_pyfunction(L, n)
2279
2280 if not py_obj:
2281 lua.luaL_argerror(L, n, "not a python object") # never returns!
2282 if not py_obj.obj:
2283 lua.luaL_argerror(L, n, "deleted python object") # never returns!
2284
2285 return py_obj
2286
2287 cdef int py_wrap_object_protocol_with_gil(lua_State* L, py_object* py_obj, int type_flags) noexcept with gil:
2288 cdef LuaRuntime runtime
2289 try:
2290 runtime = <LuaRuntime?>py_obj.runtime
2291 return py_to_lua_custom(runtime, L, <object>py_obj.obj, type_flags)
2292 except:
2293 try: runtime.store_raised_exception(L, b'error during type adaptation')
2294 finally: return -1
2295
2296 cdef int py_wrap_object_protocol(lua_State* L, int type_flags) noexcept nogil:
2297 cdef py_object* py_obj = unpack_single_python_argument_or_jump(L) # never returns on error!
2298 result = py_wrap_object_protocol_with_gil(L, py_obj, type_flags)
2299 if result < 0:
2300 return lua.lua_error(L) # never returns!
2301 return result
2302
2303 cdef int py_as_attrgetter(lua_State* L) noexcept nogil:
2304 return py_wrap_object_protocol(L, 0)
2305
2306 cdef int py_as_itemgetter(lua_State* L) noexcept nogil:
2307 return py_wrap_object_protocol(L, OBJ_AS_INDEX)
2308
2309 cdef int py_as_function(lua_State* L) noexcept nogil:
2310 cdef py_object* py_obj = unpack_single_python_argument_or_jump(L) # never returns on error!
2311 lua.lua_pushcclosure(L, <lua.lua_CFunction>py_asfunc_call, 1)
2312 return 1
2313
2314 # iteration support for Python objects in Lua
2315
2316 cdef int py_iter(lua_State* L) noexcept nogil:
2317 cdef py_object* py_obj = unpack_single_python_argument_or_jump(L) # never returns on error!
2318 result = py_iter_with_gil(L, py_obj, 0)
2319 if result < 0:
2320 return lua.lua_error(L) # never returns!
2321 return result
2322
2323 cdef int py_iterex(lua_State* L) noexcept nogil:
2324 cdef py_object* py_obj = unpack_single_python_argument_or_jump(L) # never returns on error!
2325 result = py_iter_with_gil(L, py_obj, OBJ_UNPACK_TUPLE)
2326 if result < 0:
2327 return lua.lua_error(L) # never returns!
2328 return result
2329
2330 cdef int convert_to_lua_Integer(lua_State* L, int idx, lua.lua_Integer* integer) noexcept nogil:
2331 cdef int isnum
2332 cdef lua.lua_Integer temp
2333 temp = lua.lua_tointegerx(L, idx, &isnum)
2334 if isnum:
2335 integer[0] = temp
2336 return 0
2337 else:
2338 lua.lua_pushfstring(L, "Could not convert %s to string", lua.luaL_typename(L, idx))
2339 return -1
2340
2341 cdef int py_enumerate(lua_State* L) noexcept nogil:
2342 if lua.lua_gettop(L) > 2:
2343 lua.luaL_argerror(L, 3, "invalid arguments") # never returns!
2344 cdef py_object* py_obj = unpack_python_argument_or_jump(L, 1)
2345 cdef lua.lua_Integer start
2346 if lua.lua_gettop(L) == 2:
2347 if convert_to_lua_Integer(L, -1, &start) < 0:
2348 return lua.lua_error(L) # never returns
2349 else:
2350 start = 0
2351 result = py_enumerate_with_gil(L, py_obj, start)
2352 if result < 0:
2353 return lua.lua_error(L) # never returns!
2354 return result
2355
2356
2357 cdef int py_enumerate_with_gil(lua_State* L, py_object* py_obj, lua.lua_Integer start) noexcept with gil:
2358 cdef LuaRuntime runtime
2359 try:
2360 runtime = <LuaRuntime?>py_obj.runtime
2361 obj = iter(<object>py_obj.obj)
2362 return py_push_iterator(runtime, L, obj, OBJ_ENUMERATOR, start - 1)
2363 except:
2364 try: runtime.store_raised_exception(L, b'error creating an iterator with enumerate()')
2365 finally: return -1
2366
2367 cdef int py_iter_with_gil(lua_State* L, py_object* py_obj, int type_flags) noexcept with gil:
2368 cdef LuaRuntime runtime
2369 try:
2370 runtime = <LuaRuntime?>py_obj.runtime
2371 obj = iter(<object>py_obj.obj)
2372 return py_push_iterator(runtime, L, obj, type_flags, 0)
2373 except:
2374 try: runtime.store_raised_exception(L, b'error creating an iterator')
2375 finally: return -1
2376
2377 cdef int py_push_iterator(LuaRuntime runtime, lua_State* L, iterator, int type_flags,
2378 lua.lua_Integer initial_value) except -2:
2379 """Pushes iterator function, invariant state variable and control variable
2380 Preconditions:
2381 3 extra slots in the Lua stack
2382 LuaRuntime is locked
2383 Postconditions:
2384 Pushes py_iter_next, iterator and the control variable
2385 Returns the number of pushed values
2386 """
2387 # push the iterator function
2388 lua.lua_pushcfunction(L, <lua.lua_CFunction>py_iter_next)
2389 # push the wrapped iterator object as for-loop state object
2390 if runtime._unpack_returned_tuples:
2391 type_flags |= OBJ_UNPACK_TUPLE
2392 py_to_lua_custom(runtime, L, iterator, type_flags)
2393 # push either enumerator index or nil as control variable value
2394 if type_flags & OBJ_ENUMERATOR:
2395 lua.lua_pushinteger(L, initial_value)
2396 else:
2397 lua.lua_pushnil(L)
2398 return 3
2399
2400 cdef int py_iter_next(lua_State* L) noexcept nogil:
2401 # first value in the C closure: the Python iterator object
2402 cdef py_object* py_obj = unpack_python_argument_or_jump(L, 1) # may not return on error!
2403 result = py_iter_next_with_gil(L, py_obj)
2404 if result < 0:
2405 return lua.lua_error(L) # never returns!
2406 return result
2407
2408 cdef int py_iter_next_with_gil(lua_State* L, py_object* py_iter) noexcept with gil:
2409 cdef LuaRuntime runtime
2410 try:
2411 runtime = <LuaRuntime?>py_iter.runtime
2412 try:
2413 obj = next(<object>py_iter.obj)
2414 except StopIteration:
2415 lua.lua_pushnil(L)
2416 return 1
2417
2418 # NOTE: cannot return nil for None as first item
2419 # as Lua interprets it as end of the iterator
2420 allow_nil = False
2421 if py_iter.type_flags & OBJ_ENUMERATOR:
2422 lua.lua_pushinteger(L, lua.lua_tointeger(L, -1) + 1)
2423 allow_nil = True
2424 if (py_iter.type_flags & OBJ_UNPACK_TUPLE) and isinstance(obj, tuple):
2425 # special case: when the iterable returns a tuple, unpack it
2426 push_lua_arguments(runtime, L, <tuple>obj, first_may_be_nil=allow_nil)
2427 result = len(<tuple>obj)
2428 else:
2429 result = py_to_lua(runtime, L, obj, wrap_none=not allow_nil)
2430 if result < 1:
2431 return -1
2432 if py_iter.type_flags & OBJ_ENUMERATOR:
2433 result += 1
2434 return result
2435 except:
2436 try: runtime.store_raised_exception(L, b'error while calling next(iterator)')
2437 finally: return -1
2438
2439 # support for calling Python objects in Lua with Python-like arguments
2440
2441 cdef class _PyArguments:
2442 cdef tuple args
2443 cdef dict kwargs
2444
2445 cdef int py_args_with_gil(PyObject* runtime_obj, lua_State* L) noexcept with gil:
2446 cdef _PyArguments pyargs
2447 cdef LuaRuntime runtime
2448 try:
2449 runtime = <LuaRuntime?>runtime_obj
2450 pyargs = _PyArguments.__new__(_PyArguments)
2451 pyargs.args, pyargs.kwargs = unpack_lua_table(runtime, L)
2452 return py_to_lua_custom(runtime, L, pyargs, 0)
2453 except:
2454 try: runtime.store_raised_exception(L, b'error while calling python.args()')
2455 finally: return -1
2456
2457 cdef int py_args(lua_State* L) noexcept nogil:
2458 cdef PyObject* runtime
2459 runtime = <PyObject*>lua.lua_touserdata(L, lua.lua_upvalueindex(1))
2460 if not runtime:
2461 return lua.luaL_error(L, "missing runtime")
2462 lua.luaL_checktype(L, 1, lua.LUA_TTABLE)
2463 result = py_args_with_gil(runtime, L)
2464 if result < 0:
2465 return lua.lua_error(L) # never returns!
2466 return result
2467
2468 # overflow handler setter
2469
2470 cdef int py_set_overflow_handler(lua_State* L) noexcept nogil:
2471 if (not lua.lua_isnil(L, 1)
2472 and not lua.lua_isfunction(L, 1)
2473 and not unpack_python_argument_or_jump(L, 1)):
2474 return lua.luaL_argerror(L, 1, "expected nil, a Lua function or a callable Python object")
2475 # hdl [...]
2476 lua.lua_settop(L, 1) # hdl
2477 lua.lua_setfield(L, lua.LUA_REGISTRYINDEX, LUPAOFH) #
2478 return 0
2479
2480 # 'python' module functions in Lua
2481
2482 cdef lua.luaL_Reg *py_lib = [
2483 lua.luaL_Reg(name = "as_attrgetter", func = <lua.lua_CFunction> py_as_attrgetter),
2484 lua.luaL_Reg(name = "as_itemgetter", func = <lua.lua_CFunction> py_as_itemgetter),
2485 lua.luaL_Reg(name = "as_function", func = <lua.lua_CFunction> py_as_function),
2486 lua.luaL_Reg(name = "iter", func = <lua.lua_CFunction> py_iter),
2487 lua.luaL_Reg(name = "iterex", func = <lua.lua_CFunction> py_iterex),
2488 lua.luaL_Reg(name = "enumerate", func = <lua.lua_CFunction> py_enumerate),
2489 lua.luaL_Reg(name = "set_overflow_handler", func = <lua.lua_CFunction> py_set_overflow_handler),
2490 lua.luaL_Reg(name = NULL, func = NULL),
2491 ]
2492
2493 # Setup helpers for library tables (removed from C-API in Lua 5.3).
2494
2495 cdef void luaL_setfuncs(lua_State *L, const lua.luaL_Reg *l, int nup) noexcept:
2496 cdef int i
2497 lua.luaL_checkstack(L, nup, "too many upvalues")
2498 while l.name != NULL:
2499 for i in range(nup):
2500 lua.lua_pushvalue(L, -nup)
2501 lua.lua_pushcclosure(L, l.func, nup)
2502 lua.lua_setfield(L, -(nup + 2), l.name)
2503 l += 1
2504 lua.lua_pop(L, nup)
2505
2506
2507 cdef int libsize(const lua.luaL_Reg *l) noexcept:
2508 cdef int size = 0
2509 while l and l.name:
2510 l += 1
2511 size += 1
2512 return size
2513
2514
2515 cdef const char *luaL_findtable(lua_State *L, int idx,
2516 const char *fname, int size_hint) noexcept:
2517 cdef const char *end
2518 if idx:
2519 lua.lua_pushvalue(L, idx)
2520
2521 while True:
2522 end = strchr(fname, '.')
2523 if end == NULL:
2524 end = fname + strlen(fname)
2525 lua.lua_pushlstring(L, fname, end - fname)
2526 lua.lua_rawget(L, -2)
2527 if lua.lua_type(L, -1) == lua.LUA_TNIL:
2528 lua.lua_pop(L, 1)
2529 lua.lua_createtable(L, 0, (1 if end[0] == '.' else size_hint))
2530 lua.lua_pushlstring(L, fname, end - fname)
2531 lua.lua_pushvalue(L, -2)
2532 lua.lua_settable(L, -4)
2533 elif not lua.lua_istable(L, -1):
2534 lua.lua_pop(L, 2)
2535 return fname
2536 lua.lua_remove(L, -2)
2537 fname = end + 1
2538 if end[0] != '.':
2539 break
2540 return NULL
2541
2542
2543 cdef void luaL_pushmodule(lua_State *L, const char *modname, int size_hint) noexcept:
2544 # XXX: "_LOADED" is the value of LUA_LOADED_TABLE,
2545 # but it's absent in lua51
2546 luaL_findtable(L, lua.LUA_REGISTRYINDEX, "_LOADED", 1)
2547 lua.lua_getfield(L, -1, modname)
2548 if lua.lua_type(L, -1) != lua.LUA_TTABLE:
2549 lua.lua_pop(L, 1)
2550 lua.lua_getglobal(L, '_G')
2551 if luaL_findtable(L, 0, modname, size_hint) != NULL:
2552 lua.luaL_error(L, "name conflict for module '%s'", modname)
2553 lua.lua_pushvalue(L, -1)
2554 lua.lua_setfield(L, -3, modname)
2555 lua.lua_remove(L, -2)
2556
2557
2558 cdef void luaL_openlib(lua_State *L, const char *libname,
2559 const lua.luaL_Reg *l, int nup) noexcept:
2560 if libname:
2561 luaL_pushmodule(L, libname, libsize(l))
2562 lua.lua_insert(L, -(nup + 1))
2563 if l:
2564 luaL_setfuncs(L, l, nup)
2565 else:
2566 lua.lua_pop(L, nup)
2567
2568 # internal Lua functions meant to be called in protected mode
2569
2570 cdef int get_from_lua_table(lua_State* L) noexcept nogil:
2571 """Equivalent to the following Lua function:
2572 function(t, k) return t[k] end
2573 """
2574 # tbl key [...]
2575 lua.lua_settop(L, 2) # tbl key
2576 lua.lua_gettable(L, 1) # tbl tbl[key]
2577 return 1