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