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