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