]> git.saurik.com Git - cycript.git/blame - Library.mm
Added bridging for nlist_64, activated memory manager, and setup a remap from singlet...
[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 <unistd.h>
52
53#include <CoreFoundation/CoreFoundation.h>
54#include <CoreFoundation/CFLogUtilities.h>
55
c1582939
JF
56#include <WebKit/WebScriptObject.h>
57
58#include <sys/types.h>
59#include <sys/socket.h>
60#include <netinet/in.h>
b09da87b 61#include <sys/mman.h>
c1582939 62
8d9b5eed
JF
63#include <iostream>
64#include <ext/stdio_filebuf.h>
a2d9403c
JF
65#include <set>
66#include <map>
8d9b5eed 67
bd17e6f3
JF
68#include <cmath>
69
e5332278 70#include "Parser.hpp"
63b4c5a8 71#include "Cycript.tab.hh"
e5332278 72
ea2d184c
JF
73#undef _assert
74#undef _trace
75
c1582939 76#define _assert(test) do { \
f5e9be24
JF
77 if (!(test)) \
78 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"_assert(%s):%s(%u):%s", #test, __FILE__, __LINE__, __FUNCTION__] userInfo:nil]; \
c1582939
JF
79} while (false)
80
81#define _trace() do { \
62ca2b82 82 CFLog(kCFLogLevelNotice, CFSTR("_trace():%u"), __LINE__); \
c1582939
JF
83} while (false)
84
4cf49641
JF
85#define CYPoolTry { \
86 id _saved(nil); \
87 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
88 @try
89#define CYPoolCatch(value) \
90 @catch (NSException *error) { \
91 _saved = [error retain]; \
92 @throw; \
93 return value; \
94 } @finally { \
95 [_pool release]; \
96 if (_saved != nil) \
97 [_saved autorelease]; \
98 } \
99}
100
478d4ed0 101static JSGlobalContextRef Context_;
b09da87b 102static JSObjectRef System_;
ea2d184c 103
88c977fa
JF
104static JSClassRef Functor_;
105static JSClassRef Instance_;
106static JSClassRef Pointer_;
953647c1 107static JSClassRef Runtime_;
88c977fa 108static JSClassRef Selector_;
953647c1 109static JSClassRef Struct_;
ea2d184c 110
c1582939 111static JSObjectRef Array_;
dea834b0 112static JSObjectRef Function_;
ea2d184c 113
c1582939 114static JSStringRef length_;
b4aa79af
JF
115static JSStringRef message_;
116static JSStringRef name_;
117static JSStringRef toCYON_;
118static JSStringRef toJSON_;
ea2d184c 119
c1582939
JF
120static Class NSCFBoolean_;
121
953647c1 122static NSArray *Bridge_;
88c977fa 123
953647c1 124struct CYData {
478d4ed0 125 apr_pool_t *pool_;
953647c1
JF
126
127 virtual ~CYData() {
128 }
478d4ed0
JF
129
130 void *operator new(size_t size) {
131 apr_pool_t *pool;
132 apr_pool_create(&pool, NULL);
133 void *data(apr_palloc(pool, size));
953647c1 134 reinterpret_cast<CYData *>(data)->pool_ = pool;
478d4ed0
JF
135 return data;;
136 }
137
953647c1
JF
138 static void Finalize(JSObjectRef object) {
139 CYData *data(reinterpret_cast<CYData *>(JSObjectGetPrivate(object)));
140 data->~CYData();
141 apr_pool_destroy(data->pool_);
478d4ed0 142 }
953647c1
JF
143};
144
145struct Pointer_privateData :
146 CYData
147{
148 void *value_;
149 sig::Type type_;
478d4ed0 150
bd17e6f3
JF
151 Pointer_privateData() {
152 }
153
953647c1
JF
154 Pointer_privateData(void *value) :
155 value_(value)
156 {
478d4ed0
JF
157 }
158};
159
953647c1
JF
160struct Selector_privateData : Pointer_privateData {
161 Selector_privateData(SEL value) :
162 Pointer_privateData(value)
478d4ed0
JF
163 {
164 }
165
166 SEL GetValue() const {
167 return reinterpret_cast<SEL>(value_);
168 }
169};
170
bd17e6f3
JF
171struct Instance_privateData :
172 Pointer_privateData
173{
478d4ed0
JF
174 bool transient_;
175
953647c1
JF
176 Instance_privateData(id value, bool transient) :
177 Pointer_privateData(value)
478d4ed0
JF
178 {
179 }
180
953647c1 181 virtual ~Instance_privateData() {
478d4ed0
JF
182 if (!transient_)
183 [GetValue() release];
184 }
185
186 id GetValue() const {
187 return reinterpret_cast<id>(value_);
188 }
189};
190
bd17e6f3
JF
191namespace sig {
192
193void Copy(apr_pool_t *pool, Type &lhs, Type &rhs);
194
195void Copy(apr_pool_t *pool, Element &lhs, Element &rhs) {
196 lhs.name = apr_pstrdup(pool, rhs.name);
197 if (rhs.type == NULL)
198 lhs.type = NULL;
199 else {
200 lhs.type = new(pool) Type;
201 Copy(pool, *lhs.type, *rhs.type);
202 }
203 lhs.offset = rhs.offset;
204}
205
206void Copy(apr_pool_t *pool, Signature &lhs, Signature &rhs) {
207 size_t count(rhs.count);
208 lhs.count = count;
209 lhs.elements = new(pool) Element[count];
210 for (size_t index(0); index != count; ++index)
211 Copy(pool, lhs.elements[index], rhs.elements[index]);
212}
213
214void Copy(apr_pool_t *pool, Type &lhs, Type &rhs) {
215 lhs.primitive = rhs.primitive;
216 lhs.name = apr_pstrdup(pool, rhs.name);
217 lhs.flags = rhs.flags;
218
219 if (sig::IsAggregate(rhs.primitive))
220 Copy(pool, lhs.data.signature, rhs.data.signature);
221 else {
222 if (rhs.data.data.type != NULL) {
223 lhs.data.data.type = new(pool) Type;
224 Copy(pool, *lhs.data.data.type, *rhs.data.data.type);
225 }
226
227 lhs.data.data.size = rhs.data.data.size;
228 }
229}
230
231void Copy(apr_pool_t *pool, ffi_type &lhs, ffi_type &rhs) {
232 lhs.size = rhs.size;
233 lhs.alignment = rhs.alignment;
234 lhs.type = rhs.type;
235 if (rhs.elements == NULL)
236 lhs.elements = NULL;
237 else {
238 size_t count(0);
239 while (rhs.elements[count] != NULL)
240 ++count;
241
242 lhs.elements = new(pool) ffi_type *[count + 1];
243 lhs.elements[count] = NULL;
244
245 for (size_t index(0); index != count; ++index) {
246 // XXX: if these are libffi native then you can just take them
247 ffi_type *ffi(new(pool) ffi_type);
248 lhs.elements[index] = ffi;
249 sig::Copy(pool, *ffi, *rhs.elements[index]);
250 }
251 }
252}
253
254}
255
f33b048a
JF
256struct CStringMapLess :
257 std::binary_function<const char *, const char *, bool>
258{
259 _finline bool operator ()(const char *lhs, const char *rhs) const {
260 return strcmp(lhs, rhs) < 0;
261 }
262};
263
bd17e6f3
JF
264struct Type_privateData {
265 sig::Type type_;
266 ffi_type ffi_;
bd17e6f3
JF
267
268 Type_privateData(apr_pool_t *pool, sig::Type *type, ffi_type *ffi) {
269 sig::Copy(pool, type_, *type);
270 sig::Copy(pool, ffi_, *ffi);
bd17e6f3
JF
271 }
272};
273
274struct Struct_privateData :
275 Pointer_privateData
276{
277 JSObjectRef owner_;
278 Type_privateData *type_;
279
280 Struct_privateData() {
281 }
282};
283
bd17e6f3
JF
284typedef std::map<const char *, Type_privateData *, CStringMapLess> TypeMap;
285static TypeMap Types_;
286
287JSObjectRef CYMakeStruct(JSContextRef context, void *data, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
288 Struct_privateData *internal(new Struct_privateData());
289 apr_pool_t *pool(internal->pool_);
290 Type_privateData *typical(new(pool) Type_privateData(pool, type, ffi));
291 internal->type_ = typical;
292
293 if (owner != NULL) {
294 internal->owner_ = owner;
295 internal->value_ = data;
296 } else {
297 internal->owner_ = NULL;
298
299 size_t size(typical->ffi_.size);
300 void *copy(apr_palloc(internal->pool_, size));
301 memcpy(copy, data, size);
302 internal->value_ = copy;
303 }
304
bd17e6f3
JF
305 return JSObjectMake(context, Struct_, internal);
306}
307
f33b048a 308void Structor_(apr_pool_t *pool, const char *name, const char *types, sig::Type *type) {
d63c39cc
JF
309 if (name == NULL)
310 return;
311
f33b048a
JF
312 CYPoolTry {
313 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:2] objectForKey:[NSString stringWithUTF8String:name]]) {
314 switch ([[entry objectAtIndex:0] intValue]) {
315 case 0:
316 static CYPool Pool_;
317 sig::Parse(Pool_, &type->data.signature, [[entry objectAtIndex:1] UTF8String], &Structor_);
318 break;
319 }
320 }
321 } CYPoolCatch()
322}
323
324struct Functor_privateData :
325 Pointer_privateData
326{
327 sig::Signature signature_;
328 ffi_cif cif_;
329
330 Functor_privateData(const char *type, void (*value)()) :
331 Pointer_privateData(reinterpret_cast<void *>(value))
332 {
333 sig::Parse(pool_, &signature_, type, &Structor_);
334 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature_, &cif_);
335 }
336};
337
338struct ffoData :
339 Functor_privateData
340{
341 JSContextRef context_;
342 JSObjectRef function_;
343
344 ffoData(const char *type) :
345 Functor_privateData(type, NULL)
346 {
347 }
348};
349
4cf49641 350JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
478d4ed0
JF
351 if (!transient)
352 object = [object retain];
953647c1 353 Instance_privateData *data(new Instance_privateData(object, transient));
478d4ed0
JF
354 return JSObjectMake(context, Instance_, data);
355}
356
357const char *CYPoolCString(apr_pool_t *pool, NSString *value) {
358 if (pool == NULL)
359 return [value UTF8String];
360 else {
361 size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
362 char *string(new(pool) char[size]);
363 if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
4afefdd9 364 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:@"[NSString getCString:maxLength:encoding:] == NO" userInfo:nil];
478d4ed0
JF
365 return string;
366 }
b09da87b
JF
367}
368
369JSValueRef CYCastJSValue(JSContextRef context, bool value) {
370 return JSValueMakeBoolean(context, value);
371}
372
373JSValueRef CYCastJSValue(JSContextRef context, double value) {
374 return JSValueMakeNumber(context, value);
375}
376
377#define CYCastJSValue_(Type_) \
378 JSValueRef CYCastJSValue(JSContextRef context, Type_ value) { \
379 return JSValueMakeNumber(context, static_cast<double>(value)); \
380 }
381
382CYCastJSValue_(int)
383CYCastJSValue_(unsigned int)
384CYCastJSValue_(long int)
385CYCastJSValue_(long unsigned int)
386CYCastJSValue_(long long int)
387CYCastJSValue_(long long unsigned int)
388
389JSValueRef CYJSUndefined(JSContextRef context) {
390 return JSValueMakeUndefined(context);
0c862573
JF
391}
392
283e7e33
JF
393size_t CYCastIndex(const char *value) {
394 if (value[0] == '0') {
395 if (value[1] == '\0')
396 return 0;
397 } else {
398 char *end;
399 size_t index(strtoul(value, &end, 10));
400 if (value + strlen(value) == end)
401 return index;
402 }
403
404 return _not(size_t);
405}
406
407size_t CYCastIndex(NSString *value) {
408 return CYCastIndex([value UTF8String]);
409}
410
107e3ed0 411@interface NSMethodSignature (Cycript)
7ba62cfd
JF
412- (NSString *) _typeString;
413@end
414
107e3ed0 415@interface NSObject (Cycript)
b4aa79af
JF
416
417- (JSType) cy$JSType;
418
419- (NSObject *) cy$toJSON:(NSString *)key;
420- (NSString *) cy$toCYON;
f33b048a 421- (NSString *) cy$toKey;
b4aa79af 422
4cf49641 423- (JSValueRef) cy$JSValueInContext:(JSContextRef)context transient:(bool)transient;
b4aa79af 424
cc103044
JF
425- (NSObject *) cy$getProperty:(NSString *)name;
426- (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
427- (bool) cy$deleteProperty:(NSString *)name;
b4aa79af 428
c1582939
JF
429@end
430
107e3ed0 431@interface NSString (Cycript)
88c977fa
JF
432- (void *) cy$symbol;
433@end
434
107e3ed0 435@interface NSNumber (Cycript)
88c977fa
JF
436- (void *) cy$symbol;
437@end
438
4afefdd9
JF
439struct PropertyAttributes {
440 CYPool pool_;
441
442 const char *name;
443
444 const char *variable;
445
446 const char *getter_;
447 const char *setter_;
448
449 bool readonly;
450 bool copy;
451 bool retain;
452 bool nonatomic;
453 bool dynamic;
454 bool weak;
455 bool garbage;
456
457 PropertyAttributes(objc_property_t property) :
458 variable(NULL),
459 getter_(NULL),
460 setter_(NULL),
461 readonly(false),
462 copy(false),
463 retain(false),
464 nonatomic(false),
465 dynamic(false),
466 weak(false),
467 garbage(false)
468 {
469 name = property_getName(property);
470 const char *attributes(property_getAttributes(property));
471
472 for (char *state, *token(apr_strtok(apr_pstrdup(pool_, attributes), ",", &state)); token != NULL; token = apr_strtok(NULL, ",", &state)) {
473 switch (*token) {
474 case 'R': readonly = true; break;
475 case 'C': copy = true; break;
476 case '&': retain = true; break;
477 case 'N': nonatomic = true; break;
478 case 'G': getter_ = token + 1; break;
479 case 'S': setter_ = token + 1; break;
480 case 'V': variable = token + 1; break;
481 }
482 }
483
484 /*if (variable == NULL) {
485 variable = property_getName(property);
486 size_t size(strlen(variable));
487 char *name(new(pool_) char[size + 2]);
488 name[0] = '_';
489 memcpy(name + 1, variable, size);
490 name[size + 1] = '\0';
491 variable = name;
492 }*/
493 }
494
495 const char *Getter() {
496 if (getter_ == NULL)
497 getter_ = apr_pstrdup(pool_, name);
498 return getter_;
499 }
500
501 const char *Setter() {
502 if (setter_ == NULL && !readonly) {
503 size_t length(strlen(name));
504
505 char *temp(new(pool_) char[length + 5]);
506 temp[0] = 's';
507 temp[1] = 'e';
508 temp[2] = 't';
509
510 if (length != 0) {
511 temp[3] = toupper(name[0]);
512 memcpy(temp + 4, name + 1, length - 1);
513 }
514
515 temp[length + 3] = ':';
516 temp[length + 4] = '\0';
517 setter_ = temp;
518 }
519
520 return setter_;
521 }
522
523};
524
107e3ed0 525@implementation NSObject (Cycript)
62ca2b82 526
b4aa79af
JF
527- (JSType) cy$JSType {
528 return kJSTypeObject;
6b8a9500
JF
529}
530
b4aa79af 531- (NSObject *) cy$toJSON:(NSString *)key {
62ca2b82
JF
532 return [self description];
533}
534
b4aa79af
JF
535- (NSString *) cy$toCYON {
536 return [[self cy$toJSON:@""] cy$toCYON];
537}
538
f33b048a
JF
539- (NSString *) cy$toKey {
540 return [self cy$toCYON];
541}
542
4cf49641
JF
543- (JSValueRef) cy$JSValueInContext:(JSContextRef)context transient:(bool)transient {
544 return CYMakeInstance(context, self, transient);
ea2d184c
JF
545}
546
cc103044 547- (NSObject *) cy$getProperty:(NSString *)name {
4afefdd9
JF
548 /*if (![name isEqualToString:@"prototype"])
549 NSLog(@"get:%@", name);*/
cc103044
JF
550 return nil;
551}
552
553- (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
4afefdd9 554 //NSLog(@"set:%@", name);
cc103044
JF
555 return false;
556}
557
558- (bool) cy$deleteProperty:(NSString *)name {
4afefdd9 559 //NSLog(@"delete:%@", name);
cc103044
JF
560 return false;
561}
562
62ca2b82 563@end
c1582939 564
107e3ed0 565@implementation WebUndefined (Cycript)
62ca2b82 566
b4aa79af
JF
567- (JSType) cy$JSType {
568 return kJSTypeUndefined;
569}
570
571- (NSObject *) cy$toJSON:(NSString *)key {
572 return self;
6b8a9500
JF
573}
574
b4aa79af 575- (NSString *) cy$toCYON {
c1582939 576 return @"undefined";
62ca2b82
JF
577}
578
4cf49641 579- (JSValueRef) cy$JSValueInContext:(JSContextRef)context transient:(bool)transient {
b09da87b 580 return CYJSUndefined(context);
62ca2b82
JF
581}
582
583@end
c1582939 584
478d4ed0
JF
585@implementation NSNull (Cycript)
586
b4aa79af
JF
587- (JSType) cy$JSType {
588 return kJSTypeNull;
589}
590
591- (NSObject *) cy$toJSON:(NSString *)key {
592 return self;
593}
594
595- (NSString *) cy$toCYON {
478d4ed0
JF
596 return @"null";
597}
598
599@end
600
107e3ed0 601@implementation NSArray (Cycript)
62ca2b82 602
b4aa79af 603- (NSString *) cy$toCYON {
c1582939
JF
604 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
605 [json appendString:@"["];
606
607 bool comma(false);
62ca2b82 608 for (id object in self) {
c1582939
JF
609 if (comma)
610 [json appendString:@","];
611 else
612 comma = true;
b4aa79af
JF
613 if ([object cy$JSType] != kJSTypeUndefined)
614 [json appendString:[object cy$toCYON]];
6b8a9500
JF
615 else {
616 [json appendString:@","];
617 comma = false;
618 }
c1582939
JF
619 }
620
621 [json appendString:@"]"];
622 return json;
62ca2b82
JF
623}
624
cc103044 625- (NSObject *) cy$getProperty:(NSString *)name {
4afefdd9
JF
626 if ([name isEqualToString:@"length"])
627 return [NSNumber numberWithUnsignedInteger:[self count]];
628
283e7e33
JF
629 size_t index(CYCastIndex(name));
630 if (index == _not(size_t) || index >= [self count])
cc103044
JF
631 return [super cy$getProperty:name];
632 else
633 return [self objectAtIndex:index];
634}
635
636@end
637
638@implementation NSMutableArray (Cycript)
639
640- (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
283e7e33
JF
641 size_t index(CYCastIndex(name));
642 if (index == _not(size_t) || index >= [self count])
cc103044
JF
643 return [super cy$setProperty:name to:value];
644 else {
b6ea08b6 645 [self replaceObjectAtIndex:index withObject:(value ?: [NSNull null])];
cc103044
JF
646 return true;
647 }
648}
649
650- (bool) cy$deleteProperty:(NSString *)name {
283e7e33
JF
651 size_t index(CYCastIndex(name));
652 if (index == _not(size_t) || index >= [self count])
cc103044
JF
653 return [super cy$deleteProperty:name];
654 else {
655 [self removeObjectAtIndex:index];
656 return true;
657 }
658}
659
62ca2b82
JF
660@end
661
107e3ed0 662@implementation NSDictionary (Cycript)
62ca2b82 663
b4aa79af 664- (NSString *) cy$toCYON {
62ca2b82 665 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
f33b048a 666 [json appendString:@"{"];
62ca2b82
JF
667
668 bool comma(false);
669 for (id key in self) {
670 if (comma)
671 [json appendString:@","];
672 else
673 comma = true;
f33b048a 674 [json appendString:[key cy$toKey]];
62ca2b82
JF
675 [json appendString:@":"];
676 NSObject *object([self objectForKey:key]);
b4aa79af 677 [json appendString:[object cy$toCYON]];
62ca2b82
JF
678 }
679
f33b048a 680 [json appendString:@"}"];
62ca2b82
JF
681 return json;
682}
683
cc103044
JF
684- (NSObject *) cy$getProperty:(NSString *)name {
685 return [self objectForKey:name];
686}
687
688@end
689
690@implementation NSMutableDictionary (Cycript)
691
692- (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
b6ea08b6 693 [self setObject:(value ?: [NSNull null]) forKey:name];
cc103044
JF
694 return true;
695}
696
697- (bool) cy$deleteProperty:(NSString *)name {
698 if ([self objectForKey:name] == nil)
699 return false;
700 else {
701 [self removeObjectForKey:name];
702 return true;
703 }
704}
705
62ca2b82 706@end
c1582939 707
107e3ed0 708@implementation NSNumber (Cycript)
62ca2b82 709
b4aa79af
JF
710- (JSType) cy$JSType {
711 // XXX: this just seems stupid
712 return [self class] == NSCFBoolean_ ? kJSTypeBoolean : kJSTypeNumber;
713}
714
715- (NSObject *) cy$toJSON:(NSString *)key {
716 return self;
717}
718
719- (NSString *) cy$toCYON {
720 return [self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false";
62ca2b82
JF
721}
722
4cf49641 723- (JSValueRef) cy$JSValueInContext:(JSContextRef)context transient:(bool)transient {
b4aa79af 724 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, [self boolValue]);
62ca2b82
JF
725}
726
88c977fa
JF
727- (void *) cy$symbol {
728 return [self pointerValue];
729}
730
62ca2b82 731@end
c1582939 732
107e3ed0 733@implementation NSString (Cycript)
62ca2b82 734
b4aa79af
JF
735- (JSType) cy$JSType {
736 return kJSTypeString;
737}
738
739- (NSObject *) cy$toJSON:(NSString *)key {
740 return self;
741}
742
743- (NSString *) cy$toCYON {
f33b048a 744 // XXX: this should use the better code from Output.cpp
c1582939
JF
745 CFMutableStringRef json(CFStringCreateMutableCopy(kCFAllocatorDefault, 0, (CFStringRef) self));
746
c1582939
JF
747 CFStringFindAndReplace(json, CFSTR("\\"), CFSTR("\\\\"), CFRangeMake(0, CFStringGetLength(json)), 0);
748 CFStringFindAndReplace(json, CFSTR("\""), CFSTR("\\\""), CFRangeMake(0, CFStringGetLength(json)), 0);
749 CFStringFindAndReplace(json, CFSTR("\t"), CFSTR("\\t"), CFRangeMake(0, CFStringGetLength(json)), 0);
750 CFStringFindAndReplace(json, CFSTR("\r"), CFSTR("\\r"), CFRangeMake(0, CFStringGetLength(json)), 0);
751 CFStringFindAndReplace(json, CFSTR("\n"), CFSTR("\\n"), CFRangeMake(0, CFStringGetLength(json)), 0);
752
753 CFStringInsert(json, 0, CFSTR("\""));
754 CFStringAppend(json, CFSTR("\""));
755
62ca2b82
JF
756 return [reinterpret_cast<const NSString *>(json) autorelease];
757}
758
f33b048a
JF
759- (NSString *) cy$toKey {
760 const char *value([self UTF8String]);
761 size_t size(strlen(value));
762
283e7e33 763 if (size == 0)
f33b048a 764 goto cyon;
283e7e33
JF
765
766 if (DigitRange_[value[0]]) {
767 if (CYCastIndex(self) == _not(size_t))
f33b048a 768 goto cyon;
283e7e33
JF
769 } else {
770 if (!WordStartRange_[value[0]])
771 goto cyon;
772 for (size_t i(1); i != size; ++i)
773 if (!WordEndRange_[value[i]])
774 goto cyon;
775 }
776
f33b048a
JF
777 return self;
778
779 cyon:
780 return [self cy$toCYON];
781}
782
88c977fa 783- (void *) cy$symbol {
478d4ed0
JF
784 CYPool pool;
785 return dlsym(RTLD_DEFAULT, CYPoolCString(pool, self));
88c977fa
JF
786}
787
62ca2b82
JF
788@end
789
b21525c7 790@interface CYJSObject : NSDictionary {
62ca2b82
JF
791 JSObjectRef object_;
792 JSContextRef context_;
793}
794
795- (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
796
b4aa79af
JF
797- (NSString *) cy$toJSON:(NSString *)key;
798
62ca2b82
JF
799- (NSUInteger) count;
800- (id) objectForKey:(id)key;
801- (NSEnumerator *) keyEnumerator;
802- (void) setObject:(id)object forKey:(id)key;
803- (void) removeObjectForKey:(id)key;
804
805@end
c1582939 806
b21525c7 807@interface CYJSArray : NSArray {
c1582939
JF
808 JSObjectRef object_;
809 JSContextRef context_;
810}
811
812- (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
813
814- (NSUInteger) count;
815- (id) objectAtIndex:(NSUInteger)index;
816
817@end
818
283e7e33
JF
819CYRange DigitRange_ (0x3ff000000000000LLU, 0x000000000000000LLU); // 0-9
820CYRange WordStartRange_(0x000001000000000LLU, 0x7fffffe87fffffeLLU); // A-Za-z_$
821CYRange WordEndRange_ (0x3ff001000000000LLU, 0x7fffffe87fffffeLLU); // A-Za-z_$0-9
dea834b0 822
478d4ed0 823JSGlobalContextRef CYGetJSContext() {
ea2d184c 824 return Context_;
62ca2b82
JF
825}
826
4cf49641
JF
827#define CYTry \
828 @try
0c862573
JF
829#define CYCatch \
830 @catch (id error) { \
831 CYThrow(context, error, exception); \
832 return NULL; \
833 }
834
ea2d184c
JF
835void CYThrow(JSContextRef context, JSValueRef value);
836
b09da87b
JF
837apr_status_t CYPoolRelease_(void *data) {
838 id object(reinterpret_cast<id>(data));
839 [object release];
840 return APR_SUCCESS;
841}
842
843id CYPoolRelease(apr_pool_t *pool, id object) {
b4aa79af
JF
844 if (object == nil)
845 return nil;
846 else if (pool == NULL)
b09da87b
JF
847 return [object autorelease];
848 else {
849 apr_pool_cleanup_register(pool, object, &CYPoolRelease_, &apr_pool_cleanup_null);
850 return object;
851 }
852}
853
953647c1
JF
854CFTypeRef CYPoolRelease(apr_pool_t *pool, CFTypeRef object) {
855 return (CFTypeRef) CYPoolRelease(pool, (id) object);
856}
857
b09da87b 858id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
478d4ed0 859 if (JSValueIsObjectOfClass(context, object, Instance_)) {
953647c1 860 Instance_privateData *data(reinterpret_cast<Instance_privateData *>(JSObjectGetPrivate(object)));
478d4ed0
JF
861 return data->GetValue();
862 }
863
ea2d184c
JF
864 JSValueRef exception(NULL);
865 bool array(JSValueIsInstanceOfConstructor(context, object, Array_, &exception));
866 CYThrow(context, exception);
b09da87b
JF
867 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
868 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
62ca2b82
JF
869}
870
77e87a6c 871JSStringRef CYCopyJSString(id value) {
b09da87b 872 return value == NULL ? NULL : JSStringCreateWithCFString(reinterpret_cast<CFStringRef>([value description]));
62ca2b82
JF
873}
874
77e87a6c 875JSStringRef CYCopyJSString(const char *value) {
b09da87b 876 return value == NULL ? NULL : JSStringCreateWithUTF8CString(value);
77e87a6c
JF
877}
878
879JSStringRef CYCopyJSString(JSStringRef value) {
b09da87b 880 return value == NULL ? NULL : JSStringRetain(value);
77e87a6c
JF
881}
882
883JSStringRef CYCopyJSString(JSContextRef context, JSValueRef value) {
b09da87b
JF
884 if (JSValueIsNull(context, value))
885 return NULL;
62ca2b82 886 JSValueRef exception(NULL);
ea2d184c
JF
887 JSStringRef string(JSValueToStringCopy(context, value, &exception));
888 CYThrow(context, exception);
77e87a6c
JF
889 return string;
890}
891
cf7d4c69 892class CYJSString {
77e87a6c
JF
893 private:
894 JSStringRef string_;
895
b09da87b 896 void Clear_() {
283e7e33
JF
897 if (string_ != NULL)
898 JSStringRelease(string_);
b09da87b
JF
899 }
900
77e87a6c 901 public:
b09da87b
JF
902 CYJSString(const CYJSString &rhs) :
903 string_(CYCopyJSString(rhs.string_))
904 {
905 }
906
77e87a6c 907 template <typename Arg0_>
b09da87b
JF
908 CYJSString(Arg0_ arg0) :
909 string_(CYCopyJSString(arg0))
910 {
77e87a6c
JF
911 }
912
913 template <typename Arg0_, typename Arg1_>
b09da87b
JF
914 CYJSString(Arg0_ arg0, Arg1_ arg1) :
915 string_(CYCopyJSString(arg0, arg1))
916 {
917 }
918
919 CYJSString &operator =(const CYJSString &rhs) {
920 Clear_();
921 string_ = CYCopyJSString(rhs.string_);
922 return *this;
77e87a6c
JF
923 }
924
cf7d4c69 925 ~CYJSString() {
b09da87b
JF
926 Clear_();
927 }
928
929 void Clear() {
930 Clear_();
931 string_ = NULL;
77e87a6c
JF
932 }
933
934 operator JSStringRef() const {
935 return string_;
936 }
937};
938
939CFStringRef CYCopyCFString(JSStringRef value) {
940 return JSStringCopyCFString(kCFAllocatorDefault, value);
941}
942
943CFStringRef CYCopyCFString(JSContextRef context, JSValueRef value) {
cf7d4c69 944 return CYCopyCFString(CYJSString(context, value));
c1582939
JF
945}
946
bd17e6f3
JF
947double CYCastDouble(const char *value, size_t size) {
948 char *end;
949 double number(strtod(value, &end));
950 if (end != value + size)
951 return NAN;
952 return number;
953}
954
955double CYCastDouble(const char *value) {
956 return CYCastDouble(value, strlen(value));
957}
958
f610e1a0 959double CYCastDouble(JSContextRef context, JSValueRef value) {
0c862573
JF
960 JSValueRef exception(NULL);
961 double number(JSValueToNumber(context, value, &exception));
962 CYThrow(context, exception);
f610e1a0
JF
963 return number;
964}
965
966CFNumberRef CYCopyCFNumber(JSContextRef context, JSValueRef value) {
967 double number(CYCastDouble(context, value));
0c862573
JF
968 return CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &number);
969}
970
953647c1
JF
971CFStringRef CYCopyCFString(const char *value) {
972 return CFStringCreateWithCString(kCFAllocatorDefault, value, kCFStringEncodingUTF8);
973}
974
975NSString *CYCastNSString(apr_pool_t *pool, const char *value) {
976 return (NSString *) CYPoolRelease(pool, CYCopyCFString(value));
977}
978
b09da87b 979NSString *CYCastNSString(apr_pool_t *pool, JSStringRef value) {
953647c1 980 return (NSString *) CYPoolRelease(pool, CYCopyCFString(value));
b09da87b
JF
981}
982
983bool CYCastBool(JSContextRef context, JSValueRef value) {
984 return JSValueToBoolean(context, value);
62ca2b82
JF
985}
986
b09da87b
JF
987CFTypeRef CYCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value, bool cast) {
988 CFTypeRef object;
989 bool copy;
990
f610e1a0 991 switch (JSType type = JSValueGetType(context, value)) {
c1582939 992 case kJSTypeUndefined:
b09da87b
JF
993 object = [WebUndefined undefined];
994 copy = false;
995 break;
996
c1582939 997 case kJSTypeNull:
b09da87b
JF
998 return NULL;
999 break;
1000
c1582939 1001 case kJSTypeBoolean:
b09da87b
JF
1002 object = CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse;
1003 copy = false;
1004 break;
1005
0c862573 1006 case kJSTypeNumber:
b09da87b
JF
1007 object = CYCopyCFNumber(context, value);
1008 copy = true;
1009 break;
1010
62ca2b82 1011 case kJSTypeString:
b09da87b
JF
1012 object = CYCopyCFString(context, value);
1013 copy = true;
1014 break;
1015
c1582939 1016 case kJSTypeObject:
b09da87b
JF
1017 // XXX: this might could be more efficient
1018 object = (CFTypeRef) CYCastNSObject(pool, context, (JSObjectRef) value);
1019 copy = false;
1020 break;
1021
c1582939 1022 default:
f5e9be24 1023 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"JSValueGetType() == 0x%x", type] userInfo:nil];
b09da87b 1024 break;
c1582939 1025 }
b09da87b
JF
1026
1027 if (cast != copy)
1028 return object;
1029 else if (copy)
953647c1 1030 return CYPoolRelease(pool, object);
b09da87b
JF
1031 else
1032 return CFRetain(object);
1033}
1034
1035CFTypeRef CYCastCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1036 return CYCFType(pool, context, value, true);
1037}
1038
1039CFTypeRef CYCopyCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1040 return CYCFType(pool, context, value, false);
c1582939
JF
1041}
1042
62ca2b82 1043NSArray *CYCastNSArray(JSPropertyNameArrayRef names) {
b09da87b 1044 CYPool pool;
62ca2b82
JF
1045 size_t size(JSPropertyNameArrayGetCount(names));
1046 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1047 for (size_t index(0); index != size; ++index)
b09da87b 1048 [array addObject:CYCastNSString(pool, JSPropertyNameArrayGetNameAtIndex(names, index))];
62ca2b82
JF
1049 return array;
1050}
1051
b09da87b
JF
1052id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1053 return reinterpret_cast<const NSObject *>(CYCastCFType(pool, context, value));
c1582939
JF
1054}
1055
ea2d184c 1056void CYThrow(JSContextRef context, JSValueRef value) {
62ca2b82
JF
1057 if (value == NULL)
1058 return;
b09da87b
JF
1059 @throw CYCastNSObject(NULL, context, value);
1060}
1061
1062JSValueRef CYJSNull(JSContextRef context) {
1063 return JSValueMakeNull(context);
1064}
1065
1066JSValueRef CYCastJSValue(JSContextRef context, JSStringRef value) {
1067 return value == NULL ? CYJSNull(context) : JSValueMakeString(context, value);
1068}
1069
1070JSValueRef CYCastJSValue(JSContextRef context, const char *value) {
1071 return CYCastJSValue(context, CYJSString(value));
62ca2b82
JF
1072}
1073
d63c39cc 1074JSValueRef CYCastJSValue(JSContextRef context, id value, bool transient = false) {
4cf49641 1075 return value == nil ? CYJSNull(context) : [value cy$JSValueInContext:context transient:transient];
62ca2b82
JF
1076}
1077
dea834b0
JF
1078JSObjectRef CYCastJSObject(JSContextRef context, JSValueRef value) {
1079 JSValueRef exception(NULL);
1080 JSObjectRef object(JSValueToObject(context, value, &exception));
1081 CYThrow(context, exception);
1082 return object;
1083}
1084
bd17e6f3
JF
1085JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, size_t index) {
1086 JSValueRef exception(NULL);
1087 JSValueRef value(JSObjectGetPropertyAtIndex(context, object, index, &exception));
1088 CYThrow(context, exception);
1089 return value;
1090}
1091
dea834b0
JF
1092JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, JSStringRef name) {
1093 JSValueRef exception(NULL);
1094 JSValueRef value(JSObjectGetProperty(context, object, name, &exception));
1095 CYThrow(context, exception);
1096 return value;
1097}
1098
1099void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef value) {
1100 JSValueRef exception(NULL);
1101 JSObjectSetProperty(context, object, name, value, kJSPropertyAttributeNone, &exception);
1102 CYThrow(context, exception);
1103}
1104
30ddc20c 1105void CYThrow(JSContextRef context, id error, JSValueRef *exception) {
4cf49641
JF
1106 if (exception == NULL)
1107 throw error;
7ba62cfd
JF
1108 *exception = CYCastJSValue(context, error);
1109}
1110
b4aa79af
JF
1111JSValueRef CYCallAsFunction(JSContextRef context, JSObjectRef function, JSObjectRef _this, size_t count, JSValueRef arguments[]) {
1112 JSValueRef exception(NULL);
1113 JSValueRef value(JSObjectCallAsFunction(context, function, _this, count, arguments, &exception));
1114 CYThrow(context, exception);
1115 return value;
1116}
1117
1118bool CYIsCallable(JSContextRef context, JSValueRef value) {
1119 // XXX: this isn't actually correct
1120 return value != NULL && JSValueIsObject(context, value);
1121}
1122
b21525c7 1123@implementation CYJSObject
62ca2b82
JF
1124
1125- (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
1126 if ((self = [super init]) != nil) {
1127 object_ = object;
1128 context_ = context;
1129 } return self;
1130}
1131
b4aa79af
JF
1132- (NSObject *) cy$toJSON:(NSString *)key {
1133 JSValueRef toJSON(CYGetProperty(context_, object_, toJSON_));
1134 if (!CYIsCallable(context_, toJSON))
1135 return [super cy$toJSON:key];
1136 else {
1137 JSValueRef arguments[1] = {CYCastJSValue(context_, key)};
1138 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toJSON, object_, 1, arguments));
1139 // XXX: do I really want an NSNull here?!
1140 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1141 }
1142}
1143
1144- (NSString *) cy$toCYON {
1145 JSValueRef toCYON(CYGetProperty(context_, object_, toCYON_));
1146 if (!CYIsCallable(context_, toCYON))
1147 return [super cy$toCYON];
1148 else {
1149 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toCYON, object_, 0, NULL));
1150 return CYCastNSString(NULL, CYJSString(context_, value));
1151 }
1152}
1153
62ca2b82
JF
1154- (NSUInteger) count {
1155 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1156 size_t size(JSPropertyNameArrayGetCount(names));
1157 JSPropertyNameArrayRelease(names);
1158 return size;
1159}
1160
1161- (id) objectForKey:(id)key {
478d4ed0 1162 return CYCastNSObject(NULL, context_, CYGetProperty(context_, object_, CYJSString(key))) ?: [NSNull null];
62ca2b82
JF
1163}
1164
1165- (NSEnumerator *) keyEnumerator {
1166 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1167 NSEnumerator *enumerator([CYCastNSArray(names) objectEnumerator]);
1168 JSPropertyNameArrayRelease(names);
1169 return enumerator;
1170}
1171
1172- (void) setObject:(id)object forKey:(id)key {
dea834b0 1173 CYSetProperty(context_, object_, CYJSString(key), CYCastJSValue(context_, object));
62ca2b82
JF
1174}
1175
1176- (void) removeObjectForKey:(id)key {
1177 JSValueRef exception(NULL);
f610e1a0 1178 // XXX: this returns a bool... throw exception, or ignore?
cf7d4c69 1179 JSObjectDeleteProperty(context_, object_, CYJSString(key), &exception);
62ca2b82
JF
1180 CYThrow(context_, exception);
1181}
1182
1183@end
1184
b21525c7 1185@implementation CYJSArray
c1582939
JF
1186
1187- (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
1188 if ((self = [super init]) != nil) {
1189 object_ = object;
1190 context_ = context;
1191 } return self;
1192}
1193
1194- (NSUInteger) count {
dea834b0 1195 return CYCastDouble(context_, CYGetProperty(context_, object_, length_));
c1582939
JF
1196}
1197
1198- (id) objectAtIndex:(NSUInteger)index {
62ca2b82
JF
1199 JSValueRef exception(NULL);
1200 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
1201 CYThrow(context_, exception);
478d4ed0 1202 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
c1582939
JF
1203}
1204
1205@end
1206
b4aa79af 1207CFStringRef CYCopyCYONString(JSContextRef context, JSValueRef value, JSValueRef *exception) {
4cf49641
JF
1208 CYTry {
1209 CYPoolTry {
b4aa79af
JF
1210 id object(CYCastNSObject(NULL, context, value) ?: [NSNull null]);
1211 return reinterpret_cast<CFStringRef>([[object cy$toCYON] retain]);
4cf49641
JF
1212 } CYPoolCatch(NULL)
1213 } CYCatch
c1582939
JF
1214}
1215
b4aa79af
JF
1216const char *CYPoolCYONString(apr_pool_t *pool, JSContextRef context, JSValueRef value, JSValueRef *exception) {
1217 if (NSString *json = (NSString *) CYCopyCYONString(context, value, exception)) {
4cf49641
JF
1218 const char *string(CYPoolCString(pool, json));
1219 [json release];
1220 return string;
1221 } else return NULL;
478d4ed0
JF
1222}
1223
b09da87b 1224static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
4afefdd9
JF
1225 CYPool pool;
1226
4cf49641 1227 CYTry {
cc103044 1228 NSString *self(CYCastNSObject(pool, context, object));
b09da87b 1229 NSString *name(CYCastNSString(pool, property));
4afefdd9
JF
1230
1231 CYPoolTry {
1232 if (NSObject *data = [self cy$getProperty:name])
1233 return CYCastJSValue(context, data);
1234 } CYPoolCatch(NULL)
1235
1236 if (objc_property_t property = class_getProperty(object_getClass(self), [name UTF8String])) {
1237 PropertyAttributes attributes(property);
1238 SEL sel(sel_registerName(attributes.Getter()));
1239 return CYSendMessage(pool, context, self, sel, 0, NULL, exception);
1240 }
1241
1242 return NULL;
f610e1a0 1243 } CYCatch
c1582939
JF
1244}
1245
b09da87b 1246static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
4afefdd9
JF
1247 CYPool pool;
1248
4cf49641 1249 CYTry {
cc103044 1250 NSString *self(CYCastNSObject(pool, context, object));
b09da87b 1251 NSString *name(CYCastNSString(pool, property));
cc103044 1252 NSString *data(CYCastNSObject(pool, context, value));
4afefdd9
JF
1253
1254 CYPoolTry {
1255 if ([self cy$setProperty:name to:data])
1256 return true;
1257 } CYPoolCatch(NULL)
1258
1259 if (objc_property_t property = class_getProperty(object_getClass(self), [name UTF8String])) {
1260 PropertyAttributes attributes(property);
1261 if (const char *setter = attributes.Setter()) {
1262 SEL sel(sel_registerName(setter));
1263 JSValueRef arguments[1] = {value};
1264 CYSendMessage(pool, context, self, sel, 1, arguments, exception);
1265 return true;
1266 }
1267 }
1268
1269 return false;
b09da87b
JF
1270 } CYCatch
1271}
1272
1273static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
4cf49641 1274 CYTry {
4afefdd9
JF
1275 CYPoolTry {
1276 NSString *self(CYCastNSObject(NULL, context, object));
1277 NSString *name(CYCastNSString(NULL, property));
1278 return [self cy$deleteProperty:name];
1279 } CYPoolCatch(NULL)
b09da87b
JF
1280 } CYCatch
1281}
1282
b09da87b 1283static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
4cf49641 1284 CYTry {
953647c1 1285 Instance_privateData *data(reinterpret_cast<Instance_privateData *>(JSObjectGetPrivate(object)));
4cf49641 1286 return CYMakeInstance(context, [data->GetValue() alloc], true);
0c862573
JF
1287 } CYCatch
1288}
1289
dea834b0 1290JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
953647c1 1291 Selector_privateData *data(new Selector_privateData(sel));
dea834b0
JF
1292 return JSObjectMake(context, Selector_, data);
1293}
1294
1295JSObjectRef CYMakePointer(JSContextRef context, void *pointer) {
953647c1 1296 Pointer_privateData *data(new Pointer_privateData(pointer));
dea834b0
JF
1297 return JSObjectMake(context, Pointer_, data);
1298}
1299
b09da87b 1300JSObjectRef CYMakeFunctor(JSContextRef context, void (*function)(), const char *type) {
953647c1 1301 Functor_privateData *data(new Functor_privateData(type, function));
88c977fa
JF
1302 return JSObjectMake(context, Functor_, data);
1303}
1304
bd17e6f3
JF
1305const char *CYPoolCString(apr_pool_t *pool, JSStringRef value, size_t *length = NULL) {
1306 if (pool == NULL) {
1307 const char *string([CYCastNSString(NULL, value) UTF8String]);
1308 if (length != NULL)
1309 *length = strlen(string);
1310 return string;
1311 } else {
478d4ed0
JF
1312 size_t size(JSStringGetMaximumUTF8CStringSize(value));
1313 char *string(new(pool) char[size]);
1314 JSStringGetUTF8CString(value, string, size);
bd17e6f3
JF
1315 // XXX: this is ironic
1316 if (length != NULL)
1317 *length = strlen(string);
478d4ed0
JF
1318 return string;
1319 }
7ba62cfd
JF
1320}
1321
bd17e6f3
JF
1322const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value, size_t *length = NULL) {
1323 if (!JSValueIsNull(context, value))
1324 return CYPoolCString(pool, CYJSString(context, value), length);
1325 else {
1326 if (length != NULL)
1327 *length = 0;
b09da87b 1328 return NULL;
bd17e6f3 1329 }
77e87a6c
JF
1330}
1331
f610e1a0 1332// XXX: this macro is unhygenic
b21525c7 1333#define CYCastCString(context, value) ({ \
b09da87b
JF
1334 char *utf8; \
1335 if (value == NULL) \
1336 utf8 = NULL; \
478d4ed0 1337 else if (JSStringRef string = CYCopyJSString(context, value)) { \
b09da87b
JF
1338 size_t size(JSStringGetMaximumUTF8CStringSize(string)); \
1339 utf8 = reinterpret_cast<char *>(alloca(size)); \
1340 JSStringGetUTF8CString(string, utf8, size); \
1341 JSStringRelease(string); \
478d4ed0
JF
1342 } else \
1343 utf8 = NULL; \
b21525c7
JF
1344 utf8; \
1345})
1346
b09da87b 1347void *CYCastPointer_(JSContextRef context, JSValueRef value) {
b21525c7
JF
1348 switch (JSValueGetType(context, value)) {
1349 case kJSTypeNull:
1350 return NULL;
953647c1 1351 /*case kJSTypeString:
b21525c7 1352 return dlsym(RTLD_DEFAULT, CYCastCString(context, value));
b21525c7 1353 case kJSTypeObject:
88c977fa 1354 if (JSValueIsObjectOfClass(context, value, Pointer_)) {
953647c1 1355 Pointer_privateData *data(reinterpret_cast<Pointer_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
b21525c7 1356 return data->value_;
953647c1 1357 }*/
b21525c7 1358 default:
953647c1 1359 double number(CYCastDouble(context, value));
bd17e6f3 1360 if (std::isnan(number))
953647c1
JF
1361 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"cannot convert value to pointer" userInfo:nil];
1362 return reinterpret_cast<void *>(static_cast<uintptr_t>(static_cast<long long>(number)));
7ba62cfd
JF
1363 }
1364}
1365
b09da87b
JF
1366template <typename Type_>
1367_finline Type_ CYCastPointer(JSContextRef context, JSValueRef value) {
1368 return reinterpret_cast<Type_>(CYCastPointer_(context, value));
1369}
1370
4afefdd9
JF
1371SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1372 if (JSValueIsObjectOfClass(context, value, Selector_)) {
1373 Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1374 return reinterpret_cast<SEL>(data->value_);
1375 } else
1376 return CYCastPointer<SEL>(context, value);
1377}
1378
bd17e6f3 1379void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) {
ea2d184c
JF
1380 switch (type->primitive) {
1381 case sig::boolean_P:
1382 *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
1383 break;
1384
43cb3d68 1385#define CYPoolFFI_(primitive, native) \
f610e1a0
JF
1386 case sig::primitive ## _P: \
1387 *reinterpret_cast<native *>(data) = CYCastDouble(context, value); \
1388 break;
ea2d184c 1389
43cb3d68
JF
1390 CYPoolFFI_(uchar, unsigned char)
1391 CYPoolFFI_(char, char)
1392 CYPoolFFI_(ushort, unsigned short)
1393 CYPoolFFI_(short, short)
1394 CYPoolFFI_(ulong, unsigned long)
1395 CYPoolFFI_(long, long)
1396 CYPoolFFI_(uint, unsigned int)
1397 CYPoolFFI_(int, int)
1398 CYPoolFFI_(ulonglong, unsigned long long)
1399 CYPoolFFI_(longlong, long long)
1400 CYPoolFFI_(float, float)
1401 CYPoolFFI_(double, double)
ea2d184c
JF
1402
1403 case sig::object_P:
1404 case sig::typename_P:
b09da87b 1405 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
7ba62cfd
JF
1406 break;
1407
ea2d184c 1408 case sig::selector_P:
7ba62cfd
JF
1409 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1410 break;
ea2d184c 1411
b21525c7 1412 case sig::pointer_P:
b09da87b 1413 *reinterpret_cast<void **>(data) = CYCastPointer<void *>(context, value);
b21525c7 1414 break;
ea2d184c 1415
77e87a6c 1416 case sig::string_P:
478d4ed0 1417 *reinterpret_cast<const char **>(data) = CYPoolCString(pool, context, value);
77e87a6c 1418 break;
7ba62cfd 1419
bd17e6f3
JF
1420 case sig::struct_P: {
1421 uint8_t *base(reinterpret_cast<uint8_t *>(data));
f33b048a 1422 JSObjectRef aggregate(JSValueIsObject(context, value) ? (JSObjectRef) value : NULL);
bd17e6f3 1423 for (size_t index(0); index != type->data.signature.count; ++index) {
f33b048a
JF
1424 sig::Element *element(&type->data.signature.elements[index]);
1425 ffi_type *field(ffi->elements[index]);
1426
1427 JSValueRef rhs;
1428 if (aggregate == NULL)
1429 rhs = value;
1430 else {
1431 rhs = CYGetProperty(context, aggregate, index);
1432 if (JSValueIsUndefined(context, rhs)) {
283e7e33
JF
1433 if (element->name != NULL)
1434 rhs = CYGetProperty(context, aggregate, CYJSString(element->name));
1435 else
1436 goto undefined;
1437 if (JSValueIsUndefined(context, rhs)) undefined:
f33b048a
JF
1438 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"unable to extract structure value" userInfo:nil];
1439 }
1440 }
1441
1442 CYPoolFFI(pool, context, element->type, field, base, rhs);
4e8c99fb 1443 // XXX: alignment?
f33b048a 1444 base += field->size;
bd17e6f3
JF
1445 }
1446 } break;
ea2d184c
JF
1447
1448 case sig::void_P:
1449 break;
1450
bd17e6f3 1451 default:
43cb3d68 1452 NSLog(@"CYPoolFFI(%c)\n", type->primitive);
ea2d184c
JF
1453 _assert(false);
1454 }
1455}
1456
bd17e6f3 1457JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSObjectRef owner = NULL) {
ea2d184c
JF
1458 JSValueRef value;
1459
1460 switch (type->primitive) {
1461 case sig::boolean_P:
b09da87b 1462 value = CYCastJSValue(context, *reinterpret_cast<bool *>(data));
ea2d184c
JF
1463 break;
1464
1465#define CYFromFFI_(primitive, native) \
1466 case sig::primitive ## _P: \
b09da87b 1467 value = CYCastJSValue(context, *reinterpret_cast<native *>(data)); \
ea2d184c
JF
1468 break;
1469
1470 CYFromFFI_(uchar, unsigned char)
1471 CYFromFFI_(char, char)
1472 CYFromFFI_(ushort, unsigned short)
1473 CYFromFFI_(short, short)
1474 CYFromFFI_(ulong, unsigned long)
1475 CYFromFFI_(long, long)
1476 CYFromFFI_(uint, unsigned int)
1477 CYFromFFI_(int, int)
1478 CYFromFFI_(ulonglong, unsigned long long)
1479 CYFromFFI_(longlong, long long)
1480 CYFromFFI_(float, float)
1481 CYFromFFI_(double, double)
1482
1483 case sig::object_P:
ea2d184c 1484 value = CYCastJSValue(context, *reinterpret_cast<id *>(data));
dea834b0
JF
1485 break;
1486
b09da87b 1487 case sig::typename_P:
4cf49641 1488 value = CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
b09da87b
JF
1489 break;
1490
dea834b0
JF
1491 case sig::selector_P:
1492 if (SEL sel = *reinterpret_cast<SEL *>(data))
1493 value = CYMakeSelector(context, sel);
1494 else goto null;
1495 break;
1496
1497 case sig::pointer_P:
1498 if (void *pointer = *reinterpret_cast<void **>(data))
1499 value = CYMakePointer(context, pointer);
1500 else goto null;
1501 break;
1502
1503 case sig::string_P:
f610e1a0 1504 if (char *utf8 = *reinterpret_cast<char **>(data))
b09da87b 1505 value = CYCastJSValue(context, utf8);
f610e1a0 1506 else goto null;
dea834b0 1507 break;
ea2d184c
JF
1508
1509 case sig::struct_P:
bd17e6f3
JF
1510 value = CYMakeStruct(context, data, type, ffi, owner);
1511 break;
ea2d184c
JF
1512
1513 case sig::void_P:
b09da87b 1514 value = CYJSUndefined(context);
f610e1a0
JF
1515 break;
1516
1517 null:
b09da87b 1518 value = CYJSNull(context);
ea2d184c
JF
1519 break;
1520
bd17e6f3 1521 default:
ea2d184c
JF
1522 NSLog(@"CYFromFFI(%c)\n", type->primitive);
1523 _assert(false);
1524 }
1525
1526 return value;
1527}
1528
9e20b0b7 1529bool Index_(apr_pool_t *pool, Struct_privateData *internal, JSStringRef property, ssize_t &index, uint8_t *&base) {
bd17e6f3
JF
1530 Type_privateData *typical(internal->type_);
1531
9e20b0b7
JF
1532 size_t length;
1533 const char *name(CYPoolCString(pool, property, &length));
1534 double number(CYCastDouble(name, length));
1535
f33b048a
JF
1536 size_t count(typical->type_.data.signature.count);
1537
e0dc20ec
JF
1538 if (std::isnan(number)) {
1539 if (property == NULL)
1540 return false;
9e20b0b7 1541
f33b048a
JF
1542 sig::Element *elements(typical->type_.data.signature.elements);
1543
283e7e33
JF
1544 for (size_t local(0); local != count; ++local) {
1545 sig::Element *element(&elements[local]);
1546 if (element->name != NULL && strcmp(name, element->name) == 0) {
f33b048a
JF
1547 index = local;
1548 goto base;
1549 }
283e7e33 1550 }
f33b048a 1551
9e20b0b7 1552 return false;
e0dc20ec
JF
1553 } else {
1554 index = static_cast<ssize_t>(number);
f33b048a 1555 if (index != number || index < 0 || static_cast<size_t>(index) >= count)
e0dc20ec
JF
1556 return false;
1557 }
bd17e6f3 1558
f33b048a 1559 base:
bd17e6f3
JF
1560 base = reinterpret_cast<uint8_t *>(internal->value_);
1561 for (ssize_t local(0); local != index; ++local)
9e20b0b7
JF
1562 base += typical->ffi_.elements[local]->size;
1563
1564 return true;
bd17e6f3
JF
1565}
1566
1567static JSValueRef Struct_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
f33b048a
JF
1568 CYPool pool;
1569 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
1570 Type_privateData *typical(internal->type_);
bd17e6f3 1571
f33b048a
JF
1572 ssize_t index;
1573 uint8_t *base;
bd17e6f3 1574
f33b048a
JF
1575 if (!Index_(pool, internal, property, index, base))
1576 return NULL;
bd17e6f3 1577
f33b048a 1578 CYTry {
bd17e6f3
JF
1579 return CYFromFFI(context, typical->type_.data.signature.elements[index].type, typical->ffi_.elements[index], base, object);
1580 } CYCatch
1581}
1582
1583static bool Struct_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
f33b048a
JF
1584 CYPool pool;
1585 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
1586 Type_privateData *typical(internal->type_);
bd17e6f3 1587
f33b048a
JF
1588 ssize_t index;
1589 uint8_t *base;
bd17e6f3 1590
f33b048a
JF
1591 if (!Index_(pool, internal, property, index, base))
1592 return false;
bd17e6f3 1593
f33b048a 1594 CYTry {
bd17e6f3
JF
1595 CYPoolFFI(NULL, context, typical->type_.data.signature.elements[index].type, typical->ffi_.elements[index], base, value);
1596 return true;
1597 } CYCatch
1598}
1599
f33b048a
JF
1600static void Struct_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1601 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
1602 Type_privateData *typical(internal->type_);
1603
1604 size_t count(typical->type_.data.signature.count);
1605 sig::Element *elements(typical->type_.data.signature.elements);
1606
283e7e33
JF
1607 char number[32];
1608
1609 for (size_t index(0); index != count; ++index) {
1610 const char *name;
1611 name = elements[index].name;
1612
1613 if (name == NULL) {
1614 sprintf(number, "%lu", index);
1615 name = number;
1616 }
1617
1618 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1619 }
f33b048a
JF
1620}
1621
4afefdd9 1622JSValueRef CYCallFunction(apr_pool_t *pool, JSContextRef context, size_t setups, void *setup[], size_t count, const JSValueRef *arguments, JSValueRef *exception, sig::Signature *signature, ffi_cif *cif, void (*function)()) {
4cf49641 1623 CYTry {
4afefdd9 1624 if (setups + count != signature->count - 1)
f5e9be24 1625 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to ffi function" userInfo:nil];
85a33bf5 1626
4afefdd9
JF
1627 size_t size(setups + count);
1628 void *values[size];
1629 memcpy(values, setup, sizeof(void *) * setups);
ea2d184c 1630
4afefdd9 1631 for (size_t index(setups); index != size; ++index) {
7ba62cfd 1632 sig::Element *element(&signature->elements[index + 1]);
bd17e6f3 1633 ffi_type *ffi(cif->arg_types[index]);
77e87a6c 1634 // XXX: alignment?
bd17e6f3 1635 values[index] = new(pool) uint8_t[ffi->size];
4afefdd9 1636 CYPoolFFI(pool, context, element->type, ffi, values[index], arguments[index - setups]);
7ba62cfd 1637 }
ea2d184c 1638
7ba62cfd
JF
1639 uint8_t value[cif->rtype->size];
1640 ffi_call(cif, function, value, values);
1641
bd17e6f3 1642 return CYFromFFI(context, signature->elements[0].type, cif->rtype, value);
0c862573 1643 } CYCatch
7ba62cfd 1644}
ea2d184c 1645
478d4ed0 1646void Closure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
478d4ed0
JF
1647 ffoData *data(reinterpret_cast<ffoData *>(arg));
1648
1649 JSContextRef context(data->context_);
1650
1651 size_t count(data->cif_.nargs);
1652 JSValueRef values[count];
1653
1654 for (size_t index(0); index != count; ++index)
bd17e6f3 1655 values[index] = CYFromFFI(context, data->signature_.elements[1 + index].type, data->cif_.arg_types[index], arguments[index]);
478d4ed0 1656
b4aa79af 1657 JSValueRef value(CYCallAsFunction(context, data->function_, NULL, count, values));
bd17e6f3 1658 CYPoolFFI(NULL, context, data->signature_.elements[0].type, data->cif_.rtype, result, value);
478d4ed0
JF
1659}
1660
1661JSObjectRef CYMakeFunctor(JSContextRef context, JSObjectRef function, const char *type) {
1662 // XXX: in case of exceptions this will leak
1663 ffoData *data(new ffoData(type));
1664
1665 ffi_closure *closure;
1666 _syscall(closure = (ffi_closure *) mmap(
1667 NULL, sizeof(ffi_closure),
1668 PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE,
1669 -1, 0
1670 ));
1671
1672 ffi_status status(ffi_prep_closure(closure, &data->cif_, &Closure_, data));
1673 _assert(status == FFI_OK);
1674
1675 _syscall(mprotect(closure, sizeof(*closure), PROT_READ | PROT_EXEC));
1676
1677 data->value_ = closure;
1678
1679 data->context_ = CYGetJSContext();
1680 data->function_ = function;
1681
1682 return JSObjectMake(context, Functor_, data);
1683}
1684
953647c1 1685static JSValueRef Runtime_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
4cf49641 1686 CYTry {
b09da87b
JF
1687 CYPool pool;
1688 NSString *name(CYCastNSString(pool, property));
f610e1a0 1689 if (Class _class = NSClassFromString(name))
4cf49641 1690 return CYMakeInstance(context, _class, true);
953647c1 1691 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:0] objectForKey:name])
707bcb93
JF
1692 switch ([[entry objectAtIndex:0] intValue]) {
1693 case 0:
057f943f 1694 return JSEvaluateScript(CYGetJSContext(), CYJSString([entry objectAtIndex:1]), NULL, NULL, 0, NULL);
707bcb93 1695 case 1:
478d4ed0 1696 return CYMakeFunctor(context, reinterpret_cast<void (*)()>([name cy$symbol]), CYPoolCString(pool, [entry objectAtIndex:1]));
707bcb93 1697 case 2:
bd17e6f3 1698 // XXX: this is horrendously inefficient
707bcb93 1699 sig::Signature signature;
f33b048a 1700 sig::Parse(pool, &signature, CYPoolCString(pool, [entry objectAtIndex:1]), &Structor_);
bd17e6f3
JF
1701 ffi_cif cif;
1702 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
1703 return CYFromFFI(context, signature.elements[0].type, cif.rtype, [name cy$symbol]);
707bcb93
JF
1704 }
1705 return NULL;
1706 } CYCatch
1707}
1708
04450da0
JF
1709bool stret(ffi_type *ffi_type) {
1710 return ffi_type->type == FFI_TYPE_STRUCT && (
1711 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
1712 struct_forward_array[ffi_type->size] != 0
1713 );
1714}
1715
b09da87b
JF
1716extern "C" {
1717 int *_NSGetArgc(void);
1718 char ***_NSGetArgv(void);
1719 int UIApplicationMain(int argc, char *argv[], NSString *principalClassName, NSString *delegateClassName);
1720}
1721
1722static JSValueRef System_print(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
4cf49641 1723 CYTry {
b09da87b
JF
1724 NSLog(@"%s", CYCastCString(context, arguments[0]));
1725 return CYJSUndefined(context);
1726 } CYCatch
1727}
1728
1729static JSValueRef CYApplicationMain(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
4cf49641 1730 CYTry {
b09da87b 1731 CYPool pool;
283e7e33
JF
1732
1733 int argc(CYCastDouble(context, arguments[0]));
1734 char **argv(CYCastPointer<char **>(context, arguments[1]));
1735 NSString *principal(CYCastNSObject(pool, context, arguments[2]));
1736 NSString *delegate(CYCastNSObject(pool, context, arguments[3]));
1737
1738 argc = *_NSGetArgc() - 1;
1739 argv = *_NSGetArgv() + 1;
b09da87b
JF
1740 for (int i(0); i != argc; ++i)
1741 NSLog(@"argv[%i]=%s", i, argv[i]);
283e7e33 1742
478d4ed0 1743 _pooled
283e7e33 1744 return CYCastJSValue(context, UIApplicationMain(argc, argv, principal, delegate));
b09da87b
JF
1745 } CYCatch
1746}
1747
4afefdd9 1748JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, SEL _cmd, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
7ba62cfd 1749 const char *type;
ea2d184c 1750
4afefdd9
JF
1751 Class _class(object_getClass(self));
1752 if (Method method = class_getInstanceMethod(_class, _cmd))
1753 type = method_getTypeEncoding(method);
1754 else {
1755 CYPoolTry {
1756 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
1757 if (method == nil)
1758 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"unrecognized selector %s sent to object %p", sel_getName(_cmd), self] userInfo:nil];
1759 type = CYPoolCString(pool, [method _typeString]);
1760 } CYPoolCatch(NULL)
1761 }
1762
1763 void *setup[2];
1764 setup[0] = &self;
1765 setup[1] = &_cmd;
1766
1767 sig::Signature signature;
f33b048a 1768 sig::Parse(pool, &signature, type, &Structor_);
4afefdd9
JF
1769
1770 ffi_cif cif;
1771 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
1772
1773 void (*function)() = stret(cif.rtype) ? reinterpret_cast<void (*)()>(&objc_msgSend_stret) : reinterpret_cast<void (*)()>(&objc_msgSend);
1774 return CYCallFunction(pool, context, 2, setup, count, arguments, exception, &signature, &cif, function);
1775}
1776
1777static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
478d4ed0
JF
1778 CYPool pool;
1779
4afefdd9
JF
1780 id self;
1781 SEL _cmd;
1782
4cf49641 1783 CYTry {
85a33bf5 1784 if (count < 2)
f5e9be24 1785 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"too few arguments to objc_msgSend" userInfo:nil];
85a33bf5 1786
4afefdd9 1787 self = CYCastNSObject(pool, context, arguments[0]);
7ba62cfd 1788 if (self == nil)
b09da87b 1789 return CYJSNull(context);
7ba62cfd 1790
4afefdd9 1791 _cmd = CYCastSEL(context, arguments[1]);
0c862573 1792 } CYCatch
ea2d184c 1793
4afefdd9 1794 return CYSendMessage(pool, context, self, _cmd, count - 2, arguments + 2, exception);
7ba62cfd
JF
1795}
1796
dea834b0
JF
1797static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1798 JSValueRef setup[count + 2];
1799 setup[0] = _this;
1800 setup[1] = object;
4afefdd9 1801 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
dea834b0
JF
1802 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
1803}
1804
1805static JSValueRef Functor_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
4afefdd9 1806 CYPool pool;
953647c1 1807 Functor_privateData *data(reinterpret_cast<Functor_privateData *>(JSObjectGetPrivate(object)));
4afefdd9 1808 return CYCallFunction(pool, context, 0, NULL, count, arguments, exception, &data->signature_, &data->cif_, reinterpret_cast<void (*)()>(data->value_));
ea2d184c
JF
1809}
1810
b09da87b 1811JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
4cf49641 1812 CYTry {
dea834b0
JF
1813 if (count != 1)
1814 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector constructor" userInfo:nil];
1815 const char *name(CYCastCString(context, arguments[0]));
1816 return CYMakeSelector(context, sel_registerName(name));
1817 } CYCatch
1818}
1819
b09da87b 1820JSObjectRef Functor_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
4cf49641 1821 CYTry {
b21525c7 1822 if (count != 2)
dea834b0 1823 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Functor constructor" userInfo:nil];
b21525c7 1824 const char *type(CYCastCString(context, arguments[1]));
b09da87b
JF
1825 JSValueRef exception(NULL);
1826 if (JSValueIsInstanceOfConstructor(context, arguments[0], Function_, &exception)) {
1827 JSObjectRef function(CYCastJSObject(context, arguments[0]));
1828 return CYMakeFunctor(context, function, type);
1829 } else if (exception != NULL) {
1830 return NULL;
1831 } else {
1832 void (*function)()(CYCastPointer<void (*)()>(context, arguments[0]));
1833 return CYMakeFunctor(context, function, type);
1834 }
0c862573 1835 } CYCatch
ea2d184c
JF
1836}
1837
f610e1a0 1838JSValueRef Pointer_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
953647c1 1839 Pointer_privateData *data(reinterpret_cast<Pointer_privateData *>(JSObjectGetPrivate(object)));
b09da87b 1840 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(data->value_));
04450da0
JF
1841}
1842
dea834b0
JF
1843JSValueRef Selector_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1844 return Function_;
1845}
1846
953647c1
JF
1847static JSValueRef Pointer_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1848 CYTry {
1849 Pointer_privateData *data(reinterpret_cast<Pointer_privateData *>(JSObjectGetPrivate(_this)));
1850 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(data->value_));
1851 } CYCatch
1852}
1853
b4aa79af
JF
1854static JSValueRef Pointer_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1855 return Pointer_callAsFunction_valueOf(context, object, _this, count, arguments, exception);
1856}
1857
4afefdd9
JF
1858static JSValueRef Pointer_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1859 CYTry {
1860 Pointer_privateData *data(reinterpret_cast<Pointer_privateData *>(JSObjectGetPrivate(_this)));
1861 char string[32];
1862 sprintf(string, "%p", data->value_);
1863 return CYCastJSValue(context, string);
1864 } CYCatch
1865}
1866
b4aa79af
JF
1867static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1868 CYTry {
1869 Instance_privateData *data(reinterpret_cast<Instance_privateData *>(JSObjectGetPrivate(_this)));
1870 CYPoolTry {
1871 return CYCastJSValue(context, CYJSString([data->GetValue() cy$toCYON]));
1872 } CYPoolCatch(NULL)
1873 } CYCatch
1874}
1875
1876static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1877 CYTry {
1878 Instance_privateData *data(reinterpret_cast<Instance_privateData *>(JSObjectGetPrivate(_this)));
1879 CYPoolTry {
1880 NSString *key(count == 0 ? nil : CYCastNSString(NULL, CYJSString(context, arguments[0])));
1881 return CYCastJSValue(context, CYJSString([data->GetValue() cy$toJSON:key]));
1882 } CYPoolCatch(NULL)
1883 } CYCatch
1884}
1885
4cf49641
JF
1886static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1887 CYTry {
953647c1 1888 Instance_privateData *data(reinterpret_cast<Instance_privateData *>(JSObjectGetPrivate(_this)));
4e8c99fb
JF
1889 CYPoolTry {
1890 return CYCastJSValue(context, CYJSString([data->GetValue() description]));
4cf49641 1891 } CYPoolCatch(NULL)
478d4ed0
JF
1892 } CYCatch
1893}
1894
1895static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
4cf49641 1896 CYTry {
953647c1 1897 Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
478d4ed0
JF
1898 return CYCastJSValue(context, sel_getName(data->GetValue()));
1899 } CYCatch
1900}
1901
b4aa79af
JF
1902static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1903 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
1904}
1905
1906static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1907 CYTry {
1908 Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
1909 const char *name(sel_getName(data->GetValue()));
1910 CYPoolTry {
1911 return CYCastJSValue(context, CYJSString([NSString stringWithFormat:@"@selector(%s)", name]));
1912 } CYPoolCatch(NULL)
1913 } CYCatch
1914}
1915
b09da87b 1916static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
4cf49641 1917 CYTry {
b09da87b
JF
1918 if (count != 2)
1919 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector.type" userInfo:nil];
1920 CYPool pool;
953647c1 1921 Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
b09da87b
JF
1922 Class _class(CYCastNSObject(pool, context, arguments[0]));
1923 bool instance(CYCastBool(context, arguments[1]));
1924 SEL sel(data->GetValue());
1925 if (Method method = (*(instance ? &class_getInstanceMethod : class_getClassMethod))(_class, sel))
1926 return CYCastJSValue(context, method_getTypeEncoding(method));
953647c1 1927 else if (NSString *type = [[Bridge_ objectAtIndex:1] objectForKey:CYCastNSString(pool, sel_getName(sel))])
b09da87b
JF
1928 return CYCastJSValue(context, CYJSString(type));
1929 else
1930 return CYJSNull(context);
1931 } CYCatch
1932}
1933
88c977fa
JF
1934static JSStaticValue Pointer_staticValues[2] = {
1935 {"value", &Pointer_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
04450da0
JF
1936 {NULL, NULL, NULL, 0}
1937};
1938
4afefdd9
JF
1939static JSStaticFunction Pointer_staticFunctions[4] = {
1940 {"toCYON", &Pointer_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
b4aa79af 1941 {"toJSON", &Pointer_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
953647c1
JF
1942 {"valueOf", &Pointer_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1943 {NULL, NULL, 0}
1944};
1945
dea834b0
JF
1946/*static JSStaticValue Selector_staticValues[2] = {
1947 {"prototype", &Selector_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
1948 {NULL, NULL, NULL, 0}
1949};*/
1950
b4aa79af
JF
1951static JSStaticFunction Instance_staticFunctions[4] = {
1952 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1953 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
478d4ed0
JF
1954 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1955 {NULL, NULL, 0}
1956};
1957
b4aa79af
JF
1958static JSStaticFunction Selector_staticFunctions[5] = {
1959 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1960 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
478d4ed0 1961 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
b09da87b
JF
1962 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1963 {NULL, NULL, 0}
1964};
1965
5999c315 1966CYDriver::CYDriver(const std::string &filename) :
db5e2840 1967 state_(CYClear),
e7ed5354
JF
1968 data_(NULL),
1969 size_(0),
5999c315
JF
1970 filename_(filename),
1971 source_(NULL)
1972{
924f67b2
JF
1973 ScannerInit();
1974}
1975
5999c315 1976CYDriver::~CYDriver() {
924f67b2
JF
1977 ScannerDestroy();
1978}
1979
5befe15e
JF
1980void cy::parser::error(const cy::parser::location_type &location, const std::string &message) {
1981 CYDriver::Error error;
1982 error.location_ = location;
1983 error.message_ = message;
1984 driver.errors_.push_back(error);
63b4c5a8
JF
1985}
1986
b09da87b
JF
1987void CYSetArgs(int argc, const char *argv[]) {
1988 JSContextRef context(CYGetJSContext());
1989 JSValueRef args[argc];
1990 for (int i(0); i != argc; ++i)
1991 args[i] = CYCastJSValue(context, argv[i]);
1992 JSValueRef exception(NULL);
1993 JSObjectRef array(JSObjectMakeArray(context, argc, args, &exception));
1994 CYThrow(context, exception);
1995 CYSetProperty(context, System_, CYJSString("args"), array);
1996}
1997
579ed526
JF
1998JSObjectRef CYGetGlobalObject(JSContextRef context) {
1999 return JSContextGetGlobalObject(context);
2000}
2001
7ba62cfd 2002MSInitialize { _pooled
ea2d184c
JF
2003 apr_initialize();
2004
953647c1
JF
2005 Bridge_ = [[NSMutableArray arrayWithContentsOfFile:@"/usr/lib/libcycript.plist"] retain];
2006
c1582939
JF
2007 NSCFBoolean_ = objc_getClass("NSCFBoolean");
2008
c1582939
JF
2009 JSClassDefinition definition;
2010
2011 definition = kJSClassDefinitionEmpty;
88c977fa
JF
2012 definition.className = "Pointer";
2013 definition.staticValues = Pointer_staticValues;
953647c1
JF
2014 definition.staticFunctions = Pointer_staticFunctions;
2015 definition.finalize = &CYData::Finalize;
88c977fa 2016 Pointer_ = JSClassCreate(&definition);
c1582939
JF
2017
2018 definition = kJSClassDefinitionEmpty;
88c977fa 2019 definition.className = "Functor";
953647c1
JF
2020 definition.staticValues = Pointer_staticValues;
2021 definition.staticFunctions = Pointer_staticFunctions;
dea834b0 2022 definition.callAsFunction = &Functor_callAsFunction;
953647c1 2023 definition.finalize = &CYData::Finalize;
88c977fa 2024 Functor_ = JSClassCreate(&definition);
7ba62cfd 2025
953647c1
JF
2026 definition = kJSClassDefinitionEmpty;
2027 definition.className = "Struct";
bd17e6f3
JF
2028 definition.getProperty = &Struct_getProperty;
2029 definition.setProperty = &Struct_setProperty;
f33b048a 2030 definition.getPropertyNames = &Struct_getPropertyNames;
953647c1
JF
2031 definition.finalize = &CYData::Finalize;
2032 Struct_ = JSClassCreate(&definition);
2033
77e87a6c 2034 definition = kJSClassDefinitionEmpty;
88c977fa 2035 definition.className = "Selector";
953647c1 2036 definition.staticValues = Pointer_staticValues;
dea834b0 2037 //definition.staticValues = Selector_staticValues;
b09da87b 2038 definition.staticFunctions = Selector_staticFunctions;
dea834b0 2039 definition.callAsFunction = &Selector_callAsFunction;
953647c1 2040 definition.finalize = &CYData::Finalize;
88c977fa 2041 Selector_ = JSClassCreate(&definition);
77e87a6c 2042
7ba62cfd 2043 definition = kJSClassDefinitionEmpty;
b09da87b 2044 definition.className = "Instance";
953647c1 2045 definition.staticValues = Pointer_staticValues;
478d4ed0 2046 definition.staticFunctions = Instance_staticFunctions;
88c977fa 2047 definition.getProperty = &Instance_getProperty;
b09da87b
JF
2048 definition.setProperty = &Instance_setProperty;
2049 definition.deleteProperty = &Instance_deleteProperty;
88c977fa 2050 definition.callAsConstructor = &Instance_callAsConstructor;
953647c1 2051 definition.finalize = &CYData::Finalize;
88c977fa 2052 Instance_ = JSClassCreate(&definition);
7ba62cfd
JF
2053
2054 definition = kJSClassDefinitionEmpty;
953647c1
JF
2055 definition.className = "Runtime";
2056 definition.getProperty = &Runtime_getProperty;
2057 Runtime_ = JSClassCreate(&definition);
2058
2059 definition = kJSClassDefinitionEmpty;
2060 //definition.getProperty = &Global_getProperty;
88c977fa 2061 JSClassRef Global(JSClassCreate(&definition));
c1582939 2062
478d4ed0 2063 JSGlobalContextRef context(JSGlobalContextCreate(Global));
ea2d184c
JF
2064 Context_ = context;
2065
579ed526 2066 JSObjectRef global(CYGetGlobalObject(context));
c1582939 2067
953647c1 2068 JSObjectSetPrototype(context, global, JSObjectMake(context, Runtime_, NULL));
579ed526 2069 CYSetProperty(context, global, CYJSString("ObjectiveC"), JSObjectMake(context, Runtime_, NULL));
953647c1 2070
b09da87b
JF
2071 CYSetProperty(context, global, CYJSString("Selector"), JSObjectMakeConstructor(context, Selector_, &Selector_new));
2072 CYSetProperty(context, global, CYJSString("Functor"), JSObjectMakeConstructor(context, Functor_, &Functor_new));
7ba62cfd 2073
b09da87b 2074 CYSetProperty(context, global, CYJSString("CYApplicationMain"), JSObjectMakeFunctionWithCallback(context, CYJSString("CYApplicationMain"), &CYApplicationMain));
dea834b0 2075 CYSetProperty(context, global, CYJSString("objc_msgSend"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_msgSend"), &$objc_msgSend));
7ba62cfd 2076
b09da87b
JF
2077 System_ = JSObjectMake(context, NULL, NULL);
2078 CYSetProperty(context, global, CYJSString("system"), System_);
2079 CYSetProperty(context, System_, CYJSString("args"), CYJSNull(context));
579ed526 2080 //CYSetProperty(context, System_, CYJSString("global"), global);
b09da87b
JF
2081
2082 CYSetProperty(context, System_, CYJSString("print"), JSObjectMakeFunctionWithCallback(context, CYJSString("print"), &System_print));
2083
c1582939 2084 length_ = JSStringCreateWithUTF8CString("length");
b4aa79af
JF
2085 message_ = JSStringCreateWithUTF8CString("message");
2086 name_ = JSStringCreateWithUTF8CString("name");
2087 toCYON_ = JSStringCreateWithUTF8CString("toCYON");
2088 toJSON_ = JSStringCreateWithUTF8CString("toJSON");
c1582939 2089
dea834b0
JF
2090 Array_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Array")));
2091 Function_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Function")));
c1582939 2092}