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