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