Debian Codegraph @

python/_jsonnet.c

raw
1 /*
2 Copyright 2015 Google Inc. All rights reserved.
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 */
16
17 #include <stdlib.h>
18 #include <stdio.h>
19
20 #include <Python.h>
21
22 #include "libjsonnet.h"
23
24 #if PY_MAJOR_VERSION < 3
25 #error "Python 2 is no longer supported."
26 #endif
27
28 struct StrRefAndObj {
29 /* Since Python 3.10, we have PyUnicode_AsUTF8AndSize
30 * which doesn't need its result to be deallocated, and
31 * therefore doesn't need to track the extra Bytes object. */
32 #if Py_LIMITED_API < 0x030A0000
33 PyObject *bytes;
34 #endif
35 const char *cstr;
36 Py_ssize_t len;
37 };
38
39 static struct StrRefAndObj get_py_utf8_string(PyObject *unicode_obj) {
40 Py_ssize_t len = 0;
41 struct StrRefAndObj ret = {0};
42
43 if (!unicode_obj) {
44 return ret;
45 }
46
47 #if Py_LIMITED_API < 0x030A0000
48 PyObject *bytes = PyUnicode_AsUTF8String(unicode_obj);
49 if (!bytes) {
50 return ret;
51 }
52 char *s = 0;
53 if (PyBytes_AsStringAndSize(bytes, &s, &len)) {
54 // What to do if it fails??
55 Py_XDECREF(bytes);
56 return ret;
57 }
58 ret.bytes = bytes;
59 #else
60 const char *s = PyUnicode_AsUTF8AndSize(unicode_obj, &len);
61 #endif
62 ret.cstr = s;
63 ret.len = len;
64 return ret;
65 }
66
67 static void release_py_utf8_string(struct StrRefAndObj *utf8_obj) {
68 #if Py_LIMITED_API < 0x030A0000
69 Py_XDECREF(utf8_obj->bytes);
70 utf8_obj->bytes = NULL;
71 #endif
72 utf8_obj->cstr = NULL;
73 utf8_obj->len = 0;
74 }
75
76 static char *jsonnet_str(struct JsonnetVm *vm, const char *str)
77 {
78 size_t size = strlen(str) + 1;
79 char *out = jsonnet_realloc(vm, NULL, size);
80 memcpy(out, str, size);
81 return out;
82 }
83
84 static char *jsonnet_str_nonull(struct JsonnetVm *vm, const char *str, size_t *buflen)
85 {
86 *buflen = strlen(str);
87 char *out = jsonnet_realloc(vm, NULL, *buflen);
88 memcpy(out, str, *buflen);
89 return out;
90 }
91
92 static struct StrRefAndObj exc_to_str(void)
93 {
94 PyObject *ptype, *pvalue, *ptraceback;
95 PyErr_Fetch(&ptype, &pvalue, &ptraceback);
96 PyObject *exc_str = PyObject_Str(pvalue);
97 return get_py_utf8_string(exc_str);
98 }
99
100 struct NativeCtx {
101 struct JsonnetVm *vm;
102 PyThreadState **py_thread;
103 PyObject *callback;
104 size_t argc;
105 };
106
107 static struct JsonnetJsonValue *python_to_jsonnet_json(struct JsonnetVm *vm, PyObject *v,
108 const char **err_msg)
109 {
110 if (PyUnicode_Check(v)) {
111 struct JsonnetJsonValue *r;
112 struct StrRefAndObj v_utf8 = get_py_utf8_string(v);
113 r = jsonnet_json_make_string(vm, v_utf8.cstr);
114 release_py_utf8_string(&v_utf8);
115 return r;
116 } else if (PyBool_Check(v)) {
117 return jsonnet_json_make_bool(vm, PyObject_IsTrue(v));
118 } else if (PyFloat_Check(v)) {
119 return jsonnet_json_make_number(vm, PyFloat_AsDouble(v));
120 } else if (PyLong_Check(v)) {
121 return jsonnet_json_make_number(vm, (double)(PyLong_AsLong(v)));
122 } else if (v == Py_None) {
123 return jsonnet_json_make_null(vm);
124 } else if (PySequence_Check(v)) {
125 Py_ssize_t len, i;
126 struct JsonnetJsonValue *arr;
127 // Convert it to a O(1) indexable form if necessary.
128 PyObject *fast = PySequence_Fast(v, "python_to_jsonnet_json internal error: not sequence");
129 len = PySequence_Size(fast);
130 arr = jsonnet_json_make_array(vm);
131 for (i = 0; i < len; ++i) {
132 struct JsonnetJsonValue *json_el;
133 PyObject *el = PySequence_GetItem(fast, i);
134 json_el = python_to_jsonnet_json(vm, el, err_msg);
135 if (json_el == NULL) {
136 Py_DECREF(fast);
137 jsonnet_json_destroy(vm, arr);
138 return NULL;
139 }
140 jsonnet_json_array_append(vm, arr, json_el);
141 }
142 Py_DECREF(fast);
143 return arr;
144 } else if (PyDict_Check(v)) {
145 struct JsonnetJsonValue *obj;
146 PyObject *key, *val;
147 Py_ssize_t pos = 0;
148 obj = jsonnet_json_make_object(vm);
149 while (PyDict_Next(v, &pos, &key, &val)) {
150 struct JsonnetJsonValue *json_val;
151 struct StrRefAndObj key_utf8 = get_py_utf8_string(key);
152 if (!key_utf8.cstr) {
153 release_py_utf8_string(&key_utf8);
154 *err_msg = "Non-string key in dict returned from Python Jsonnet native extension.";
155 jsonnet_json_destroy(vm, obj);
156 return NULL;
157 }
158 json_val = python_to_jsonnet_json(vm, val, err_msg);
159 if (json_val == NULL) {
160 release_py_utf8_string(&key_utf8);
161 jsonnet_json_destroy(vm, obj);
162 return NULL;
163 }
164 jsonnet_json_object_append(vm, obj, key_utf8.cstr, json_val);
165 release_py_utf8_string(&key_utf8);
166 }
167 return obj;
168 } else {
169 *err_msg = "Unrecognized type return from Python Jsonnet native extension.";
170 return NULL;
171 }
172 }
173
174 /* This function is bound for every native callback, but with a different
175 * context.
176 */
177 static struct JsonnetJsonValue *cpython_native_callback(
178 void *ctx_, const struct JsonnetJsonValue * const *argv, int *succ)
179 {
180 const struct NativeCtx *ctx = ctx_;
181
182 PyEval_RestoreThread(*ctx->py_thread);
183
184 PyObject *arglist; // Will hold a tuple of strings.
185 PyObject *result; // Will hold a string.
186
187 // Populate python function args.
188 arglist = PyTuple_New(ctx->argc);
189 for (size_t i = 0; i < ctx->argc; ++i) {
190 double d;
191 const char *param_str = jsonnet_json_extract_string(ctx->vm, argv[i]);
192 int param_null = jsonnet_json_extract_null(ctx->vm, argv[i]);
193 int param_bool = jsonnet_json_extract_bool(ctx->vm, argv[i]);
194 int param_num = jsonnet_json_extract_number(ctx->vm, argv[i], &d);
195 PyObject *pyobj;
196 if (param_str != NULL) {
197 pyobj = PyUnicode_FromString(param_str);
198 } else if (param_null) {
199 pyobj = Py_None;
200 } else if (param_bool != 2) {
201 pyobj = PyBool_FromLong(param_bool);
202 } else if (param_num) {
203 pyobj = PyFloat_FromDouble(d);
204 } else {
205 // TODO(dcunnin): Support arrays (to tuples).
206 // TODO(dcunnin): Support objects (to dicts).
207 Py_DECREF(arglist);
208 *succ = 0;
209 *ctx->py_thread = PyEval_SaveThread();
210 return jsonnet_json_make_string(ctx->vm, "Non-primitive param.");
211 }
212 PyTuple_SetItem(arglist, i, pyobj);
213 }
214
215 // Call python function.
216 result = PyObject_CallObject(ctx->callback, arglist);
217 Py_DECREF(arglist);
218
219 if (result == NULL) {
220 // Get string from exception.
221 struct StrRefAndObj err_utf8 = exc_to_str();
222 struct JsonnetJsonValue *r = jsonnet_json_make_string(ctx->vm, err_utf8.cstr);
223 release_py_utf8_string(&err_utf8);
224 *succ = 0;
225 PyErr_Clear();
226 *ctx->py_thread = PyEval_SaveThread();
227 return r;
228 }
229
230 const char *err_msg;
231 struct JsonnetJsonValue *r = python_to_jsonnet_json(ctx->vm, result, &err_msg);
232 if (r != NULL) {
233 *succ = 1;
234 } else {
235 *succ = 0;
236 r = jsonnet_json_make_string(ctx->vm, err_msg);
237 }
238 *ctx->py_thread = PyEval_SaveThread();
239 return r;
240 }
241
242
243 struct ImportCtx {
244 struct JsonnetVm *vm;
245 PyThreadState **py_thread;
246 PyObject *callback;
247 };
248
249 static int cpython_import_callback(void *ctx_, const char *base, const char *rel,
250 char **found_here, char **buf, size_t *buflen)
251 {
252 const struct ImportCtx *ctx = ctx_;
253 PyObject *arglist, *result;
254 int success;
255
256 PyEval_RestoreThread(*ctx->py_thread);
257 arglist = Py_BuildValue("(s, s)", base, rel);
258 result = PyObject_CallObject(ctx->callback, arglist);
259 Py_DECREF(arglist);
260
261 if (result == NULL) {
262 // Get string from exception
263 struct StrRefAndObj err_utf8 = exc_to_str();
264 *buf = jsonnet_str_nonull(ctx->vm, err_utf8.cstr, buflen);
265 release_py_utf8_string(&err_utf8);
266 PyErr_Clear();
267 *ctx->py_thread = PyEval_SaveThread();
268 return 1; // failure
269 }
270
271 if (!PyTuple_Check(result)) {
272 *buf = jsonnet_str_nonull(ctx->vm, "import_callback did not return a tuple", buflen);
273 success = 0;
274 } else if (PyTuple_Size(result) != 2) {
275 *buf = jsonnet_str_nonull(ctx->vm, "import_callback did not return a tuple (size 2)", buflen);
276 success = 0;
277 } else {
278 PyObject *file_name = PyTuple_GetItem(result, 0);
279 PyObject *file_content = PyTuple_GetItem(result, 1);
280 if (!PyUnicode_Check(file_name) || !PyBytes_Check(file_content)) {
281 *buf = jsonnet_str_nonull(ctx->vm, "import_callback did not return (string, bytes). Since 0.19.0 imports should be returned as bytes instead of as a string. You may want to call .encode() on your string.", buflen);
282 success = 0;
283 } else {
284 char *content_buf;
285 Py_ssize_t content_len;
286 struct StrRefAndObj found_here_utf8 = get_py_utf8_string(file_name);
287 PyBytes_AsStringAndSize(file_content, &content_buf, &content_len);
288 *found_here = jsonnet_str(ctx->vm, found_here_utf8.cstr);
289 release_py_utf8_string(&found_here_utf8);
290 *buflen = content_len;
291 *buf = jsonnet_realloc(ctx->vm, NULL, *buflen);
292 memcpy(*buf, content_buf, *buflen);
293 success = 1;
294 }
295 }
296
297 Py_DECREF(result);
298 *ctx->py_thread = PyEval_SaveThread();
299
300 return success ? 0 : 1;
301 }
302
303 static PyObject *handle_result(struct JsonnetVm *vm, char *out, int error)
304 {
305 if (error) {
306 PyErr_SetString(PyExc_RuntimeError, out);
307 jsonnet_realloc(vm, out, 0);
308 jsonnet_destroy(vm);
309 return NULL;
310 } else {
311 PyObject *ret = PyUnicode_FromString(out);
312 jsonnet_realloc(vm, out, 0);
313 jsonnet_destroy(vm);
314 return ret;
315 }
316 }
317
318 int handle_vars(struct JsonnetVm *vm, PyObject *map, int code, int tla)
319 {
320 if (map == NULL) return 1;
321
322 PyObject *key, *val;
323 Py_ssize_t pos = 0;
324
325 while (PyDict_Next(map, &pos, &key, &val)) {
326 struct StrRefAndObj key_utf8 = get_py_utf8_string(key);
327 if (!key_utf8.cstr) {
328 release_py_utf8_string(&key_utf8);
329 jsonnet_destroy(vm);
330 return 0;
331 }
332 struct StrRefAndObj val_utf8 = get_py_utf8_string(val);
333 if (!val_utf8.cstr) {
334 release_py_utf8_string(&val_utf8);
335 release_py_utf8_string(&key_utf8);
336 jsonnet_destroy(vm);
337 return 0;
338 }
339 if (!tla && !code) {
340 jsonnet_ext_var(vm, key_utf8.cstr, val_utf8.cstr);
341 } else if (!tla && code) {
342 jsonnet_ext_code(vm, key_utf8.cstr, val_utf8.cstr);
343 } else if (tla && !code) {
344 jsonnet_tla_var(vm, key_utf8.cstr, val_utf8.cstr);
345 } else {
346 jsonnet_tla_code(vm, key_utf8.cstr, val_utf8.cstr);
347 }
348 release_py_utf8_string(&val_utf8);
349 release_py_utf8_string(&key_utf8);
350 }
351 return 1;
352 }
353
354
355 int handle_import_callback(struct ImportCtx *ctx, PyObject *import_callback)
356 {
357 if (import_callback == NULL) return 1;
358
359 if (!PyCallable_Check(import_callback)) {
360 jsonnet_destroy(ctx->vm);
361 PyErr_SetString(PyExc_TypeError, "import_callback must be callable");
362 return 0;
363 }
364
365 jsonnet_import_callback(ctx->vm, cpython_import_callback, ctx);
366
367 return 1;
368 }
369
370
371 /** Register native callbacks with Jsonnet VM.
372 *
373 * Example native_callbacks = { 'name': (('p1', 'p2', 'p3'), func) }
374 *
375 * May set *ctxs, in which case it should be free()'d by caller.
376 *
377 * \returns 1 on success, 0 with exception set upon failure.
378 */
379 static int handle_native_callbacks(struct JsonnetVm *vm, PyObject *native_callbacks,
380 struct NativeCtx **ctxs, PyThreadState **py_thread)
381 {
382 size_t num_natives = 0;
383 PyObject *key, *val;
384 Py_ssize_t pos = 0;
385
386 if (native_callbacks == NULL) return 1;
387
388 /* Verify the input before we allocate memory, throw all errors at this point.
389 * Also, count the callbacks to see how much memory we need.
390 */
391 while (PyDict_Next(native_callbacks, &pos, &key, &val)) {
392 Py_ssize_t i;
393 Py_ssize_t num_params;
394 PyObject *params;
395 if (!PyUnicode_Check(key)) {
396 PyErr_SetString(PyExc_TypeError, "native callback dict keys must be string");
397 goto bad;
398 }
399 if (!PyTuple_Check(val)) {
400 PyErr_SetString(PyExc_TypeError, "native callback dict values must be tuples");
401 goto bad;
402 } else if (PyTuple_Size(val) != 2) {
403 PyErr_SetString(PyExc_TypeError, "native callback tuples must have size 2");
404 goto bad;
405 }
406 params = PyTuple_GetItem(val, 0);
407 if (!PyTuple_Check(params)) {
408 PyErr_SetString(PyExc_TypeError, "native callback params must be a tuple");
409 goto bad;
410 }
411 /* Check the params are all strings */
412 num_params = PyTuple_Size(params);
413 for (i = 0; i < num_params ; ++i) {
414 PyObject *param = PyTuple_GetItem(params, 0);
415 if (!PyUnicode_Check(param)) {
416 PyErr_SetString(PyExc_TypeError, "native callback param must be string");
417 goto bad;
418 }
419 }
420 if (!PyCallable_Check(PyTuple_GetItem(val, 1))) {
421 PyErr_SetString(PyExc_TypeError, "native callback must be callable");
422 goto bad;
423 }
424
425 num_natives++;
426 continue;
427
428 bad:
429 jsonnet_destroy(vm);
430 return 0;
431 }
432
433 if (num_natives == 0) {
434 return 1;
435 }
436
437 *ctxs = malloc(sizeof(struct NativeCtx) * num_natives);
438
439 /* Re-use num_natives but just as a counter this time. */
440 num_natives = 0;
441 pos = 0;
442 while (PyDict_Next(native_callbacks, &pos, &key, &val)) {
443 Py_ssize_t i;
444 Py_ssize_t num_params;
445 PyObject *params;
446 struct StrRefAndObj key_utf8 = get_py_utf8_string(key);
447 params = PyTuple_GetItem(val, 0);
448 num_params = PyTuple_Size(params);
449 /* Include space for terminating NULL. */
450 const char **params_c = malloc(sizeof(const char*) * (num_params + 1));
451 for (i = 0; i < num_params ; ++i) {
452 struct StrRefAndObj param_c_utf8 = get_py_utf8_string(PyTuple_GetItem(params, i));
453 params_c[i] = param_c_utf8.cstr;
454 release_py_utf8_string(&param_c_utf8);
455 }
456 params_c[num_params] = NULL;
457 (*ctxs)[num_natives].vm = vm;
458 (*ctxs)[num_natives].py_thread = py_thread;
459 (*ctxs)[num_natives].callback = PyTuple_GetItem(val, 1);
460 (*ctxs)[num_natives].argc = num_params;
461 jsonnet_native_callback(vm, key_utf8.cstr, cpython_native_callback, &(*ctxs)[num_natives],
462 params_c);
463 release_py_utf8_string(&key_utf8);
464 free(params_c);
465 num_natives++;
466 }
467
468 return 1;
469 }
470
471
472 static PyObject* evaluate_file(PyObject* self, PyObject* args, PyObject *keywds)
473 {
474 const char *filename;
475 char *out;
476 unsigned max_stack = 500, gc_min_objects = 1000, max_trace = 20;
477 double gc_growth_trigger = 2;
478 int error;
479 Py_ssize_t num_jpathdir, i;
480 PyObject *jpathdir = NULL;
481 PyObject *ext_vars = NULL, *ext_codes = NULL;
482 PyObject *tla_vars = NULL, *tla_codes = NULL;
483 PyObject *import_callback = NULL;
484 PyObject *native_callbacks = NULL;
485 struct JsonnetVm *vm;
486 static char *kwlist[] = {
487 "filename", "jpathdir",
488 "max_stack", "gc_min_objects", "gc_growth_trigger", "ext_vars",
489 "ext_codes", "tla_vars", "tla_codes", "max_trace", "import_callback",
490 "native_callbacks",
491 NULL
492 };
493
494 (void) self;
495
496 if (!PyArg_ParseTupleAndKeywords(
497 args, keywds, "s|OIIdOOOOIOO", kwlist,
498 &filename, &jpathdir,
499 &max_stack, &gc_min_objects, &gc_growth_trigger, &ext_vars,
500 &ext_codes, &tla_vars, &tla_codes, &max_trace, &import_callback,
501 &native_callbacks)) {
502 return NULL;
503 }
504
505 PyThreadState *py_thread;
506
507 vm = jsonnet_make();
508 jsonnet_max_stack(vm, max_stack);
509 jsonnet_gc_min_objects(vm, gc_min_objects);
510 jsonnet_max_trace(vm, max_trace);
511 jsonnet_gc_growth_trigger(vm, gc_growth_trigger);
512
513 if (jpathdir != NULL) {
514 // Support string for backward compatibility with <= 0.15.0
515 if (PyUnicode_Check(jpathdir)) {
516 struct StrRefAndObj jpath_utf8 = get_py_utf8_string(jpathdir);
517 jsonnet_jpath_add(vm, jpath_utf8.cstr);
518 release_py_utf8_string(&jpath_utf8);
519 } else if (PyList_Check(jpathdir)) {
520 num_jpathdir = PyList_Size(jpathdir);
521 for (i = 0; i < num_jpathdir ; ++i) {
522 PyObject *jpath = PyList_GetItem(jpathdir, i);
523 if (PyUnicode_Check(jpath)) {
524 struct StrRefAndObj jpath_utf8 = get_py_utf8_string(jpath);
525 jsonnet_jpath_add(vm, jpath_utf8.cstr);
526 release_py_utf8_string(&jpath_utf8);
527 }
528 }
529 }
530 }
531
532 if (!handle_vars(vm, ext_vars, 0, 0)) return NULL;
533 if (!handle_vars(vm, ext_codes, 1, 0)) return NULL;
534 if (!handle_vars(vm, tla_vars, 0, 1)) return NULL;
535 if (!handle_vars(vm, tla_codes, 1, 1)) return NULL;
536
537 struct ImportCtx ctx = { vm, &py_thread, import_callback };
538 if (!handle_import_callback(&ctx, import_callback)) {
539 return NULL;
540 }
541 struct NativeCtx *ctxs = NULL;
542 if (!handle_native_callbacks(vm, native_callbacks, &ctxs, &py_thread)) {
543 free(ctxs);
544 return NULL;
545 }
546 py_thread = PyEval_SaveThread();
547 out = jsonnet_evaluate_file(vm, filename, &error);
548 PyEval_RestoreThread(py_thread);
549 free(ctxs);
550 return handle_result(vm, out, error);
551 }
552
553 static PyObject* evaluate_snippet(PyObject* self, PyObject* args, PyObject *keywds)
554 {
555 const char *filename, *src;
556 char *out;
557 unsigned max_stack = 500, gc_min_objects = 1000, max_trace = 20;
558 double gc_growth_trigger = 2;
559 int error;
560 Py_ssize_t num_jpathdir, i;
561 PyObject *jpathdir = NULL;
562 PyObject *ext_vars = NULL, *ext_codes = NULL;
563 PyObject *tla_vars = NULL, *tla_codes = NULL;
564 PyObject *import_callback = NULL;
565 PyObject *native_callbacks = NULL;
566 struct JsonnetVm *vm;
567 static char *kwlist[] = {
568 "filename", "src", "jpathdir",
569 "max_stack", "gc_min_objects", "gc_growth_trigger", "ext_vars",
570 "ext_codes", "tla_vars", "tla_codes", "max_trace", "import_callback",
571 "native_callbacks",
572 NULL
573 };
574
575 (void) self;
576
577 if (!PyArg_ParseTupleAndKeywords(
578 args, keywds, "ss|OIIdOOOOIOO", kwlist,
579 &filename, &src, &jpathdir,
580 &max_stack, &gc_min_objects, &gc_growth_trigger, &ext_vars,
581 &ext_codes, &tla_vars, &tla_codes, &max_trace, &import_callback,
582 &native_callbacks)) {
583 return NULL;
584 }
585
586 PyThreadState *py_thread;
587
588 vm = jsonnet_make();
589 jsonnet_max_stack(vm, max_stack);
590 jsonnet_gc_min_objects(vm, gc_min_objects);
591 jsonnet_max_trace(vm, max_trace);
592 jsonnet_gc_growth_trigger(vm, gc_growth_trigger);
593
594 if (jpathdir != NULL) {
595 // Support string for backward compatibility with <= 0.15.0
596 if (PyUnicode_Check(jpathdir)) {
597 struct StrRefAndObj jpath_utf8 = get_py_utf8_string(jpathdir);
598 jsonnet_jpath_add(vm, jpath_utf8.cstr);
599 release_py_utf8_string(&jpath_utf8);
600 } else if (PyList_Check(jpathdir)) {
601 num_jpathdir = PyList_Size(jpathdir);
602 for (i = 0; i < num_jpathdir ; ++i) {
603 PyObject *jpath = PyList_GetItem(jpathdir, i);
604 if (PyUnicode_Check(jpath)) {
605 struct StrRefAndObj jpath_utf8 = get_py_utf8_string(jpath);
606 jsonnet_jpath_add(vm, jpath_utf8.cstr);
607 release_py_utf8_string(&jpath_utf8);
608 }
609 }
610 }
611 }
612
613 if (!handle_vars(vm, ext_vars, 0, 0)) return NULL;
614 if (!handle_vars(vm, ext_codes, 1, 0)) return NULL;
615 if (!handle_vars(vm, tla_vars, 0, 1)) return NULL;
616 if (!handle_vars(vm, tla_codes, 1, 1)) return NULL;
617 struct ImportCtx ctx = { vm, &py_thread, import_callback };
618 if (!handle_import_callback(&ctx, import_callback)) {
619 return NULL;
620 }
621 struct NativeCtx *ctxs = NULL;
622 if (!handle_native_callbacks(vm, native_callbacks, &ctxs, &py_thread)) {
623 free(ctxs);
624 return NULL;
625 }
626 py_thread = PyEval_SaveThread();
627 out = jsonnet_evaluate_snippet(vm, filename, src, &error);
628 PyEval_RestoreThread(py_thread);
629 free(ctxs);
630 return handle_result(vm, out, error);
631 }
632
633 static PyMethodDef module_methods[] = {
634 {"evaluate_file", (PyCFunction)evaluate_file, METH_VARARGS | METH_KEYWORDS,
635 "Interpret the given Jsonnet file."},
636 {"evaluate_snippet", (PyCFunction)evaluate_snippet, METH_VARARGS | METH_KEYWORDS,
637 "Interpret the given Jsonnet code."},
638 {NULL, NULL, 0, NULL}
639 };
640
641 static struct PyModuleDef _module =
642 {
643 PyModuleDef_HEAD_INIT,
644 "_jsonnet",
645 "A Python interface to Jsonnet.",
646 -1,
647 module_methods,
648 };
649
650 PyMODINIT_FUNC PyInit__jsonnet(void)
651 {
652 PyObject *module = PyModule_Create(&_module);
653 PyObject *version_str = PyUnicode_FromString(LIB_JSONNET_VERSION);
654 if (PyModule_AddObject(module, "version", PyUnicode_FromString(LIB_JSONNET_VERSION)) < 0) {
655 Py_XDECREF(version_str);
656 }
657 return module;
658 }