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