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