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