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