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