comparison pymonkey.c @ 0:21aa6e3abb49

Origination.
author Atul Varma <varmaa@toolness.com>
date Sun, 28 Jun 2009 12:02:22 -0700
parents
children 2f6bdc9f7245
comparison
equal deleted inserted replaced
-1:000000000000 0:21aa6e3abb49
1 #include "jsapi.h"
2 #include <Python/Python.h>
3
4 static JSClass PYM_JSGlobalClass = {
5 "PymonkeyGlobal", JSCLASS_GLOBAL_FLAGS,
6 JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub,
7 JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, JS_FinalizeStub,
8 JSCLASS_NO_OPTIONAL_MEMBERS
9 };
10
11 static PyObject *PYM_error;
12
13 static PyObject *
14 PYM_evaluate(PyObject *self, PyObject *args)
15 {
16 const char *source;
17 int sourceLen;
18 const char *filename;
19 int lineNo;
20
21 if (!PyArg_ParseTuple(args, "s#si", &source, &sourceLen,
22 &filename, &lineNo))
23 return NULL;
24
25 JSRuntime *rt = JS_NewRuntime(8L * 1024L * 1024L);
26 if (rt == NULL) {
27 PyErr_SetString(PYM_error, "JS_NewRuntime() failed");
28 return NULL;
29 }
30
31 JSContext *cx = JS_NewContext(rt, 8192);
32 if (cx == NULL) {
33 PyErr_SetString(PYM_error, "JS_NewContext() failed");
34 JS_DestroyRuntime(rt);
35 }
36
37 JS_SetOptions(cx, JSOPTION_VAROBJFIX);
38 JS_SetVersion(cx, JSVERSION_LATEST);
39
40 JS_BeginRequest(cx);
41
42 JSObject *global = JS_NewObject(cx, &PYM_JSGlobalClass, NULL, NULL);
43 if (global == NULL) {
44 PyErr_SetString(PYM_error, "JS_NewObject() failed");
45 JS_EndRequest(cx);
46 JS_DestroyContext(cx);
47 JS_DestroyRuntime(rt);
48 return NULL;
49 }
50
51 if (!JS_InitStandardClasses(cx, global)) {
52 PyErr_SetString(PYM_error, "JS_InitStandardClasses() failed");
53 JS_EndRequest(cx);
54 JS_DestroyContext(cx);
55 JS_DestroyRuntime(rt);
56 return NULL;
57 }
58
59 jsval rval;
60 if (!JS_EvaluateScript(cx, global, source, sourceLen, filename,
61 lineNo, &rval)) {
62 // TODO: Actually get the error that was raised.
63 PyErr_SetString(PYM_error, "Script failed");
64 JS_EndRequest(cx);
65 JS_DestroyContext(cx);
66 JS_DestroyRuntime(rt);
67 return NULL;
68 }
69
70 JS_EndRequest(cx);
71 JS_DestroyContext(cx);
72 JS_DestroyRuntime(rt);
73
74 // TODO: Get the return value of the script.
75
76 Py_INCREF(Py_None);
77 return Py_None;
78 }
79
80 static PyMethodDef PYM_methods[] = {
81 {"evaluate", PYM_evaluate, METH_VARARGS,
82 "Evaluate the given JavaScript code, using the given filename "
83 "and line number information."},
84 {NULL, NULL, 0, NULL}
85 };
86
87 PyMODINIT_FUNC
88 initpymonkey(void)
89 {
90 PyObject *module;
91
92 module = Py_InitModule("pymonkey", PYM_methods);
93 if (module == NULL)
94 return;
95
96 PYM_error = PyErr_NewException("pymonkey.error", NULL, NULL);
97 Py_INCREF(PYM_error);
98 PyModule_AddObject(module, "error", PYM_error);
99 }