forked from WebKit/WebKit-http
-
Notifications
You must be signed in to change notification settings - Fork 157
Expand file tree
/
Copy pathJSValue.mm
More file actions
1385 lines (1166 loc) · 45.4 KB
/
JSValue.mm
File metadata and controls
1385 lines (1166 loc) · 45.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
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 (C) 2013-2024 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#import "config.h"
#import "APICast.h"
#import "DateInstance.h"
#import "Error.h"
#import "Exception.h"
#import "JavaScriptCore.h"
#import "JSContextInternal.h"
#import "JSObjectRefPrivate.h"
#import "JSVirtualMachineInternal.h"
#import "JSValueInternal.h"
#import "JSValuePrivate.h"
#import "JSWrapperMap.h"
#import "MarkedJSValueRefArray.h"
#import "ObjcRuntimeExtras.h"
#import "JSCInlines.h"
#import "JSCJSValue.h"
#import "Strong.h"
#import "StrongInlines.h"
#import <wtf/Expected.h>
#import <wtf/HashMap.h>
#import <wtf/HashSet.h>
#import <wtf/Lock.h>
#import <wtf/StdLibExtras.h>
#import <wtf/Vector.h>
#import <wtf/text/WTFString.h>
#import <wtf/text/StringHash.h>
#if ENABLE(REMOTE_INSPECTOR)
#import "CallFrame.h"
#import "JSGlobalObject.h"
#import "JSGlobalObjectInspectorController.h"
#endif
#if JSC_OBJC_API_ENABLED
WTF_ALLOW_UNSAFE_BUFFER_USAGE_BEGIN
using JSC::Integrity::audit;
NSString * const JSPropertyDescriptorWritableKey = @"writable";
NSString * const JSPropertyDescriptorEnumerableKey = @"enumerable";
NSString * const JSPropertyDescriptorConfigurableKey = @"configurable";
NSString * const JSPropertyDescriptorValueKey = @"value";
NSString * const JSPropertyDescriptorGetKey = @"get";
NSString * const JSPropertyDescriptorSetKey = @"set";
@implementation JSValue {
JSValueRef m_value;
}
- (void)dealloc
{
if (_context) {
JSValueUnprotect([_context JSGlobalContextRef], m_value);
[_context release];
_context = nil;
}
[super dealloc];
}
- (NSString *)description
{
if (id wrapped = tryUnwrapObjcObject([_context JSGlobalContextRef], m_value))
return [wrapped description];
return [self toString];
}
- (JSValueRef)JSValueRef
{
return m_value;
}
+ (JSValue *)valueWithObject:(id)value inContext:(JSContext *)context
{
return [JSValue valueWithJSValueRef:objectToValue(context, value) inContext:context];
}
+ (JSValue *)valueWithBool:(BOOL)value inContext:(JSContext *)context
{
return [JSValue valueWithJSValueRef:JSValueMakeBoolean([context JSGlobalContextRef], value) inContext:context];
}
+ (JSValue *)valueWithDouble:(double)value inContext:(JSContext *)context
{
return [JSValue valueWithJSValueRef:JSValueMakeNumber([context JSGlobalContextRef], value) inContext:context];
}
+ (JSValue *)valueWithInt32:(int32_t)value inContext:(JSContext *)context
{
return [JSValue valueWithJSValueRef:JSValueMakeNumber([context JSGlobalContextRef], value) inContext:context];
}
+ (JSValue *)valueWithUInt32:(uint32_t)value inContext:(JSContext *)context
{
return [JSValue valueWithJSValueRef:JSValueMakeNumber([context JSGlobalContextRef], value) inContext:context];
}
+ (JSValue *)valueWithNewObjectInContext:(JSContext *)context
{
return [JSValue valueWithJSValueRef:JSObjectMake([context JSGlobalContextRef], 0, 0) inContext:context];
}
+ (JSValue *)valueWithNewArrayInContext:(JSContext *)context
{
return [JSValue valueWithJSValueRef:JSObjectMakeArray([context JSGlobalContextRef], 0, NULL, 0) inContext:context];
}
+ (JSValue *)valueWithNewRegularExpressionFromPattern:(NSString *)pattern flags:(NSString *)flags inContext:(JSContext *)context
{
auto patternString = OpaqueJSString::tryCreate(pattern);
auto flagsString = OpaqueJSString::tryCreate(flags);
JSValueRef arguments[2] = { JSValueMakeString([context JSGlobalContextRef], patternString.get()), JSValueMakeString([context JSGlobalContextRef], flagsString.get()) };
return [JSValue valueWithJSValueRef:JSObjectMakeRegExp([context JSGlobalContextRef], 2, arguments, 0) inContext:context];
}
+ (JSValue *)valueWithNewErrorFromMessage:(NSString *)message inContext:(JSContext *)context
{
auto string = OpaqueJSString::tryCreate(message);
JSValueRef argument = JSValueMakeString([context JSGlobalContextRef], string.get());
return [JSValue valueWithJSValueRef:JSObjectMakeError([context JSGlobalContextRef], 1, &argument, 0) inContext:context];
}
+ (JSValue *)valueWithNullInContext:(JSContext *)context
{
return [JSValue valueWithJSValueRef:JSValueMakeNull([context JSGlobalContextRef]) inContext:context];
}
+ (JSValue *)valueWithUndefinedInContext:(JSContext *)context
{
return [JSValue valueWithJSValueRef:JSValueMakeUndefined([context JSGlobalContextRef]) inContext:context];
}
+ (JSValue *)valueWithNewSymbolFromDescription:(NSString *)description inContext:(JSContext *)context
{
auto string = OpaqueJSString::tryCreate(description);
return [JSValue valueWithJSValueRef:JSValueMakeSymbol([context JSGlobalContextRef], string.get()) inContext:context];
}
+ (JSValue *)valueWithNewBigIntFromString:(NSString *)string inContext:(JSContext *)context
{
JSValueRef exception = nullptr;
JSValueRef bigInt = JSBigIntCreateWithString([context JSGlobalContextRef], OpaqueJSString::tryCreate(string).get(), &exception);
if (exception) {
[context notifyException:exception];
return nil;
}
return [JSValue valueWithJSValueRef:bigInt inContext:context];
}
+ (JSValue *)valueWithNewBigIntFromInt64:(int64_t)int64 inContext:(JSContext *)context
{
JSValueRef exception = nullptr;
JSValueRef bigInt = JSBigIntCreateWithInt64([context JSGlobalContextRef], int64, &exception);
if (exception) {
[context notifyException:exception];
return nil;
}
return [JSValue valueWithJSValueRef:bigInt inContext:context];
}
+ (JSValue *)valueWithNewBigIntFromUInt64:(uint64_t)uint64 inContext:(JSContext *)context
{
JSValueRef exception = nullptr;
JSValueRef bigInt = JSBigIntCreateWithUInt64([context JSGlobalContextRef], uint64, &exception);
if (exception) {
[context notifyException:exception];
return nil;
}
return [JSValue valueWithJSValueRef:bigInt inContext:context];
}
+ (JSValue *)valueWithNewBigIntFromDouble:(double)value inContext:(JSContext *)context
{
JSValueRef exception = nullptr;
JSValueRef bigInt = JSBigIntCreateWithDouble([context JSGlobalContextRef], value, &exception);
if (exception) {
[context notifyException:exception];
return nil;
}
return [JSValue valueWithJSValueRef:bigInt inContext:context];
}
- (JSRelationCondition)compareUInt64:(uint64_t)other
{
JSValueRef exception = nullptr;
JSRelationCondition result = JSValueCompareUInt64([_context JSGlobalContextRef], m_value, other, &exception);
if (exception)
[_context notifyException:exception];
return result;
}
- (JSRelationCondition)compareInt64:(int64_t)other
{
JSValueRef exception = nullptr;
JSRelationCondition result = JSValueCompareInt64([_context JSGlobalContextRef], m_value, other, &exception);
if (exception)
[_context notifyException:exception];
return result;
}
- (JSRelationCondition)compareDouble:(double)other
{
JSValueRef exception = nullptr;
JSRelationCondition result = JSValueCompareDouble([_context JSGlobalContextRef], m_value, other, &exception);
if (exception)
[_context notifyException:exception];
return result;
}
- (JSRelationCondition)compareJSValue:(JSValue *)other
{
JSValueRef exception = nullptr;
JSRelationCondition result = JSValueCompare([_context JSGlobalContextRef], m_value, other->m_value, &exception);
if (exception)
[_context notifyException:exception];
return result;
}
+ (JSValue *)valueWithNewPromiseInContext:(JSContext *)context fromExecutor:(void (^)(JSValue *, JSValue *))executor
{
JSObjectRef resolve;
JSObjectRef reject;
JSValueRef exception = nullptr;
JSObjectRef promise = JSObjectMakeDeferredPromise([context JSGlobalContextRef], &resolve, &reject, &exception);
if (exception) {
[context notifyException:exception];
return nil;
}
JSValue *result = [JSValue valueWithJSValueRef:promise inContext:context];
JSValue *rejection = [JSValue valueWithJSValueRef:reject inContext:context];
CallbackData callbackData;
const size_t argumentCount = 2;
JSValueRef arguments[argumentCount];
arguments[0] = resolve;
arguments[1] = reject;
[context beginCallbackWithData:&callbackData calleeValue:nullptr thisValue:promise argumentCount:argumentCount arguments:arguments];
executor([JSValue valueWithJSValueRef:resolve inContext:context], rejection);
if (context.exception)
[rejection callWithArguments:@[context.exception]];
[context endCallbackWithData:&callbackData];
return result;
}
+ (JSValue *)valueWithNewPromiseResolvedWithResult:(id)result inContext:(JSContext *)context
{
return [JSValue valueWithNewPromiseInContext:context fromExecutor:^(JSValue *resolve, JSValue *) {
[resolve callWithArguments:@[result]];
}];
}
+ (JSValue *)valueWithNewPromiseRejectedWithReason:(id)reason inContext:(JSContext *)context
{
return [JSValue valueWithNewPromiseInContext:context fromExecutor:^(JSValue *, JSValue *reject) {
[reject callWithArguments:@[reason]];
}];
}
- (id)toObject
{
return valueToObject(_context, m_value);
}
- (id)toObjectOfClass:(Class)expectedClass
{
id result = [self toObject];
return [result isKindOfClass:expectedClass] ? result : nil;
}
- (BOOL)toBool
{
return JSValueToBoolean([_context JSGlobalContextRef], m_value);
}
- (double)toDouble
{
JSValueRef exception = 0;
double result = JSValueToNumber([_context JSGlobalContextRef], m_value, &exception);
if (exception) {
[_context notifyException:exception];
return std::numeric_limits<double>::quiet_NaN();
}
return result;
}
- (int32_t)toInt32
{
JSValueRef exception = nullptr;
int32_t result = JSValueToInt32([_context JSGlobalContextRef], m_value, &exception);
if (exception) {
[_context notifyException:exception];
return 0;
}
return result;
}
- (uint32_t)toUInt32
{
JSValueRef exception = nullptr;
uint32_t result = JSValueToUInt32([_context JSGlobalContextRef], m_value, &exception);
if (exception)
[_context notifyException:exception];
return result;
}
- (int64_t)toInt64
{
JSValueRef exception = nullptr;
int64_t result = JSValueToInt64([_context JSGlobalContextRef], m_value, &exception);
if (exception) {
[_context notifyException:exception];
return 0;
}
return result;
}
- (uint64_t)toUInt64
{
JSValueRef exception = nullptr;
uint64_t result = JSValueToUInt64([_context JSGlobalContextRef], m_value, &exception);
if (exception)
[_context notifyException:exception];
return result;
}
- (NSNumber *)toNumber
{
JSValueRef exception = 0;
id result = valueToNumber([_context JSGlobalContextRef], m_value, &exception);
if (exception)
[_context notifyException:exception];
return result;
}
- (NSString *)toString
{
JSValueRef exception = 0;
id result = valueToString([_context JSGlobalContextRef], m_value, &exception);
if (exception)
[_context notifyException:exception];
return result;
}
- (NSDate *)toDate
{
JSValueRef exception = 0;
id result = valueToDate([_context JSGlobalContextRef], m_value, &exception);
if (exception)
[_context notifyException:exception];
return result;
}
- (NSArray *)toArray
{
JSValueRef exception = 0;
id result = valueToArray([_context JSGlobalContextRef], m_value, &exception);
if (exception)
[_context notifyException:exception];
return result;
}
- (NSDictionary *)toDictionary
{
JSValueRef exception = 0;
id result = valueToDictionary([_context JSGlobalContextRef], m_value, &exception);
if (exception)
[_context notifyException:exception];
return result;
}
template<typename Result, typename NSStringFunction, typename JSValueFunction, typename... Types>
inline Expected<Result, JSValueRef> performPropertyOperation(NSStringFunction stringFunction, JSValueFunction jsFunction, JSValue* value, id propertyKey, Types... arguments)
{
JSContext* context = [value context];
JSValueRef exception = nullptr;
JSObjectRef object = JSValueToObject([context JSGlobalContextRef], [value JSValueRef], &exception);
if (exception)
return Unexpected<JSValueRef>(exception);
Result result;
// If it's a NSString already, reduce indirection and just pass the NSString.
if ([propertyKey isKindOfClass:[NSString class]]) {
auto name = OpaqueJSString::tryCreate((NSString *)propertyKey);
result = stringFunction([context JSGlobalContextRef], object, name.get(), arguments..., &exception);
} else
result = jsFunction([context JSGlobalContextRef], object, [[JSValue valueWithObject:propertyKey inContext:context] JSValueRef], arguments..., &exception);
return Expected<Result, JSValueRef>(result);
}
- (JSValue *)valueForProperty:(id)key
{
auto result = performPropertyOperation<JSValueRef>(JSObjectGetProperty, JSObjectGetPropertyForKey, self, key);
if (!result)
return [_context valueFromNotifyException:result.error()];
return [JSValue valueWithJSValueRef:result.value() inContext:_context];
}
- (void)setValue:(id)value forProperty:(JSValueProperty)key
{
// We need Unit business because void can't be assigned to in performPropertyOperation and I don't want to duplicate the code...
using Unit = std::tuple<>;
auto stringSetProperty = [] (auto... args) -> Unit {
JSObjectSetProperty(args...);
return { };
};
auto jsValueSetProperty = [] (auto... args) -> Unit {
JSObjectSetPropertyForKey(args...);
return { };
};
auto result = performPropertyOperation<Unit>(stringSetProperty, jsValueSetProperty, self, key, objectToValue(_context, value), kJSPropertyAttributeNone);
if (!result) {
[_context notifyException:result.error()];
return;
}
}
- (BOOL)deleteProperty:(JSValueProperty)key
{
Expected<BOOL, JSValueRef> result = performPropertyOperation<BOOL>(JSObjectDeleteProperty, JSObjectDeletePropertyForKey, self, key);
if (!result)
return [_context boolFromNotifyException:result.error()];
return result.value();
}
- (BOOL)hasProperty:(JSValueProperty)key
{
// The C-api doesn't return an exception value for the string version of has property.
auto stringHasProperty = [] (JSContextRef ctx, JSObjectRef object, JSStringRef propertyName, JSValueRef*) -> BOOL {
return JSObjectHasProperty(ctx, object, propertyName);
};
Expected<BOOL, JSValueRef> result = performPropertyOperation<BOOL>(stringHasProperty, JSObjectHasPropertyForKey, self, key);
if (!result)
return [_context boolFromNotifyException:result.error()];
return result.value();
}
- (void)defineProperty:(JSValueProperty)key descriptor:(id)descriptor
{
[[_context globalObject][@"Object"] invokeMethod:@"defineProperty" withArguments:@[ self, key, descriptor ]];
}
- (JSValue *)valueAtIndex:(NSUInteger)index
{
// Properties that are higher than an unsigned value can hold are converted to a double then inserted as a normal property.
// Indices that are bigger than the max allowed index size (UINT_MAX - 1) will be handled internally in get().
if (index != (unsigned)index)
return [self valueForProperty:[[JSValue valueWithDouble:index inContext:_context] toString]];
JSValueRef exception = 0;
JSObjectRef object = JSValueToObject([_context JSGlobalContextRef], m_value, &exception);
if (exception)
return [_context valueFromNotifyException:exception];
JSValueRef result = JSObjectGetPropertyAtIndex([_context JSGlobalContextRef], object, (unsigned)index, &exception);
if (exception)
return [_context valueFromNotifyException:exception];
return [JSValue valueWithJSValueRef:result inContext:_context];
}
- (void)setValue:(id)value atIndex:(NSUInteger)index
{
// Properties that are higher than an unsigned value can hold are converted to a double, then inserted as a normal property.
// Indices that are bigger than the max allowed index size (UINT_MAX - 1) will be handled internally in putByIndex().
if (index != (unsigned)index)
return [self setValue:value forProperty:[[JSValue valueWithDouble:index inContext:_context] toString]];
JSValueRef exception = 0;
JSObjectRef object = JSValueToObject([_context JSGlobalContextRef], m_value, &exception);
if (exception) {
[_context notifyException:exception];
return;
}
JSObjectSetPropertyAtIndex([_context JSGlobalContextRef], object, (unsigned)index, objectToValue(_context, value), &exception);
if (exception) {
[_context notifyException:exception];
return;
}
}
- (BOOL)isUndefined
{
#if !CPU(ADDRESS64)
return JSValueIsUndefined([_context JSGlobalContextRef], m_value);
#else
return toJS(m_value).isUndefined();
#endif
}
- (BOOL)isNull
{
#if !CPU(ADDRESS64)
return JSValueIsNull([_context JSGlobalContextRef], m_value);
#else
return toJS(m_value).isNull();
#endif
}
- (BOOL)isBoolean
{
#if !CPU(ADDRESS64)
return JSValueIsBoolean([_context JSGlobalContextRef], m_value);
#else
return toJS(m_value).isBoolean();
#endif
}
- (BOOL)isNumber
{
#if !CPU(ADDRESS64)
return JSValueIsNumber([_context JSGlobalContextRef], m_value);
#else
return toJS(m_value).isNumber();
#endif
}
- (BOOL)isString
{
#if !CPU(ADDRESS64)
return JSValueIsString([_context JSGlobalContextRef], m_value);
#else
return toJS(m_value).isString();
#endif
}
- (BOOL)isObject
{
#if !CPU(ADDRESS64)
return JSValueIsObject([_context JSGlobalContextRef], m_value);
#else
return toJS(m_value).isObject();
#endif
}
- (BOOL)isSymbol
{
#if !CPU(ADDRESS64)
return JSValueIsSymbol([_context JSGlobalContextRef], m_value);
#else
return toJS(m_value).isSymbol();
#endif
}
- (BOOL)isBigInt
{
#if !CPU(ADDRESS64)
return JSValueIsBigInt([_context JSGlobalContextRef], m_value);
#else
return toJS(m_value).isBigInt();
#endif
}
- (BOOL)isArray
{
return JSValueIsArray([_context JSGlobalContextRef], m_value);
}
- (BOOL)isDate
{
return JSValueIsDate([_context JSGlobalContextRef], m_value);
}
- (BOOL)isEqualToObject:(id)value
{
return JSValueIsStrictEqual([_context JSGlobalContextRef], m_value, objectToValue(_context, value));
}
- (BOOL)isEqualWithTypeCoercionToObject:(id)value
{
JSValueRef exception = 0;
BOOL result = JSValueIsEqual([_context JSGlobalContextRef], m_value, objectToValue(_context, value), &exception);
if (exception)
return [_context boolFromNotifyException:exception];
return result;
}
- (BOOL)isInstanceOf:(id)value
{
JSValueRef exception = 0;
JSObjectRef constructor = JSValueToObject([_context JSGlobalContextRef], objectToValue(_context, value), &exception);
if (exception)
return [_context boolFromNotifyException:exception];
BOOL result = JSValueIsInstanceOfConstructor([_context JSGlobalContextRef], m_value, constructor, &exception);
if (exception)
return [_context boolFromNotifyException:exception];
return result;
}
- (JSValue *)callWithArguments:(NSArray *)argumentArray
{
JSC::JSGlobalObject* globalObject = toJS([_context JSGlobalContextRef]);
JSC::VM& vm = globalObject->vm();
JSC::JSLockHolder locker(vm);
NSUInteger argumentCount = [argumentArray count];
JSC::MarkedJSValueRefArray arguments([_context JSGlobalContextRef], argumentCount);
for (unsigned i = 0; i < argumentCount; ++i)
arguments[i] = objectToValue(_context, [argumentArray objectAtIndex:i]);
JSValueRef exception = 0;
JSObjectRef object = JSValueToObject([_context JSGlobalContextRef], m_value, &exception);
if (exception)
return [_context valueFromNotifyException:exception];
JSValueRef result = JSObjectCallAsFunction([_context JSGlobalContextRef], object, 0, argumentCount, arguments.data(), &exception);
if (exception)
return [_context valueFromNotifyException:exception];
return [JSValue valueWithJSValueRef:result inContext:_context];
}
- (JSValue *)constructWithArguments:(NSArray *)argumentArray
{
JSC::JSGlobalObject* globalObject = toJS([_context JSGlobalContextRef]);
JSC::VM& vm = globalObject->vm();
JSC::JSLockHolder locker(vm);
NSUInteger argumentCount = [argumentArray count];
JSC::MarkedJSValueRefArray arguments([_context JSGlobalContextRef], argumentCount);
for (unsigned i = 0; i < argumentCount; ++i)
arguments[i] = objectToValue(_context, [argumentArray objectAtIndex:i]);
JSValueRef exception = 0;
JSObjectRef object = JSValueToObject([_context JSGlobalContextRef], m_value, &exception);
if (exception)
return [_context valueFromNotifyException:exception];
JSObjectRef result = JSObjectCallAsConstructor([_context JSGlobalContextRef], object, argumentCount, arguments.data(), &exception);
if (exception)
return [_context valueFromNotifyException:exception];
return [JSValue valueWithJSValueRef:result inContext:_context];
}
- (JSValue *)invokeMethod:(NSString *)method withArguments:(NSArray *)arguments
{
JSC::JSGlobalObject* globalObject = toJS([_context JSGlobalContextRef]);
JSC::VM& vm = globalObject->vm();
JSC::JSLockHolder locker(vm);
NSUInteger argumentCount = [arguments count];
JSC::MarkedJSValueRefArray argumentArray([_context JSGlobalContextRef], argumentCount);
for (unsigned i = 0; i < argumentCount; ++i)
argumentArray[i] = objectToValue(_context, [arguments objectAtIndex:i]);
JSValueRef exception = 0;
JSObjectRef thisObject = JSValueToObject([_context JSGlobalContextRef], m_value, &exception);
if (exception)
return [_context valueFromNotifyException:exception];
auto name = OpaqueJSString::tryCreate(method);
JSValueRef function = JSObjectGetProperty([_context JSGlobalContextRef], thisObject, name.get(), &exception);
if (exception)
return [_context valueFromNotifyException:exception];
JSObjectRef object = JSValueToObject([_context JSGlobalContextRef], function, &exception);
if (exception)
return [_context valueFromNotifyException:exception];
JSValueRef result = JSObjectCallAsFunction([_context JSGlobalContextRef], object, thisObject, argumentCount, argumentArray.data(), &exception);
if (exception)
return [_context valueFromNotifyException:exception];
return [JSValue valueWithJSValueRef:result inContext:_context];
}
@end
@implementation JSValue(StructSupport)
- (CGPoint)toPoint
{
return (CGPoint){
static_cast<CGFloat>([self[@"x"] toDouble]),
static_cast<CGFloat>([self[@"y"] toDouble])
};
}
- (NSRange)toRange
{
return (NSRange){
[[self[@"location"] toNumber] unsignedIntegerValue],
[[self[@"length"] toNumber] unsignedIntegerValue]
};
}
- (CGRect)toRect
{
return (CGRect){
[self toPoint],
[self toSize]
};
}
- (CGSize)toSize
{
return (CGSize){
static_cast<CGFloat>([self[@"width"] toDouble]),
static_cast<CGFloat>([self[@"height"] toDouble])
};
}
+ (JSValue *)valueWithPoint:(CGPoint)point inContext:(JSContext *)context
{
return [JSValue valueWithObject:@{
@"x":@(point.x),
@"y":@(point.y)
} inContext:context];
}
+ (JSValue *)valueWithRange:(NSRange)range inContext:(JSContext *)context
{
return [JSValue valueWithObject:@{
@"location":@(range.location),
@"length":@(range.length)
} inContext:context];
}
+ (JSValue *)valueWithRect:(CGRect)rect inContext:(JSContext *)context
{
return [JSValue valueWithObject:@{
@"x":@(rect.origin.x),
@"y":@(rect.origin.y),
@"width":@(rect.size.width),
@"height":@(rect.size.height)
} inContext:context];
}
+ (JSValue *)valueWithSize:(CGSize)size inContext:(JSContext *)context
{
return [JSValue valueWithObject:@{
@"width":@(size.width),
@"height":@(size.height)
} inContext:context];
}
@end
@implementation JSValue(SubscriptSupport)
- (JSValue *)objectForKeyedSubscript:(id)key
{
return [self valueForProperty:key];
}
- (JSValue *)objectAtIndexedSubscript:(NSUInteger)index
{
return [self valueAtIndex:index];
}
- (void)setObject:(id)object forKeyedSubscript:(id)key
{
[self setValue:object forProperty:key];
}
- (void)setObject:(id)object atIndexedSubscript:(NSUInteger)index
{
[self setValue:object atIndex:index];
}
@end
inline bool isDate(JSObjectRef object, JSGlobalContextRef context)
{
JSC::JSLockHolder locker(toJS(context));
return toJS(object)->inherits<JSC::DateInstance>();
}
inline bool isArray(JSObjectRef object, JSGlobalContextRef context)
{
JSC::JSLockHolder locker(toJS(context));
return toJS(object)->inherits<JSC::JSArray>();
}
@implementation JSValue(Internal)
enum ConversionType {
ContainerNone,
ContainerArray,
ContainerDictionary
};
class JSContainerConvertor {
public:
struct Task {
JSValueRef js;
id objc;
ConversionType type;
};
JSContainerConvertor(JSGlobalContextRef context)
: m_context(context)
{
}
id convert(JSValueRef property);
void add(Task);
Task take();
bool isWorkListEmpty() const { return !m_worklist.size(); }
private:
JSGlobalContextRef m_context;
UncheckedKeyHashMap<JSValueRef, __unsafe_unretained id> m_objectMap;
Vector<Task> m_worklist;
Vector<JSC::Strong<JSC::Unknown>> m_jsValues;
};
inline id JSContainerConvertor::convert(JSValueRef value)
{
auto iter = m_objectMap.find(value);
if (iter != m_objectMap.end())
return iter->value;
Task result = valueToObjectWithoutCopy(m_context, value);
if (result.js)
add(result);
return result.objc;
}
void JSContainerConvertor::add(Task task)
{
JSC::JSGlobalObject* globalObject = toJS(m_context);
m_jsValues.append(JSC::Strong<JSC::Unknown>(globalObject->vm(), toJSForGC(globalObject, task.js)));
m_objectMap.add(task.js, task.objc);
if (task.type != ContainerNone)
m_worklist.append(task);
}
JSContainerConvertor::Task JSContainerConvertor::take()
{
ASSERT(!isWorkListEmpty());
Task last = m_worklist.last();
m_worklist.removeLast();
return last;
}
#if ENABLE(REMOTE_INSPECTOR)
static void reportExceptionToInspector(JSGlobalContextRef context, JSC::JSValue exceptionValue)
{
JSC::JSGlobalObject* globalObject = toJS(context);
JSC::VM& vm = globalObject->vm();
JSC::Exception* exception = JSC::Exception::create(vm, exceptionValue);
globalObject->inspectorController().reportAPIException(globalObject, exception);
}
#endif
static JSContainerConvertor::Task valueToObjectWithoutCopy(JSGlobalContextRef context, JSValueRef value)
{
if (!JSValueIsObject(context, value)) {
id primitive;
if (JSValueIsBoolean(context, value))
primitive = JSValueToBoolean(context, value) ? @YES : @NO;
else if (JSValueIsNumber(context, value)) {
// Normalize the number, so it will unique correctly in the hash map -
// it's nicer not to leak this internal implementation detail!
value = JSValueMakeNumber(context, JSValueToNumber(context, value, 0));
primitive = @(JSValueToNumber(context, value, 0));
} else if (JSValueIsString(context, value)) {
// Would be nice to unique strings, too.
auto jsstring = adoptRef(JSValueToStringCopy(context, value, 0));
primitive = adoptCF(JSStringCopyCFString(kCFAllocatorDefault, jsstring.get())).bridgingAutorelease();
} else if (JSValueIsNull(context, value))
primitive = [NSNull null];
else {
ASSERT(JSValueIsUndefined(context, value));
primitive = nil;
}
return { value, primitive, ContainerNone };
}
JSObjectRef object = JSValueToObject(context, value, 0);
if (id wrapped = tryUnwrapObjcObject(context, object))
return { object, wrapped, ContainerNone };
if (isDate(object, context))
return { object, [NSDate dateWithTimeIntervalSince1970:JSValueToNumber(context, object, 0) / 1000.0], ContainerNone };
if (isArray(object, context))
return { object, [NSMutableArray array], ContainerArray };
return { object, [NSMutableDictionary dictionary], ContainerDictionary };
}
static id containerValueToObject(JSGlobalContextRef context, JSContainerConvertor::Task task)
{
ASSERT(task.type != ContainerNone);
JSC::JSLockHolder locker(toJS(context));
JSContainerConvertor convertor(context);
convertor.add(task);
ASSERT(!convertor.isWorkListEmpty());
do {
JSContainerConvertor::Task current = convertor.take();
ASSERT(JSValueIsObject(context, current.js));
JSObjectRef js = JSValueToObject(context, current.js, 0);
if (current.type == ContainerArray) {
ASSERT([current.objc isKindOfClass:[NSMutableArray class]]);
NSMutableArray *array = (NSMutableArray *)current.objc;
auto lengthString = OpaqueJSString::tryCreate("length"_s);
unsigned length = JSC::toUInt32(JSValueToNumber(context, JSObjectGetProperty(context, js, lengthString.get(), 0), 0));
for (unsigned i = 0; i < length; ++i) {
id objc = convertor.convert(JSObjectGetPropertyAtIndex(context, js, i, 0));
[array addObject:objc ? objc : [NSNull null]];
}
} else {
ASSERT([current.objc isKindOfClass:[NSMutableDictionary class]]);
NSMutableDictionary *dictionary = (NSMutableDictionary *)current.objc;
JSC::JSLockHolder locker(toJS(context));
JSPropertyNameArrayRef propertyNameArray = JSObjectCopyPropertyNames(context, js);
size_t length = JSPropertyNameArrayGetCount(propertyNameArray);
for (size_t i = 0; i < length; ++i) {
JSStringRef propertyName = JSPropertyNameArrayGetNameAtIndex(propertyNameArray, i);
if (id objc = convertor.convert(JSObjectGetProperty(context, js, propertyName, 0)))
dictionary[(__bridge NSString *)adoptCF(JSStringCopyCFString(kCFAllocatorDefault, propertyName)).get()] = objc;
}
JSPropertyNameArrayRelease(propertyNameArray);
}
} while (!convertor.isWorkListEmpty());
return task.objc;
}
id valueToObject(JSContext *context, JSValueRef value)
{
JSContainerConvertor::Task result = valueToObjectWithoutCopy([context JSGlobalContextRef], value);
if (result.type == ContainerNone)
return result.objc;
return containerValueToObject([context JSGlobalContextRef], result);
}
id valueToNumber(JSGlobalContextRef context, JSValueRef value, JSValueRef* exception)
{
ASSERT(!*exception);
if (id wrapped = tryUnwrapObjcObject(context, value)) {
if ([wrapped isKindOfClass:[NSNumber class]])
return wrapped;
}
if (JSValueIsBoolean(context, value))
return JSValueToBoolean(context, value) ? @YES : @NO;
double result = JSValueToNumber(context, value, exception);
return @(*exception ? std::numeric_limits<double>::quiet_NaN() : result);
}
id valueToString(JSGlobalContextRef context, JSValueRef value, JSValueRef* exception)
{
ASSERT(!*exception);
if (id wrapped = tryUnwrapObjcObject(context, value)) {
if ([wrapped isKindOfClass:[NSString class]])
return wrapped;
}