-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathLibrary.mm
3134 lines (2547 loc) · 110 KB
/
Library.mm
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
/* Cycript - Optimizing JavaScript Compiler/Runtime
* Copyright (C) 2009-2013 Jay Freeman (saurik)
*/
/* GNU General Public License, Version 3 {{{ */
/*
* Cycript is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* Cycript is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Cycript. If not, see <http://www.gnu.org/licenses/>.
**/
/* }}} */
#include <Foundation/Foundation.h>
#include "ObjectiveC/Internal.hpp"
#include <objc/objc-api.h>
#include "cycript.hpp"
#include "ObjectiveC/Internal.hpp"
#ifdef __APPLE__
#include <CoreFoundation/CoreFoundation.h>
#include <JavaScriptCore/JSStringRefCF.h>
#include <objc/runtime.h>
#endif
#ifdef __APPLE__
#include <malloc/malloc.h>
#include <mach/mach.h>
#endif
#include "Code.hpp"
#include "Error.hpp"
#include "JavaScript.hpp"
#include "String.hpp"
#include "Execute.hpp"
#include <cmath>
#include <map>
#include <set>
#include <dlfcn.h>
#define CYObjectiveTry_ { \
try
#define CYObjectiveTry { \
JSContextRef context(context_); \
try
#define CYObjectiveCatch \
catch (const CYException &error) { \
@throw CYCastNSObject(NULL, context, error.CastJSValue(context)); \
} \
}
#define CYPoolTry { \
id _saved(nil); \
NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
@try
#define CYPoolCatch(value) \
@catch (NSException *error) { \
_saved = [error retain]; \
throw CYJSError(context, CYCastJSValue(context, error)); \
return value; \
} @finally { \
[_pool release]; \
if (_saved != nil) \
[_saved autorelease]; \
} \
}
#define CYSadTry { \
@try
#define CYSadCatch(value) \
@catch (NSException *error ) { \
throw CYJSError(context, CYCastJSValue(context, error)); \
} return value; \
}
#define _oassert(test) \
if (!(test)) \
@throw [NSException exceptionWithName:NSInternalInconsistencyException reason:@"_assert(" #test ")" userInfo:nil];
#ifndef __APPLE__
#define class_getSuperclass GSObjCSuper
#define class_getInstanceVariable GSCGetInstanceVariableDefinition
#define class_getName GSNameFromClass
#define class_removeMethods(cls, list) GSRemoveMethodList(cls, list, YES)
#define ivar_getName(ivar) ((ivar)->ivar_name)
#define ivar_getOffset(ivar) ((ivar)->ivar_offset)
#define ivar_getTypeEncoding(ivar) ((ivar)->ivar_type)
#define method_getName(method) ((method)->method_name)
#define method_getImplementation(method) ((method)->method_imp)
#define method_getTypeEncoding(method) ((method)->method_types)
#define method_setImplementation(method, imp) ((void) ((method)->method_imp = (imp)))
#undef objc_getClass
#define objc_getClass GSClassFromName
#define objc_getProtocol GSProtocolFromName
#define object_getClass GSObjCClass
#define object_getInstanceVariable(object, name, value) ({ \
objc_ivar *ivar(class_getInstanceVariable(object_getClass(object), name)); \
_assert(value != NULL); \
if (ivar != NULL) \
GSObjCGetVariable(object, ivar_getOffset(ivar), sizeof(void *), value); \
ivar; \
})
#define object_setIvar(object, ivar, value) ({ \
void *data = (value); \
GSObjCSetVariable(object, ivar_getOffset(ivar), sizeof(void *), &data); \
})
#define protocol_getName(protocol) [(protocol) name]
#endif
static void (*$objc_setAssociatedObject)(id object, void *key, id value, objc_AssociationPolicy policy);
static id (*$objc_getAssociatedObject)(id object, void *key);
static void (*$objc_removeAssociatedObjects)(id object);
@class NSBlock;
struct BlockLiteral {
Class isa;
int flags;
int reserved;
void (*invoke)(void *, ...);
void *descriptor;
};
struct BlockDescriptor1 {
unsigned long int reserved;
unsigned long int size;
};
struct BlockDescriptor2 {
void (*copy_helper)(BlockLiteral *dst, BlockLiteral *src);
void (*dispose_helper)(BlockLiteral *src);
};
struct BlockDescriptor3 {
const char *signature;
const char *layout;
};
enum {
BLOCK_DEALLOCATING = 0x0001,
BLOCK_REFCOUNT_MASK = 0xfffe,
BLOCK_NEEDS_FREE = 1 << 24,
BLOCK_HAS_COPY_DISPOSE = 1 << 25,
BLOCK_HAS_CTOR = 1 << 26,
BLOCK_IS_GC = 1 << 27,
BLOCK_IS_GLOBAL = 1 << 28,
BLOCK_HAS_STRET = 1 << 29,
BLOCK_HAS_SIGNATURE = 1 << 30,
};
JSValueRef CYSendMessage(CYPool &pool, JSContextRef context, id self, Class super, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize);
/* Objective-C Pool Release {{{ */
void CYPoolRelease_(void *data) {
id object(reinterpret_cast<id>(data));
[object release];
}
id CYPoolRelease_(CYPool *pool, id object) {
if (object == nil)
return nil;
else if (pool == NULL)
return [object autorelease];
else {
pool->atexit(CYPoolRelease_);
return object;
}
}
template <typename Type_>
Type_ CYPoolRelease(CYPool *pool, Type_ object) {
return (Type_) CYPoolRelease_(pool, (id) object);
}
/* }}} */
/* Objective-C Strings {{{ */
const char *CYPoolCString(CYPool &pool, JSContextRef context, NSString *value) {
size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
char *string(new(pool) char[size]);
if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
throw CYJSError(context, "[NSString getCString:maxLength:encoding:] == NO");
return string;
}
JSStringRef CYCopyJSString(JSContextRef context, NSString *value) {
#ifdef __APPLE__
return JSStringCreateWithCFString(reinterpret_cast<CFStringRef>(value));
#else
CYPool pool;
return CYCopyJSString(CYPoolCString(pool, context, value));
#endif
}
JSStringRef CYCopyJSString(JSContextRef context, NSObject *value) {
if (value == nil)
return NULL;
// XXX: this definition scares me; is anyone using this?!
NSString *string([value description]);
return CYCopyJSString(context, string);
}
NSString *CYCopyNSString(const CYUTF8String &value) {
#ifdef __APPLE__
return (NSString *) CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const UInt8 *>(value.data), value.size, kCFStringEncodingUTF8, true);
#else
return [[NSString alloc] initWithBytes:value.data length:value.size encoding:NSUTF8StringEncoding];
#endif
}
NSString *CYCopyNSString(JSContextRef context, JSStringRef value) {
#ifdef __APPLE__
return (NSString *) JSStringCopyCFString(kCFAllocatorDefault, value);
#else
CYPool pool;
return CYCopyNSString(CYPoolUTF8String(pool, context, value));
#endif
}
NSString *CYCopyNSString(JSContextRef context, JSValueRef value) {
return CYCopyNSString(context, CYJSString(context, value));
}
NSString *CYCastNSString(CYPool *pool, const CYUTF8String &value) {
return CYPoolRelease(pool, CYCopyNSString(value));
}
NSString *CYCastNSString(CYPool *pool, SEL sel) {
const char *name(sel_getName(sel));
return CYPoolRelease(pool, CYCopyNSString(CYUTF8String(name, strlen(name))));
}
NSString *CYCastNSString(CYPool *pool, JSContextRef context, JSStringRef value) {
return CYPoolRelease(pool, CYCopyNSString(context, value));
}
CYUTF8String CYCastUTF8String(NSString *value) {
NSData *data([value dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO]);
return CYUTF8String(reinterpret_cast<const char *>([data bytes]), [data length]);
}
/* }}} */
JSValueRef CYCastJSValue(JSContextRef context, NSObject *value);
void CYThrow(JSContextRef context, NSException *error, JSValueRef *exception) {
if (exception == NULL)
throw error;
*exception = CYCastJSValue(context, error);
}
size_t CYGetIndex(NSString *value) {
return CYGetIndex(CYCastUTF8String(value));
}
bool CYGetOffset(CYPool &pool, JSContextRef context, NSString *value, ssize_t &index) {
return CYGetOffset(CYPoolCString(pool, context, value), index);
}
static JSClassRef Instance_;
static JSClassRef ArrayInstance_;
static JSClassRef BooleanInstance_;
static JSClassRef FunctionInstance_;
static JSClassRef NumberInstance_;
static JSClassRef ObjectInstance_;
static JSClassRef StringInstance_;
static JSClassRef Class_;
static JSClassRef Internal_;
static JSClassRef Message_;
static JSClassRef Messages_;
static JSClassRef Selector_;
static JSClassRef Super_;
static JSClassRef ObjectiveC_Classes_;
static JSClassRef ObjectiveC_Constants_;
static JSClassRef ObjectiveC_Protocols_;
#ifdef __APPLE__
static JSClassRef ObjectiveC_Image_Classes_;
static JSClassRef ObjectiveC_Images_;
#endif
#ifdef __APPLE__
static Class __NSMallocBlock__;
static Class NSCFBoolean_;
static Class NSCFType_;
static Class NSGenericDeallocHandler_;
static Class NSZombie_;
#else
static Class NSBoolNumber_;
#endif
static Class NSArray_;
static Class NSBlock_;
static Class NSDictionary_;
static Class NSNumber_;
static Class NSString_;
static Class Object_;
static Type_privateData *Object_type;
static Type_privateData *Selector_type;
Type_privateData *Instance::GetType() const {
return Object_type;
}
Type_privateData *Selector_privateData::GetType() const {
return Selector_type;
}
static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception);
JSValueRef CYGetClassPrototype(JSContextRef context, Class self, bool meta) {
if (self == nil)
return CYGetCachedObject(context, CYJSString("Instance_prototype"));
else if (meta && !class_isMetaClass(self))
return CYGetCachedObject(context, CYJSString("Class_prototype"));
JSObjectRef global(CYGetGlobalObject(context));
JSObjectRef cy(CYCastJSObject(context, CYGetProperty(context, global, cy_s)));
char label[32];
sprintf(label, "i%p", self);
CYJSString name(label);
JSValueRef value(CYGetProperty(context, cy, name));
if (!JSValueIsUndefined(context, value))
return value;
JSClassRef _class(NULL);
JSValueRef prototype;
#ifdef __APPLE__
if (self == NSCFBoolean_)
#else
if (self == NSBoolNumber_)
#endif
prototype = CYGetCachedObject(context, CYJSString("BooleanInstance_prototype"));
else if (self == NSArray_)
prototype = CYGetCachedObject(context, CYJSString("ArrayInstance_prototype"));
else if (self == NSBlock_)
prototype = CYGetCachedObject(context, CYJSString("FunctionInstance_prototype"));
else if (self == NSNumber_)
prototype = CYGetCachedObject(context, CYJSString("NumberInstance_prototype"));
else if (self == NSDictionary_)
prototype = CYGetCachedObject(context, CYJSString("ObjectInstance_prototype"));
else if (self == NSString_)
prototype = CYGetCachedObject(context, CYJSString("StringInstance_prototype"));
else
prototype = CYGetClassPrototype(context, class_getSuperclass(self), meta);
JSObjectRef object(JSObjectMake(context, _class, NULL));
CYSetPrototype(context, object, prototype);
CYSetProperty(context, cy, name, object);
return object;
}
_finline JSValueRef CYGetClassPrototype(JSContextRef context, Class self) {
return CYGetClassPrototype(context, self, class_isMetaClass(self));
}
JSObjectRef Messages::Make(JSContextRef context, Class _class) {
JSObjectRef value(JSObjectMake(context, Messages_, new Messages(_class)));
if (Class super = class_getSuperclass(_class))
CYSetPrototype(context, value, Messages::Make(context, super));
return value;
}
JSObjectRef Internal::Make(JSContextRef context, id object, JSObjectRef owner) {
return JSObjectMake(context, Internal_, new Internal(object, context, owner));
}
namespace cy {
JSObjectRef Super::Make(JSContextRef context, id object, Class _class) {
JSObjectRef value(JSObjectMake(context, Super_, new Super(object, _class)));
return value;
} }
bool CYIsKindOfClass(id object, Class _class) {
for (Class isa(object_getClass(object)); isa != NULL; isa = class_getSuperclass(isa))
if (isa == _class)
return true;
return false;
}
JSObjectRef Instance::Make(JSContextRef context, id object, Flags flags) {
JSObjectRef value(JSObjectMake(context, CYIsKindOfClass(object, NSBlock_) ? FunctionInstance_ : Instance_, new Instance(object, flags)));
CYSetPrototype(context, value, CYGetClassPrototype(context, object_getClass(object)));
return value;
}
Instance::~Instance() {
if ((flags_ & Transient) == 0)
[GetValue() release];
}
struct Message_privateData :
cy::Functor
{
SEL sel_;
Message_privateData(SEL sel, const char *type, IMP value = NULL) :
cy::Functor(type, reinterpret_cast<void (*)()>(value)),
sel_(sel)
{
}
};
JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
Instance::Flags flags;
if (transient)
flags = Instance::Transient;
else {
flags = Instance::None;
object = [object retain];
}
return Instance::Make(context, object, flags);
}
@interface NSMethodSignature (Cycript)
- (NSString *) _typeString;
@end
@interface NSObject (Cycript)
- (JSValueRef) cy$valueOfInContext:(JSContextRef)context;
- (JSType) cy$JSType;
- (JSValueRef) cy$toJSON:(NSString *)key inContext:(JSContextRef)context;
- (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects;
- (bool) cy$hasProperty:(NSString *)name;
- (NSObject *) cy$getProperty:(NSString *)name;
- (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context;
- (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
- (bool) cy$deleteProperty:(NSString *)name;
- (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context;
+ (bool) cy$hasImplicitProperties;
@end
@protocol Cycript
- (id) cy$box;
- (JSValueRef) cy$valueOfInContext:(JSContextRef)context;
@end
NSString *CYCastNSCYON(id value, bool objective, std::set<void *> &objects) {
NSString *string;
if (value == nil)
string = @"nil";
else {
Class _class(object_getClass(value));
SEL sel(@selector(cy$toCYON:inSet:));
if (class_isMetaClass(_class)) {
const char *name(class_getName(value));
if (class_isMetaClass(value))
string = [NSString stringWithFormat:@"object_getClass(%s)", name];
else
string = [NSString stringWithUTF8String:name];
} else if (objc_method *toCYON = class_getInstanceMethod(_class, sel))
string = reinterpret_cast<NSString *(*)(id, SEL, bool, std::set<void *> &)>(method_getImplementation(toCYON))(value, sel, objective, objects);
else if (objc_method *methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:))) {
if (reinterpret_cast<NSMethodSignature *(*)(id, SEL, SEL)>(method_getImplementation(methodSignatureForSelector))(value, @selector(methodSignatureForSelector:), sel) != nil)
string = [value cy$toCYON:objective inSet:objects];
else goto fail;
} else fail: {
if (false);
#ifdef __APPLE__
else if (_class == NSZombie_)
string = [NSString stringWithFormat:@"<_NSZombie_: %p>", value];
#endif
else
string = [NSString stringWithFormat:@"%@", value];
}
// XXX: frowny pants
if (string == nil)
string = @"undefined";
}
return string;
}
NSString *CYCastNSCYON(id value, bool objective, std::set<void *> *objects) {
if (objects != NULL)
return CYCastNSCYON(value, objective, *objects);
else {
std::set<void *> objects;
return CYCastNSCYON(value, objective, objects);
}
}
#ifdef __APPLE__
struct PropertyAttributes {
CYPool pool_;
const char *name;
const char *variable;
const char *getter_;
const char *setter_;
bool readonly;
bool copy;
bool retain;
bool nonatomic;
bool dynamic;
bool weak;
bool garbage;
PropertyAttributes(objc_property_t property) :
variable(NULL),
getter_(NULL),
setter_(NULL),
readonly(false),
copy(false),
retain(false),
nonatomic(false),
dynamic(false),
weak(false),
garbage(false)
{
name = property_getName(property);
const char *attributes(property_getAttributes(property));
for (char *token(pool_.strdup(attributes)), *next; token != NULL; token = next) {
if ((next = strchr(token, ',')) != NULL)
*next++ = '\0';
switch (*token) {
case 'R': readonly = true; break;
case 'C': copy = true; break;
case '&': retain = true; break;
case 'N': nonatomic = true; break;
case 'G': getter_ = token + 1; break;
case 'S': setter_ = token + 1; break;
case 'V': variable = token + 1; break;
}
}
/*if (variable == NULL) {
variable = property_getName(property);
size_t size(strlen(variable));
char *name(new(pool_) char[size + 2]);
name[0] = '_';
memcpy(name + 1, variable, size);
name[size + 1] = '\0';
variable = name;
}*/
}
const char *Getter() {
if (getter_ == NULL)
getter_ = pool_.strdup(name);
return getter_;
}
const char *Setter() {
if (setter_ == NULL && !readonly) {
size_t length(strlen(name));
char *temp(new(pool_) char[length + 5]);
temp[0] = 's';
temp[1] = 'e';
temp[2] = 't';
if (length != 0) {
temp[3] = toupper(name[0]);
memcpy(temp + 4, name + 1, length - 1);
}
temp[length + 3] = ':';
temp[length + 4] = '\0';
setter_ = temp;
}
return setter_;
}
};
#endif
@interface CYWebUndefined : NSObject {
}
+ (CYWebUndefined *) undefined;
@end
@implementation CYWebUndefined
+ (CYWebUndefined *) undefined {
static CYWebUndefined *instance_([[CYWebUndefined alloc] init]);
return instance_;
}
@end
#define WebUndefined CYWebUndefined
/* Bridge: CYJSObject {{{ */
@interface CYJSObject : NSMutableDictionary {
JSObjectRef object_;
JSGlobalContextRef context_;
}
- (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
- (NSUInteger) count;
- (id) objectForKey:(id)key;
- (NSEnumerator *) keyEnumerator;
- (void) setObject:(id)object forKey:(id)key;
- (void) removeObjectForKey:(id)key;
@end
/* }}} */
/* Bridge: CYJSArray {{{ */
@interface CYJSArray : NSMutableArray {
JSObjectRef object_;
JSGlobalContextRef context_;
}
- (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
- (NSUInteger) count;
- (id) objectAtIndex:(NSUInteger)index;
- (void) addObject:(id)anObject;
- (void) insertObject:(id)anObject atIndex:(NSUInteger)index;
- (void) removeLastObject;
- (void) removeObjectAtIndex:(NSUInteger)index;
- (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;
@end
/* }}} */
_finline bool CYJSValueIsNSObject(JSContextRef context, JSValueRef value) {
return JSValueIsObjectOfClass(context, value, Instance_) || JSValueIsObjectOfClass(context, value, FunctionInstance_);
}
_finline bool CYJSValueIsInstanceOfCachedConstructor(JSContextRef context, JSValueRef value, JSStringRef cache) {
return _jsccall(JSValueIsInstanceOfConstructor, context, value, CYGetCachedObject(context, cache));
}
struct CYBlockDescriptor {
struct {
BlockDescriptor1 one_;
BlockDescriptor2 two_;
BlockDescriptor3 three_;
} d_;
Closure_privateData *internal_;
};
void CYDisposeBlock(BlockLiteral *literal) {
delete reinterpret_cast<CYBlockDescriptor *>(literal->descriptor)->internal_;
}
static JSValueRef BlockAdapter_(JSContextRef context, size_t count, JSValueRef values[], JSObjectRef function) {
JSObjectRef _this(CYCastJSObject(context, values[0]));
return CYCallAsFunction(context, function, _this, count - 1, values + 1);
}
static void BlockClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
CYExecuteClosure(cif, result, arguments, arg, &BlockAdapter_);
}
NSBlock *CYMakeBlock(JSContextRef context, JSObjectRef function, sig::Signature &signature) {
_assert(__NSMallocBlock__ != Nil);
BlockLiteral *literal(reinterpret_cast<BlockLiteral *>(malloc(sizeof(BlockLiteral))));
CYBlockDescriptor *descriptor(new CYBlockDescriptor);
memset(&descriptor->d_, 0, sizeof(descriptor->d_));
descriptor->internal_ = CYMakeFunctor_(context, function, signature, &BlockClosure_);
literal->invoke = reinterpret_cast<void (*)(void *, ...)>(descriptor->internal_->GetValue());
literal->isa = __NSMallocBlock__;
literal->flags = BLOCK_HAS_SIGNATURE | BLOCK_HAS_COPY_DISPOSE | BLOCK_IS_GLOBAL;
literal->reserved = 0;
literal->descriptor = descriptor;
descriptor->d_.one_.size = sizeof(descriptor->d_);
descriptor->d_.two_.dispose_helper = &CYDisposeBlock;
descriptor->d_.three_.signature = sig::Unparse(*descriptor->internal_->pool_, &signature);
return reinterpret_cast<NSBlock *>(literal);
}
NSObject *CYCastNSObject(CYPool *pool, JSContextRef context, JSObjectRef object) {
if (CYJSValueIsNSObject(context, object)) {
Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
return internal->GetValue();
}
bool array(CYJSValueIsInstanceOfCachedConstructor(context, object, Array_s));
id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
}
NSNumber *CYCopyNSNumber(JSContextRef context, JSValueRef value) {
return [[NSNumber alloc] initWithDouble:CYCastDouble(context, value)];
}
#ifndef __APPLE__
@interface NSBoolNumber : NSNumber {
}
@end
#endif
id CYNSObject(CYPool *pool, JSContextRef context, JSValueRef value, bool cast) {
id object;
bool copy;
switch (JSType type = JSValueGetType(context, value)) {
case kJSTypeUndefined:
object = [WebUndefined undefined];
copy = false;
break;
case kJSTypeNull:
return NULL;
break;
case kJSTypeBoolean:
#ifdef __APPLE__
object = (id) (CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse);
copy = false;
#else
object = [[NSBoolNumber alloc] initWithBool:CYCastBool(context, value)];
copy = true;
#endif
break;
case kJSTypeNumber:
object = CYCopyNSNumber(context, value);
copy = true;
break;
case kJSTypeString:
object = CYCopyNSString(context, value);
copy = true;
break;
case kJSTypeObject:
// XXX: this might could be more efficient
object = CYCastNSObject(pool, context, (JSObjectRef) value);
copy = false;
break;
default:
throw CYJSError(context, "JSValueGetType() == 0x%x", type);
break;
}
if (cast != copy)
return object;
else if (copy)
return CYPoolRelease(pool, object);
else
return [object retain];
}
NSObject *CYCastNSObject(CYPool *pool, JSContextRef context, JSValueRef value) {
return CYNSObject(pool, context, value, true);
}
NSObject *CYCopyNSObject(CYPool &pool, JSContextRef context, JSValueRef value) {
return CYNSObject(&pool, context, value, false);
}
/* Bridge: NSArray {{{ */
@implementation NSArray (Cycript)
- (id) cy$box {
return [[self mutableCopy] autorelease];
}
- (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
_oassert(objects.insert(self).second);
NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
[json appendString:@"@["];
bool comma(false);
#ifdef __APPLE__
for (id object in self) {
#else
for (size_t index(0), count([self count]); index != count; ++index) {
id object([self objectAtIndex:index]);
#endif
if (comma)
[json appendString:@","];
else
comma = true;
if (object == nil || [object cy$JSType] != kJSTypeUndefined)
[json appendString:CYCastNSCYON(object, true, objects)];
else {
[json appendString:@","];
comma = false;
}
}
[json appendString:@"]"];
return json;
}
- (bool) cy$hasProperty:(NSString *)name {
if ([name isEqualToString:@"length"])
return true;
size_t index(CYGetIndex(name));
if (index == _not(size_t) || index >= [self count])
return [super cy$hasProperty:name];
else
return true;
}
- (NSObject *) cy$getProperty:(NSString *)name {
size_t index(CYGetIndex(name));
if (index == _not(size_t) || index >= [self count])
return [super cy$getProperty:name];
else
return [self objectAtIndex:index];
}
- (JSValueRef) cy$getProperty:(NSString *)name inContext:(JSContextRef)context {
CYObjectiveTry_ {
if ([name isEqualToString:@"length"])
return CYCastJSValue(context, [self count]);
} CYObjectiveCatch
return [super cy$getProperty:name inContext:context];
}
- (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
[super cy$getPropertyNames:names inContext:context];
for (size_t index(0), count([self count]); index != count; ++index) {
id object([self objectAtIndex:index]);
if (object == nil || [object cy$JSType] != kJSTypeUndefined) {
char name[32];
sprintf(name, "%zu", index);
JSPropertyNameAccumulatorAddName(names, CYJSString(name));
}
}
}
+ (bool) cy$hasImplicitProperties {
return false;
}
@end
/* }}} */
/* Bridge: NSBlock {{{ */
#ifdef __APPLE__
@interface NSBlock
- (void) invoke;
@end
#endif
/* }}} */
/* Bridge: NSBoolNumber {{{ */
#ifndef __APPLE__
@implementation NSBoolNumber (Cycript)
- (JSType) cy$JSType {
return kJSTypeBoolean;
}
- (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
NSString *value([self boolValue] ? @"true" : @"false");
return objective ? value : [NSString stringWithFormat:@"@%@", value];
}
- (JSValueRef) cy$valueOfInContext:(JSContextRef)context { CYObjectiveTry_ {
return CYCastJSValue(context, (bool) [self boolValue]);
} CYObjectiveCatch }
@end
#endif
/* }}} */
/* Bridge: NSDictionary {{{ */
@implementation NSDictionary (Cycript)
- (id) cy$box {
return [[self mutableCopy] autorelease];
}
- (NSString *) cy$toCYON:(bool)objective inSet:(std::set<void *> &)objects {
_oassert(objects.insert(self).second);
NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
[json appendString:@"@{"];
bool comma(false);
#ifdef __APPLE__
for (NSObject *key in self) {
#else
NSEnumerator *keys([self keyEnumerator]);
while (NSObject *key = [keys nextObject]) {
#endif
if (comma)
[json appendString:@","];
else
comma = true;
[json appendString:CYCastNSCYON(key, true, objects)];
[json appendString:@":"];
NSObject *object([self objectForKey:key]);
[json appendString:CYCastNSCYON(object, true, objects)];
}
[json appendString:@"}"];
return json;
}
- (bool) cy$hasProperty:(NSString *)name {
return [self objectForKey:name] != nil;
}
- (NSObject *) cy$getProperty:(NSString *)name {
return [self objectForKey:name];
}
- (void) cy$getPropertyNames:(JSPropertyNameAccumulatorRef)names inContext:(JSContextRef)context {
[super cy$getPropertyNames:names inContext:context];
#ifdef __APPLE__
for (NSObject *key in self) {
#else
NSEnumerator *keys([self keyEnumerator]);
while (NSObject *key = [keys nextObject]) {
#endif
JSPropertyNameAccumulatorAddName(names, CYJSString(context, key));
}
}
+ (bool) cy$hasImplicitProperties {
return false;
}
@end
/* }}} */
/* Bridge: NSMutableArray {{{ */
@implementation NSMutableArray (Cycript)
- (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
if ([name isEqualToString:@"length"]) {
// XXX: is this not intelligent?
NSNumber *number(reinterpret_cast<NSNumber *>(value));
#ifdef __APPLE__
NSUInteger size([number unsignedIntegerValue]);
#else
NSUInteger size([number unsignedIntValue]);
#endif
NSUInteger count([self count]);
if (size < count)
[self removeObjectsInRange:NSMakeRange(size, count - size)];
else if (size != count) {
WebUndefined *undefined([WebUndefined undefined]);
for (size_t i(count); i != size; ++i)
[self addObject:undefined];
}
return true;
}
size_t index(CYGetIndex(name));
if (index == _not(size_t))
return [super cy$setProperty:name to:value];
id object(value ?: [NSNull null]);
size_t count([self count]);