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