-
Notifications
You must be signed in to change notification settings - Fork 3.3k
/
Copy pathembind.js
2429 lines (2182 loc) · 88.4 KB
/
embind.js
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
// Copyright 2012 The Emscripten Authors. All rights reserved.
// Emscripten is available under two separate licenses, the MIT license and the
// University of Illinois/NCSA Open Source License. Both these licenses can be
// found in the LICENSE file.
/*global addToLibrary*/
/*global Module, asm*/
/*global _malloc, _free, _memcpy*/
/*global FUNCTION_TABLE, HEAP8, HEAPU8, HEAP16, HEAPU16, HEAP32, HEAPU32, HEAPF32, HEAPF64*/
/*global readLatin1String*/
/*global Emval, emval_handle_array, __emval_decref*/
/*jslint sub:true*/ /* The symbols 'fromWireType' and 'toWireType' must be accessed via array notation to be closure-safe since craftInvokerFunction crafts functions as strings that can't be closured. */
// -- jshint doesn't understand library syntax, so we need to specifically tell it about the symbols we define
/*global typeDependencies, flushPendingDeletes, getTypeName, getBasestPointer, throwBindingError, UnboundTypeError, embindRepr, registeredInstances, registeredTypes*/
/*global ensureOverloadTable, embind__requireFunction, awaitingDependencies, makeLegalFunctionName, embind_charCodes:true, registerType, createNamedFunction, RegisteredPointer, throwInternalError*/
/*global simpleReadValueFromPointer, floatReadValueFromPointer, integerReadValueFromPointer, enumReadValueFromPointer, replacePublicSymbol, craftInvokerFunction, tupleRegistrations*/
/*global finalizationRegistry, attachFinalizer, detachFinalizer, releaseClassHandle, runDestructor*/
/*global ClassHandle, makeClassHandle, structRegistrations, whenDependentTypesAreResolved, BindingError, deletionQueue, delayFunction:true, upcastPointer*/
/*global exposePublicSymbol, heap32VectorToArray, newFunc, char_0, char_9*/
/*global getInheritedInstanceCount, getLiveInheritedInstances, setDelayFunction, InternalError, runDestructors*/
/*global requireRegisteredType, unregisterInheritedInstance, registerInheritedInstance, PureVirtualError, throwUnboundTypeError*/
/*global assert, validateThis, downcastPointer, registeredPointers, RegisteredClass, getInheritedInstance */
/*global throwInstanceAlreadyDeleted, shallowCopyInternalPointer*/
/*global RegisteredPointer_fromWireType, constNoSmartPtrRawPointerToWireType, nonConstNoSmartPtrRawPointerToWireType, genericPointerToWireType*/
#include "embind/embind_shared.js"
var LibraryEmbind = {
$UnboundTypeError__postset: "UnboundTypeError = Module['UnboundTypeError'] = extendError(Error, 'UnboundTypeError');",
$UnboundTypeError__deps: ['$extendError'],
$UnboundTypeError: undefined,
$PureVirtualError__postset: "PureVirtualError = Module['PureVirtualError'] = extendError(Error, 'PureVirtualError');",
$PureVirtualError__deps: ['$extendError'],
$PureVirtualError: undefined,
$GenericWireTypeSize: {{{ 2 * POINTER_SIZE }}},
$init_embind__deps: [
'$getInheritedInstanceCount', '$getLiveInheritedInstances',
'$flushPendingDeletes', '$setDelayFunction'],
$init_embind__postset: 'init_embind();',
$init_embind: () => {
Module['getInheritedInstanceCount'] = getInheritedInstanceCount;
Module['getLiveInheritedInstances'] = getLiveInheritedInstances;
Module['flushPendingDeletes'] = flushPendingDeletes;
Module['setDelayFunction'] = setDelayFunction;
},
$throwUnboundTypeError__deps: ['$registeredTypes', '$typeDependencies', '$UnboundTypeError', '$getTypeName'],
$throwUnboundTypeError: (message, types) => {
var unboundTypes = [];
var seen = {};
function visit(type) {
if (seen[type]) {
return;
}
if (registeredTypes[type]) {
return;
}
if (typeDependencies[type]) {
typeDependencies[type].forEach(visit);
return;
}
unboundTypes.push(type);
seen[type] = true;
}
types.forEach(visit);
throw new UnboundTypeError(`${message}: ` + unboundTypes.map(getTypeName).join([', ']));
},
// Creates a function overload resolution table to the given method 'methodName' in the given prototype,
// if the overload table doesn't yet exist.
$ensureOverloadTable__deps: ['$throwBindingError'],
$ensureOverloadTable: (proto, methodName, humanName) => {
if (undefined === proto[methodName].overloadTable) {
var prevFunc = proto[methodName];
// Inject an overload resolver function that routes to the appropriate overload based on the number of arguments.
proto[methodName] = function() {
// TODO This check can be removed in -O3 level "unsafe" optimizations.
if (!proto[methodName].overloadTable.hasOwnProperty(arguments.length)) {
throwBindingError(`Function '${humanName}' called with an invalid number of arguments (${arguments.length}) - expects one of (${proto[methodName].overloadTable})!`);
}
return proto[methodName].overloadTable[arguments.length].apply(this, arguments);
};
// Move the previous function into the overload table.
proto[methodName].overloadTable = [];
proto[methodName].overloadTable[prevFunc.argCount] = prevFunc;
}
},
/*
Registers a symbol (function, class, enum, ...) as part of the Module JS object so that
hand-written code is able to access that symbol via 'Module.name'.
name: The name of the symbol that's being exposed.
value: The object itself to expose (function, class, ...)
numArguments: For functions, specifies the number of arguments the function takes in. For other types, unused and undefined.
To implement support for multiple overloads of a function, an 'overload selector' function is used. That selector function chooses
the appropriate overload to call from an function overload table. This selector function is only used if multiple overloads are
actually registered, since it carries a slight performance penalty. */
$exposePublicSymbol__deps: ['$ensureOverloadTable', '$throwBindingError'],
$exposePublicSymbol__docs: '/** @param {number=} numArguments */',
$exposePublicSymbol: (name, value, numArguments) => {
if (Module.hasOwnProperty(name)) {
if (undefined === numArguments || (undefined !== Module[name].overloadTable && undefined !== Module[name].overloadTable[numArguments])) {
throwBindingError(`Cannot register public name '${name}' twice`);
}
// We are exposing a function with the same name as an existing function. Create an overload table and a function selector
// that routes between the two.
ensureOverloadTable(Module, name, name);
if (Module.hasOwnProperty(numArguments)) {
throwBindingError(`Cannot register multiple overloads of a function with the same number of arguments (${numArguments})!`);
}
// Add the new function into the overload table.
Module[name].overloadTable[numArguments] = value;
}
else {
Module[name] = value;
if (undefined !== numArguments) {
Module[name].numArguments = numArguments;
}
}
},
$replacePublicSymbol__deps: ['$throwInternalError'],
$replacePublicSymbol__docs: '/** @param {number=} numArguments */',
$replacePublicSymbol: (name, value, numArguments) => {
if (!Module.hasOwnProperty(name)) {
throwInternalError('Replacing nonexistant public symbol');
}
// If there's an overload table for this symbol, replace the symbol in the overload table instead.
if (undefined !== Module[name].overloadTable && undefined !== numArguments) {
Module[name].overloadTable[numArguments] = value;
}
else {
Module[name] = value;
Module[name].argCount = numArguments;
}
},
// from https://github.com/imvu/imvujs/blob/master/src/error.js
$extendError__deps: ['$createNamedFunction'],
$extendError: (baseErrorType, errorName) => {
var errorClass = createNamedFunction(errorName, function(message) {
this.name = errorName;
this.message = message;
var stack = (new Error(message)).stack;
if (stack !== undefined) {
this.stack = this.toString() + '\n' +
stack.replace(/^Error(:[^\n]*)?\n/, '');
}
});
errorClass.prototype = Object.create(baseErrorType.prototype);
errorClass.prototype.constructor = errorClass;
errorClass.prototype.toString = function() {
if (this.message === undefined) {
return this.name;
} else {
return `${this.name}: ${this.message}`;
}
};
return errorClass;
},
$createNamedFunction: (name, body) => Object.defineProperty(body, 'name', {
value: name
}),
// All browsers that support WebAssembly also support configurable function name,
// but we might be building for very old browsers via WASM2JS.
#if MIN_CHROME_VERSION < 43 || MIN_EDGE_VERSION < 14 || MIN_SAFARI_VERSION < 100101 || MIN_FIREFOX_VERSION < 38
// In that case, check if configurable function name is supported at init time
// and, if not, replace with a fallback that returns function as-is as those browsers
// don't support other methods either.
$createNamedFunction__postset: `
if (!Object.getOwnPropertyDescriptor(Function.prototype, 'name').configurable) {
createNamedFunction = (name, body) => body;
}
`,
#endif
$embindRepr: (v) => {
if (v === null) {
return 'null';
}
var t = typeof v;
if (t === 'object' || t === 'array' || t === 'function') {
return v.toString();
} else {
return '' + v;
}
},
// raw pointer -> instance
$registeredInstances__deps: ['$init_embind'],
$registeredInstances: {},
$getBasestPointer__deps: ['$throwBindingError'],
$getBasestPointer: (class_, ptr) => {
if (ptr === undefined) {
throwBindingError('ptr should not be undefined');
}
while (class_.baseClass) {
ptr = class_.upcast(ptr);
class_ = class_.baseClass;
}
return ptr;
},
$registerInheritedInstance__deps: ['$registeredInstances', '$getBasestPointer', '$throwBindingError'],
$registerInheritedInstance: (class_, ptr, instance) => {
ptr = getBasestPointer(class_, ptr);
if (registeredInstances.hasOwnProperty(ptr)) {
throwBindingError(`Tried to register registered instance: ${ptr}`);
} else {
registeredInstances[ptr] = instance;
}
},
$unregisterInheritedInstance__deps: ['$registeredInstances', '$getBasestPointer', '$throwBindingError'],
$unregisterInheritedInstance: (class_, ptr) => {
ptr = getBasestPointer(class_, ptr);
if (registeredInstances.hasOwnProperty(ptr)) {
delete registeredInstances[ptr];
} else {
throwBindingError(`Tried to unregister unregistered instance: ${ptr}`);
}
},
$getInheritedInstance__deps: ['$registeredInstances', '$getBasestPointer'],
$getInheritedInstance: (class_, ptr) => {
ptr = getBasestPointer(class_, ptr);
return registeredInstances[ptr];
},
$getInheritedInstanceCount__deps: ['$registeredInstances'],
$getInheritedInstanceCount: () => Object.keys(registeredInstances).length,
$getLiveInheritedInstances__deps: ['$registeredInstances'],
$getLiveInheritedInstances: () => {
var rv = [];
for (var k in registeredInstances) {
if (registeredInstances.hasOwnProperty(k)) {
rv.push(registeredInstances[k]);
}
}
return rv;
},
// class typeID -> {pointerType: ..., constPointerType: ...}
$registeredPointers: {},
$registerType__deps: ['$sharedRegisterType'],
$registerType__docs: '/** @param {Object=} options */',
$registerType: function(rawType, registeredInstance, options = {}) {
if (!('argPackAdvance' in registeredInstance)) {
throw new TypeError('registerType registeredInstance requires argPackAdvance');
}
return sharedRegisterType(rawType, registeredInstance, options);
},
_embind_register_void__deps: ['$readLatin1String', '$registerType'],
_embind_register_void: (rawType, name) => {
name = readLatin1String(name);
registerType(rawType, {
isVoid: true, // void return values can be optimized out sometimes
name,
'argPackAdvance': 0,
'fromWireType': () => undefined,
// TODO: assert if anything else is given?
'toWireType': (destructors, o) => undefined,
});
},
_embind_register_bool__docs: '/** @suppress {globalThis} */',
_embind_register_bool__deps: ['$readLatin1String', '$registerType', '$GenericWireTypeSize'],
_embind_register_bool: (rawType, name, trueValue, falseValue) => {
name = readLatin1String(name);
registerType(rawType, {
name,
'fromWireType': function(wt) {
// ambiguous emscripten ABI: sometimes return values are
// true or false, and sometimes integers (0 or 1)
return !!wt;
},
'toWireType': function(destructors, o) {
return o ? trueValue : falseValue;
},
'argPackAdvance': GenericWireTypeSize,
'readValueFromPointer': function(pointer) {
return this['fromWireType'](HEAPU8[pointer]);
},
destructorFunction: null, // This type does not need a destructor
});
},
$integerReadValueFromPointer__deps: [],
$integerReadValueFromPointer: (name, width, signed) => {
// integers are quite common, so generate very specialized functions
switch (width) {
case 1: return signed ?
(pointer) => {{{ makeGetValue('pointer', 0, 'i8') }}} :
(pointer) => {{{ makeGetValue('pointer', 0, 'u8') }}};
case 2: return signed ?
(pointer) => {{{ makeGetValue('pointer', 0, 'i16') }}} :
(pointer) => {{{ makeGetValue('pointer', 0, 'u16') }}}
case 4: return signed ?
(pointer) => {{{ makeGetValue('pointer', 0, 'i32') }}} :
(pointer) => {{{ makeGetValue('pointer', 0, 'u32') }}}
#if WASM_BIGINT
case 8: return signed ?
(pointer) => {{{ makeGetValue('pointer', 0, 'i64') }}} :
(pointer) => {{{ makeGetValue('pointer', 0, 'u64') }}}
#endif
default:
throw new TypeError(`invalid integer width (${width}): ${name}`);
}
},
$enumReadValueFromPointer__deps: [],
$enumReadValueFromPointer: (name, width, signed) => {
switch (width) {
case 1: return signed ?
function(pointer) { return this['fromWireType']({{{ makeGetValue('pointer', 0, 'i8') }}}) } :
function(pointer) { return this['fromWireType']({{{ makeGetValue('pointer', 0, 'u8') }}}) };
case 2: return signed ?
function(pointer) { return this['fromWireType']({{{ makeGetValue('pointer', 0, 'i16') }}}) } :
function(pointer) { return this['fromWireType']({{{ makeGetValue('pointer', 0, 'u16') }}}) };
case 4: return signed ?
function(pointer) { return this['fromWireType']({{{ makeGetValue('pointer', 0, 'i32') }}}) } :
function(pointer) { return this['fromWireType']({{{ makeGetValue('pointer', 0, 'u32') }}}) };
default:
throw new TypeError(`invalid integer width (${width}): ${name}`);
}
},
$floatReadValueFromPointer__deps: [],
$floatReadValueFromPointer: (name, width) => {
switch (width) {
case 4: return function(pointer) {
return this['fromWireType']({{{ makeGetValue('pointer', 0, 'float') }}});
};
case 8: return function(pointer) {
return this['fromWireType']({{{ makeGetValue('pointer', 0, 'double') }}});
};
default:
throw new TypeError(`invalid float width (${width}): ${name}`);
}
},
_embind_register_integer__docs: '/** @suppress {globalThis} */',
// When converting a number from JS to C++ side, the valid range of the number is
// [minRange, maxRange], inclusive.
_embind_register_integer__deps: [
'$embindRepr', '$integerReadValueFromPointer',
'$readLatin1String', '$registerType'],
_embind_register_integer: (primitiveType, name, size, minRange, maxRange) => {
name = readLatin1String(name);
// LLVM doesn't have signed and unsigned 32-bit types, so u32 literals come
// out as 'i32 -1'. Always treat those as max u32.
if (maxRange === -1) {
maxRange = 4294967295;
}
var fromWireType = (value) => value;
if (minRange === 0) {
var bitshift = 32 - 8*size;
fromWireType = (value) => (value << bitshift) >>> bitshift;
}
var isUnsignedType = (name.includes('unsigned'));
var checkAssertions = (value, toTypeName) => {
#if ASSERTIONS
if (typeof value != "number" && typeof value != "boolean") {
throw new TypeError(`Cannot convert "${embindRepr(value)}" to ${toTypeName}`);
}
if (value < minRange || value > maxRange) {
throw new TypeError(`Passing a number "${embindRepr(value)}" from JS side to C/C++ side to an argument of type "${name}", which is outside the valid range [${minRange}, ${maxRange}]!`);
}
#endif
}
var toWireType;
if (isUnsignedType) {
toWireType = function(destructors, value) {
checkAssertions(value, this.name);
return value >>> 0;
}
} else {
toWireType = function(destructors, value) {
checkAssertions(value, this.name);
// The VM will perform JS to Wasm value conversion, according to the spec:
// https://www.w3.org/TR/wasm-js-api-1/#towebassemblyvalue
return value;
}
}
registerType(primitiveType, {
name,
'fromWireType': fromWireType,
'toWireType': toWireType,
'argPackAdvance': GenericWireTypeSize,
'readValueFromPointer': integerReadValueFromPointer(name, size, minRange !== 0),
destructorFunction: null, // This type does not need a destructor
});
},
#if WASM_BIGINT
_embind_register_bigint__docs: '/** @suppress {globalThis} */',
_embind_register_bigint__deps: [
'$embindRepr', '$readLatin1String', '$registerType', '$integerReadValueFromPointer'],
_embind_register_bigint: (primitiveType, name, size, minRange, maxRange) => {
name = readLatin1String(name);
var isUnsignedType = (name.indexOf('u') != -1);
// maxRange comes through as -1 for uint64_t (see issue 13902). Work around that temporarily
if (isUnsignedType) {
maxRange = (1n << 64n) - 1n;
}
registerType(primitiveType, {
name,
'fromWireType': (value) => value,
'toWireType': function(destructors, value) {
if (typeof value != "bigint" && typeof value != "number") {
throw new TypeError(`Cannot convert "${embindRepr(value)}" to ${this.name}`);
}
if (value < minRange || value > maxRange) {
throw new TypeError(`Passing a number "${embindRepr(value)}" from JS side to C/C++ side to an argument of type "${name}", which is outside the valid range [${minRange}, ${maxRange}]!`);
}
return value;
},
'argPackAdvance': GenericWireTypeSize,
'readValueFromPointer': integerReadValueFromPointer(name, size, !isUnsignedType),
destructorFunction: null, // This type does not need a destructor
});
},
#else
_embind_register_bigint__deps: [],
_embind_register_bigint: (primitiveType, name, size, minRange, maxRange) => {},
#endif
_embind_register_float__deps: [
'$embindRepr', '$floatReadValueFromPointer',
'$readLatin1String', '$registerType'],
_embind_register_float: (rawType, name, size) => {
name = readLatin1String(name);
registerType(rawType, {
name,
'fromWireType': (value) => value,
'toWireType': (destructors, value) => {
#if ASSERTIONS
if (typeof value != "number" && typeof value != "boolean") {
throw new TypeError(`Cannot convert ${embindRepr(value)} to ${this.name}`);
}
#endif
// The VM will perform JS to Wasm value conversion, according to the spec:
// https://www.w3.org/TR/wasm-js-api-1/#towebassemblyvalue
return value;
},
'argPackAdvance': GenericWireTypeSize,
'readValueFromPointer': floatReadValueFromPointer(name, size),
destructorFunction: null, // This type does not need a destructor
});
},
$simpleReadValueFromPointer__docs: '/** @suppress {globalThis} */',
// For types whose wire types are 32-bit pointers.
$simpleReadValueFromPointer: function(pointer) {
return this['fromWireType']({{{ makeGetValue('pointer', '0', 'i32') }}});
},
$readPointer__docs: '/** @suppress {globalThis} */',
$readPointer: function(pointer) {
return this['fromWireType']({{{ makeGetValue('pointer', '0', '*') }}});
},
_embind_register_std_string__deps: [
'$readLatin1String', '$registerType',
'$readPointer', '$throwBindingError',
'$stringToUTF8', '$lengthBytesUTF8', 'malloc', 'free'],
_embind_register_std_string: (rawType, name) => {
name = readLatin1String(name);
var stdStringIsUTF8
#if EMBIND_STD_STRING_IS_UTF8
//process only std::string bindings with UTF8 support, in contrast to e.g. std::basic_string<unsigned char>
= (name === "std::string");
#else
= false;
#endif
registerType(rawType, {
name,
// For some method names we use string keys here since they are part of
// the public/external API and/or used by the runtime-generated code.
'fromWireType'(value) {
var length = {{{ makeGetValue('value', '0', SIZE_TYPE) }}};
var payload = value + {{{ POINTER_SIZE }}};
var str;
if (stdStringIsUTF8) {
var decodeStartPtr = payload;
// Looping here to support possible embedded '0' bytes
for (var i = 0; i <= length; ++i) {
var currentBytePtr = payload + i;
if (i == length || HEAPU8[currentBytePtr] == 0) {
var maxRead = currentBytePtr - decodeStartPtr;
var stringSegment = UTF8ToString(decodeStartPtr, maxRead);
if (str === undefined) {
str = stringSegment;
} else {
str += String.fromCharCode(0);
str += stringSegment;
}
decodeStartPtr = currentBytePtr + 1;
}
}
} else {
var a = new Array(length);
for (var i = 0; i < length; ++i) {
a[i] = String.fromCharCode(HEAPU8[payload + i]);
}
str = a.join('');
}
_free(value);
return str;
},
'toWireType'(destructors, value) {
if (value instanceof ArrayBuffer) {
value = new Uint8Array(value);
}
var length;
var valueIsOfTypeString = (typeof value == 'string');
if (!(valueIsOfTypeString || value instanceof Uint8Array || value instanceof Uint8ClampedArray || value instanceof Int8Array)) {
throwBindingError('Cannot pass non-string to std::string');
}
if (stdStringIsUTF8 && valueIsOfTypeString) {
length = lengthBytesUTF8(value);
} else {
length = value.length;
}
// assumes 4-byte alignment
var base = _malloc({{{ POINTER_SIZE }}} + length + 1);
var ptr = base + {{{ POINTER_SIZE }}};
{{{ makeSetValue('base', '0', 'length', SIZE_TYPE) }}};
if (stdStringIsUTF8 && valueIsOfTypeString) {
stringToUTF8(value, ptr, length + 1);
} else {
if (valueIsOfTypeString) {
for (var i = 0; i < length; ++i) {
var charCode = value.charCodeAt(i);
if (charCode > 255) {
_free(ptr);
throwBindingError('String has UTF-16 code units that do not fit in 8 bits');
}
HEAPU8[ptr + i] = charCode;
}
} else {
for (var i = 0; i < length; ++i) {
HEAPU8[ptr + i] = value[i];
}
}
}
if (destructors !== null) {
destructors.push(_free, base);
}
return base;
},
'argPackAdvance': GenericWireTypeSize,
'readValueFromPointer': readPointer,
destructorFunction(ptr) {
_free(ptr);
},
});
},
_embind_register_std_wstring__deps: [
'$readLatin1String', '$registerType', '$readPointer',
'$UTF16ToString', '$stringToUTF16', '$lengthBytesUTF16',
'$UTF32ToString', '$stringToUTF32', '$lengthBytesUTF32',
],
_embind_register_std_wstring: (rawType, charSize, name) => {
name = readLatin1String(name);
var decodeString, encodeString, getHeap, lengthBytesUTF, shift;
if (charSize === 2) {
decodeString = UTF16ToString;
encodeString = stringToUTF16;
lengthBytesUTF = lengthBytesUTF16;
getHeap = () => HEAPU16;
shift = 1;
} else if (charSize === 4) {
decodeString = UTF32ToString;
encodeString = stringToUTF32;
lengthBytesUTF = lengthBytesUTF32;
getHeap = () => HEAPU32;
shift = 2;
}
registerType(rawType, {
name,
'fromWireType': (value) => {
// Code mostly taken from _embind_register_std_string fromWireType
var length = {{{ makeGetValue('value', 0, '*') }}};
var HEAP = getHeap();
var str;
var decodeStartPtr = value + 4;
// Looping here to support possible embedded '0' bytes
for (var i = 0; i <= length; ++i) {
var currentBytePtr = value + 4 + i * charSize;
if (i == length || HEAP[currentBytePtr >> shift] == 0) {
var maxReadBytes = currentBytePtr - decodeStartPtr;
var stringSegment = decodeString(decodeStartPtr, maxReadBytes);
if (str === undefined) {
str = stringSegment;
} else {
str += String.fromCharCode(0);
str += stringSegment;
}
decodeStartPtr = currentBytePtr + charSize;
}
}
_free(value);
return str;
},
'toWireType': (destructors, value) => {
if (!(typeof value == 'string')) {
throwBindingError(`Cannot pass non-string to C++ string type ${name}`);
}
// assumes 4-byte alignment
var length = lengthBytesUTF(value);
var ptr = _malloc(4 + length + charSize);
HEAPU32[ptr >> 2] = length >> shift;
encodeString(value, ptr + 4, length + charSize);
if (destructors !== null) {
destructors.push(_free, ptr);
}
return ptr;
},
'argPackAdvance': GenericWireTypeSize,
'readValueFromPointer': simpleReadValueFromPointer,
destructorFunction(ptr) {
_free(ptr);
}
});
},
_embind_register_emval__deps: [
'_emval_decref', '$Emval',
'$readLatin1String', '$registerType', '$simpleReadValueFromPointer'],
_embind_register_emval: (rawType, name) => {
name = readLatin1String(name);
registerType(rawType, {
name,
'fromWireType': (handle) => {
var rv = Emval.toValue(handle);
__emval_decref(handle);
return rv;
},
'toWireType': (destructors, value) => Emval.toHandle(value),
'argPackAdvance': GenericWireTypeSize,
'readValueFromPointer': simpleReadValueFromPointer,
destructorFunction: null, // This type does not need a destructor
// TODO: do we need a deleteObject here? write a test where
// emval is passed into JS via an interface
});
},
_embind_register_user_type__deps: ['_embind_register_emval'],
_embind_register_user_type: (rawType, name) => {
__embind_register_emval(rawType, name);
},
_embind_register_memory_view__deps: ['$readLatin1String', '$registerType'],
_embind_register_memory_view: (rawType, dataTypeIndex, name) => {
var typeMapping = [
Int8Array,
Uint8Array,
Int16Array,
Uint16Array,
Int32Array,
Uint32Array,
Float32Array,
Float64Array,
#if WASM_BIGINT
BigInt64Array,
BigUint64Array,
#endif
];
var TA = typeMapping[dataTypeIndex];
function decodeMemoryView(handle) {
var size = {{{ makeGetValue('handle', 0, '*') }}};
var data = {{{ makeGetValue('handle', POINTER_SIZE, '*') }}};
return new TA(HEAP8.buffer, data, size);
}
name = readLatin1String(name);
registerType(rawType, {
name,
'fromWireType': decodeMemoryView,
'argPackAdvance': GenericWireTypeSize,
'readValueFromPointer': decodeMemoryView,
}, {
ignoreDuplicateRegistrations: true,
});
},
$runDestructors: (destructors) => {
while (destructors.length) {
var ptr = destructors.pop();
var del = destructors.pop();
del(ptr);
}
},
#if DYNAMIC_EXECUTION
$newFunc__deps: ['$createNamedFunction'],
$newFunc: function(constructor, argumentList) {
if (!(constructor instanceof Function)) {
throw new TypeError(`new_ called with constructor type ${typeof(constructor)} which is not a function`);
}
/*
* Previously, the following line was just:
* function dummy() {};
* Unfortunately, Chrome was preserving 'dummy' as the object's name, even
* though at creation, the 'dummy' has the correct constructor name. Thus,
* objects created with IMVU.new would show up in the debugger as 'dummy',
* which isn't very helpful. Using IMVU.createNamedFunction addresses the
* issue. Doublely-unfortunately, there's no way to write a test for this
* behavior. -NRD 2013.02.22
*/
var dummy = createNamedFunction(constructor.name || 'unknownFunctionName', function(){});
dummy.prototype = constructor.prototype;
var obj = new dummy;
var r = constructor.apply(obj, argumentList);
return (r instanceof Object) ? r : obj;
},
#endif
// The path to interop from JS code to C++ code:
// (hand-written JS code) -> (autogenerated JS invoker) -> (template-generated C++ invoker) -> (target C++ function)
// craftInvokerFunction generates the JS invoker function for each function exposed to JS through embind.
$craftInvokerFunction__deps: [
'$makeLegalFunctionName', '$runDestructors', '$throwBindingError',
#if DYNAMIC_EXECUTION
'$newFunc',
#endif
#if ASYNCIFY
'$Asyncify',
#endif
],
$craftInvokerFunction: function(humanName, argTypes, classType, cppInvokerFunc, cppTargetFunc, /** boolean= */ isAsync) {
// humanName: a human-readable string name for the function to be generated.
// argTypes: An array that contains the embind type objects for all types in the function signature.
// argTypes[0] is the type object for the function return value.
// argTypes[1] is the type object for function this object/class type, or null if not crafting an invoker for a class method.
// argTypes[2...] are the actual function parameters.
// classType: The embind type object for the class to be bound, or null if this is not a method of a class.
// cppInvokerFunc: JS Function object to the C++-side function that interops into C++ code.
// cppTargetFunc: Function pointer (an integer to FUNCTION_TABLE) to the target C++ function the cppInvokerFunc will end up calling.
// isAsync: Optional. If true, returns an async function. Async bindings are only supported with JSPI.
var argCount = argTypes.length;
if (argCount < 2) {
throwBindingError("argTypes array size mismatch! Must at least get return value and 'this' types!");
}
#if ASSERTIONS && ASYNCIFY != 2
assert(!isAsync, 'Async bindings are only supported with JSPI.');
#endif
var isClassMethodFunc = (argTypes[1] !== null && classType !== null);
// Free functions with signature "void function()" do not need an invoker that marshalls between wire types.
// TODO: This omits argument count check - enable only at -O3 or similar.
// if (ENABLE_UNSAFE_OPTS && argCount == 2 && argTypes[0].name == "void" && !isClassMethodFunc) {
// return FUNCTION_TABLE[fn];
// }
// Determine if we need to use a dynamic stack to store the destructors for the function parameters.
// TODO: Remove this completely once all function invokers are being dynamically generated.
var needsDestructorStack = false;
for (var i = 1; i < argTypes.length; ++i) { // Skip return value at index 0 - it's not deleted here.
if (argTypes[i] !== null && argTypes[i].destructorFunction === undefined) { // The type does not define a destructor function - must use dynamic stack
needsDestructorStack = true;
break;
}
}
var returns = (argTypes[0].name !== "void");
#if DYNAMIC_EXECUTION == 0
var expectedArgCount = argCount - 2;
var argsWired = new Array(expectedArgCount);
var invokerFuncArgs = [];
var destructors = [];
return function() {
if (arguments.length !== expectedArgCount) {
throwBindingError(`function ${humanName} called with ${arguments.length} arguments, expected ${expectedArgCount}`);
}
#if EMSCRIPTEN_TRACING
Module.emscripten_trace_enter_context(`embind::${humanName}`);
#endif
destructors.length = 0;
var thisWired;
invokerFuncArgs.length = isClassMethodFunc ? 2 : 1;
invokerFuncArgs[0] = cppTargetFunc;
if (isClassMethodFunc) {
thisWired = argTypes[1]['toWireType'](destructors, this);
invokerFuncArgs[1] = thisWired;
}
for (var i = 0; i < expectedArgCount; ++i) {
argsWired[i] = argTypes[i + 2]['toWireType'](destructors, arguments[i]);
invokerFuncArgs.push(argsWired[i]);
}
var rv = cppInvokerFunc.apply(null, invokerFuncArgs);
function onDone(rv) {
if (needsDestructorStack) {
runDestructors(destructors);
} else {
for (var i = isClassMethodFunc ? 1 : 2; i < argTypes.length; i++) {
var param = i === 1 ? thisWired : argsWired[i - 2];
if (argTypes[i].destructorFunction !== null) {
argTypes[i].destructorFunction(param);
}
}
}
#if EMSCRIPTEN_TRACING
Module.emscripten_trace_exit_context();
#endif
if (returns) {
return argTypes[0]['fromWireType'](rv);
}
}
#if ASYNCIFY == 1
if (Asyncify.currData) {
return Asyncify.whenDone().then(onDone);
}
#elif ASYNCIFY == 2
if (isAsync) {
return rv.then(onDone);
}
#endif
return onDone(rv);
};
#else
var argsList = "";
var argsListWired = "";
for (var i = 0; i < argCount - 2; ++i) {
argsList += (i!==0?", ":"")+"arg"+i;
argsListWired += (i!==0?", ":"")+"arg"+i+"Wired";
}
var invokerFnBody = `
return function ${makeLegalFunctionName(humanName)}(${argsList}) {
if (arguments.length !== ${argCount - 2}) {
throwBindingError('function ${humanName} called with ' + arguments.length + ' arguments, expected ${argCount - 2}');
}`;
#if EMSCRIPTEN_TRACING
invokerFnBody += `Module.emscripten_trace_enter_context('embind::${humanName}');\n`;
#endif
if (needsDestructorStack) {
invokerFnBody += "var destructors = [];\n";
}
var dtorStack = needsDestructorStack ? "destructors" : "null";
var args1 = ["throwBindingError", "invoker", "fn", "runDestructors", "retType", "classParam"];
var args2 = [throwBindingError, cppInvokerFunc, cppTargetFunc, runDestructors, argTypes[0], argTypes[1]];
#if EMSCRIPTEN_TRACING
args1.push("Module");
args2.push(Module);
#endif
if (isClassMethodFunc) {
invokerFnBody += "var thisWired = classParam.toWireType("+dtorStack+", this);\n";
}
for (var i = 0; i < argCount - 2; ++i) {
invokerFnBody += "var arg"+i+"Wired = argType"+i+".toWireType("+dtorStack+", arg"+i+"); // "+argTypes[i+2].name+"\n";
args1.push("argType"+i);
args2.push(argTypes[i+2]);
}
if (isClassMethodFunc) {
argsListWired = "thisWired" + (argsListWired.length > 0 ? ", " : "") + argsListWired;
}
invokerFnBody +=
(returns || isAsync ? "var rv = ":"") + "invoker(fn"+(argsListWired.length>0?", ":"")+argsListWired+");\n";
#if ASYNCIFY == 1
args1.push("Asyncify");
args2.push(Asyncify);
#endif
#if ASYNCIFY
invokerFnBody += "function onDone(" + (returns ? "rv" : "") + ") {\n";
#endif
if (needsDestructorStack) {
invokerFnBody += "runDestructors(destructors);\n";
} else {
for (var i = isClassMethodFunc?1:2; i < argTypes.length; ++i) { // Skip return value at index 0 - it's not deleted here. Also skip class type if not a method.
var paramName = (i === 1 ? "thisWired" : ("arg"+(i - 2)+"Wired"));
if (argTypes[i].destructorFunction !== null) {
invokerFnBody += paramName+"_dtor("+paramName+"); // "+argTypes[i].name+"\n";
args1.push(paramName+"_dtor");
args2.push(argTypes[i].destructorFunction);
}
}
}
if (returns) {
invokerFnBody += "var ret = retType.fromWireType(rv);\n" +
#if EMSCRIPTEN_TRACING
"Module.emscripten_trace_exit_context();\n" +
#endif
"return ret;\n";
} else {
#if EMSCRIPTEN_TRACING
invokerFnBody += "Module.emscripten_trace_exit_context();\n";
#endif
}
#if ASYNCIFY == 1
invokerFnBody += "}\n";
invokerFnBody += "return Asyncify.currData ? Asyncify.whenDone().then(onDone) : onDone(" + (returns ? "rv" : "") +");\n"
#elif ASYNCIFY == 2
invokerFnBody += "}\n";
invokerFnBody += "return " + (isAsync ? "rv.then(onDone)" : "onDone(" + (returns ? "rv" : "") + ")") + ";";
#endif
invokerFnBody += "}\n";
args1.push(invokerFnBody);
return newFunc(Function, args1).apply(null, args2);
#endif
},
$embind__requireFunction__deps: ['$readLatin1String', '$throwBindingError'
#if DYNCALLS || !WASM_BIGINT || MEMORY64
, '$getDynCaller'
#endif
],
$embind__requireFunction: (signature, rawFunction) => {
signature = readLatin1String(signature);
function makeDynCaller() {
#if DYNCALLS
return getDynCaller(signature, rawFunction);
#else
#if !WASM_BIGINT
if (signature.includes('j')) {
return getDynCaller(signature, rawFunction);
}
#elif MEMORY64
if (signature.includes('p')) {
return getDynCaller(signature, rawFunction);
}
#endif
return getWasmTableEntry(rawFunction);
#endif
}
var fp = makeDynCaller();
if (typeof fp != "function") {
throwBindingError(`unknown function pointer with signature ${signature}: ${rawFunction}`);
}
return fp;
},