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