]> git.saurik.com Git - cycript.git/blob - Library.mm
Not quite the original, but pretty damn near close.
[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 <CoreFoundation/CoreFoundation.h>
52 #include <CoreFoundation/CFLogUtilities.h>
53
54 #include <WebKit/WebScriptObject.h>
55
56 #include <sys/mman.h>
57
58 #include <iostream>
59 #include <ext/stdio_filebuf.h>
60 #include <set>
61 #include <map>
62
63 #include <sstream>
64 #include <cmath>
65
66 #include "Parser.hpp"
67 #include "Cycript.tab.hh"
68
69 #include <apr-1/apr_thread_proc.h>
70
71 #undef _assert
72 #undef _trace
73
74 #define _assert(test) do { \
75 if (!(test)) \
76 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"_assert(%s):%s(%u):%s", #test, __FILE__, __LINE__, __FUNCTION__] userInfo:nil]; \
77 } while (false)
78
79 #define _trace() do { \
80 CFLog(kCFLogLevelNotice, CFSTR("_trace():%u"), __LINE__); \
81 } while (false)
82
83 #define CYPoolTry { \
84 id _saved(nil); \
85 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
86 @try
87 #define CYPoolCatch(value) \
88 @catch (NSException *error) { \
89 _saved = [error retain]; \
90 @throw; \
91 return value; \
92 } @finally { \
93 [_pool release]; \
94 if (_saved != nil) \
95 [_saved autorelease]; \
96 } \
97 }
98
99 static JSGlobalContextRef Context_;
100 static JSObjectRef System_;
101 static JSObjectRef ObjectiveC_;
102
103 static JSClassRef Functor_;
104 static JSClassRef Instance_;
105 static JSClassRef Internal_;
106 static JSClassRef Message_;
107 static JSClassRef Pointer_;
108 static JSClassRef Prototype_;
109 static JSClassRef Runtime_;
110 static JSClassRef Selector_;
111 static JSClassRef Struct_;
112 static JSClassRef Type_;
113
114 static JSClassRef ObjectiveC_Classes_;
115 static JSClassRef ObjectiveC_Image_Classes_;
116 static JSClassRef ObjectiveC_Images_;
117 static JSClassRef ObjectiveC_Protocols_;
118
119 static JSObjectRef Array_;
120 static JSObjectRef Function_;
121
122 static JSStringRef Result_;
123
124 static JSStringRef length_;
125 static JSStringRef message_;
126 static JSStringRef name_;
127 static JSStringRef prototype_;
128 static JSStringRef toCYON_;
129 static JSStringRef toJSON_;
130
131 static JSObjectRef Array_prototype_;
132 static JSObjectRef Array_pop_;
133 static JSObjectRef Array_push_;
134 static JSObjectRef Array_splice_;
135
136 static Class NSArray_;
137 static Class NSCFBoolean_;
138 static Class NSCFType_;
139 static Class NSMessageBuilder_;
140 static Class NSZombie_;
141 static Class Object_;
142
143 static NSArray *Bridge_;
144
145 static void Finalize(JSObjectRef object) {
146 delete reinterpret_cast<CYData *>(JSObjectGetPrivate(object));
147 }
148
149 class Type_privateData;
150
151 struct CYValue :
152 CYData
153 {
154 void *value_;
155
156 CYValue() {
157 }
158
159 CYValue(void *value) :
160 value_(value)
161 {
162 }
163
164 CYValue(const CYValue &rhs) :
165 value_(rhs.value_)
166 {
167 }
168
169 virtual Type_privateData *GetType() const {
170 return NULL;
171 }
172 };
173
174 struct Selector_privateData :
175 CYValue
176 {
177 Selector_privateData(SEL value) :
178 CYValue(value)
179 {
180 }
181
182 SEL GetValue() const {
183 return reinterpret_cast<SEL>(value_);
184 }
185
186 virtual Type_privateData *GetType() const;
187 };
188
189 struct Instance :
190 CYValue
191 {
192 enum Flags {
193 None = 0,
194 Transient = (1 << 0),
195 Uninitialized = (1 << 1),
196 };
197
198 Flags flags_;
199
200 Instance(id value, Flags flags) :
201 CYValue(value),
202 flags_(flags)
203 {
204 }
205
206 virtual ~Instance() {
207 if ((flags_ & Transient) == 0)
208 // XXX: does this handle background threads correctly?
209 [GetValue() performSelector:@selector(release) withObject:nil afterDelay:0];
210 }
211
212 static JSObjectRef Make(JSContextRef context, id object, Flags flags = None) {
213 JSObjectRef value(JSObjectMake(context, Instance_, new Instance(object, flags)));
214 if (object != nil)
215 for (Class _class(object_getClass(object)); _class != nil; _class = class_getSuperclass(_class))
216 if (_class == NSArray_) {
217 JSObjectSetPrototype(context, value, Array_prototype_);
218 break;
219 }
220 return value;
221 }
222
223 id GetValue() const {
224 return reinterpret_cast<id>(value_);
225 }
226
227 bool IsUninitialized() const {
228 return (flags_ & Uninitialized) != 0;
229 }
230
231 virtual Type_privateData *GetType() const;
232 };
233
234 struct Prototype :
235 CYValue
236 {
237 Prototype(Class value) :
238 CYValue(value)
239 {
240 }
241
242 static JSObjectRef Make(JSContextRef context, Class _class, bool array = false) {
243 JSObjectRef value(JSObjectMake(context, Prototype_, new Prototype(_class)));
244 if (_class == NSArray_)
245 array = true;
246 if (Class super = class_getSuperclass(_class))
247 JSObjectSetPrototype(context, value, Prototype::Make(context, super, array));
248 /*else if (array)
249 JSObjectSetPrototype(context, value, Array_prototype_);*/
250 return value;
251 }
252
253 Class GetValue() const {
254 return reinterpret_cast<Class>(value_);
255 }
256 };
257
258 struct Internal :
259 CYValue
260 {
261 JSObjectRef owner_;
262
263 Internal(id value, JSObjectRef owner) :
264 CYValue(value),
265 owner_(owner)
266 {
267 }
268
269 static JSObjectRef Make(JSContextRef context, id object, JSObjectRef owner) {
270 return JSObjectMake(context, Internal_, new Internal(object, owner));
271 }
272
273 id GetValue() const {
274 return reinterpret_cast<id>(value_);
275 }
276 };
277
278 namespace sig {
279
280 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs);
281
282 void Copy(apr_pool_t *pool, Element &lhs, Element &rhs) {
283 lhs.name = apr_pstrdup(pool, rhs.name);
284 if (rhs.type == NULL)
285 lhs.type = NULL;
286 else {
287 lhs.type = new(pool) Type;
288 Copy(pool, *lhs.type, *rhs.type);
289 }
290 lhs.offset = rhs.offset;
291 }
292
293 void Copy(apr_pool_t *pool, Signature &lhs, Signature &rhs) {
294 size_t count(rhs.count);
295 lhs.count = count;
296 lhs.elements = new(pool) Element[count];
297 for (size_t index(0); index != count; ++index)
298 Copy(pool, lhs.elements[index], rhs.elements[index]);
299 }
300
301 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs) {
302 lhs.primitive = rhs.primitive;
303 lhs.name = apr_pstrdup(pool, rhs.name);
304 lhs.flags = rhs.flags;
305
306 if (sig::IsAggregate(rhs.primitive))
307 Copy(pool, lhs.data.signature, rhs.data.signature);
308 else {
309 if (rhs.data.data.type != NULL) {
310 lhs.data.data.type = new(pool) Type;
311 Copy(pool, *lhs.data.data.type, *rhs.data.data.type);
312 }
313
314 lhs.data.data.size = rhs.data.data.size;
315 }
316 }
317
318 void Copy(apr_pool_t *pool, ffi_type &lhs, ffi_type &rhs) {
319 lhs.size = rhs.size;
320 lhs.alignment = rhs.alignment;
321 lhs.type = rhs.type;
322 if (rhs.elements == NULL)
323 lhs.elements = NULL;
324 else {
325 size_t count(0);
326 while (rhs.elements[count] != NULL)
327 ++count;
328
329 lhs.elements = new(pool) ffi_type *[count + 1];
330 lhs.elements[count] = NULL;
331
332 for (size_t index(0); index != count; ++index) {
333 // XXX: if these are libffi native then you can just take them
334 ffi_type *ffi(new(pool) ffi_type);
335 lhs.elements[index] = ffi;
336 sig::Copy(pool, *ffi, *rhs.elements[index]);
337 }
338 }
339 }
340
341 }
342
343 struct CStringMapLess :
344 std::binary_function<const char *, const char *, bool>
345 {
346 _finline bool operator ()(const char *lhs, const char *rhs) const {
347 return strcmp(lhs, rhs) < 0;
348 }
349 };
350
351 void Structor_(apr_pool_t *pool, const char *name, const char *types, sig::Type *&type) {
352 if (name == NULL)
353 return;
354
355 CYPoolTry {
356 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:2] objectForKey:[NSString stringWithUTF8String:name]])
357 switch ([[entry objectAtIndex:0] intValue]) {
358 case 0: {
359 sig::Parse(pool, &type->data.signature, [[entry objectAtIndex:1] UTF8String], &Structor_);
360 } break;
361
362 case 1: {
363 sig::Signature signature;
364 sig::Parse(pool, &signature, [[entry objectAtIndex:1] UTF8String], &Structor_);
365 type = signature.elements[0].type;
366 } break;
367 }
368 } CYPoolCatch()
369 }
370
371 struct Type_privateData :
372 CYData
373 {
374 static Type_privateData *Object;
375 static Type_privateData *Selector;
376
377 ffi_type *ffi_;
378 sig::Type *type_;
379
380 void Set(sig::Type *type) {
381 type_ = new(pool_) sig::Type;
382 sig::Copy(pool_, *type_, *type);
383 }
384
385 Type_privateData(apr_pool_t *pool, const char *type) :
386 ffi_(NULL)
387 {
388 if (pool != NULL)
389 pool_ = pool;
390
391 sig::Signature signature;
392 sig::Parse(pool_, &signature, type, &Structor_);
393 type_ = signature.elements[0].type;
394 }
395
396 Type_privateData(sig::Type *type) :
397 ffi_(NULL)
398 {
399 if (type != NULL)
400 Set(type);
401 }
402
403 Type_privateData(sig::Type *type, ffi_type *ffi) {
404 ffi_ = new(pool_) ffi_type;
405 sig::Copy(pool_, *ffi_, *ffi);
406 Set(type);
407 }
408
409 ffi_type *GetFFI() {
410 if (ffi_ == NULL) {
411 ffi_ = new(pool_) ffi_type;
412
413 sig::Element element;
414 element.name = NULL;
415 element.type = type_;
416 element.offset = 0;
417
418 sig::Signature signature;
419 signature.elements = &element;
420 signature.count = 1;
421
422 ffi_cif cif;
423 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature, &cif);
424 *ffi_ = *cif.rtype;
425 }
426
427 return ffi_;
428 }
429 };
430
431 Type_privateData *Type_privateData::Object;
432 Type_privateData *Type_privateData::Selector;
433
434 Type_privateData *Instance::GetType() const {
435 return Type_privateData::Object;
436 }
437
438 Type_privateData *Selector_privateData::GetType() const {
439 return Type_privateData::Selector;
440 }
441
442 struct Pointer :
443 CYValue
444 {
445 JSObjectRef owner_;
446 Type_privateData *type_;
447
448 Pointer(void *value, sig::Type *type, JSObjectRef owner) :
449 CYValue(value),
450 owner_(owner),
451 type_(new(pool_) Type_privateData(type))
452 {
453 }
454 };
455
456 struct Struct_privateData :
457 CYValue
458 {
459 JSObjectRef owner_;
460 Type_privateData *type_;
461
462 Struct_privateData(JSObjectRef owner) :
463 owner_(owner)
464 {
465 }
466 };
467
468 typedef std::map<const char *, Type_privateData *, CStringMapLess> TypeMap;
469 static TypeMap Types_;
470
471 JSObjectRef CYMakeStruct(JSContextRef context, void *data, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
472 Struct_privateData *internal(new Struct_privateData(owner));
473 apr_pool_t *pool(internal->pool_);
474 Type_privateData *typical(new(pool) Type_privateData(type, ffi));
475 internal->type_ = typical;
476
477 if (owner != NULL)
478 internal->value_ = data;
479 else {
480 size_t size(typical->GetFFI()->size);
481 void *copy(apr_palloc(internal->pool_, size));
482 memcpy(copy, data, size);
483 internal->value_ = copy;
484 }
485
486 return JSObjectMake(context, Struct_, internal);
487 }
488
489 struct Functor_privateData :
490 CYValue
491 {
492 sig::Signature signature_;
493 ffi_cif cif_;
494
495
496 Functor_privateData(const char *type, void (*value)()) :
497 CYValue(reinterpret_cast<void *>(value))
498 {
499 sig::Parse(pool_, &signature_, type, &Structor_);
500 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature_, &cif_);
501 }
502
503 void (*GetValue())() const {
504 return reinterpret_cast<void (*)()>(value_);
505 }
506 };
507
508 struct Closure_privateData :
509 Functor_privateData
510 {
511 JSContextRef context_;
512 JSObjectRef function_;
513
514 Closure_privateData(const char *type) :
515 Functor_privateData(type, NULL)
516 {
517 }
518 };
519
520 struct Message_privateData :
521 Functor_privateData
522 {
523 SEL sel_;
524
525 Message_privateData(SEL sel, const char *type, IMP value = NULL) :
526 Functor_privateData(type, reinterpret_cast<void (*)()>(value)),
527 sel_(sel)
528 {
529 }
530 };
531
532 JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
533 Instance::Flags flags;
534
535 if (transient)
536 flags = Instance::Transient;
537 else {
538 flags = Instance::None;
539 object = [object retain];
540 }
541
542 return Instance::Make(context, object, flags);
543 }
544
545 const char *CYPoolCString(apr_pool_t *pool, NSString *value) {
546 if (pool == NULL)
547 return [value UTF8String];
548 else {
549 size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
550 char *string(new(pool) char[size]);
551 if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
552 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:@"[NSString getCString:maxLength:encoding:] == NO" userInfo:nil];
553 return string;
554 }
555 }
556
557 JSValueRef CYCastJSValue(JSContextRef context, bool value) {
558 return JSValueMakeBoolean(context, value);
559 }
560
561 JSValueRef CYCastJSValue(JSContextRef context, double value) {
562 return JSValueMakeNumber(context, value);
563 }
564
565 #define CYCastJSValue_(Type_) \
566 JSValueRef CYCastJSValue(JSContextRef context, Type_ value) { \
567 return JSValueMakeNumber(context, static_cast<double>(value)); \
568 }
569
570 CYCastJSValue_(int)
571 CYCastJSValue_(unsigned int)
572 CYCastJSValue_(long int)
573 CYCastJSValue_(long unsigned int)
574 CYCastJSValue_(long long int)
575 CYCastJSValue_(long long unsigned int)
576
577 JSValueRef CYJSUndefined(JSContextRef context) {
578 return JSValueMakeUndefined(context);
579 }
580
581 size_t CYGetIndex(const char *value) {
582 if (value[0] != '0') {
583 char *end;
584 size_t index(strtoul(value, &end, 10));
585 if (value + strlen(value) == end)
586 return index;
587 } else if (value[1] == '\0')
588 return 0;
589 return _not(size_t);
590 }
591
592 size_t CYGetIndex(apr_pool_t *pool, NSString *value) {
593 return CYGetIndex(CYPoolCString(pool, value));
594 }
595
596 bool CYGetOffset(const char *value, ssize_t &index) {
597 if (value[0] != '0') {
598 char *end;
599 index = strtol(value, &end, 10);
600 if (value + strlen(value) == end)
601 return true;
602 } else if (value[1] == '\0') {
603 index = 0;
604 return true;
605 }
606
607 return false;
608 }
609
610 bool CYGetOffset(apr_pool_t *pool, NSString *value, ssize_t &index) {
611 return CYGetOffset(CYPoolCString(pool, value), index);
612 }
613
614 NSString *CYPoolNSCYON(apr_pool_t *pool, id value);
615
616 @interface NSMethodSignature (Cycript)
617 - (NSString *) _typeString;
618 @end
619
620 @interface NSObject (Cycript)
621
622 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
623 - (JSType) cy$JSType;
624
625 - (NSObject *) cy$toJSON:(NSString *)key;
626 - (NSString *) cy$toCYON;
627 - (NSString *) cy$toKey;
628
629 - (bool) cy$hasProperty:(NSString *)name;
630 - (NSObject *) cy$getProperty:(NSString *)name;
631 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
632 - (bool) cy$deleteProperty:(NSString *)name;
633
634 @end
635
636 @protocol Cycript
637 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
638 @end
639
640 @interface NSString (Cycript)
641 - (void *) cy$symbol;
642 @end
643
644 struct PropertyAttributes {
645 CYPool pool_;
646
647 const char *name;
648
649 const char *variable;
650
651 const char *getter_;
652 const char *setter_;
653
654 bool readonly;
655 bool copy;
656 bool retain;
657 bool nonatomic;
658 bool dynamic;
659 bool weak;
660 bool garbage;
661
662 PropertyAttributes(objc_property_t property) :
663 variable(NULL),
664 getter_(NULL),
665 setter_(NULL),
666 readonly(false),
667 copy(false),
668 retain(false),
669 nonatomic(false),
670 dynamic(false),
671 weak(false),
672 garbage(false)
673 {
674 name = property_getName(property);
675 const char *attributes(property_getAttributes(property));
676
677 for (char *state, *token(apr_strtok(apr_pstrdup(pool_, attributes), ",", &state)); token != NULL; token = apr_strtok(NULL, ",", &state)) {
678 switch (*token) {
679 case 'R': readonly = true; break;
680 case 'C': copy = true; break;
681 case '&': retain = true; break;
682 case 'N': nonatomic = true; break;
683 case 'G': getter_ = token + 1; break;
684 case 'S': setter_ = token + 1; break;
685 case 'V': variable = token + 1; break;
686 }
687 }
688
689 /*if (variable == NULL) {
690 variable = property_getName(property);
691 size_t size(strlen(variable));
692 char *name(new(pool_) char[size + 2]);
693 name[0] = '_';
694 memcpy(name + 1, variable, size);
695 name[size + 1] = '\0';
696 variable = name;
697 }*/
698 }
699
700 const char *Getter() {
701 if (getter_ == NULL)
702 getter_ = apr_pstrdup(pool_, name);
703 return getter_;
704 }
705
706 const char *Setter() {
707 if (setter_ == NULL && !readonly) {
708 size_t length(strlen(name));
709
710 char *temp(new(pool_) char[length + 5]);
711 temp[0] = 's';
712 temp[1] = 'e';
713 temp[2] = 't';
714
715 if (length != 0) {
716 temp[3] = toupper(name[0]);
717 memcpy(temp + 4, name + 1, length - 1);
718 }
719
720 temp[length + 3] = ':';
721 temp[length + 4] = '\0';
722 setter_ = temp;
723 }
724
725 return setter_;
726 }
727
728 };
729
730 @implementation NSProxy (Cycript)
731
732 - (NSObject *) cy$toJSON:(NSString *)key {
733 return [self description];
734 }
735
736 - (NSString *) cy$toCYON {
737 return [[self cy$toJSON:@""] cy$toCYON];
738 }
739
740 @end
741
742 @implementation NSObject (Cycript)
743
744 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
745 return CYMakeInstance(context, self, false);
746 }
747
748 - (JSType) cy$JSType {
749 return kJSTypeObject;
750 }
751
752 - (NSObject *) cy$toJSON:(NSString *)key {
753 return [self description];
754 }
755
756 - (NSString *) cy$toCYON {
757 return [[self cy$toJSON:@""] cy$toCYON];
758 }
759
760 - (NSString *) cy$toKey {
761 return [self cy$toCYON];
762 }
763
764 - (bool) cy$hasProperty:(NSString *)name {
765 return false;
766 }
767
768 - (NSObject *) cy$getProperty:(NSString *)name {
769 return nil;
770 }
771
772 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
773 return false;
774 }
775
776 - (bool) cy$deleteProperty:(NSString *)name {
777 return false;
778 }
779
780 @end
781
782 NSString *NSCFType$cy$toJSON(id self, SEL sel, NSString *key) {
783 return [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease];
784 }
785
786 @implementation WebUndefined (Cycript)
787
788 - (JSType) cy$JSType {
789 return kJSTypeUndefined;
790 }
791
792 - (NSObject *) cy$toJSON:(NSString *)key {
793 return self;
794 }
795
796 - (NSString *) cy$toCYON {
797 return @"undefined";
798 }
799
800 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
801 return CYJSUndefined(context);
802 }
803
804 @end
805
806 @implementation NSNull (Cycript)
807
808 - (JSType) cy$JSType {
809 return kJSTypeNull;
810 }
811
812 - (NSObject *) cy$toJSON:(NSString *)key {
813 return self;
814 }
815
816 - (NSString *) cy$toCYON {
817 return @"null";
818 }
819
820 @end
821
822 @implementation NSArray (Cycript)
823
824 - (NSString *) cy$toCYON {
825 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
826 [json appendString:@"["];
827
828 bool comma(false);
829 for (id object in self) {
830 if (comma)
831 [json appendString:@","];
832 else
833 comma = true;
834 if (object == nil || [object cy$JSType] != kJSTypeUndefined)
835 [json appendString:CYPoolNSCYON(NULL, object)];
836 else {
837 [json appendString:@","];
838 comma = false;
839 }
840 }
841
842 [json appendString:@"]"];
843 return json;
844 }
845
846 - (bool) cy$hasProperty:(NSString *)name {
847 if ([name isEqualToString:@"length"])
848 return true;
849
850 size_t index(CYGetIndex(NULL, name));
851 if (index == _not(size_t) || index >= [self count])
852 return [super cy$hasProperty:name];
853 else
854 return true;
855 }
856
857 - (NSObject *) cy$getProperty:(NSString *)name {
858 if ([name isEqualToString:@"length"])
859 return [NSNumber numberWithUnsignedInteger:[self count]];
860
861 size_t index(CYGetIndex(NULL, name));
862 if (index == _not(size_t) || index >= [self count])
863 return [super cy$getProperty:name];
864 else
865 return [self objectAtIndex:index];
866 }
867
868 @end
869
870 @implementation NSMutableArray (Cycript)
871
872 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
873 if ([name isEqualToString:@"length"]) {
874 // XXX: is this not intelligent?
875 NSUInteger size([(NSNumber *)value unsignedIntegerValue]);
876 NSUInteger count([self count]);
877 if (size < count)
878 [self removeObjectsInRange:NSMakeRange(size, count - size)];
879 else if (size != count) {
880 WebUndefined *undefined([WebUndefined undefined]);
881 for (size_t i(count); i != size; ++i)
882 [self addObject:undefined];
883 }
884 return true;
885 }
886
887 size_t index(CYGetIndex(NULL, name));
888 if (index == _not(size_t))
889 return [super cy$setProperty:name to:value];
890
891 id object(value ?: [NSNull null]);
892
893 size_t count([self count]);
894 if (index < count)
895 [self replaceObjectAtIndex:index withObject:object];
896 else {
897 if (index != count) {
898 WebUndefined *undefined([WebUndefined undefined]);
899 for (size_t i(count); i != index; ++i)
900 [self addObject:undefined];
901 }
902
903 [self addObject:object];
904 }
905
906 return true;
907 }
908
909 - (bool) cy$deleteProperty:(NSString *)name {
910 size_t index(CYGetIndex(NULL, name));
911 if (index == _not(size_t) || index >= [self count])
912 return [super cy$deleteProperty:name];
913 [self replaceObjectAtIndex:index withObject:[WebUndefined undefined]];
914 return true;
915 }
916
917 @end
918
919 @implementation NSDictionary (Cycript)
920
921 - (NSString *) cy$toCYON {
922 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
923 [json appendString:@"{"];
924
925 bool comma(false);
926 for (id key in self) {
927 if (comma)
928 [json appendString:@","];
929 else
930 comma = true;
931 [json appendString:[key cy$toKey]];
932 [json appendString:@":"];
933 NSObject *object([self objectForKey:key]);
934 [json appendString:CYPoolNSCYON(NULL, object)];
935 }
936
937 [json appendString:@"}"];
938 return json;
939 }
940
941 - (bool) cy$hasProperty:(NSString *)name {
942 return [self objectForKey:name] != nil;
943 }
944
945 - (NSObject *) cy$getProperty:(NSString *)name {
946 return [self objectForKey:name];
947 }
948
949 @end
950
951 @implementation NSMutableDictionary (Cycript)
952
953 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
954 [self setObject:(value ?: [NSNull null]) forKey:name];
955 return true;
956 }
957
958 - (bool) cy$deleteProperty:(NSString *)name {
959 if ([self objectForKey:name] == nil)
960 return false;
961 else {
962 [self removeObjectForKey:name];
963 return true;
964 }
965 }
966
967 @end
968
969 @implementation NSNumber (Cycript)
970
971 - (JSType) cy$JSType {
972 // XXX: this just seems stupid
973 return [self class] == NSCFBoolean_ ? kJSTypeBoolean : kJSTypeNumber;
974 }
975
976 - (NSObject *) cy$toJSON:(NSString *)key {
977 return self;
978 }
979
980 - (NSString *) cy$toCYON {
981 return [self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false";
982 }
983
984 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
985 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, [self boolValue]);
986 }
987
988 @end
989
990 @implementation NSString (Cycript)
991
992 - (JSType) cy$JSType {
993 return kJSTypeString;
994 }
995
996 - (NSObject *) cy$toJSON:(NSString *)key {
997 return self;
998 }
999
1000 - (NSString *) cy$toCYON {
1001 // XXX: this should use the better code from Output.cpp
1002 CFMutableStringRef json(CFStringCreateMutableCopy(kCFAllocatorDefault, 0, (CFStringRef) self));
1003
1004 CFStringFindAndReplace(json, CFSTR("\\"), CFSTR("\\\\"), CFRangeMake(0, CFStringGetLength(json)), 0);
1005 CFStringFindAndReplace(json, CFSTR("\""), CFSTR("\\\""), CFRangeMake(0, CFStringGetLength(json)), 0);
1006 CFStringFindAndReplace(json, CFSTR("\t"), CFSTR("\\t"), CFRangeMake(0, CFStringGetLength(json)), 0);
1007 CFStringFindAndReplace(json, CFSTR("\r"), CFSTR("\\r"), CFRangeMake(0, CFStringGetLength(json)), 0);
1008 CFStringFindAndReplace(json, CFSTR("\n"), CFSTR("\\n"), CFRangeMake(0, CFStringGetLength(json)), 0);
1009
1010 CFStringInsert(json, 0, CFSTR("\""));
1011 CFStringAppend(json, CFSTR("\""));
1012
1013 return [reinterpret_cast<const NSString *>(json) autorelease];
1014 }
1015
1016 - (NSString *) cy$toKey {
1017 const char *value([self UTF8String]);
1018 size_t size(strlen(value));
1019
1020 if (size == 0)
1021 goto cyon;
1022
1023 if (DigitRange_[value[0]]) {
1024 size_t index(CYGetIndex(NULL, self));
1025 if (index == _not(size_t))
1026 goto cyon;
1027 } else {
1028 if (!WordStartRange_[value[0]])
1029 goto cyon;
1030 for (size_t i(1); i != size; ++i)
1031 if (!WordEndRange_[value[i]])
1032 goto cyon;
1033 }
1034
1035 return self;
1036
1037 cyon:
1038 return [self cy$toCYON];
1039 }
1040
1041 - (void *) cy$symbol {
1042 CYPool pool;
1043 return dlsym(RTLD_DEFAULT, CYPoolCString(pool, self));
1044 }
1045
1046 @end
1047
1048 @interface CYJSObject : NSMutableDictionary {
1049 JSObjectRef object_;
1050 JSContextRef context_;
1051 }
1052
1053 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
1054
1055 - (NSString *) cy$toJSON:(NSString *)key;
1056
1057 - (NSUInteger) count;
1058 - (id) objectForKey:(id)key;
1059 - (NSEnumerator *) keyEnumerator;
1060 - (void) setObject:(id)object forKey:(id)key;
1061 - (void) removeObjectForKey:(id)key;
1062
1063 @end
1064
1065 @interface CYJSArray : NSMutableArray {
1066 JSObjectRef object_;
1067 JSContextRef context_;
1068 }
1069
1070 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
1071
1072 - (NSUInteger) count;
1073 - (id) objectAtIndex:(NSUInteger)index;
1074
1075 - (void) addObject:(id)anObject;
1076 - (void) insertObject:(id)anObject atIndex:(NSUInteger)index;
1077 - (void) removeLastObject;
1078 - (void) removeObjectAtIndex:(NSUInteger)index;
1079 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;
1080
1081 @end
1082
1083 CYRange DigitRange_ (0x3ff000000000000LLU, 0x000000000000000LLU); // 0-9
1084 CYRange WordStartRange_(0x000001000000000LLU, 0x7fffffe87fffffeLLU); // A-Za-z_$
1085 CYRange WordEndRange_ (0x3ff001000000000LLU, 0x7fffffe87fffffeLLU); // A-Za-z_$0-9
1086
1087 #define CYTry \
1088 @try
1089 #define CYCatch \
1090 @catch (id error) { \
1091 CYThrow(context, error, exception); \
1092 return NULL; \
1093 }
1094
1095 void CYThrow(JSContextRef context, JSValueRef value);
1096
1097 apr_status_t CYPoolRelease_(void *data) {
1098 id object(reinterpret_cast<id>(data));
1099 [object release];
1100 return APR_SUCCESS;
1101 }
1102
1103 id CYPoolRelease(apr_pool_t *pool, id object) {
1104 if (object == nil)
1105 return nil;
1106 else if (pool == NULL)
1107 return [object autorelease];
1108 else {
1109 apr_pool_cleanup_register(pool, object, &CYPoolRelease_, &apr_pool_cleanup_null);
1110 return object;
1111 }
1112 }
1113
1114 CFTypeRef CYPoolRelease(apr_pool_t *pool, CFTypeRef object) {
1115 return (CFTypeRef) CYPoolRelease(pool, (id) object);
1116 }
1117
1118 id CYCastNSObject_(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
1119 JSValueRef exception(NULL);
1120 bool array(JSValueIsInstanceOfConstructor(context, object, Array_, &exception));
1121 CYThrow(context, exception);
1122 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
1123 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
1124 }
1125
1126 id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
1127 if (!JSValueIsObjectOfClass(context, object, Instance_))
1128 return CYCastNSObject_(pool, context, object);
1129 else {
1130 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1131 return internal->GetValue();
1132 }
1133 }
1134
1135 JSStringRef CYCopyJSString(id value) {
1136 return value == NULL ? NULL : JSStringCreateWithCFString(reinterpret_cast<CFStringRef>([value description]));
1137 }
1138
1139 JSStringRef CYCopyJSString(const char *value) {
1140 return value == NULL ? NULL : JSStringCreateWithUTF8CString(value);
1141 }
1142
1143 JSStringRef CYCopyJSString(JSStringRef value) {
1144 return value == NULL ? NULL : JSStringRetain(value);
1145 }
1146
1147 JSStringRef CYCopyJSString(JSContextRef context, JSValueRef value) {
1148 if (JSValueIsNull(context, value))
1149 return NULL;
1150 JSValueRef exception(NULL);
1151 JSStringRef string(JSValueToStringCopy(context, value, &exception));
1152 CYThrow(context, exception);
1153 return string;
1154 }
1155
1156 class CYJSString {
1157 private:
1158 JSStringRef string_;
1159
1160 void Clear_() {
1161 if (string_ != NULL)
1162 JSStringRelease(string_);
1163 }
1164
1165 public:
1166 CYJSString(const CYJSString &rhs) :
1167 string_(CYCopyJSString(rhs.string_))
1168 {
1169 }
1170
1171 template <typename Arg0_>
1172 CYJSString(Arg0_ arg0) :
1173 string_(CYCopyJSString(arg0))
1174 {
1175 }
1176
1177 template <typename Arg0_, typename Arg1_>
1178 CYJSString(Arg0_ arg0, Arg1_ arg1) :
1179 string_(CYCopyJSString(arg0, arg1))
1180 {
1181 }
1182
1183 CYJSString &operator =(const CYJSString &rhs) {
1184 Clear_();
1185 string_ = CYCopyJSString(rhs.string_);
1186 return *this;
1187 }
1188
1189 ~CYJSString() {
1190 Clear_();
1191 }
1192
1193 void Clear() {
1194 Clear_();
1195 string_ = NULL;
1196 }
1197
1198 operator JSStringRef() const {
1199 return string_;
1200 }
1201 };
1202
1203 CFStringRef CYCopyCFString(JSStringRef value) {
1204 return JSStringCopyCFString(kCFAllocatorDefault, value);
1205 }
1206
1207 CFStringRef CYCopyCFString(JSContextRef context, JSValueRef value) {
1208 return CYCopyCFString(CYJSString(context, value));
1209 }
1210
1211 double CYCastDouble(const char *value, size_t size) {
1212 char *end;
1213 double number(strtod(value, &end));
1214 if (end != value + size)
1215 return NAN;
1216 return number;
1217 }
1218
1219 double CYCastDouble(const char *value) {
1220 return CYCastDouble(value, strlen(value));
1221 }
1222
1223 double CYCastDouble(JSContextRef context, JSValueRef value) {
1224 JSValueRef exception(NULL);
1225 double number(JSValueToNumber(context, value, &exception));
1226 CYThrow(context, exception);
1227 return number;
1228 }
1229
1230 CFNumberRef CYCopyCFNumber(JSContextRef context, JSValueRef value) {
1231 double number(CYCastDouble(context, value));
1232 return CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &number);
1233 }
1234
1235 CFStringRef CYCopyCFString(const char *value) {
1236 return CFStringCreateWithCString(kCFAllocatorDefault, value, kCFStringEncodingUTF8);
1237 }
1238
1239 NSString *CYCastNSString(apr_pool_t *pool, const char *value) {
1240 return (NSString *) CYPoolRelease(pool, CYCopyCFString(value));
1241 }
1242
1243 NSString *CYCastNSString(apr_pool_t *pool, JSStringRef value) {
1244 return (NSString *) CYPoolRelease(pool, CYCopyCFString(value));
1245 }
1246
1247 bool CYCastBool(JSContextRef context, JSValueRef value) {
1248 return JSValueToBoolean(context, value);
1249 }
1250
1251 CFTypeRef CYCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value, bool cast) {
1252 CFTypeRef object;
1253 bool copy;
1254
1255 switch (JSType type = JSValueGetType(context, value)) {
1256 case kJSTypeUndefined:
1257 object = [WebUndefined undefined];
1258 copy = false;
1259 break;
1260
1261 case kJSTypeNull:
1262 return NULL;
1263 break;
1264
1265 case kJSTypeBoolean:
1266 object = CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse;
1267 copy = false;
1268 break;
1269
1270 case kJSTypeNumber:
1271 object = CYCopyCFNumber(context, value);
1272 copy = true;
1273 break;
1274
1275 case kJSTypeString:
1276 object = CYCopyCFString(context, value);
1277 copy = true;
1278 break;
1279
1280 case kJSTypeObject:
1281 // XXX: this might could be more efficient
1282 object = (CFTypeRef) CYCastNSObject(pool, context, (JSObjectRef) value);
1283 copy = false;
1284 break;
1285
1286 default:
1287 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"JSValueGetType() == 0x%x", type] userInfo:nil];
1288 break;
1289 }
1290
1291 if (cast != copy)
1292 return object;
1293 else if (copy)
1294 return CYPoolRelease(pool, object);
1295 else
1296 return CFRetain(object);
1297 }
1298
1299 CFTypeRef CYCastCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1300 return CYCFType(pool, context, value, true);
1301 }
1302
1303 CFTypeRef CYCopyCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1304 return CYCFType(pool, context, value, false);
1305 }
1306
1307 NSArray *CYCastNSArray(JSPropertyNameArrayRef names) {
1308 CYPool pool;
1309 size_t size(JSPropertyNameArrayGetCount(names));
1310 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1311 for (size_t index(0); index != size; ++index)
1312 [array addObject:CYCastNSString(pool, JSPropertyNameArrayGetNameAtIndex(names, index))];
1313 return array;
1314 }
1315
1316 id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1317 return reinterpret_cast<const NSObject *>(CYCastCFType(pool, context, value));
1318 }
1319
1320 void CYThrow(JSContextRef context, JSValueRef value) {
1321 if (value == NULL)
1322 return;
1323 @throw CYCastNSObject(NULL, context, value);
1324 }
1325
1326 JSValueRef CYJSNull(JSContextRef context) {
1327 return JSValueMakeNull(context);
1328 }
1329
1330 JSValueRef CYCastJSValue(JSContextRef context, JSStringRef value) {
1331 return value == NULL ? CYJSNull(context) : JSValueMakeString(context, value);
1332 }
1333
1334 JSValueRef CYCastJSValue(JSContextRef context, const char *value) {
1335 return CYCastJSValue(context, CYJSString(value));
1336 }
1337
1338 JSValueRef CYCastJSValue(JSContextRef context, id value) {
1339 if (value == nil)
1340 return CYJSNull(context);
1341 else if ([value respondsToSelector:@selector(cy$JSValueInContext:)])
1342 return [value cy$JSValueInContext:context];
1343 else
1344 return CYMakeInstance(context, value, false);
1345 }
1346
1347 JSObjectRef CYCastJSObject(JSContextRef context, JSValueRef value) {
1348 JSValueRef exception(NULL);
1349 JSObjectRef object(JSValueToObject(context, value, &exception));
1350 CYThrow(context, exception);
1351 return object;
1352 }
1353
1354 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, size_t index) {
1355 JSValueRef exception(NULL);
1356 JSValueRef value(JSObjectGetPropertyAtIndex(context, object, index, &exception));
1357 CYThrow(context, exception);
1358 return value;
1359 }
1360
1361 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, JSStringRef name) {
1362 JSValueRef exception(NULL);
1363 JSValueRef value(JSObjectGetProperty(context, object, name, &exception));
1364 CYThrow(context, exception);
1365 return value;
1366 }
1367
1368 void CYSetProperty(JSContextRef context, JSObjectRef object, size_t index, JSValueRef value) {
1369 JSValueRef exception(NULL);
1370 JSObjectSetPropertyAtIndex(context, object, index, value, &exception);
1371 CYThrow(context, exception);
1372 }
1373
1374 void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef value) {
1375 JSValueRef exception(NULL);
1376 JSObjectSetProperty(context, object, name, value, kJSPropertyAttributeNone, &exception);
1377 CYThrow(context, exception);
1378 }
1379
1380 void CYThrow(JSContextRef context, id error, JSValueRef *exception) {
1381 if (exception == NULL)
1382 throw error;
1383 *exception = CYCastJSValue(context, error);
1384 }
1385
1386 JSValueRef CYCallAsFunction(JSContextRef context, JSObjectRef function, JSObjectRef _this, size_t count, JSValueRef arguments[]) {
1387 JSValueRef exception(NULL);
1388 JSValueRef value(JSObjectCallAsFunction(context, function, _this, count, arguments, &exception));
1389 CYThrow(context, exception);
1390 return value;
1391 }
1392
1393 bool CYIsCallable(JSContextRef context, JSValueRef value) {
1394 // XXX: this isn't actually correct
1395 return value != NULL && JSValueIsObject(context, value);
1396 }
1397
1398 @implementation CYJSObject
1399
1400 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
1401 if ((self = [super init]) != nil) {
1402 object_ = object;
1403 context_ = context;
1404 } return self;
1405 }
1406
1407 - (NSObject *) cy$toJSON:(NSString *)key {
1408 JSValueRef toJSON(CYGetProperty(context_, object_, toJSON_));
1409 if (!CYIsCallable(context_, toJSON))
1410 return [super cy$toJSON:key];
1411 else {
1412 JSValueRef arguments[1] = {CYCastJSValue(context_, key)};
1413 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toJSON, object_, 1, arguments));
1414 // XXX: do I really want an NSNull here?!
1415 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1416 }
1417 }
1418
1419 - (NSString *) cy$toCYON {
1420 JSValueRef toCYON(CYGetProperty(context_, object_, toCYON_));
1421 if (!CYIsCallable(context_, toCYON))
1422 return [super cy$toCYON];
1423 else {
1424 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toCYON, object_, 0, NULL));
1425 return CYCastNSString(NULL, CYJSString(context_, value));
1426 }
1427 }
1428
1429 - (NSUInteger) count {
1430 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1431 size_t size(JSPropertyNameArrayGetCount(names));
1432 JSPropertyNameArrayRelease(names);
1433 return size;
1434 }
1435
1436 - (id) objectForKey:(id)key {
1437 JSValueRef value(CYGetProperty(context_, object_, CYJSString(key)));
1438 if (JSValueIsUndefined(context_, value))
1439 return nil;
1440 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1441 }
1442
1443 - (NSEnumerator *) keyEnumerator {
1444 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1445 NSEnumerator *enumerator([CYCastNSArray(names) objectEnumerator]);
1446 JSPropertyNameArrayRelease(names);
1447 return enumerator;
1448 }
1449
1450 - (void) setObject:(id)object forKey:(id)key {
1451 CYSetProperty(context_, object_, CYJSString(key), CYCastJSValue(context_, object));
1452 }
1453
1454 - (void) removeObjectForKey:(id)key {
1455 JSValueRef exception(NULL);
1456 (void) JSObjectDeleteProperty(context_, object_, CYJSString(key), &exception);
1457 CYThrow(context_, exception);
1458 }
1459
1460 @end
1461
1462 @implementation CYJSArray
1463
1464 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
1465 if ((self = [super init]) != nil) {
1466 object_ = object;
1467 context_ = context;
1468 } return self;
1469 }
1470
1471 - (NSUInteger) count {
1472 return CYCastDouble(context_, CYGetProperty(context_, object_, length_));
1473 }
1474
1475 - (id) objectAtIndex:(NSUInteger)index {
1476 size_t bounds([self count]);
1477 if (index >= bounds)
1478 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1479 JSValueRef exception(NULL);
1480 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
1481 CYThrow(context_, exception);
1482 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1483 }
1484
1485 - (void) addObject:(id)object {
1486 JSValueRef exception(NULL);
1487 JSValueRef arguments[1];
1488 arguments[0] = CYCastJSValue(context_, object);
1489 JSObjectCallAsFunction(context_, Array_push_, object_, 1, arguments, &exception);
1490 CYThrow(context_, exception);
1491 }
1492
1493 - (void) insertObject:(id)object atIndex:(NSUInteger)index {
1494 size_t bounds([self count] + 1);
1495 if (index >= bounds)
1496 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1497 JSValueRef exception(NULL);
1498 JSValueRef arguments[3];
1499 arguments[0] = CYCastJSValue(context_, index);
1500 arguments[1] = CYCastJSValue(context_, 0);
1501 arguments[2] = CYCastJSValue(context_, object);
1502 JSObjectCallAsFunction(context_, Array_splice_, object_, 3, arguments, &exception);
1503 CYThrow(context_, exception);
1504 }
1505
1506 - (void) removeLastObject {
1507 JSValueRef exception(NULL);
1508 JSObjectCallAsFunction(context_, Array_pop_, object_, 0, NULL, &exception);
1509 CYThrow(context_, exception);
1510 }
1511
1512 - (void) removeObjectAtIndex:(NSUInteger)index {
1513 size_t bounds([self count]);
1514 if (index >= bounds)
1515 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1516 JSValueRef exception(NULL);
1517 JSValueRef arguments[2];
1518 arguments[0] = CYCastJSValue(context_, index);
1519 arguments[1] = CYCastJSValue(context_, 1);
1520 JSObjectCallAsFunction(context_, Array_splice_, object_, 2, arguments, &exception);
1521 CYThrow(context_, exception);
1522 }
1523
1524 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object {
1525 size_t bounds([self count]);
1526 if (index >= bounds)
1527 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1528 CYSetProperty(context_, object_, index, CYCastJSValue(context_, object));
1529 }
1530
1531 @end
1532
1533 NSString *CYCopyNSCYON(id value) {
1534 NSString *string;
1535
1536 if (value == nil)
1537 string = @"nil";
1538 else {
1539 Class _class(object_getClass(value));
1540 SEL sel(@selector(cy$toCYON));
1541
1542 if (Method toCYON = class_getInstanceMethod(_class, sel))
1543 string = reinterpret_cast<NSString *(*)(id, SEL)>(method_getImplementation(toCYON))(value, sel);
1544 else if (Method methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:))) {
1545 if (reinterpret_cast<NSMethodSignature *(*)(id, SEL, SEL)>(method_getImplementation(methodSignatureForSelector))(value, @selector(methodSignatureForSelector:), sel) != nil)
1546 string = [value cy$toCYON];
1547 else goto fail;
1548 } else fail: {
1549 if (value == NSZombie_)
1550 string = @"_NSZombie_";
1551 else if (_class == NSZombie_)
1552 string = [NSString stringWithFormat:@"<_NSZombie_: %p>", value];
1553 // XXX: frowny /in/ the pants
1554 else if (value == NSMessageBuilder_ || value == Object_)
1555 string = nil;
1556 else
1557 string = [NSString stringWithFormat:@"%@", value];
1558 }
1559
1560 // XXX: frowny pants
1561 if (string == nil)
1562 string = @"undefined";
1563 }
1564
1565 return [string retain];
1566 }
1567
1568 NSString *CYCopyNSCYON(JSContextRef context, JSValueRef value, JSValueRef *exception) {
1569 if (JSValueIsNull(context, value))
1570 return [@"null" retain];
1571
1572 CYTry {
1573 CYPoolTry {
1574 return CYCopyNSCYON(CYCastNSObject(NULL, context, value));
1575 } CYPoolCatch(NULL)
1576 } CYCatch
1577 }
1578
1579 NSString *CYPoolNSCYON(apr_pool_t *pool, id value) {
1580 return CYPoolRelease(pool, static_cast<id>(CYCopyNSCYON(value)));
1581 }
1582
1583 const char *CYPoolCCYON(apr_pool_t *pool, JSContextRef context, JSValueRef value, JSValueRef *exception) {
1584 if (NSString *json = CYCopyNSCYON(context, value, exception)) {
1585 const char *string(CYPoolCString(pool, json));
1586 [json release];
1587 return string;
1588 } else return NULL;
1589 }
1590
1591 // XXX: use objc_getAssociatedObject and objc_setAssociatedObject on 10.6
1592 struct CYInternal :
1593 CYData
1594 {
1595 JSObjectRef object_;
1596
1597 CYInternal() :
1598 object_(NULL)
1599 {
1600 }
1601
1602 ~CYInternal() {
1603 // XXX: delete object_? ;(
1604 }
1605
1606 static CYInternal *Get(id self) {
1607 CYInternal *internal(NULL);
1608 if (object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal)) == NULL) {
1609 // XXX: do something epic? ;P
1610 }
1611
1612 return internal;
1613 }
1614
1615 static CYInternal *Set(id self) {
1616 CYInternal *internal(NULL);
1617 if (Ivar ivar = object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal))) {
1618 if (internal == NULL) {
1619 internal = new CYInternal();
1620 object_setIvar(self, ivar, reinterpret_cast<id>(internal));
1621 }
1622 } else {
1623 // XXX: do something epic? ;P
1624 }
1625
1626 return internal;
1627 }
1628
1629 bool HasProperty(JSContextRef context, JSStringRef name) {
1630 if (object_ == NULL)
1631 return false;
1632 return JSObjectHasProperty(context, object_, name);
1633 }
1634
1635 JSValueRef GetProperty(JSContextRef context, JSStringRef name) {
1636 if (object_ == NULL)
1637 return NULL;
1638 return CYGetProperty(context, object_, name);
1639 }
1640
1641 void SetProperty(JSContextRef context, JSStringRef name, JSValueRef value) {
1642 if (object_ == NULL)
1643 object_ = JSObjectMake(context, NULL, NULL);
1644 CYSetProperty(context, object_, name, value);
1645 }
1646 };
1647
1648 JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1649 Selector_privateData *internal(new Selector_privateData(sel));
1650 return JSObjectMake(context, Selector_, internal);
1651 }
1652
1653 JSObjectRef CYMakePointer(JSContextRef context, void *pointer, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
1654 Pointer *internal(new Pointer(pointer, type, owner));
1655 return JSObjectMake(context, Pointer_, internal);
1656 }
1657
1658 JSObjectRef CYMakeFunctor(JSContextRef context, void (*function)(), const char *type) {
1659 Functor_privateData *internal(new Functor_privateData(type, function));
1660 return JSObjectMake(context, Functor_, internal);
1661 }
1662
1663 const char *CYPoolCString(apr_pool_t *pool, JSStringRef value) {
1664 if (pool == NULL) {
1665 const char *string([CYCastNSString(NULL, value) UTF8String]);
1666 return string;
1667 } else {
1668 size_t size(JSStringGetMaximumUTF8CStringSize(value));
1669 char *string(new(pool) char[size]);
1670 JSStringGetUTF8CString(value, string, size);
1671 return string;
1672 }
1673 }
1674
1675 const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1676 return JSValueIsNull(context, value) ? NULL : CYPoolCString(pool, CYJSString(context, value));
1677 }
1678
1679 bool CYGetOffset(apr_pool_t *pool, JSStringRef value, ssize_t &index) {
1680 return CYGetOffset(CYPoolCString(pool, value), index);
1681 }
1682
1683 // XXX: this macro is unhygenic
1684 #define CYCastCString(context, value) ({ \
1685 char *utf8; \
1686 if (value == NULL) \
1687 utf8 = NULL; \
1688 else if (JSStringRef string = CYCopyJSString(context, value)) { \
1689 size_t size(JSStringGetMaximumUTF8CStringSize(string)); \
1690 utf8 = reinterpret_cast<char *>(alloca(size)); \
1691 JSStringGetUTF8CString(string, utf8, size); \
1692 JSStringRelease(string); \
1693 } else \
1694 utf8 = NULL; \
1695 utf8; \
1696 })
1697
1698 void *CYCastPointer_(JSContextRef context, JSValueRef value) {
1699 switch (JSValueGetType(context, value)) {
1700 case kJSTypeNull:
1701 return NULL;
1702 /*case kJSTypeString:
1703 return dlsym(RTLD_DEFAULT, CYCastCString(context, value));
1704 case kJSTypeObject:
1705 if (JSValueIsObjectOfClass(context, value, Pointer_)) {
1706 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate((JSObjectRef) value)));
1707 return internal->value_;
1708 }*/
1709 default:
1710 double number(CYCastDouble(context, value));
1711 if (std::isnan(number))
1712 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"cannot convert value to pointer" userInfo:nil];
1713 return reinterpret_cast<void *>(static_cast<uintptr_t>(static_cast<long long>(number)));
1714 }
1715 }
1716
1717 template <typename Type_>
1718 _finline Type_ CYCastPointer(JSContextRef context, JSValueRef value) {
1719 return reinterpret_cast<Type_>(CYCastPointer_(context, value));
1720 }
1721
1722 SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1723 if (JSValueIsObjectOfClass(context, value, Selector_)) {
1724 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1725 return reinterpret_cast<SEL>(internal->value_);
1726 } else
1727 return CYCastPointer<SEL>(context, value);
1728 }
1729
1730 void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) {
1731 switch (type->primitive) {
1732 case sig::boolean_P:
1733 *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
1734 break;
1735
1736 #define CYPoolFFI_(primitive, native) \
1737 case sig::primitive ## _P: \
1738 *reinterpret_cast<native *>(data) = CYCastDouble(context, value); \
1739 break;
1740
1741 CYPoolFFI_(uchar, unsigned char)
1742 CYPoolFFI_(char, char)
1743 CYPoolFFI_(ushort, unsigned short)
1744 CYPoolFFI_(short, short)
1745 CYPoolFFI_(ulong, unsigned long)
1746 CYPoolFFI_(long, long)
1747 CYPoolFFI_(uint, unsigned int)
1748 CYPoolFFI_(int, int)
1749 CYPoolFFI_(ulonglong, unsigned long long)
1750 CYPoolFFI_(longlong, long long)
1751 CYPoolFFI_(float, float)
1752 CYPoolFFI_(double, double)
1753
1754 case sig::object_P:
1755 case sig::typename_P:
1756 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1757 break;
1758
1759 case sig::selector_P:
1760 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1761 break;
1762
1763 case sig::pointer_P:
1764 *reinterpret_cast<void **>(data) = CYCastPointer<void *>(context, value);
1765 break;
1766
1767 case sig::string_P:
1768 *reinterpret_cast<const char **>(data) = CYPoolCString(pool, context, value);
1769 break;
1770
1771 case sig::struct_P: {
1772 uint8_t *base(reinterpret_cast<uint8_t *>(data));
1773 JSObjectRef aggregate(JSValueIsObject(context, value) ? (JSObjectRef) value : NULL);
1774 for (size_t index(0); index != type->data.signature.count; ++index) {
1775 sig::Element *element(&type->data.signature.elements[index]);
1776 ffi_type *field(ffi->elements[index]);
1777
1778 JSValueRef rhs;
1779 if (aggregate == NULL)
1780 rhs = value;
1781 else {
1782 rhs = CYGetProperty(context, aggregate, index);
1783 if (JSValueIsUndefined(context, rhs)) {
1784 if (element->name != NULL)
1785 rhs = CYGetProperty(context, aggregate, CYJSString(element->name));
1786 else
1787 goto undefined;
1788 if (JSValueIsUndefined(context, rhs)) undefined:
1789 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"unable to extract structure value" userInfo:nil];
1790 }
1791 }
1792
1793 CYPoolFFI(pool, context, element->type, field, base, rhs);
1794 // XXX: alignment?
1795 base += field->size;
1796 }
1797 } break;
1798
1799 case sig::void_P:
1800 break;
1801
1802 default:
1803 NSLog(@"CYPoolFFI(%c)\n", type->primitive);
1804 _assert(false);
1805 }
1806 }
1807
1808 JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize = false, JSObjectRef owner = NULL) {
1809 JSValueRef value;
1810
1811 switch (type->primitive) {
1812 case sig::boolean_P:
1813 value = CYCastJSValue(context, *reinterpret_cast<bool *>(data));
1814 break;
1815
1816 #define CYFromFFI_(primitive, native) \
1817 case sig::primitive ## _P: \
1818 value = CYCastJSValue(context, *reinterpret_cast<native *>(data)); \
1819 break;
1820
1821 CYFromFFI_(uchar, unsigned char)
1822 CYFromFFI_(char, char)
1823 CYFromFFI_(ushort, unsigned short)
1824 CYFromFFI_(short, short)
1825 CYFromFFI_(ulong, unsigned long)
1826 CYFromFFI_(long, long)
1827 CYFromFFI_(uint, unsigned int)
1828 CYFromFFI_(int, int)
1829 CYFromFFI_(ulonglong, unsigned long long)
1830 CYFromFFI_(longlong, long long)
1831 CYFromFFI_(float, float)
1832 CYFromFFI_(double, double)
1833
1834 case sig::object_P: {
1835 if (id object = *reinterpret_cast<id *>(data)) {
1836 value = CYCastJSValue(context, object);
1837 if (initialize)
1838 [object release];
1839 } else goto null;
1840 } break;
1841
1842 case sig::typename_P:
1843 value = CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
1844 break;
1845
1846 case sig::selector_P:
1847 if (SEL sel = *reinterpret_cast<SEL *>(data))
1848 value = CYMakeSelector(context, sel);
1849 else goto null;
1850 break;
1851
1852 case sig::pointer_P:
1853 if (void *pointer = *reinterpret_cast<void **>(data))
1854 value = CYMakePointer(context, pointer, type->data.data.type, ffi, owner);
1855 else goto null;
1856 break;
1857
1858 case sig::string_P:
1859 if (char *utf8 = *reinterpret_cast<char **>(data))
1860 value = CYCastJSValue(context, utf8);
1861 else goto null;
1862 break;
1863
1864 case sig::struct_P:
1865 value = CYMakeStruct(context, data, type, ffi, owner);
1866 break;
1867
1868 case sig::void_P:
1869 value = CYJSUndefined(context);
1870 break;
1871
1872 null:
1873 value = CYJSNull(context);
1874 break;
1875
1876 default:
1877 NSLog(@"CYFromFFI(%c)\n", type->primitive);
1878 _assert(false);
1879 }
1880
1881 return value;
1882 }
1883
1884 static bool CYImplements(id object, Class _class, SEL selector, bool devoid) {
1885 if (Method method = class_getInstanceMethod(_class, selector)) {
1886 if (!devoid)
1887 return true;
1888 char type[16];
1889 method_getReturnType(method, type, sizeof(type));
1890 if (type[0] != 'v')
1891 return true;
1892 }
1893
1894 // XXX: possibly use a more "awesome" check?
1895 return false;
1896 }
1897
1898 const char *CYPoolTypeEncoding(apr_pool_t *pool, Class _class, SEL sel, Method method) {
1899 if (method != NULL)
1900 return method_getTypeEncoding(method);
1901 else if (NSString *type = [[Bridge_ objectAtIndex:1] objectForKey:CYCastNSString(pool, sel_getName(sel))])
1902 return CYPoolCString(pool, type);
1903 else
1904 return NULL;
1905 }
1906
1907 void FunctionClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1908 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
1909
1910 JSContextRef context(internal->context_);
1911
1912 size_t count(internal->cif_.nargs);
1913 JSValueRef values[count];
1914
1915 for (size_t index(0); index != count; ++index)
1916 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
1917
1918 JSValueRef value(CYCallAsFunction(context, internal->function_, NULL, count, values));
1919 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
1920 }
1921
1922 void MessageClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1923 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
1924
1925 JSContextRef context(internal->context_);
1926
1927 size_t count(internal->cif_.nargs);
1928 JSValueRef values[count];
1929
1930 for (size_t index(0); index != count; ++index)
1931 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
1932
1933 JSObjectRef _this(CYCastJSObject(context, values[0]));
1934
1935 JSValueRef value(CYCallAsFunction(context, internal->function_, _this, count - 2, values + 2));
1936 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
1937 }
1938
1939 Closure_privateData *CYMakeFunctor_(JSContextRef context, JSObjectRef function, const char *type, void (*callback)(ffi_cif *, void *, void **, void *)) {
1940 // XXX: in case of exceptions this will leak
1941 // XXX: in point of fact, this may /need/ to leak :(
1942 Closure_privateData *internal(new Closure_privateData(type));
1943
1944 ffi_closure *closure((ffi_closure *) _syscall(mmap(
1945 NULL, sizeof(ffi_closure),
1946 PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE,
1947 -1, 0
1948 )));
1949
1950 ffi_status status(ffi_prep_closure(closure, &internal->cif_, callback, internal));
1951 _assert(status == FFI_OK);
1952
1953 _syscall(mprotect(closure, sizeof(*closure), PROT_READ | PROT_EXEC));
1954
1955 internal->value_ = closure;
1956
1957 internal->context_ = CYGetJSContext();
1958 internal->function_ = function;
1959
1960 return internal;
1961 }
1962
1963 JSObjectRef CYMakeFunctor(JSContextRef context, JSObjectRef function, const char *type) {
1964 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &FunctionClosure_));
1965 return JSObjectMake(context, Functor_, internal);
1966 }
1967
1968 static JSObjectRef CYMakeFunctor(JSContextRef context, JSValueRef value, const char *type) {
1969 JSValueRef exception(NULL);
1970 bool function(JSValueIsInstanceOfConstructor(context, value, Function_, &exception));
1971 CYThrow(context, exception);
1972
1973 if (function) {
1974 JSObjectRef function(CYCastJSObject(context, value));
1975 return CYMakeFunctor(context, function, type);
1976 } else {
1977 void (*function)()(CYCastPointer<void (*)()>(context, value));
1978 return CYMakeFunctor(context, function, type);
1979 }
1980 }
1981
1982 static JSObjectRef CYMakeMessage(JSContextRef context, SEL sel, IMP imp, const char *type) {
1983 Message_privateData *internal(new Message_privateData(sel, type, imp));
1984 return JSObjectMake(context, Message_, internal);
1985 }
1986
1987 static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *type) {
1988 JSObjectRef function(CYCastJSObject(context, value));
1989 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &MessageClosure_));
1990 return reinterpret_cast<IMP>(internal->GetValue());
1991 }
1992
1993 static bool Prototype_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1994 Prototype *internal(reinterpret_cast<Prototype *>(JSObjectGetPrivate(object)));
1995 Class _class(internal->GetValue());
1996
1997 CYPool pool;
1998 const char *name(CYPoolCString(pool, property));
1999
2000 if (SEL sel = sel_getUid(name))
2001 if (class_getInstanceMethod(_class, sel) != NULL)
2002 return true;
2003
2004 return false;
2005 }
2006
2007 static JSValueRef Prototype_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2008 Prototype *internal(reinterpret_cast<Prototype *>(JSObjectGetPrivate(object)));
2009 Class _class(internal->GetValue());
2010
2011 CYPool pool;
2012 const char *name(CYPoolCString(pool, property));
2013
2014 if (SEL sel = sel_getUid(name))
2015 if (Method method = class_getInstanceMethod(_class, sel))
2016 return CYMakeMessage(context, sel, method_getImplementation(method), method_getTypeEncoding(method));
2017
2018 return NULL;
2019 }
2020
2021 static bool Prototype_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2022 Prototype *internal(reinterpret_cast<Prototype *>(JSObjectGetPrivate(object)));
2023 Class _class(internal->GetValue());
2024
2025 CYPool pool;
2026 const char *name(CYPoolCString(pool, property));
2027
2028 SEL sel(sel_registerName(name));
2029
2030 Method method(class_getInstanceMethod(_class, sel));
2031
2032 const char *type;
2033 IMP imp;
2034
2035 if (JSValueIsObjectOfClass(context, value, Message_)) {
2036 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
2037 type = sig::Unparse(pool, &message->signature_);
2038 imp = reinterpret_cast<IMP>(message->GetValue());
2039 } else {
2040 type = CYPoolTypeEncoding(pool, _class, sel, method);
2041 imp = CYMakeMessage(context, value, type);
2042 }
2043
2044 if (method != NULL)
2045 method_setImplementation(method, imp);
2046 else
2047 class_replaceMethod(_class, sel, imp, type);
2048
2049 return true;
2050 }
2051
2052 #if !__OBJC2__
2053 static bool Prototype_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2054 Prototype *internal(reinterpret_cast<Prototype *>(JSObjectGetPrivate(object)));
2055 Class _class(internal->GetValue());
2056
2057 CYPool pool;
2058 const char *name(CYPoolCString(pool, property));
2059
2060 if (SEL sel = sel_getUid(name))
2061 if (Method method = class_getInstanceMethod(_class, sel)) {
2062 objc_method_list list = {NULL, 1, {method}};
2063 class_removeMethods(_class, &list);
2064 return true;
2065 }
2066
2067 return false;
2068 }
2069 #endif
2070
2071 static void Prototype_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2072 Prototype *internal(reinterpret_cast<Prototype *>(JSObjectGetPrivate(object)));
2073 Class _class(internal->GetValue());
2074
2075 unsigned int size;
2076 Method *data(class_copyMethodList(_class, &size));
2077 for (size_t i(0); i != size; ++i)
2078 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
2079 free(data);
2080 }
2081
2082 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2083 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2084 id self(internal->GetValue());
2085
2086 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
2087 return true;
2088
2089 CYPool pool;
2090 NSString *name(CYCastNSString(pool, property));
2091
2092 if (CYInternal *internal = CYInternal::Get(self))
2093 if (internal->HasProperty(context, property))
2094 return true;
2095
2096 CYPoolTry {
2097 if ([self cy$hasProperty:name])
2098 return true;
2099 } CYPoolCatch(false)
2100
2101 const char *string(CYPoolCString(pool, name));
2102 Class _class(object_getClass(self));
2103
2104 if (class_getProperty(_class, string) != NULL)
2105 return true;
2106
2107 if (SEL sel = sel_getUid(string))
2108 if (CYImplements(self, _class, sel, true))
2109 return true;
2110
2111 return false;
2112 }
2113
2114 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2115 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2116 id self(internal->GetValue());
2117
2118 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
2119 return Internal::Make(context, self, object);
2120
2121 CYTry {
2122 CYPool pool;
2123 NSString *name(CYCastNSString(pool, property));
2124
2125 if (CYInternal *internal = CYInternal::Get(self))
2126 if (JSValueRef value = internal->GetProperty(context, property))
2127 return value;
2128
2129 CYPoolTry {
2130 if (NSObject *data = [self cy$getProperty:name])
2131 return CYCastJSValue(context, data);
2132 } CYPoolCatch(NULL)
2133
2134 const char *string(CYPoolCString(pool, name));
2135 Class _class(object_getClass(self));
2136
2137 if (objc_property_t property = class_getProperty(_class, string)) {
2138 PropertyAttributes attributes(property);
2139 SEL sel(sel_registerName(attributes.Getter()));
2140 return CYSendMessage(pool, context, self, sel, 0, NULL, false, exception);
2141 }
2142
2143 if (SEL sel = sel_getUid(string))
2144 if (CYImplements(self, _class, sel, true))
2145 return CYSendMessage(pool, context, self, sel, 0, NULL, false, exception);
2146
2147 return NULL;
2148 } CYCatch
2149 }
2150
2151 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2152 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2153 id self(internal->GetValue());
2154
2155 CYPool pool;
2156
2157 CYTry {
2158 NSString *name(CYCastNSString(pool, property));
2159 NSString *data(CYCastNSObject(pool, context, value));
2160
2161 CYPoolTry {
2162 if ([self cy$setProperty:name to:data])
2163 return true;
2164 } CYPoolCatch(NULL)
2165
2166 const char *string(CYPoolCString(pool, name));
2167 Class _class(object_getClass(self));
2168
2169 if (objc_property_t property = class_getProperty(_class, string)) {
2170 PropertyAttributes attributes(property);
2171 if (const char *setter = attributes.Setter()) {
2172 SEL sel(sel_registerName(setter));
2173 JSValueRef arguments[1] = {value};
2174 CYSendMessage(pool, context, self, sel, 1, arguments, false, exception);
2175 return true;
2176 }
2177 }
2178
2179 size_t length(strlen(string));
2180
2181 char set[length + 5];
2182
2183 set[0] = 's';
2184 set[1] = 'e';
2185 set[2] = 't';
2186
2187 if (string[0] != '\0') {
2188 set[3] = toupper(string[0]);
2189 memcpy(set + 4, string + 1, length - 1);
2190 }
2191
2192 set[length + 3] = ':';
2193 set[length + 4] = '\0';
2194
2195 if (SEL sel = sel_getUid(set))
2196 if (CYImplements(self, _class, sel, false)) {
2197 JSValueRef arguments[1] = {value};
2198 CYSendMessage(pool, context, self, sel, 1, arguments, false, exception);
2199 }
2200
2201 if (CYInternal *internal = CYInternal::Set(self)) {
2202 internal->SetProperty(context, property, value);
2203 return true;
2204 }
2205
2206 return false;
2207 } CYCatch
2208 }
2209
2210 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2211 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2212 id self(internal->GetValue());
2213
2214 CYTry {
2215 CYPoolTry {
2216 NSString *name(CYCastNSString(NULL, property));
2217 return [self cy$deleteProperty:name];
2218 } CYPoolCatch(NULL)
2219 } CYCatch
2220 }
2221
2222 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2223 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2224 id self(internal->GetValue());
2225
2226 CYPool pool;
2227 Class _class(object_getClass(self));
2228
2229 {
2230 unsigned int size;
2231 objc_property_t *data(class_copyPropertyList(_class, &size));
2232 for (size_t i(0); i != size; ++i)
2233 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
2234 free(data);
2235 }
2236 }
2237
2238 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2239 CYTry {
2240 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2241 JSObjectRef value(Instance::Make(context, [internal->GetValue() alloc], Instance::Uninitialized));
2242 return value;
2243 } CYCatch
2244 }
2245
2246 static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2247 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2248 CYPool pool;
2249
2250 id self(internal->GetValue());
2251 const char *name(CYPoolCString(pool, property));
2252
2253 if (object_getInstanceVariable(self, name, NULL) != NULL)
2254 return true;
2255
2256 return false;
2257 }
2258
2259 static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2260 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2261 CYPool pool;
2262
2263 CYTry {
2264 id self(internal->GetValue());
2265 const char *name(CYPoolCString(pool, property));
2266
2267 if (Ivar ivar = object_getInstanceVariable(self, name, NULL)) {
2268 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
2269 return CYFromFFI(context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar));
2270 }
2271
2272 return NULL;
2273 } CYCatch
2274 }
2275
2276 static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2277 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2278 CYPool pool;
2279
2280 CYTry {
2281 id self(internal->GetValue());
2282 const char *name(CYPoolCString(pool, property));
2283
2284 if (Ivar ivar = object_getInstanceVariable(self, name, NULL)) {
2285 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
2286 CYPoolFFI(pool, context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
2287 return true;
2288 }
2289
2290 return false;
2291 } CYCatch
2292 }
2293
2294 static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
2295 if (Class super = class_getSuperclass(_class))
2296 Internal_getPropertyNames_(super, names);
2297
2298 unsigned int size;
2299 Ivar *data(class_copyIvarList(_class, &size));
2300 for (size_t i(0); i != size; ++i)
2301 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
2302 free(data);
2303 }
2304
2305 static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2306 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2307 CYPool pool;
2308
2309 id self(internal->GetValue());
2310 Class _class(object_getClass(self));
2311
2312 Internal_getPropertyNames_(_class, names);
2313 }
2314
2315 static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2316 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2317 return internal->owner_;
2318 }
2319
2320 bool Index_(apr_pool_t *pool, Struct_privateData *internal, JSStringRef property, ssize_t &index, uint8_t *&base) {
2321 Type_privateData *typical(internal->type_);
2322 sig::Type *type(typical->type_);
2323 if (type == NULL)
2324 return false;
2325
2326 const char *name(CYPoolCString(pool, property));
2327 size_t length(strlen(name));
2328 double number(CYCastDouble(name, length));
2329
2330 size_t count(type->data.signature.count);
2331
2332 if (std::isnan(number)) {
2333 if (property == NULL)
2334 return false;
2335
2336 sig::Element *elements(type->data.signature.elements);
2337
2338 for (size_t local(0); local != count; ++local) {
2339 sig::Element *element(&elements[local]);
2340 if (element->name != NULL && strcmp(name, element->name) == 0) {
2341 index = local;
2342 goto base;
2343 }
2344 }
2345
2346 return false;
2347 } else {
2348 index = static_cast<ssize_t>(number);
2349 if (index != number || index < 0 || static_cast<size_t>(index) >= count)
2350 return false;
2351 }
2352
2353 base:
2354 ffi_type **elements(typical->GetFFI()->elements);
2355
2356 base = reinterpret_cast<uint8_t *>(internal->value_);
2357 for (ssize_t local(0); local != index; ++local)
2358 base += elements[local]->size;
2359
2360 return true;
2361 }
2362
2363 static JSValueRef Pointer_getIndex(JSContextRef context, JSObjectRef object, size_t index, JSValueRef *exception) {
2364 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2365 Type_privateData *typical(internal->type_);
2366
2367 ffi_type *ffi(typical->GetFFI());
2368
2369 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
2370 base += ffi->size * index;
2371
2372 JSObjectRef owner(internal->owner_ ?: object);
2373
2374 CYTry {
2375 return CYFromFFI(context, typical->type_, ffi, base, false, owner);
2376 } CYCatch
2377 }
2378
2379 static JSValueRef Pointer_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2380 CYPool pool;
2381 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2382 Type_privateData *typical(internal->type_);
2383
2384 if (typical->type_ == NULL)
2385 return NULL;
2386
2387 ssize_t offset;
2388 if (!CYGetOffset(pool, property, offset))
2389 return NULL;
2390
2391 return Pointer_getIndex(context, object, offset, exception);
2392 }
2393
2394 static JSValueRef Pointer_getProperty_$cyi(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2395 return Pointer_getIndex(context, object, 0, exception);
2396 }
2397
2398 static bool Pointer_setIndex(JSContextRef context, JSObjectRef object, size_t index, JSValueRef value, JSValueRef *exception) {
2399 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2400 Type_privateData *typical(internal->type_);
2401
2402 ffi_type *ffi(typical->GetFFI());
2403
2404 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
2405 base += ffi->size * index;
2406
2407 CYTry {
2408 CYPoolFFI(NULL, context, typical->type_, ffi, base, value);
2409 return true;
2410 } CYCatch
2411 }
2412
2413 static bool Pointer_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2414 CYPool pool;
2415 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2416 Type_privateData *typical(internal->type_);
2417
2418 if (typical->type_ == NULL)
2419 return NULL;
2420
2421 ssize_t offset;
2422 if (!CYGetOffset(pool, property, offset))
2423 return NULL;
2424
2425 return Pointer_setIndex(context, object, offset, value, exception);
2426 }
2427
2428 static bool Pointer_setProperty_$cyi(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2429 return Pointer_setIndex(context, object, 0, value, exception);
2430 }
2431
2432 static JSValueRef Struct_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2433 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(_this)));
2434 Type_privateData *typical(internal->type_);
2435 return CYMakePointer(context, internal->value_, typical->type_, typical->ffi_, _this);
2436 }
2437
2438 static JSValueRef Struct_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2439 CYPool pool;
2440 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
2441 Type_privateData *typical(internal->type_);
2442
2443 ssize_t index;
2444 uint8_t *base;
2445
2446 if (!Index_(pool, internal, property, index, base))
2447 return NULL;
2448
2449 JSObjectRef owner(internal->owner_ ?: object);
2450
2451 CYTry {
2452 return CYFromFFI(context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, false, owner);
2453 } CYCatch
2454 }
2455
2456 static bool Struct_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2457 CYPool pool;
2458 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
2459 Type_privateData *typical(internal->type_);
2460
2461 ssize_t index;
2462 uint8_t *base;
2463
2464 if (!Index_(pool, internal, property, index, base))
2465 return false;
2466
2467 CYTry {
2468 CYPoolFFI(NULL, context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, value);
2469 return true;
2470 } CYCatch
2471 }
2472
2473 static void Struct_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2474 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
2475 Type_privateData *typical(internal->type_);
2476 sig::Type *type(typical->type_);
2477
2478 if (type == NULL)
2479 return;
2480
2481 size_t count(type->data.signature.count);
2482 sig::Element *elements(type->data.signature.elements);
2483
2484 char number[32];
2485
2486 for (size_t index(0); index != count; ++index) {
2487 const char *name;
2488 name = elements[index].name;
2489
2490 if (name == NULL) {
2491 sprintf(number, "%lu", index);
2492 name = number;
2493 }
2494
2495 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
2496 }
2497 }
2498
2499 JSValueRef CYCallFunction(apr_pool_t *pool, JSContextRef context, size_t setups, void *setup[], size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception, sig::Signature *signature, ffi_cif *cif, void (*function)()) {
2500 CYTry {
2501 if (setups + count != signature->count - 1)
2502 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to ffi function" userInfo:nil];
2503
2504 size_t size(setups + count);
2505 void *values[size];
2506 memcpy(values, setup, sizeof(void *) * setups);
2507
2508 for (size_t index(setups); index != size; ++index) {
2509 sig::Element *element(&signature->elements[index + 1]);
2510 ffi_type *ffi(cif->arg_types[index]);
2511 // XXX: alignment?
2512 values[index] = new(pool) uint8_t[ffi->size];
2513 CYPoolFFI(pool, context, element->type, ffi, values[index], arguments[index - setups]);
2514 }
2515
2516 uint8_t value[cif->rtype->size];
2517 ffi_call(cif, function, value, values);
2518
2519 return CYFromFFI(context, signature->elements[0].type, cif->rtype, value, initialize);
2520 } CYCatch
2521 }
2522
2523 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2524 CYTry {
2525 CYPool pool;
2526 NSString *name(CYCastNSString(pool, property));
2527 if (Class _class = NSClassFromString(name))
2528 return CYMakeInstance(context, _class, true);
2529 return NULL;
2530 } CYCatch
2531 }
2532
2533 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2534 size_t size(objc_getClassList(NULL, 0));
2535 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
2536
2537 get:
2538 size_t writ(objc_getClassList(data, size));
2539 if (size < writ) {
2540 size = writ;
2541 if (Class *copy = reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ))) {
2542 data = copy;
2543 goto get;
2544 } else goto done;
2545 }
2546
2547 for (size_t i(0); i != writ; ++i)
2548 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
2549
2550 done:
2551 free(data);
2552 }
2553
2554 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2555 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2556
2557 CYTry {
2558 CYPool pool;
2559 const char *name(CYPoolCString(pool, property));
2560 unsigned int size;
2561 const char **data(objc_copyClassNamesForImage(internal, &size));
2562 JSValueRef value;
2563 for (size_t i(0); i != size; ++i)
2564 if (strcmp(name, data[i]) == 0) {
2565 if (Class _class = objc_getClass(name)) {
2566 value = CYMakeInstance(context, _class, true);
2567 goto free;
2568 } else
2569 break;
2570 }
2571 value = NULL;
2572 free:
2573 free(data);
2574 return value;
2575 } CYCatch
2576 }
2577
2578 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2579 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2580 unsigned int size;
2581 const char **data(objc_copyClassNamesForImage(internal, &size));
2582 for (size_t i(0); i != size; ++i)
2583 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2584 free(data);
2585 }
2586
2587 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2588 CYTry {
2589 CYPool pool;
2590 const char *name(CYPoolCString(pool, property));
2591 unsigned int size;
2592 const char **data(objc_copyImageNames(&size));
2593 for (size_t i(0); i != size; ++i)
2594 if (strcmp(name, data[i]) == 0) {
2595 name = data[i];
2596 goto free;
2597 }
2598 name = NULL;
2599 free:
2600 free(data);
2601 if (name == NULL)
2602 return NULL;
2603 JSObjectRef value(JSObjectMake(context, NULL, NULL));
2604 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(name)));
2605 return value;
2606 } CYCatch
2607 }
2608
2609 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2610 unsigned int size;
2611 const char **data(objc_copyImageNames(&size));
2612 for (size_t i(0); i != size; ++i)
2613 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2614 free(data);
2615 }
2616
2617 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2618 CYTry {
2619 CYPool pool;
2620 NSString *name(CYCastNSString(pool, property));
2621 if (Protocol *protocol = NSProtocolFromString(name))
2622 return CYMakeInstance(context, protocol, true);
2623 return NULL;
2624 } CYCatch
2625 }
2626
2627 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2628 unsigned int size;
2629 Protocol **data(objc_copyProtocolList(&size));
2630 for (size_t i(0); i != size; ++i)
2631 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
2632 free(data);
2633 }
2634
2635 static JSValueRef Runtime_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2636 if (JSStringIsEqualToUTF8CString(property, "nil"))
2637 return Instance::Make(context, nil);
2638
2639 CYTry {
2640 CYPool pool;
2641 NSString *name(CYCastNSString(pool, property));
2642 if (Class _class = NSClassFromString(name))
2643 return CYMakeInstance(context, _class, true);
2644 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:0] objectForKey:name])
2645 switch ([[entry objectAtIndex:0] intValue]) {
2646 case 0:
2647 return JSEvaluateScript(CYGetJSContext(), CYJSString([entry objectAtIndex:1]), NULL, NULL, 0, NULL);
2648 case 1:
2649 return CYMakeFunctor(context, reinterpret_cast<void (*)()>([name cy$symbol]), CYPoolCString(pool, [entry objectAtIndex:1]));
2650 case 2:
2651 // XXX: this is horrendously inefficient
2652 sig::Signature signature;
2653 sig::Parse(pool, &signature, CYPoolCString(pool, [entry objectAtIndex:1]), &Structor_);
2654 ffi_cif cif;
2655 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2656 return CYFromFFI(context, signature.elements[0].type, cif.rtype, [name cy$symbol]);
2657 }
2658 return NULL;
2659 } CYCatch
2660 }
2661
2662 bool stret(ffi_type *ffi_type) {
2663 return ffi_type->type == FFI_TYPE_STRUCT && (
2664 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
2665 struct_forward_array[ffi_type->size] != 0
2666 );
2667 }
2668
2669 extern "C" {
2670 int *_NSGetArgc(void);
2671 char ***_NSGetArgv(void);
2672 int UIApplicationMain(int argc, char *argv[], NSString *principalClassName, NSString *delegateClassName);
2673 }
2674
2675 static JSValueRef System_print(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2676 CYTry {
2677 NSLog(@"%s", CYCastCString(context, arguments[0]));
2678 return CYJSUndefined(context);
2679 } CYCatch
2680 }
2681
2682 JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception) {
2683 const char *type;
2684
2685 Class _class(object_getClass(self));
2686 if (Method method = class_getInstanceMethod(_class, _cmd))
2687 type = method_getTypeEncoding(method);
2688 else {
2689 CYTry {
2690 CYPoolTry {
2691 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
2692 if (method == nil)
2693 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"unrecognized selector %s sent to object %p", sel_getName(_cmd), self] userInfo:nil];
2694 type = CYPoolCString(pool, [method _typeString]);
2695 } CYPoolCatch(NULL)
2696 } CYCatch
2697 }
2698
2699 void *setup[2];
2700 setup[0] = &self;
2701 setup[1] = &_cmd;
2702
2703 sig::Signature signature;
2704 sig::Parse(pool, &signature, type, &Structor_);
2705
2706 ffi_cif cif;
2707 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2708
2709 void (*function)() = stret(cif.rtype) ? reinterpret_cast<void (*)()>(&objc_msgSend_stret) : reinterpret_cast<void (*)()>(&objc_msgSend);
2710 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, exception, &signature, &cif, function);
2711 }
2712
2713 static size_t Nonce_(0);
2714
2715 static JSValueRef $cyq(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2716 char name[16];
2717 sprintf(name, "%s%zu", CYCastCString(context, arguments[0]), Nonce_++);
2718 return CYCastJSValue(context, name);
2719 }
2720
2721 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2722 CYPool pool;
2723
2724 bool uninitialized;
2725
2726 id self;
2727 SEL _cmd;
2728
2729 CYTry {
2730 if (count < 2)
2731 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"too few arguments to objc_msgSend" userInfo:nil];
2732
2733 if (JSValueIsObjectOfClass(context, arguments[0], Instance_)) {
2734 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2735 self = internal->GetValue();
2736 uninitialized = internal->IsUninitialized();
2737 if (uninitialized)
2738 internal->value_ = nil;
2739 } else {
2740 self = CYCastNSObject(pool, context, arguments[0]);
2741 uninitialized = false;
2742 }
2743
2744 if (self == nil)
2745 return CYJSNull(context);
2746
2747 _cmd = CYCastSEL(context, arguments[1]);
2748 } CYCatch
2749
2750 return CYSendMessage(pool, context, self, _cmd, count - 2, arguments + 2, uninitialized, exception);
2751 }
2752
2753 MSHook(void, CYDealloc, id self, SEL sel) {
2754 CYInternal *internal;
2755 object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal));
2756 if (internal != NULL)
2757 delete internal;
2758 _CYDealloc(self, sel);
2759 }
2760
2761 MSHook(void, objc_registerClassPair, Class _class) {
2762 Class super(class_getSuperclass(_class));
2763 if (super == NULL || class_getInstanceVariable(super, "cy$internal_") == NULL) {
2764 class_addIvar(_class, "cy$internal_", sizeof(CYInternal *), log2(sizeof(CYInternal *)), "^{CYInternal}");
2765 MSHookMessage(_class, @selector(dealloc), MSHake(CYDealloc));
2766 }
2767
2768 _objc_registerClassPair(_class);
2769 }
2770
2771 static JSValueRef objc_registerClassPair_(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2772 CYTry {
2773 if (count != 1)
2774 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to objc_registerClassPair" userInfo:nil];
2775 CYPool pool;
2776 Class _class(CYCastNSObject(pool, context, arguments[0]));
2777 $objc_registerClassPair(_class);
2778 return CYJSUndefined(context);
2779 } CYCatch
2780 }
2781
2782 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2783 JSValueRef setup[count + 2];
2784 setup[0] = _this;
2785 setup[1] = object;
2786 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
2787 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
2788 }
2789
2790 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2791 CYPool pool;
2792 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
2793
2794 // XXX: handle Instance::Uninitialized?
2795 id self(CYCastNSObject(pool, context, _this));
2796
2797 void *setup[2];
2798 setup[0] = &self;
2799 setup[1] = &internal->sel_;
2800
2801 return CYCallFunction(pool, context, 2, setup, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
2802 }
2803
2804 static JSValueRef Functor_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2805 CYPool pool;
2806 Functor_privateData *internal(reinterpret_cast<Functor_privateData *>(JSObjectGetPrivate(object)));
2807 return CYCallFunction(pool, context, 0, NULL, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
2808 }
2809
2810 JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2811 CYTry {
2812 if (count != 1)
2813 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector constructor" userInfo:nil];
2814 const char *name(CYCastCString(context, arguments[0]));
2815 return CYMakeSelector(context, sel_registerName(name));
2816 } CYCatch
2817 }
2818
2819 JSObjectRef Pointer_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2820 CYTry {
2821 if (count != 2)
2822 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Functor constructor" userInfo:nil];
2823
2824 void *value(CYCastPointer<void *>(context, arguments[0]));
2825 const char *type(CYCastCString(context, arguments[1]));
2826
2827 CYPool pool;
2828
2829 sig::Signature signature;
2830 sig::Parse(pool, &signature, type, &Structor_);
2831
2832 return CYMakePointer(context, value, signature.elements[0].type, NULL, NULL);
2833 } CYCatch
2834 }
2835
2836 JSObjectRef CYMakeType(JSContextRef context, JSObjectRef object, const char *type) {
2837 Type_privateData *internal(new Type_privateData(NULL, type));
2838 return JSObjectMake(context, Type_, internal);
2839 }
2840
2841 JSObjectRef Type_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2842 CYTry {
2843 if (count != 1)
2844 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Type constructor" userInfo:nil];
2845 const char *type(CYCastCString(context, arguments[0]));
2846 return CYMakeType(context, object, type);
2847 } CYCatch
2848 }
2849
2850 static JSValueRef Type_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2851 CYTry {
2852 if (count != 1)
2853 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to type cast function" userInfo:nil];
2854 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
2855 sig::Type *type(internal->type_);
2856 ffi_type *ffi(internal->GetFFI());
2857 // XXX: alignment?
2858 uint8_t value[ffi->size];
2859 CYPool pool;
2860 CYPoolFFI(pool, context, type, ffi, value, arguments[0]);
2861 return CYFromFFI(context, type, ffi, value);
2862 } CYCatch
2863 }
2864
2865 static JSObjectRef Type_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2866 CYTry {
2867 if (count > 1)
2868 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to type cast function" userInfo:nil];
2869 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
2870 size_t size(count == 0 ? 0 : CYCastDouble(context, arguments[0]));
2871 // XXX: alignment?
2872 void *value(malloc(internal->GetFFI()->size * size));
2873 return CYMakePointer(context, value, internal->type_, internal->ffi_, NULL);
2874 } CYCatch
2875 }
2876
2877 JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2878 CYTry {
2879 if (count > 1)
2880 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Instance constructor" userInfo:nil];
2881 id self(count == 0 ? nil : CYCastPointer<id>(context, arguments[0]));
2882 return Instance::Make(context, self);
2883 } CYCatch
2884 }
2885
2886 JSObjectRef Functor_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2887 CYTry {
2888 if (count != 2)
2889 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Functor constructor" userInfo:nil];
2890 const char *type(CYCastCString(context, arguments[1]));
2891 return CYMakeFunctor(context, arguments[0], type);
2892 } CYCatch
2893 }
2894
2895 JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2896 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
2897 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2898 }
2899
2900 static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2901 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2902 Type_privateData *typical(internal->GetType());
2903
2904 sig::Type *type;
2905 ffi_type *ffi;
2906
2907 if (typical == NULL) {
2908 type = NULL;
2909 ffi = NULL;
2910 } else {
2911 type = typical->type_;
2912 ffi = typical->ffi_;
2913 }
2914
2915 return CYMakePointer(context, &internal->value_, type, ffi, object);
2916 }
2917
2918 static JSValueRef CYValue_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2919 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2920
2921 CYTry {
2922 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2923 } CYCatch
2924 }
2925
2926 static JSValueRef CYValue_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2927 return CYValue_callAsFunction_valueOf(context, object, _this, count, arguments, exception);
2928 }
2929
2930 static JSValueRef CYValue_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2931 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2932 char string[32];
2933 sprintf(string, "%p", internal->value_);
2934
2935 CYTry {
2936 return CYCastJSValue(context, string);
2937 } CYCatch
2938 }
2939
2940 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2941 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2942 return Instance::Make(context, object_getClass(internal->GetValue()));
2943 }
2944
2945 static JSValueRef Instance_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2946 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2947 id self(internal->GetValue());
2948 // XXX: this is a lame object_isClass
2949 if (class_getInstanceMethod(object_getClass(self), @selector(alloc)) == NULL)
2950 return CYJSUndefined(context);
2951 return Prototype::Make(context, self);
2952 }
2953
2954 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2955 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2956
2957 CYTry {
2958 CYPoolTry {
2959 return CYCastJSValue(context, CYJSString(CYPoolNSCYON(NULL, internal->GetValue())));
2960 } CYPoolCatch(NULL)
2961 } CYCatch
2962 }
2963
2964 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2965 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2966
2967 CYTry {
2968 CYPoolTry {
2969 NSString *key(count == 0 ? nil : CYCastNSString(NULL, CYJSString(context, arguments[0])));
2970 return CYCastJSValue(context, CYJSString([internal->GetValue() cy$toJSON:key]));
2971 } CYPoolCatch(NULL)
2972 } CYCatch
2973 }
2974
2975 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2976 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2977
2978 CYTry {
2979 CYPoolTry {
2980 return CYCastJSValue(context, CYJSString([internal->GetValue() description]));
2981 } CYPoolCatch(NULL)
2982 } CYCatch
2983 }
2984
2985 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2986 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2987
2988 CYTry {
2989 return CYCastJSValue(context, sel_getName(internal->GetValue()));
2990 } CYCatch
2991 }
2992
2993 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2994 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
2995 }
2996
2997 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2998 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2999 const char *name(sel_getName(internal->GetValue()));
3000
3001 CYTry {
3002 CYPoolTry {
3003 return CYCastJSValue(context, CYJSString([NSString stringWithFormat:@"@selector(%s)", name]));
3004 } CYPoolCatch(NULL)
3005 } CYCatch
3006 }
3007
3008 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3009 CYTry {
3010 if (count != 1)
3011 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector.type" userInfo:nil];
3012 CYPool pool;
3013 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
3014 Class _class(CYCastNSObject(pool, context, arguments[0]));
3015 SEL sel(internal->GetValue());
3016 Method method(class_getInstanceMethod(_class, sel));
3017 const char *type(CYPoolTypeEncoding(pool, _class, sel, method));
3018 return type == NULL ? CYJSNull(context) : CYCastJSValue(context, CYJSString(type));
3019 } CYCatch
3020 }
3021
3022 static JSValueRef Type_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3023 CYTry {
3024 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
3025 CYPool pool;
3026 const char *type(sig::Unparse(pool, internal->type_));
3027 CYPoolTry {
3028 return CYCastJSValue(context, CYJSString(type));
3029 } CYPoolCatch(NULL)
3030 } CYCatch
3031 }
3032
3033 static JSValueRef Type_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3034 CYTry {
3035 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
3036 CYPool pool;
3037 const char *type(sig::Unparse(pool, internal->type_));
3038 CYPoolTry {
3039 return CYCastJSValue(context, CYJSString([NSString stringWithFormat:@"new Type(%@)", [[NSString stringWithUTF8String:type] cy$toCYON]]));
3040 } CYPoolCatch(NULL)
3041 } CYCatch
3042 }
3043
3044 static JSValueRef Type_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3045 return Type_callAsFunction_toString(context, object, _this, count, arguments, exception);
3046 }
3047
3048 static JSStaticValue CYValue_staticValues[2] = {
3049 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
3050 {NULL, NULL, NULL, 0}
3051 };
3052
3053 static JSStaticValue Pointer_staticValues[2] = {
3054 {"$cyi", &Pointer_getProperty_$cyi, &Pointer_setProperty_$cyi, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3055 {NULL, NULL, NULL, 0}
3056 };
3057
3058 static JSStaticFunction Pointer_staticFunctions[4] = {
3059 {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3060 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3061 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3062 {NULL, NULL, 0}
3063 };
3064
3065 static JSStaticFunction Struct_staticFunctions[2] = {
3066 {"$cya", &Struct_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3067 {NULL, NULL, 0}
3068 };
3069
3070 static JSStaticFunction Functor_staticFunctions[4] = {
3071 {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3072 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3073 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3074 {NULL, NULL, 0}
3075 };
3076
3077 static JSStaticValue Instance_staticValues[4] = {
3078 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3079 {"prototype", &Instance_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3080 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3081 {NULL, NULL, NULL, 0}
3082 };
3083
3084 static JSStaticFunction Instance_staticFunctions[5] = {
3085 {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3086 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3087 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3088 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3089 {NULL, NULL, 0}
3090 };
3091
3092 static JSStaticFunction Internal_staticFunctions[2] = {
3093 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3094 {NULL, NULL, 0}
3095 };
3096
3097 static JSStaticFunction Selector_staticFunctions[5] = {
3098 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3099 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3100 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3101 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3102 {NULL, NULL, 0}
3103 };
3104
3105 static JSStaticFunction Type_staticFunctions[4] = {
3106 {"toCYON", &Type_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3107 {"toJSON", &Type_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3108 {"toString", &Type_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3109 {NULL, NULL, 0}
3110 };
3111
3112 CYDriver::CYDriver(const std::string &filename) :
3113 state_(CYClear),
3114 data_(NULL),
3115 size_(0),
3116 file_(NULL),
3117 filename_(filename),
3118 source_(NULL)
3119 {
3120 ScannerInit();
3121 }
3122
3123 CYDriver::~CYDriver() {
3124 ScannerDestroy();
3125 }
3126
3127 void cy::parser::error(const cy::parser::location_type &location, const std::string &message) {
3128 CYDriver::Error error;
3129 error.location_ = location;
3130 error.message_ = message;
3131 driver.errors_.push_back(error);
3132 }
3133
3134 void CYSetArgs(int argc, const char *argv[]) {
3135 JSContextRef context(CYGetJSContext());
3136 JSValueRef args[argc];
3137 for (int i(0); i != argc; ++i)
3138 args[i] = CYCastJSValue(context, argv[i]);
3139 JSValueRef exception(NULL);
3140 JSObjectRef array(JSObjectMakeArray(context, argc, args, &exception));
3141 CYThrow(context, exception);
3142 CYSetProperty(context, System_, CYJSString("args"), array);
3143 }
3144
3145 JSObjectRef CYGetGlobalObject(JSContextRef context) {
3146 return JSContextGetGlobalObject(context);
3147 }
3148
3149 const char *CYExecute(apr_pool_t *pool, const char *code) { _pooled
3150 JSContextRef context(CYGetJSContext());
3151 JSValueRef exception(NULL), result;
3152
3153 try {
3154 result = JSEvaluateScript(context, CYJSString(code), NULL, NULL, 0, &exception);
3155 } catch (const char *error) {
3156 return error;
3157 }
3158
3159 if (exception != NULL) { error:
3160 result = exception;
3161 exception = NULL;
3162 }
3163
3164 if (JSValueIsUndefined(context, result))
3165 return NULL;
3166
3167 const char *json(CYPoolCCYON(pool, context, result, &exception));
3168 if (exception != NULL)
3169 goto error;
3170
3171 CYSetProperty(context, CYGetGlobalObject(context), Result_, result);
3172 return json;
3173 }
3174
3175 bool CYRecvAll_(int socket, uint8_t *data, size_t size) {
3176 while (size != 0) if (size_t writ = _syscall(recv(socket, data, size, 0))) {
3177 data += writ;
3178 size -= writ;
3179 } else
3180 return false;
3181 return true;
3182 }
3183
3184 bool CYSendAll_(int socket, const uint8_t *data, size_t size) {
3185 while (size != 0) if (size_t writ = _syscall(send(socket, data, size, 0))) {
3186 data += writ;
3187 size -= writ;
3188 } else
3189 return false;
3190 return true;
3191 }
3192
3193 apr_pool_t *Pool_;
3194
3195 struct CYExecute_ {
3196 apr_pool_t *pool_;
3197 const char * volatile data_;
3198 };
3199
3200 // XXX: this is "tre lame"
3201 @interface CYClient_ : NSObject {
3202 }
3203
3204 - (void) execute:(NSValue *)value;
3205
3206 @end
3207
3208 @implementation CYClient_
3209
3210 - (void) execute:(NSValue *)value {
3211 CYExecute_ *execute(reinterpret_cast<CYExecute_ *>([value pointerValue]));
3212 const char *data(execute->data_);
3213 execute->data_ = NULL;
3214 execute->data_ = CYExecute(execute->pool_, data);
3215 }
3216
3217 @end
3218
3219 struct CYClient :
3220 CYData
3221 {
3222 int socket_;
3223 apr_thread_t *thread_;
3224
3225 CYClient(int socket) :
3226 socket_(socket)
3227 {
3228 }
3229
3230 ~CYClient() {
3231 _syscall(close(socket_));
3232 }
3233
3234 void Handle() { _pooled
3235 CYClient_ *client = [[[CYClient_ alloc] init] autorelease];
3236
3237 for (;;) {
3238 size_t size;
3239 if (!CYRecvAll(socket_, &size, sizeof(size)))
3240 return;
3241
3242 CYPool pool;
3243 char *data(new(pool) char[size + 1]);
3244 if (!CYRecvAll(socket_, data, size))
3245 return;
3246 data[size] = '\0';
3247
3248 CYDriver driver("");
3249 cy::parser parser(driver);
3250
3251 driver.data_ = data;
3252 driver.size_ = size;
3253
3254 const char *json;
3255 if (parser.parse() != 0 || !driver.errors_.empty()) {
3256 json = NULL;
3257 size = _not(size_t);
3258 } else {
3259 std::ostringstream str;
3260 driver.source_->Show(str);
3261 std::string code(str.str());
3262 CYExecute_ execute = {pool, code.c_str()};
3263 [client performSelectorOnMainThread:@selector(execute:) withObject:[NSValue valueWithPointer:&execute] waitUntilDone:YES];
3264 json = execute.data_;
3265 size = json == NULL ? _not(size_t) : strlen(json);
3266 }
3267
3268 if (!CYSendAll(socket_, &size, sizeof(size)))
3269 return;
3270 if (json != NULL)
3271 if (!CYSendAll(socket_, json, size))
3272 return;
3273 }
3274 }
3275 };
3276
3277 static void * APR_THREAD_FUNC OnClient(apr_thread_t *thread, void *data) {
3278 CYClient *client(reinterpret_cast<CYClient *>(data));
3279 client->Handle();
3280 delete client;
3281 return NULL;
3282 }
3283
3284 extern "C" void CYHandleClient(apr_pool_t *pool, int socket) {
3285 CYClient *client(new(pool) CYClient(socket));
3286 apr_threadattr_t *attr;
3287 _aprcall(apr_threadattr_create(&attr, client->pool_));
3288 _aprcall(apr_thread_create(&client->thread_, attr, &OnClient, client, client->pool_));
3289 }
3290
3291 MSInitialize { _pooled
3292 _aprcall(apr_initialize());
3293 _aprcall(apr_pool_create(&Pool_, NULL));
3294
3295 Type_privateData::Object = new(Pool_) Type_privateData(Pool_, "@");
3296 Type_privateData::Selector = new(Pool_) Type_privateData(Pool_, ":");
3297
3298 Bridge_ = [[NSMutableArray arrayWithContentsOfFile:@"/usr/lib/libcycript.plist"] retain];
3299
3300 NSArray_ = objc_getClass("NSArray");
3301 NSCFBoolean_ = objc_getClass("NSCFBoolean");
3302 NSCFType_ = objc_getClass("NSCFType");
3303 NSMessageBuilder_ = objc_getClass("NSMessageBuilder");
3304 NSZombie_ = objc_getClass("_NSZombie_");
3305 Object_ = objc_getClass("Object");
3306 }
3307
3308 JSGlobalContextRef CYGetJSContext() {
3309 if (Context_ == NULL) {
3310 JSClassDefinition definition;
3311
3312 definition = kJSClassDefinitionEmpty;
3313 definition.className = "Functor";
3314 definition.staticFunctions = Functor_staticFunctions;
3315 definition.callAsFunction = &Functor_callAsFunction;
3316 definition.finalize = &Finalize;
3317 Functor_ = JSClassCreate(&definition);
3318
3319 definition = kJSClassDefinitionEmpty;
3320 definition.className = "Instance";
3321 definition.staticValues = Instance_staticValues;
3322 definition.staticFunctions = Instance_staticFunctions;
3323 definition.hasProperty = &Instance_hasProperty;
3324 definition.getProperty = &Instance_getProperty;
3325 definition.setProperty = &Instance_setProperty;
3326 definition.deleteProperty = &Instance_deleteProperty;
3327 definition.getPropertyNames = &Instance_getPropertyNames;
3328 definition.callAsConstructor = &Instance_callAsConstructor;
3329 definition.finalize = &Finalize;
3330 Instance_ = JSClassCreate(&definition);
3331
3332 definition = kJSClassDefinitionEmpty;
3333 definition.className = "Internal";
3334 definition.staticFunctions = Internal_staticFunctions;
3335 definition.hasProperty = &Internal_hasProperty;
3336 definition.getProperty = &Internal_getProperty;
3337 definition.setProperty = &Internal_setProperty;
3338 definition.getPropertyNames = &Internal_getPropertyNames;
3339 definition.finalize = &Finalize;
3340 Internal_ = JSClassCreate(&definition);
3341
3342 definition = kJSClassDefinitionEmpty;
3343 definition.className = "Message";
3344 definition.staticFunctions = Functor_staticFunctions;
3345 definition.callAsFunction = &Message_callAsFunction;
3346 definition.finalize = &Finalize;
3347 Message_ = JSClassCreate(&definition);
3348
3349 definition = kJSClassDefinitionEmpty;
3350 definition.className = "Pointer";
3351 definition.staticValues = Pointer_staticValues;
3352 definition.staticFunctions = Pointer_staticFunctions;
3353 definition.getProperty = &Pointer_getProperty;
3354 definition.setProperty = &Pointer_setProperty;
3355 definition.finalize = &Finalize;
3356 Pointer_ = JSClassCreate(&definition);
3357
3358 definition = kJSClassDefinitionEmpty;
3359 definition.className = "Prototype";
3360 definition.hasProperty = &Prototype_hasProperty;
3361 definition.getProperty = &Prototype_getProperty;
3362 definition.setProperty = &Prototype_setProperty;
3363 #if !__OBJC2__
3364 definition.deleteProperty = &Prototype_deleteProperty;
3365 #endif
3366 definition.getPropertyNames = &Prototype_getPropertyNames;
3367 definition.finalize = &Finalize;
3368 Prototype_ = JSClassCreate(&definition);
3369
3370 definition = kJSClassDefinitionEmpty;
3371 definition.className = "Selector";
3372 definition.staticValues = CYValue_staticValues;
3373 definition.staticFunctions = Selector_staticFunctions;
3374 definition.callAsFunction = &Selector_callAsFunction;
3375 definition.finalize = &Finalize;
3376 Selector_ = JSClassCreate(&definition);
3377
3378 definition = kJSClassDefinitionEmpty;
3379 definition.className = "Struct";
3380 definition.staticFunctions = Struct_staticFunctions;
3381 definition.getProperty = &Struct_getProperty;
3382 definition.setProperty = &Struct_setProperty;
3383 definition.getPropertyNames = &Struct_getPropertyNames;
3384 definition.finalize = &Finalize;
3385 Struct_ = JSClassCreate(&definition);
3386
3387 definition = kJSClassDefinitionEmpty;
3388 definition.className = "Type";
3389 definition.staticFunctions = Type_staticFunctions;
3390 //definition.getProperty = &Type_getProperty;
3391 definition.callAsFunction = &Type_callAsFunction;
3392 definition.callAsConstructor = &Type_callAsConstructor;
3393 definition.finalize = &Finalize;
3394 Type_ = JSClassCreate(&definition);
3395
3396 definition = kJSClassDefinitionEmpty;
3397 definition.className = "Runtime";
3398 definition.getProperty = &Runtime_getProperty;
3399 Runtime_ = JSClassCreate(&definition);
3400
3401 definition = kJSClassDefinitionEmpty;
3402 definition.className = "ObjectiveC::Classes";
3403 definition.getProperty = &ObjectiveC_Classes_getProperty;
3404 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
3405 ObjectiveC_Classes_ = JSClassCreate(&definition);
3406
3407 definition = kJSClassDefinitionEmpty;
3408 definition.className = "ObjectiveC::Images";
3409 definition.getProperty = &ObjectiveC_Images_getProperty;
3410 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
3411 ObjectiveC_Images_ = JSClassCreate(&definition);
3412
3413 definition = kJSClassDefinitionEmpty;
3414 definition.className = "ObjectiveC::Image::Classes";
3415 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
3416 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
3417 definition.finalize = &Finalize;
3418 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
3419
3420 definition = kJSClassDefinitionEmpty;
3421 definition.className = "ObjectiveC::Protocols";
3422 definition.getProperty = &ObjectiveC_Protocols_getProperty;
3423 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
3424 ObjectiveC_Protocols_ = JSClassCreate(&definition);
3425
3426 definition = kJSClassDefinitionEmpty;
3427 //definition.getProperty = &Global_getProperty;
3428 JSClassRef Global(JSClassCreate(&definition));
3429
3430 JSGlobalContextRef context(JSGlobalContextCreate(Global));
3431 Context_ = context;
3432
3433 JSObjectRef global(CYGetGlobalObject(context));
3434
3435 JSObjectSetPrototype(context, global, JSObjectMake(context, Runtime_, NULL));
3436 ObjectiveC_ = JSObjectMake(context, NULL, NULL);
3437 CYSetProperty(context, global, CYJSString("ObjectiveC"), ObjectiveC_);
3438
3439 CYSetProperty(context, ObjectiveC_, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Classes_, NULL));
3440 CYSetProperty(context, ObjectiveC_, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
3441 CYSetProperty(context, ObjectiveC_, CYJSString("protocols"), JSObjectMake(context, ObjectiveC_Protocols_, NULL));
3442
3443 Array_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Array")));
3444 Function_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Function")));
3445
3446 length_ = JSStringCreateWithUTF8CString("length");
3447 message_ = JSStringCreateWithUTF8CString("message");
3448 name_ = JSStringCreateWithUTF8CString("name");
3449 prototype_ = JSStringCreateWithUTF8CString("prototype");
3450 toCYON_ = JSStringCreateWithUTF8CString("toCYON");
3451 toJSON_ = JSStringCreateWithUTF8CString("toJSON");
3452
3453 Array_prototype_ = CYCastJSObject(context, CYGetProperty(context, Array_, prototype_));
3454 Array_pop_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("pop")));
3455 Array_push_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("push")));
3456 Array_splice_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("splice")));
3457
3458 JSObjectRef Functor(JSObjectMakeConstructor(context, Functor_, &Functor_new));
3459 JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL));
3460 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new));
3461
3462 JSValueRef function(CYGetProperty(context, Function_, prototype_));
3463 JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Message, prototype_), function);
3464 JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Functor, prototype_), function);
3465 JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Selector, prototype_), function);
3466
3467 CYSetProperty(context, global, CYJSString("Functor"), Functor);
3468 CYSetProperty(context, global, CYJSString("Instance"), JSObjectMakeConstructor(context, Instance_, &Instance_new));
3469 CYSetProperty(context, global, CYJSString("Pointer"), JSObjectMakeConstructor(context, Pointer_, &Pointer_new));
3470 CYSetProperty(context, global, CYJSString("Selector"), Selector);
3471 CYSetProperty(context, global, CYJSString("Type"), JSObjectMakeConstructor(context, Type_, &Type_new));
3472
3473 MSHookFunction(&objc_registerClassPair, MSHake(objc_registerClassPair));
3474
3475 class_addMethod(NSCFType_, @selector(cy$toJSON:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON), "@12@0:4@8");
3476
3477 CYSetProperty(context, global, CYJSString("objc_registerClassPair"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_registerClassPair"), &objc_registerClassPair_));
3478 CYSetProperty(context, global, CYJSString("objc_msgSend"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_msgSend"), &$objc_msgSend));
3479 CYSetProperty(context, global, CYJSString("$cyq"), JSObjectMakeFunctionWithCallback(context, CYJSString("$cyq"), &$cyq));
3480
3481 System_ = JSObjectMake(context, NULL, NULL);
3482 CYSetProperty(context, global, CYJSString("system"), System_);
3483 CYSetProperty(context, System_, CYJSString("args"), CYJSNull(context));
3484 //CYSetProperty(context, System_, CYJSString("global"), global);
3485
3486 CYSetProperty(context, System_, CYJSString("print"), JSObjectMakeFunctionWithCallback(context, CYJSString("print"), &System_print));
3487
3488 Result_ = JSStringCreateWithUTF8CString("_");
3489 }
3490
3491 return Context_;
3492 }