]> git.saurik.com Git - cycript.git/blame - Library.mm
Protect bash glob expansions while generating libcycript.plist (thanks to kennytm...
[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>
b09da87b 61#include <sys/mman.h>
c1582939 62
8d9b5eed
JF
63#include <iostream>
64#include <ext/stdio_filebuf.h>
a2d9403c
JF
65#include <set>
66#include <map>
8d9b5eed 67
bd17e6f3
JF
68#include <cmath>
69
e5332278 70#include "Parser.hpp"
63b4c5a8 71#include "Cycript.tab.hh"
e5332278 72
ea2d184c
JF
73#undef _assert
74#undef _trace
75
c1582939 76#define _assert(test) do { \
f5e9be24
JF
77 if (!(test)) \
78 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"_assert(%s):%s(%u):%s", #test, __FILE__, __LINE__, __FUNCTION__] userInfo:nil]; \
c1582939
JF
79} while (false)
80
81#define _trace() do { \
62ca2b82 82 CFLog(kCFLogLevelNotice, CFSTR("_trace():%u"), __LINE__); \
c1582939
JF
83} while (false)
84
4cf49641
JF
85#define CYPoolTry { \
86 id _saved(nil); \
87 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
88 @try
89#define CYPoolCatch(value) \
90 @catch (NSException *error) { \
91 _saved = [error retain]; \
92 @throw; \
93 return value; \
94 } @finally { \
95 [_pool release]; \
96 if (_saved != nil) \
97 [_saved autorelease]; \
98 } \
99}
100
478d4ed0 101static JSGlobalContextRef Context_;
b09da87b 102static JSObjectRef System_;
ea2d184c 103
88c977fa
JF
104static JSClassRef Functor_;
105static JSClassRef Instance_;
106static JSClassRef Pointer_;
953647c1 107static JSClassRef Runtime_;
88c977fa 108static JSClassRef Selector_;
953647c1 109static JSClassRef Struct_;
ea2d184c 110
c1582939 111static JSObjectRef Array_;
dea834b0 112static JSObjectRef Function_;
ea2d184c 113
c1582939 114static JSStringRef length_;
b4aa79af
JF
115static JSStringRef message_;
116static JSStringRef name_;
117static JSStringRef toCYON_;
118static JSStringRef toJSON_;
ea2d184c 119
c1582939
JF
120static Class NSCFBoolean_;
121
953647c1 122static NSArray *Bridge_;
88c977fa 123
953647c1 124struct CYData {
478d4ed0 125 apr_pool_t *pool_;
ff783f8c
JF
126 void *value_;
127
128 CYData() {
129 }
130
131 CYData(void *value) :
132 value_(value)
133 {
134 }
953647c1
JF
135
136 virtual ~CYData() {
137 }
478d4ed0
JF
138
139 void *operator new(size_t size) {
140 apr_pool_t *pool;
141 apr_pool_create(&pool, NULL);
142 void *data(apr_palloc(pool, size));
953647c1 143 reinterpret_cast<CYData *>(data)->pool_ = pool;
478d4ed0
JF
144 return data;;
145 }
146
953647c1
JF
147 static void Finalize(JSObjectRef object) {
148 CYData *data(reinterpret_cast<CYData *>(JSObjectGetPrivate(object)));
149 data->~CYData();
150 apr_pool_destroy(data->pool_);
478d4ed0 151 }
953647c1
JF
152};
153
ff783f8c 154struct Selector_privateData :
953647c1
JF
155 CYData
156{
953647c1 157 Selector_privateData(SEL value) :
ff783f8c 158 CYData(value)
478d4ed0
JF
159 {
160 }
161
162 SEL GetValue() const {
163 return reinterpret_cast<SEL>(value_);
164 }
165};
166
2b52f27e 167struct Instance :
ff783f8c 168 CYData
bd17e6f3 169{
2b52f27e
JF
170 enum Flags {
171 None = 0,
172 Transient = (1 << 0),
173 Uninitialized = (1 << 1),
174 };
478d4ed0 175
2b52f27e
JF
176 Flags flags_;
177
178 Instance(id value, Flags flags) :
ff783f8c 179 CYData(value),
2b52f27e 180 flags_(flags)
478d4ed0
JF
181 {
182 }
183
2b52f27e
JF
184 virtual ~Instance() {
185 if ((flags_ & Transient) == 0)
478d4ed0
JF
186 [GetValue() release];
187 }
188
2b52f27e
JF
189 static JSObjectRef Make(JSContextRef context, id object, Flags flags) {
190 return JSObjectMake(context, Instance_, new Instance(object, flags));
191 }
192
478d4ed0
JF
193 id GetValue() const {
194 return reinterpret_cast<id>(value_);
195 }
2b52f27e
JF
196
197 bool IsUninitialized() const {
198 return (flags_ & Uninitialized) != 0;
199 }
478d4ed0
JF
200};
201
bd17e6f3
JF
202namespace sig {
203
204void Copy(apr_pool_t *pool, Type &lhs, Type &rhs);
205
206void Copy(apr_pool_t *pool, Element &lhs, Element &rhs) {
207 lhs.name = apr_pstrdup(pool, rhs.name);
208 if (rhs.type == NULL)
209 lhs.type = NULL;
210 else {
211 lhs.type = new(pool) Type;
212 Copy(pool, *lhs.type, *rhs.type);
213 }
214 lhs.offset = rhs.offset;
215}
216
217void Copy(apr_pool_t *pool, Signature &lhs, Signature &rhs) {
218 size_t count(rhs.count);
219 lhs.count = count;
220 lhs.elements = new(pool) Element[count];
221 for (size_t index(0); index != count; ++index)
222 Copy(pool, lhs.elements[index], rhs.elements[index]);
223}
224
225void Copy(apr_pool_t *pool, Type &lhs, Type &rhs) {
226 lhs.primitive = rhs.primitive;
227 lhs.name = apr_pstrdup(pool, rhs.name);
228 lhs.flags = rhs.flags;
229
230 if (sig::IsAggregate(rhs.primitive))
231 Copy(pool, lhs.data.signature, rhs.data.signature);
232 else {
233 if (rhs.data.data.type != NULL) {
234 lhs.data.data.type = new(pool) Type;
235 Copy(pool, *lhs.data.data.type, *rhs.data.data.type);
236 }
237
238 lhs.data.data.size = rhs.data.data.size;
239 }
240}
241
242void Copy(apr_pool_t *pool, ffi_type &lhs, ffi_type &rhs) {
243 lhs.size = rhs.size;
244 lhs.alignment = rhs.alignment;
245 lhs.type = rhs.type;
246 if (rhs.elements == NULL)
247 lhs.elements = NULL;
248 else {
249 size_t count(0);
250 while (rhs.elements[count] != NULL)
251 ++count;
252
253 lhs.elements = new(pool) ffi_type *[count + 1];
254 lhs.elements[count] = NULL;
255
256 for (size_t index(0); index != count; ++index) {
257 // XXX: if these are libffi native then you can just take them
258 ffi_type *ffi(new(pool) ffi_type);
259 lhs.elements[index] = ffi;
260 sig::Copy(pool, *ffi, *rhs.elements[index]);
261 }
262 }
263}
264
265}
266
f33b048a
JF
267struct CStringMapLess :
268 std::binary_function<const char *, const char *, bool>
269{
270 _finline bool operator ()(const char *lhs, const char *rhs) const {
271 return strcmp(lhs, rhs) < 0;
272 }
273};
274
bd17e6f3 275struct Type_privateData {
ff783f8c
JF
276 apr_pool_t *pool_;
277
278 ffi_type *ffi_;
930aa21b 279 sig::Type *type_;
bd17e6f3 280
ff783f8c
JF
281 Type_privateData(apr_pool_t *pool, sig::Type *type) :
282 pool_(pool),
283 ffi_(NULL)
284 {
930aa21b
JF
285 if (type != NULL) {
286 type_ = new(pool) sig::Type;
287 sig::Copy(pool, *type_, *type);
288 }
ff783f8c
JF
289 }
290
291 Type_privateData(apr_pool_t *pool, sig::Type *type, ffi_type *ffi) :
292 pool_(pool)
293 {
294 ffi_ = new(pool) ffi_type;
295 sig::Copy(pool, *ffi_, *ffi);
930aa21b
JF
296 type_ = new(pool) sig::Type;
297 sig::Copy(pool, *type_, *type);
ff783f8c
JF
298 }
299
300 ffi_type *GetFFI() {
301 if (ffi_ == NULL) {
302 ffi_ = new(pool_) ffi_type;
303
304 sig::Element element;
305 element.name = NULL;
930aa21b 306 element.type = type_;
ff783f8c
JF
307 element.offset = 0;
308
309 sig::Signature signature;
310 signature.elements = &element;
311 signature.count = 1;
312
313 ffi_cif cif;
314 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature, &cif);
315 *ffi_ = *cif.rtype;
316 }
317
318 return ffi_;
319 }
320};
321
322struct Pointer :
323 CYData
324{
325 JSObjectRef owner_;
326 Type_privateData *type_;
327
328 Pointer(void *value, sig::Type *type, JSObjectRef owner) :
329 CYData(value),
330 owner_(owner),
331 type_(new(pool_) Type_privateData(pool_, type))
332 {
bd17e6f3
JF
333 }
334};
335
336struct Struct_privateData :
ff783f8c 337 CYData
bd17e6f3
JF
338{
339 JSObjectRef owner_;
340 Type_privateData *type_;
341
ff783f8c
JF
342 Struct_privateData(JSObjectRef owner) :
343 owner_(owner)
344 {
bd17e6f3
JF
345 }
346};
347
bd17e6f3
JF
348typedef std::map<const char *, Type_privateData *, CStringMapLess> TypeMap;
349static TypeMap Types_;
350
351JSObjectRef CYMakeStruct(JSContextRef context, void *data, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
ff783f8c 352 Struct_privateData *internal(new Struct_privateData(owner));
bd17e6f3
JF
353 apr_pool_t *pool(internal->pool_);
354 Type_privateData *typical(new(pool) Type_privateData(pool, type, ffi));
355 internal->type_ = typical;
356
ff783f8c 357 if (owner != NULL)
bd17e6f3 358 internal->value_ = data;
ff783f8c
JF
359 else {
360 size_t size(typical->GetFFI()->size);
bd17e6f3
JF
361 void *copy(apr_palloc(internal->pool_, size));
362 memcpy(copy, data, size);
363 internal->value_ = copy;
364 }
365
bd17e6f3
JF
366 return JSObjectMake(context, Struct_, internal);
367}
368
f7c38a29 369void Structor_(apr_pool_t *pool, const char *name, const char *types, sig::Type *&type) {
d63c39cc
JF
370 if (name == NULL)
371 return;
372
f33b048a
JF
373 CYPoolTry {
374 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:2] objectForKey:[NSString stringWithUTF8String:name]]) {
375 switch ([[entry objectAtIndex:0] intValue]) {
376 case 0:
377 static CYPool Pool_;
378 sig::Parse(Pool_, &type->data.signature, [[entry objectAtIndex:1] UTF8String], &Structor_);
379 break;
380 }
381 }
382 } CYPoolCatch()
383}
384
385struct Functor_privateData :
ff783f8c 386 CYData
f33b048a
JF
387{
388 sig::Signature signature_;
389 ffi_cif cif_;
390
391 Functor_privateData(const char *type, void (*value)()) :
ff783f8c 392 CYData(reinterpret_cast<void *>(value))
f33b048a
JF
393 {
394 sig::Parse(pool_, &signature_, type, &Structor_);
395 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature_, &cif_);
396 }
397};
398
399struct ffoData :
400 Functor_privateData
401{
402 JSContextRef context_;
403 JSObjectRef function_;
404
405 ffoData(const char *type) :
406 Functor_privateData(type, NULL)
407 {
408 }
409};
410
f7c38a29 411JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
2b52f27e
JF
412 Instance::Flags flags;
413
414 if (transient)
415 flags = Instance::Transient;
416 else {
417 flags = Instance::None;
478d4ed0 418 object = [object retain];
2b52f27e
JF
419 }
420
421 return Instance::Make(context, object, flags);
478d4ed0
JF
422}
423
424const char *CYPoolCString(apr_pool_t *pool, NSString *value) {
425 if (pool == NULL)
426 return [value UTF8String];
427 else {
428 size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
429 char *string(new(pool) char[size]);
430 if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
4afefdd9 431 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:@"[NSString getCString:maxLength:encoding:] == NO" userInfo:nil];
478d4ed0
JF
432 return string;
433 }
b09da87b
JF
434}
435
436JSValueRef CYCastJSValue(JSContextRef context, bool value) {
437 return JSValueMakeBoolean(context, value);
438}
439
440JSValueRef CYCastJSValue(JSContextRef context, double value) {
441 return JSValueMakeNumber(context, value);
442}
443
444#define CYCastJSValue_(Type_) \
445 JSValueRef CYCastJSValue(JSContextRef context, Type_ value) { \
446 return JSValueMakeNumber(context, static_cast<double>(value)); \
447 }
448
449CYCastJSValue_(int)
450CYCastJSValue_(unsigned int)
451CYCastJSValue_(long int)
452CYCastJSValue_(long unsigned int)
453CYCastJSValue_(long long int)
454CYCastJSValue_(long long unsigned int)
455
456JSValueRef CYJSUndefined(JSContextRef context) {
457 return JSValueMakeUndefined(context);
0c862573
JF
458}
459
ff783f8c
JF
460bool CYGetIndex(const char *value, ssize_t &index) {
461 if (value[0] != '0') {
283e7e33 462 char *end;
ff783f8c 463 index = strtol(value, &end, 10);
283e7e33 464 if (value + strlen(value) == end)
ff783f8c
JF
465 return true;
466 } else if (value[1] == '\0') {
467 index = 0;
468 return true;
283e7e33
JF
469 }
470
ff783f8c 471 return false;
283e7e33
JF
472}
473
ff783f8c
JF
474bool CYGetIndex(apr_pool_t *pool, NSString *value, ssize_t &index) {
475 return CYGetIndex(CYPoolCString(pool, value), index);
283e7e33
JF
476}
477
107e3ed0 478@interface NSMethodSignature (Cycript)
7ba62cfd
JF
479- (NSString *) _typeString;
480@end
481
107e3ed0 482@interface NSObject (Cycript)
b4aa79af
JF
483
484- (JSType) cy$JSType;
485
486- (NSObject *) cy$toJSON:(NSString *)key;
487- (NSString *) cy$toCYON;
f33b048a 488- (NSString *) cy$toKey;
b4aa79af 489
cc103044
JF
490- (NSObject *) cy$getProperty:(NSString *)name;
491- (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
492- (bool) cy$deleteProperty:(NSString *)name;
b4aa79af 493
c1582939
JF
494@end
495
f7c38a29
JF
496@protocol Cycript
497- (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
498@end
499
107e3ed0 500@interface NSString (Cycript)
88c977fa
JF
501- (void *) cy$symbol;
502@end
503
107e3ed0 504@interface NSNumber (Cycript)
88c977fa
JF
505- (void *) cy$symbol;
506@end
507
4afefdd9
JF
508struct PropertyAttributes {
509 CYPool pool_;
510
511 const char *name;
512
513 const char *variable;
514
515 const char *getter_;
516 const char *setter_;
517
518 bool readonly;
519 bool copy;
520 bool retain;
521 bool nonatomic;
522 bool dynamic;
523 bool weak;
524 bool garbage;
525
526 PropertyAttributes(objc_property_t property) :
527 variable(NULL),
528 getter_(NULL),
529 setter_(NULL),
530 readonly(false),
531 copy(false),
532 retain(false),
533 nonatomic(false),
534 dynamic(false),
535 weak(false),
536 garbage(false)
537 {
538 name = property_getName(property);
539 const char *attributes(property_getAttributes(property));
540
541 for (char *state, *token(apr_strtok(apr_pstrdup(pool_, attributes), ",", &state)); token != NULL; token = apr_strtok(NULL, ",", &state)) {
542 switch (*token) {
543 case 'R': readonly = true; break;
544 case 'C': copy = true; break;
545 case '&': retain = true; break;
546 case 'N': nonatomic = true; break;
547 case 'G': getter_ = token + 1; break;
548 case 'S': setter_ = token + 1; break;
549 case 'V': variable = token + 1; break;
550 }
551 }
552
553 /*if (variable == NULL) {
554 variable = property_getName(property);
555 size_t size(strlen(variable));
556 char *name(new(pool_) char[size + 2]);
557 name[0] = '_';
558 memcpy(name + 1, variable, size);
559 name[size + 1] = '\0';
560 variable = name;
561 }*/
562 }
563
564 const char *Getter() {
565 if (getter_ == NULL)
566 getter_ = apr_pstrdup(pool_, name);
567 return getter_;
568 }
569
570 const char *Setter() {
571 if (setter_ == NULL && !readonly) {
572 size_t length(strlen(name));
573
574 char *temp(new(pool_) char[length + 5]);
575 temp[0] = 's';
576 temp[1] = 'e';
577 temp[2] = 't';
578
579 if (length != 0) {
580 temp[3] = toupper(name[0]);
581 memcpy(temp + 4, name + 1, length - 1);
582 }
583
584 temp[length + 3] = ':';
585 temp[length + 4] = '\0';
586 setter_ = temp;
587 }
588
589 return setter_;
590 }
591
592};
593
107e3ed0 594@implementation NSObject (Cycript)
62ca2b82 595
b4aa79af
JF
596- (JSType) cy$JSType {
597 return kJSTypeObject;
6b8a9500
JF
598}
599
b4aa79af 600- (NSObject *) cy$toJSON:(NSString *)key {
62ca2b82
JF
601 return [self description];
602}
603
b4aa79af
JF
604- (NSString *) cy$toCYON {
605 return [[self cy$toJSON:@""] cy$toCYON];
606}
607
f33b048a
JF
608- (NSString *) cy$toKey {
609 return [self cy$toCYON];
610}
611
cc103044 612- (NSObject *) cy$getProperty:(NSString *)name {
4afefdd9
JF
613 /*if (![name isEqualToString:@"prototype"])
614 NSLog(@"get:%@", name);*/
cc103044
JF
615 return nil;
616}
617
618- (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
4afefdd9 619 //NSLog(@"set:%@", name);
cc103044
JF
620 return false;
621}
622
623- (bool) cy$deleteProperty:(NSString *)name {
4afefdd9 624 //NSLog(@"delete:%@", name);
cc103044
JF
625 return false;
626}
627
62ca2b82 628@end
c1582939 629
107e3ed0 630@implementation WebUndefined (Cycript)
62ca2b82 631
b4aa79af
JF
632- (JSType) cy$JSType {
633 return kJSTypeUndefined;
634}
635
636- (NSObject *) cy$toJSON:(NSString *)key {
637 return self;
6b8a9500
JF
638}
639
b4aa79af 640- (NSString *) cy$toCYON {
c1582939 641 return @"undefined";
62ca2b82
JF
642}
643
2b52f27e 644- (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
b09da87b 645 return CYJSUndefined(context);
62ca2b82
JF
646}
647
648@end
c1582939 649
478d4ed0
JF
650@implementation NSNull (Cycript)
651
b4aa79af
JF
652- (JSType) cy$JSType {
653 return kJSTypeNull;
654}
655
656- (NSObject *) cy$toJSON:(NSString *)key {
657 return self;
658}
659
660- (NSString *) cy$toCYON {
478d4ed0
JF
661 return @"null";
662}
663
664@end
665
107e3ed0 666@implementation NSArray (Cycript)
62ca2b82 667
b4aa79af 668- (NSString *) cy$toCYON {
c1582939
JF
669 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
670 [json appendString:@"["];
671
672 bool comma(false);
62ca2b82 673 for (id object in self) {
c1582939
JF
674 if (comma)
675 [json appendString:@","];
676 else
677 comma = true;
b4aa79af
JF
678 if ([object cy$JSType] != kJSTypeUndefined)
679 [json appendString:[object cy$toCYON]];
6b8a9500
JF
680 else {
681 [json appendString:@","];
682 comma = false;
683 }
c1582939
JF
684 }
685
686 [json appendString:@"]"];
687 return json;
62ca2b82
JF
688}
689
cc103044 690- (NSObject *) cy$getProperty:(NSString *)name {
4afefdd9
JF
691 if ([name isEqualToString:@"length"])
692 return [NSNumber numberWithUnsignedInteger:[self count]];
693
ff783f8c
JF
694 ssize_t index;
695 if (!CYGetIndex(NULL, name, index) || index < 0 || index >= static_cast<ssize_t>([self count]))
cc103044
JF
696 return [super cy$getProperty:name];
697 else
698 return [self objectAtIndex:index];
699}
700
701@end
702
703@implementation NSMutableArray (Cycript)
704
705- (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
ff783f8c
JF
706 ssize_t index;
707 if (!CYGetIndex(NULL, name, index) || index < 0 || index >= static_cast<ssize_t>([self count]))
cc103044
JF
708 return [super cy$setProperty:name to:value];
709 else {
b6ea08b6 710 [self replaceObjectAtIndex:index withObject:(value ?: [NSNull null])];
cc103044
JF
711 return true;
712 }
713}
714
715- (bool) cy$deleteProperty:(NSString *)name {
ff783f8c
JF
716 ssize_t index;
717 if (!CYGetIndex(NULL, name, index) || index < 0 || index >= static_cast<ssize_t>([self count]))
cc103044
JF
718 return [super cy$deleteProperty:name];
719 else {
720 [self removeObjectAtIndex:index];
721 return true;
722 }
723}
724
62ca2b82
JF
725@end
726
107e3ed0 727@implementation NSDictionary (Cycript)
62ca2b82 728
b4aa79af 729- (NSString *) cy$toCYON {
62ca2b82 730 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
f33b048a 731 [json appendString:@"{"];
62ca2b82
JF
732
733 bool comma(false);
734 for (id key in self) {
735 if (comma)
736 [json appendString:@","];
737 else
738 comma = true;
f33b048a 739 [json appendString:[key cy$toKey]];
62ca2b82
JF
740 [json appendString:@":"];
741 NSObject *object([self objectForKey:key]);
b4aa79af 742 [json appendString:[object cy$toCYON]];
62ca2b82
JF
743 }
744
f33b048a 745 [json appendString:@"}"];
62ca2b82
JF
746 return json;
747}
748
cc103044
JF
749- (NSObject *) cy$getProperty:(NSString *)name {
750 return [self objectForKey:name];
751}
752
753@end
754
755@implementation NSMutableDictionary (Cycript)
756
757- (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
b6ea08b6 758 [self setObject:(value ?: [NSNull null]) forKey:name];
cc103044
JF
759 return true;
760}
761
762- (bool) cy$deleteProperty:(NSString *)name {
763 if ([self objectForKey:name] == nil)
764 return false;
765 else {
766 [self removeObjectForKey:name];
767 return true;
768 }
769}
770
62ca2b82 771@end
c1582939 772
107e3ed0 773@implementation NSNumber (Cycript)
62ca2b82 774
b4aa79af
JF
775- (JSType) cy$JSType {
776 // XXX: this just seems stupid
777 return [self class] == NSCFBoolean_ ? kJSTypeBoolean : kJSTypeNumber;
778}
779
780- (NSObject *) cy$toJSON:(NSString *)key {
781 return self;
782}
783
784- (NSString *) cy$toCYON {
785 return [self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false";
62ca2b82
JF
786}
787
2b52f27e 788- (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
b4aa79af 789 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, [self boolValue]);
62ca2b82
JF
790}
791
88c977fa
JF
792- (void *) cy$symbol {
793 return [self pointerValue];
794}
795
62ca2b82 796@end
c1582939 797
107e3ed0 798@implementation NSString (Cycript)
62ca2b82 799
b4aa79af
JF
800- (JSType) cy$JSType {
801 return kJSTypeString;
802}
803
804- (NSObject *) cy$toJSON:(NSString *)key {
805 return self;
806}
807
808- (NSString *) cy$toCYON {
f33b048a 809 // XXX: this should use the better code from Output.cpp
c1582939
JF
810 CFMutableStringRef json(CFStringCreateMutableCopy(kCFAllocatorDefault, 0, (CFStringRef) self));
811
c1582939
JF
812 CFStringFindAndReplace(json, CFSTR("\\"), CFSTR("\\\\"), CFRangeMake(0, CFStringGetLength(json)), 0);
813 CFStringFindAndReplace(json, CFSTR("\""), CFSTR("\\\""), CFRangeMake(0, CFStringGetLength(json)), 0);
814 CFStringFindAndReplace(json, CFSTR("\t"), CFSTR("\\t"), CFRangeMake(0, CFStringGetLength(json)), 0);
815 CFStringFindAndReplace(json, CFSTR("\r"), CFSTR("\\r"), CFRangeMake(0, CFStringGetLength(json)), 0);
816 CFStringFindAndReplace(json, CFSTR("\n"), CFSTR("\\n"), CFRangeMake(0, CFStringGetLength(json)), 0);
817
818 CFStringInsert(json, 0, CFSTR("\""));
819 CFStringAppend(json, CFSTR("\""));
820
62ca2b82
JF
821 return [reinterpret_cast<const NSString *>(json) autorelease];
822}
823
f33b048a
JF
824- (NSString *) cy$toKey {
825 const char *value([self UTF8String]);
826 size_t size(strlen(value));
827
283e7e33 828 if (size == 0)
f33b048a 829 goto cyon;
283e7e33
JF
830
831 if (DigitRange_[value[0]]) {
ff783f8c
JF
832 ssize_t index;
833 if (!CYGetIndex(NULL, self, index) || index < 0)
f33b048a 834 goto cyon;
283e7e33
JF
835 } else {
836 if (!WordStartRange_[value[0]])
837 goto cyon;
838 for (size_t i(1); i != size; ++i)
839 if (!WordEndRange_[value[i]])
840 goto cyon;
841 }
842
f33b048a
JF
843 return self;
844
845 cyon:
846 return [self cy$toCYON];
847}
848
88c977fa 849- (void *) cy$symbol {
478d4ed0
JF
850 CYPool pool;
851 return dlsym(RTLD_DEFAULT, CYPoolCString(pool, self));
88c977fa
JF
852}
853
62ca2b82
JF
854@end
855
b21525c7 856@interface CYJSObject : NSDictionary {
62ca2b82
JF
857 JSObjectRef object_;
858 JSContextRef context_;
859}
860
861- (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
862
b4aa79af
JF
863- (NSString *) cy$toJSON:(NSString *)key;
864
62ca2b82
JF
865- (NSUInteger) count;
866- (id) objectForKey:(id)key;
867- (NSEnumerator *) keyEnumerator;
868- (void) setObject:(id)object forKey:(id)key;
869- (void) removeObjectForKey:(id)key;
870
871@end
c1582939 872
b21525c7 873@interface CYJSArray : NSArray {
c1582939
JF
874 JSObjectRef object_;
875 JSContextRef context_;
876}
877
878- (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
879
880- (NSUInteger) count;
881- (id) objectAtIndex:(NSUInteger)index;
882
883@end
884
283e7e33
JF
885CYRange DigitRange_ (0x3ff000000000000LLU, 0x000000000000000LLU); // 0-9
886CYRange WordStartRange_(0x000001000000000LLU, 0x7fffffe87fffffeLLU); // A-Za-z_$
887CYRange WordEndRange_ (0x3ff001000000000LLU, 0x7fffffe87fffffeLLU); // A-Za-z_$0-9
dea834b0 888
478d4ed0 889JSGlobalContextRef CYGetJSContext() {
ea2d184c 890 return Context_;
62ca2b82
JF
891}
892
4cf49641
JF
893#define CYTry \
894 @try
0c862573
JF
895#define CYCatch \
896 @catch (id error) { \
897 CYThrow(context, error, exception); \
898 return NULL; \
899 }
900
ea2d184c
JF
901void CYThrow(JSContextRef context, JSValueRef value);
902
b09da87b
JF
903apr_status_t CYPoolRelease_(void *data) {
904 id object(reinterpret_cast<id>(data));
905 [object release];
906 return APR_SUCCESS;
907}
908
909id CYPoolRelease(apr_pool_t *pool, id object) {
b4aa79af
JF
910 if (object == nil)
911 return nil;
912 else if (pool == NULL)
b09da87b
JF
913 return [object autorelease];
914 else {
915 apr_pool_cleanup_register(pool, object, &CYPoolRelease_, &apr_pool_cleanup_null);
916 return object;
917 }
918}
919
953647c1
JF
920CFTypeRef CYPoolRelease(apr_pool_t *pool, CFTypeRef object) {
921 return (CFTypeRef) CYPoolRelease(pool, (id) object);
922}
923
2b52f27e 924id CYCastNSObject_(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
ea2d184c
JF
925 JSValueRef exception(NULL);
926 bool array(JSValueIsInstanceOfConstructor(context, object, Array_, &exception));
927 CYThrow(context, exception);
b09da87b
JF
928 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
929 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
62ca2b82
JF
930}
931
2b52f27e
JF
932id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
933 if (!JSValueIsObjectOfClass(context, object, Instance_))
934 return CYCastNSObject_(pool, context, object);
935 else {
936 Instance *data(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
937 return data->GetValue();
938 }
939}
940
77e87a6c 941JSStringRef CYCopyJSString(id value) {
b09da87b 942 return value == NULL ? NULL : JSStringCreateWithCFString(reinterpret_cast<CFStringRef>([value description]));
62ca2b82
JF
943}
944
77e87a6c 945JSStringRef CYCopyJSString(const char *value) {
b09da87b 946 return value == NULL ? NULL : JSStringCreateWithUTF8CString(value);
77e87a6c
JF
947}
948
949JSStringRef CYCopyJSString(JSStringRef value) {
b09da87b 950 return value == NULL ? NULL : JSStringRetain(value);
77e87a6c
JF
951}
952
953JSStringRef CYCopyJSString(JSContextRef context, JSValueRef value) {
b09da87b
JF
954 if (JSValueIsNull(context, value))
955 return NULL;
62ca2b82 956 JSValueRef exception(NULL);
ea2d184c
JF
957 JSStringRef string(JSValueToStringCopy(context, value, &exception));
958 CYThrow(context, exception);
77e87a6c
JF
959 return string;
960}
961
cf7d4c69 962class CYJSString {
77e87a6c
JF
963 private:
964 JSStringRef string_;
965
b09da87b 966 void Clear_() {
283e7e33
JF
967 if (string_ != NULL)
968 JSStringRelease(string_);
b09da87b
JF
969 }
970
77e87a6c 971 public:
b09da87b
JF
972 CYJSString(const CYJSString &rhs) :
973 string_(CYCopyJSString(rhs.string_))
974 {
975 }
976
77e87a6c 977 template <typename Arg0_>
b09da87b
JF
978 CYJSString(Arg0_ arg0) :
979 string_(CYCopyJSString(arg0))
980 {
77e87a6c
JF
981 }
982
983 template <typename Arg0_, typename Arg1_>
b09da87b
JF
984 CYJSString(Arg0_ arg0, Arg1_ arg1) :
985 string_(CYCopyJSString(arg0, arg1))
986 {
987 }
988
989 CYJSString &operator =(const CYJSString &rhs) {
990 Clear_();
991 string_ = CYCopyJSString(rhs.string_);
992 return *this;
77e87a6c
JF
993 }
994
cf7d4c69 995 ~CYJSString() {
b09da87b
JF
996 Clear_();
997 }
998
999 void Clear() {
1000 Clear_();
1001 string_ = NULL;
77e87a6c
JF
1002 }
1003
1004 operator JSStringRef() const {
1005 return string_;
1006 }
1007};
1008
1009CFStringRef CYCopyCFString(JSStringRef value) {
1010 return JSStringCopyCFString(kCFAllocatorDefault, value);
1011}
1012
1013CFStringRef CYCopyCFString(JSContextRef context, JSValueRef value) {
cf7d4c69 1014 return CYCopyCFString(CYJSString(context, value));
c1582939
JF
1015}
1016
bd17e6f3
JF
1017double CYCastDouble(const char *value, size_t size) {
1018 char *end;
1019 double number(strtod(value, &end));
1020 if (end != value + size)
1021 return NAN;
1022 return number;
1023}
1024
1025double CYCastDouble(const char *value) {
1026 return CYCastDouble(value, strlen(value));
1027}
1028
f610e1a0 1029double CYCastDouble(JSContextRef context, JSValueRef value) {
0c862573
JF
1030 JSValueRef exception(NULL);
1031 double number(JSValueToNumber(context, value, &exception));
1032 CYThrow(context, exception);
f610e1a0
JF
1033 return number;
1034}
1035
1036CFNumberRef CYCopyCFNumber(JSContextRef context, JSValueRef value) {
1037 double number(CYCastDouble(context, value));
0c862573
JF
1038 return CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &number);
1039}
1040
953647c1
JF
1041CFStringRef CYCopyCFString(const char *value) {
1042 return CFStringCreateWithCString(kCFAllocatorDefault, value, kCFStringEncodingUTF8);
1043}
1044
1045NSString *CYCastNSString(apr_pool_t *pool, const char *value) {
1046 return (NSString *) CYPoolRelease(pool, CYCopyCFString(value));
1047}
1048
b09da87b 1049NSString *CYCastNSString(apr_pool_t *pool, JSStringRef value) {
953647c1 1050 return (NSString *) CYPoolRelease(pool, CYCopyCFString(value));
b09da87b
JF
1051}
1052
1053bool CYCastBool(JSContextRef context, JSValueRef value) {
1054 return JSValueToBoolean(context, value);
62ca2b82
JF
1055}
1056
b09da87b
JF
1057CFTypeRef CYCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value, bool cast) {
1058 CFTypeRef object;
1059 bool copy;
1060
f610e1a0 1061 switch (JSType type = JSValueGetType(context, value)) {
c1582939 1062 case kJSTypeUndefined:
b09da87b
JF
1063 object = [WebUndefined undefined];
1064 copy = false;
1065 break;
1066
c1582939 1067 case kJSTypeNull:
b09da87b
JF
1068 return NULL;
1069 break;
1070
c1582939 1071 case kJSTypeBoolean:
b09da87b
JF
1072 object = CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse;
1073 copy = false;
1074 break;
1075
0c862573 1076 case kJSTypeNumber:
b09da87b
JF
1077 object = CYCopyCFNumber(context, value);
1078 copy = true;
1079 break;
1080
62ca2b82 1081 case kJSTypeString:
b09da87b
JF
1082 object = CYCopyCFString(context, value);
1083 copy = true;
1084 break;
1085
c1582939 1086 case kJSTypeObject:
b09da87b
JF
1087 // XXX: this might could be more efficient
1088 object = (CFTypeRef) CYCastNSObject(pool, context, (JSObjectRef) value);
1089 copy = false;
1090 break;
1091
c1582939 1092 default:
f5e9be24 1093 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"JSValueGetType() == 0x%x", type] userInfo:nil];
b09da87b 1094 break;
c1582939 1095 }
b09da87b
JF
1096
1097 if (cast != copy)
1098 return object;
1099 else if (copy)
953647c1 1100 return CYPoolRelease(pool, object);
b09da87b
JF
1101 else
1102 return CFRetain(object);
1103}
1104
1105CFTypeRef CYCastCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1106 return CYCFType(pool, context, value, true);
1107}
1108
1109CFTypeRef CYCopyCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1110 return CYCFType(pool, context, value, false);
c1582939
JF
1111}
1112
62ca2b82 1113NSArray *CYCastNSArray(JSPropertyNameArrayRef names) {
b09da87b 1114 CYPool pool;
62ca2b82
JF
1115 size_t size(JSPropertyNameArrayGetCount(names));
1116 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1117 for (size_t index(0); index != size; ++index)
b09da87b 1118 [array addObject:CYCastNSString(pool, JSPropertyNameArrayGetNameAtIndex(names, index))];
62ca2b82
JF
1119 return array;
1120}
1121
b09da87b
JF
1122id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1123 return reinterpret_cast<const NSObject *>(CYCastCFType(pool, context, value));
c1582939
JF
1124}
1125
ea2d184c 1126void CYThrow(JSContextRef context, JSValueRef value) {
62ca2b82
JF
1127 if (value == NULL)
1128 return;
b09da87b
JF
1129 @throw CYCastNSObject(NULL, context, value);
1130}
1131
1132JSValueRef CYJSNull(JSContextRef context) {
1133 return JSValueMakeNull(context);
1134}
1135
1136JSValueRef CYCastJSValue(JSContextRef context, JSStringRef value) {
1137 return value == NULL ? CYJSNull(context) : JSValueMakeString(context, value);
1138}
1139
1140JSValueRef CYCastJSValue(JSContextRef context, const char *value) {
1141 return CYCastJSValue(context, CYJSString(value));
62ca2b82
JF
1142}
1143
2b52f27e 1144JSValueRef CYCastJSValue(JSContextRef context, id value) {
f7c38a29
JF
1145 if (value == nil)
1146 return CYJSNull(context);
1147 else if ([value respondsToSelector:@selector(cy$JSValueInContext:)])
1148 return [value cy$JSValueInContext:context];
1149 else
1150 return CYMakeInstance(context, value, false);
62ca2b82
JF
1151}
1152
dea834b0
JF
1153JSObjectRef CYCastJSObject(JSContextRef context, JSValueRef value) {
1154 JSValueRef exception(NULL);
1155 JSObjectRef object(JSValueToObject(context, value, &exception));
1156 CYThrow(context, exception);
1157 return object;
1158}
1159
bd17e6f3
JF
1160JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, size_t index) {
1161 JSValueRef exception(NULL);
1162 JSValueRef value(JSObjectGetPropertyAtIndex(context, object, index, &exception));
1163 CYThrow(context, exception);
1164 return value;
1165}
1166
dea834b0
JF
1167JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, JSStringRef name) {
1168 JSValueRef exception(NULL);
1169 JSValueRef value(JSObjectGetProperty(context, object, name, &exception));
1170 CYThrow(context, exception);
1171 return value;
1172}
1173
1174void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef value) {
1175 JSValueRef exception(NULL);
1176 JSObjectSetProperty(context, object, name, value, kJSPropertyAttributeNone, &exception);
1177 CYThrow(context, exception);
1178}
1179
30ddc20c 1180void CYThrow(JSContextRef context, id error, JSValueRef *exception) {
4cf49641
JF
1181 if (exception == NULL)
1182 throw error;
7ba62cfd
JF
1183 *exception = CYCastJSValue(context, error);
1184}
1185
b4aa79af
JF
1186JSValueRef CYCallAsFunction(JSContextRef context, JSObjectRef function, JSObjectRef _this, size_t count, JSValueRef arguments[]) {
1187 JSValueRef exception(NULL);
1188 JSValueRef value(JSObjectCallAsFunction(context, function, _this, count, arguments, &exception));
1189 CYThrow(context, exception);
1190 return value;
1191}
1192
1193bool CYIsCallable(JSContextRef context, JSValueRef value) {
1194 // XXX: this isn't actually correct
1195 return value != NULL && JSValueIsObject(context, value);
1196}
1197
b21525c7 1198@implementation CYJSObject
62ca2b82
JF
1199
1200- (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
1201 if ((self = [super init]) != nil) {
1202 object_ = object;
1203 context_ = context;
1204 } return self;
1205}
1206
b4aa79af
JF
1207- (NSObject *) cy$toJSON:(NSString *)key {
1208 JSValueRef toJSON(CYGetProperty(context_, object_, toJSON_));
1209 if (!CYIsCallable(context_, toJSON))
1210 return [super cy$toJSON:key];
1211 else {
1212 JSValueRef arguments[1] = {CYCastJSValue(context_, key)};
1213 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toJSON, object_, 1, arguments));
1214 // XXX: do I really want an NSNull here?!
1215 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1216 }
1217}
1218
1219- (NSString *) cy$toCYON {
1220 JSValueRef toCYON(CYGetProperty(context_, object_, toCYON_));
1221 if (!CYIsCallable(context_, toCYON))
1222 return [super cy$toCYON];
1223 else {
1224 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toCYON, object_, 0, NULL));
1225 return CYCastNSString(NULL, CYJSString(context_, value));
1226 }
1227}
1228
62ca2b82
JF
1229- (NSUInteger) count {
1230 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1231 size_t size(JSPropertyNameArrayGetCount(names));
1232 JSPropertyNameArrayRelease(names);
1233 return size;
1234}
1235
1236- (id) objectForKey:(id)key {
478d4ed0 1237 return CYCastNSObject(NULL, context_, CYGetProperty(context_, object_, CYJSString(key))) ?: [NSNull null];
62ca2b82
JF
1238}
1239
1240- (NSEnumerator *) keyEnumerator {
1241 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1242 NSEnumerator *enumerator([CYCastNSArray(names) objectEnumerator]);
1243 JSPropertyNameArrayRelease(names);
1244 return enumerator;
1245}
1246
1247- (void) setObject:(id)object forKey:(id)key {
dea834b0 1248 CYSetProperty(context_, object_, CYJSString(key), CYCastJSValue(context_, object));
62ca2b82
JF
1249}
1250
1251- (void) removeObjectForKey:(id)key {
1252 JSValueRef exception(NULL);
2b52f27e 1253 (void) JSObjectDeleteProperty(context_, object_, CYJSString(key), &exception);
62ca2b82
JF
1254 CYThrow(context_, exception);
1255}
1256
1257@end
1258
b21525c7 1259@implementation CYJSArray
c1582939
JF
1260
1261- (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
1262 if ((self = [super init]) != nil) {
1263 object_ = object;
1264 context_ = context;
1265 } return self;
1266}
1267
1268- (NSUInteger) count {
dea834b0 1269 return CYCastDouble(context_, CYGetProperty(context_, object_, length_));
c1582939
JF
1270}
1271
1272- (id) objectAtIndex:(NSUInteger)index {
62ca2b82
JF
1273 JSValueRef exception(NULL);
1274 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
1275 CYThrow(context_, exception);
478d4ed0 1276 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
c1582939
JF
1277}
1278
1279@end
1280
b4aa79af 1281CFStringRef CYCopyCYONString(JSContextRef context, JSValueRef value, JSValueRef *exception) {
4cf49641
JF
1282 CYTry {
1283 CYPoolTry {
b4aa79af
JF
1284 id object(CYCastNSObject(NULL, context, value) ?: [NSNull null]);
1285 return reinterpret_cast<CFStringRef>([[object cy$toCYON] retain]);
4cf49641
JF
1286 } CYPoolCatch(NULL)
1287 } CYCatch
c1582939
JF
1288}
1289
b4aa79af
JF
1290const char *CYPoolCYONString(apr_pool_t *pool, JSContextRef context, JSValueRef value, JSValueRef *exception) {
1291 if (NSString *json = (NSString *) CYCopyCYONString(context, value, exception)) {
4cf49641
JF
1292 const char *string(CYPoolCString(pool, json));
1293 [json release];
1294 return string;
1295 } else return NULL;
478d4ed0
JF
1296}
1297
b09da87b 1298static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
4afefdd9
JF
1299 CYPool pool;
1300
4cf49641 1301 CYTry {
cc103044 1302 NSString *self(CYCastNSObject(pool, context, object));
b09da87b 1303 NSString *name(CYCastNSString(pool, property));
4afefdd9
JF
1304
1305 CYPoolTry {
1306 if (NSObject *data = [self cy$getProperty:name])
1307 return CYCastJSValue(context, data);
1308 } CYPoolCatch(NULL)
1309
1310 if (objc_property_t property = class_getProperty(object_getClass(self), [name UTF8String])) {
1311 PropertyAttributes attributes(property);
1312 SEL sel(sel_registerName(attributes.Getter()));
2b52f27e 1313 return CYSendMessage(pool, context, self, sel, 0, NULL, false, exception);
4afefdd9
JF
1314 }
1315
1316 return NULL;
f610e1a0 1317 } CYCatch
c1582939
JF
1318}
1319
b09da87b 1320static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
4afefdd9
JF
1321 CYPool pool;
1322
4cf49641 1323 CYTry {
cc103044 1324 NSString *self(CYCastNSObject(pool, context, object));
b09da87b 1325 NSString *name(CYCastNSString(pool, property));
cc103044 1326 NSString *data(CYCastNSObject(pool, context, value));
4afefdd9
JF
1327
1328 CYPoolTry {
1329 if ([self cy$setProperty:name to:data])
1330 return true;
1331 } CYPoolCatch(NULL)
1332
1333 if (objc_property_t property = class_getProperty(object_getClass(self), [name UTF8String])) {
1334 PropertyAttributes attributes(property);
1335 if (const char *setter = attributes.Setter()) {
1336 SEL sel(sel_registerName(setter));
1337 JSValueRef arguments[1] = {value};
2b52f27e 1338 CYSendMessage(pool, context, self, sel, 1, arguments, false, exception);
4afefdd9
JF
1339 return true;
1340 }
1341 }
1342
1343 return false;
b09da87b
JF
1344 } CYCatch
1345}
1346
1347static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
4cf49641 1348 CYTry {
4afefdd9
JF
1349 CYPoolTry {
1350 NSString *self(CYCastNSObject(NULL, context, object));
1351 NSString *name(CYCastNSString(NULL, property));
1352 return [self cy$deleteProperty:name];
1353 } CYPoolCatch(NULL)
b09da87b
JF
1354 } CYCatch
1355}
1356
b09da87b 1357static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
4cf49641 1358 CYTry {
2b52f27e
JF
1359 Instance *data(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1360 JSObjectRef value(Instance::Make(context, [data->GetValue() alloc], Instance::Uninitialized));
1361 return value;
0c862573
JF
1362 } CYCatch
1363}
1364
dea834b0 1365JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
953647c1 1366 Selector_privateData *data(new Selector_privateData(sel));
dea834b0
JF
1367 return JSObjectMake(context, Selector_, data);
1368}
1369
ff783f8c
JF
1370JSObjectRef CYMakePointer(JSContextRef context, void *pointer, sig::Type *type, JSObjectRef owner) {
1371 Pointer *data(new Pointer(pointer, type, owner));
dea834b0
JF
1372 return JSObjectMake(context, Pointer_, data);
1373}
1374
b09da87b 1375JSObjectRef CYMakeFunctor(JSContextRef context, void (*function)(), const char *type) {
953647c1 1376 Functor_privateData *data(new Functor_privateData(type, function));
88c977fa
JF
1377 return JSObjectMake(context, Functor_, data);
1378}
1379
bd17e6f3
JF
1380const char *CYPoolCString(apr_pool_t *pool, JSStringRef value, size_t *length = NULL) {
1381 if (pool == NULL) {
1382 const char *string([CYCastNSString(NULL, value) UTF8String]);
1383 if (length != NULL)
1384 *length = strlen(string);
1385 return string;
1386 } else {
478d4ed0
JF
1387 size_t size(JSStringGetMaximumUTF8CStringSize(value));
1388 char *string(new(pool) char[size]);
1389 JSStringGetUTF8CString(value, string, size);
bd17e6f3
JF
1390 // XXX: this is ironic
1391 if (length != NULL)
1392 *length = strlen(string);
478d4ed0
JF
1393 return string;
1394 }
7ba62cfd
JF
1395}
1396
bd17e6f3
JF
1397const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value, size_t *length = NULL) {
1398 if (!JSValueIsNull(context, value))
1399 return CYPoolCString(pool, CYJSString(context, value), length);
1400 else {
1401 if (length != NULL)
1402 *length = 0;
b09da87b 1403 return NULL;
bd17e6f3 1404 }
77e87a6c
JF
1405}
1406
ff783f8c
JF
1407bool CYGetIndex(apr_pool_t *pool, JSStringRef value, ssize_t &index) {
1408 return CYGetIndex(CYPoolCString(pool, value), index);
1409}
1410
f610e1a0 1411// XXX: this macro is unhygenic
b21525c7 1412#define CYCastCString(context, value) ({ \
b09da87b
JF
1413 char *utf8; \
1414 if (value == NULL) \
1415 utf8 = NULL; \
478d4ed0 1416 else if (JSStringRef string = CYCopyJSString(context, value)) { \
b09da87b
JF
1417 size_t size(JSStringGetMaximumUTF8CStringSize(string)); \
1418 utf8 = reinterpret_cast<char *>(alloca(size)); \
1419 JSStringGetUTF8CString(string, utf8, size); \
1420 JSStringRelease(string); \
478d4ed0
JF
1421 } else \
1422 utf8 = NULL; \
b21525c7
JF
1423 utf8; \
1424})
1425
b09da87b 1426void *CYCastPointer_(JSContextRef context, JSValueRef value) {
b21525c7
JF
1427 switch (JSValueGetType(context, value)) {
1428 case kJSTypeNull:
1429 return NULL;
953647c1 1430 /*case kJSTypeString:
b21525c7 1431 return dlsym(RTLD_DEFAULT, CYCastCString(context, value));
b21525c7 1432 case kJSTypeObject:
88c977fa 1433 if (JSValueIsObjectOfClass(context, value, Pointer_)) {
ff783f8c 1434 Pointer *data(reinterpret_cast<Pointer *>(JSObjectGetPrivate((JSObjectRef) value)));
b21525c7 1435 return data->value_;
953647c1 1436 }*/
b21525c7 1437 default:
953647c1 1438 double number(CYCastDouble(context, value));
bd17e6f3 1439 if (std::isnan(number))
953647c1
JF
1440 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"cannot convert value to pointer" userInfo:nil];
1441 return reinterpret_cast<void *>(static_cast<uintptr_t>(static_cast<long long>(number)));
7ba62cfd
JF
1442 }
1443}
1444
b09da87b
JF
1445template <typename Type_>
1446_finline Type_ CYCastPointer(JSContextRef context, JSValueRef value) {
1447 return reinterpret_cast<Type_>(CYCastPointer_(context, value));
1448}
1449
4afefdd9
JF
1450SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1451 if (JSValueIsObjectOfClass(context, value, Selector_)) {
1452 Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1453 return reinterpret_cast<SEL>(data->value_);
1454 } else
1455 return CYCastPointer<SEL>(context, value);
1456}
1457
bd17e6f3 1458void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) {
ea2d184c
JF
1459 switch (type->primitive) {
1460 case sig::boolean_P:
1461 *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
1462 break;
1463
43cb3d68 1464#define CYPoolFFI_(primitive, native) \
f610e1a0
JF
1465 case sig::primitive ## _P: \
1466 *reinterpret_cast<native *>(data) = CYCastDouble(context, value); \
1467 break;
ea2d184c 1468
43cb3d68
JF
1469 CYPoolFFI_(uchar, unsigned char)
1470 CYPoolFFI_(char, char)
1471 CYPoolFFI_(ushort, unsigned short)
1472 CYPoolFFI_(short, short)
1473 CYPoolFFI_(ulong, unsigned long)
1474 CYPoolFFI_(long, long)
1475 CYPoolFFI_(uint, unsigned int)
1476 CYPoolFFI_(int, int)
1477 CYPoolFFI_(ulonglong, unsigned long long)
1478 CYPoolFFI_(longlong, long long)
1479 CYPoolFFI_(float, float)
1480 CYPoolFFI_(double, double)
ea2d184c
JF
1481
1482 case sig::object_P:
1483 case sig::typename_P:
b09da87b 1484 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
7ba62cfd
JF
1485 break;
1486
ea2d184c 1487 case sig::selector_P:
7ba62cfd
JF
1488 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1489 break;
ea2d184c 1490
b21525c7 1491 case sig::pointer_P:
b09da87b 1492 *reinterpret_cast<void **>(data) = CYCastPointer<void *>(context, value);
b21525c7 1493 break;
ea2d184c 1494
77e87a6c 1495 case sig::string_P:
478d4ed0 1496 *reinterpret_cast<const char **>(data) = CYPoolCString(pool, context, value);
77e87a6c 1497 break;
7ba62cfd 1498
bd17e6f3
JF
1499 case sig::struct_P: {
1500 uint8_t *base(reinterpret_cast<uint8_t *>(data));
f33b048a 1501 JSObjectRef aggregate(JSValueIsObject(context, value) ? (JSObjectRef) value : NULL);
bd17e6f3 1502 for (size_t index(0); index != type->data.signature.count; ++index) {
f33b048a
JF
1503 sig::Element *element(&type->data.signature.elements[index]);
1504 ffi_type *field(ffi->elements[index]);
1505
1506 JSValueRef rhs;
1507 if (aggregate == NULL)
1508 rhs = value;
1509 else {
1510 rhs = CYGetProperty(context, aggregate, index);
1511 if (JSValueIsUndefined(context, rhs)) {
283e7e33
JF
1512 if (element->name != NULL)
1513 rhs = CYGetProperty(context, aggregate, CYJSString(element->name));
1514 else
1515 goto undefined;
1516 if (JSValueIsUndefined(context, rhs)) undefined:
f33b048a
JF
1517 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"unable to extract structure value" userInfo:nil];
1518 }
1519 }
1520
1521 CYPoolFFI(pool, context, element->type, field, base, rhs);
4e8c99fb 1522 // XXX: alignment?
f33b048a 1523 base += field->size;
bd17e6f3
JF
1524 }
1525 } break;
ea2d184c
JF
1526
1527 case sig::void_P:
1528 break;
1529
bd17e6f3 1530 default:
43cb3d68 1531 NSLog(@"CYPoolFFI(%c)\n", type->primitive);
ea2d184c
JF
1532 _assert(false);
1533 }
1534}
1535
2b52f27e 1536JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner = NULL) {
ea2d184c
JF
1537 JSValueRef value;
1538
1539 switch (type->primitive) {
1540 case sig::boolean_P:
b09da87b 1541 value = CYCastJSValue(context, *reinterpret_cast<bool *>(data));
ea2d184c
JF
1542 break;
1543
1544#define CYFromFFI_(primitive, native) \
1545 case sig::primitive ## _P: \
b09da87b 1546 value = CYCastJSValue(context, *reinterpret_cast<native *>(data)); \
ea2d184c
JF
1547 break;
1548
1549 CYFromFFI_(uchar, unsigned char)
1550 CYFromFFI_(char, char)
1551 CYFromFFI_(ushort, unsigned short)
1552 CYFromFFI_(short, short)
1553 CYFromFFI_(ulong, unsigned long)
1554 CYFromFFI_(long, long)
1555 CYFromFFI_(uint, unsigned int)
1556 CYFromFFI_(int, int)
1557 CYFromFFI_(ulonglong, unsigned long long)
1558 CYFromFFI_(longlong, long long)
1559 CYFromFFI_(float, float)
1560 CYFromFFI_(double, double)
1561
2b52f27e
JF
1562 case sig::object_P: {
1563 if (id object = *reinterpret_cast<id *>(data)) {
1564 value = CYCastJSValue(context, object);
1565 if (initialize)
1566 [object release];
1567 } else goto null;
1568 } break;
dea834b0 1569
b09da87b 1570 case sig::typename_P:
4cf49641 1571 value = CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
b09da87b
JF
1572 break;
1573
dea834b0
JF
1574 case sig::selector_P:
1575 if (SEL sel = *reinterpret_cast<SEL *>(data))
1576 value = CYMakeSelector(context, sel);
1577 else goto null;
1578 break;
1579
1580 case sig::pointer_P:
1581 if (void *pointer = *reinterpret_cast<void **>(data))
ff783f8c 1582 value = CYMakePointer(context, pointer, type->data.data.type, owner);
dea834b0
JF
1583 else goto null;
1584 break;
1585
1586 case sig::string_P:
f610e1a0 1587 if (char *utf8 = *reinterpret_cast<char **>(data))
b09da87b 1588 value = CYCastJSValue(context, utf8);
f610e1a0 1589 else goto null;
dea834b0 1590 break;
ea2d184c
JF
1591
1592 case sig::struct_P:
bd17e6f3
JF
1593 value = CYMakeStruct(context, data, type, ffi, owner);
1594 break;
ea2d184c
JF
1595
1596 case sig::void_P:
b09da87b 1597 value = CYJSUndefined(context);
f610e1a0
JF
1598 break;
1599
1600 null:
b09da87b 1601 value = CYJSNull(context);
ea2d184c
JF
1602 break;
1603
bd17e6f3 1604 default:
ea2d184c
JF
1605 NSLog(@"CYFromFFI(%c)\n", type->primitive);
1606 _assert(false);
1607 }
1608
1609 return value;
1610}
1611
9e20b0b7 1612bool Index_(apr_pool_t *pool, Struct_privateData *internal, JSStringRef property, ssize_t &index, uint8_t *&base) {
bd17e6f3 1613 Type_privateData *typical(internal->type_);
930aa21b
JF
1614 sig::Type *type(typical->type_);
1615 if (type == NULL)
1616 return false;
bd17e6f3 1617
9e20b0b7
JF
1618 size_t length;
1619 const char *name(CYPoolCString(pool, property, &length));
1620 double number(CYCastDouble(name, length));
1621
930aa21b 1622 size_t count(type->data.signature.count);
f33b048a 1623
e0dc20ec
JF
1624 if (std::isnan(number)) {
1625 if (property == NULL)
1626 return false;
9e20b0b7 1627
930aa21b 1628 sig::Element *elements(type->data.signature.elements);
f33b048a 1629
283e7e33
JF
1630 for (size_t local(0); local != count; ++local) {
1631 sig::Element *element(&elements[local]);
1632 if (element->name != NULL && strcmp(name, element->name) == 0) {
f33b048a
JF
1633 index = local;
1634 goto base;
1635 }
283e7e33 1636 }
f33b048a 1637
9e20b0b7 1638 return false;
e0dc20ec
JF
1639 } else {
1640 index = static_cast<ssize_t>(number);
f33b048a 1641 if (index != number || index < 0 || static_cast<size_t>(index) >= count)
e0dc20ec
JF
1642 return false;
1643 }
bd17e6f3 1644
f33b048a 1645 base:
ff783f8c
JF
1646 ffi_type **elements(typical->GetFFI()->elements);
1647
bd17e6f3
JF
1648 base = reinterpret_cast<uint8_t *>(internal->value_);
1649 for (ssize_t local(0); local != index; ++local)
ff783f8c 1650 base += elements[local]->size;
9e20b0b7
JF
1651
1652 return true;
bd17e6f3
JF
1653}
1654
ff783f8c
JF
1655static JSValueRef Pointer_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1656 CYPool pool;
1657 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
1658 Type_privateData *typical(internal->type_);
1659
930aa21b
JF
1660 if (typical->type_ == NULL)
1661 return NULL;
1662
ff783f8c
JF
1663 ssize_t index;
1664 if (!CYGetIndex(pool, property, index))
1665 return NULL;
1666
1667 ffi_type *ffi(typical->GetFFI());
1668
1669 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
1670 base += ffi->size * index;
1671
1672 JSObjectRef owner(internal->owner_ ?: object);
1673
1674 CYTry {
930aa21b 1675 return CYFromFFI(context, typical->type_, ffi, base, false, owner);
ff783f8c
JF
1676 } CYCatch
1677}
1678
f37b3d2b
JF
1679static bool Pointer_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1680 CYPool pool;
1681 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
1682 Type_privateData *typical(internal->type_);
1683
930aa21b
JF
1684 if (typical->type_ == NULL)
1685 return NULL;
1686
f37b3d2b
JF
1687 ssize_t index;
1688 if (!CYGetIndex(pool, property, index))
1689 return NULL;
1690
1691 ffi_type *ffi(typical->GetFFI());
1692
1693 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
1694 base += ffi->size * index;
1695
1696 CYTry {
930aa21b 1697 CYPoolFFI(NULL, context, typical->type_, ffi, base, value);
f37b3d2b
JF
1698 return true;
1699 } CYCatch
1700}
1701
bd17e6f3 1702static JSValueRef Struct_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
f33b048a
JF
1703 CYPool pool;
1704 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
1705 Type_privateData *typical(internal->type_);
bd17e6f3 1706
f33b048a
JF
1707 ssize_t index;
1708 uint8_t *base;
bd17e6f3 1709
f33b048a
JF
1710 if (!Index_(pool, internal, property, index, base))
1711 return NULL;
bd17e6f3 1712
ff783f8c
JF
1713 JSObjectRef owner(internal->owner_ ?: object);
1714
f33b048a 1715 CYTry {
930aa21b 1716 return CYFromFFI(context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, false, owner);
bd17e6f3
JF
1717 } CYCatch
1718}
1719
1720static bool Struct_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
f33b048a
JF
1721 CYPool pool;
1722 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
1723 Type_privateData *typical(internal->type_);
bd17e6f3 1724
f33b048a
JF
1725 ssize_t index;
1726 uint8_t *base;
bd17e6f3 1727
f33b048a
JF
1728 if (!Index_(pool, internal, property, index, base))
1729 return false;
bd17e6f3 1730
f33b048a 1731 CYTry {
930aa21b 1732 CYPoolFFI(NULL, context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, value);
bd17e6f3
JF
1733 return true;
1734 } CYCatch
1735}
1736
f33b048a
JF
1737static void Struct_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1738 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
1739 Type_privateData *typical(internal->type_);
930aa21b
JF
1740 sig::Type *type(typical->type_);
1741
1742 if (type == NULL)
1743 return;
f33b048a 1744
930aa21b
JF
1745 size_t count(type->data.signature.count);
1746 sig::Element *elements(type->data.signature.elements);
f33b048a 1747
283e7e33
JF
1748 char number[32];
1749
1750 for (size_t index(0); index != count; ++index) {
1751 const char *name;
1752 name = elements[index].name;
1753
1754 if (name == NULL) {
1755 sprintf(number, "%lu", index);
1756 name = number;
1757 }
1758
1759 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1760 }
f33b048a
JF
1761}
1762
2b52f27e 1763JSValueRef 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 1764 CYTry {
4afefdd9 1765 if (setups + count != signature->count - 1)
f5e9be24 1766 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to ffi function" userInfo:nil];
85a33bf5 1767
4afefdd9
JF
1768 size_t size(setups + count);
1769 void *values[size];
1770 memcpy(values, setup, sizeof(void *) * setups);
ea2d184c 1771
4afefdd9 1772 for (size_t index(setups); index != size; ++index) {
7ba62cfd 1773 sig::Element *element(&signature->elements[index + 1]);
bd17e6f3 1774 ffi_type *ffi(cif->arg_types[index]);
77e87a6c 1775 // XXX: alignment?
bd17e6f3 1776 values[index] = new(pool) uint8_t[ffi->size];
4afefdd9 1777 CYPoolFFI(pool, context, element->type, ffi, values[index], arguments[index - setups]);
7ba62cfd 1778 }
ea2d184c 1779
7ba62cfd
JF
1780 uint8_t value[cif->rtype->size];
1781 ffi_call(cif, function, value, values);
1782
2b52f27e 1783 return CYFromFFI(context, signature->elements[0].type, cif->rtype, value, initialize);
0c862573 1784 } CYCatch
7ba62cfd 1785}
ea2d184c 1786
478d4ed0 1787void Closure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
478d4ed0
JF
1788 ffoData *data(reinterpret_cast<ffoData *>(arg));
1789
1790 JSContextRef context(data->context_);
1791
1792 size_t count(data->cif_.nargs);
1793 JSValueRef values[count];
1794
1795 for (size_t index(0); index != count; ++index)
2b52f27e 1796 values[index] = CYFromFFI(context, data->signature_.elements[1 + index].type, data->cif_.arg_types[index], arguments[index], false);
478d4ed0 1797
b4aa79af 1798 JSValueRef value(CYCallAsFunction(context, data->function_, NULL, count, values));
bd17e6f3 1799 CYPoolFFI(NULL, context, data->signature_.elements[0].type, data->cif_.rtype, result, value);
478d4ed0
JF
1800}
1801
1802JSObjectRef CYMakeFunctor(JSContextRef context, JSObjectRef function, const char *type) {
1803 // XXX: in case of exceptions this will leak
1804 ffoData *data(new ffoData(type));
1805
1806 ffi_closure *closure;
1807 _syscall(closure = (ffi_closure *) mmap(
1808 NULL, sizeof(ffi_closure),
1809 PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE,
1810 -1, 0
1811 ));
1812
1813 ffi_status status(ffi_prep_closure(closure, &data->cif_, &Closure_, data));
1814 _assert(status == FFI_OK);
1815
1816 _syscall(mprotect(closure, sizeof(*closure), PROT_READ | PROT_EXEC));
1817
1818 data->value_ = closure;
1819
1820 data->context_ = CYGetJSContext();
1821 data->function_ = function;
1822
1823 return JSObjectMake(context, Functor_, data);
1824}
1825
953647c1 1826static JSValueRef Runtime_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
4cf49641 1827 CYTry {
b09da87b
JF
1828 CYPool pool;
1829 NSString *name(CYCastNSString(pool, property));
f610e1a0 1830 if (Class _class = NSClassFromString(name))
4cf49641 1831 return CYMakeInstance(context, _class, true);
953647c1 1832 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:0] objectForKey:name])
707bcb93
JF
1833 switch ([[entry objectAtIndex:0] intValue]) {
1834 case 0:
057f943f 1835 return JSEvaluateScript(CYGetJSContext(), CYJSString([entry objectAtIndex:1]), NULL, NULL, 0, NULL);
707bcb93 1836 case 1:
478d4ed0 1837 return CYMakeFunctor(context, reinterpret_cast<void (*)()>([name cy$symbol]), CYPoolCString(pool, [entry objectAtIndex:1]));
707bcb93 1838 case 2:
bd17e6f3 1839 // XXX: this is horrendously inefficient
707bcb93 1840 sig::Signature signature;
f33b048a 1841 sig::Parse(pool, &signature, CYPoolCString(pool, [entry objectAtIndex:1]), &Structor_);
bd17e6f3
JF
1842 ffi_cif cif;
1843 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2b52f27e 1844 return CYFromFFI(context, signature.elements[0].type, cif.rtype, [name cy$symbol], false);
707bcb93
JF
1845 }
1846 return NULL;
1847 } CYCatch
1848}
1849
04450da0
JF
1850bool stret(ffi_type *ffi_type) {
1851 return ffi_type->type == FFI_TYPE_STRUCT && (
1852 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
1853 struct_forward_array[ffi_type->size] != 0
1854 );
1855}
1856
b09da87b
JF
1857extern "C" {
1858 int *_NSGetArgc(void);
1859 char ***_NSGetArgv(void);
1860 int UIApplicationMain(int argc, char *argv[], NSString *principalClassName, NSString *delegateClassName);
1861}
1862
1863static JSValueRef System_print(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
4cf49641 1864 CYTry {
b09da87b
JF
1865 NSLog(@"%s", CYCastCString(context, arguments[0]));
1866 return CYJSUndefined(context);
1867 } CYCatch
1868}
1869
2b52f27e 1870JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception) {
7ba62cfd 1871 const char *type;
ea2d184c 1872
4afefdd9
JF
1873 Class _class(object_getClass(self));
1874 if (Method method = class_getInstanceMethod(_class, _cmd))
1875 type = method_getTypeEncoding(method);
1876 else {
1877 CYPoolTry {
1878 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
1879 if (method == nil)
1880 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"unrecognized selector %s sent to object %p", sel_getName(_cmd), self] userInfo:nil];
1881 type = CYPoolCString(pool, [method _typeString]);
1882 } CYPoolCatch(NULL)
1883 }
1884
1885 void *setup[2];
1886 setup[0] = &self;
1887 setup[1] = &_cmd;
1888
1889 sig::Signature signature;
f33b048a 1890 sig::Parse(pool, &signature, type, &Structor_);
4afefdd9
JF
1891
1892 ffi_cif cif;
1893 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
1894
1895 void (*function)() = stret(cif.rtype) ? reinterpret_cast<void (*)()>(&objc_msgSend_stret) : reinterpret_cast<void (*)()>(&objc_msgSend);
2b52f27e 1896 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, exception, &signature, &cif, function);
4afefdd9
JF
1897}
1898
1899static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
478d4ed0
JF
1900 CYPool pool;
1901
2b52f27e
JF
1902 bool uninitialized;
1903
4afefdd9
JF
1904 id self;
1905 SEL _cmd;
1906
4cf49641 1907 CYTry {
85a33bf5 1908 if (count < 2)
f5e9be24 1909 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"too few arguments to objc_msgSend" userInfo:nil];
85a33bf5 1910
2b52f27e
JF
1911 if (JSValueIsObjectOfClass(context, arguments[0], Instance_)) {
1912 Instance *data(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
1913 self = data->GetValue();
1914 uninitialized = data->IsUninitialized();
1915 if (uninitialized)
1916 data->value_ = nil;
1917 } else {
1918 self = CYCastNSObject(pool, context, arguments[0]);
1919 uninitialized = false;
1920 }
1921
7ba62cfd 1922 if (self == nil)
b09da87b 1923 return CYJSNull(context);
7ba62cfd 1924
4afefdd9 1925 _cmd = CYCastSEL(context, arguments[1]);
0c862573 1926 } CYCatch
ea2d184c 1927
2b52f27e 1928 return CYSendMessage(pool, context, self, _cmd, count - 2, arguments + 2, uninitialized, exception);
7ba62cfd
JF
1929}
1930
f7c38a29
JF
1931static JSValueRef CYJSValueInContext(id self, SEL _cmd, JSContextRef context) {
1932 // XXX: the offset of this Ivar could be recomputed and stored in some form of closure during $objc_registerClassPair
1933
1934 JSObjectRef value;
1935 object_getInstanceVariable(self, "cy$value_", reinterpret_cast<void **>(&value));
1936
1937 if (value == NULL) {
1938 value = CYMakeInstance(context, self, false);
1939 object_setInstanceVariable(self, "cy$value_", value);
1940 }
1941
1942 return value;
1943}
1944
1945static JSValueRef $objc_registerClassPair(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1946 CYTry {
1947 CYPool pool;
1948
1949 Class _class(CYCastNSObject(pool, context, object));
1950 if (class_getInstanceMethod(_class, @selector(cy$JSValueInContext:)) == NULL) {
1951 class_addIvar(_class, "cy$value_", sizeof(JSObjectRef), log2(sizeof(JSObjectRef)), "^v");
1952 class_addMethod(_class, @selector(cy$JSValueInContext:), reinterpret_cast<IMP>(&CYJSValueInContext), "^v12@0:4^v8");
1953 }
1954
1955 objc_registerClassPair(_class);
1956 return CYJSUndefined(context);
1957 } CYCatch
1958}
1959
dea834b0
JF
1960static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1961 JSValueRef setup[count + 2];
1962 setup[0] = _this;
1963 setup[1] = object;
4afefdd9 1964 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
dea834b0
JF
1965 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
1966}
1967
1968static JSValueRef Functor_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
4afefdd9 1969 CYPool pool;
953647c1 1970 Functor_privateData *data(reinterpret_cast<Functor_privateData *>(JSObjectGetPrivate(object)));
2b52f27e 1971 return CYCallFunction(pool, context, 0, NULL, count, arguments, false, exception, &data->signature_, &data->cif_, reinterpret_cast<void (*)()>(data->value_));
ea2d184c
JF
1972}
1973
b09da87b 1974JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
4cf49641 1975 CYTry {
dea834b0
JF
1976 if (count != 1)
1977 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector constructor" userInfo:nil];
1978 const char *name(CYCastCString(context, arguments[0]));
1979 return CYMakeSelector(context, sel_registerName(name));
1980 } CYCatch
1981}
1982
f7c38a29
JF
1983JSObjectRef Pointer_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1984 CYTry {
1985 if (count != 2)
1986 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Functor constructor" userInfo:nil];
1987
1988 void *value(CYCastPointer<void *>(context, arguments[0]));
1989 const char *type(CYCastCString(context, arguments[1]));
1990
1991 CYPool pool;
1992
1993 sig::Signature signature;
1994 sig::Parse(pool, &signature, type, &Structor_);
1995
1996 return CYMakePointer(context, value, signature.elements[0].type, NULL);
1997 } CYCatch
1998}
1999
b09da87b 2000JSObjectRef Functor_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
4cf49641 2001 CYTry {
b21525c7 2002 if (count != 2)
dea834b0 2003 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Functor constructor" userInfo:nil];
b21525c7 2004 const char *type(CYCastCString(context, arguments[1]));
b09da87b
JF
2005 JSValueRef exception(NULL);
2006 if (JSValueIsInstanceOfConstructor(context, arguments[0], Function_, &exception)) {
2007 JSObjectRef function(CYCastJSObject(context, arguments[0]));
2008 return CYMakeFunctor(context, function, type);
2009 } else if (exception != NULL) {
2010 return NULL;
2011 } else {
2012 void (*function)()(CYCastPointer<void (*)()>(context, arguments[0]));
2013 return CYMakeFunctor(context, function, type);
2014 }
0c862573 2015 } CYCatch
ea2d184c
JF
2016}
2017
ff783f8c
JF
2018JSValueRef CYData_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2019 CYData *data(reinterpret_cast<CYData *>(JSObjectGetPrivate(object)));
b09da87b 2020 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(data->value_));
04450da0
JF
2021}
2022
dea834b0
JF
2023JSValueRef Selector_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2024 return Function_;
2025}
2026
ff783f8c 2027static JSValueRef CYData_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
953647c1 2028 CYTry {
ff783f8c 2029 CYData *data(reinterpret_cast<CYData *>(JSObjectGetPrivate(_this)));
953647c1
JF
2030 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(data->value_));
2031 } CYCatch
2032}
2033
ff783f8c
JF
2034static JSValueRef CYData_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2035 return CYData_callAsFunction_valueOf(context, object, _this, count, arguments, exception);
b4aa79af
JF
2036}
2037
ff783f8c 2038static JSValueRef CYData_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
4afefdd9 2039 CYTry {
ff783f8c 2040 CYData *data(reinterpret_cast<CYData *>(JSObjectGetPrivate(_this)));
4afefdd9
JF
2041 char string[32];
2042 sprintf(string, "%p", data->value_);
2043 return CYCastJSValue(context, string);
2044 } CYCatch
2045}
2046
b4aa79af
JF
2047static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2048 CYTry {
2b52f27e 2049 Instance *data(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
b4aa79af
JF
2050 CYPoolTry {
2051 return CYCastJSValue(context, CYJSString([data->GetValue() cy$toCYON]));
2052 } CYPoolCatch(NULL)
2053 } CYCatch
2054}
2055
2056static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2057 CYTry {
2b52f27e 2058 Instance *data(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
b4aa79af
JF
2059 CYPoolTry {
2060 NSString *key(count == 0 ? nil : CYCastNSString(NULL, CYJSString(context, arguments[0])));
2061 return CYCastJSValue(context, CYJSString([data->GetValue() cy$toJSON:key]));
2062 } CYPoolCatch(NULL)
2063 } CYCatch
2064}
2065
4cf49641
JF
2066static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2067 CYTry {
2b52f27e 2068 Instance *data(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
4e8c99fb
JF
2069 CYPoolTry {
2070 return CYCastJSValue(context, CYJSString([data->GetValue() description]));
4cf49641 2071 } CYPoolCatch(NULL)
478d4ed0
JF
2072 } CYCatch
2073}
2074
2075static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
4cf49641 2076 CYTry {
953647c1 2077 Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
478d4ed0
JF
2078 return CYCastJSValue(context, sel_getName(data->GetValue()));
2079 } CYCatch
2080}
2081
b4aa79af
JF
2082static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2083 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
2084}
2085
2086static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2087 CYTry {
2088 Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2089 const char *name(sel_getName(data->GetValue()));
2090 CYPoolTry {
2091 return CYCastJSValue(context, CYJSString([NSString stringWithFormat:@"@selector(%s)", name]));
2092 } CYPoolCatch(NULL)
2093 } CYCatch
2094}
2095
b09da87b 2096static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
4cf49641 2097 CYTry {
b09da87b
JF
2098 if (count != 2)
2099 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector.type" userInfo:nil];
2100 CYPool pool;
953647c1 2101 Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
b09da87b
JF
2102 Class _class(CYCastNSObject(pool, context, arguments[0]));
2103 bool instance(CYCastBool(context, arguments[1]));
2104 SEL sel(data->GetValue());
2105 if (Method method = (*(instance ? &class_getInstanceMethod : class_getClassMethod))(_class, sel))
2106 return CYCastJSValue(context, method_getTypeEncoding(method));
953647c1 2107 else if (NSString *type = [[Bridge_ objectAtIndex:1] objectForKey:CYCastNSString(pool, sel_getName(sel))])
b09da87b
JF
2108 return CYCastJSValue(context, CYJSString(type));
2109 else
2110 return CYJSNull(context);
2111 } CYCatch
2112}
2113
ff783f8c
JF
2114static JSStaticValue CYData_staticValues[2] = {
2115 {"value", &CYData_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
04450da0
JF
2116 {NULL, NULL, NULL, 0}
2117};
2118
4afefdd9 2119static JSStaticFunction Pointer_staticFunctions[4] = {
ff783f8c
JF
2120 {"toCYON", &CYData_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2121 {"toJSON", &CYData_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2122 {"valueOf", &CYData_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2123 {NULL, NULL, 0}
2124};
2125
2126static JSStaticFunction Functor_staticFunctions[4] = {
2127 {"toCYON", &CYData_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2128 {"toJSON", &CYData_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2129 {"valueOf", &CYData_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
953647c1
JF
2130 {NULL, NULL, 0}
2131};
2132
dea834b0
JF
2133/*static JSStaticValue Selector_staticValues[2] = {
2134 {"prototype", &Selector_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
2135 {NULL, NULL, NULL, 0}
2136};*/
2137
b4aa79af
JF
2138static JSStaticFunction Instance_staticFunctions[4] = {
2139 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2140 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
478d4ed0
JF
2141 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2142 {NULL, NULL, 0}
2143};
2144
b4aa79af
JF
2145static JSStaticFunction Selector_staticFunctions[5] = {
2146 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2147 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
478d4ed0 2148 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
b09da87b
JF
2149 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2150 {NULL, NULL, 0}
2151};
2152
5999c315 2153CYDriver::CYDriver(const std::string &filename) :
db5e2840 2154 state_(CYClear),
e7ed5354
JF
2155 data_(NULL),
2156 size_(0),
5999c315
JF
2157 filename_(filename),
2158 source_(NULL)
2159{
924f67b2
JF
2160 ScannerInit();
2161}
2162
5999c315 2163CYDriver::~CYDriver() {
924f67b2
JF
2164 ScannerDestroy();
2165}
2166
5befe15e
JF
2167void cy::parser::error(const cy::parser::location_type &location, const std::string &message) {
2168 CYDriver::Error error;
2169 error.location_ = location;
2170 error.message_ = message;
2171 driver.errors_.push_back(error);
63b4c5a8
JF
2172}
2173
b09da87b
JF
2174void CYSetArgs(int argc, const char *argv[]) {
2175 JSContextRef context(CYGetJSContext());
2176 JSValueRef args[argc];
2177 for (int i(0); i != argc; ++i)
2178 args[i] = CYCastJSValue(context, argv[i]);
2179 JSValueRef exception(NULL);
2180 JSObjectRef array(JSObjectMakeArray(context, argc, args, &exception));
2181 CYThrow(context, exception);
2182 CYSetProperty(context, System_, CYJSString("args"), array);
2183}
2184
579ed526
JF
2185JSObjectRef CYGetGlobalObject(JSContextRef context) {
2186 return JSContextGetGlobalObject(context);
2187}
2188
7ba62cfd 2189MSInitialize { _pooled
ea2d184c
JF
2190 apr_initialize();
2191
953647c1
JF
2192 Bridge_ = [[NSMutableArray arrayWithContentsOfFile:@"/usr/lib/libcycript.plist"] retain];
2193
c1582939
JF
2194 NSCFBoolean_ = objc_getClass("NSCFBoolean");
2195
c1582939
JF
2196 JSClassDefinition definition;
2197
2198 definition = kJSClassDefinitionEmpty;
88c977fa 2199 definition.className = "Pointer";
953647c1 2200 definition.staticFunctions = Pointer_staticFunctions;
ff783f8c 2201 definition.getProperty = &Pointer_getProperty;
f37b3d2b 2202 definition.setProperty = &Pointer_setProperty;
953647c1 2203 definition.finalize = &CYData::Finalize;
88c977fa 2204 Pointer_ = JSClassCreate(&definition);
c1582939
JF
2205
2206 definition = kJSClassDefinitionEmpty;
88c977fa 2207 definition.className = "Functor";
ff783f8c 2208 definition.staticFunctions = Functor_staticFunctions;
dea834b0 2209 definition.callAsFunction = &Functor_callAsFunction;
953647c1 2210 definition.finalize = &CYData::Finalize;
88c977fa 2211 Functor_ = JSClassCreate(&definition);
7ba62cfd 2212
953647c1
JF
2213 definition = kJSClassDefinitionEmpty;
2214 definition.className = "Struct";
bd17e6f3
JF
2215 definition.getProperty = &Struct_getProperty;
2216 definition.setProperty = &Struct_setProperty;
f33b048a 2217 definition.getPropertyNames = &Struct_getPropertyNames;
953647c1
JF
2218 definition.finalize = &CYData::Finalize;
2219 Struct_ = JSClassCreate(&definition);
2220
77e87a6c 2221 definition = kJSClassDefinitionEmpty;
88c977fa 2222 definition.className = "Selector";
ff783f8c 2223 definition.staticValues = CYData_staticValues;
dea834b0 2224 //definition.staticValues = Selector_staticValues;
b09da87b 2225 definition.staticFunctions = Selector_staticFunctions;
dea834b0 2226 definition.callAsFunction = &Selector_callAsFunction;
953647c1 2227 definition.finalize = &CYData::Finalize;
88c977fa 2228 Selector_ = JSClassCreate(&definition);
77e87a6c 2229
7ba62cfd 2230 definition = kJSClassDefinitionEmpty;
b09da87b 2231 definition.className = "Instance";
ff783f8c 2232 definition.staticValues = CYData_staticValues;
478d4ed0 2233 definition.staticFunctions = Instance_staticFunctions;
88c977fa 2234 definition.getProperty = &Instance_getProperty;
b09da87b
JF
2235 definition.setProperty = &Instance_setProperty;
2236 definition.deleteProperty = &Instance_deleteProperty;
88c977fa 2237 definition.callAsConstructor = &Instance_callAsConstructor;
953647c1 2238 definition.finalize = &CYData::Finalize;
88c977fa 2239 Instance_ = JSClassCreate(&definition);
7ba62cfd
JF
2240
2241 definition = kJSClassDefinitionEmpty;
953647c1
JF
2242 definition.className = "Runtime";
2243 definition.getProperty = &Runtime_getProperty;
2244 Runtime_ = JSClassCreate(&definition);
2245
2246 definition = kJSClassDefinitionEmpty;
2247 //definition.getProperty = &Global_getProperty;
88c977fa 2248 JSClassRef Global(JSClassCreate(&definition));
c1582939 2249
478d4ed0 2250 JSGlobalContextRef context(JSGlobalContextCreate(Global));
ea2d184c
JF
2251 Context_ = context;
2252
579ed526 2253 JSObjectRef global(CYGetGlobalObject(context));
c1582939 2254
953647c1 2255 JSObjectSetPrototype(context, global, JSObjectMake(context, Runtime_, NULL));
579ed526 2256 CYSetProperty(context, global, CYJSString("ObjectiveC"), JSObjectMake(context, Runtime_, NULL));
953647c1 2257
b09da87b 2258 CYSetProperty(context, global, CYJSString("Functor"), JSObjectMakeConstructor(context, Functor_, &Functor_new));
f7c38a29
JF
2259 CYSetProperty(context, global, CYJSString("Pointer"), JSObjectMakeConstructor(context, Pointer_, &Pointer_new));
2260 CYSetProperty(context, global, CYJSString("Selector"), JSObjectMakeConstructor(context, Selector_, &Selector_new));
7ba62cfd 2261
f7c38a29 2262 CYSetProperty(context, global, CYJSString("objc_registerClassPair"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_registerClassPair"), &$objc_registerClassPair));
dea834b0 2263 CYSetProperty(context, global, CYJSString("objc_msgSend"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_msgSend"), &$objc_msgSend));
7ba62cfd 2264
b09da87b
JF
2265 System_ = JSObjectMake(context, NULL, NULL);
2266 CYSetProperty(context, global, CYJSString("system"), System_);
2267 CYSetProperty(context, System_, CYJSString("args"), CYJSNull(context));
579ed526 2268 //CYSetProperty(context, System_, CYJSString("global"), global);
b09da87b
JF
2269
2270 CYSetProperty(context, System_, CYJSString("print"), JSObjectMakeFunctionWithCallback(context, CYJSString("print"), &System_print));
2271
c1582939 2272 length_ = JSStringCreateWithUTF8CString("length");
b4aa79af
JF
2273 message_ = JSStringCreateWithUTF8CString("message");
2274 name_ = JSStringCreateWithUTF8CString("name");
2275 toCYON_ = JSStringCreateWithUTF8CString("toCYON");
2276 toJSON_ = JSStringCreateWithUTF8CString("toJSON");
c1582939 2277
dea834b0
JF
2278 Array_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Array")));
2279 Function_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Function")));
c1582939 2280}