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