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