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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
|
/*
* Copyright (C) 2013 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.
*/
#include "config.h"
#import "APICast.h"
#import "APIShims.h"
#import "DateInstance.h"
#import "Error.h"
#import "JavaScriptCore.h"
#import "JSContextInternal.h"
#import "JSVirtualMachineInternal.h"
#import "JSValueInternal.h"
#import "JSWrapperMap.h"
#import "ObjcRuntimeExtras.h"
#import "Operations.h"
#import "JSCJSValue.h"
#import <wtf/HashMap.h>
#import <wtf/HashSet.h>
#import <wtf/Vector.h>
#import <wtf/TCSpinLock.h>
#import <wtf/text/WTFString.h>
#import <wtf/text/StringHash.h>
#if JSC_OBJC_API_ENABLED
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;
}
- (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
{
JSStringRef patternString = JSStringCreateWithCFString((CFStringRef)pattern);
JSStringRef flagsString = JSStringCreateWithCFString((CFStringRef)flags);
JSValueRef arguments[2] = { JSValueMakeString([context JSGlobalContextRef], patternString), JSValueMakeString([context JSGlobalContextRef], flagsString) };
JSStringRelease(patternString);
JSStringRelease(flagsString);
return [JSValue valueWithJSValueRef:JSObjectMakeRegExp([context JSGlobalContextRef], 2, arguments, 0) inContext:context];
}
+ (JSValue *)valueWithNewErrorFromMessage:(NSString *)message inContext:(JSContext *)context
{
JSStringRef string = JSStringCreateWithCFString((CFStringRef)message);
JSValueRef argument = JSValueMakeString([context JSGlobalContextRef], string);
JSStringRelease(string);
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];
}
- (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
{
return JSC::toInt32([self toDouble]);
}
- (uint32_t)toUInt32
{
return JSC::toUInt32([self toDouble]);
}
- (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;
}
- (JSValue *)valueForProperty:(NSString *)propertyName
{
JSValueRef exception = 0;
JSObjectRef object = JSValueToObject([_context JSGlobalContextRef], m_value, &exception);
if (exception)
return [_context valueFromNotifyException:exception];
JSStringRef name = JSStringCreateWithCFString((CFStringRef)propertyName);
JSValueRef result = JSObjectGetProperty([_context JSGlobalContextRef], object, name, &exception);
JSStringRelease(name);
if (exception)
return [_context valueFromNotifyException:exception];
return [JSValue valueWithJSValueRef:result inContext:_context];
}
- (void)setValue:(id)value forProperty:(NSString *)propertyName
{
JSValueRef exception = 0;
JSObjectRef object = JSValueToObject([_context JSGlobalContextRef], m_value, &exception);
if (exception) {
[_context notifyException:exception];
return;
}
JSStringRef name = JSStringCreateWithCFString((CFStringRef)propertyName);
JSObjectSetProperty([_context JSGlobalContextRef], object, name, objectToValue(_context, value), 0, &exception);
JSStringRelease(name);
if (exception) {
[_context notifyException:exception];
return;
}
}
- (BOOL)deleteProperty:(NSString *)propertyName
{
JSValueRef exception = 0;
JSObjectRef object = JSValueToObject([_context JSGlobalContextRef], m_value, &exception);
if (exception)
return [_context boolFromNotifyException:exception];
JSStringRef name = JSStringCreateWithCFString((CFStringRef)propertyName);
BOOL result = JSObjectDeleteProperty([_context JSGlobalContextRef], object, name, &exception);
JSStringRelease(name);
if (exception)
return [_context boolFromNotifyException:exception];
return result;
}
- (BOOL)hasProperty:(NSString *)propertyName
{
JSValueRef exception = 0;
JSObjectRef object = JSValueToObject([_context JSGlobalContextRef], m_value, &exception);
if (exception)
return [_context boolFromNotifyException:exception];
JSStringRef name = JSStringCreateWithCFString((CFStringRef)propertyName);
BOOL result = JSObjectHasProperty([_context JSGlobalContextRef], object, name);
JSStringRelease(name);
return result;
}
- (void)defineProperty:(NSString *)property descriptor:(id)descriptor
{
[[_context globalObject][@"Object"] invokeMethod:@"defineProperty" withArguments:@[ self, property, 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
{
return JSValueIsUndefined([_context JSGlobalContextRef], m_value);
}
- (BOOL)isNull
{
return JSValueIsNull([_context JSGlobalContextRef], m_value);
}
- (BOOL)isBoolean
{
return JSValueIsBoolean([_context JSGlobalContextRef], m_value);
}
- (BOOL)isNumber
{
return JSValueIsNumber([_context JSGlobalContextRef], m_value);
}
- (BOOL)isString
{
return JSValueIsString([_context JSGlobalContextRef], m_value);
}
- (BOOL)isObject
{
return JSValueIsObject([_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
{
NSUInteger argumentCount = [argumentArray count];
JSValueRef arguments[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, &exception);
if (exception)
return [_context valueFromNotifyException:exception];
return [JSValue valueWithJSValueRef:result inContext:_context];
}
- (JSValue *)constructWithArguments:(NSArray *)argumentArray
{
NSUInteger argumentCount = [argumentArray count];
JSValueRef arguments[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, &exception);
if (exception)
return [_context valueFromNotifyException:exception];
return [JSValue valueWithJSValueRef:result inContext:_context];
}
- (JSValue *)invokeMethod:(NSString *)method withArguments:(NSArray *)arguments
{
NSUInteger argumentCount = [arguments count];
JSValueRef argumentArray[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];
JSStringRef name = JSStringCreateWithCFString((CFStringRef)method);
JSValueRef function = JSObjectGetProperty([_context JSGlobalContextRef], thisObject, name, &exception);
JSStringRelease(name);
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, &exception);
if (exception)
return [_context valueFromNotifyException:exception];
return [JSValue valueWithJSValueRef:result inContext:_context];
}
@end
@implementation JSValue(StructSupport)
- (CGPoint)toPoint
{
return (CGPoint){
[self[@"x"] toDouble],
[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){
[self[@"width"] toDouble],
[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
{
if (![key isKindOfClass:[NSString class]]) {
key = [[JSValue valueWithObject:key inContext:_context] toString];
if (!key)
return [JSValue valueWithUndefinedInContext:_context];
}
return [self valueForProperty:(NSString *)key];
}
- (JSValue *)objectAtIndexedSubscript:(NSUInteger)index
{
return [self valueAtIndex:index];
}
- (void)setObject:(id)object forKeyedSubscript:(NSObject <NSCopying> *)key
{
if (![key isKindOfClass:[NSString class]]) {
key = [[JSValue valueWithObject:key inContext:_context] toString];
if (!key)
return;
}
[self setValue:object forProperty:(NSString *)key];
}
- (void)setObject:(id)object atIndexedSubscript:(NSUInteger)index
{
[self setValue:object atIndex:index];
}
@end
inline bool isDate(JSObjectRef object, JSGlobalContextRef context)
{
JSC::APIEntryShim entryShim(toJS(context));
return toJS(object)->inherits(&JSC::DateInstance::s_info);
}
inline bool isArray(JSObjectRef object, JSGlobalContextRef context)
{
JSC::APIEntryShim entryShim(toJS(context));
return toJS(object)->inherits(&JSC::JSArray::s_info);
}
@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;
HashMap<JSValueRef, id> m_objectMap;
Vector<Task> m_worklist;
};
inline id JSContainerConvertor::convert(JSValueRef value)
{
HashMap<JSValueRef, id>::iterator 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)
{
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;
}
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 = [NSNumber numberWithDouble:JSValueToNumber(context, value, 0)];
} else if (JSValueIsString(context, value)) {
// Would be nice to unique strings, too.
JSStringRef jsstring = JSValueToStringCopy(context, value, 0);
NSString * stringNS = (NSString *)JSStringCopyCFString(kCFAllocatorDefault, jsstring);
JSStringRelease(jsstring);
primitive = [stringNS autorelease];
} else if (JSValueIsNull(context, value))
primitive = [NSNull null];
else {
ASSERT(JSValueIsUndefined(context, value));
primitive = nil;
}
return (JSContainerConvertor::Task){ value, primitive, ContainerNone };
}
JSObjectRef object = JSValueToObject(context, value, 0);
if (id wrapped = tryUnwrapObjcObject(context, object))
return (JSContainerConvertor::Task){ object, wrapped, ContainerNone };
if (isDate(object, context))
return (JSContainerConvertor::Task){ object, [NSDate dateWithTimeIntervalSince1970:JSValueToNumber(context, object, 0)], ContainerNone };
if (isArray(object, context))
return (JSContainerConvertor::Task){ object, [NSMutableArray array], ContainerArray };
return (JSContainerConvertor::Task){ object, [NSMutableDictionary dictionary], ContainerDictionary };
}
static id containerValueToObject(JSGlobalContextRef context, JSContainerConvertor::Task task)
{
ASSERT(task.type != ContainerNone);
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;
JSStringRef lengthString = JSStringCreateWithUTF8CString("length");
unsigned length = JSC::toUInt32(JSValueToNumber(context, JSObjectGetProperty(context, js, lengthString, 0), 0));
JSStringRelease(lengthString);
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;
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[[(NSString *)JSStringCopyCFString(kCFAllocatorDefault, propertyName) autorelease]] = 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 [NSNumber numberWithDouble:*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;
}
JSStringRef jsstring = JSValueToStringCopy(context, value, exception);
if (*exception) {
ASSERT(!jsstring);
return nil;
}
NSString *stringNS = [(NSString *)JSStringCopyCFString(kCFAllocatorDefault, jsstring) autorelease];
JSStringRelease(jsstring);
return stringNS;
}
id valueToDate(JSGlobalContextRef context, JSValueRef value, JSValueRef* exception)
{
ASSERT(!*exception);
if (id wrapped = tryUnwrapObjcObject(context, value)) {
if ([wrapped isKindOfClass:[NSDate class]])
return wrapped;
}
double result = JSValueToNumber(context, value, exception);
return *exception ? nil : [NSDate dateWithTimeIntervalSince1970:result];
}
id valueToArray(JSGlobalContextRef context, JSValueRef value, JSValueRef* exception)
{
ASSERT(!*exception);
if (id wrapped = tryUnwrapObjcObject(context, value)) {
if ([wrapped isKindOfClass:[NSArray class]])
return wrapped;
}
if (JSValueIsObject(context, value))
return containerValueToObject(context, (JSContainerConvertor::Task){ value, [NSMutableArray array], ContainerArray});
if (!(JSValueIsNull(context, value) || JSValueIsUndefined(context, value)))
*exception = toRef(JSC::createTypeError(toJS(context), "Cannot convert primitive to NSArray"));
return nil;
}
id valueToDictionary(JSGlobalContextRef context, JSValueRef value, JSValueRef* exception)
{
ASSERT(!*exception);
if (id wrapped = tryUnwrapObjcObject(context, value)) {
if ([wrapped isKindOfClass:[NSDictionary class]])
return wrapped;
}
if (JSValueIsObject(context, value))
return containerValueToObject(context, (JSContainerConvertor::Task){ value, [NSMutableDictionary dictionary], ContainerDictionary});
if (!(JSValueIsNull(context, value) || JSValueIsUndefined(context, value)))
*exception = toRef(JSC::createTypeError(toJS(context), "Cannot convert primitive to NSDictionary"));
return nil;
}
class ObjcContainerConvertor {
public:
struct Task {
id objc;
JSValueRef js;
ConversionType type;
};
ObjcContainerConvertor(JSContext *context)
: m_context(context)
{
}
JSValueRef convert(id object);
void add(Task);
Task take();
bool isWorkListEmpty() const { return !m_worklist.size(); }
private:
JSContext *m_context;
HashMap<id, JSValueRef> m_objectMap;
Vector<Task> m_worklist;
};
JSValueRef ObjcContainerConvertor::convert(id object)
{
ASSERT(object);
auto it = m_objectMap.find(object);
if (it != m_objectMap.end())
return it->value;
ObjcContainerConvertor::Task task = objectToValueWithoutCopy(m_context, object);
add(task);
return task.js;
}
void ObjcContainerConvertor::add(ObjcContainerConvertor::Task task)
{
m_objectMap.add(task.objc, task.js);
if (task.type != ContainerNone)
m_worklist.append(task);
}
ObjcContainerConvertor::Task ObjcContainerConvertor::take()
{
ASSERT(!isWorkListEmpty());
Task last = m_worklist.last();
m_worklist.removeLast();
return last;
}
inline bool isNSBoolean(id object)
{
ASSERT([@YES class] == [@NO class]);
ASSERT([@YES class] != [NSNumber class]);
ASSERT([[@YES class] isSubclassOfClass:[NSNumber class]]);
return [object isKindOfClass:[@YES class]];
}
static ObjcContainerConvertor::Task objectToValueWithoutCopy(JSContext *context, id object)
{
JSGlobalContextRef contextRef = [context JSGlobalContextRef];
if (!object)
return (ObjcContainerConvertor::Task){ object, JSValueMakeUndefined(contextRef), ContainerNone };
if (!class_conformsToProtocol(object_getClass(object), getJSExportProtocol())) {
if ([object isKindOfClass:[NSArray class]])
return (ObjcContainerConvertor::Task){ object, JSObjectMakeArray(contextRef, 0, NULL, 0), ContainerArray };
if ([object isKindOfClass:[NSDictionary class]])
return (ObjcContainerConvertor::Task){ object, JSObjectMake(contextRef, 0, 0), ContainerDictionary };
if ([object isKindOfClass:[NSNull class]])
return (ObjcContainerConvertor::Task){ object, JSValueMakeNull(contextRef), ContainerNone };
if ([object isKindOfClass:[JSValue class]])
return (ObjcContainerConvertor::Task){ object, ((JSValue *)object)->m_value, ContainerNone };
if ([object isKindOfClass:[NSString class]]) {
JSStringRef string = JSStringCreateWithCFString((CFStringRef)object);
JSValueRef js = JSValueMakeString(contextRef, string);
JSStringRelease(string);
return (ObjcContainerConvertor::Task){ object, js, ContainerNone };
}
if ([object isKindOfClass:[NSNumber class]]) {
if (isNSBoolean(object))
return (ObjcContainerConvertor::Task){ object, JSValueMakeBoolean(contextRef, [object boolValue]), ContainerNone };
return (ObjcContainerConvertor::Task){ object, JSValueMakeNumber(contextRef, [object doubleValue]), ContainerNone };
}
if ([object isKindOfClass:[NSDate class]]) {
JSValueRef argument = JSValueMakeNumber(contextRef, [object timeIntervalSince1970]);
JSObjectRef result = JSObjectMakeDate(contextRef, 1, &argument, 0);
return (ObjcContainerConvertor::Task){ object, result, ContainerNone };
}
if ([object isKindOfClass:[JSManagedValue class]]) {
JSValue *value = [static_cast<JSManagedValue *>(object) value];
if (!value)
return (ObjcContainerConvertor::Task) { object, JSValueMakeUndefined(contextRef), ContainerNone };
return (ObjcContainerConvertor::Task){ object, value->m_value, ContainerNone };
}
}
return (ObjcContainerConvertor::Task){ object, valueInternalValue([context wrapperForObjCObject:object]), ContainerNone };
}
JSValueRef objectToValue(JSContext *context, id object)
{
JSGlobalContextRef contextRef = [context JSGlobalContextRef];
ObjcContainerConvertor::Task task = objectToValueWithoutCopy(context, object);
if (task.type == ContainerNone)
return task.js;
ObjcContainerConvertor convertor(context);
convertor.add(task);
ASSERT(!convertor.isWorkListEmpty());
do {
ObjcContainerConvertor::Task current = convertor.take();
ASSERT(JSValueIsObject(contextRef, current.js));
JSObjectRef js = JSValueToObject(contextRef, current.js, 0);
if (current.type == ContainerArray) {
ASSERT([current.objc isKindOfClass:[NSArray class]]);
NSArray *array = (NSArray *)current.objc;
NSUInteger count = [array count];
for (NSUInteger index = 0; index < count; ++index)
JSObjectSetPropertyAtIndex(contextRef, js, index, convertor.convert([array objectAtIndex:index]), 0);
} else {
ASSERT(current.type == ContainerDictionary);
ASSERT([current.objc isKindOfClass:[NSDictionary class]]);
NSDictionary *dictionary = (NSDictionary *)current.objc;
for (id key in [dictionary keyEnumerator]) {
if ([key isKindOfClass:[NSString class]]) {
JSStringRef propertyName = JSStringCreateWithCFString((CFStringRef)key);
JSObjectSetProperty(contextRef, js, propertyName, convertor.convert([dictionary objectForKey:key]), 0, 0);
JSStringRelease(propertyName);
}
}
}
} while (!convertor.isWorkListEmpty());
return task.js;
}
JSValueRef valueInternalValue(JSValue * value)
{
return value->m_value;
}
+ (JSValue *)valueWithJSValueRef:(JSValueRef)value inContext:(JSContext *)context
{
return [context wrapperForJSObject:value];
}
- (JSValue *)init
{
return nil;
}
- (JSValue *)initWithValue:(JSValueRef)value inContext:(JSContext *)context
{
if (!value || !context)
return nil;
self = [super init];
if (!self)
return nil;
_context = [context retain];
m_value = value;
JSValueProtect([_context JSGlobalContextRef], m_value);
return self;
}
struct StructTagHandler {
SEL typeToValueSEL;
SEL valueToTypeSEL;
};
typedef HashMap<String, StructTagHandler> StructHandlers;
static StructHandlers* createStructHandlerMap()
{
StructHandlers* structHandlers = new StructHandlers();
size_t valueWithXinContextLength = strlen("valueWithX:inContext:");
size_t toXLength = strlen("toX");
// Step 1: find all valueWith<Foo>:inContext: class methods in JSValue.
forEachMethodInClass(object_getClass([JSValue class]), ^(Method method){
SEL selector = method_getName(method);
const char* name = sel_getName(selector);
size_t nameLength = strlen(name);
// Check for valueWith<Foo>:context:
if (nameLength < valueWithXinContextLength || memcmp(name, "valueWith", 9) || memcmp(name + nameLength - 11, ":inContext:", 11))
return;
// Check for [ id, SEL, <type>, <contextType> ]
if (method_getNumberOfArguments(method) != 4)
return;
char idType[3];
// Check 2nd argument type is "@"
char* secondType = method_copyArgumentType(method, 3);
if (strcmp(secondType, "@") != 0) {
free(secondType);
return;
}
free(secondType);
// Check result type is also "@"
method_getReturnType(method, idType, 3);
if (strcmp(idType, "@") != 0)
return;
char* type = method_copyArgumentType(method, 2);
structHandlers->add(StringImpl::create(type), (StructTagHandler){ selector, 0 });
free(type);
});
// Step 2: find all to<Foo> instance methods in JSValue.
forEachMethodInClass([JSValue class], ^(Method method){
SEL selector = method_getName(method);
const char* name = sel_getName(selector);
size_t nameLength = strlen(name);
// Check for to<Foo>
if (nameLength < toXLength || memcmp(name, "to", 2))
return;
// Check for [ id, SEL ]
if (method_getNumberOfArguments(method) != 2)
return;
// Try to find a matching valueWith<Foo>:context: method.
char* type = method_copyReturnType(method);
StructHandlers::iterator iter = structHandlers->find(type);
free(type);
if (iter == structHandlers->end())
return;
StructTagHandler& handler = iter->value;
// check that strlen(<foo>) == strlen(<Foo>)
const char* valueWithName = sel_getName(handler.typeToValueSEL);
size_t valueWithLength = strlen(valueWithName);
if (valueWithLength - valueWithXinContextLength != nameLength - toXLength)
return;
// Check that <Foo> == <Foo>
if (memcmp(valueWithName + 9, name + 2, nameLength - toXLength - 1))
return;
handler.valueToTypeSEL = selector;
});
// Step 3: clean up - remove entries where we found prospective valueWith<Foo>:inContext: conversions, but no matching to<Foo> methods.
typedef HashSet<String> RemoveSet;
RemoveSet removeSet;
for (StructHandlers::iterator iter = structHandlers->begin(); iter != structHandlers->end(); ++iter) {
StructTagHandler& handler = iter->value;
if (!handler.valueToTypeSEL)
removeSet.add(iter->key);
}
for (RemoveSet::iterator iter = removeSet.begin(); iter != removeSet.end(); ++iter)
structHandlers->remove(*iter);
return structHandlers;
}
static StructTagHandler* handerForStructTag(const char* encodedType)
{
static SpinLock handerForStructTagLock = SPINLOCK_INITIALIZER;
SpinLockHolder lockHolder(&handerForStructTagLock);
static StructHandlers* structHandlers = createStructHandlerMap();
StructHandlers::iterator iter = structHandlers->find(encodedType);
if (iter == structHandlers->end())
return 0;
return &iter->value;
}
+ (SEL)selectorForStructToValue:(const char *)structTag
{
StructTagHandler* handler = handerForStructTag(structTag);
return handler ? handler->typeToValueSEL : nil;
}
+ (SEL)selectorForValueToStruct:(const char *)structTag
{
StructTagHandler* handler = handerForStructTag(structTag);
return handler ? handler->valueToTypeSEL : nil;
}
- (void)dealloc
{
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];
}
NSInvocation *typeToValueInvocationFor(const char* encodedType)
{
SEL selector = [JSValue selectorForStructToValue:encodedType];
if (!selector)
return 0;
const char* methodTypes = method_getTypeEncoding(class_getClassMethod([JSValue class], selector));
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[NSMethodSignature signatureWithObjCTypes:methodTypes]];
[invocation setSelector:selector];
return invocation;
}
NSInvocation *valueToTypeInvocationFor(const char* encodedType)
{
SEL selector = [JSValue selectorForValueToStruct:encodedType];
if (!selector)
return 0;
const char* methodTypes = method_getTypeEncoding(class_getInstanceMethod([JSValue class], selector));
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[NSMethodSignature signatureWithObjCTypes:methodTypes]];
[invocation setSelector:selector];
return invocation;
}
@end
#endif
|