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