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