-
-
Notifications
You must be signed in to change notification settings - Fork 132
/
_lupa.pyx
1722 lines (1492 loc) · 61.6 KB
/
_lupa.pyx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# cython: embedsignature=True, binding=True
"""
A fast Python wrapper around Lua and LuaJIT2.
"""
from __future__ import absolute_import
cimport cython
from lupa cimport lua
from .lua cimport lua_State
cimport cpython.ref
cimport cpython.tuple
cimport cpython.float
cimport cpython.long
from cpython.ref cimport PyObject
from cpython.method cimport (
PyMethod_Check, PyMethod_GET_SELF, PyMethod_GET_FUNCTION)
from cpython.version cimport PY_MAJOR_VERSION
from cpython.bytes cimport PyBytes_FromFormat
from libc.stdint cimport uintptr_t
cdef extern from *:
ctypedef char* const_char_ptr "const char*"
cdef object exc_info
from sys import exc_info
cdef object Mapping
from collections import Mapping
cdef object wraps
from functools import wraps
__all__ = ['LuaRuntime', 'LuaError', 'LuaSyntaxError',
'as_itemgetter', 'as_attrgetter', 'lua_type',
'unpacks_lua_table', 'unpacks_lua_table_method']
cdef object builtins
try:
import __builtin__ as builtins
except ImportError:
import builtins
DEF POBJECT = b"POBJECT" # as used by LunaticPython
cdef int IS_PY2 = PY_MAJOR_VERSION == 2
cdef enum WrappedObjectFlags:
# flags that determine the behaviour of a wrapped object:
OBJ_AS_INDEX = 1 # prefers the getitem protocol (over getattr)
OBJ_UNPACK_TUPLE = 2 # unpacks into separate values if it is a tuple
OBJ_ENUMERATOR = 4 # iteration uses native enumerate() implementation
cdef struct py_object:
PyObject* obj
PyObject* runtime
int type_flags # or-ed set of WrappedObjectFlags
include "lock.pxi"
class LuaError(Exception):
"""Base class for errors in the Lua runtime.
"""
class LuaSyntaxError(LuaError):
"""Syntax error in Lua code.
"""
def lua_type(obj):
"""
Return the Lua type name of a wrapped object as string, as provided
by Lua's type() function.
For non-wrapper objects (i.e. normal Python objects), returns None.
"""
if not isinstance(obj, _LuaObject):
return None
lua_object = <_LuaObject>obj
assert lua_object._runtime is not None
lock_runtime(lua_object._runtime)
L = lua_object._state
old_top = lua.lua_gettop(L)
cdef const char* lua_type_name
try:
lua.lua_rawgeti(L, lua.LUA_REGISTRYINDEX, lua_object._ref)
ltype = lua.lua_type(L, -1)
if ltype == lua.LUA_TTABLE:
return 'table'
elif ltype == lua.LUA_TFUNCTION:
return 'function'
elif ltype == lua.LUA_TTHREAD:
return 'thread'
elif ltype in (lua.LUA_TUSERDATA, lua.LUA_TLIGHTUSERDATA):
return 'userdata'
else:
lua_type_name = lua.lua_typename(L, ltype)
return lua_type_name if IS_PY2 else lua_type_name.decode('ascii')
finally:
lua.lua_settop(L, old_top)
unlock_runtime(lua_object._runtime)
@cython.no_gc_clear
cdef class LuaRuntime:
"""The main entry point to the Lua runtime.
Available options:
* ``encoding``: the string encoding, defaulting to UTF-8. If set
to ``None``, all string values will be returned as byte strings.
Otherwise, they will be decoded to unicode strings on the way
from Lua to Python and unicode strings will be encoded on the
way to Lua. Note that ``str()`` calls on Lua objects will
always return a unicode object.
* ``source_encoding``: the encoding used for Lua code, defaulting to
the string encoding or UTF-8 if the string encoding is ``None``.
* ``attribute_filter``: filter function for attribute access
(get/set). Must have the signature ``func(obj, attr_name,
is_setting)``, where ``is_setting`` is True when the attribute
is being set. If provided, the function will be called for all
Python object attributes that are being accessed from Lua code.
Normally, it should return an attribute name that will then be
used for the lookup. If it wants to prevent access, it should
raise an ``AttributeError``. Note that Lua does not guarantee
that the names will be strings. (New in Lupa 0.20)
* ``attribute_handlers``: like ``attribute_filter`` above, but
handles the getting/setting itself rather than giving hints
to the LuaRuntime. This must be a 2-tuple, ``(getter, setter)``
where ``getter`` has the signature ``func(obj, attr_name)``
and either returns the value for ``obj.attr_name`` or raises an
``AttributeError`` The function ``setter`` has the signature
``func(obj, attr_name, value)`` and may raise an ``AttributeError``.
The return value of the setter is unused. (New in Lupa 1.0)
* ``register_eval``: should Python's ``eval()`` function be available
to Lua code as ``python.eval()``? Note that this does not remove it
from the builtins. Use an ``attribute_filter`` function for that.
(default: True)
* ``register_builtins``: should Python's builtins be available to Lua
code as ``python.builtins.*``? Note that this does not prevent access
to the globals available as special Python function attributes, for
example. Use an ``attribute_filter`` function for that.
(default: True, new in Lupa 1.2)
* ``unpack_returned_tuples``: should Python tuples be unpacked in Lua?
If ``py_fun()`` returns ``(1, 2, 3)``, then does ``a, b, c = py_fun()``
give ``a == 1 and b == 2 and c == 3`` or does it give
``a == (1,2,3), b == nil, c == nil``? ``unpack_returned_tuples=True``
gives the former.
(default: False, new in Lupa 0.21)
Example usage::
>>> from lupa import LuaRuntime
>>> lua = LuaRuntime()
>>> lua.eval('1+1')
2
>>> lua_func = lua.eval('function(f, n) return f(n) end')
>>> def py_add1(n): return n+1
>>> lua_func(py_add1, 2)
3
"""
cdef lua_State *_state
cdef FastRLock _lock
cdef dict _pyrefs_in_lua
cdef tuple _raised_exception
cdef bytes _encoding
cdef bytes _source_encoding
cdef object _attribute_filter
cdef object _attribute_getter
cdef object _attribute_setter
cdef bint _unpack_returned_tuples
def __cinit__(self, encoding='UTF-8', source_encoding=None,
attribute_filter=None, attribute_handlers=None,
bint register_eval=True, bint unpack_returned_tuples=False,
bint register_builtins=True):
cdef lua_State* L = lua.luaL_newstate()
if L is NULL:
raise LuaError("Failed to initialise Lua runtime")
self._state = L
self._lock = FastRLock()
self._pyrefs_in_lua = {}
self._encoding = _asciiOrNone(encoding)
self._source_encoding = _asciiOrNone(source_encoding) or self._encoding or b'UTF-8'
if attribute_filter is not None and not callable(attribute_filter):
raise ValueError("attribute_filter must be callable")
self._attribute_filter = attribute_filter
self._unpack_returned_tuples = unpack_returned_tuples
if attribute_handlers:
raise_error = False
try:
getter, setter = attribute_handlers
except (ValueError, TypeError):
raise_error = True
else:
if (getter is not None and not callable(getter) or
setter is not None and not callable(setter)):
raise_error = True
if raise_error:
raise ValueError("attribute_handlers must be a sequence of two callables")
if attribute_filter and (getter is not None or setter is not None):
raise ValueError("attribute_filter and attribute_handlers are mutually exclusive")
self._attribute_getter, self._attribute_setter = getter, setter
lua.luaL_openlibs(L)
self.init_python_lib(register_eval, register_builtins)
lua.lua_settop(L, 0)
lua.lua_atpanic(L, <lua.lua_CFunction>1)
def __dealloc__(self):
if self._state is not NULL:
lua.lua_close(self._state)
self._state = NULL
@cython.final
cdef int reraise_on_exception(self) except -1:
if self._raised_exception is not None:
exception = self._raised_exception
self._raised_exception = None
raise exception[0], exception[1], exception[2]
return 0
@cython.final
cdef int store_raised_exception(self) except -1:
self._raised_exception = exc_info()
return 0
def eval(self, lua_code, *args):
"""Evaluate a Lua expression passed in a string.
"""
assert self._state is not NULL
if isinstance(lua_code, unicode):
lua_code = (<unicode>lua_code).encode(self._source_encoding)
return run_lua(self, b'return ' + lua_code, args)
def execute(self, lua_code, *args):
"""Execute a Lua program passed in a string.
"""
assert self._state is not NULL
if isinstance(lua_code, unicode):
lua_code = (<unicode>lua_code).encode(self._source_encoding)
return run_lua(self, lua_code, args)
def require(self, modulename):
"""Load a Lua library into the runtime.
"""
assert self._state is not NULL
cdef lua_State *L = self._state
if not isinstance(modulename, (bytes, unicode)):
raise TypeError("modulename must be a string")
lock_runtime(self)
old_top = lua.lua_gettop(L)
try:
lua.lua_getglobal(L, 'require')
if lua.lua_isnil(L, -1):
raise LuaError("require is not defined")
return call_lua(self, L, (modulename,))
finally:
lua.lua_settop(L, old_top)
unlock_runtime(self)
def globals(self):
"""Return the globals defined in this Lua runtime as a Lua
table.
"""
assert self._state is not NULL
cdef lua_State *L = self._state
lock_runtime(self)
old_top = lua.lua_gettop(L)
try:
lua.lua_getglobal(L, '_G')
if lua.lua_isnil(L, -1):
raise LuaError("globals not defined")
return py_from_lua(self, L, -1)
finally:
lua.lua_settop(L, old_top)
unlock_runtime(self)
def table(self, *items, **kwargs):
"""Create a new table with the provided items. Positional
arguments are placed in the table in order, keyword arguments
are set as key-value pairs.
"""
return self.table_from(items, kwargs)
def table_from(self, *args):
"""Create a new table from Python mapping or iterable.
table_from() accepts either a dict/mapping or an iterable with items.
Items from dicts are set as key-value pairs; items from iterables
are placed in the table in order.
Nested mappings / iterables are passed to Lua as userdata
(wrapped Python objects); they are not converted to Lua tables.
"""
assert self._state is not NULL
cdef lua_State *L = self._state
cdef int i = 1
lock_runtime(self)
old_top = lua.lua_gettop(L)
try:
lua.lua_newtable(L)
# FIXME: how to check for failure?
for obj in args:
if isinstance(obj, dict):
for key, value in obj.iteritems():
py_to_lua(self, L, key)
py_to_lua(self, L, value)
lua.lua_rawset(L, -3)
elif isinstance(obj, _LuaTable):
# Stack: # tbl
(<_LuaObject>obj).push_lua_object() # tbl, obj
lua.lua_pushnil(L) # tbl, obj, nil // iterate over obj (-2)
while lua.lua_next(L, -2): # tbl, obj, k, v
lua.lua_pushvalue(L, -2) # tbl, obj, k, v, k // copy key (because
lua.lua_insert(L, -2) # tbl, obj, k, k, v // lua_next needs a key for iteration)
lua.lua_settable(L, -5) # tbl, obj, k // tbl[k] = v
lua.lua_pop(L, 1) # tbl // remove obj from stack
elif isinstance(obj, Mapping):
for key in obj:
value = obj[key]
py_to_lua(self, L, key)
py_to_lua(self, L, value)
lua.lua_rawset(L, -3)
else:
for arg in obj:
py_to_lua(self, L, arg)
lua.lua_rawseti(L, -2, i)
i += 1
return py_from_lua(self, L, -1)
finally:
lua.lua_settop(L, old_top)
unlock_runtime(self)
@cython.final
cdef int register_py_object(self, bytes cname, bytes pyname, object obj) except -1:
cdef lua_State *L = self._state
lua.lua_pushlstring(L, cname, len(cname))
if not py_to_lua_custom(self, L, obj, 0):
lua.lua_pop(L, 1)
raise LuaError("failed to convert %s object" % pyname)
lua.lua_pushlstring(L, pyname, len(pyname))
lua.lua_pushvalue(L, -2)
lua.lua_rawset(L, -5)
lua.lua_rawset(L, lua.LUA_REGISTRYINDEX)
return 0
@cython.final
cdef int init_python_lib(self, bint register_eval, bint register_builtins) except -1:
cdef lua_State *L = self._state
# create 'python' lib and register our own object metatable
lua.luaL_openlib(L, "python", py_lib, 0)
lua.luaL_newmetatable(L, POBJECT)
lua.luaL_openlib(L, NULL, py_object_lib, 0)
lua.lua_pop(L, 1)
# register global names in the module
self.register_py_object(b'Py_None', b'none', None)
if register_eval:
self.register_py_object(b'eval', b'eval', eval)
if register_builtins:
self.register_py_object(b'builtins', b'builtins', builtins)
return 0 # nothing left to return on the stack
################################################################################
# decorators for calling Python functions with keyword (named) arguments
# from Lua scripts
def unpacks_lua_table(func):
"""
A decorator to make the decorated function receive kwargs
when it is called from Lua with a single Lua table argument.
Python functions wrapped in this decorator can be called from Lua code
as ``func(foo, bar)``, ``func{foo=foo, bar=bar}`` and ``func{foo, bar=bar}``.
See also: http://lua-users.org/wiki/NamedParameters
WARNING: avoid using this decorator for functions where the
first argument can be a Lua table.
WARNING: be careful with ``nil`` values. Depending on the context,
passing ``nil`` as a parameter can mean either "omit a parameter"
or "pass None". This even depends on the Lua version. It is
possible to use ``python.none`` instead of ``nil`` to pass None values
robustly.
"""
@wraps(func)
def wrapper(*args):
args, kwargs = _fix_args_kwargs(args)
return func(*args, **kwargs)
return wrapper
def unpacks_lua_table_method(meth):
"""
This is :func:`unpacks_lua_table` for methods
(i.e. it knows about the 'self' argument).
"""
@wraps(meth)
def wrapper(self, *args):
args, kwargs = _fix_args_kwargs(args)
return meth(self, *args, **kwargs)
return wrapper
cdef tuple _fix_args_kwargs(tuple args):
"""
Extract named arguments from args passed to a Python function by Lua
script. Arguments are processed only if a single argument is passed and
it is a table.
"""
if len(args) != 1:
return args, {}
arg = args[0]
if not isinstance(arg, _LuaTable):
return args, {}
table = <_LuaTable>arg
encoding = table._runtime._source_encoding
# arguments with keys from 1 to #tbl are passed as positional
new_args = [
table._getitem(key, is_attr_access=False)
for key in range(1, table._len() + 1)
]
# arguments with non-integer keys are passed as named
new_kwargs = {
(<bytes>key).decode(encoding) if not IS_PY2 and isinstance(key, bytes) else key: value
for key, value in _LuaIter(table, ITEMS)
if not isinstance(key, (int, long))
}
return new_args, new_kwargs
################################################################################
# fast, re-entrant runtime locking
cdef inline int lock_runtime(LuaRuntime runtime) except -1:
if not lock_lock(runtime._lock, pythread.PyThread_get_thread_ident(), True):
raise LuaError("Failed to acquire thread lock")
return 0
cdef inline void unlock_runtime(LuaRuntime runtime) nogil:
unlock_lock(runtime._lock)
################################################################################
# Lua object wrappers
@cython.internal
@cython.no_gc_clear
@cython.freelist(16)
cdef class _LuaObject:
"""A wrapper around a Lua object such as a table or function.
"""
cdef LuaRuntime _runtime
cdef lua_State* _state
cdef int _ref
def __init__(self):
raise TypeError("Type cannot be instantiated manually")
def __dealloc__(self):
if self._runtime is None:
return
cdef lua_State* L = self._state
try:
lock_runtime(self._runtime)
locked = True
except:
locked = False
lua.luaL_unref(L, lua.LUA_REGISTRYINDEX, self._ref)
if locked:
unlock_runtime(self._runtime)
@cython.final
cdef inline int push_lua_object(self) except -1:
cdef lua_State* L = self._state
lua.lua_rawgeti(L, lua.LUA_REGISTRYINDEX, self._ref)
if lua.lua_isnil(L, -1):
lua.lua_pop(L, 1)
raise LuaError("lost reference")
def __call__(self, *args):
assert self._runtime is not None
cdef lua_State* L = self._state
lock_runtime(self._runtime)
try:
lua.lua_settop(L, 0)
self.push_lua_object()
return call_lua(self._runtime, L, args)
finally:
lua.lua_settop(L, 0)
unlock_runtime(self._runtime)
def __len__(self):
return self._len()
@cython.final
cdef size_t _len(self):
assert self._runtime is not None
cdef lua_State* L = self._state
lock_runtime(self._runtime)
size = 0
try:
self.push_lua_object()
size = lua.lua_objlen(L, -1)
lua.lua_pop(L, 1)
finally:
unlock_runtime(self._runtime)
return size
def __nonzero__(self):
return True
def __iter__(self):
# if not provided, iteration will try item access and call into Lua
raise TypeError("iteration is only supported for tables")
def __repr__(self):
assert self._runtime is not None
cdef lua_State* L = self._state
encoding = self._runtime._encoding.decode('ASCII') if self._runtime._encoding else 'UTF-8'
lock_runtime(self._runtime)
try:
self.push_lua_object()
return lua_object_repr(L, encoding)
finally:
lua.lua_pop(L, 1)
unlock_runtime(self._runtime)
def __str__(self):
assert self._runtime is not None
cdef lua_State* L = self._state
cdef unicode py_string = None
cdef const_char_ptr s
cdef size_t size = 0
encoding = self._runtime._encoding.decode('ASCII') if self._runtime._encoding else 'UTF-8'
lock_runtime(self._runtime)
old_top = lua.lua_gettop(L)
try:
self.push_lua_object()
# lookup and call "__tostring" metatable method manually to catch any errors
if lua.lua_getmetatable(L, -1):
lua.lua_pushlstring(L, "__tostring", 10)
lua.lua_rawget(L, -2)
if not lua.lua_isnil(L, -1) and lua.lua_pcall(L, 1, 1, 0) == 0:
s = lua.lua_tolstring(L, -1, &size)
if s:
try:
py_string = s[:size].decode(encoding)
except UnicodeDecodeError:
# safe 'decode'
py_string = s[:size].decode('ISO-8859-1')
if py_string is None:
lua.lua_settop(L, old_top + 1)
py_string = lua_object_repr(L, encoding)
finally:
lua.lua_settop(L, old_top)
unlock_runtime(self._runtime)
return py_string
def __getattr__(self, name):
assert self._runtime is not None
if isinstance(name, unicode):
if (<unicode>name).startswith(u'__') and (<unicode>name).endswith(u'__'):
return object.__getattr__(self, name)
name = (<unicode>name).encode(self._runtime._source_encoding)
elif isinstance(name, bytes):
if (<bytes>name).startswith(b'__') and (<bytes>name).endswith(b'__'):
return object.__getattr__(self, name)
return self._getitem(name, is_attr_access=True)
def __getitem__(self, index_or_name):
return self._getitem(index_or_name, is_attr_access=False)
@cython.final
cdef _getitem(self, name, bint is_attr_access):
cdef lua_State* L = self._state
lock_runtime(self._runtime)
old_top = lua.lua_gettop(L)
try:
self.push_lua_object()
lua_type = lua.lua_type(L, -1)
if lua_type == lua.LUA_TFUNCTION or lua_type == lua.LUA_TTHREAD:
lua.lua_pop(L, 1)
raise (AttributeError if is_attr_access else TypeError)(
"item/attribute access not supported on functions")
# table[nil] fails, so map None -> python.none for Lua tables
py_to_lua(self._runtime, L, name, wrap_none=lua_type == lua.LUA_TTABLE)
lua.lua_gettable(L, -2)
return py_from_lua(self._runtime, L, -1)
finally:
lua.lua_settop(L, old_top)
unlock_runtime(self._runtime)
cdef _LuaObject new_lua_object(LuaRuntime runtime, lua_State* L, int n):
cdef _LuaObject obj = _LuaObject.__new__(_LuaObject)
init_lua_object(obj, runtime, L, n)
return obj
cdef void init_lua_object(_LuaObject obj, LuaRuntime runtime, lua_State* L, int n):
obj._runtime = runtime
obj._state = L
lua.lua_pushvalue(L, n)
obj._ref = lua.luaL_ref(L, lua.LUA_REGISTRYINDEX)
cdef object lua_object_repr(lua_State* L, encoding):
cdef bytes py_bytes
lua_type = lua.lua_type(L, -1)
if lua_type in (lua.LUA_TTABLE, lua.LUA_TFUNCTION):
ptr = <void*>lua.lua_topointer(L, -1)
elif lua_type in (lua.LUA_TUSERDATA, lua.LUA_TLIGHTUSERDATA):
ptr = <void*>lua.lua_touserdata(L, -1)
elif lua_type == lua.LUA_TTHREAD:
ptr = <void*>lua.lua_tothread(L, -1)
else:
ptr = NULL
if ptr:
py_bytes = PyBytes_FromFormat(
"<Lua %s at %p>", lua.lua_typename(L, lua_type), ptr)
else:
py_bytes = PyBytes_FromFormat(
"<Lua %s>", lua.lua_typename(L, lua_type))
try:
return py_bytes.decode(encoding)
except UnicodeDecodeError:
# safe 'decode'
return py_bytes.decode('ISO-8859-1')
@cython.final
@cython.internal
@cython.no_gc_clear
cdef class _LuaTable(_LuaObject):
def __iter__(self):
return _LuaIter(self, KEYS)
def keys(self):
"""Returns an iterator over the keys of a table that this
object represents. Same as iter(obj).
"""
return _LuaIter(self, KEYS)
def values(self):
"""Returns an iterator over the values of a table that this
object represents.
"""
return _LuaIter(self, VALUES)
def items(self):
"""Returns an iterator over the key-value pairs of a table
that this object represents.
"""
return _LuaIter(self, ITEMS)
def __setattr__(self, name, value):
assert self._runtime is not None
if isinstance(name, unicode):
if (<unicode>name).startswith(u'__') and (<unicode>name).endswith(u'__'):
object.__setattr__(self, name, value)
return
name = (<unicode>name).encode(self._runtime._source_encoding)
elif isinstance(name, bytes) and (<bytes>name).startswith(b'__') and (<bytes>name).endswith(b'__'):
object.__setattr__(self, name, value)
return
self._setitem(name, value)
def __setitem__(self, index_or_name, value):
self._setitem(index_or_name, value)
@cython.final
cdef int _setitem(self, name, value) except -1:
cdef lua_State* L = self._state
lock_runtime(self._runtime)
old_top = lua.lua_gettop(L)
try:
self.push_lua_object()
# table[nil] fails, so map None -> python.none for Lua tables
py_to_lua(self._runtime, L, name, wrap_none=True)
py_to_lua(self._runtime, L, value)
lua.lua_settable(L, -3)
finally:
lua.lua_settop(L, old_top)
unlock_runtime(self._runtime)
return 0
def __delattr__(self, item):
assert self._runtime is not None
if isinstance(item, unicode):
if (<unicode>item).startswith(u'__') and (<unicode>item).endswith(u'__'):
object.__delattr__(self, item)
return
item = (<unicode>item).encode(self._runtime._source_encoding)
elif isinstance(item, bytes) and (<bytes>item).startswith(b'__') and (<bytes>item).endswith(b'__'):
object.__delattr__(self, item)
return
self._delitem(item)
def __delitem__(self, key):
self._delitem(key)
@cython.final
cdef _delitem(self, name):
cdef lua_State* L = self._state
lock_runtime(self._runtime)
old_top = lua.lua_gettop(L)
try:
self.push_lua_object()
py_to_lua(self._runtime, L, name, wrap_none=True)
lua.lua_pushnil(L)
lua.lua_settable(L, -3)
finally:
lua.lua_settop(L, old_top)
unlock_runtime(self._runtime)
cdef _LuaTable new_lua_table(LuaRuntime runtime, lua_State* L, int n):
cdef _LuaTable obj = _LuaTable.__new__(_LuaTable)
init_lua_object(obj, runtime, L, n)
return obj
@cython.internal
@cython.no_gc_clear
cdef class _LuaFunction(_LuaObject):
"""A Lua function (which may become a coroutine).
"""
def coroutine(self, *args):
"""Create a Lua coroutine from a Lua function and call it with
the passed parameters to start it up.
"""
assert self._runtime is not None
cdef lua_State* L = self._state
cdef lua_State* co
cdef _LuaThread thread
lock_runtime(self._runtime)
old_top = lua.lua_gettop(L)
try:
self.push_lua_object()
if not lua.lua_isfunction(L, -1) or lua.lua_iscfunction(L, -1):
raise TypeError("Lua object is not a function")
# create thread stack and push the function on it
co = lua.lua_newthread(L)
lua.lua_pushvalue(L, 1)
lua.lua_xmove(L, co, 1)
# create the coroutine object and initialise it
assert lua.lua_isthread(L, -1)
thread = new_lua_thread(self._runtime, L, -1)
thread._arguments = args # always a tuple, not None !
return thread
finally:
lua.lua_settop(L, old_top)
unlock_runtime(self._runtime)
cdef _LuaFunction new_lua_function(LuaRuntime runtime, lua_State* L, int n):
cdef _LuaFunction obj = _LuaFunction.__new__(_LuaFunction)
init_lua_object(obj, runtime, L, n)
return obj
@cython.final
@cython.internal
@cython.no_gc_clear
cdef class _LuaCoroutineFunction(_LuaFunction):
"""A function that returns a new coroutine when called.
"""
def __call__(self, *args):
return self.coroutine(*args)
cdef _LuaCoroutineFunction new_lua_coroutine_function(LuaRuntime runtime, lua_State* L, int n):
cdef _LuaCoroutineFunction obj = _LuaCoroutineFunction.__new__(_LuaCoroutineFunction)
init_lua_object(obj, runtime, L, n)
return obj
@cython.final
@cython.internal
@cython.no_gc_clear # FIXME: get rid if this
cdef class _LuaThread(_LuaObject):
"""A Lua thread (coroutine).
"""
cdef lua_State* _co_state
cdef tuple _arguments
def __iter__(self):
return self
def __next__(self):
assert self._runtime is not None
cdef tuple args = self._arguments
if args is not None:
self._arguments = None
return resume_lua_thread(self, args)
def send(self, value):
"""Send a value into the coroutine. If the value is a tuple,
send the unpacked elements.
"""
if value is not None:
if self._arguments is not None:
raise TypeError("can't send non-None value to a just-started generator")
if not isinstance(value, tuple):
value = (value,)
elif self._arguments is not None:
value = self._arguments
self._arguments = None
return resume_lua_thread(self, <tuple>value)
def __bool__(self):
cdef lua.lua_Debug dummy
assert self._runtime is not None
cdef int status = lua.lua_status(self._co_state)
if status == lua.LUA_YIELD:
return True
if status == 0:
# copied from Lua code: check for frames
if lua.lua_getstack(self._co_state, 0, &dummy) > 0:
return True # currently running
elif lua.lua_gettop(self._co_state) > 0:
return True # not started yet
return False
cdef _LuaThread new_lua_thread(LuaRuntime runtime, lua_State* L, int n):
cdef _LuaThread obj = _LuaThread.__new__(_LuaThread)
init_lua_object(obj, runtime, L, n)
obj._co_state = lua.lua_tothread(L, n)
return obj
cdef _LuaObject new_lua_thread_or_function(LuaRuntime runtime, lua_State* L, int n):
# this is special - we replace a new (unstarted) thread by its
# underlying function to better follow Python's own generator
# protocol
cdef lua_State* co = lua.lua_tothread(L, n)
assert co is not NULL
if lua.lua_status(co) == 0 and lua.lua_gettop(co) == 1:
# not started yet => get the function and return that
lua.lua_pushvalue(co, 1)
lua.lua_xmove(co, L, 1)
try:
return new_lua_coroutine_function(runtime, L, -1)
finally:
lua.lua_pop(L, 1)
else:
# already started => wrap the thread
return new_lua_thread(runtime, L, n)
cdef object resume_lua_thread(_LuaThread thread, tuple args):
cdef lua_State* co = thread._co_state
cdef lua_State* L = thread._state
cdef int status, i, nargs = 0, nres = 0
lock_runtime(thread._runtime)
old_top = lua.lua_gettop(L)
try:
if lua.lua_status(co) == 0 and lua.lua_gettop(co) == 0:
# already terminated
raise StopIteration
if args:
nargs = len(args)
push_lua_arguments(thread._runtime, co, args)
with nogil:
status = lua.lua_resume(co, L, nargs)
nres = lua.lua_gettop(co)
if status != lua.LUA_YIELD:
if status == 0:
# terminated
if nres == 0:
# no values left to return
raise StopIteration
else:
raise_lua_error(thread._runtime, co, status)
# Move yielded values to the main state before unpacking.
# This is what Lua's internal auxresume function is doing;
# it affects wrapped Lua functions returned to Python.
lua.lua_xmove(co, L, nres)
return unpack_lua_results(thread._runtime, L)
finally:
# FIXME: check that coroutine state is OK in case of errors?
lua.lua_settop(L, old_top)
unlock_runtime(thread._runtime)
cdef enum:
KEYS = 1
VALUES = 2
ITEMS = 3
@cython.final
@cython.internal
@cython.no_gc_clear
cdef class _LuaIter:
cdef LuaRuntime _runtime
cdef _LuaObject _obj
cdef lua_State* _state
cdef int _refiter
cdef char _what
def __cinit__(self, _LuaObject obj not None, int what):
self._state = NULL
assert obj._runtime is not None
self._runtime = obj._runtime
self._obj = obj
self._state = obj._state
self._refiter = 0
self._what = what
def __dealloc__(self):
if self._runtime is None:
return
cdef lua_State* L = self._state
if L is not NULL and self._refiter:
locked = False
try:
lock_runtime(self._runtime)
locked = True
except:
pass
lua.luaL_unref(L, lua.LUA_REGISTRYINDEX, self._refiter)
if locked:
unlock_runtime(self._runtime)
def __repr__(self):
return u"LuaIter(%r)" % (self._obj)
def __iter__(self):
return self
def __next__(self):
if self._obj is None:
raise StopIteration
cdef lua_State* L = self._obj._state
lock_runtime(self._runtime)
old_top = lua.lua_gettop(L)
try:
if self._obj is None:
raise StopIteration
# iterable object
lua.lua_rawgeti(L, lua.LUA_REGISTRYINDEX, self._obj._ref)
if not lua.lua_istable(L, -1):
if lua.lua_isnil(L, -1):
lua.lua_pop(L, 1)
raise LuaError("lost reference")
raise TypeError("cannot iterate over non-table (found %r)" % self._obj)
if not self._refiter:
# initial key
lua.lua_pushnil(L)
else:
# last key
lua.lua_rawgeti(L, lua.LUA_REGISTRYINDEX, self._refiter)
if lua.lua_next(L, -2):
try:
if self._what == KEYS:
retval = py_from_lua(self._runtime, L, -2)
elif self._what == VALUES:
retval = py_from_lua(self._runtime, L, -1)
else: # ITEMS
retval = (py_from_lua(self._runtime, L, -2), py_from_lua(self._runtime, L, -1))
finally:
# pop value
lua.lua_pop(L, 1)
# pop and store key
if not self._refiter:
self._refiter = lua.luaL_ref(L, lua.LUA_REGISTRYINDEX)
else:
lua.lua_rawseti(L, lua.LUA_REGISTRYINDEX, self._refiter)
return retval
# iteration done, clean up
if self._refiter:
lua.luaL_unref(L, lua.LUA_REGISTRYINDEX, self._refiter)
self._refiter = 0
self._obj = None