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