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