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