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