forked from Distributive-Network/PythonMonkey
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpythonmonkey.cc
More file actions
349 lines (295 loc) · 12.1 KB
/
pythonmonkey.cc
File metadata and controls
349 lines (295 loc) · 12.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
/**
* @file pythonmonkey.cc
* @author Caleb Aikens (caleb@distributive.network)
* @brief This file defines the pythonmonkey module, along with its various functions.
* @version 0.1
* @date 2023-03-29
*
* @copyright Copyright (c) 2023
*
*/
#include "include/modules/pythonmonkey/pythonmonkey.hh"
#include "include/BoolType.hh"
#include "include/setSpiderMonkeyException.hh"
#include "include/DateType.hh"
#include "include/FloatType.hh"
#include "include/FuncType.hh"
#include "include/PyType.hh"
#include "include/pyTypeFactory.hh"
#include "include/StrType.hh"
#include "include/PyEventLoop.hh"
#include <jsapi.h>
#include <jsfriendapi.h>
#include <js/friend/ErrorMessages.h>
#include <js/CompilationAndEvaluation.h>
#include <js/Class.h>
#include <js/Date.h>
#include <js/Initialization.h>
#include <js/Object.h>
#include <js/Proxy.h>
#include <js/SourceText.h>
#include <js/Symbol.h>
#include <Python.h>
#include <datetime.h>
typedef std::unordered_map<PyType *, std::vector<JS::PersistentRooted<JS::Value> *>>::iterator PyToGCIterator;
typedef struct {
PyObject_HEAD
} NullObject;
std::unordered_map<PyType *, std::vector<JS::PersistentRooted<JS::Value> *>> PyTypeToGCThing; /**< data structure to hold memoized PyObject & GCThing data for handling GC*/
static PyTypeObject NullType = {
.ob_base = PyVarObject_HEAD_INIT(NULL, 0)
.tp_name = "pythonmonkey.null",
.tp_basicsize = sizeof(NullObject),
.tp_flags = Py_TPFLAGS_DEFAULT,
.tp_doc = PyDoc_STR("Javascript null object"),
};
static PyTypeObject BigIntType = {
.tp_name = "pythonmonkey.bigint",
.tp_flags = Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_LONG_SUBCLASS // https://docs.python.org/3/c-api/typeobj.html#Py_TPFLAGS_LONG_SUBCLASS
| Py_TPFLAGS_BASETYPE, // can be subclassed
.tp_doc = PyDoc_STR("Javascript BigInt object"),
.tp_base = &PyLong_Type, // extending the builtin int type
};
static void cleanup() {
delete autoRealm;
delete global;
delete JOB_QUEUE;
if (GLOBAL_CX) JS_DestroyContext(GLOBAL_CX);
JS_ShutDown();
}
void memoizePyTypeAndGCThing(PyType *pyType, JS::Handle<JS::Value> GCThing) {
JS::PersistentRooted<JS::Value> *RootedGCThing = new JS::PersistentRooted<JS::Value>(GLOBAL_CX, GCThing);
PyToGCIterator pyIt = PyTypeToGCThing.find(pyType);
if (pyIt == PyTypeToGCThing.end()) { // if the PythonObject is not memoized
std::vector<JS::PersistentRooted<JS::Value> *> gcVector(
{{RootedGCThing}});
PyTypeToGCThing.insert({{pyType, gcVector}});
}
else {
pyIt->second.push_back(RootedGCThing);
}
}
void handleSharedPythonMonkeyMemory(JSContext *cx, JSGCStatus status, JS::GCReason reason, void *data) {
if (status == JSGCStatus::JSGC_BEGIN) {
PyToGCIterator pyIt = PyTypeToGCThing.begin();
while (pyIt != PyTypeToGCThing.end()) {
// If the PyObject reference count is exactly 1, then the only reference to the object is the one
// we are holding, which means the object is ready to be free'd.
if (PyObject_GC_IsFinalized(pyIt->first->getPyObject()) || pyIt->first->getPyObject()->ob_refcnt == 1) {
for (JS::PersistentRooted<JS::Value> *rval: pyIt->second) { // for each related GCThing
bool found = false;
for (PyToGCIterator innerPyIt = PyTypeToGCThing.begin(); innerPyIt != PyTypeToGCThing.end(); innerPyIt++) { // for each other PyType pointer
if (innerPyIt != pyIt && std::find(innerPyIt->second.begin(), innerPyIt->second.end(), rval) != innerPyIt->second.end()) { // if the PyType is also related to the GCThing
found = true;
break;
}
}
// if this PyObject is the last PyObject that references this GCThing, then the GCThing can also be free'd
if (!found) {
delete rval;
}
}
pyIt = PyTypeToGCThing.erase(pyIt);
}
else {
pyIt++;
}
}
}
};
static PyObject *collect(PyObject *self, PyObject *args) {
JS_GC(GLOBAL_CX);
Py_RETURN_NONE;
}
static PyObject *asUCS4(PyObject *self, PyObject *args) {
StrType *str = new StrType(PyTuple_GetItem(args, 0));
if (!PyUnicode_Check(str->getPyObject())) {
PyErr_SetString(PyExc_TypeError, "pythonmonkey.asUCS4 expects a string as its first argument");
return NULL;
}
return str->asUCS4();
}
static PyObject *eval(PyObject *self, PyObject *args) {
StrType *code = new StrType(PyTuple_GetItem(args, 0));
if (!PyUnicode_Check(code->getPyObject())) {
PyErr_SetString(PyExc_TypeError, "pythonmonkey.eval expects a string as its first argument");
return NULL;
}
JSAutoRealm ar(GLOBAL_CX, *global);
JS::CompileOptions options (GLOBAL_CX);
options.setFileAndLine("noname", 1);
// initialize JS context
JS::SourceText<mozilla::Utf8Unit> source;
if (!source.init(GLOBAL_CX, code->getValue(), strlen(code->getValue()), JS::SourceOwnership::Borrowed)) {
setSpiderMonkeyException(GLOBAL_CX);
return NULL;
}
delete code;
// evaluate source code
JS::PersistentRootedValue *rval = new JS::PersistentRootedValue(GLOBAL_CX);
if (!JS::Evaluate(GLOBAL_CX, options, source, rval)) {
setSpiderMonkeyException(GLOBAL_CX);
return NULL;
}
// translate to the proper python type
PyType *returnValue = pyTypeFactory(GLOBAL_CX, global, rval);
if (PyErr_Occurred()) {
return NULL;
}
// TODO: Find a better way to destroy the root when necessary (when the returned Python object is GCed).
// delete rval; // rval may be a JS function which must be kept alive.
if (returnValue) {
return returnValue->getPyObject();
}
else {
Py_RETURN_NONE;
}
}
PyMethodDef PythonMonkeyMethods[] = {
{"eval", eval, METH_VARARGS, "Javascript evaluator in Python"},
{"collect", collect, METH_VARARGS, "Calls the spidermonkey garbage collector"},
{"asUCS4", asUCS4, METH_VARARGS, "Expects a python string in UTF16 encoding, and returns a new equivalent string in UCS4. Undefined behaviour if the string is not in UTF16."},
{NULL, NULL, 0, NULL}
};
struct PyModuleDef pythonmonkey =
{
PyModuleDef_HEAD_INIT,
"pythonmonkey", /* name of module */
"A module for python to JS interoperability", /* module documentation, may be NULL */
-1, /* size of per-interpreter state of the module, or -1 if the module keeps state in global variables. */
PythonMonkeyMethods
};
PyObject *SpiderMonkeyError = NULL;
// Implement the `setTimeout` global function
// https://developer.mozilla.org/en-US/docs/Web/API/setTimeout
// https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-settimeout
static bool setTimeout(JSContext *cx, unsigned argc, JS::Value *vp) {
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
// Ensure the first parameter is a function
// We don't support passing a `code` string to `setTimeout` (yet)
JS::HandleValue jobArgVal = args.get(0);
bool jobArgIsFunction = jobArgVal.isObject() && js::IsFunctionObject(&jobArgVal.toObject());
if (!jobArgIsFunction) {
JS_ReportErrorNumberASCII(cx, nullptr, nullptr, JSErrNum::JSMSG_NOT_FUNCTION, "The first parameter to setTimeout()");
return false;
}
// Get the function to be executed
// FIXME (Tom Tang): memory leak, not free-ed
JS::RootedObject *thisv = new JS::RootedObject(cx, JS::GetNonCCWObjectGlobal(&args.callee())); // HTML spec requires `thisArg` to be the global object
JS::PersistentRootedValue *jobArg = new JS::PersistentRootedValue(cx, jobArgVal);
// `setTimeout` allows passing additional arguments to the callback, as spec-ed
if (args.length() > 2) { // having additional arguments
// Wrap the job function into a bound function with the given additional arguments
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
JS::RootedVector<JS::Value> bindArgs(cx);
bindArgs.append(JS::ObjectValue(**thisv));
for (size_t i = 1, j = 2; j < args.length(); j++) {
bindArgs.append(args[j]);
}
JS::RootedObject jobArgObj = JS::RootedObject(cx, &jobArgVal.toObject());
JS_CallFunctionName(cx, jobArgObj, "bind", JS::HandleValueArray(bindArgs), jobArg); // jobArg = jobArg.bind(thisv, ...bindArgs)
}
// Convert to a Python function
PyObject *job = pyTypeFactory(cx, thisv, jobArg)->getPyObject();
// Get the delay time
// JS `setTimeout` takes milliseconds, but Python takes seconds
double delayMs = 0; // use value of 0 if the delay parameter is omitted
if (args.hasDefined(1)) { JS::ToNumber(cx, args[1], &delayMs); } // implicitly do type coercion to a `number`
if (delayMs < 0) { delayMs = 0; } // as spec-ed
double delaySeconds = delayMs / 1000; // convert ms to s
// Schedule job to the running Python event-loop
PyEventLoop loop = PyEventLoop::getRunningLoop();
if (!loop.initialized()) return false;
PyEventLoop::AsyncHandle handle = loop.enqueueWithDelay(job, delaySeconds);
// Return the `timeoutID` to use in `clearTimeout`
args.rval().setDouble((double)PyEventLoop::AsyncHandle::getUniqueId(std::move(handle)));
return true;
}
// Implement the `clearTimeout` global function
// https://developer.mozilla.org/en-US/docs/Web/API/clearTimeout
// https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-cleartimeout
static bool clearTimeout(JSContext *cx, unsigned argc, JS::Value *vp) {
using AsyncHandle = PyEventLoop::AsyncHandle;
JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
JS::HandleValue timeoutIdArg = args.get(0);
args.rval().setUndefined();
// silently does nothing when an invalid timeoutID is passed in
if (!timeoutIdArg.isInt32()) {
return true;
}
// Retrieve the AsyncHandle by `timeoutID`
int32_t timeoutID = timeoutIdArg.toInt32();
AsyncHandle *handle = AsyncHandle::fromId((uint32_t)timeoutID);
if (!handle) return true; // does nothing on invalid timeoutID
// Cancel this job on Python event-loop
handle->cancel();
return true;
}
static JSFunctionSpec jsGlobalFunctions[] = {
JS_FN("setTimeout", setTimeout, /* nargs */ 2, 0),
JS_FN("clearTimeout", clearTimeout, 1, 0),
JS_FS_END
};
PyMODINIT_FUNC PyInit_pythonmonkey(void)
{
PyDateTime_IMPORT;
SpiderMonkeyError = PyErr_NewException("pythonmonkey.SpiderMonkeyError", NULL, NULL);
if (!JS_Init()) {
PyErr_SetString(SpiderMonkeyError, "Spidermonkey could not be initialized.");
return NULL;
}
Py_AtExit(cleanup);
GLOBAL_CX = JS_NewContext(JS::DefaultHeapMaxBytes);
if (!GLOBAL_CX) {
PyErr_SetString(SpiderMonkeyError, "Spidermonkey could not create a JS context.");
return NULL;
}
JOB_QUEUE = new JobQueue();
if (!JOB_QUEUE->init(GLOBAL_CX)) {
PyErr_SetString(SpiderMonkeyError, "Spidermonkey could not create the event-loop.");
return NULL;
}
if (!JS::InitSelfHostedCode(GLOBAL_CX)) {
PyErr_SetString(SpiderMonkeyError, "Spidermonkey could not initialize self-hosted code.");
return NULL;
}
JS::RealmOptions options;
static JSClass globalClass = {"global", JSCLASS_GLOBAL_FLAGS, &JS::DefaultGlobalClassOps};
global = new JS::RootedObject(GLOBAL_CX, JS_NewGlobalObject(GLOBAL_CX, &globalClass, nullptr, JS::FireOnNewGlobalHook, options));
if (!global) {
PyErr_SetString(SpiderMonkeyError, "Spidermonkey could not create a global object.");
return NULL;
}
autoRealm = new JSAutoRealm(GLOBAL_CX, *global);
if (!JS_DefineFunctions(GLOBAL_CX, *global, jsGlobalFunctions)) {
PyErr_SetString(SpiderMonkeyError, "Spidermonkey could not define global functions.");
return NULL;
}
JS_SetGCCallback(GLOBAL_CX, handleSharedPythonMonkeyMemory, NULL);
PyObject *pyModule;
if (PyType_Ready(&NullType) < 0)
return NULL;
if (PyType_Ready(&BigIntType) < 0)
return NULL;
pyModule = PyModule_Create(&pythonmonkey);
if (pyModule == NULL)
return NULL;
Py_INCREF(&NullType);
if (PyModule_AddObject(pyModule, "null", (PyObject *)&NullType) < 0) {
Py_DECREF(&NullType);
Py_DECREF(pyModule);
return NULL;
}
Py_INCREF(&BigIntType);
if (PyModule_AddObject(pyModule, "bigint", (PyObject *)&BigIntType) < 0) {
Py_DECREF(&BigIntType);
Py_DECREF(pyModule);
return NULL;
}
if (PyModule_AddObject(pyModule, "SpiderMonkeyError", SpiderMonkeyError)) {
Py_DECREF(pyModule);
return NULL;
}
return pyModule;
}