/
jswrap_object.c
1353 lines (1250 loc) · 42.7 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
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
/*
* 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" : "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);
const char *objName = jswGetBasicObjectName(value);
JsVar *funcName = objName ? jspGetNamedVariable(objName) : 0;
if (!funcName) return jsvNewObject();
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","[optional] 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"],
"return_object" : "string"
}
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);
}
/*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) {
if (!parent) return 0;
return jsvCopy(parent, true);
}
/*JSON{
"type" : "staticmethod",
"class" : "Object",
"name" : "keys",
"generate_full" : "jswrap_object_keys_or_property_names(object, JSWOKPF_NONE)",
"params" : [
["object","JsVar","The object to return keys for"]
],
"return" : ["JsVar","An array of strings - one for each key on the given object"],
"return_object" : "Array<any>"
}
Return all enumerable keys of the given object
*/
/*JSON{
"type" : "staticmethod",
"class" : "Object",
"name" : "getOwnPropertyNames",
"generate_full" : "jswrap_object_keys_or_property_names(object, JSWOKPF_INCLUDE_NON_ENUMERABLE)",
"params" : [
["object","JsVar","The Object to return a list of property names for"]
],
"return" : ["JsVar","An array of the Object's own properties"],
"return_object" : "Array<any>"
}
Returns an array of all properties (enumerable or not) found directly on a given
object.
*/
static void _jswrap_object_keys_or_property_names_iterator(
const JswSymList *symbols,
void (*callback)(void *data, JsVar *name),
void *data) {
if (!symbols) return;
unsigned int i;
unsigned char symbolCount = READ_FLASH_UINT8(&symbols->symbolCount);
for (i=0;i<symbolCount;i++) {
unsigned short strOffset = READ_FLASH_UINT16(&symbols->symbols[i].strOffset);
#ifndef USE_FLASH_MEMORY
JsVar *name = jsvNewFromString(&symbols->symbolChars[strOffset]);
#else
// On the esp8266 the string is in flash, so we have to copy it to RAM first
// We can't use flash_strncpy here because it assumes that strings start on a word
// boundary and that's not the case here.
char buf[64], *b = buf, c; const char *s = &symbols->symbolChars[strOffset];
do { c = READ_FLASH_UINT8(s++); *b++ = c; } while (c && b != buf+64);
JsVar *name = jsvNewFromString(buf);
#endif
//os_printf_plus("OBJ cb %s\n", buf);
callback(data, name);
jsvUnLock(name);
}
}
/** This is for Object.keys and Object. However it uses a callback so doesn't allocate anything */
void jswrap_object_keys_or_property_names_cb(
JsVar *obj,
JswObjectKeysOrPropertiesFlags flags,
void (*callback)(void *data, JsVar *name),
void *data
) {
// add the keys that are on this object itself
// strings are iterable, but we shouldn't try and show keys for them
if (jsvIsIterable(obj) && !(jsvIsArrayBuffer(obj) && (flags&JSWOKPF_NO_INCLUDE_ARRAYBUFFER))) {
JsvIsInternalChecker checkerFunction = jsvGetInternalFunctionCheckerFor(obj);
JsvIterator it;
jsvIteratorNew(&it, obj, JSIF_DEFINED_ARRAY_ElEMENTS);
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 = jsvAsStringAndUnLock(jsvCopyNameOnly(key, false, false));
if (name) {
callback(data, name);
jsvUnLock(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 (flags & JSWOKPF_INCLUDE_NON_ENUMERABLE) {
const JswSymList *objSymbols = jswGetSymbolListForObjectProto(0);
JsVar *protoOwner = jspGetPrototypeOwner(obj);
if (protoOwner) {
// If protoOwner then this is the prototype (protoOwner is the object)
const JswSymList *symbols = jswGetSymbolListForObjectProto(protoOwner);
jsvUnLock(protoOwner);
_jswrap_object_keys_or_property_names_iterator(symbols, callback, data);
} else if (!jsvIsObject(obj) || jsvIsRoot(obj)) {
// get symbols, but only if we're not doing it on a basic object
const JswSymList *symbols = jswGetSymbolListForObject(obj);
_jswrap_object_keys_or_property_names_iterator(symbols, callback, data);
}
if (flags & JSWOKPF_INCLUDE_PROTOTYPE) {
JsVar *proto = 0;
if (jsvIsObject(obj) || jsvIsFunction(obj)) {
proto = jsvObjectGetChildIfExists(obj, JSPARSE_INHERITS_VAR);
}
if (jsvIsObject(proto)) {
jswrap_object_keys_or_property_names_cb(proto, flags, callback, data);
} else {
// include Object/String/etc
const JswSymList *symbols = jswGetSymbolListForObjectProto(obj);
_jswrap_object_keys_or_property_names_iterator(symbols, callback, data);
// if the last call wasn't an Object, add the object proto as well
if (objSymbols!=symbols)
_jswrap_object_keys_or_property_names_iterator(objSymbols, callback, data);
}
jsvUnLock(proto);
}
if (jsvIsArray(obj) || jsvIsString(obj)) {
JsVar *name = jsvNewFromString("length");
callback(data, name);
jsvUnLock(name);
}
}
#ifndef ESPR_EMBED
// If this is the root object, add all the pins (as these are not part of the symbol table)
if (jsvIsRoot(obj)) {
int i;
for (i=0;i<JSH_PIN_COUNT;i++) {
char buf[10];
jshGetPinString(buf, (Pin)i);
JsVar *str = jsvNewFromString(buf);
callback(data, str);
jsvUnLock(str);
}
}
#endif
}
JsVar *jswrap_object_keys_or_property_names(
JsVar *obj,
JswObjectKeysOrPropertiesFlags flags
) {
JsVar *arr = jsvNewEmptyArray();
if (!arr) return 0;
jswrap_object_keys_or_property_names_cb(obj, flags, (void (*)(void *, JsVar *))jsvArrayAddUnique, arr);
return arr;
}
/*JSON{
"type" : "staticmethod",
"class" : "Object",
"name" : "values",
"ifndef" : "SAVE_ON_FLASH",
"generate_full" : "jswrap_object_values_or_entries(object, false);",
"params" : [
["object","JsVar","The object to return values for"]
],
"return" : ["JsVar","An array of values - one for each key on the given object"],
"return_object" : "Array<any>"
}
Return all enumerable values of the given object
*/
/*JSON{
"type" : "staticmethod",
"class" : "Object",
"name" : "entries",
"ifndef" : "SAVE_ON_FLASH",
"generate_full" : "jswrap_object_values_or_entries(object, true);",
"params" : [
["object","JsVar","The object to return values for"]
],
"return" : ["JsVar","An array of `[key,value]` pairs - one for each key on the given object"],
"return_object" : "Array<[string, any]>"
}
Return all enumerable keys and values of the given object
*/
void _jswrap_object_values_cb(void *data, JsVar *name) {
JsVar **cbData = (JsVar**)data;
JsVar *field = jsvAsArrayIndex(name);
jsvArrayPushAndUnLock(cbData[0], jspGetVarNamedField(cbData[1], field, false));
jsvUnLock(field);
}
void _jswrap_object_entries_cb(void *data, JsVar *name) {
JsVar **cbData = (JsVar**)data;
JsVar *tuple = jsvNewEmptyArray();
if (!tuple) return;
jsvArrayPush(tuple, name);
JsVar *field = jsvAsArrayIndex(name);
jsvArrayPushAndUnLock(tuple, jspGetVarNamedField(cbData[1], field, false));
jsvUnLock(field);
jsvArrayPushAndUnLock(cbData[0], tuple);
}
JsVar *jswrap_object_values_or_entries(JsVar *object, bool returnEntries) {
JsVar *cbData[2];
cbData[0] = jsvNewEmptyArray();
cbData[1] = object;
if (!cbData[0]) return 0;
jswrap_object_keys_or_property_names_cb(
object, JSWOKPF_NONE,
returnEntries ? _jswrap_object_entries_cb : _jswrap_object_values_cb,
(void*)cbData
);
return cbData[0];
}
/*JSON{
"type" : "staticmethod",
"class" : "Object",
"name" : "fromEntries",
"ifndef" : "SAVE_ON_FLASH",
"generate" : "jswrap_object_fromEntries",
"params" : [
["entries","JsVar","An array of `[key,value]` pairs to be used to create an object"]
],
"return" : ["JsVar","An object containing all the specified pairs"]
}
Transforms an array of key-value pairs into an object
*/
JsVar *jswrap_object_fromEntries(JsVar *entries) {
if (!jsvIsArray(entries)) return 0;
JsVar *obj = jsvNewObject();
if (!obj) return 0;
JsvObjectIterator it;
jsvObjectIteratorNew(&it, entries);
while (jsvObjectIteratorHasValue(&it)) {
JsVar *e = jsvObjectIteratorGetValue(&it);
if (jsvIsArray(e)) {
JsVar *key = jsvGetArrayItem(e, 0);
JsVar *value = jsvGetArrayItem(e, 1);
if (jsvIsString(key))
jsvObjectSetChildVar(obj, key, value);
jsvUnLock2(key,value);
}
jsvUnLock(e);
jsvObjectIteratorNext(&it);
}
return obj;
}
/*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)) {
jsExceptionHere(JSET_TYPEERROR, "Object prototype may only be an Object or null: %t", proto);
return 0;
}
if (jsvIsObject(propertiesObject)) {
jsExceptionHere(JSET_ERROR, "propertiesObject is not supported yet");
}
JsVar *obj = jsvNewObject();
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 = jsvNewObject();
if (!obj) {
jsvUnLock(varName);
return 0;
}
bool isBuiltIn = jsvIsNewChild(varName);
JsvIsInternalChecker checkerFunction = jsvGetInternalFunctionCheckerFor(parent);
jsvObjectSetChildAndUnLock(obj, "writable", jsvNewFromBool(!jsvIsConstant(varName)));
jsvObjectSetChildAndUnLock(obj, "enumerable", jsvNewFromBool(!checkerFunction || !checkerFunction(varName)));
jsvObjectSetChildAndUnLock(obj, "configurable", jsvNewFromBool(!isBuiltIn));
#ifndef ESPR_NO_GET_SET
JsVar *getset = jsvGetValueOfName(varName);
if (jsvIsGetterOrSetter(getset)) {
jsvObjectSetChildAndUnLock(obj, "get", jsvObjectGetChildIfExists(getset,"get"));
jsvObjectSetChildAndUnLock(obj, "set", jsvObjectGetChildIfExists(getset,"set"));
} else {
#endif
jsvObjectSetChildAndUnLock(obj, "value", jsvSkipName(varName));
#ifndef ESPR_NO_GET_SET
}
jsvUnLock(getset);
#endif
jsvUnLock(varName);
return obj;
}
/*JSON{
"type" : "staticmethod",
"class" : "Object",
"name" : "getOwnPropertyDescriptors",
"ifndef" : "SAVE_ON_FLASH",
"generate" : "jswrap_object_getOwnPropertyDescriptors",
"params" : [
["obj","JsVar","The object"]
],
"return" : ["JsVar","An object containing all the property descriptors of an object"]
}
Get information on all properties in the object (from `Object.getOwnPropertyDescriptor`), or just `{}` if no properties
*/
JsVar *jswrap_object_getOwnPropertyDescriptors(JsVar *parent) {
if (!jsvHasChildren(parent)) {
jsExceptionHere(JSET_TYPEERROR, "First argument must be Object, got %t", parent);
return 0;
}
JsVar *descriptors = jsvNewObject();
if (!descriptors) return 0;
/* There is some code mentioned at https://github.com/espruino/Espruino/issues/1302#issuecomment-1430833414
const protoPropDescriptor = Object.getOwnPropertyDescriptor(obj, '__proto__');
const descriptors = protoPropDescriptor ? { ['__proto__']: protoPropDescriptor } : {};
which we're not implementing here - but I think the current implementation is fine for 99% of cases
*/
JsVar *ownPropertyNames = jswrap_object_keys_or_property_names(parent, JSWOKPF_INCLUDE_NON_ENUMERABLE);
JsvObjectIterator it;
jsvObjectIteratorNew(&it, ownPropertyNames);
while (jsvObjectIteratorHasValue(&it)) {
JsVar *propName = jsvObjectIteratorGetValue(&it);
JsVar *propValue = jswrap_object_getOwnPropertyDescriptor(parent, propName);
jsvObjectSetChildVar(descriptors, propName, propValue);
jsvUnLock2(propName, propValue);
jsvObjectIteratorNext(&it);
}
jsvObjectIteratorFree(&it);
jsvUnLock(ownPropertyNames);
return descriptors;
}
/*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 (not
implemented)
* `enumerable` (bool = false) - can this property be enumerated (not
implemented)
* `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 (only
supported on some platforms)
* `set` (function) - the setter function, or undefined if no setter (only
supported on some platforms)
**Note:** `configurable`, `enumerable` and `writable` 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 Object, got %t", parent);
return 0;
}
if (!jsvIsObject(desc)) {
jsExceptionHere(JSET_ERROR, "Property description must be Object, got %t", desc);
return 0;
}
JsVar *name = jsvAsArrayIndex(propName);
JsVar *value = 0;
JsVar *getter = jsvObjectGetChildIfExists(desc, "get");
JsVar *setter = jsvObjectGetChildIfExists(desc, "set");
if (getter || setter) {
#ifdef ESPR_NO_GET_SET
jsExceptionHere(JSET_ERROR, "get/set unsupported in this build");
#else
// also see jsvAddGetterOrSetter(contents, varName, isGetter, method);
value = jsvNewWithFlags(JSV_GET_SET);
if (value) {
if (getter) jsvObjectSetChild(value, "get", getter);
if (setter) jsvObjectSetChild(value, "set", setter);
}
#endif
jsvUnLock2(getter,setter);
}
if (!value) value = jsvObjectGetChildIfExists(desc, "value");
jsvObjectSetChildVar(parent, name, value);
JsVar *writable = jsvObjectGetChildIfExists(desc, "writable");
if (!jsvIsUndefined(writable) && !jsvGetBoolAndUnLock(writable))
name->flags |= JSV_CONSTANT;
jsvUnLock2(name, 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 Object, got %t", parent);
return 0;
}
if (!jsvIsObject(props)) {
jsExceptionHere(JSET_ERROR, "Second argument must be 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);
}
/*JSON{
"type" : "staticmethod",
"class" : "Object",
"name" : "getPrototypeOf",
"generate" : "jswrap_object_getPrototypeOf",
"params" : [
["object","JsVar","An object"]
],
"return" : ["JsVar","The prototype"]
}
Get the prototype of the given object - this is like writing `object.__proto__`
but is the 'proper' ES6 way of doing it
*/
JsVar *jswrap_object_getPrototypeOf(JsVar *object) {
return jspGetNamedField(object, "__proto__", false);
}
/*JSON{
"type" : "staticmethod",
"class" : "Object",
"name" : "setPrototypeOf",
"generate" : "jswrap_object_setPrototypeOf",
"params" : [
["object","JsVar","An object"],
["prototype","JsVar","The prototype to set on the object"]
],
"return" : ["JsVar","The object passed in"]
}
Set the prototype of the given object - this is like writing `object.__proto__ =
prototype` but is the 'proper' ES6 way of doing it
*/
JsVar *jswrap_object_setPrototypeOf(JsVar *object, JsVar *proto) {
JsVar *v = (jsvIsFunction(object)||jsvIsObject(object)) ? jsvFindOrAddChildFromString(object, "__proto__") : 0;
if (!jsvIsName(v)) {
jsExceptionHere(JSET_TYPEERROR, "Can't extend %t", v);
} else {
jsvSetValueOfName(v, proto);
}
jsvUnLock(v);
return jsvLockAgainSafe(object);
}
/*JSON{
"type" : "staticmethod",
"class" : "Object",
"name" : "assign",
"generate" : "jswrap_object_assign",
"params" : [
["args","JsVarArray","The target object, then any items objects to use as sources of keys"]
],
"return" : ["JsVar","The target object"]
}
Appends all keys and values in any subsequent objects to the first object
**Note:** Unlike the standard ES6 `Object.assign`, this will throw an exception
if given raw strings, bools or numbers rather than objects.
*/
JsVar *jswrap_object_assign(JsVar *args) {
JsVar *result = 0;
JsvObjectIterator argsIt;
jsvObjectIteratorNew(&argsIt, args);
bool error = false;
while (!error && jsvObjectIteratorHasValue(&argsIt)) {
JsVar *arg = jsvObjectIteratorGetValue(&argsIt);
if (jsvIsUndefined(arg) || jsvIsNull(arg)) {
// ignore
} else if (!jsvIsObject(arg)) {
jsExceptionHere(JSET_TYPEERROR, "Expecting Object, got %t", arg);
error = true;
} else if (!result) {
result = jsvLockAgain(arg);
} else {
jsvObjectAppendAll(result, arg);
}
jsvUnLock(arg);
jsvObjectIteratorNext(&argsIt);
};
jsvObjectIteratorFree(&argsIt);
return result;
}
// --------------------------------------------------------------------------
// 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"],
"typescript" : [
"new(...value: any[]): Number;",
"(value: any): boolean;"
]
}
Creates a boolean
*/
bool jswrap_boolean_constructor(JsVar *value) {
return jsvGetBool(value);
}
// --------------------------------------------------------------------------
// These should be in EventEmitter
#ifndef ESPR_EMBED
/** 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);
}
#endif
/*JSON{
"type" : "method",
"class" : "Object",
"name" : "on",
"ifndef" : "ESPR_EMBED",
"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 `Serial1.on('data',
function(d) {...})`.
This is the same as Node.js's [EventEmitter](https://nodejs.org/api/events.html)
but on Espruino the functionality is built into every object:
* `Object.on`
* `Object.emit`
* `Object.removeListener`
* `Object.removeAllListeners`
```
var o = {}; // o can be any object...
// call an arrow function when the 'answer' event is received
o.on('answer', x => console.log(x));
// call a named function when the 'answer' event is received
function printAnswer(d) {
console.log("The answer is", d);
}
o.on('answer', printAnswer);
// emit the 'answer' event - functions added with 'on' will be executed
o.emit('answer', 42);
// prints: 42
// prints: The answer is 42
// If you have a named function, it can be removed by name
o.removeListener('answer', printAnswer);
// Now 'printAnswer' is removed
o.emit('answer', 43);
// prints: 43
// Or you can remove all listeners for 'answer'
o.removeAllListeners('answer')
// Now nothing happens
o.emit('answer', 44);
// nothing printed
```
If you have more than one handler for an event, and you'd
like that handler to stop the event being passed to other handlers
then you can call `E.stopEventPropagation()` in that handler.
*/
/*JSON{
"type" : "method",
"class" : "Object",
"name" : "addListener",
"ifndef" : "ESPR_EMBED",
"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 `Serial1.addListener('data', function(d) {...})`.
An alias for `Object.on`
*/
#ifndef ESPR_EMBED
void jswrap_object_on_X(JsVar *parent, JsVar *event, JsVar *listener, bool addFirst) {
if (!jsvHasChildren(parent)) {
jsExceptionHere(JSET_TYPEERROR, "Parent must be an object - not a String, Integer, etc");
return;
}
if (!jsvIsString(event)) {
jsExceptionHere(JSET_TYPEERROR, "First argument must be String");
return;
}
if (!jsvIsFunction(listener) && !jsvIsString(listener)) {
jsExceptionHere(JSET_TYPEERROR, "Second argument must be a function or a String");
return;
}
JsVar *eventName = jsvVarPrintf(JS_EVENT_PREFIX"%v",event);
if (!eventName) return; // no memory
JsVar *eventList = jsvFindChildFromVar(parent, eventName, true);
jsvUnLock(eventName);
JsVar *eventListeners = jsvSkipName(eventList);
if (jsvIsUndefined(eventListeners)) {
// just add the one handler on its own
jsvSetValueOfName(eventList, listener);
} else {
// we already have an array and we just add to it
// OR it's not an array but we need to make it an array
JsVar *arr = jsvNewEmptyArray();
if (addFirst) jsvArrayPush(arr, listener);
if (jsvIsArray(eventListeners))
jsvArrayPushAll(arr, eventListeners, false);
else
jsvArrayPush(arr, eventListeners);
if (!addFirst) 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 = jsvObjectGetChildIfExists(parent, STREAM_BUFFER_NAME);
if (jsvIsString(buf)) {
jsiQueueObjectCallbacks(parent, STREAM_CALLBACK_NAME, &buf, 1);
jsvObjectRemoveChild(parent, STREAM_BUFFER_NAME);
}
jsvUnLock(buf);
}
}
void jswrap_object_on(JsVar *parent, JsVar *event, JsVar *listener) {
jswrap_object_on_X(parent, event, listener, false/*addFirst*/);
}
/*JSON{
"type" : "method",
"class" : "Object",
"name" : "prependListener",
"ifndef" : "ESPR_EMBED",
"generate" : "jswrap_object_prependListener",
"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 `Serial1.addListener('data', function(d) {...})`.
An alias for `Object.on`
*/
void jswrap_object_prependListener(JsVar *parent, JsVar *event, JsVar *listener) {
jswrap_object_on_X(parent, event, listener, true/*addFirst*/);
}
#endif
/*JSON{
"type" : "method",
"class" : "Object",
"name" : "emit",
"ifndef" : "ESPR_EMBED",
"generate" : "jswrap_object_emit",
"params" : [
["event","JsVar","The name of the event, for instance 'data'"],
["args","JsVarArray","Optional arguments"]
]
}
Call any event listeners that were added to this object with `Object.on`, for
instance `obj.emit('data', 'Foo')`.
For more information see `Object.on`
*/
#ifndef ESPR_EMBED
void jswrap_object_emit(JsVar *parent, JsVar *event, JsVar *argArray) {
if (!jsvHasChildren(parent)) {
jsExceptionHere(JSET_TYPEERROR, "Parent must be an object - not a String, Integer, etc");
return;
}
if (!jsvIsString(event)) {
jsExceptionHere(JSET_TYPEERROR, "First argument must be String");
return;
}
JsVar *eventName = jsvVarPrintf(JS_EVENT_PREFIX"%v", event);
if (!eventName) return; // no memory
// extract data
const unsigned int MAX_EMIT_ARGS = 4;
JsVar *args[MAX_EMIT_ARGS];
unsigned int n = 0;
JsvObjectIterator it;
jsvObjectIteratorNew(&it, argArray);
while (jsvObjectIteratorHasValue(&it)) {
if (n>=MAX_EMIT_ARGS) {
jsExceptionHere(JSET_TYPEERROR, "Too many arguments (>%d)", MAX_EMIT_ARGS);
break;
}
args[n++] = jsvObjectIteratorGetValue(&it);
jsvObjectIteratorNext(&it);
}
jsvObjectIteratorFree(&it);
JsVar *callback = jsvSkipNameAndUnLock(jsvFindChildFromVar(parent, eventName, 0));
jsvUnLock(eventName);
if (callback) jsiQueueEvents(parent, callback, args, (int)n);
jsvUnLock(callback);
// unlock
jsvUnLockMany(n, args);
}
#endif
/*JSON{
"type" : "method",
"class" : "Object",
"name" : "removeListener",
"generate" : "jswrap_object_removeListener",
"params" : [
["event","JsVar","The name of the event, for instance 'data'"],
["listener","JsVar","The listener to remove"]