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