]> git.saurik.com Git - cycript.git/blob - Library.mm
Made Selector derive from Function, fixed numerability of Instance.{constructor,proto...
[cycript.git] / Library.mm
1 /* Cycript - Remove Execution Server and Disassembler
2 * Copyright (C) 2009 Jay Freeman (saurik)
3 */
4
5 /* Modified BSD License {{{ */
6 /*
7 * Redistribution and use in source and binary
8 * forms, with or without modification, are permitted
9 * provided that the following conditions are met:
10 *
11 * 1. Redistributions of source code must retain the
12 * above copyright notice, this list of conditions
13 * and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the
15 * above copyright notice, this list of conditions
16 * and the following disclaimer in the documentation
17 * and/or other materials provided with the
18 * distribution.
19 * 3. The name of the author may not be used to endorse
20 * or promote products derived from this software
21 * without specific prior written permission.
22 *
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS''
24 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
25 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
26 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
28 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
31 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
34 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
35 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
36 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
37 */
38 /* }}} */
39
40 #define _GNU_SOURCE
41
42 #include <substrate.h>
43 #include "cycript.hpp"
44
45 #include "sig/parse.hpp"
46 #include "sig/ffi_type.hpp"
47
48 #include "Pooling.hpp"
49 #include "Struct.hpp"
50
51 #include <CoreFoundation/CoreFoundation.h>
52 #include <CoreFoundation/CFLogUtilities.h>
53
54 #include <WebKit/WebScriptObject.h>
55
56 #include <sys/mman.h>
57
58 #include <iostream>
59 #include <ext/stdio_filebuf.h>
60 #include <set>
61 #include <map>
62
63 #include <sstream>
64 #include <cmath>
65
66 #include "Parser.hpp"
67 #include "Cycript.tab.hh"
68
69 #include <apr-1/apr_thread_proc.h>
70
71 #undef _assert
72 #undef _trace
73
74 #define _assert(test) do { \
75 if (!(test)) \
76 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"_assert(%s):%s(%u):%s", #test, __FILE__, __LINE__, __FUNCTION__] userInfo:nil]; \
77 } while (false)
78
79 #define _trace() do { \
80 CFLog(kCFLogLevelNotice, CFSTR("_trace():%u"), __LINE__); \
81 } while (false)
82
83 #define CYPoolTry { \
84 id _saved(nil); \
85 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
86 @try
87 #define CYPoolCatch(value) \
88 @catch (NSException *error) { \
89 _saved = [error retain]; \
90 @throw; \
91 return value; \
92 } @finally { \
93 [_pool release]; \
94 if (_saved != nil) \
95 [_saved autorelease]; \
96 } \
97 }
98
99 static JSGlobalContextRef Context_;
100 static JSObjectRef System_;
101 static JSObjectRef ObjectiveC_;
102
103 static JSClassRef Functor_;
104 static JSClassRef Instance_;
105 static JSClassRef Internal_;
106 static JSClassRef Message_;
107 static JSClassRef Pointer_;
108 static JSClassRef Prototype_;
109 static JSClassRef Runtime_;
110 static JSClassRef Selector_;
111 static JSClassRef Struct_;
112 static JSClassRef Type_;
113
114 static JSClassRef ObjectiveC_Classes_;
115 static JSClassRef ObjectiveC_Image_Classes_;
116 static JSClassRef ObjectiveC_Images_;
117 static JSClassRef ObjectiveC_Protocols_;
118
119 static JSObjectRef Array_;
120 static JSObjectRef Function_;
121
122 static JSStringRef Result_;
123
124 static JSStringRef length_;
125 static JSStringRef message_;
126 static JSStringRef name_;
127 static JSStringRef prototype_;
128 static JSStringRef toCYON_;
129 static JSStringRef toJSON_;
130
131 static Class NSCFBoolean_;
132 static Class NSCFType_;
133 static Class NSMessageBuilder_;
134 static Class NSZombie_;
135 static Class Object_;
136
137 static NSArray *Bridge_;
138
139 static void Finalize(JSObjectRef object) {
140 delete reinterpret_cast<CYData *>(JSObjectGetPrivate(object));
141 }
142
143 class Type_privateData;
144
145 struct CYValue :
146 CYData
147 {
148 void *value_;
149
150 CYValue() {
151 }
152
153 CYValue(void *value) :
154 value_(value)
155 {
156 }
157
158 CYValue(const CYValue &rhs) :
159 value_(rhs.value_)
160 {
161 }
162
163 virtual Type_privateData *GetType() const {
164 return NULL;
165 }
166 };
167
168 struct Selector_privateData :
169 CYValue
170 {
171 Selector_privateData(SEL value) :
172 CYValue(value)
173 {
174 }
175
176 SEL GetValue() const {
177 return reinterpret_cast<SEL>(value_);
178 }
179
180 virtual Type_privateData *GetType() const;
181 };
182
183 struct Instance :
184 CYValue
185 {
186 enum Flags {
187 None = 0,
188 Transient = (1 << 0),
189 Uninitialized = (1 << 1),
190 };
191
192 Flags flags_;
193
194 Instance(id value, Flags flags) :
195 CYValue(value),
196 flags_(flags)
197 {
198 }
199
200 virtual ~Instance() {
201 if ((flags_ & Transient) == 0)
202 // XXX: does this handle background threads correctly?
203 [GetValue() performSelector:@selector(release) withObject:nil afterDelay:0];
204 }
205
206 static JSObjectRef Make(JSContextRef context, id object, Flags flags = None) {
207 return JSObjectMake(context, Instance_, new Instance(object, flags));
208 }
209
210 id GetValue() const {
211 return reinterpret_cast<id>(value_);
212 }
213
214 bool IsUninitialized() const {
215 return (flags_ & Uninitialized) != 0;
216 }
217
218 virtual Type_privateData *GetType() const;
219 };
220
221 struct Prototype :
222 CYValue
223 {
224 Prototype(Class value) :
225 CYValue(value)
226 {
227 }
228
229 static JSObjectRef Make(JSContextRef context, Class _class) {
230 JSObjectRef value(JSObjectMake(context, Prototype_, new Prototype(_class)));
231 if (Class super = class_getSuperclass(_class))
232 JSObjectSetPrototype(context, value, Prototype::Make(context, super));
233 return value;
234 }
235
236 Class GetValue() const {
237 return reinterpret_cast<Class>(value_);
238 }
239 };
240
241 struct Internal :
242 CYValue
243 {
244 JSObjectRef owner_;
245
246 Internal(id value, JSObjectRef owner) :
247 CYValue(value),
248 owner_(owner)
249 {
250 }
251
252 static JSObjectRef Make(JSContextRef context, id object, JSObjectRef owner) {
253 return JSObjectMake(context, Internal_, new Internal(object, owner));
254 }
255
256 id GetValue() const {
257 return reinterpret_cast<id>(value_);
258 }
259 };
260
261 namespace sig {
262
263 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs);
264
265 void Copy(apr_pool_t *pool, Element &lhs, Element &rhs) {
266 lhs.name = apr_pstrdup(pool, rhs.name);
267 if (rhs.type == NULL)
268 lhs.type = NULL;
269 else {
270 lhs.type = new(pool) Type;
271 Copy(pool, *lhs.type, *rhs.type);
272 }
273 lhs.offset = rhs.offset;
274 }
275
276 void Copy(apr_pool_t *pool, Signature &lhs, Signature &rhs) {
277 size_t count(rhs.count);
278 lhs.count = count;
279 lhs.elements = new(pool) Element[count];
280 for (size_t index(0); index != count; ++index)
281 Copy(pool, lhs.elements[index], rhs.elements[index]);
282 }
283
284 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs) {
285 lhs.primitive = rhs.primitive;
286 lhs.name = apr_pstrdup(pool, rhs.name);
287 lhs.flags = rhs.flags;
288
289 if (sig::IsAggregate(rhs.primitive))
290 Copy(pool, lhs.data.signature, rhs.data.signature);
291 else {
292 if (rhs.data.data.type != NULL) {
293 lhs.data.data.type = new(pool) Type;
294 Copy(pool, *lhs.data.data.type, *rhs.data.data.type);
295 }
296
297 lhs.data.data.size = rhs.data.data.size;
298 }
299 }
300
301 void Copy(apr_pool_t *pool, ffi_type &lhs, ffi_type &rhs) {
302 lhs.size = rhs.size;
303 lhs.alignment = rhs.alignment;
304 lhs.type = rhs.type;
305 if (rhs.elements == NULL)
306 lhs.elements = NULL;
307 else {
308 size_t count(0);
309 while (rhs.elements[count] != NULL)
310 ++count;
311
312 lhs.elements = new(pool) ffi_type *[count + 1];
313 lhs.elements[count] = NULL;
314
315 for (size_t index(0); index != count; ++index) {
316 // XXX: if these are libffi native then you can just take them
317 ffi_type *ffi(new(pool) ffi_type);
318 lhs.elements[index] = ffi;
319 sig::Copy(pool, *ffi, *rhs.elements[index]);
320 }
321 }
322 }
323
324 }
325
326 struct CStringMapLess :
327 std::binary_function<const char *, const char *, bool>
328 {
329 _finline bool operator ()(const char *lhs, const char *rhs) const {
330 return strcmp(lhs, rhs) < 0;
331 }
332 };
333
334 void Structor_(apr_pool_t *pool, const char *name, const char *types, sig::Type *&type) {
335 if (name == NULL)
336 return;
337
338 CYPoolTry {
339 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:2] objectForKey:[NSString stringWithUTF8String:name]])
340 switch ([[entry objectAtIndex:0] intValue]) {
341 case 0: {
342 sig::Parse(pool, &type->data.signature, [[entry objectAtIndex:1] UTF8String], &Structor_);
343 } break;
344
345 case 1: {
346 sig::Signature signature;
347 sig::Parse(pool, &signature, [[entry objectAtIndex:1] UTF8String], &Structor_);
348 type = signature.elements[0].type;
349 } break;
350 }
351 } CYPoolCatch()
352 }
353
354 struct Type_privateData :
355 CYData
356 {
357 static Type_privateData *Object;
358 static Type_privateData *Selector;
359
360 ffi_type *ffi_;
361 sig::Type *type_;
362
363 void Set(sig::Type *type) {
364 type_ = new(pool_) sig::Type;
365 sig::Copy(pool_, *type_, *type);
366 }
367
368 Type_privateData(apr_pool_t *pool, const char *type) :
369 ffi_(NULL)
370 {
371 if (pool != NULL)
372 pool_ = pool;
373
374 sig::Signature signature;
375 sig::Parse(pool_, &signature, type, &Structor_);
376 type_ = signature.elements[0].type;
377 }
378
379 Type_privateData(sig::Type *type) :
380 ffi_(NULL)
381 {
382 if (type != NULL)
383 Set(type);
384 }
385
386 Type_privateData(sig::Type *type, ffi_type *ffi) {
387 ffi_ = new(pool_) ffi_type;
388 sig::Copy(pool_, *ffi_, *ffi);
389 Set(type);
390 }
391
392 ffi_type *GetFFI() {
393 if (ffi_ == NULL) {
394 ffi_ = new(pool_) ffi_type;
395
396 sig::Element element;
397 element.name = NULL;
398 element.type = type_;
399 element.offset = 0;
400
401 sig::Signature signature;
402 signature.elements = &element;
403 signature.count = 1;
404
405 ffi_cif cif;
406 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature, &cif);
407 *ffi_ = *cif.rtype;
408 }
409
410 return ffi_;
411 }
412 };
413
414 Type_privateData *Type_privateData::Object;
415 Type_privateData *Type_privateData::Selector;
416
417 Type_privateData *Instance::GetType() const {
418 return Type_privateData::Object;
419 }
420
421 Type_privateData *Selector_privateData::GetType() const {
422 return Type_privateData::Selector;
423 }
424
425 struct Pointer :
426 CYValue
427 {
428 JSObjectRef owner_;
429 Type_privateData *type_;
430
431 Pointer(void *value, sig::Type *type, JSObjectRef owner) :
432 CYValue(value),
433 owner_(owner),
434 type_(new(pool_) Type_privateData(type))
435 {
436 }
437 };
438
439 struct Struct_privateData :
440 CYValue
441 {
442 JSObjectRef owner_;
443 Type_privateData *type_;
444
445 Struct_privateData(JSObjectRef owner) :
446 owner_(owner)
447 {
448 }
449 };
450
451 typedef std::map<const char *, Type_privateData *, CStringMapLess> TypeMap;
452 static TypeMap Types_;
453
454 JSObjectRef CYMakeStruct(JSContextRef context, void *data, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
455 Struct_privateData *internal(new Struct_privateData(owner));
456 apr_pool_t *pool(internal->pool_);
457 Type_privateData *typical(new(pool) Type_privateData(type, ffi));
458 internal->type_ = typical;
459
460 if (owner != NULL)
461 internal->value_ = data;
462 else {
463 size_t size(typical->GetFFI()->size);
464 void *copy(apr_palloc(internal->pool_, size));
465 memcpy(copy, data, size);
466 internal->value_ = copy;
467 }
468
469 return JSObjectMake(context, Struct_, internal);
470 }
471
472 struct Functor_privateData :
473 CYValue
474 {
475 sig::Signature signature_;
476 ffi_cif cif_;
477
478
479 Functor_privateData(const char *type, void (*value)()) :
480 CYValue(reinterpret_cast<void *>(value))
481 {
482 sig::Parse(pool_, &signature_, type, &Structor_);
483 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature_, &cif_);
484 }
485
486 void (*GetValue())() const {
487 return reinterpret_cast<void (*)()>(value_);
488 }
489 };
490
491 struct Closure_privateData :
492 Functor_privateData
493 {
494 JSContextRef context_;
495 JSObjectRef function_;
496
497 Closure_privateData(const char *type) :
498 Functor_privateData(type, NULL)
499 {
500 }
501 };
502
503 struct Message_privateData :
504 Functor_privateData
505 {
506 SEL sel_;
507
508 Message_privateData(SEL sel, const char *type, IMP value = NULL) :
509 Functor_privateData(type, reinterpret_cast<void (*)()>(value)),
510 sel_(sel)
511 {
512 }
513 };
514
515 JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
516 Instance::Flags flags;
517
518 if (transient)
519 flags = Instance::Transient;
520 else {
521 flags = Instance::None;
522 object = [object retain];
523 }
524
525 return Instance::Make(context, object, flags);
526 }
527
528 const char *CYPoolCString(apr_pool_t *pool, NSString *value) {
529 if (pool == NULL)
530 return [value UTF8String];
531 else {
532 size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
533 char *string(new(pool) char[size]);
534 if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
535 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:@"[NSString getCString:maxLength:encoding:] == NO" userInfo:nil];
536 return string;
537 }
538 }
539
540 JSValueRef CYCastJSValue(JSContextRef context, bool value) {
541 return JSValueMakeBoolean(context, value);
542 }
543
544 JSValueRef CYCastJSValue(JSContextRef context, double value) {
545 return JSValueMakeNumber(context, value);
546 }
547
548 #define CYCastJSValue_(Type_) \
549 JSValueRef CYCastJSValue(JSContextRef context, Type_ value) { \
550 return JSValueMakeNumber(context, static_cast<double>(value)); \
551 }
552
553 CYCastJSValue_(int)
554 CYCastJSValue_(unsigned int)
555 CYCastJSValue_(long int)
556 CYCastJSValue_(long unsigned int)
557 CYCastJSValue_(long long int)
558 CYCastJSValue_(long long unsigned int)
559
560 JSValueRef CYJSUndefined(JSContextRef context) {
561 return JSValueMakeUndefined(context);
562 }
563
564 bool CYGetIndex(const char *value, ssize_t &index) {
565 if (value[0] != '0') {
566 char *end;
567 index = strtol(value, &end, 10);
568 if (value + strlen(value) == end)
569 return true;
570 } else if (value[1] == '\0') {
571 index = 0;
572 return true;
573 }
574
575 return false;
576 }
577
578 bool CYGetIndex(apr_pool_t *pool, NSString *value, ssize_t &index) {
579 return CYGetIndex(CYPoolCString(pool, value), index);
580 }
581
582 NSString *CYPoolNSCYON(apr_pool_t *pool, id value);
583
584 @interface NSMethodSignature (Cycript)
585 - (NSString *) _typeString;
586 @end
587
588 @interface NSObject (Cycript)
589
590 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
591 - (JSType) cy$JSType;
592
593 - (NSObject *) cy$toJSON:(NSString *)key;
594 - (NSString *) cy$toCYON;
595 - (NSString *) cy$toKey;
596
597 - (bool) cy$hasProperty:(NSString *)name;
598 - (NSObject *) cy$getProperty:(NSString *)name;
599 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
600 - (bool) cy$deleteProperty:(NSString *)name;
601
602 @end
603
604 @protocol Cycript
605 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
606 @end
607
608 @interface NSString (Cycript)
609 - (void *) cy$symbol;
610 @end
611
612 struct PropertyAttributes {
613 CYPool pool_;
614
615 const char *name;
616
617 const char *variable;
618
619 const char *getter_;
620 const char *setter_;
621
622 bool readonly;
623 bool copy;
624 bool retain;
625 bool nonatomic;
626 bool dynamic;
627 bool weak;
628 bool garbage;
629
630 PropertyAttributes(objc_property_t property) :
631 variable(NULL),
632 getter_(NULL),
633 setter_(NULL),
634 readonly(false),
635 copy(false),
636 retain(false),
637 nonatomic(false),
638 dynamic(false),
639 weak(false),
640 garbage(false)
641 {
642 name = property_getName(property);
643 const char *attributes(property_getAttributes(property));
644
645 for (char *state, *token(apr_strtok(apr_pstrdup(pool_, attributes), ",", &state)); token != NULL; token = apr_strtok(NULL, ",", &state)) {
646 switch (*token) {
647 case 'R': readonly = true; break;
648 case 'C': copy = true; break;
649 case '&': retain = true; break;
650 case 'N': nonatomic = true; break;
651 case 'G': getter_ = token + 1; break;
652 case 'S': setter_ = token + 1; break;
653 case 'V': variable = token + 1; break;
654 }
655 }
656
657 /*if (variable == NULL) {
658 variable = property_getName(property);
659 size_t size(strlen(variable));
660 char *name(new(pool_) char[size + 2]);
661 name[0] = '_';
662 memcpy(name + 1, variable, size);
663 name[size + 1] = '\0';
664 variable = name;
665 }*/
666 }
667
668 const char *Getter() {
669 if (getter_ == NULL)
670 getter_ = apr_pstrdup(pool_, name);
671 return getter_;
672 }
673
674 const char *Setter() {
675 if (setter_ == NULL && !readonly) {
676 size_t length(strlen(name));
677
678 char *temp(new(pool_) char[length + 5]);
679 temp[0] = 's';
680 temp[1] = 'e';
681 temp[2] = 't';
682
683 if (length != 0) {
684 temp[3] = toupper(name[0]);
685 memcpy(temp + 4, name + 1, length - 1);
686 }
687
688 temp[length + 3] = ':';
689 temp[length + 4] = '\0';
690 setter_ = temp;
691 }
692
693 return setter_;
694 }
695
696 };
697
698 @implementation NSProxy (Cycript)
699
700 - (NSObject *) cy$toJSON:(NSString *)key {
701 return [self description];
702 }
703
704 - (NSString *) cy$toCYON {
705 return [[self cy$toJSON:@""] cy$toCYON];
706 }
707
708 @end
709
710 @implementation NSObject (Cycript)
711
712 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
713 return CYMakeInstance(context, self, false);
714 }
715
716 - (JSType) cy$JSType {
717 return kJSTypeObject;
718 }
719
720 - (NSObject *) cy$toJSON:(NSString *)key {
721 return [self description];
722 }
723
724 - (NSString *) cy$toCYON {
725 return [[self cy$toJSON:@""] cy$toCYON];
726 }
727
728 - (NSString *) cy$toKey {
729 return [self cy$toCYON];
730 }
731
732 - (bool) cy$hasProperty:(NSString *)name {
733 return false;
734 }
735
736 - (NSObject *) cy$getProperty:(NSString *)name {
737 return nil;
738 }
739
740 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
741 return false;
742 }
743
744 - (bool) cy$deleteProperty:(NSString *)name {
745 return false;
746 }
747
748 @end
749
750 NSString *NSCFType$cy$toJSON(id self, SEL sel, NSString *key) {
751 return [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease];
752 }
753
754 @implementation WebUndefined (Cycript)
755
756 - (JSType) cy$JSType {
757 return kJSTypeUndefined;
758 }
759
760 - (NSObject *) cy$toJSON:(NSString *)key {
761 return self;
762 }
763
764 - (NSString *) cy$toCYON {
765 return @"undefined";
766 }
767
768 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
769 return CYJSUndefined(context);
770 }
771
772 @end
773
774 @implementation NSNull (Cycript)
775
776 - (JSType) cy$JSType {
777 return kJSTypeNull;
778 }
779
780 - (NSObject *) cy$toJSON:(NSString *)key {
781 return self;
782 }
783
784 - (NSString *) cy$toCYON {
785 return @"null";
786 }
787
788 @end
789
790 @implementation NSArray (Cycript)
791
792 - (NSString *) cy$toCYON {
793 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
794 [json appendString:@"["];
795
796 bool comma(false);
797 for (id object in self) {
798 if (comma)
799 [json appendString:@","];
800 else
801 comma = true;
802 if (object == nil || [object cy$JSType] != kJSTypeUndefined)
803 [json appendString:CYPoolNSCYON(NULL, object)];
804 else {
805 [json appendString:@","];
806 comma = false;
807 }
808 }
809
810 [json appendString:@"]"];
811 return json;
812 }
813
814 - (bool) cy$hasProperty:(NSString *)name {
815 if ([name isEqualToString:@"length"])
816 return true;
817
818 ssize_t index;
819 if (!CYGetIndex(NULL, name, index) || index < 0 || index >= static_cast<ssize_t>([self count]))
820 return [super cy$hasProperty:name];
821 else
822 return true;
823 }
824
825 - (NSObject *) cy$getProperty:(NSString *)name {
826 if ([name isEqualToString:@"length"])
827 return [NSNumber numberWithUnsignedInteger:[self count]];
828
829 ssize_t index;
830 if (!CYGetIndex(NULL, name, index) || index < 0 || index >= static_cast<ssize_t>([self count]))
831 return [super cy$getProperty:name];
832 else
833 return [self objectAtIndex:index];
834 }
835
836 @end
837
838 @implementation NSMutableArray (Cycript)
839
840 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
841 ssize_t index;
842 if (!CYGetIndex(NULL, name, index) || index < 0 || index >= static_cast<ssize_t>([self count]))
843 return [super cy$setProperty:name to:value];
844 else {
845 [self replaceObjectAtIndex:index withObject:(value ?: [NSNull null])];
846 return true;
847 }
848 }
849
850 - (bool) cy$deleteProperty:(NSString *)name {
851 ssize_t index;
852 if (!CYGetIndex(NULL, name, index) || index < 0 || index >= static_cast<ssize_t>([self count]))
853 return [super cy$deleteProperty:name];
854 else {
855 [self removeObjectAtIndex:index];
856 return true;
857 }
858 }
859
860 @end
861
862 @implementation NSDictionary (Cycript)
863
864 - (NSString *) cy$toCYON {
865 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
866 [json appendString:@"{"];
867
868 bool comma(false);
869 for (id key in self) {
870 if (comma)
871 [json appendString:@","];
872 else
873 comma = true;
874 [json appendString:[key cy$toKey]];
875 [json appendString:@":"];
876 NSObject *object([self objectForKey:key]);
877 [json appendString:CYPoolNSCYON(NULL, object)];
878 }
879
880 [json appendString:@"}"];
881 return json;
882 }
883
884 - (bool) cy$hasProperty:(NSString *)name {
885 return [self objectForKey:name] != nil;
886 }
887
888 - (NSObject *) cy$getProperty:(NSString *)name {
889 return [self objectForKey:name];
890 }
891
892 @end
893
894 @implementation NSMutableDictionary (Cycript)
895
896 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
897 [self setObject:(value ?: [NSNull null]) forKey:name];
898 return true;
899 }
900
901 - (bool) cy$deleteProperty:(NSString *)name {
902 if ([self objectForKey:name] == nil)
903 return false;
904 else {
905 [self removeObjectForKey:name];
906 return true;
907 }
908 }
909
910 @end
911
912 @implementation NSNumber (Cycript)
913
914 - (JSType) cy$JSType {
915 // XXX: this just seems stupid
916 return [self class] == NSCFBoolean_ ? kJSTypeBoolean : kJSTypeNumber;
917 }
918
919 - (NSObject *) cy$toJSON:(NSString *)key {
920 return self;
921 }
922
923 - (NSString *) cy$toCYON {
924 return [self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false";
925 }
926
927 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
928 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, [self boolValue]);
929 }
930
931 @end
932
933 @implementation NSString (Cycript)
934
935 - (JSType) cy$JSType {
936 return kJSTypeString;
937 }
938
939 - (NSObject *) cy$toJSON:(NSString *)key {
940 return self;
941 }
942
943 - (NSString *) cy$toCYON {
944 // XXX: this should use the better code from Output.cpp
945 CFMutableStringRef json(CFStringCreateMutableCopy(kCFAllocatorDefault, 0, (CFStringRef) self));
946
947 CFStringFindAndReplace(json, CFSTR("\\"), CFSTR("\\\\"), CFRangeMake(0, CFStringGetLength(json)), 0);
948 CFStringFindAndReplace(json, CFSTR("\""), CFSTR("\\\""), CFRangeMake(0, CFStringGetLength(json)), 0);
949 CFStringFindAndReplace(json, CFSTR("\t"), CFSTR("\\t"), CFRangeMake(0, CFStringGetLength(json)), 0);
950 CFStringFindAndReplace(json, CFSTR("\r"), CFSTR("\\r"), CFRangeMake(0, CFStringGetLength(json)), 0);
951 CFStringFindAndReplace(json, CFSTR("\n"), CFSTR("\\n"), CFRangeMake(0, CFStringGetLength(json)), 0);
952
953 CFStringInsert(json, 0, CFSTR("\""));
954 CFStringAppend(json, CFSTR("\""));
955
956 return [reinterpret_cast<const NSString *>(json) autorelease];
957 }
958
959 - (NSString *) cy$toKey {
960 const char *value([self UTF8String]);
961 size_t size(strlen(value));
962
963 if (size == 0)
964 goto cyon;
965
966 if (DigitRange_[value[0]]) {
967 ssize_t index;
968 if (!CYGetIndex(NULL, self, index) || index < 0)
969 goto cyon;
970 } else {
971 if (!WordStartRange_[value[0]])
972 goto cyon;
973 for (size_t i(1); i != size; ++i)
974 if (!WordEndRange_[value[i]])
975 goto cyon;
976 }
977
978 return self;
979
980 cyon:
981 return [self cy$toCYON];
982 }
983
984 - (void *) cy$symbol {
985 CYPool pool;
986 return dlsym(RTLD_DEFAULT, CYPoolCString(pool, self));
987 }
988
989 @end
990
991 @interface CYJSObject : NSDictionary {
992 JSObjectRef object_;
993 JSContextRef context_;
994 }
995
996 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
997
998 - (NSString *) cy$toJSON:(NSString *)key;
999
1000 - (NSUInteger) count;
1001 - (id) objectForKey:(id)key;
1002 - (NSEnumerator *) keyEnumerator;
1003 - (void) setObject:(id)object forKey:(id)key;
1004 - (void) removeObjectForKey:(id)key;
1005
1006 @end
1007
1008 @interface CYJSArray : NSArray {
1009 JSObjectRef object_;
1010 JSContextRef context_;
1011 }
1012
1013 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
1014
1015 - (NSUInteger) count;
1016 - (id) objectAtIndex:(NSUInteger)index;
1017
1018 @end
1019
1020 CYRange DigitRange_ (0x3ff000000000000LLU, 0x000000000000000LLU); // 0-9
1021 CYRange WordStartRange_(0x000001000000000LLU, 0x7fffffe87fffffeLLU); // A-Za-z_$
1022 CYRange WordEndRange_ (0x3ff001000000000LLU, 0x7fffffe87fffffeLLU); // A-Za-z_$0-9
1023
1024 #define CYTry \
1025 @try
1026 #define CYCatch \
1027 @catch (id error) { \
1028 CYThrow(context, error, exception); \
1029 return NULL; \
1030 }
1031
1032 void CYThrow(JSContextRef context, JSValueRef value);
1033
1034 apr_status_t CYPoolRelease_(void *data) {
1035 id object(reinterpret_cast<id>(data));
1036 [object release];
1037 return APR_SUCCESS;
1038 }
1039
1040 id CYPoolRelease(apr_pool_t *pool, id object) {
1041 if (object == nil)
1042 return nil;
1043 else if (pool == NULL)
1044 return [object autorelease];
1045 else {
1046 apr_pool_cleanup_register(pool, object, &CYPoolRelease_, &apr_pool_cleanup_null);
1047 return object;
1048 }
1049 }
1050
1051 CFTypeRef CYPoolRelease(apr_pool_t *pool, CFTypeRef object) {
1052 return (CFTypeRef) CYPoolRelease(pool, (id) object);
1053 }
1054
1055 id CYCastNSObject_(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
1056 JSValueRef exception(NULL);
1057 bool array(JSValueIsInstanceOfConstructor(context, object, Array_, &exception));
1058 CYThrow(context, exception);
1059 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
1060 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
1061 }
1062
1063 id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
1064 if (!JSValueIsObjectOfClass(context, object, Instance_))
1065 return CYCastNSObject_(pool, context, object);
1066 else {
1067 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1068 return internal->GetValue();
1069 }
1070 }
1071
1072 JSStringRef CYCopyJSString(id value) {
1073 return value == NULL ? NULL : JSStringCreateWithCFString(reinterpret_cast<CFStringRef>([value description]));
1074 }
1075
1076 JSStringRef CYCopyJSString(const char *value) {
1077 return value == NULL ? NULL : JSStringCreateWithUTF8CString(value);
1078 }
1079
1080 JSStringRef CYCopyJSString(JSStringRef value) {
1081 return value == NULL ? NULL : JSStringRetain(value);
1082 }
1083
1084 JSStringRef CYCopyJSString(JSContextRef context, JSValueRef value) {
1085 if (JSValueIsNull(context, value))
1086 return NULL;
1087 JSValueRef exception(NULL);
1088 JSStringRef string(JSValueToStringCopy(context, value, &exception));
1089 CYThrow(context, exception);
1090 return string;
1091 }
1092
1093 class CYJSString {
1094 private:
1095 JSStringRef string_;
1096
1097 void Clear_() {
1098 if (string_ != NULL)
1099 JSStringRelease(string_);
1100 }
1101
1102 public:
1103 CYJSString(const CYJSString &rhs) :
1104 string_(CYCopyJSString(rhs.string_))
1105 {
1106 }
1107
1108 template <typename Arg0_>
1109 CYJSString(Arg0_ arg0) :
1110 string_(CYCopyJSString(arg0))
1111 {
1112 }
1113
1114 template <typename Arg0_, typename Arg1_>
1115 CYJSString(Arg0_ arg0, Arg1_ arg1) :
1116 string_(CYCopyJSString(arg0, arg1))
1117 {
1118 }
1119
1120 CYJSString &operator =(const CYJSString &rhs) {
1121 Clear_();
1122 string_ = CYCopyJSString(rhs.string_);
1123 return *this;
1124 }
1125
1126 ~CYJSString() {
1127 Clear_();
1128 }
1129
1130 void Clear() {
1131 Clear_();
1132 string_ = NULL;
1133 }
1134
1135 operator JSStringRef() const {
1136 return string_;
1137 }
1138 };
1139
1140 CFStringRef CYCopyCFString(JSStringRef value) {
1141 return JSStringCopyCFString(kCFAllocatorDefault, value);
1142 }
1143
1144 CFStringRef CYCopyCFString(JSContextRef context, JSValueRef value) {
1145 return CYCopyCFString(CYJSString(context, value));
1146 }
1147
1148 double CYCastDouble(const char *value, size_t size) {
1149 char *end;
1150 double number(strtod(value, &end));
1151 if (end != value + size)
1152 return NAN;
1153 return number;
1154 }
1155
1156 double CYCastDouble(const char *value) {
1157 return CYCastDouble(value, strlen(value));
1158 }
1159
1160 double CYCastDouble(JSContextRef context, JSValueRef value) {
1161 JSValueRef exception(NULL);
1162 double number(JSValueToNumber(context, value, &exception));
1163 CYThrow(context, exception);
1164 return number;
1165 }
1166
1167 CFNumberRef CYCopyCFNumber(JSContextRef context, JSValueRef value) {
1168 double number(CYCastDouble(context, value));
1169 return CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &number);
1170 }
1171
1172 CFStringRef CYCopyCFString(const char *value) {
1173 return CFStringCreateWithCString(kCFAllocatorDefault, value, kCFStringEncodingUTF8);
1174 }
1175
1176 NSString *CYCastNSString(apr_pool_t *pool, const char *value) {
1177 return (NSString *) CYPoolRelease(pool, CYCopyCFString(value));
1178 }
1179
1180 NSString *CYCastNSString(apr_pool_t *pool, JSStringRef value) {
1181 return (NSString *) CYPoolRelease(pool, CYCopyCFString(value));
1182 }
1183
1184 bool CYCastBool(JSContextRef context, JSValueRef value) {
1185 return JSValueToBoolean(context, value);
1186 }
1187
1188 CFTypeRef CYCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value, bool cast) {
1189 CFTypeRef object;
1190 bool copy;
1191
1192 switch (JSType type = JSValueGetType(context, value)) {
1193 case kJSTypeUndefined:
1194 object = [WebUndefined undefined];
1195 copy = false;
1196 break;
1197
1198 case kJSTypeNull:
1199 return NULL;
1200 break;
1201
1202 case kJSTypeBoolean:
1203 object = CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse;
1204 copy = false;
1205 break;
1206
1207 case kJSTypeNumber:
1208 object = CYCopyCFNumber(context, value);
1209 copy = true;
1210 break;
1211
1212 case kJSTypeString:
1213 object = CYCopyCFString(context, value);
1214 copy = true;
1215 break;
1216
1217 case kJSTypeObject:
1218 // XXX: this might could be more efficient
1219 object = (CFTypeRef) CYCastNSObject(pool, context, (JSObjectRef) value);
1220 copy = false;
1221 break;
1222
1223 default:
1224 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"JSValueGetType() == 0x%x", type] userInfo:nil];
1225 break;
1226 }
1227
1228 if (cast != copy)
1229 return object;
1230 else if (copy)
1231 return CYPoolRelease(pool, object);
1232 else
1233 return CFRetain(object);
1234 }
1235
1236 CFTypeRef CYCastCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1237 return CYCFType(pool, context, value, true);
1238 }
1239
1240 CFTypeRef CYCopyCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1241 return CYCFType(pool, context, value, false);
1242 }
1243
1244 NSArray *CYCastNSArray(JSPropertyNameArrayRef names) {
1245 CYPool pool;
1246 size_t size(JSPropertyNameArrayGetCount(names));
1247 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1248 for (size_t index(0); index != size; ++index)
1249 [array addObject:CYCastNSString(pool, JSPropertyNameArrayGetNameAtIndex(names, index))];
1250 return array;
1251 }
1252
1253 id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1254 return reinterpret_cast<const NSObject *>(CYCastCFType(pool, context, value));
1255 }
1256
1257 void CYThrow(JSContextRef context, JSValueRef value) {
1258 if (value == NULL)
1259 return;
1260 @throw CYCastNSObject(NULL, context, value);
1261 }
1262
1263 JSValueRef CYJSNull(JSContextRef context) {
1264 return JSValueMakeNull(context);
1265 }
1266
1267 JSValueRef CYCastJSValue(JSContextRef context, JSStringRef value) {
1268 return value == NULL ? CYJSNull(context) : JSValueMakeString(context, value);
1269 }
1270
1271 JSValueRef CYCastJSValue(JSContextRef context, const char *value) {
1272 return CYCastJSValue(context, CYJSString(value));
1273 }
1274
1275 JSValueRef CYCastJSValue(JSContextRef context, id value) {
1276 if (value == nil)
1277 return CYJSNull(context);
1278 else if ([value respondsToSelector:@selector(cy$JSValueInContext:)])
1279 return [value cy$JSValueInContext:context];
1280 else
1281 return CYMakeInstance(context, value, false);
1282 }
1283
1284 JSObjectRef CYCastJSObject(JSContextRef context, JSValueRef value) {
1285 JSValueRef exception(NULL);
1286 JSObjectRef object(JSValueToObject(context, value, &exception));
1287 CYThrow(context, exception);
1288 return object;
1289 }
1290
1291 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, size_t index) {
1292 JSValueRef exception(NULL);
1293 JSValueRef value(JSObjectGetPropertyAtIndex(context, object, index, &exception));
1294 CYThrow(context, exception);
1295 return value;
1296 }
1297
1298 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, JSStringRef name) {
1299 JSValueRef exception(NULL);
1300 JSValueRef value(JSObjectGetProperty(context, object, name, &exception));
1301 CYThrow(context, exception);
1302 return value;
1303 }
1304
1305 void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef value) {
1306 JSValueRef exception(NULL);
1307 JSObjectSetProperty(context, object, name, value, kJSPropertyAttributeNone, &exception);
1308 CYThrow(context, exception);
1309 }
1310
1311 void CYThrow(JSContextRef context, id error, JSValueRef *exception) {
1312 if (exception == NULL)
1313 throw error;
1314 *exception = CYCastJSValue(context, error);
1315 }
1316
1317 JSValueRef CYCallAsFunction(JSContextRef context, JSObjectRef function, JSObjectRef _this, size_t count, JSValueRef arguments[]) {
1318 JSValueRef exception(NULL);
1319 JSValueRef value(JSObjectCallAsFunction(context, function, _this, count, arguments, &exception));
1320 CYThrow(context, exception);
1321 return value;
1322 }
1323
1324 bool CYIsCallable(JSContextRef context, JSValueRef value) {
1325 // XXX: this isn't actually correct
1326 return value != NULL && JSValueIsObject(context, value);
1327 }
1328
1329 @implementation CYJSObject
1330
1331 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
1332 if ((self = [super init]) != nil) {
1333 object_ = object;
1334 context_ = context;
1335 } return self;
1336 }
1337
1338 - (NSObject *) cy$toJSON:(NSString *)key {
1339 JSValueRef toJSON(CYGetProperty(context_, object_, toJSON_));
1340 if (!CYIsCallable(context_, toJSON))
1341 return [super cy$toJSON:key];
1342 else {
1343 JSValueRef arguments[1] = {CYCastJSValue(context_, key)};
1344 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toJSON, object_, 1, arguments));
1345 // XXX: do I really want an NSNull here?!
1346 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1347 }
1348 }
1349
1350 - (NSString *) cy$toCYON {
1351 JSValueRef toCYON(CYGetProperty(context_, object_, toCYON_));
1352 if (!CYIsCallable(context_, toCYON))
1353 return [super cy$toCYON];
1354 else {
1355 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toCYON, object_, 0, NULL));
1356 return CYCastNSString(NULL, CYJSString(context_, value));
1357 }
1358 }
1359
1360 - (NSUInteger) count {
1361 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1362 size_t size(JSPropertyNameArrayGetCount(names));
1363 JSPropertyNameArrayRelease(names);
1364 return size;
1365 }
1366
1367 - (id) objectForKey:(id)key {
1368 return CYCastNSObject(NULL, context_, CYGetProperty(context_, object_, CYJSString(key))) ?: [NSNull null];
1369 }
1370
1371 - (NSEnumerator *) keyEnumerator {
1372 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1373 NSEnumerator *enumerator([CYCastNSArray(names) objectEnumerator]);
1374 JSPropertyNameArrayRelease(names);
1375 return enumerator;
1376 }
1377
1378 - (void) setObject:(id)object forKey:(id)key {
1379 CYSetProperty(context_, object_, CYJSString(key), CYCastJSValue(context_, object));
1380 }
1381
1382 - (void) removeObjectForKey:(id)key {
1383 JSValueRef exception(NULL);
1384 (void) JSObjectDeleteProperty(context_, object_, CYJSString(key), &exception);
1385 CYThrow(context_, exception);
1386 }
1387
1388 @end
1389
1390 @implementation CYJSArray
1391
1392 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
1393 if ((self = [super init]) != nil) {
1394 object_ = object;
1395 context_ = context;
1396 } return self;
1397 }
1398
1399 - (NSUInteger) count {
1400 return CYCastDouble(context_, CYGetProperty(context_, object_, length_));
1401 }
1402
1403 - (id) objectAtIndex:(NSUInteger)index {
1404 JSValueRef exception(NULL);
1405 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
1406 CYThrow(context_, exception);
1407 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1408 }
1409
1410 @end
1411
1412 NSString *CYCopyNSCYON(id value) {
1413 NSString *string;
1414
1415 if (value == nil)
1416 string = @"nil";
1417 else {
1418 Class _class(object_getClass(value));
1419 SEL sel(@selector(cy$toCYON));
1420
1421 if (Method toCYON = class_getInstanceMethod(_class, sel))
1422 string = reinterpret_cast<NSString *(*)(id, SEL)>(method_getImplementation(toCYON))(value, sel);
1423 else if (Method methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:))) {
1424 if (reinterpret_cast<NSMethodSignature *(*)(id, SEL, SEL)>(method_getImplementation(methodSignatureForSelector))(value, @selector(methodSignatureForSelector:), sel) != nil)
1425 string = [value cy$toCYON];
1426 else goto fail;
1427 } else fail: {
1428 if (value == NSZombie_)
1429 string = @"_NSZombie_";
1430 else if (_class == NSZombie_)
1431 string = [NSString stringWithFormat:@"<_NSZombie_: %p>", value];
1432 // XXX: frowny /in/ the pants
1433 else if (value == NSMessageBuilder_ || value == Object_)
1434 string = nil;
1435 else
1436 string = [NSString stringWithFormat:@"%@", value];
1437 }
1438
1439 // XXX: frowny pants
1440 if (string == nil)
1441 string = @"undefined";
1442 }
1443
1444 return [string retain];
1445 }
1446
1447 NSString *CYCopyNSCYON(JSContextRef context, JSValueRef value, JSValueRef *exception) {
1448 if (JSValueIsNull(context, value))
1449 return [@"null" retain];
1450
1451 CYTry {
1452 CYPoolTry {
1453 return CYCopyNSCYON(CYCastNSObject(NULL, context, value));
1454 } CYPoolCatch(NULL)
1455 } CYCatch
1456 }
1457
1458 NSString *CYPoolNSCYON(apr_pool_t *pool, id value) {
1459 return CYPoolRelease(pool, static_cast<id>(CYCopyNSCYON(value)));
1460 }
1461
1462 const char *CYPoolCCYON(apr_pool_t *pool, JSContextRef context, JSValueRef value, JSValueRef *exception) {
1463 if (NSString *json = CYCopyNSCYON(context, value, exception)) {
1464 const char *string(CYPoolCString(pool, json));
1465 [json release];
1466 return string;
1467 } else return NULL;
1468 }
1469
1470 // XXX: use objc_getAssociatedObject and objc_setAssociatedObject on 10.6
1471 struct CYInternal :
1472 CYData
1473 {
1474 JSObjectRef object_;
1475
1476 CYInternal() :
1477 object_(NULL)
1478 {
1479 }
1480
1481 ~CYInternal() {
1482 // XXX: delete object_? ;(
1483 }
1484
1485 static CYInternal *Get(id self) {
1486 CYInternal *internal(NULL);
1487 if (object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal)) == NULL) {
1488 // XXX: do something epic? ;P
1489 }
1490
1491 return internal;
1492 }
1493
1494 static CYInternal *Set(id self) {
1495 CYInternal *internal(NULL);
1496 if (Ivar ivar = object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal))) {
1497 if (internal == NULL) {
1498 internal = new CYInternal();
1499 object_setIvar(self, ivar, reinterpret_cast<id>(internal));
1500 }
1501 } else {
1502 // XXX: do something epic? ;P
1503 }
1504
1505 return internal;
1506 }
1507
1508 bool HasProperty(JSContextRef context, JSStringRef name) {
1509 if (object_ == NULL)
1510 return false;
1511 return JSObjectHasProperty(context, object_, name);
1512 }
1513
1514 JSValueRef GetProperty(JSContextRef context, JSStringRef name) {
1515 if (object_ == NULL)
1516 return NULL;
1517 return CYGetProperty(context, object_, name);
1518 }
1519
1520 void SetProperty(JSContextRef context, JSStringRef name, JSValueRef value) {
1521 if (object_ == NULL)
1522 object_ = JSObjectMake(context, NULL, NULL);
1523 CYSetProperty(context, object_, name, value);
1524 }
1525 };
1526
1527 JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1528 Selector_privateData *internal(new Selector_privateData(sel));
1529 return JSObjectMake(context, Selector_, internal);
1530 }
1531
1532 JSObjectRef CYMakePointer(JSContextRef context, void *pointer, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
1533 Pointer *internal(new Pointer(pointer, type, owner));
1534 return JSObjectMake(context, Pointer_, internal);
1535 }
1536
1537 JSObjectRef CYMakeFunctor(JSContextRef context, void (*function)(), const char *type) {
1538 Functor_privateData *internal(new Functor_privateData(type, function));
1539 return JSObjectMake(context, Functor_, internal);
1540 }
1541
1542 const char *CYPoolCString(apr_pool_t *pool, JSStringRef value) {
1543 if (pool == NULL) {
1544 const char *string([CYCastNSString(NULL, value) UTF8String]);
1545 return string;
1546 } else {
1547 size_t size(JSStringGetMaximumUTF8CStringSize(value));
1548 char *string(new(pool) char[size]);
1549 JSStringGetUTF8CString(value, string, size);
1550 return string;
1551 }
1552 }
1553
1554 const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1555 return JSValueIsNull(context, value) ? NULL : CYPoolCString(pool, CYJSString(context, value));
1556 }
1557
1558 bool CYGetIndex(apr_pool_t *pool, JSStringRef value, ssize_t &index) {
1559 return CYGetIndex(CYPoolCString(pool, value), index);
1560 }
1561
1562 // XXX: this macro is unhygenic
1563 #define CYCastCString(context, value) ({ \
1564 char *utf8; \
1565 if (value == NULL) \
1566 utf8 = NULL; \
1567 else if (JSStringRef string = CYCopyJSString(context, value)) { \
1568 size_t size(JSStringGetMaximumUTF8CStringSize(string)); \
1569 utf8 = reinterpret_cast<char *>(alloca(size)); \
1570 JSStringGetUTF8CString(string, utf8, size); \
1571 JSStringRelease(string); \
1572 } else \
1573 utf8 = NULL; \
1574 utf8; \
1575 })
1576
1577 void *CYCastPointer_(JSContextRef context, JSValueRef value) {
1578 switch (JSValueGetType(context, value)) {
1579 case kJSTypeNull:
1580 return NULL;
1581 /*case kJSTypeString:
1582 return dlsym(RTLD_DEFAULT, CYCastCString(context, value));
1583 case kJSTypeObject:
1584 if (JSValueIsObjectOfClass(context, value, Pointer_)) {
1585 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate((JSObjectRef) value)));
1586 return internal->value_;
1587 }*/
1588 default:
1589 double number(CYCastDouble(context, value));
1590 if (std::isnan(number))
1591 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"cannot convert value to pointer" userInfo:nil];
1592 return reinterpret_cast<void *>(static_cast<uintptr_t>(static_cast<long long>(number)));
1593 }
1594 }
1595
1596 template <typename Type_>
1597 _finline Type_ CYCastPointer(JSContextRef context, JSValueRef value) {
1598 return reinterpret_cast<Type_>(CYCastPointer_(context, value));
1599 }
1600
1601 SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1602 if (JSValueIsObjectOfClass(context, value, Selector_)) {
1603 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1604 return reinterpret_cast<SEL>(internal->value_);
1605 } else
1606 return CYCastPointer<SEL>(context, value);
1607 }
1608
1609 void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) {
1610 switch (type->primitive) {
1611 case sig::boolean_P:
1612 *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
1613 break;
1614
1615 #define CYPoolFFI_(primitive, native) \
1616 case sig::primitive ## _P: \
1617 *reinterpret_cast<native *>(data) = CYCastDouble(context, value); \
1618 break;
1619
1620 CYPoolFFI_(uchar, unsigned char)
1621 CYPoolFFI_(char, char)
1622 CYPoolFFI_(ushort, unsigned short)
1623 CYPoolFFI_(short, short)
1624 CYPoolFFI_(ulong, unsigned long)
1625 CYPoolFFI_(long, long)
1626 CYPoolFFI_(uint, unsigned int)
1627 CYPoolFFI_(int, int)
1628 CYPoolFFI_(ulonglong, unsigned long long)
1629 CYPoolFFI_(longlong, long long)
1630 CYPoolFFI_(float, float)
1631 CYPoolFFI_(double, double)
1632
1633 case sig::object_P:
1634 case sig::typename_P:
1635 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1636 break;
1637
1638 case sig::selector_P:
1639 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1640 break;
1641
1642 case sig::pointer_P:
1643 *reinterpret_cast<void **>(data) = CYCastPointer<void *>(context, value);
1644 break;
1645
1646 case sig::string_P:
1647 *reinterpret_cast<const char **>(data) = CYPoolCString(pool, context, value);
1648 break;
1649
1650 case sig::struct_P: {
1651 uint8_t *base(reinterpret_cast<uint8_t *>(data));
1652 JSObjectRef aggregate(JSValueIsObject(context, value) ? (JSObjectRef) value : NULL);
1653 for (size_t index(0); index != type->data.signature.count; ++index) {
1654 sig::Element *element(&type->data.signature.elements[index]);
1655 ffi_type *field(ffi->elements[index]);
1656
1657 JSValueRef rhs;
1658 if (aggregate == NULL)
1659 rhs = value;
1660 else {
1661 rhs = CYGetProperty(context, aggregate, index);
1662 if (JSValueIsUndefined(context, rhs)) {
1663 if (element->name != NULL)
1664 rhs = CYGetProperty(context, aggregate, CYJSString(element->name));
1665 else
1666 goto undefined;
1667 if (JSValueIsUndefined(context, rhs)) undefined:
1668 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"unable to extract structure value" userInfo:nil];
1669 }
1670 }
1671
1672 CYPoolFFI(pool, context, element->type, field, base, rhs);
1673 // XXX: alignment?
1674 base += field->size;
1675 }
1676 } break;
1677
1678 case sig::void_P:
1679 break;
1680
1681 default:
1682 NSLog(@"CYPoolFFI(%c)\n", type->primitive);
1683 _assert(false);
1684 }
1685 }
1686
1687 JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize = false, JSObjectRef owner = NULL) {
1688 JSValueRef value;
1689
1690 switch (type->primitive) {
1691 case sig::boolean_P:
1692 value = CYCastJSValue(context, *reinterpret_cast<bool *>(data));
1693 break;
1694
1695 #define CYFromFFI_(primitive, native) \
1696 case sig::primitive ## _P: \
1697 value = CYCastJSValue(context, *reinterpret_cast<native *>(data)); \
1698 break;
1699
1700 CYFromFFI_(uchar, unsigned char)
1701 CYFromFFI_(char, char)
1702 CYFromFFI_(ushort, unsigned short)
1703 CYFromFFI_(short, short)
1704 CYFromFFI_(ulong, unsigned long)
1705 CYFromFFI_(long, long)
1706 CYFromFFI_(uint, unsigned int)
1707 CYFromFFI_(int, int)
1708 CYFromFFI_(ulonglong, unsigned long long)
1709 CYFromFFI_(longlong, long long)
1710 CYFromFFI_(float, float)
1711 CYFromFFI_(double, double)
1712
1713 case sig::object_P: {
1714 if (id object = *reinterpret_cast<id *>(data)) {
1715 value = CYCastJSValue(context, object);
1716 if (initialize)
1717 [object release];
1718 } else goto null;
1719 } break;
1720
1721 case sig::typename_P:
1722 value = CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
1723 break;
1724
1725 case sig::selector_P:
1726 if (SEL sel = *reinterpret_cast<SEL *>(data))
1727 value = CYMakeSelector(context, sel);
1728 else goto null;
1729 break;
1730
1731 case sig::pointer_P:
1732 if (void *pointer = *reinterpret_cast<void **>(data))
1733 value = CYMakePointer(context, pointer, type->data.data.type, ffi, owner);
1734 else goto null;
1735 break;
1736
1737 case sig::string_P:
1738 if (char *utf8 = *reinterpret_cast<char **>(data))
1739 value = CYCastJSValue(context, utf8);
1740 else goto null;
1741 break;
1742
1743 case sig::struct_P:
1744 value = CYMakeStruct(context, data, type, ffi, owner);
1745 break;
1746
1747 case sig::void_P:
1748 value = CYJSUndefined(context);
1749 break;
1750
1751 null:
1752 value = CYJSNull(context);
1753 break;
1754
1755 default:
1756 NSLog(@"CYFromFFI(%c)\n", type->primitive);
1757 _assert(false);
1758 }
1759
1760 return value;
1761 }
1762
1763 static bool CYImplements(id object, Class _class, SEL selector, bool devoid) {
1764 if (Method method = class_getInstanceMethod(_class, selector)) {
1765 if (!devoid)
1766 return true;
1767 char type[16];
1768 method_getReturnType(method, type, sizeof(type));
1769 if (type[0] != 'v')
1770 return true;
1771 }
1772
1773 // XXX: possibly use a more "awesome" check?
1774 return false;
1775 }
1776
1777 const char *CYPoolTypeEncoding(apr_pool_t *pool, Class _class, SEL sel, Method method) {
1778 if (method != NULL)
1779 return method_getTypeEncoding(method);
1780 else if (NSString *type = [[Bridge_ objectAtIndex:1] objectForKey:CYCastNSString(pool, sel_getName(sel))])
1781 return CYPoolCString(pool, type);
1782 else
1783 return NULL;
1784 }
1785
1786 void FunctionClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1787 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
1788
1789 JSContextRef context(internal->context_);
1790
1791 size_t count(internal->cif_.nargs);
1792 JSValueRef values[count];
1793
1794 for (size_t index(0); index != count; ++index)
1795 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
1796
1797 JSValueRef value(CYCallAsFunction(context, internal->function_, NULL, count, values));
1798 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
1799 }
1800
1801 void MessageClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1802 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
1803
1804 JSContextRef context(internal->context_);
1805
1806 size_t count(internal->cif_.nargs);
1807 JSValueRef values[count];
1808
1809 for (size_t index(0); index != count; ++index)
1810 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
1811
1812 JSObjectRef _this(CYCastJSObject(context, values[0]));
1813
1814 JSValueRef value(CYCallAsFunction(context, internal->function_, _this, count - 2, values + 2));
1815 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
1816 }
1817
1818 Closure_privateData *CYMakeFunctor_(JSContextRef context, JSObjectRef function, const char *type, void (*callback)(ffi_cif *, void *, void **, void *)) {
1819 // XXX: in case of exceptions this will leak
1820 // XXX: in point of fact, this may /need/ to leak :(
1821 Closure_privateData *internal(new Closure_privateData(type));
1822
1823 ffi_closure *closure((ffi_closure *) _syscall(mmap(
1824 NULL, sizeof(ffi_closure),
1825 PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE,
1826 -1, 0
1827 )));
1828
1829 ffi_status status(ffi_prep_closure(closure, &internal->cif_, callback, internal));
1830 _assert(status == FFI_OK);
1831
1832 _syscall(mprotect(closure, sizeof(*closure), PROT_READ | PROT_EXEC));
1833
1834 internal->value_ = closure;
1835
1836 internal->context_ = CYGetJSContext();
1837 internal->function_ = function;
1838
1839 return internal;
1840 }
1841
1842 JSObjectRef CYMakeFunctor(JSContextRef context, JSObjectRef function, const char *type) {
1843 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &FunctionClosure_));
1844 return JSObjectMake(context, Functor_, internal);
1845 }
1846
1847 static JSObjectRef CYMakeFunctor(JSContextRef context, JSValueRef value, const char *type) {
1848 JSValueRef exception(NULL);
1849 bool function(JSValueIsInstanceOfConstructor(context, value, Function_, &exception));
1850 CYThrow(context, exception);
1851
1852 if (function) {
1853 JSObjectRef function(CYCastJSObject(context, value));
1854 return CYMakeFunctor(context, function, type);
1855 } else {
1856 void (*function)()(CYCastPointer<void (*)()>(context, value));
1857 return CYMakeFunctor(context, function, type);
1858 }
1859 }
1860
1861 static JSObjectRef CYMakeMessage(JSContextRef context, SEL sel, IMP imp, const char *type) {
1862 Message_privateData *internal(new Message_privateData(sel, type, imp));
1863 return JSObjectMake(context, Message_, internal);
1864 }
1865
1866 static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *type) {
1867 JSObjectRef function(CYCastJSObject(context, value));
1868 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &MessageClosure_));
1869 return reinterpret_cast<IMP>(internal->GetValue());
1870 }
1871
1872 static bool Prototype_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1873 Prototype *internal(reinterpret_cast<Prototype *>(JSObjectGetPrivate(object)));
1874 Class _class(internal->GetValue());
1875
1876 CYPool pool;
1877 const char *name(CYPoolCString(pool, property));
1878
1879 if (SEL sel = sel_getUid(name))
1880 if (class_getInstanceMethod(_class, sel) != NULL)
1881 return true;
1882
1883 return false;
1884 }
1885
1886 static JSValueRef Prototype_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1887 Prototype *internal(reinterpret_cast<Prototype *>(JSObjectGetPrivate(object)));
1888 Class _class(internal->GetValue());
1889
1890 CYPool pool;
1891 const char *name(CYPoolCString(pool, property));
1892
1893 if (SEL sel = sel_getUid(name))
1894 if (Method method = class_getInstanceMethod(_class, sel))
1895 return CYMakeMessage(context, sel, method_getImplementation(method), method_getTypeEncoding(method));
1896
1897 return NULL;
1898 }
1899
1900 static bool Prototype_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1901 Prototype *internal(reinterpret_cast<Prototype *>(JSObjectGetPrivate(object)));
1902 Class _class(internal->GetValue());
1903
1904 CYPool pool;
1905 const char *name(CYPoolCString(pool, property));
1906
1907 SEL sel(sel_registerName(name));
1908
1909 Method method(class_getInstanceMethod(_class, sel));
1910
1911 const char *type;
1912 IMP imp;
1913
1914 if (JSValueIsObjectOfClass(context, value, Message_)) {
1915 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1916 type = sig::Unparse(pool, &message->signature_);
1917 imp = reinterpret_cast<IMP>(message->GetValue());
1918 } else {
1919 type = CYPoolTypeEncoding(pool, _class, sel, method);
1920 imp = CYMakeMessage(context, value, type);
1921 }
1922
1923 if (method != NULL)
1924 method_setImplementation(method, imp);
1925 else
1926 class_replaceMethod(_class, sel, imp, type);
1927
1928 return true;
1929 }
1930
1931 #if !__OBJC2__
1932 static bool Prototype_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1933 Prototype *internal(reinterpret_cast<Prototype *>(JSObjectGetPrivate(object)));
1934 Class _class(internal->GetValue());
1935
1936 CYPool pool;
1937 const char *name(CYPoolCString(pool, property));
1938
1939 if (SEL sel = sel_getUid(name))
1940 if (Method method = class_getInstanceMethod(_class, sel)) {
1941 objc_method_list list = {NULL, 1, {method}};
1942 class_removeMethods(_class, &list);
1943 return true;
1944 }
1945
1946 return false;
1947 }
1948 #endif
1949
1950 static void Prototype_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1951 Prototype *internal(reinterpret_cast<Prototype *>(JSObjectGetPrivate(object)));
1952 Class _class(internal->GetValue());
1953
1954 unsigned int size;
1955 Method *data(class_copyMethodList(_class, &size));
1956 for (size_t i(0); i != size; ++i)
1957 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
1958 free(data);
1959 }
1960
1961 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1962 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1963 id self(internal->GetValue());
1964
1965 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1966 return true;
1967
1968 CYPool pool;
1969 NSString *name(CYCastNSString(pool, property));
1970
1971 if (CYInternal *internal = CYInternal::Get(self))
1972 if (internal->HasProperty(context, property))
1973 return true;
1974
1975 CYPoolTry {
1976 if ([self cy$hasProperty:name])
1977 return true;
1978 } CYPoolCatch(false)
1979
1980 const char *string(CYPoolCString(pool, name));
1981 Class _class(object_getClass(self));
1982
1983 if (class_getProperty(_class, string) != NULL)
1984 return true;
1985
1986 if (SEL sel = sel_getUid(string))
1987 if (CYImplements(self, _class, sel, true))
1988 return true;
1989
1990 return false;
1991 }
1992
1993 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1994 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1995 id self(internal->GetValue());
1996
1997 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1998 return Internal::Make(context, self, object);
1999
2000 CYTry {
2001 CYPool pool;
2002 NSString *name(CYCastNSString(pool, property));
2003
2004 if (CYInternal *internal = CYInternal::Get(self))
2005 if (JSValueRef value = internal->GetProperty(context, property))
2006 return value;
2007
2008 CYPoolTry {
2009 if (NSObject *data = [self cy$getProperty:name])
2010 return CYCastJSValue(context, data);
2011 } CYPoolCatch(NULL)
2012
2013 const char *string(CYPoolCString(pool, name));
2014 Class _class(object_getClass(self));
2015
2016 if (objc_property_t property = class_getProperty(_class, string)) {
2017 PropertyAttributes attributes(property);
2018 SEL sel(sel_registerName(attributes.Getter()));
2019 return CYSendMessage(pool, context, self, sel, 0, NULL, false, exception);
2020 }
2021
2022 if (SEL sel = sel_getUid(string))
2023 if (CYImplements(self, _class, sel, true))
2024 return CYSendMessage(pool, context, self, sel, 0, NULL, false, exception);
2025
2026 return NULL;
2027 } CYCatch
2028 }
2029
2030 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2031 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2032 id self(internal->GetValue());
2033
2034 CYPool pool;
2035
2036 CYTry {
2037 NSString *name(CYCastNSString(pool, property));
2038 NSString *data(CYCastNSObject(pool, context, value));
2039
2040 CYPoolTry {
2041 if ([self cy$setProperty:name to:data])
2042 return true;
2043 } CYPoolCatch(NULL)
2044
2045 const char *string(CYPoolCString(pool, name));
2046 Class _class(object_getClass(self));
2047
2048 if (objc_property_t property = class_getProperty(_class, string)) {
2049 PropertyAttributes attributes(property);
2050 if (const char *setter = attributes.Setter()) {
2051 SEL sel(sel_registerName(setter));
2052 JSValueRef arguments[1] = {value};
2053 CYSendMessage(pool, context, self, sel, 1, arguments, false, exception);
2054 return true;
2055 }
2056 }
2057
2058 size_t length(strlen(string));
2059
2060 char set[length + 5];
2061
2062 set[0] = 's';
2063 set[1] = 'e';
2064 set[2] = 't';
2065
2066 if (string[0] != '\0') {
2067 set[3] = toupper(string[0]);
2068 memcpy(set + 4, string + 1, length - 1);
2069 }
2070
2071 set[length + 3] = ':';
2072 set[length + 4] = '\0';
2073
2074 if (SEL sel = sel_getUid(set))
2075 if (CYImplements(self, _class, sel, false)) {
2076 JSValueRef arguments[1] = {value};
2077 CYSendMessage(pool, context, self, sel, 1, arguments, false, exception);
2078 }
2079
2080 if (CYInternal *internal = CYInternal::Set(self)) {
2081 internal->SetProperty(context, property, value);
2082 return true;
2083 }
2084
2085 return false;
2086 } CYCatch
2087 }
2088
2089 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2090 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2091 id self(internal->GetValue());
2092
2093 CYTry {
2094 CYPoolTry {
2095 NSString *name(CYCastNSString(NULL, property));
2096 return [self cy$deleteProperty:name];
2097 } CYPoolCatch(NULL)
2098 } CYCatch
2099 }
2100
2101 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2102 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2103 id self(internal->GetValue());
2104
2105 CYPool pool;
2106 Class _class(object_getClass(self));
2107
2108 {
2109 unsigned int size;
2110 objc_property_t *data(class_copyPropertyList(_class, &size));
2111 for (size_t i(0); i != size; ++i)
2112 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
2113 free(data);
2114 }
2115 }
2116
2117 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2118 CYTry {
2119 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2120 JSObjectRef value(Instance::Make(context, [internal->GetValue() alloc], Instance::Uninitialized));
2121 return value;
2122 } CYCatch
2123 }
2124
2125 static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2126 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2127 CYPool pool;
2128
2129 id self(internal->GetValue());
2130 const char *name(CYPoolCString(pool, property));
2131
2132 if (object_getInstanceVariable(self, name, NULL) != NULL)
2133 return true;
2134
2135 return false;
2136 }
2137
2138 static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2139 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2140 CYPool pool;
2141
2142 CYTry {
2143 id self(internal->GetValue());
2144 const char *name(CYPoolCString(pool, property));
2145
2146 if (Ivar ivar = object_getInstanceVariable(self, name, NULL)) {
2147 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
2148 return CYFromFFI(context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar));
2149 }
2150
2151 return NULL;
2152 } CYCatch
2153 }
2154
2155 static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2156 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2157 CYPool pool;
2158
2159 CYTry {
2160 id self(internal->GetValue());
2161 const char *name(CYPoolCString(pool, property));
2162
2163 if (Ivar ivar = object_getInstanceVariable(self, name, NULL)) {
2164 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
2165 CYPoolFFI(pool, context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
2166 return true;
2167 }
2168
2169 return false;
2170 } CYCatch
2171 }
2172
2173 static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
2174 if (Class super = class_getSuperclass(_class))
2175 Internal_getPropertyNames_(super, names);
2176
2177 unsigned int size;
2178 Ivar *data(class_copyIvarList(_class, &size));
2179 for (size_t i(0); i != size; ++i)
2180 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
2181 free(data);
2182 }
2183
2184 static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2185 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2186 CYPool pool;
2187
2188 id self(internal->GetValue());
2189 Class _class(object_getClass(self));
2190
2191 Internal_getPropertyNames_(_class, names);
2192 }
2193
2194 static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2195 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2196 return internal->owner_;
2197 }
2198
2199 bool Index_(apr_pool_t *pool, Struct_privateData *internal, JSStringRef property, ssize_t &index, uint8_t *&base) {
2200 Type_privateData *typical(internal->type_);
2201 sig::Type *type(typical->type_);
2202 if (type == NULL)
2203 return false;
2204
2205 const char *name(CYPoolCString(pool, property));
2206 size_t length(strlen(name));
2207 double number(CYCastDouble(name, length));
2208
2209 size_t count(type->data.signature.count);
2210
2211 if (std::isnan(number)) {
2212 if (property == NULL)
2213 return false;
2214
2215 sig::Element *elements(type->data.signature.elements);
2216
2217 for (size_t local(0); local != count; ++local) {
2218 sig::Element *element(&elements[local]);
2219 if (element->name != NULL && strcmp(name, element->name) == 0) {
2220 index = local;
2221 goto base;
2222 }
2223 }
2224
2225 return false;
2226 } else {
2227 index = static_cast<ssize_t>(number);
2228 if (index != number || index < 0 || static_cast<size_t>(index) >= count)
2229 return false;
2230 }
2231
2232 base:
2233 ffi_type **elements(typical->GetFFI()->elements);
2234
2235 base = reinterpret_cast<uint8_t *>(internal->value_);
2236 for (ssize_t local(0); local != index; ++local)
2237 base += elements[local]->size;
2238
2239 return true;
2240 }
2241
2242 static JSValueRef Pointer_getIndex(JSContextRef context, JSObjectRef object, size_t index, JSValueRef *exception) {
2243 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2244 Type_privateData *typical(internal->type_);
2245
2246 ffi_type *ffi(typical->GetFFI());
2247
2248 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
2249 base += ffi->size * index;
2250
2251 JSObjectRef owner(internal->owner_ ?: object);
2252
2253 CYTry {
2254 return CYFromFFI(context, typical->type_, ffi, base, false, owner);
2255 } CYCatch
2256 }
2257
2258 static JSValueRef Pointer_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2259 CYPool pool;
2260 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2261 Type_privateData *typical(internal->type_);
2262
2263 if (typical->type_ == NULL)
2264 return NULL;
2265
2266 ssize_t index;
2267 if (!CYGetIndex(pool, property, index))
2268 return NULL;
2269
2270 return Pointer_getIndex(context, object, index, exception);
2271 }
2272
2273 static JSValueRef Pointer_getProperty_$cyi(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2274 return Pointer_getIndex(context, object, 0, exception);
2275 }
2276
2277 static bool Pointer_setIndex(JSContextRef context, JSObjectRef object, size_t index, JSValueRef value, JSValueRef *exception) {
2278 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2279 Type_privateData *typical(internal->type_);
2280
2281 ffi_type *ffi(typical->GetFFI());
2282
2283 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
2284 base += ffi->size * index;
2285
2286 CYTry {
2287 CYPoolFFI(NULL, context, typical->type_, ffi, base, value);
2288 return true;
2289 } CYCatch
2290 }
2291
2292 static bool Pointer_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2293 CYPool pool;
2294 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2295 Type_privateData *typical(internal->type_);
2296
2297 if (typical->type_ == NULL)
2298 return NULL;
2299
2300 ssize_t index;
2301 if (!CYGetIndex(pool, property, index))
2302 return NULL;
2303
2304 return Pointer_setIndex(context, object, 0, value, exception);
2305 }
2306
2307 static bool Pointer_setProperty_$cyi(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2308 return Pointer_setIndex(context, object, 0, value, exception);
2309 }
2310
2311 static JSValueRef Struct_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2312 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(_this)));
2313 Type_privateData *typical(internal->type_);
2314 return CYMakePointer(context, internal->value_, typical->type_, typical->ffi_, _this);
2315 }
2316
2317 static JSValueRef Struct_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2318 CYPool pool;
2319 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
2320 Type_privateData *typical(internal->type_);
2321
2322 ssize_t index;
2323 uint8_t *base;
2324
2325 if (!Index_(pool, internal, property, index, base))
2326 return NULL;
2327
2328 JSObjectRef owner(internal->owner_ ?: object);
2329
2330 CYTry {
2331 return CYFromFFI(context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, false, owner);
2332 } CYCatch
2333 }
2334
2335 static bool Struct_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2336 CYPool pool;
2337 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
2338 Type_privateData *typical(internal->type_);
2339
2340 ssize_t index;
2341 uint8_t *base;
2342
2343 if (!Index_(pool, internal, property, index, base))
2344 return false;
2345
2346 CYTry {
2347 CYPoolFFI(NULL, context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, value);
2348 return true;
2349 } CYCatch
2350 }
2351
2352 static void Struct_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2353 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
2354 Type_privateData *typical(internal->type_);
2355 sig::Type *type(typical->type_);
2356
2357 if (type == NULL)
2358 return;
2359
2360 size_t count(type->data.signature.count);
2361 sig::Element *elements(type->data.signature.elements);
2362
2363 char number[32];
2364
2365 for (size_t index(0); index != count; ++index) {
2366 const char *name;
2367 name = elements[index].name;
2368
2369 if (name == NULL) {
2370 sprintf(number, "%lu", index);
2371 name = number;
2372 }
2373
2374 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
2375 }
2376 }
2377
2378 JSValueRef CYCallFunction(apr_pool_t *pool, JSContextRef context, size_t setups, void *setup[], size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception, sig::Signature *signature, ffi_cif *cif, void (*function)()) {
2379 CYTry {
2380 if (setups + count != signature->count - 1)
2381 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to ffi function" userInfo:nil];
2382
2383 size_t size(setups + count);
2384 void *values[size];
2385 memcpy(values, setup, sizeof(void *) * setups);
2386
2387 for (size_t index(setups); index != size; ++index) {
2388 sig::Element *element(&signature->elements[index + 1]);
2389 ffi_type *ffi(cif->arg_types[index]);
2390 // XXX: alignment?
2391 values[index] = new(pool) uint8_t[ffi->size];
2392 CYPoolFFI(pool, context, element->type, ffi, values[index], arguments[index - setups]);
2393 }
2394
2395 uint8_t value[cif->rtype->size];
2396 ffi_call(cif, function, value, values);
2397
2398 return CYFromFFI(context, signature->elements[0].type, cif->rtype, value, initialize);
2399 } CYCatch
2400 }
2401
2402 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2403 CYTry {
2404 CYPool pool;
2405 NSString *name(CYCastNSString(pool, property));
2406 if (Class _class = NSClassFromString(name))
2407 return CYMakeInstance(context, _class, true);
2408 return NULL;
2409 } CYCatch
2410 }
2411
2412 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2413 size_t size(objc_getClassList(NULL, 0));
2414 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
2415
2416 get:
2417 size_t writ(objc_getClassList(data, size));
2418 if (size < writ) {
2419 size = writ;
2420 if (Class *copy = reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ))) {
2421 data = copy;
2422 goto get;
2423 } else goto done;
2424 }
2425
2426 for (size_t i(0); i != writ; ++i)
2427 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
2428
2429 done:
2430 free(data);
2431 }
2432
2433 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2434 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2435
2436 CYTry {
2437 CYPool pool;
2438 const char *name(CYPoolCString(pool, property));
2439 unsigned int size;
2440 const char **data(objc_copyClassNamesForImage(internal, &size));
2441 JSValueRef value;
2442 for (size_t i(0); i != size; ++i)
2443 if (strcmp(name, data[i]) == 0) {
2444 if (Class _class = objc_getClass(name)) {
2445 value = CYMakeInstance(context, _class, true);
2446 goto free;
2447 } else
2448 break;
2449 }
2450 value = NULL;
2451 free:
2452 free(data);
2453 return value;
2454 } CYCatch
2455 }
2456
2457 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2458 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2459 unsigned int size;
2460 const char **data(objc_copyClassNamesForImage(internal, &size));
2461 for (size_t i(0); i != size; ++i)
2462 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2463 free(data);
2464 }
2465
2466 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2467 CYTry {
2468 CYPool pool;
2469 const char *name(CYPoolCString(pool, property));
2470 unsigned int size;
2471 const char **data(objc_copyImageNames(&size));
2472 for (size_t i(0); i != size; ++i)
2473 if (strcmp(name, data[i]) == 0) {
2474 name = data[i];
2475 goto free;
2476 }
2477 name = NULL;
2478 free:
2479 free(data);
2480 if (name == NULL)
2481 return NULL;
2482 JSObjectRef value(JSObjectMake(context, NULL, NULL));
2483 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(name)));
2484 return value;
2485 } CYCatch
2486 }
2487
2488 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2489 unsigned int size;
2490 const char **data(objc_copyImageNames(&size));
2491 for (size_t i(0); i != size; ++i)
2492 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2493 free(data);
2494 }
2495
2496 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2497 CYTry {
2498 CYPool pool;
2499 NSString *name(CYCastNSString(pool, property));
2500 if (Protocol *protocol = NSProtocolFromString(name))
2501 return CYMakeInstance(context, protocol, true);
2502 return NULL;
2503 } CYCatch
2504 }
2505
2506 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2507 unsigned int size;
2508 Protocol **data(objc_copyProtocolList(&size));
2509 for (size_t i(0); i != size; ++i)
2510 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
2511 free(data);
2512 }
2513
2514 static JSValueRef Runtime_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2515 if (JSStringIsEqualToUTF8CString(property, "nil"))
2516 return Instance::Make(context, nil);
2517
2518 CYTry {
2519 CYPool pool;
2520 NSString *name(CYCastNSString(pool, property));
2521 if (Class _class = NSClassFromString(name))
2522 return CYMakeInstance(context, _class, true);
2523 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:0] objectForKey:name])
2524 switch ([[entry objectAtIndex:0] intValue]) {
2525 case 0:
2526 return JSEvaluateScript(CYGetJSContext(), CYJSString([entry objectAtIndex:1]), NULL, NULL, 0, NULL);
2527 case 1:
2528 return CYMakeFunctor(context, reinterpret_cast<void (*)()>([name cy$symbol]), CYPoolCString(pool, [entry objectAtIndex:1]));
2529 case 2:
2530 // XXX: this is horrendously inefficient
2531 sig::Signature signature;
2532 sig::Parse(pool, &signature, CYPoolCString(pool, [entry objectAtIndex:1]), &Structor_);
2533 ffi_cif cif;
2534 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2535 return CYFromFFI(context, signature.elements[0].type, cif.rtype, [name cy$symbol]);
2536 }
2537 return NULL;
2538 } CYCatch
2539 }
2540
2541 bool stret(ffi_type *ffi_type) {
2542 return ffi_type->type == FFI_TYPE_STRUCT && (
2543 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
2544 struct_forward_array[ffi_type->size] != 0
2545 );
2546 }
2547
2548 extern "C" {
2549 int *_NSGetArgc(void);
2550 char ***_NSGetArgv(void);
2551 int UIApplicationMain(int argc, char *argv[], NSString *principalClassName, NSString *delegateClassName);
2552 }
2553
2554 static JSValueRef System_print(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2555 CYTry {
2556 NSLog(@"%s", CYCastCString(context, arguments[0]));
2557 return CYJSUndefined(context);
2558 } CYCatch
2559 }
2560
2561 JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception) {
2562 const char *type;
2563
2564 Class _class(object_getClass(self));
2565 if (Method method = class_getInstanceMethod(_class, _cmd))
2566 type = method_getTypeEncoding(method);
2567 else {
2568 CYTry {
2569 CYPoolTry {
2570 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
2571 if (method == nil)
2572 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"unrecognized selector %s sent to object %p", sel_getName(_cmd), self] userInfo:nil];
2573 type = CYPoolCString(pool, [method _typeString]);
2574 } CYPoolCatch(NULL)
2575 } CYCatch
2576 }
2577
2578 void *setup[2];
2579 setup[0] = &self;
2580 setup[1] = &_cmd;
2581
2582 sig::Signature signature;
2583 sig::Parse(pool, &signature, type, &Structor_);
2584
2585 ffi_cif cif;
2586 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2587
2588 void (*function)() = stret(cif.rtype) ? reinterpret_cast<void (*)()>(&objc_msgSend_stret) : reinterpret_cast<void (*)()>(&objc_msgSend);
2589 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, exception, &signature, &cif, function);
2590 }
2591
2592 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2593 CYPool pool;
2594
2595 bool uninitialized;
2596
2597 id self;
2598 SEL _cmd;
2599
2600 CYTry {
2601 if (count < 2)
2602 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"too few arguments to objc_msgSend" userInfo:nil];
2603
2604 if (JSValueIsObjectOfClass(context, arguments[0], Instance_)) {
2605 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2606 self = internal->GetValue();
2607 uninitialized = internal->IsUninitialized();
2608 if (uninitialized)
2609 internal->value_ = nil;
2610 } else {
2611 self = CYCastNSObject(pool, context, arguments[0]);
2612 uninitialized = false;
2613 }
2614
2615 if (self == nil)
2616 return CYJSNull(context);
2617
2618 _cmd = CYCastSEL(context, arguments[1]);
2619 } CYCatch
2620
2621 return CYSendMessage(pool, context, self, _cmd, count - 2, arguments + 2, uninitialized, exception);
2622 }
2623
2624 MSHook(void, CYDealloc, id self, SEL sel) {
2625 CYInternal *internal;
2626 object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal));
2627 if (internal != NULL)
2628 delete internal;
2629 _CYDealloc(self, sel);
2630 }
2631
2632 MSHook(void, objc_registerClassPair, Class _class) {
2633 Class super(class_getSuperclass(_class));
2634 if (super == NULL || class_getInstanceVariable(super, "cy$internal_") == NULL) {
2635 class_addIvar(_class, "cy$internal_", sizeof(CYInternal *), log2(sizeof(CYInternal *)), "^{CYInternal}");
2636 MSHookMessage(_class, @selector(dealloc), MSHake(CYDealloc));
2637 }
2638
2639 _objc_registerClassPair(_class);
2640 }
2641
2642 static JSValueRef objc_registerClassPair_(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2643 CYTry {
2644 if (count != 1)
2645 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to objc_registerClassPair" userInfo:nil];
2646 CYPool pool;
2647 Class _class(CYCastNSObject(pool, context, arguments[0]));
2648 $objc_registerClassPair(_class);
2649 return CYJSUndefined(context);
2650 } CYCatch
2651 }
2652
2653 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2654 JSValueRef setup[count + 2];
2655 setup[0] = _this;
2656 setup[1] = object;
2657 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
2658 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
2659 }
2660
2661 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2662 CYPool pool;
2663 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
2664
2665 // XXX: handle Instance::Uninitialized?
2666 id self(CYCastNSObject(pool, context, _this));
2667
2668 void *setup[2];
2669 setup[0] = &self;
2670 setup[1] = &internal->sel_;
2671
2672 return CYCallFunction(pool, context, 2, setup, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
2673 }
2674
2675 static JSValueRef Functor_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2676 CYPool pool;
2677 Functor_privateData *internal(reinterpret_cast<Functor_privateData *>(JSObjectGetPrivate(object)));
2678 return CYCallFunction(pool, context, 0, NULL, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
2679 }
2680
2681 JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2682 CYTry {
2683 if (count != 1)
2684 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector constructor" userInfo:nil];
2685 const char *name(CYCastCString(context, arguments[0]));
2686 return CYMakeSelector(context, sel_registerName(name));
2687 } CYCatch
2688 }
2689
2690 JSObjectRef Pointer_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2691 CYTry {
2692 if (count != 2)
2693 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Functor constructor" userInfo:nil];
2694
2695 void *value(CYCastPointer<void *>(context, arguments[0]));
2696 const char *type(CYCastCString(context, arguments[1]));
2697
2698 CYPool pool;
2699
2700 sig::Signature signature;
2701 sig::Parse(pool, &signature, type, &Structor_);
2702
2703 return CYMakePointer(context, value, signature.elements[0].type, NULL, NULL);
2704 } CYCatch
2705 }
2706
2707 JSObjectRef CYMakeType(JSContextRef context, JSObjectRef object, const char *type) {
2708 Type_privateData *internal(new Type_privateData(NULL, type));
2709 return JSObjectMake(context, Type_, internal);
2710 }
2711
2712 JSObjectRef Type_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2713 CYTry {
2714 if (count != 1)
2715 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Type constructor" userInfo:nil];
2716 const char *type(CYCastCString(context, arguments[0]));
2717 return CYMakeType(context, object, type);
2718 } CYCatch
2719 }
2720
2721 static JSValueRef Type_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2722 CYTry {
2723 if (count != 1)
2724 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to type cast function" userInfo:nil];
2725 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
2726 sig::Type *type(internal->type_);
2727 ffi_type *ffi(internal->GetFFI());
2728 // XXX: alignment?
2729 uint8_t value[ffi->size];
2730 CYPool pool;
2731 CYPoolFFI(pool, context, type, ffi, value, arguments[0]);
2732 return CYFromFFI(context, type, ffi, value);
2733 } CYCatch
2734 }
2735
2736 static JSObjectRef Type_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2737 CYTry {
2738 if (count > 1)
2739 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to type cast function" userInfo:nil];
2740 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
2741 size_t size(count == 0 ? 0 : CYCastDouble(context, arguments[0]));
2742 // XXX: alignment?
2743 void *value(malloc(internal->GetFFI()->size * size));
2744 return CYMakePointer(context, value, internal->type_, internal->ffi_, NULL);
2745 } CYCatch
2746 }
2747
2748 JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2749 CYTry {
2750 if (count > 1)
2751 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Instance constructor" userInfo:nil];
2752 id self(count == 0 ? nil : CYCastPointer<id>(context, arguments[0]));
2753 return Instance::Make(context, self);
2754 } CYCatch
2755 }
2756
2757 JSObjectRef Functor_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2758 CYTry {
2759 if (count != 2)
2760 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Functor constructor" userInfo:nil];
2761 const char *type(CYCastCString(context, arguments[1]));
2762 return CYMakeFunctor(context, arguments[0], type);
2763 } CYCatch
2764 }
2765
2766 JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2767 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
2768 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2769 }
2770
2771 static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2772 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2773 Type_privateData *typical(internal->GetType());
2774
2775 sig::Type *type;
2776 ffi_type *ffi;
2777
2778 if (typical == NULL) {
2779 type = NULL;
2780 ffi = NULL;
2781 } else {
2782 type = typical->type_;
2783 ffi = typical->ffi_;
2784 }
2785
2786 return CYMakePointer(context, &internal->value_, type, ffi, object);
2787 }
2788
2789 static JSValueRef CYValue_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2790 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2791
2792 CYTry {
2793 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2794 } CYCatch
2795 }
2796
2797 static JSValueRef CYValue_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2798 return CYValue_callAsFunction_valueOf(context, object, _this, count, arguments, exception);
2799 }
2800
2801 static JSValueRef CYValue_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2802 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2803 char string[32];
2804 sprintf(string, "%p", internal->value_);
2805
2806 CYTry {
2807 return CYCastJSValue(context, string);
2808 } CYCatch
2809 }
2810
2811 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2812 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2813 return Instance::Make(context, object_getClass(internal->GetValue()));
2814 }
2815
2816 static JSValueRef Instance_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2817 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2818 id self(internal->GetValue());
2819 // XXX: this is a lame object_isClass
2820 if (class_getInstanceMethod(object_getClass(self), @selector(alloc)) == NULL)
2821 return CYJSUndefined(context);
2822 return Prototype::Make(context, self);
2823 }
2824
2825 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2826 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2827
2828 CYTry {
2829 CYPoolTry {
2830 return CYCastJSValue(context, CYJSString(CYPoolNSCYON(NULL, internal->GetValue())));
2831 } CYPoolCatch(NULL)
2832 } CYCatch
2833 }
2834
2835 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2836 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2837
2838 CYTry {
2839 CYPoolTry {
2840 NSString *key(count == 0 ? nil : CYCastNSString(NULL, CYJSString(context, arguments[0])));
2841 return CYCastJSValue(context, CYJSString([internal->GetValue() cy$toJSON:key]));
2842 } CYPoolCatch(NULL)
2843 } CYCatch
2844 }
2845
2846 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2847 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2848
2849 CYTry {
2850 CYPoolTry {
2851 return CYCastJSValue(context, CYJSString([internal->GetValue() description]));
2852 } CYPoolCatch(NULL)
2853 } CYCatch
2854 }
2855
2856 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2857 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2858
2859 CYTry {
2860 return CYCastJSValue(context, sel_getName(internal->GetValue()));
2861 } CYCatch
2862 }
2863
2864 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2865 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
2866 }
2867
2868 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2869 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2870 const char *name(sel_getName(internal->GetValue()));
2871
2872 CYTry {
2873 CYPoolTry {
2874 return CYCastJSValue(context, CYJSString([NSString stringWithFormat:@"@selector(%s)", name]));
2875 } CYPoolCatch(NULL)
2876 } CYCatch
2877 }
2878
2879 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2880 CYTry {
2881 if (count != 1)
2882 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector.type" userInfo:nil];
2883 CYPool pool;
2884 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2885 Class _class(CYCastNSObject(pool, context, arguments[0]));
2886 SEL sel(internal->GetValue());
2887 Method method(class_getInstanceMethod(_class, sel));
2888 const char *type(CYPoolTypeEncoding(pool, _class, sel, method));
2889 return type == NULL ? CYJSNull(context) : CYCastJSValue(context, CYJSString(type));
2890 } CYCatch
2891 }
2892
2893 static JSValueRef Type_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2894 CYTry {
2895 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
2896 CYPool pool;
2897 const char *type(sig::Unparse(pool, internal->type_));
2898 CYPoolTry {
2899 return CYCastJSValue(context, CYJSString(type));
2900 } CYPoolCatch(NULL)
2901 } CYCatch
2902 }
2903
2904 static JSValueRef Type_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2905 CYTry {
2906 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
2907 CYPool pool;
2908 const char *type(sig::Unparse(pool, internal->type_));
2909 CYPoolTry {
2910 return CYCastJSValue(context, CYJSString([NSString stringWithFormat:@"new Type(%@)", [[NSString stringWithUTF8String:type] cy$toCYON]]));
2911 } CYPoolCatch(NULL)
2912 } CYCatch
2913 }
2914
2915 static JSValueRef Type_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2916 return Type_callAsFunction_toString(context, object, _this, count, arguments, exception);
2917 }
2918
2919 static JSStaticValue CYValue_staticValues[2] = {
2920 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
2921 {NULL, NULL, NULL, 0}
2922 };
2923
2924 static JSStaticValue Pointer_staticValues[2] = {
2925 {"$cyi", &Pointer_getProperty_$cyi, &Pointer_setProperty_$cyi, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2926 {NULL, NULL, NULL, 0}
2927 };
2928
2929 static JSStaticFunction Pointer_staticFunctions[4] = {
2930 {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2931 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2932 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2933 {NULL, NULL, 0}
2934 };
2935
2936 static JSStaticFunction Struct_staticFunctions[2] = {
2937 {"$cya", &Struct_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2938 {NULL, NULL, 0}
2939 };
2940
2941 static JSStaticFunction Functor_staticFunctions[4] = {
2942 {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2943 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2944 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2945 {NULL, NULL, 0}
2946 };
2947
2948 static JSStaticValue Instance_staticValues[4] = {
2949 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2950 {"prototype", &Instance_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2951 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2952 {NULL, NULL, NULL, 0}
2953 };
2954
2955 static JSStaticFunction Instance_staticFunctions[5] = {
2956 {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2957 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2958 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2959 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2960 {NULL, NULL, 0}
2961 };
2962
2963 static JSStaticFunction Internal_staticFunctions[2] = {
2964 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2965 {NULL, NULL, 0}
2966 };
2967
2968 static JSStaticFunction Selector_staticFunctions[5] = {
2969 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2970 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2971 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2972 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2973 {NULL, NULL, 0}
2974 };
2975
2976 static JSStaticFunction Type_staticFunctions[4] = {
2977 {"toCYON", &Type_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2978 {"toJSON", &Type_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2979 {"toString", &Type_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2980 {NULL, NULL, 0}
2981 };
2982
2983 CYDriver::CYDriver(const std::string &filename) :
2984 state_(CYClear),
2985 data_(NULL),
2986 size_(0),
2987 file_(NULL),
2988 filename_(filename),
2989 source_(NULL)
2990 {
2991 ScannerInit();
2992 }
2993
2994 CYDriver::~CYDriver() {
2995 ScannerDestroy();
2996 }
2997
2998 void cy::parser::error(const cy::parser::location_type &location, const std::string &message) {
2999 CYDriver::Error error;
3000 error.location_ = location;
3001 error.message_ = message;
3002 driver.errors_.push_back(error);
3003 }
3004
3005 void CYSetArgs(int argc, const char *argv[]) {
3006 JSContextRef context(CYGetJSContext());
3007 JSValueRef args[argc];
3008 for (int i(0); i != argc; ++i)
3009 args[i] = CYCastJSValue(context, argv[i]);
3010 JSValueRef exception(NULL);
3011 JSObjectRef array(JSObjectMakeArray(context, argc, args, &exception));
3012 CYThrow(context, exception);
3013 CYSetProperty(context, System_, CYJSString("args"), array);
3014 }
3015
3016 JSObjectRef CYGetGlobalObject(JSContextRef context) {
3017 return JSContextGetGlobalObject(context);
3018 }
3019
3020 const char *CYExecute(apr_pool_t *pool, const char *code) { _pooled
3021 JSContextRef context(CYGetJSContext());
3022 JSValueRef exception(NULL), result;
3023
3024 try {
3025 result = JSEvaluateScript(context, CYJSString(code), NULL, NULL, 0, &exception);
3026 } catch (const char *error) {
3027 return error;
3028 }
3029
3030 if (exception != NULL) { error:
3031 result = exception;
3032 exception = NULL;
3033 }
3034
3035 if (JSValueIsUndefined(context, result))
3036 return NULL;
3037
3038 const char *json(CYPoolCCYON(pool, context, result, &exception));
3039 if (exception != NULL)
3040 goto error;
3041
3042 CYSetProperty(context, CYGetGlobalObject(context), Result_, result);
3043 return json;
3044 }
3045
3046 bool CYRecvAll_(int socket, uint8_t *data, size_t size) {
3047 while (size != 0) if (size_t writ = _syscall(recv(socket, data, size, 0))) {
3048 data += writ;
3049 size -= writ;
3050 } else
3051 return false;
3052 return true;
3053 }
3054
3055 bool CYSendAll_(int socket, const uint8_t *data, size_t size) {
3056 while (size != 0) if (size_t writ = _syscall(send(socket, data, size, 0))) {
3057 data += writ;
3058 size -= writ;
3059 } else
3060 return false;
3061 return true;
3062 }
3063
3064 apr_pool_t *Pool_;
3065
3066 struct CYExecute_ {
3067 apr_pool_t *pool_;
3068 const char * volatile data_;
3069 };
3070
3071 // XXX: this is "tre lame"
3072 @interface CYClient_ : NSObject {
3073 }
3074
3075 - (void) execute:(NSValue *)value;
3076
3077 @end
3078
3079 @implementation CYClient_
3080
3081 - (void) execute:(NSValue *)value {
3082 CYExecute_ *execute(reinterpret_cast<CYExecute_ *>([value pointerValue]));
3083 const char *data(execute->data_);
3084 execute->data_ = NULL;
3085 execute->data_ = CYExecute(execute->pool_, data);
3086 }
3087
3088 @end
3089
3090 struct CYClient :
3091 CYData
3092 {
3093 int socket_;
3094 apr_thread_t *thread_;
3095
3096 CYClient(int socket) :
3097 socket_(socket)
3098 {
3099 }
3100
3101 ~CYClient() {
3102 _syscall(close(socket_));
3103 }
3104
3105 void Handle() { _pooled
3106 CYClient_ *client = [[[CYClient_ alloc] init] autorelease];
3107
3108 for (;;) {
3109 size_t size;
3110 if (!CYRecvAll(socket_, &size, sizeof(size)))
3111 return;
3112
3113 CYPool pool;
3114 char *data(new(pool) char[size + 1]);
3115 if (!CYRecvAll(socket_, data, size))
3116 return;
3117 data[size] = '\0';
3118
3119 CYDriver driver("");
3120 cy::parser parser(driver);
3121
3122 driver.data_ = data;
3123 driver.size_ = size;
3124
3125 const char *json;
3126 if (parser.parse() != 0 || !driver.errors_.empty()) {
3127 json = NULL;
3128 size = _not(size_t);
3129 } else {
3130 std::ostringstream str;
3131 driver.source_->Show(str);
3132 std::string code(str.str());
3133 CYExecute_ execute = {pool, code.c_str()};
3134 [client performSelectorOnMainThread:@selector(execute:) withObject:[NSValue valueWithPointer:&execute] waitUntilDone:YES];
3135 json = execute.data_;
3136 size = json == NULL ? _not(size_t) : strlen(json);
3137 }
3138
3139 if (!CYSendAll(socket_, &size, sizeof(size)))
3140 return;
3141 if (json != NULL)
3142 if (!CYSendAll(socket_, json, size))
3143 return;
3144 }
3145 }
3146 };
3147
3148 static void * APR_THREAD_FUNC OnClient(apr_thread_t *thread, void *data) {
3149 CYClient *client(reinterpret_cast<CYClient *>(data));
3150 client->Handle();
3151 delete client;
3152 return NULL;
3153 }
3154
3155 extern "C" void CYHandleClient(apr_pool_t *pool, int socket) {
3156 CYClient *client(new(pool) CYClient(socket));
3157 apr_threadattr_t *attr;
3158 _aprcall(apr_threadattr_create(&attr, client->pool_));
3159 _aprcall(apr_thread_create(&client->thread_, attr, &OnClient, client, client->pool_));
3160 }
3161
3162 MSInitialize { _pooled
3163 _aprcall(apr_initialize());
3164 _aprcall(apr_pool_create(&Pool_, NULL));
3165
3166 Type_privateData::Object = new(Pool_) Type_privateData(Pool_, "@");
3167 Type_privateData::Selector = new(Pool_) Type_privateData(Pool_, ":");
3168
3169 Bridge_ = [[NSMutableArray arrayWithContentsOfFile:@"/usr/lib/libcycript.plist"] retain];
3170
3171 NSCFBoolean_ = objc_getClass("NSCFBoolean");
3172 NSCFType_ = objc_getClass("NSCFType");
3173 NSMessageBuilder_ = objc_getClass("NSMessageBuilder");
3174 NSZombie_ = objc_getClass("_NSZombie_");
3175 Object_ = objc_getClass("Object");
3176 }
3177
3178 JSGlobalContextRef CYGetJSContext() {
3179 if (Context_ == NULL) {
3180 JSClassDefinition definition;
3181
3182 definition = kJSClassDefinitionEmpty;
3183 definition.className = "Functor";
3184 definition.staticFunctions = Functor_staticFunctions;
3185 definition.callAsFunction = &Functor_callAsFunction;
3186 definition.finalize = &Finalize;
3187 Functor_ = JSClassCreate(&definition);
3188
3189 definition = kJSClassDefinitionEmpty;
3190 definition.className = "Instance";
3191 definition.staticValues = Instance_staticValues;
3192 definition.staticFunctions = Instance_staticFunctions;
3193 definition.hasProperty = &Instance_hasProperty;
3194 definition.getProperty = &Instance_getProperty;
3195 definition.setProperty = &Instance_setProperty;
3196 definition.deleteProperty = &Instance_deleteProperty;
3197 definition.getPropertyNames = &Instance_getPropertyNames;
3198 definition.callAsConstructor = &Instance_callAsConstructor;
3199 definition.finalize = &Finalize;
3200 Instance_ = JSClassCreate(&definition);
3201
3202 definition = kJSClassDefinitionEmpty;
3203 definition.className = "Internal";
3204 definition.staticFunctions = Internal_staticFunctions;
3205 definition.hasProperty = &Internal_hasProperty;
3206 definition.getProperty = &Internal_getProperty;
3207 definition.setProperty = &Internal_setProperty;
3208 definition.getPropertyNames = &Internal_getPropertyNames;
3209 definition.finalize = &Finalize;
3210 Internal_ = JSClassCreate(&definition);
3211
3212 definition = kJSClassDefinitionEmpty;
3213 definition.className = "Message";
3214 definition.staticFunctions = Functor_staticFunctions;
3215 definition.callAsFunction = &Message_callAsFunction;
3216 definition.finalize = &Finalize;
3217 Message_ = JSClassCreate(&definition);
3218
3219 definition = kJSClassDefinitionEmpty;
3220 definition.className = "Pointer";
3221 definition.staticValues = Pointer_staticValues;
3222 definition.staticFunctions = Pointer_staticFunctions;
3223 definition.getProperty = &Pointer_getProperty;
3224 definition.setProperty = &Pointer_setProperty;
3225 definition.finalize = &Finalize;
3226 Pointer_ = JSClassCreate(&definition);
3227
3228 definition = kJSClassDefinitionEmpty;
3229 definition.className = "Prototype";
3230 definition.hasProperty = &Prototype_hasProperty;
3231 definition.getProperty = &Prototype_getProperty;
3232 definition.setProperty = &Prototype_setProperty;
3233 #if !__OBJC2__
3234 definition.deleteProperty = &Prototype_deleteProperty;
3235 #endif
3236 definition.getPropertyNames = &Prototype_getPropertyNames;
3237 definition.finalize = &Finalize;
3238 Prototype_ = JSClassCreate(&definition);
3239
3240 definition = kJSClassDefinitionEmpty;
3241 definition.className = "Selector";
3242 definition.staticValues = CYValue_staticValues;
3243 definition.staticFunctions = Selector_staticFunctions;
3244 definition.callAsFunction = &Selector_callAsFunction;
3245 definition.finalize = &Finalize;
3246 Selector_ = JSClassCreate(&definition);
3247
3248 definition = kJSClassDefinitionEmpty;
3249 definition.className = "Struct";
3250 definition.staticFunctions = Struct_staticFunctions;
3251 definition.getProperty = &Struct_getProperty;
3252 definition.setProperty = &Struct_setProperty;
3253 definition.getPropertyNames = &Struct_getPropertyNames;
3254 definition.finalize = &Finalize;
3255 Struct_ = JSClassCreate(&definition);
3256
3257 definition = kJSClassDefinitionEmpty;
3258 definition.className = "Type";
3259 definition.staticFunctions = Type_staticFunctions;
3260 //definition.getProperty = &Type_getProperty;
3261 definition.callAsFunction = &Type_callAsFunction;
3262 definition.callAsConstructor = &Type_callAsConstructor;
3263 definition.finalize = &Finalize;
3264 Type_ = JSClassCreate(&definition);
3265
3266 definition = kJSClassDefinitionEmpty;
3267 definition.className = "Runtime";
3268 definition.getProperty = &Runtime_getProperty;
3269 Runtime_ = JSClassCreate(&definition);
3270
3271 definition = kJSClassDefinitionEmpty;
3272 definition.className = "ObjectiveC::Classes";
3273 definition.getProperty = &ObjectiveC_Classes_getProperty;
3274 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
3275 ObjectiveC_Classes_ = JSClassCreate(&definition);
3276
3277 definition = kJSClassDefinitionEmpty;
3278 definition.className = "ObjectiveC::Images";
3279 definition.getProperty = &ObjectiveC_Images_getProperty;
3280 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
3281 ObjectiveC_Images_ = JSClassCreate(&definition);
3282
3283 definition = kJSClassDefinitionEmpty;
3284 definition.className = "ObjectiveC::Image::Classes";
3285 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
3286 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
3287 definition.finalize = &Finalize;
3288 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
3289
3290 definition = kJSClassDefinitionEmpty;
3291 definition.className = "ObjectiveC::Protocols";
3292 definition.getProperty = &ObjectiveC_Protocols_getProperty;
3293 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
3294 ObjectiveC_Protocols_ = JSClassCreate(&definition);
3295
3296 definition = kJSClassDefinitionEmpty;
3297 //definition.getProperty = &Global_getProperty;
3298 JSClassRef Global(JSClassCreate(&definition));
3299
3300 JSGlobalContextRef context(JSGlobalContextCreate(Global));
3301 Context_ = context;
3302
3303 JSObjectRef global(CYGetGlobalObject(context));
3304
3305 JSObjectSetPrototype(context, global, JSObjectMake(context, Runtime_, NULL));
3306 ObjectiveC_ = JSObjectMake(context, NULL, NULL);
3307 CYSetProperty(context, global, CYJSString("ObjectiveC"), ObjectiveC_);
3308
3309 CYSetProperty(context, ObjectiveC_, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Classes_, NULL));
3310 CYSetProperty(context, ObjectiveC_, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
3311 CYSetProperty(context, ObjectiveC_, CYJSString("protocols"), JSObjectMake(context, ObjectiveC_Protocols_, NULL));
3312
3313 Array_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Array")));
3314 Function_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Function")));
3315
3316 length_ = JSStringCreateWithUTF8CString("length");
3317 message_ = JSStringCreateWithUTF8CString("message");
3318 name_ = JSStringCreateWithUTF8CString("name");
3319 prototype_ = JSStringCreateWithUTF8CString("prototype");
3320 toCYON_ = JSStringCreateWithUTF8CString("toCYON");
3321 toJSON_ = JSStringCreateWithUTF8CString("toJSON");
3322
3323 JSObjectRef Functor(JSObjectMakeConstructor(context, Functor_, &Functor_new));
3324 JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL));
3325 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new));
3326
3327 JSValueRef function(CYGetProperty(context, Function_, prototype_));
3328 JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Message, prototype_), function);
3329 JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Functor, prototype_), function);
3330 JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Selector, prototype_), function);
3331
3332 CYSetProperty(context, global, CYJSString("Functor"), Functor);
3333 CYSetProperty(context, global, CYJSString("Instance"), JSObjectMakeConstructor(context, Instance_, &Instance_new));
3334 CYSetProperty(context, global, CYJSString("Pointer"), JSObjectMakeConstructor(context, Pointer_, &Pointer_new));
3335 CYSetProperty(context, global, CYJSString("Selector"), Selector);
3336 CYSetProperty(context, global, CYJSString("Type"), JSObjectMakeConstructor(context, Type_, &Type_new));
3337
3338 MSHookFunction(&objc_registerClassPair, MSHake(objc_registerClassPair));
3339
3340 class_addMethod(NSCFType_, @selector(cy$toJSON:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON), "@12@0:4@8");
3341
3342 CYSetProperty(context, global, CYJSString("objc_registerClassPair"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_registerClassPair"), &objc_registerClassPair_));
3343 CYSetProperty(context, global, CYJSString("objc_msgSend"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_msgSend"), &$objc_msgSend));
3344
3345 System_ = JSObjectMake(context, NULL, NULL);
3346 CYSetProperty(context, global, CYJSString("system"), System_);
3347 CYSetProperty(context, System_, CYJSString("args"), CYJSNull(context));
3348 //CYSetProperty(context, System_, CYJSString("global"), global);
3349
3350 CYSetProperty(context, System_, CYJSString("print"), JSObjectMakeFunctionWithCallback(context, CYJSString("print"), &System_print));
3351
3352 Result_ = JSStringCreateWithUTF8CString("_");
3353 }
3354
3355 return Context_;
3356 }