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