-
Notifications
You must be signed in to change notification settings - Fork 87
Expand file tree
/
Copy pathluainpython.c
More file actions
594 lines (522 loc) · 15.1 KB
/
luainpython.c
File metadata and controls
594 lines (522 loc) · 15.1 KB
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
/*
Lunatic Python
--------------
Copyright (c) 2002-2005 Gustavo Niemeyer <gustavo@niemeyer.net>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#define PY_SSIZE_T_CLEAN
#include <Python.h>
/* need this to build with Lua 5.2: enables lua_strlen() macro */
#define LUA_COMPAT_ALL
#include <lua.h>
#include <luaconf.h>
#include <lauxlib.h>
#include <lualib.h>
#include "pythoninlua.h"
#include "luainpython.h"
lua_State *LuaState = NULL;
static PyObject *LuaObject_New(lua_State *L, int n)
{
LuaObject *obj = PyObject_New(LuaObject, &LuaObject_Type);
if (obj)
{
lua_pushvalue(L, n);
obj->ref = luaL_ref(L, LUA_REGISTRYINDEX);
obj->refiter = 0;
}
return (PyObject*) obj;
}
PyObject *LuaConvert(lua_State *L, int n)
{
PyObject *ret = NULL;
switch (lua_type(L, n)) {
case LUA_TNIL:
Py_INCREF(Py_None);
ret = Py_None;
break;
case LUA_TSTRING: {
size_t len;
const char *s = lua_tolstring(L, n, &len);
ret = PyUnicode_FromStringAndSize(s, len);
if (!ret)
{
PyErr_Clear();
ret = PyBytes_FromStringAndSize(s, len);
}
break;
}
case LUA_TNUMBER: {
lua_Number num = lua_tonumber(L, n);
if (num != (long)num) {
ret = PyFloat_FromDouble(num);
} else {
ret = PyLong_FromLong((long)num);
}
break;
}
case LUA_TBOOLEAN:
ret = lua_toboolean(L, n) ? Py_True : Py_False;
Py_INCREF(ret);
break;
case LUA_TUSERDATA: {
py_object *obj = luaPy_to_pobject(L, n);
if (obj) {
Py_INCREF(obj->o);
ret = obj->o;
break;
}
/* Otherwise go on and handle as custom. */
}
default:
ret = LuaObject_New(L, n);
break;
}
return ret;
}
static PyObject *LuaCall(lua_State *L, PyObject *args)
{
PyObject *ret = NULL;
PyObject *arg;
#ifdef PY_SSIZE_T_CLEAN
Py_ssize_t nargs, i;
#else
int nargs, i;
#endif
int rc;
if (!PyTuple_Check(args)) {
PyErr_SetString(PyExc_TypeError, "tuple expected");
lua_settop(L, 0);
return NULL;
}
nargs = PyTuple_Size(args);
for (i = 0; i != nargs; i++) {
arg = PyTuple_GetItem(args, i);
if (arg == NULL) {
PyErr_Format(PyExc_TypeError,
"failed to get tuple item #%d", i);
lua_settop(L, 0);
return NULL;
}
rc = py_convert(L, arg);
if (!rc) {
PyErr_Format(PyExc_TypeError,
"failed to convert argument #%d", i);
lua_settop(L, 0);
return NULL;
}
}
if (lua_pcall(L, nargs, LUA_MULTRET, 0) != 0) {
PyErr_Format(PyExc_Exception,
"error: %s", lua_tostring(L, -1));
return NULL;
}
nargs = lua_gettop(L);
if (nargs == 1) {
ret = LuaConvert(L, 1);
if (!ret) {
PyErr_SetString(PyExc_TypeError,
"failed to convert return");
lua_settop(L, 0);
Py_DECREF(ret);
return NULL;
}
} else if (nargs > 1) {
ret = PyTuple_New(nargs);
if (!ret) {
PyErr_SetString(PyExc_RuntimeError,
"failed to create return tuple");
lua_settop(L, 0);
return NULL;
}
for (i = 0; i != nargs; i++) {
arg = LuaConvert(L, i+1);
if (!arg) {
PyErr_Format(PyExc_TypeError,
"failed to convert return #%d", i);
lua_settop(L, 0);
Py_DECREF(ret);
return NULL;
}
PyTuple_SetItem(ret, i, arg);
}
} else {
Py_INCREF(Py_None);
ret = Py_None;
}
lua_settop(L, 0);
return ret;
}
static void LuaObject_dealloc(LuaObject *self)
{
luaL_unref(LuaState, LUA_REGISTRYINDEX, self->ref);
if (self->refiter)
luaL_unref(LuaState, LUA_REGISTRYINDEX, self->refiter);
Py_TYPE(self)->tp_free((PyObject *)self);
}
static PyObject *LuaObject_getattr(PyObject *obj, PyObject *attr)
{
lua_rawgeti(LuaState, LUA_REGISTRYINDEX, ((LuaObject*)obj)->ref);
if (lua_isnil(LuaState, -1)) {
lua_pop(LuaState, 1);
PyErr_SetString(PyExc_RuntimeError, "lost reference");
return NULL;
}
if (!lua_isstring(LuaState, -1)
&& !lua_istable(LuaState, -1)
&& !lua_isuserdata(LuaState, -1))
{
lua_pop(LuaState, 1);
PyErr_SetString(PyExc_RuntimeError, "not an indexable value");
return NULL;
}
PyObject *ret = NULL;
int rc = py_convert(LuaState, attr);
if (rc) {
lua_gettable(LuaState, -2);
ret = LuaConvert(LuaState, -1);
} else {
PyErr_SetString(PyExc_ValueError, "can't convert attr/key");
}
lua_settop(LuaState, 0);
return ret;
}
static int LuaObject_setattr(PyObject *obj, PyObject *attr, PyObject *value)
{
int ret = -1;
int rc;
lua_rawgeti(LuaState, LUA_REGISTRYINDEX, ((LuaObject*)obj)->ref);
if (lua_isnil(LuaState, -1)) {
lua_pop(LuaState, 1);
PyErr_SetString(PyExc_RuntimeError, "lost reference");
return -1;
}
if (!lua_istable(LuaState, -1)) {
lua_pop(LuaState, -1);
PyErr_SetString(PyExc_TypeError, "Lua object is not a table");
return -1;
}
rc = py_convert(LuaState, attr);
if (rc) {
if (NULL == value) {
lua_pushnil(LuaState);
rc = 1;
} else {
rc = py_convert(LuaState, value);
}
if (rc) {
lua_settable(LuaState, -3);
ret = 0;
} else {
PyErr_SetString(PyExc_ValueError,
"can't convert value");
}
} else {
PyErr_SetString(PyExc_ValueError, "can't convert key/attr");
}
lua_settop(LuaState, 0);
return ret;
}
static PyObject *LuaObject_str(PyObject *obj)
{
PyObject *ret = NULL;
const char *s;
lua_rawgeti(LuaState, LUA_REGISTRYINDEX, ((LuaObject*)obj)->ref);
if (luaL_callmeta(LuaState, -1, "__tostring")) {
s = lua_tostring(LuaState, -1);
lua_pop(LuaState, 1);
if (s) ret = PyUnicode_FromString(s);
}
if (!ret) {
int type = lua_type(LuaState, -1);
switch (type) {
case LUA_TTABLE:
case LUA_TFUNCTION:
ret = PyUnicode_FromFormat("<Lua %s at %p>",
lua_typename(LuaState, type),
lua_topointer(LuaState, -1));
break;
case LUA_TUSERDATA:
case LUA_TLIGHTUSERDATA:
ret = PyUnicode_FromFormat("<Lua %s at %p>",
lua_typename(LuaState, type),
lua_touserdata(LuaState, -1));
break;
case LUA_TTHREAD:
ret = PyUnicode_FromFormat("<Lua %s at %p>",
lua_typename(LuaState, type),
(void*)lua_tothread(LuaState, -1));
break;
default:
ret = PyUnicode_FromFormat("<Lua %s>",
lua_typename(LuaState, type));
break;
}
}
lua_pop(LuaState, 1);
return ret;
}
#if LUA_VERSION_NUM == 501
#ifdef LUA_OK // defined in LuaJIT
#undef LUA_OK
#endif
enum
{
LUA_OK, LUA_OPEQ, LUA_OPLT, LUA_OPLE,
};
static int lua_compare(lua_State *L, int lhs, int rhs, int op)
{
switch(op)
{
case LUA_OPEQ:
return lua_equal(L, lhs, rhs);
case LUA_OPLT:
return lua_lessthan(L, lhs, rhs);
case LUA_OPLE:
return lua_lessthan(L, lhs, rhs) || lua_equal(L, lhs, rhs);
}
return 0;
}
#endif
static int LuaObject_pcmp(lua_State *L)
{
int op = lua_tointeger(L, -3);
switch(op)
{
case Py_EQ:
lua_pushboolean(L, lua_compare(L, -2, -1, LUA_OPEQ));
break;
case Py_NE:
lua_pushboolean(L, !lua_compare(L, -2, -1, LUA_OPEQ));
break;
case Py_GT:
lua_insert(LuaState, -2);
case Py_LT:
lua_pushboolean(L, lua_compare(L, -2, -1, LUA_OPLT));
break;
case Py_GE:
lua_insert(LuaState, -2);
case Py_LE:
lua_pushboolean(L, lua_compare(L, -2, -1, LUA_OPLE));
}
return 1;
}
static PyObject* LuaObject_richcmp(PyObject *lhs, PyObject *rhs, int op)
{
if (!LuaObject_Check(rhs)) return Py_False;
lua_pushcfunction(LuaState, LuaObject_pcmp);
lua_pushinteger(LuaState, op);
lua_rawgeti(LuaState, LUA_REGISTRYINDEX, ((LuaObject *)lhs)->ref);
lua_rawgeti(LuaState, LUA_REGISTRYINDEX, ((LuaObject *)rhs)->ref);
if (lua_pcall(LuaState, 3, 1, 0) != LUA_OK)
{
PyErr_SetString(PyExc_RuntimeError, lua_tostring(LuaState, -1));
return NULL;
}
return LuaConvert(LuaState, -1);
}
static PyObject *LuaObject_call(PyObject *obj, PyObject *args)
{
lua_settop(LuaState, 0);
lua_rawgeti(LuaState, LUA_REGISTRYINDEX, ((LuaObject*)obj)->ref);
return LuaCall(LuaState, args);
}
static PyObject *LuaObject_iternext(LuaObject *obj)
{
PyObject *ret = NULL;
lua_rawgeti(LuaState, LUA_REGISTRYINDEX, ((LuaObject*)obj)->ref);
if (obj->refiter == 0)
lua_pushnil(LuaState);
else
lua_rawgeti(LuaState, LUA_REGISTRYINDEX, obj->refiter);
if (lua_next(LuaState, -2) != 0) {
/* Remove value. */
lua_pop(LuaState, 1);
ret = LuaConvert(LuaState, -1);
/* Save key for next iteration. */
if (!obj->refiter)
obj->refiter = luaL_ref(LuaState, LUA_REGISTRYINDEX);
else
lua_rawseti(LuaState, LUA_REGISTRYINDEX, obj->refiter);
} else if (obj->refiter) {
luaL_unref(LuaState, LUA_REGISTRYINDEX, obj->refiter);
obj->refiter = 0;
}
return ret;
}
#ifdef PY_SSIZE_T_CLEAN
static Py_ssize_t LuaObject_length(LuaObject *obj)
#else
static int LuaObject_length(LuaObject *obj)
#endif
{
#ifdef PY_SSIZE_T_CLEAN
Py_ssize_t len;
#else
int len;
#endif
lua_rawgeti(LuaState, LUA_REGISTRYINDEX, ((LuaObject*)obj)->ref);
len = luaL_len(LuaState, -1);
lua_settop(LuaState, 0);
return len;
}
static PyObject *LuaObject_subscript(PyObject *obj, PyObject *key)
{
return LuaObject_getattr(obj, key);
}
static int LuaObject_ass_subscript(PyObject *obj,
PyObject *key, PyObject *value)
{
return LuaObject_setattr(obj, key, value);
}
static PyMappingMethods LuaObject_as_mapping = {
#if PY_VERSION_HEX >= 0x02050000
(lenfunc)LuaObject_length, /*mp_length*/
#else
(inquiry)LuaObject_length, /*mp_length*/
#endif
(binaryfunc)LuaObject_subscript,/*mp_subscript*/
(objobjargproc)LuaObject_ass_subscript,/*mp_ass_subscript*/
};
PyTypeObject LuaObject_Type = {
PyVarObject_HEAD_INIT(NULL, 0)
.tp_name = "lua.custom",
.tp_basicsize = sizeof(LuaObject),
.tp_dealloc = (destructor)LuaObject_dealloc,
.tp_repr = LuaObject_str,
.tp_as_mapping = &LuaObject_as_mapping,
.tp_call = (ternaryfunc)LuaObject_call,
.tp_str = LuaObject_str,
.tp_getattro = LuaObject_getattr,
.tp_setattro = LuaObject_setattr,
.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
.tp_doc = "custom lua object",
.tp_richcompare = LuaObject_richcmp,
.tp_iter = PyObject_SelfIter,
.tp_iternext = (iternextfunc)LuaObject_iternext,
.tp_alloc = PyType_GenericAlloc,
.tp_new = PyType_GenericNew,
.tp_free = PyObject_Del,
};
PyObject *Lua_run(PyObject *args, int eval)
{
PyObject *ret;
char *buf = NULL;
char *s;
#ifdef PY_SSIZE_T_CLEAN
Py_ssize_t len;
#else
int len;
#endif
if (!PyArg_ParseTuple(args, "s#", &s, &len))
return NULL;
if (eval) {
buf = (char *) malloc(strlen("return ")+len+1);
strcpy(buf, "return ");
strncat(buf, s, len);
s = buf;
len = strlen("return ")+len;
}
if (luaL_loadbuffer(LuaState, s, len, "<python>") != 0) {
PyErr_Format(PyExc_RuntimeError,
"error loading code: %s",
lua_tostring(LuaState, -1));
free(buf);
return NULL;
}
free(buf);
if (lua_pcall(LuaState, 0, 1, 0) != 0) {
PyErr_Format(PyExc_RuntimeError,
"error executing code: %s",
lua_tostring(LuaState, -1));
return NULL;
}
ret = LuaConvert(LuaState, -1);
lua_settop(LuaState, 0);
return ret;
}
PyObject *Lua_execute(PyObject *self, PyObject *args)
{
return Lua_run(args, 0);
}
PyObject *Lua_eval(PyObject *self, PyObject *args)
{
return Lua_run(args, 1);
}
PyObject *Lua_globals(PyObject *self, PyObject *args)
{
PyObject *ret = NULL;
lua_getglobal(LuaState, "_G");
if (lua_isnil(LuaState, -1)) {
PyErr_SetString(PyExc_RuntimeError,
"lost globals reference");
lua_pop(LuaState, 1);
return NULL;
}
ret = LuaConvert(LuaState, -1);
if (!ret)
PyErr_Format(PyExc_TypeError,
"failed to convert globals table");
lua_settop(LuaState, 0);
return ret;
}
static PyObject *Lua_require(PyObject *self, PyObject *args)
{
lua_getglobal(LuaState, "require");
if (lua_isnil(LuaState, -1)) {
lua_pop(LuaState, 1);
PyErr_SetString(PyExc_RuntimeError, "require is not defined");
return NULL;
}
return LuaCall(LuaState, args);
}
static PyMethodDef lua_methods[] =
{
{"execute", Lua_execute, METH_VARARGS, NULL},
{"eval", Lua_eval, METH_VARARGS, NULL},
{"globals", Lua_globals, METH_NOARGS, NULL},
{"require", Lua_require, METH_VARARGS, NULL},
{NULL, NULL}
};
#if PY_MAJOR_VERSION >= 3
static struct PyModuleDef lua_module =
{
PyModuleDef_HEAD_INIT,
"lua",
"Lunatic-Python Python-Lua bridge",
-1,
lua_methods
};
#endif
PyMODINIT_FUNC PyInit_lua(void)
{
PyObject *m;
if (PyType_Ready(&LuaObject_Type) < 0 ||
#if PY_MAJOR_VERSION >= 3
(m = PyModule_Create(&lua_module)) == NULL)
return NULL;
#else
(m = Py_InitModule3("lua", lua_methods,
"Lunatic-Python Python-Lua bridge")) == NULL)
return;
#endif
if (!LuaState)
{
LuaState = luaL_newstate();
luaL_openlibs(LuaState);
luaopen_python(LuaState);
lua_settop(LuaState, 0);
}
#if PY_MAJOR_VERSION >= 3
return m;
#endif
}