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