/
jswrap_object.c
853 lines (785 loc) · 26.6 KB
/
jswrap_object.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
/*
* This file is part of Espruino, a JavaScript interpreter for Microcontrollers
*
* Copyright (C) 2013 Gordon Williams <gw@pur3.co.uk>
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* ----------------------------------------------------------------------------
* This file is designed to be parsed during the build process
*
* JavaScript methods for Objects and Functions
* ----------------------------------------------------------------------------
*/
#include "jswrap_object.h"
#include "jsparse.h"
#include "jsinteractive.h"
#include "jswrapper.h"
#include "jswrap_stream.h"
#include "jswrap_functions.h"
#ifdef __MINGW32__
#include "malloc.h" // needed for alloca
#endif//__MINGW32__
/*JSON{
"type" : "class",
"class" : "Hardware",
"check" : "jsvIsRoot(var)"
}
This is the built-in class for the Espruino device. It is the 'root scope', as 'Window' is for JavaScript on the desktop.
*/
/*JSON{
"type" : "class",
"class" : "Object",
"check" : "jsvIsObject(var)"
}
This is the built-in class for Objects
*/
/*JSON{
"type" : "class",
"class" : "Function",
"check" : "jsvIsFunction(var)"
}
This is the built-in class for Functions
*/
/*JSON{
"type" : "constructor",
"class" : "Object",
"name" : "Object",
"generate" : "jswrap_object_constructor",
"params" : [
["value","JsVar","A single value to be converted to an object"]
],
"return" : ["JsVar","An Object"]
}
Creates an Object from the supplied argument
*/
JsVar *jswrap_object_constructor(JsVar *value) {
if (jsvIsObject(value) || jsvIsArray(value) || jsvIsFunction(value))
return jsvLockAgain(value);
char *objName = jswGetBasicObjectName(value);
JsVar *funcName = objName ? jspGetNamedVariable(objName) : 0;
if (!funcName) return jsvNewWithFlags(JSV_OBJECT);
JsVar *func = jsvSkipName(funcName);
JsVar *result = jspeFunctionCall(func, funcName, 0, false, 1, &value);
jsvUnLock2(funcName, func);
return result;
}
/*JSON{
"type" : "property",
"class" : "Object",
"name" : "length",
"generate" : "jswrap_object_length",
"return" : ["JsVar","The length of the object"]
}
Find the length of the object
*/
JsVar *jswrap_object_length(JsVar *parent) {
JsVarInt l;
if (jsvIsArray(parent)) {
l = jsvGetArrayLength(parent);
} else if (jsvIsArrayBuffer(parent)) {
l = (JsVarInt)jsvGetArrayBufferLength(parent);
} else if (jsvIsString(parent)) {
l = (JsVarInt)jsvGetStringLength(parent);
} else if (jsvIsFunction(parent)) {
JsVar *args = jsvGetFunctionArgumentLength(parent);
l = jsvGetArrayLength(args);
jsvUnLock(args);
} else
return 0;
return jsvNewFromInteger(l);
}
/*JSON{
"type" : "method",
"class" : "Object",
"name" : "valueOf",
"generate" : "jswrap_object_valueOf",
"return" : ["JsVar","The primitive value of this object"]
}
Returns the primitive value of this object.
*/
JsVar *jswrap_object_valueOf(JsVar *parent) {
if (!parent) {
jsExceptionHere(JSET_TYPEERROR, "Invalid type %t for valueOf", parent);
return 0;
}
return jsvLockAgain(parent);
}
/*JSON{
"type" : "method",
"class" : "Object",
"name" : "toString",
"generate" : "jswrap_object_toString",
"params" : [
["radix","JsVar","If the object is an integer, the radix (between 2 and 36) to use. NOTE: Setting a radix does not work on floating point numbers."]
],
"return" : ["JsVar","A String representing the object"]
}
Convert the Object to a string
*/
JsVar *jswrap_object_toString(JsVar *parent, JsVar *arg0) {
if (jsvIsInt(arg0) && jsvIsNumeric(parent)) {
JsVarInt radix = jsvGetInteger(arg0);
if (radix>=2 && radix<=36) {
char buf[JS_NUMBER_BUFFER_SIZE];
if (jsvIsInt(parent))
itostr(jsvGetInteger(parent), buf, (unsigned int)radix);
else
ftoa_bounded_extra(jsvGetFloat(parent), buf, sizeof(buf), (int)radix, -1);
return jsvNewFromString(buf);
}
}
return jsvAsString(parent, false);
}
/*JSON{
"type" : "method",
"class" : "Object",
"name" : "clone",
"generate" : "jswrap_object_clone",
"return" : ["JsVar","A copy of this Object"]
}
Copy this object completely
*/
JsVar *jswrap_object_clone(JsVar *parent) {
return jsvCopy(parent);
}
/*JSON{
"type" : "staticmethod",
"class" : "Object",
"name" : "keys",
"generate_full" : "jswrap_object_keys_or_property_names(object, false, false)",
"params" : [
["object","JsVar","The object to return keys for"]
],
"return" : ["JsVar","An array of strings - one for each key on the given object"]
}
Return all enumerable keys of the given object
*/
/*JSON{
"type" : "staticmethod",
"class" : "Object",
"name" : "getOwnPropertyNames",
"generate_full" : "jswrap_object_keys_or_property_names(object, true, false)",
"params" : [
["object","JsVar","The Object to return a list of property names for"]
],
"return" : ["JsVar","An array of the Object's own properties"]
}
Returns an array of all properties (enumerable or not) found directly on a given object.
**Note:** This doesn't currently work as it should for built-in objects and their prototypes. See bug #380
*/
/** This is for Object.keys and Object. */
JsVar *jswrap_object_keys_or_property_names(
JsVar *obj,
bool includeNonEnumerable, ///< include 'hidden' items
bool includePrototype) { ///< include items for the prototype too (for autocomplete)
JsVar *arr = jsvNewWithFlags(JSV_ARRAY);
if (!arr) return 0;
// strings are iterable, but we shouldn't try and show keys for them
if (jsvIsIterable(obj)) {
JsvIsInternalChecker checkerFunction = jsvGetInternalFunctionCheckerFor(obj);
JsvIterator it;
jsvIteratorNew(&it, obj);
while (jsvIteratorHasElement(&it)) {
JsVar *key = jsvIteratorGetKey(&it);
if (!(checkerFunction && checkerFunction(key)) || (jsvIsStringEqual(key, JSPARSE_CONSTRUCTOR_VAR))) {
/* Not sure why constructor is included in getOwnPropertyNames, but
* not in for (i in ...) but it is, so we must explicitly override the
* check in jsvIsInternalObjectKey! */
JsVar *name = jsvAsArrayIndexAndUnLock(jsvCopyNameOnly(key, false, false));
if (name) {
jsvArrayPushAndUnLock(arr, name);
}
}
jsvUnLock(key);
jsvIteratorNext(&it);
}
jsvIteratorFree(&it);
}
/* Search our built-in symbol table
Assume that ALL builtins are non-enumerable. This isn't great but
seems to work quite well right now! */
if (includeNonEnumerable) {
const JswSymList *symbols = 0;
JsVar *protoOwner = jspGetPrototypeOwner(obj);
if (protoOwner) {
// If protoOwner then this is the prototype (protoOwner is the object)
symbols = jswGetSymbolListForObjectProto(protoOwner);
jsvUnLock(protoOwner);
} else if (!jsvIsObject(obj) || jsvIsRoot(obj)) {
// get symbols, but only if we're not doing it on a basic object
symbols = jswGetSymbolListForObject(obj);
}
if (symbols) {
unsigned int i;
for (i=0;i<symbols->symbolCount;i++)
jsvArrayAddString(arr, &symbols->symbolChars[symbols->symbols[i].strOffset]);
}
if (includePrototype) {
symbols = jswGetSymbolListForObjectProto(obj);
if (symbols) {
unsigned int i;
for (i=0;i<symbols->symbolCount;i++)
jsvArrayAddString(arr, &symbols->symbolChars[symbols->symbols[i].strOffset]);
}
}
if (jsvIsArray(obj) || jsvIsString(obj)) {
jsvArrayAddString(arr, "length");
}
}
return arr;
}
/*JSON{
"type" : "staticmethod",
"class" : "Object",
"name" : "create",
"generate" : "jswrap_object_create",
"params" : [
["proto","JsVar","A prototype object","propertiesObject","JsVar","An object containing properties. NOT IMPLEMENTED"]
],
"return" : ["JsVar","A new object"]
}
Creates a new object with the specified prototype object and properties. properties are currently unsupported.
*/
JsVar *jswrap_object_create(JsVar *proto, JsVar *propertiesObject) {
if (!jsvIsObject(proto) && !jsvIsNull(proto)) {
jsWarn("Object prototype may only be an Object or null: %t", proto);
return 0;
}
if (jsvIsObject(propertiesObject)) {
jsWarn("propertiesObject is not supported yet");
}
JsVar *obj = jsvNewWithFlags(JSV_OBJECT);
if (!obj) return 0;
if (jsvIsObject(proto))
jsvObjectSetChild(obj, JSPARSE_INHERITS_VAR, proto);
return obj;
}
/*JSON{
"type" : "staticmethod",
"class" : "Object",
"name" : "getOwnPropertyDescriptor",
"generate" : "jswrap_object_getOwnPropertyDescriptor",
"params" : [
["obj","JsVar","The object"],
["name","JsVar","The name of the property"]
],
"return" : ["JsVar","An object with a description of the property. The values of writable/enumerable/configurable may not be entirely correct due to Espruino's implementation."]
}
Get information on the given property in the object, or undefined
*/
JsVar *jswrap_object_getOwnPropertyDescriptor(JsVar *parent, JsVar *name) {
if (!jswrap_object_hasOwnProperty(parent, name))
return 0;
JsVar *propName = jsvAsArrayIndex(name);
JsVar *varName = jspGetVarNamedField(parent, propName, true);
jsvUnLock(propName);
assert(varName); // we had it! (apparently)
if (!varName) return 0;
JsVar *obj = jsvNewWithFlags(JSV_OBJECT);
if (!obj) {
jsvUnLock(varName);
return 0;
}
//jsvTrace(varName, 5);
JsVar *var = jsvSkipName(varName);
bool isBuiltIn = jsvIsNewChild(varName);
JsvIsInternalChecker checkerFunction = jsvGetInternalFunctionCheckerFor(parent);
jsvObjectSetChild(obj, "value", var);
jsvObjectSetChildAndUnLock(obj, "writable", jsvNewFromBool(true));
jsvObjectSetChildAndUnLock(obj, "enumerable", jsvNewFromBool(!checkerFunction || !checkerFunction(varName)));
jsvObjectSetChildAndUnLock(obj, "configurable", jsvNewFromBool(!isBuiltIn));
jsvUnLock2(var, varName);
return obj;
}
/*JSON{
"type" : "method",
"class" : "Object",
"name" : "hasOwnProperty",
"generate" : "jswrap_object_hasOwnProperty",
"params" : [
["name","JsVar","The name of the property to search for"]
],
"return" : ["bool","True if it exists, false if it doesn't"]
}
Return true if the object (not its prototype) has the given property.
NOTE: This currently returns false-positives for built-in functions in prototypes
*/
bool jswrap_object_hasOwnProperty(JsVar *parent, JsVar *name) {
JsVar *propName = jsvAsArrayIndex(name);
bool contains = false;
if (jsvHasChildren(parent)) {
JsVar *foundVar = jsvFindChildFromVar(parent, propName, false);
if (foundVar) {
contains = true;
jsvUnLock(foundVar);
}
}
if (!contains && !jsvIsObject(parent)) {
/* search builtin symbol table, but not for Objects, as these
* are descended from Objects but do not themselves contain
* an Object's properties */
const JswSymList *symbols = jswGetSymbolListForObject(parent);
if (symbols) {
char str[32];
jsvGetString(propName, str, sizeof(str));
JsVar *v = jswBinarySearch(symbols, parent, str);
if (v) contains = true;
jsvUnLock(v);
}
}
jsvUnLock(propName);
return contains;
}
/*JSON{
"type" : "staticmethod",
"class" : "Object",
"name" : "defineProperty",
"generate" : "jswrap_object_defineProperty",
"params" : [
["obj","JsVar","An object"],
["name","JsVar","The name of the property"],
["desc","JsVar","The property descriptor"]
],
"return" : ["JsVar","The object, obj."]
}
Add a new property to the Object. 'Desc' is an object with the following fields:
* `configurable` (bool = false) - can this property be changed/deleted
* `enumerable` (bool = false) - can this property be enumerated
* `value` (anything) - the value of this property
* `writable` (bool = false) - can the value be changed with the assignment operator?
* `get` (function) - the getter function, or undefined if no getter
* `set` (function) - the setter function, or undefined if no setter
*
**Note:** `configurable`, `enumerable`, `writable`, `get`, and `set` are not implemented and will be ignored.
*/
JsVar *jswrap_object_defineProperty(JsVar *parent, JsVar *propName, JsVar *desc) {
if (!jsvIsObject(parent)) {
jsExceptionHere(JSET_ERROR, "First argument must be an object, got %t", parent);
return 0;
}
if (!jsvIsObject(desc)) {
jsExceptionHere(JSET_ERROR, "Property description must be an object, got %t", desc);
return 0;
}
JsVar *name = jsvAsArrayIndex(propName);
JsVar *value = jsvObjectGetChild(desc, "value", 0);
JsVar *property = jsvFindChildFromVar(parent, name, true);
jsvUnLock(name);
if (property && value)
jsvSetValueOfName(property, value);
jsvUnLock2(property, value);
return jsvLockAgain(parent);
}
/*JSON{
"type" : "staticmethod",
"class" : "Object",
"name" : "defineProperties",
"generate" : "jswrap_object_defineProperties",
"params" : [
["obj","JsVar","An object"],
["props","JsVar","An object whose fields represent property names, and whose values are property descriptors."]
],
"return" : ["JsVar","The object, obj."]
}
Adds new properties to the Object. See `Object.defineProperty` for more information
*/
JsVar *jswrap_object_defineProperties(JsVar *parent, JsVar *props) {
if (!jsvIsObject(parent)) {
jsExceptionHere(JSET_ERROR, "First argument must be an object, got %t", parent);
return 0;
}
if (!jsvIsObject(props)) {
jsExceptionHere(JSET_ERROR, "Second argument must be an object, got %t", props);
return 0;
}
JsvObjectIterator it;
jsvObjectIteratorNew(&it, props);
while (jsvObjectIteratorHasValue(&it)) {
JsVar *name = jsvObjectIteratorGetKey(&it);
JsVar *desc = jsvObjectIteratorGetValue(&it);
jsvUnLock3(jswrap_object_defineProperty(parent, name, desc), name, desc);
jsvObjectIteratorNext(&it);
}
jsvObjectIteratorFree(&it);
return jsvLockAgain(parent);
}
// --------------------------------------------------------------------------
// Misc constructors
/*JSON{
"type" : "constructor",
"class" : "Boolean",
"name" : "Boolean",
"generate" : "jswrap_boolean_constructor",
"params" : [
["value","JsVar","A single value to be converted to a number"]
],
"return" : ["bool","A Boolean object"]
}
Creates a number
*/
bool jswrap_boolean_constructor(JsVar *value) {
return jsvGetBool(value);
}
// --------------------------------------------------------------------------
// These should be in EventEmitter
/** A convenience function for adding event listeners */
void jswrap_object_addEventListener(JsVar *parent, const char *eventName, void (*callback)(), JsnArgumentType argTypes) {
JsVar *n = jsvNewFromString(eventName);
JsVar *cb = jsvNewNativeFunction(callback, argTypes);
jswrap_object_on(parent, n, cb);
jsvUnLock2(cb, n);
}
#define EVENTNAME_SIZE 16
bool jswrap_object_get_event_name(char *eventName, JsVar *event) {
strncpy(eventName, JS_EVENT_PREFIX, EVENTNAME_SIZE);
if (jsvGetString(event, &eventName[3], EVENTNAME_SIZE-4)==(EVENTNAME_SIZE-4)) {
jsExceptionHere(JSET_ERROR, "Event name too long\n");
return false;
}
return true;
}
/*JSON{
"type" : "method",
"class" : "Object",
"name" : "on",
"generate" : "jswrap_object_on",
"params" : [
["event","JsVar","The name of the event, for instance 'data'"],
["listener","JsVar","The listener to call when this event is received"]
]
}
Register an event listener for this object, for instance ```http.on('data', function(d) {...})```. See Node.js's EventEmitter.
*/
void jswrap_object_on(JsVar *parent, JsVar *event, JsVar *listener) {
if (!jsvHasChildren(parent)) {
jsWarn("Parent must be an object - not a String, Integer, etc.");
return;
}
if (!jsvIsString(event)) {
jsWarn("First argument to EventEmitter.on(..) must be a string");
return;
}
if (!jsvIsFunction(listener) && !jsvIsString(listener)) {
jsWarn("Second argument to EventEmitter.on(..) must be a function or a String (containing code)");
return;
}
char eventName[16];
if (!jswrap_object_get_event_name(eventName, event)) return;
JsVar *eventList = jsvFindChildFromString(parent, eventName, true);
JsVar *eventListeners = jsvSkipName(eventList);
if (jsvIsUndefined(eventListeners)) {
// just add
jsvSetValueOfName(eventList, listener);
} else {
if (jsvIsArray(eventListeners)) {
// we already have an array, just add to it
jsvArrayPush(eventListeners, listener);
} else {
// not an array - we need to make it an array
JsVar *arr = jsvNewWithFlags(JSV_ARRAY);
jsvArrayPush(arr, eventListeners);
jsvArrayPush(arr, listener);
jsvSetValueOfName(eventList, arr);
jsvUnLock(arr);
}
}
jsvUnLock2(eventListeners, eventList);
/* Special case if we're a data listener and data has already arrived then
* we queue an event immediately. */
if (jsvIsStringEqual(event, "data")) {
JsVar *buf = jsvObjectGetChild(parent, STREAM_BUFFER_NAME, 0);
if (jsvIsString(buf)) {
jsiQueueObjectCallbacks(parent, STREAM_CALLBACK_NAME, &buf, 1);
jsvRemoveNamedChild(parent, STREAM_BUFFER_NAME);
}
jsvUnLock(buf);
}
}
/*JSON{
"type" : "method",
"class" : "Object",
"name" : "emit",
"generate" : "jswrap_object_emit",
"params" : [
["event","JsVar","The name of the event, for instance 'data'"],
["args","JsVarArray","Optional arguments"]
]
}
Call the event listeners for this object, for instance ```http.emit('data', 'Foo')```. See Node.js's EventEmitter.
*/
void jswrap_object_emit(JsVar *parent, JsVar *event, JsVar *argArray) {
if (!jsvHasChildren(parent)) {
jsWarn("Parent must be an object - not a String, Integer, etc.");
return;
}
if (!jsvIsString(event)) {
jsWarn("First argument to EventEmitter.emit(..) must be a string");
return;
}
char eventName[16];
if (!jswrap_object_get_event_name(eventName, event)) return;
// extract data
const unsigned int MAX_ARGS = 4;
JsVar *args[MAX_ARGS];
unsigned int n = 0;
JsvObjectIterator it;
jsvObjectIteratorNew(&it, argArray);
while (jsvObjectIteratorHasValue(&it)) {
if (n>=MAX_ARGS) {
jsWarn("Too many arguments");
break;
}
args[n++] = jsvObjectIteratorGetValue(&it);
jsvObjectIteratorNext(&it);
}
jsvObjectIteratorFree(&it);
jsiQueueObjectCallbacks(parent, eventName, args, (int)n);
// unlock
jsvUnLockMany(n, args);
}
/*JSON{
"type" : "method",
"class" : "Object",
"name" : "removeAllListeners",
"generate" : "jswrap_object_removeAllListeners",
"params" : [
["event","JsVar","The name of the event, for instance 'data'"]
]
}
Removes all listeners, or those of the specified event.
*/
void jswrap_object_removeAllListeners(JsVar *parent, JsVar *event) {
if (!jsvHasChildren(parent)) {
jsWarn("Parent must be an object - not a String, Integer, etc.");
return;
}
if (jsvIsString(event)) {
// remove the whole child containing listeners
char eventName[16];
if (!jswrap_object_get_event_name(eventName, event)) return;
JsVar *eventList = jsvFindChildFromString(parent, eventName, true);
if (eventList) {
jsvRemoveChild(parent, eventList);
jsvUnLock(eventList);
}
} else if (jsvIsUndefined(event)) {
// Eep. We must remove everything beginning with '#on' (JS_EVENT_PREFIX)
JsvObjectIterator it;
jsvObjectIteratorNew(&it, parent);
while (jsvObjectIteratorHasValue(&it)) {
JsVar *key = jsvObjectIteratorGetKey(&it);
jsvObjectIteratorNext(&it);
if (jsvIsStringEqualOrStartsWith(key, JS_EVENT_PREFIX, true)) {
// begins with #on - we must kill it
jsvRemoveChild(parent, key);
}
jsvUnLock(key);
}
jsvObjectIteratorFree(&it);
} else {
jsWarn("First argument to EventEmitter.removeAllListeners(..) must be a string, or undefined");
return;
}
}
// For internal use - like jswrap_object_removeAllListeners but takes a C string
void jswrap_object_removeAllListeners_cstr(JsVar *parent, const char *event) {
JsVar *s = jsvNewFromString(event);
if (s) {
jswrap_object_removeAllListeners(parent, s);
jsvUnLock(s);
}
}
// ------------------------------------------------------------------------------
/*JSON{
"type" : "method",
"class" : "Function",
"name" : "replaceWith",
"generate" : "jswrap_function_replaceWith",
"params" : [
["newFunc","JsVar","The new function to replace this function with"]
]
}
This replaces the function with the one in the argument - while keeping the old function's scope. This allows inner functions to be edited, and is used when edit() is called on an inner function.
*/
void jswrap_function_replaceWith(JsVar *oldFunc, JsVar *newFunc) {
if (!jsvIsFunction(newFunc)) {
jsWarn("First argument of replaceWith should be a function - ignoring");
return;
}
// Grab scope - the one thing we want to keep
JsVar *scope = jsvFindChildFromString(oldFunc, JSPARSE_FUNCTION_SCOPE_NAME, false);
// so now remove all existing entries
jsvRemoveAllChildren(oldFunc);
// now re-add scope
if (scope) jsvAddName(oldFunc, scope);
jsvUnLock(scope);
// now re-add other entries
JsvObjectIterator it;
jsvObjectIteratorNew(&it, newFunc);
while (jsvObjectIteratorHasValue(&it)) {
JsVar *el = jsvObjectIteratorGetKey(&it);
jsvObjectIteratorNext(&it);
if (!jsvIsStringEqual(el, JSPARSE_FUNCTION_SCOPE_NAME)) {
JsVar *copy = jsvCopy(el);
if (copy) {
jsvAddName(oldFunc, copy);
jsvUnLock(copy);
}
}
jsvUnLock(el);
}
jsvObjectIteratorFree(&it);
}
/*JSON{
"type" : "method",
"class" : "Function",
"name" : "call",
"generate" : "jswrap_function_apply_or_call",
"params" : [
["this","JsVar","The value to use as the 'this' argument when executing the function"],
["params","JsVarArray","Optional Parameters"]
],
"return" : ["JsVar","The return value of executing this function"]
}
This executes the function with the supplied 'this' argument and parameters
*/
// ... it just so happens that the way JsVarArray is parsed means that apply and call can be exactly the same function!
/*JSON{
"type" : "method",
"class" : "Function",
"name" : "apply",
"generate" : "jswrap_function_apply_or_call",
"params" : [
["this","JsVar","The value to use as the 'this' argument when executing the function"],
["args","JsVar","Optional Array of Arguments"]
],
"return" : ["JsVar","The return value of executing this function"]
}
This executes the function with the supplied 'this' argument and parameters
*/
JsVar *jswrap_function_apply_or_call(JsVar *parent, JsVar *thisArg, JsVar *argsArray) {
unsigned int i;
JsVar **args = 0;
unsigned int argC = 0;
if (jsvIsIterable(argsArray)) {
argC = (unsigned int)jsvGetLength(argsArray);
if (argC>64) {
jsExceptionHere(JSET_ERROR, "Array passed to Function.apply is too big! Maximum 64 arguments, got %d", argC);
return 0;
}
args = (JsVar**)alloca((size_t)argC * sizeof(JsVar*));
for (i=0;i<argC;i++) args[i] = 0;
// TODO: Use jsvGetArrayItems?
JsvIterator it;
jsvIteratorNew(&it, argsArray);
while (jsvIteratorHasElement(&it)) {
JsVarInt idx = jsvGetIntegerAndUnLock(jsvIteratorGetKey(&it));
if (idx>=0 && idx<(int)argC) {
assert(!args[idx]); // just in case there were dups
args[idx] = jsvIteratorGetValue(&it);
}
jsvIteratorNext(&it);
}
jsvIteratorFree(&it);
} else if (!jsvIsUndefined(argsArray)) {
jsExceptionHere(JSET_ERROR, "Second argument to Function.apply must be iterable, got %t", argsArray);
return 0;
}
JsVar *r = jspeFunctionCall(parent, 0, thisArg, false, (int)argC, args);
jsvUnLockMany(argC, args);
return r;
}
/*JSON{
"type" : "method",
"class" : "Function",
"name" : "bind",
"generate" : "jswrap_function_bind",
"params" : [
["this","JsVar","The value to use as the 'this' argument when executing the function"],
["params","JsVarArray","Optional Default parameters that are prepended to the call"]
],
"return" : ["JsVar","The 'bound' function"]
}
This executes the function with the supplied 'this' argument and parameters
*/
JsVar *jswrap_function_bind(JsVar *parent, JsVar *thisArg, JsVar *argsArray) {
if (!jsvIsFunction(parent)) {
jsExceptionHere(JSET_TYPEERROR, "Function.bind expects to be called on function, got %t", parent);
return 0;
}
JsVar *fn;
if (jsvIsNativeFunction(parent))
fn = jsvNewNativeFunction(parent->varData.native.ptr, parent->varData.native.argTypes);
else
fn = jsvNewWithFlags(jsvIsFunctionReturn(parent) ? JSV_FUNCTION_RETURN : JSV_FUNCTION);
if (!fn) return 0;
// Old function info
JsvObjectIterator fnIt;
jsvObjectIteratorNew(&fnIt, parent);
// add previously bound arguments
while (jsvObjectIteratorHasValue(&fnIt)) {
JsVar *param = jsvObjectIteratorGetKey(&fnIt);
JsVar *defaultValue = jsvObjectIteratorGetValue(&fnIt);
bool wasBound = jsvIsFunctionParameter(param) && defaultValue;
if (wasBound) {
JsVar *newParam = jsvCopy(param);
if (newParam) { // could be out of memory
jsvAddName(fn, newParam);
jsvUnLock(newParam);
}
}
jsvUnLock2(param, defaultValue);
if (!wasBound) break;
jsvObjectIteratorNext(&fnIt);
}
// add bound arguments
JsvObjectIterator argIt;
jsvObjectIteratorNew(&argIt, argsArray);
while (jsvObjectIteratorHasValue(&argIt)) {
JsVar *defaultValue = jsvObjectIteratorGetValue(&argIt);
bool addedParam = false;
while (!addedParam && jsvObjectIteratorHasValue(&fnIt)) {
JsVar *param = jsvObjectIteratorGetKey(&fnIt);
if (!jsvIsFunctionParameter(param)) {
jsvUnLock(param);
break;
}
JsVar *newParam = jsvCopyNameOnly(param, false, true);
jsvSetValueOfName(newParam, defaultValue);
jsvAddName(fn, newParam);
addedParam = true;
jsvUnLock2(param, newParam);
jsvObjectIteratorNext(&fnIt);
}
if (!addedParam) {
JsVar *paramName = jsvNewFromEmptyString();
if (paramName) {
jsvMakeFunctionParameter(paramName); // force this to be called a function parameter
jsvSetValueOfName(paramName, defaultValue);
jsvAddName(fn, paramName);
jsvUnLock(paramName);
}
}
jsvUnLock(defaultValue);
jsvObjectIteratorNext(&argIt);
}
jsvObjectIteratorFree(&argIt);
// Copy the rest of the old function's info
while (jsvObjectIteratorHasValue(&fnIt)) {
JsVar *param = jsvObjectIteratorGetKey(&fnIt);
JsVar *newParam = jsvCopyNameOnly(param, true, true);
if (newParam) { // could be out of memory
jsvAddName(fn, newParam);
jsvUnLock(newParam);
}
jsvUnLock(param);
jsvObjectIteratorNext(&fnIt);
}
jsvObjectIteratorFree(&fnIt);
// Add 'this'
jsvObjectSetChild(fn, JSPARSE_FUNCTION_THIS_NAME, thisArg); // no unlock needed
return fn;
}