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