-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathpython_to_starlark.go
387 lines (321 loc) Β· 10.4 KB
/
python_to_starlark.go
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
package main
/*
#include "starlark.h"
extern PyObject *ConversionToStarlarkFailed;
*/
import "C"
import (
"fmt"
"math/big"
"unsafe"
"go.starlark.net/starlark"
)
func pythonToStarlarkTuple(obj *C.PyObject, env PythonEnv) (starlark.Tuple, error) {
var elems []starlark.Value
pyiter := C.PyObject_GetIter(obj)
if pyiter == nil {
return starlark.Tuple{}, fmt.Errorf("Couldn't get iterator for Python tuple")
}
defer C.Py_DecRef(pyiter)
index := 0
for pyvalue := C.PyIter_Next(pyiter); pyvalue != nil; pyvalue = C.PyIter_Next(pyiter) {
defer C.Py_DecRef(pyvalue)
value, err := innerPythonToStarlarkValue(pyvalue, env)
if err != nil {
return starlark.Tuple{}, fmt.Errorf("While converting value at index %v in Python tuple: %v", index, err)
}
elems = append(elems, value)
index += 1
}
if C.PyErr_Occurred() != nil {
return starlark.Tuple{}, fmt.Errorf("Python exception while converting value at index %v in Python tuple", index)
}
return starlark.Tuple(elems), nil
}
func pythonToStarlarkBytes(obj *C.PyObject) (starlark.Bytes, error) {
cbytes := C.PyBytes_AsString(obj)
if cbytes == nil {
return starlark.Bytes(""), fmt.Errorf("Couldn't get pointer to Python bytes")
}
return starlark.Bytes(C.GoString(cbytes)), nil
}
func pythonToStarlarkList(obj *C.PyObject, env PythonEnv) (*starlark.List, error) {
len := C.PyObject_Length(obj)
if len < 0 {
return &starlark.List{}, fmt.Errorf("Couldn't get size of Python list")
}
var elems []starlark.Value
pyiter := C.PyObject_GetIter(obj)
if pyiter == nil {
return &starlark.List{}, fmt.Errorf("Couldn't get iterator for Python list")
}
defer C.Py_DecRef(pyiter)
index := 0
for pyvalue := C.PyIter_Next(pyiter); pyvalue != nil; pyvalue = C.PyIter_Next(pyiter) {
defer C.Py_DecRef(pyvalue)
value, err := innerPythonToStarlarkValue(pyvalue, env)
if err != nil {
return &starlark.List{}, fmt.Errorf("While converting value at index %v in Python list: %v", index, err)
}
elems = append(elems, value)
index += 1
}
if C.PyErr_Occurred() != nil {
return &starlark.List{}, fmt.Errorf("Python exception while converting value at index %v in Python list", index)
}
return starlark.NewList(elems), nil
}
func pythonToStarlarkDict(obj *C.PyObject, env PythonEnv) (*starlark.Dict, error) {
size := C.PyObject_Length(obj)
if size < 0 {
return &starlark.Dict{}, fmt.Errorf("Couldn't get size of Python dict")
}
dict := starlark.NewDict(int(size))
pyiter := C.PyObject_GetIter(obj)
if pyiter == nil {
return &starlark.Dict{}, fmt.Errorf("Couldn't get iterator for Python dict")
}
defer C.Py_DecRef(pyiter)
for pykey := C.PyIter_Next(pyiter); pykey != nil; pykey = C.PyIter_Next(pyiter) {
defer C.Py_DecRef(pykey)
key, err := innerPythonToStarlarkValue(pykey, env)
if err != nil {
return &starlark.Dict{}, fmt.Errorf("While converting key in Python dict: %v", err)
}
pyvalue := C.PyObject_GetItem(obj, pykey)
if pyvalue == nil {
return &starlark.Dict{}, fmt.Errorf("Couldn't get value of key %v in Python dict", key)
}
defer C.Py_DecRef(pyvalue)
value, err := innerPythonToStarlarkValue(pyvalue, env)
if err != nil {
return &starlark.Dict{}, fmt.Errorf("While converting value of key %v in Python dict: %v", key, err)
}
err = dict.SetKey(key, value)
if err != nil {
return &starlark.Dict{}, fmt.Errorf("While setting %v to %v in Starlark dict: %v", key, value, err)
}
}
if C.PyErr_Occurred() != nil {
return &starlark.Dict{}, fmt.Errorf("Python exception while iterating through Python dict")
}
return dict, nil
}
func pythonToStarlarkSet(obj *C.PyObject, env PythonEnv) (*starlark.Set, error) {
size := C.PyObject_Length(obj)
if size < 0 {
return &starlark.Set{}, fmt.Errorf("Couldn't get size of Python set")
}
set := starlark.NewSet(int(size))
pyiter := C.PyObject_GetIter(obj)
if pyiter == nil {
return &starlark.Set{}, fmt.Errorf("Couldn't get iterator for Python set")
}
defer C.Py_DecRef(pyiter)
for pyvalue := C.PyIter_Next(pyiter); pyvalue != nil; pyvalue = C.PyIter_Next(pyiter) {
defer C.Py_DecRef(pyvalue)
value, err := innerPythonToStarlarkValue(pyvalue, env)
if err != nil {
return &starlark.Set{}, fmt.Errorf("While converting value in Python set: %v", err)
}
err = set.Insert(value)
if err != nil {
raisePythonException(err)
return &starlark.Set{}, fmt.Errorf("While inserting %v into Starlark set: %v", value, err)
}
}
if C.PyErr_Occurred() != nil {
return &starlark.Set{}, fmt.Errorf("Python exception while converting value in Python set to Starlark")
}
return set, nil
}
func pythonToStarlarkString(obj *C.PyObject) (starlark.String, error) {
var size C.Py_ssize_t
cstr := C.PyUnicode_AsUTF8AndSize(obj, &size)
if cstr == nil {
return starlark.String(""), fmt.Errorf("Couldn't convert Python string to C string")
}
return starlark.String(C.GoString(cstr)), nil
}
func pythonToStarlarkInt(obj *C.PyObject) (starlark.Int, error) {
overflow := C.int(0)
longlong := int64(C.PyLong_AsLongLongAndOverflow(obj, &overflow)) // https://youtu.be/6-1Ue0FFrHY
if C.PyErr_Occurred() != nil {
return starlark.Int{}, fmt.Errorf("Couldn't convert Python int to long")
}
if overflow == 0 {
return starlark.MakeInt64(longlong), nil
}
pystr := C.PyObject_Str(obj)
if pystr == nil {
return starlark.Int{}, fmt.Errorf("Couldn't convert Python int to string")
}
defer C.Py_DecRef(pystr)
var size C.Py_ssize_t
cstr := C.PyUnicode_AsUTF8AndSize(pystr, &size)
if cstr == nil {
return starlark.Int{}, fmt.Errorf("Couldn't convert Python int to C string")
}
i := new(big.Int)
i.SetString(C.GoString(cstr), 10)
return starlark.MakeBigInt(i), nil
}
func pythonToStarlarkFloat(obj *C.PyObject) (starlark.Float, error) {
cvalue := C.PyFloat_AsDouble(obj)
if C.PyErr_Occurred() != nil {
return starlark.Float(0), fmt.Errorf("Couldn't convert Python float to double")
}
return starlark.Float(cvalue), nil
}
func getFuncName(obj *C.PyObject) (string, error) {
nameAttr := C.CString("__name__")
defer C.free(unsafe.Pointer(nameAttr))
funcName, err := pythonToStarlarkString(C.PyObject_GetAttrString(obj, nameAttr))
if err != nil {
return "", err
}
return funcName.GoString(), nil
}
func getPyError() error {
// TODO: replace with PyErr_GetRaisedException when requiring Python >= 3.12
var (
errType *C.PyObject
errValue *C.PyObject
errTraceback *C.PyObject
)
C.PyErr_Fetch(&errType, &errValue, &errTraceback)
defer C.Py_DecRef(errType)
defer C.Py_DecRef(errValue)
defer C.Py_DecRef(errTraceback)
errStr, err := pythonToStarlarkString(C.PyObject_Str(errValue))
if err != nil {
return err
}
return fmt.Errorf(errStr.GoString())
}
func pythonToStarlarkFunc(obj *C.PyObject, env PythonEnv) (starlark.Value, error) {
funcName, err := getFuncName(obj)
if err != nil {
return starlark.None, err
}
return starlark.NewBuiltin(funcName, func(
_ *starlark.Thread,
_ *starlark.Builtin,
args starlark.Tuple,
kwargs []starlark.Tuple,
) (starlark.Value, error) {
env.ReattachGIL()
defer env.DetachGIL()
cargs, err := starlarkTupleToPython(args)
if err != nil {
return starlark.None, err
}
defer C.Py_DecRef(cargs)
ckwargs, err := starlarkDictItemsToPython(kwargs)
if err != nil {
return starlark.None, err
}
defer C.Py_DecRef(ckwargs)
res := C.PyObject_Call(obj, cargs, ckwargs)
if C.PyErr_Occurred() != nil {
return starlark.None, getPyError()
}
defer C.Py_DecRef(res)
return innerPythonToStarlarkValue(res, env)
}), nil
}
func pythonToStarlarkMethod(obj *C.PyObject, env PythonEnv) (starlark.Value, error) {
self := C.PyMethod_Self(obj)
f := C.PyMethod_Function(obj)
funcName, err := getFuncName(f)
if err != nil {
return starlark.None, err
}
return starlark.NewBuiltin(funcName, func(
_ *starlark.Thread,
_ *starlark.Builtin,
args starlark.Tuple,
kwargs []starlark.Tuple,
) (starlark.Value, error) {
env.ReattachGIL()
defer env.DetachGIL()
// create args list with self at the front
cargsList, err := starlarkTupleToPythonList(args)
if err != nil {
return starlark.None, err
}
cargs := C.PyTuple_New(C.Py_ssize_t(len(cargsList) + 1))
if cargs == nil {
return starlark.None, fmt.Errorf("Could not initialize argument list")
}
C.Py_IncRef(self)
C.PyTuple_SetItem(cargs, 0, self)
for i, arg := range cargsList {
C.PyTuple_SetItem(cargs, C.Py_ssize_t(i + 1), arg)
}
defer C.Py_DecRef(cargs)
ckwargs, err := starlarkDictItemsToPython(kwargs)
if err != nil {
return starlark.None, err
}
defer C.Py_DecRef(ckwargs)
res := C.PyObject_Call(f, cargs, ckwargs)
if C.PyErr_Occurred() != nil {
return starlark.None, getPyError()
}
defer C.Py_DecRef(res)
return innerPythonToStarlarkValue(res, env)
}), nil
}
func innerPythonToStarlarkValue(obj *C.PyObject, env PythonEnv) (starlark.Value, error) {
var value starlark.Value = nil
var err error = nil
switch {
case obj == C.Py_None:
value = starlark.None
case obj == C.Py_True:
value = starlark.True
case obj == C.Py_False:
value = starlark.False
case C.cgoPyFloat_Check(obj) == 1:
value, err = pythonToStarlarkFloat(obj)
case C.cgoPyLong_Check(obj) == 1:
value, err = pythonToStarlarkInt(obj)
case C.cgoPyUnicode_Check(obj) == 1:
value, err = pythonToStarlarkString(obj)
case C.cgoPyBytes_Check(obj) == 1:
value, err = pythonToStarlarkBytes(obj)
case C.cgoPySet_Check(obj) == 1:
value, err = pythonToStarlarkSet(obj, env)
case C.cgoPyDict_Check(obj) == 1:
value, err = pythonToStarlarkDict(obj, env)
case C.cgoPyList_Check(obj) == 1:
value, err = pythonToStarlarkList(obj, env)
case C.cgoPyTuple_Check(obj) == 1:
value, err = pythonToStarlarkTuple(obj, env)
case C.PySequence_Check(obj) == 1:
value, err = pythonToStarlarkList(obj, env)
case C.PyMapping_Check(obj) == 1:
value, err = pythonToStarlarkDict(obj, env)
case C.cgoPyFunc_Check(obj) == 1:
value, err = pythonToStarlarkFunc(obj, env)
case C.cgoPyMethod_Check(obj) == 1:
value, err = pythonToStarlarkMethod(obj, env)
default:
err = fmt.Errorf("Don't know how to convert Python %s to Starlark", C.GoString(obj.ob_type.tp_name))
}
if err == nil {
if C.PyErr_Occurred() != nil {
err = fmt.Errorf("Python exception while converting to Starlark")
}
}
return value, err
}
func pythonToStarlarkValue(obj *C.PyObject, env PythonEnv) (starlark.Value, error) {
value, err := innerPythonToStarlarkValue(obj, env)
if err != nil {
handleConversionError(err, C.ConversionToStarlarkFailed)
return starlark.None, err
}
return value, nil
}