Debian Codegraph @

lupa/_lupa.pyx

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