-
Notifications
You must be signed in to change notification settings - Fork 1
/
browsermodule.c
1182 lines (1056 loc) · 28.3 KB
/
browsermodule.c
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
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @file browsermodule.c
* @author rdb
* @date 2021-02-02
*/
#undef _POSIX_C_SOURCE
#undef _XOPEN_SOURCE
#define PY_SSIZE_T_CLEAN 1
#include "Python.h"
#include "structmember.h"
#include <emscripten/emscripten.h>
#include <stdbool.h>
/**
* emval interface, excerpted from emscripten/val.h (which is C++)
*/
typedef const void* TYPEID;
void _emval_register_symbol(const char*);
enum {
_EMVAL_UNDEFINED = 1,
_EMVAL_NULL = 2,
_EMVAL_TRUE = 3,
_EMVAL_FALSE = 4
};
typedef struct _EM_VAL* EM_VAL;
typedef struct _EM_DESTRUCTORS* EM_DESTRUCTORS;
typedef struct _EM_METHOD_CALLER* EM_METHOD_CALLER;
typedef double EM_GENERIC_WIRE_TYPE;
typedef const void* EM_VAR_ARGS;
void _emval_incref(EM_VAL value);
void _emval_decref(EM_VAL value);
void _emval_run_destructors(EM_DESTRUCTORS handle);
EM_VAL _emval_new_array();
EM_VAL _emval_new_object();
EM_VAL _emval_new_cstring(const char*);
EM_VAL _emval_take_value(TYPEID type, EM_VAR_ARGS argv);
EM_VAL _emval_new(
EM_VAL value,
unsigned argCount,
const TYPEID argTypes[],
EM_VAR_ARGS argv);
EM_VAL _emval_get_global(const char* name);
EM_VAL _emval_get_module_property(const char* name);
EM_VAL _emval_get_property(EM_VAL object, EM_VAL key);
void _emval_set_property(EM_VAL object, EM_VAL key, EM_VAL value);
EM_GENERIC_WIRE_TYPE _emval_as(EM_VAL value, TYPEID returnType, EM_DESTRUCTORS* destructors);
bool _emval_equals(EM_VAL first, EM_VAL second);
bool _emval_strictly_equals(EM_VAL first, EM_VAL second);
bool _emval_greater_than(EM_VAL first, EM_VAL second);
bool _emval_less_than(EM_VAL first, EM_VAL second);
bool _emval_not(EM_VAL object);
EM_VAL _emval_call(
EM_VAL value,
unsigned argCount,
const TYPEID argTypes[],
EM_VAR_ARGS argv);
// DO NOT call this more than once per signature. It will
// leak generated function objects!
EM_METHOD_CALLER _emval_get_method_caller(
unsigned argCount, // including return value
const TYPEID argTypes[]);
EM_GENERIC_WIRE_TYPE _emval_call_method(
EM_METHOD_CALLER caller,
EM_VAL handle,
const char* methodName,
EM_DESTRUCTORS* destructors,
EM_VAR_ARGS argv);
void _emval_call_void_method(
EM_METHOD_CALLER caller,
EM_VAL handle,
const char* methodName,
EM_VAR_ARGS argv);
EM_VAL _emval_typeof(EM_VAL value);
bool _emval_instanceof(EM_VAL object, EM_VAL constructor);
bool _emval_is_number(EM_VAL object);
bool _emval_is_string(EM_VAL object);
bool _emval_in(EM_VAL item, EM_VAL object);
bool _emval_delete(EM_VAL object, EM_VAL property);
bool _emval_throw(EM_VAL object);
EM_VAL _emval_await(EM_VAL promise);
/**
* Forward declarations.
*/
static EM_VAL py_to_emval(PyObject *val);
static PyObject *emval_to_py(EM_VAL val);
static PyTypeObject Object_Type;
static PyTypeObject Function_Type;
static PyTypeObject Symbol_Type;
static int _next_callback_id = 0;
typedef struct {
PyObject_HEAD
EM_VAL result; // 0 = pending, positive = result, negative = exception
char asyncio_future_blocking;
} PromiseWrapper;
typedef struct {
PyObject_HEAD
EM_VAL handle;
} Object;
typedef struct {
PyObject_HEAD
EM_VAL handle;
EM_VAL bound;
} Function;
typedef Object Symbol;
/**
* Decrements refcount of this PromiseWrapper.
*/
static void
PromiseWrapper_dealloc(PromiseWrapper *self) {
if (self->result != NULL) {
_emval_decref((EM_VAL)abs((int)self->result));
}
Py_TYPE(self)->tp_free((PyObject *)self);
}
/**
* Implements done().
*/
static PyObject *
PromiseWrapper_done(PromiseWrapper *self, PyObject *noarg) {
return PyBool_FromLong(self->result != NULL);
}
/**
* Implements cancelled().
*/
static PyObject *
PromiseWrapper_cancelled(PromiseWrapper *self, PyObject *noarg) {
Py_INCREF(Py_False);
return Py_False;
}
/**
* Implements result().
*/
static PyObject *
PromiseWrapper_result(PromiseWrapper *self, PyObject *noarg) {
if (self->result == NULL) {
PyErr_SetString(PyExc_Exception, "Still pending.");
return NULL;
}
_emval_incref((EM_VAL)abs((int)self->result));
return emval_to_py(self->result);
}
/**
* Implements iter() and await.
*/
static PyObject *
PromiseWrapper_iter(PyObject *self) {
Py_INCREF(self);
return self;
}
/**
* Implements next().
*/
static PyObject *
PromiseWrapper_next(PromiseWrapper *self) {
if (self->result == NULL) {
Py_INCREF(self);
return (PyObject *)self;
}
else {
_emval_incref((EM_VAL)abs((int)self->result));
PyObject *result = emval_to_py(self->result);
if (result != NULL) {
PyErr_SetObject(PyExc_StopIteration, result);
Py_DECREF(result);
}
return NULL;
}
}
/**
* Defines future wrapper.
*/
static PyAsyncMethods PromiseWrapper_async = {
.am_await = (unaryfunc)PromiseWrapper_iter,
};
static PyMethodDef PromiseWrapper_methods[] = {
{ "done", (PyCFunction)PromiseWrapper_done, METH_NOARGS },
{ "cancelled", (PyCFunction)PromiseWrapper_cancelled, METH_NOARGS },
{ "result", (PyCFunction)PromiseWrapper_result, METH_NOARGS },
{ NULL, NULL, 0 }
};
static PyMemberDef PromiseWrapper_members[] = {
{ "_asyncio_future_blocking", T_BOOL, offsetof(PromiseWrapper, asyncio_future_blocking), 0 },
{ NULL }
};
static PyTypeObject PromiseWrapper_Type = {
PyVarObject_HEAD_INIT(NULL, 0)
.tp_name = "browser.PromiseWrapper",
.tp_doc = "JavaScript Promise wrapper",
.tp_basicsize = sizeof(PromiseWrapper),
.tp_itemsize = 0,
.tp_flags = Py_TPFLAGS_DEFAULT,
.tp_dealloc = (destructor)PromiseWrapper_dealloc,
.tp_as_async = &PromiseWrapper_async,
.tp_iter = (getiterfunc)PromiseWrapper_iter,
.tp_iternext = (iternextfunc)PromiseWrapper_next,
.tp_methods = PromiseWrapper_methods,
.tp_members = PromiseWrapper_members,
.tp_new = PyType_GenericNew,
};
/**
* Sets promise wrapper result.
*/
void EMSCRIPTEN_KEEPALIVE
_py_notify_done(PromiseWrapper *wrapper, EM_VAL result_handle) {
if (wrapper->result == NULL && result_handle != NULL) {
wrapper->result = result_handle;
Py_DECREF(wrapper);
}
}
/**
* Decrements refcount of this Object.
*/
static void
Object_dealloc(Object *self) {
_emval_decref(self->handle);
Py_TYPE(self)->tp_free((PyObject *)self);
}
/**
* Implements await.
*/
static PyObject *
Object_await(Object *self) {
// Note that all JS objects are awaitable. Non-thenables simply return a
// resolved promise with the value already set.
PromiseWrapper *wrapper = PyObject_New(PromiseWrapper, &PromiseWrapper_Type);
wrapper->asyncio_future_blocking = 0;
wrapper->result = (EM_VAL)EM_ASM_INT({
var value = Emval.toValue($0);
if (value && typeof value.then === "function") {
value.then(function (result) {
__py_notify_done($1, Emval.toHandle(result));
}, function (error) {
__py_notify_done($1, -Emval.toHandle(error));
});
return 0;
}
else {
// Already done, return the result.
__emval_incref($0);
return $0;
}
}, self->handle, wrapper);
if (wrapper->result == NULL) {
// This is decreffed by _py_notify_done.
Py_INCREF(wrapper);
}
return (PyObject *)wrapper;
}
/**
* Returns a string representation of the object.
*/
static PyObject *
Object_repr(Object *self) {
char *str = (char *)EM_ASM_INT({
var value = Emval.toValue($0);
var str = value.constructor ? value.constructor.name : 'Object';
var len = lengthBytesUTF8(str) + 1;
var buffer = _malloc(len);
stringToUTF8(str, buffer, len);
return buffer;
}, self->handle);
PyObject *result = PyUnicode_FromFormat("[object %s]", str);
free(str);
return result;
}
/**
* Hash function.
*/
static Py_hash_t
Object_hash(Object *self) {
return (Py_hash_t)self->handle;
}
/**
* Returns a string representation of the object.
*/
static PyObject *
Object_str(Object *self) {
char *str = (char *)EM_ASM_INT({
var str = Emval.toValue($0).toString();
var len = lengthBytesUTF8(str) + 1;
var buffer = _malloc(len);
stringToUTF8(str, buffer, len);
return buffer;
}, self->handle);
PyObject *result = PyUnicode_FromString(str);
free(str);
return result;
}
/**
* Implements len().
*/
static Py_ssize_t
Object_length(Object *self) {
int len = EM_ASM_INT({
var val = Emval.toValue($0);
if (val[Symbol.iterator] && val.length !== undefined) {
return val.length;
}
else {
return -1;
}
}, self->handle);
if (len >= 0) {
return len;
}
else {
PyErr_SetString(PyExc_TypeError, "object has no len()");
return -1;
}
}
/**
* Gets a property of this object.
*/
static PyObject *
Object_getprop(Object *self, PyObject *item) {
EM_VAL key_handle = py_to_emval(item);
if (key_handle == NULL) {
return NULL;
}
EM_VAL result = (EM_VAL)EM_ASM_INT({
try {
return Emval.toHandle(Emval.toValue($0)[Emval.toValue($1)]);
}
catch (ex) {
return -Emval.toHandle(ex);
}
finally {
__emval_decref($1);
}
}, self->handle, key_handle);
PyObject *obj = emval_to_py(result);
if (obj != NULL && Py_TYPE(obj) == &Function_Type) {
// Remember self, so that we can make bound method calls.
_emval_incref(self->handle);
((Function *)obj)->bound = self->handle;
}
return obj;
}
/**
* Sets a property of this object.
*/
static int
Object_setprop(Object *self, PyObject *item, PyObject *value) {
EM_VAL key_handle = py_to_emval(item);
if (key_handle == NULL) {
return -1;
}
if (value != NULL) {
EM_VAL value_val = py_to_emval(value);
if (value_val == NULL) {
return -1;
}
_emval_set_property(self->handle, key_handle, value_val);
_emval_decref(value_val);
}
else {
if (!_emval_delete(self->handle, key_handle)) {
//_emval_decref(key_handle);
//return -1;
}
}
_emval_decref(key_handle);
return 0;
}
/**
* Comparison.
*/
static PyObject *
Object_richcompare(Object *self, PyObject *other, int op) {
EM_VAL other_handle = py_to_emval(other);
if (other_handle == NULL) {
PyErr_Clear();
Py_INCREF(Py_NotImplemented);
return Py_NotImplemented;
}
switch (op) {
case Py_LT:
return PyBool_FromLong(_emval_less_than(self->handle, other_handle));
case Py_LE:
return PyBool_FromLong(!_emval_greater_than(self->handle, other_handle));
case Py_EQ:
return PyBool_FromLong(self->handle == other_handle ||
_emval_strictly_equals(self->handle, other_handle));
case Py_NE:
return PyBool_FromLong(self->handle != other_handle &&
!_emval_strictly_equals(self->handle, other_handle));
case Py_GT:
return PyBool_FromLong(_emval_greater_than(self->handle, other_handle));
case Py_GE:
return PyBool_FromLong(!_emval_less_than(self->handle, other_handle));
}
return NULL;
}
/**
* Implements iter().
*/
static PyObject *
Object_iter(Object *self) {
EM_VAL val = (EM_VAL)EM_ASM_INT({
var val = Emval.toValue($0);
if (val[Symbol.iterator]) {
return Emval.toHandle(val[Symbol.iterator]());
} else {
return 0;
}
}, self->handle);
if (val == self->handle) {
// Common case, don't create a new wrapper.
Py_INCREF(self);
return (PyObject *)self;
}
else if (val != NULL) {
return emval_to_py(val);
}
else {
PyErr_SetString(PyExc_TypeError, "object has no iter()");
return NULL;
}
}
/**
* Implements next().
*/
static PyObject *
Object_next(Object *self) {
EM_VAL val = (EM_VAL)EM_ASM_INT({
var val = Emval.toValue($0);
if (!val.next) {
return 0;
}
var result = val.next();
if (result && !result.done) {
return Emval.toHandle(result.value);
} else {
return 0;
}
}, self->handle);
if (val != NULL) {
return emval_to_py(val);
}
else {
return NULL;
}
}
/**
* Implements dir().
*/
static PyObject *
Object_dir(Object *self, PyObject *noarg) {
return emval_to_py((EM_VAL)EM_ASM_INT({
var props = [];
for (var prop in Emval.toValue($0)) {
props.push(prop);
}
return Emval.toHandle(props);
}, self->handle));
}
static PyAsyncMethods Object_async = {
.am_await = (unaryfunc)Object_await,
};
static PyMappingMethods Object_mapping = {
.mp_length = (lenfunc)Object_length,
.mp_subscript = (binaryfunc)Object_getprop,
.mp_ass_subscript = (objobjargproc)Object_setprop,
};
static PyMethodDef Object_methods[] = {
{ "__dir__", (PyCFunction)Object_dir, METH_NOARGS },
{ NULL, NULL },
};
static PyTypeObject Object_Type = {
PyVarObject_HEAD_INIT(NULL, 0)
.tp_name = "browser.Object",
.tp_doc = "JavaScript object",
.tp_basicsize = sizeof(Object),
.tp_itemsize = 0,
.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
.tp_dealloc = (destructor)Object_dealloc,
.tp_as_async = &Object_async,
.tp_repr = (reprfunc)Object_repr,
.tp_as_mapping = &Object_mapping,
.tp_hash = (hashfunc)Object_hash,
.tp_str = (reprfunc)Object_str,
.tp_getattro = (getattrofunc)Object_getprop,
.tp_setattro = (setattrofunc)Object_setprop,
.tp_richcompare = (richcmpfunc)Object_richcompare,
.tp_iter = (getiterfunc)Object_iter,
.tp_iternext = (iternextfunc)Object_next,
.tp_methods = Object_methods,
.tp_new = PyType_GenericNew,
};
/**
* Decrements refcount of this Function.
*/
static void
Function_dealloc(Function *self) {
_emval_decref(self->handle);
if (self->bound != (EM_VAL)_EMVAL_UNDEFINED) {
_emval_decref(self->bound);
}
Py_TYPE(self)->tp_free((PyObject *)self);
}
/**
* Calls the object.
*/
static PyObject *
Function_call(Function *self, PyObject *args, PyObject *kwargs) {
if (kwargs != NULL && PyDict_Size(kwargs) > 0) {
PyErr_SetString(PyExc_TypeError, "__call__() takes no keyword arguments");
return NULL;
}
EM_VAL result;
// emval has no elegant call interface, so we add it ourselves. Make more
// optimal special cases for 0 and 1 args.
int num_args = PyTuple_GET_SIZE(args);
switch (num_args) {
case 0:
result = (EM_VAL)EM_ASM_INT({
try {
return Emval.toHandle(Emval.toValue($0).call(Emval.toValue($1)));
}
catch (ex) {
return -Emval.toHandle(ex);
}}, self->handle, self->bound);
break;
case 1:
{
EM_VAL arg_handle = py_to_emval(PyTuple_GET_ITEM(args, 0));
if (arg_handle == NULL) {
return NULL;
}
result = (EM_VAL)EM_ASM_INT({
try {
return Emval.toHandle(Emval.toValue($0).call(Emval.toValue($1), Emval.toValue($2)));
}
catch (ex) {
return -Emval.toHandle(ex);
}
finally {
__emval_decref($2);
}
}, self->handle, self->bound, arg_handle);
}
break;
default:
{
EM_VAL *arg_handles = (EM_VAL *)alloca(num_args * sizeof(EM_VAL));
for (int i = 0; i < num_args; ++i) {
EM_VAL handle = py_to_emval(PyTuple_GET_ITEM(args, i));
if (handle == NULL) {
while (--i >= 0) {
_emval_decref(arg_handles[i]);
}
return NULL;
}
arg_handles[i] = handle;
}
result = (EM_VAL)EM_ASM_INT({
var arg_handles = [];
try {
var arg_values = [];
for (var i = 0; i < $2; ++i) {
var arg_handle = getValue($3+i*4, '*');
arg_handles.push(arg_handle);
arg_values.push(Emval.toValue(arg_handle));
}
return Emval.toHandle(Emval.toValue($0).apply(Emval.toValue($1), arg_values));
}
catch (ex) {
return -Emval.toHandle(ex);
}
finally {
for (var i = 0; i < $2; ++i) {
__emval_decref(arg_handles[i]);
}
}
}, self->handle, self->bound, num_args, arg_handles);
}
break;
}
return emval_to_py(result);
}
/**
* Subclass for functions.
*/
static PyTypeObject Function_Type = {
PyVarObject_HEAD_INIT(NULL, 0)
.tp_name = "browser.Function",
.tp_doc = "JavaScript function",
.tp_basicsize = sizeof(Function),
.tp_itemsize = 0,
.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
.tp_dealloc = (destructor)Function_dealloc,
.tp_call = (ternaryfunc)Function_call,
.tp_base = &Object_Type,
};
/**
* obj.description is the only property that Symbol exports.
*/
static PyObject *
Symbol_description(Symbol *self, void *unused) {
char *str = (char *)EM_ASM_INT({
var str = Emval.toValue($0).description;
var len = lengthBytesUTF8(str) + 1;
var buffer = _malloc(len);
stringToUTF8(str, buffer, len);
return buffer;
}, self->handle);
PyObject *result = PyUnicode_FromString(str);
free(str);
return result;
}
static PyGetSetDef Symbol_getset[] = {
{ "description", (getter)Symbol_description, NULL, NULL, NULL },
{ NULL, NULL, NULL, NULL, NULL }
};
/**
* Wraps around the JavaScript Symbol type. Does not derive from Object, even
* though it uses the same struct!
*/
static PyTypeObject Symbol_Type = {
PyVarObject_HEAD_INIT(NULL, 0)
.tp_name = "browser.Symbol",
.tp_doc = "JavaScript symbol",
.tp_basicsize = sizeof(Object),
.tp_itemsize = 0,
.tp_flags = Py_TPFLAGS_DEFAULT,
.tp_dealloc = (destructor)Object_dealloc,
.tp_repr = (reprfunc)Object_repr,
.tp_hash = (hashfunc)Object_hash,
.tp_str = (reprfunc)Object_str,
.tp_richcompare = (richcmpfunc)Object_richcompare,
.tp_getset = Symbol_getset,
.tp_new = PyType_GenericNew,
};
/**
* Calls a Python method from C. Frees given argv pointer.
*/
EM_VAL EMSCRIPTEN_KEEPALIVE
_py_call(PyObject *func, PyObject *self, EM_VAL this_handle, int argc, EM_VAL *argv) {
PyObject *args;
if (self != NULL) {
args = PyTuple_New(argc + 1);
PyTuple_SET_ITEM(args, 0, self);
Py_INCREF(self);
for (int i = 0; i < argc; ++i) {
PyTuple_SET_ITEM(args, i + 1, emval_to_py(argv[i]));
}
}
else {
args = PyTuple_New(argc);
for (int i = 0; i < argc; ++i) {
PyTuple_SET_ITEM(args, i, emval_to_py(argv[i]));
}
}
free(argv);
// Store the old "this" from the globals object.
PyObject *globals = PyFunction_GET_GLOBALS(func);
PyObject *old_this = PyDict_GetItemString(globals, "this");
Py_XINCREF(old_this);
// Replace it with the new one.
PyObject *this = emval_to_py(this_handle);
PyDict_SetItemString(globals, "this", this);
Py_DECREF(this);
PyObject *result = PyObject_Call(func, args, NULL);
Py_DECREF(args);
EM_VAL result_handle = (EM_VAL)_EMVAL_UNDEFINED;
if (result == NULL) {
PyErr_Print();
}
else {
if (result != Py_None) {
result_handle = py_to_emval(result);
}
Py_DECREF(result);
}
// Put back the old "this" object.
if (old_this != NULL) {
PyDict_SetItemString(globals, "this", old_this);
Py_DECREF(old_this);
}
else {
PyDict_DelItemString(globals, "this");
}
return result_handle;
}
/**
* Unregisters the given callback with JavaScript.
*/
static PyObject *
py_callback_destructor(PyObject *handle, PyObject *weakref) {
int id = PyLong_AsLong(handle);
EM_ASM(__py_alive.delete($0), id);
Py_DECREF(weakref);
Py_INCREF(Py_None);
return Py_None;
}
static PyMethodDef py_callback_destructor_def = {
"__callback__", &py_callback_destructor, METH_O
};
/**
* Returns the given Python object as emval.
*/
static EM_VAL py_to_emval(PyObject *val) {
if (val == Py_None) {
return (EM_VAL)_EMVAL_NULL;
}
else if (val == Py_True) {
return (EM_VAL)_EMVAL_TRUE;
}
else if (val == Py_False) {
return (EM_VAL)_EMVAL_FALSE;
}
else if (Py_TYPE(val) == &Object_Type ||
Py_TYPE(val) == &Function_Type ||
Py_TYPE(val) == &Symbol_Type) {
EM_VAL handle = ((Object *)val)->handle;
_emval_incref(handle);
return handle;
}
else if (PyFloat_Check(val)) {
return (EM_VAL)EM_ASM_INT(return Emval.toHandle($0), PyFloat_AsDouble(val));
}
else if (PyLong_Check(val)) {
return (EM_VAL)EM_ASM_INT(return Emval.toHandle($0), PyLong_AsLong(val));
}
else if (PyUnicode_Check(val)) {
return _emval_new_cstring(PyUnicode_AsUTF8(val));
}
else if (PyFunction_Check(val) || PyMethod_Check(val)) {
PyObject *func = val;
PyObject *self = NULL;
if (PyMethod_Check(val)) {
func = PyMethod_GET_FUNCTION(val);
self = PyMethod_GET_SELF(val);
}
// Allocate a function ID, which we use to identify this this function, to
// determine whether it is still alive in the Python interpreter.
int callback_id = _next_callback_id++;
PyObject *id_obj = PyLong_FromLong(callback_id);
// Register a callback that gets invoked when either the "func" or "self"
// objects go away, which marks them as no longer being alive.
PyObject *callback = PyCFunction_New(&py_callback_destructor_def, id_obj);
PyWeakref_NewRef(func, callback);
if (self != NULL) {
PyWeakref_NewRef(self, callback);
}
Py_DECREF(id_obj);
Py_DECREF(callback);
// Like in JS, extraneous arguments should be ignored, so we need to check how
// many arguments this function actually takes.
int max_args = -1;
PyCodeObject *code = (PyCodeObject *)PyFunction_GET_CODE(func);
if ((code->co_flags & CO_VARARGS) == 0) {
max_args = code->co_argcount;
if (self != NULL) {
--max_args;
}
}
return (EM_VAL)EM_ASM_INT({
__py_alive.add($0);
return Emval.toHandle(function() {
if (__py_alive.has($0)) {
var argc = arguments.length;
if ($3 >= 0 && argc > $3) {
argc = $3;
}
var argv = _malloc(argc * 4);
for (var i = 0; i < argc; ++i) {
setValue(argv+i*4, Emval.toHandle(arguments[i]), 'i32');
}
var result = __py_call($1, $2, Emval.toHandle(this), argc, argv);
return Emval.toValue(result);
}
});
}, callback_id, func, self, max_args);
}
else {
return (EM_VAL)PyErr_Format(PyExc_TypeError,
"object of type '%002s' cannot be converted to JavaScript",
Py_TYPE(val)->tp_name);
}
}
/**
* And the other way around. Steals a reference to handle.
*/
static PyObject *emval_to_py(EM_VAL handle) {
if (handle == (EM_VAL)_EMVAL_TRUE) {
Py_INCREF(Py_True);
return Py_True;
}
if (handle == (EM_VAL)_EMVAL_FALSE) {
Py_INCREF(Py_False);
return Py_False;
}
if (handle == (EM_VAL)_EMVAL_UNDEFINED || handle == (EM_VAL)_EMVAL_NULL) {
Py_INCREF(Py_None);
return Py_None;
}
// We use a negative handle to raise an exception from JavaScript to Python.
if ((int)handle < 0) {
handle = (EM_VAL)-(int)handle;
char message[512];
message[0] = 0;
// Extract the message and the exception type.
int type = EM_ASM_INT({
var exc = Emval.toValue($0);
try {
if (exc.message) {
stringToUTF8(exc.message, $1, 512);
}
if (exc instanceof TypeError) {
return 1;
}
if (exc instanceof SyntaxError) {
return 2;
}
return 0;
}
finally {
__emval_decref($0);
}
}, handle, message);
PyObject *exc_type;
switch (type) {
case 1:
exc_type = PyExc_TypeError;
break;
case 2:
exc_type = PyExc_SyntaxError;
break;
default:
exc_type = PyExc_Exception;
break;
}
PyErr_SetString(exc_type, message);
return NULL;
}
// Get the type and value in one JS call.
union {
int _integer;
double _number;
char *_str;
} target;
int type = EM_ASM_INT(({
var value = Emval.toValue($0);
var type = typeof value;
if (type === "number") {
// Check whether it fits in an int.
if ((value | 0) === value) {
setValue($1, value, "i32");
__emval_decref($0);
return 1;
}
else {
setValue($1, value, "double");
__emval_decref($0);
return 2;
}
}
else if (type === "string") {
var len = lengthBytesUTF8(value) + 1;
var buffer = _malloc(len);
stringToUTF8(value, buffer, len);
__emval_decref($0);
setValue($1, buffer, "*");
return 3;
}
else if (type === "function") {
return 4;
}
else if (type === "symbol") {
return 5;
}
else { // object
return 6;
}
}), handle, &target);
switch (type) {
case 1: // integer
return PyLong_FromLong(target._integer);
case 2: // number
return PyFloat_FromDouble(target._number);
case 3: // string
{
PyObject *result = PyUnicode_FromString(target._str);
free(target._str);
return result;
}
case 4: // function
{
Function *obj = PyObject_New(Function, &Function_Type);
obj->handle = handle;
obj->bound = (EM_VAL)_EMVAL_UNDEFINED;
return (PyObject *)obj;
}