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