]> git.saurik.com Git - cycript.git/blob - Execute.cpp
Support @error when CYONifying JavaScript arrays.
[cycript.git] / Execute.cpp
1 /* Cycript - Optimizing JavaScript Compiler/Runtime
2 * Copyright (C) 2009-2013 Jay Freeman (saurik)
3 */
4
5 /* GNU General Public License, Version 3 {{{ */
6 /*
7 * Cycript is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published
9 * by the Free Software Foundation, either version 3 of the License,
10 * or (at your option) any later version.
11 *
12 * Cycript is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with Cycript. If not, see <http://www.gnu.org/licenses/>.
19 **/
20 /* }}} */
21
22 #include "Internal.hpp"
23
24 #include <dlfcn.h>
25
26 #include "cycript.hpp"
27
28 #include "sig/parse.hpp"
29 #include "sig/ffi_type.hpp"
30
31 #include "Pooling.hpp"
32 #include "Execute.hpp"
33
34 #include <sys/mman.h>
35
36 #include <iostream>
37 #include <set>
38 #include <map>
39 #include <iomanip>
40 #include <sstream>
41 #include <cmath>
42
43 #include "Parser.hpp"
44
45 #include "Error.hpp"
46 #include "JavaScript.hpp"
47 #include "String.hpp"
48
49 struct CYHooks *hooks_;
50
51 /* JavaScript Properties {{{ */
52 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, size_t index) {
53 return _jsccall(JSObjectGetPropertyAtIndex, context, object, index);
54 }
55
56 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, JSStringRef name) {
57 return _jsccall(JSObjectGetProperty, context, object, name);
58 }
59
60 void CYSetProperty(JSContextRef context, JSObjectRef object, size_t index, JSValueRef value) {
61 _jsccall(JSObjectSetPropertyAtIndex, context, object, index, value);
62 }
63
64 void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef value, JSPropertyAttributes attributes) {
65 _jsccall(JSObjectSetProperty, context, object, name, value, attributes);
66 }
67
68 void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef (*callback)(JSContextRef, JSObjectRef, JSObjectRef, size_t, const JSValueRef[], JSValueRef *), JSPropertyAttributes attributes) {
69 CYSetProperty(context, object, name, JSObjectMakeFunctionWithCallback(context, name, callback), attributes);
70 }
71 /* }}} */
72 /* JavaScript Strings {{{ */
73 JSStringRef CYCopyJSString(const char *value) {
74 return value == NULL ? NULL : JSStringCreateWithUTF8CString(value);
75 }
76
77 JSStringRef CYCopyJSString(JSStringRef value) {
78 return value == NULL ? NULL : JSStringRetain(value);
79 }
80
81 JSStringRef CYCopyJSString(CYUTF8String value) {
82 // XXX: this is very wrong; it needs to convert to UTF16 and then create from there
83 return CYCopyJSString(value.data);
84 }
85
86 JSStringRef CYCopyJSString(JSContextRef context, JSValueRef value) {
87 if (JSValueIsNull(context, value))
88 return NULL;
89 return _jsccall(JSValueToStringCopy, context, value);
90 }
91
92 static CYUTF16String CYCastUTF16String(JSStringRef value) {
93 return CYUTF16String(JSStringGetCharactersPtr(value), JSStringGetLength(value));
94 }
95
96 CYUTF8String CYPoolUTF8String(CYPool &pool, JSContextRef context, JSStringRef value) {
97 return CYPoolUTF8String(pool, CYCastUTF16String(value));
98 }
99
100 const char *CYPoolCString(CYPool &pool, JSContextRef context, JSStringRef value) {
101 CYUTF8String utf8(CYPoolUTF8String(pool, context, value));
102 _assert(memchr(utf8.data, '\0', utf8.size) == NULL);
103 return utf8.data;
104 }
105
106 const char *CYPoolCString(CYPool &pool, JSContextRef context, JSValueRef value) {
107 return JSValueIsNull(context, value) ? NULL : CYPoolCString(pool, context, CYJSString(context, value));
108 }
109 /* }}} */
110 /* Index Offsets {{{ */
111 size_t CYGetIndex(CYPool &pool, JSContextRef context, JSStringRef value) {
112 return CYGetIndex(CYPoolUTF8String(pool, context, value));
113 }
114 /* }}} */
115
116 static JSClassRef All_;
117 static JSClassRef Context_;
118 JSClassRef Functor_;
119 static JSClassRef Global_;
120 static JSClassRef Pointer_;
121 static JSClassRef Struct_;
122
123 JSStringRef Array_s;
124 JSStringRef cy_s;
125 JSStringRef length_s;
126 JSStringRef message_s;
127 JSStringRef name_s;
128 JSStringRef pop_s;
129 JSStringRef prototype_s;
130 JSStringRef push_s;
131 JSStringRef splice_s;
132 JSStringRef toCYON_s;
133 JSStringRef toJSON_s;
134 JSStringRef toPointer_s;
135 JSStringRef toString_s;
136
137 static JSStringRef Result_;
138
139 void CYFinalize(JSObjectRef object) {
140 CYData *internal(reinterpret_cast<CYData *>(JSObjectGetPrivate(object)));
141 _assert(internal->count_ != _not(unsigned));
142 if (--internal->count_ == 0)
143 delete internal;
144 }
145
146 void Structor_(CYPool &pool, sig::Type *&type) {
147 if (
148 type->primitive == sig::pointer_P &&
149 type->data.data.type != NULL &&
150 type->data.data.type->primitive == sig::struct_P &&
151 type->data.data.type->name != NULL &&
152 strcmp(type->data.data.type->name, "_objc_class") == 0
153 ) {
154 type->primitive = sig::typename_P;
155 type->data.data.type = NULL;
156 return;
157 }
158
159 if (type->primitive != sig::struct_P || type->name == NULL)
160 return;
161
162 size_t length(strlen(type->name));
163 char keyed[length + 2];
164 memcpy(keyed + 1, type->name, length + 1);
165
166 static const char *modes = "34";
167 for (size_t i(0); i != 2; ++i) {
168 char mode(modes[i]);
169 keyed[0] = mode;
170
171 if (CYBridgeEntry *entry = CYBridgeHash(keyed, length + 1))
172 switch (mode) {
173 case '3':
174 sig::Parse(pool, &type->data.signature, entry->value_, &Structor_);
175 break;
176
177 case '4': {
178 sig::Signature signature;
179 sig::Parse(pool, &signature, entry->value_, &Structor_);
180 type = signature.elements[0].type;
181 } break;
182 }
183 }
184 }
185
186 JSClassRef Type_privateData::Class_;
187
188 struct Context :
189 CYData
190 {
191 JSGlobalContextRef context_;
192
193 Context(JSGlobalContextRef context) :
194 context_(context)
195 {
196 }
197 };
198
199 struct Pointer :
200 CYOwned
201 {
202 Type_privateData *type_;
203 size_t length_;
204
205 Pointer(void *value, JSContextRef context, JSObjectRef owner, size_t length, sig::Type *type) :
206 CYOwned(value, context, owner),
207 type_(new(*pool_) Type_privateData(type)),
208 length_(length)
209 {
210 }
211 };
212
213 struct Struct_privateData :
214 CYOwned
215 {
216 Type_privateData *type_;
217
218 Struct_privateData(JSContextRef context, JSObjectRef owner) :
219 CYOwned(NULL, context, owner)
220 {
221 }
222 };
223
224 typedef std::map<const char *, Type_privateData *, CYCStringLess> TypeMap;
225 static TypeMap Types_;
226
227 JSObjectRef CYMakeStruct(JSContextRef context, void *data, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
228 Struct_privateData *internal(new Struct_privateData(context, owner));
229 CYPool &pool(*internal->pool_);
230 Type_privateData *typical(new(pool) Type_privateData(type, ffi));
231 internal->type_ = typical;
232
233 if (owner != NULL)
234 internal->value_ = data;
235 else {
236 size_t size(typical->GetFFI()->size);
237 void *copy(internal->pool_->malloc<void>(size));
238 memcpy(copy, data, size);
239 internal->value_ = copy;
240 }
241
242 return JSObjectMake(context, Struct_, internal);
243 }
244
245 static void *CYCastSymbol(const char *name) {
246 return dlsym(RTLD_DEFAULT, name);
247 }
248
249 JSValueRef CYCastJSValue(JSContextRef context, bool value) {
250 return JSValueMakeBoolean(context, value);
251 }
252
253 JSValueRef CYCastJSValue(JSContextRef context, double value) {
254 return JSValueMakeNumber(context, value);
255 }
256
257 #define CYCastJSValue_(Type_) \
258 JSValueRef CYCastJSValue(JSContextRef context, Type_ value) { \
259 return JSValueMakeNumber(context, static_cast<double>(value)); \
260 }
261
262 CYCastJSValue_(int)
263 CYCastJSValue_(unsigned int)
264 CYCastJSValue_(long int)
265 CYCastJSValue_(long unsigned int)
266 CYCastJSValue_(long long int)
267 CYCastJSValue_(long long unsigned int)
268
269 JSValueRef CYJSUndefined(JSContextRef context) {
270 return JSValueMakeUndefined(context);
271 }
272
273 double CYCastDouble(JSContextRef context, JSValueRef value) {
274 return _jsccall(JSValueToNumber, context, value);
275 }
276
277 bool CYCastBool(JSContextRef context, JSValueRef value) {
278 return JSValueToBoolean(context, value);
279 }
280
281 JSValueRef CYJSNull(JSContextRef context) {
282 return JSValueMakeNull(context);
283 }
284
285 JSValueRef CYCastJSValue(JSContextRef context, JSStringRef value) {
286 return value == NULL ? CYJSNull(context) : JSValueMakeString(context, value);
287 }
288
289 JSValueRef CYCastJSValue(JSContextRef context, const char *value) {
290 return CYCastJSValue(context, CYJSString(value));
291 }
292
293 JSObjectRef CYCastJSObject(JSContextRef context, JSValueRef value) {
294 return _jsccall(JSValueToObject, context, value);
295 }
296
297 JSValueRef CYCallAsFunction(JSContextRef context, JSObjectRef function, JSObjectRef _this, size_t count, const JSValueRef arguments[]) {
298 return _jsccall(JSObjectCallAsFunction, context, function, _this, count, arguments);
299 }
300
301 bool CYIsCallable(JSContextRef context, JSValueRef value) {
302 return value != NULL && JSValueIsObject(context, value) && JSObjectIsFunction(context, (JSObjectRef) value);
303 }
304
305 size_t CYArrayLength(JSContextRef context, JSObjectRef array) {
306 return CYCastDouble(context, CYGetProperty(context, array, length_s));
307 }
308
309 JSValueRef CYArrayGet(JSContextRef context, JSObjectRef array, size_t index) {
310 return _jsccall(JSObjectGetPropertyAtIndex, context, array, index);
311 }
312
313 void CYArrayPush(JSContextRef context, JSObjectRef array, JSValueRef value) {
314 JSValueRef arguments[1];
315 arguments[0] = value;
316 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
317 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, push_s)), array, 1, arguments);
318 }
319
320 static JSValueRef System_print(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
321 if (count == 0)
322 printf("\n");
323 else {
324 CYPool pool;
325 printf("%s\n", CYPoolCString(pool, context, arguments[0]));
326 }
327
328 return CYJSUndefined(context);
329 } CYCatch(NULL) }
330
331 static size_t Nonce_(0);
332
333 static JSValueRef $cyq(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
334 CYPool pool;
335 const char *name(pool.strcat(CYPoolCString(pool, context, arguments[0]), pool.itoa(Nonce_++), NULL));
336 return CYCastJSValue(context, name);
337 } CYCatch(NULL) }
338
339 static JSValueRef Cycript_gc_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
340 JSGarbageCollect(context);
341 return CYJSUndefined(context);
342 } CYCatch(NULL) }
343
344 const char *CYPoolCCYON(CYPool &pool, JSContextRef context, JSValueRef value, JSValueRef *exception) { CYTry {
345 switch (JSType type = JSValueGetType(context, value)) {
346 case kJSTypeUndefined:
347 return "undefined";
348 case kJSTypeNull:
349 return "null";
350 case kJSTypeBoolean:
351 return CYCastBool(context, value) ? "true" : "false";
352
353 case kJSTypeNumber: {
354 std::ostringstream str;
355 CYNumerify(str, CYCastDouble(context, value));
356 std::string value(str.str());
357 return pool.strmemdup(value.c_str(), value.size());
358 } break;
359
360 case kJSTypeString: {
361 std::ostringstream str;
362 CYUTF8String string(CYPoolUTF8String(pool, context, CYJSString(context, value)));
363 CYStringify(str, string.data, string.size);
364 std::string value(str.str());
365 return pool.strmemdup(value.c_str(), value.size());
366 } break;
367
368 case kJSTypeObject:
369 return CYPoolCCYON(pool, context, (JSObjectRef) value);
370 default:
371 throw CYJSError(context, "JSValueGetType() == 0x%x", type);
372 }
373 } CYCatch(NULL) }
374
375 const char *CYPoolCCYON(CYPool &pool, JSContextRef context, JSValueRef value) {
376 return _jsccall(CYPoolCCYON, pool, context, value);
377 }
378
379 const char *CYPoolCCYON(CYPool &pool, JSContextRef context, JSObjectRef object) {
380 JSValueRef toCYON(CYGetProperty(context, object, toCYON_s));
381 if (CYIsCallable(context, toCYON)) {
382 JSValueRef value(CYCallAsFunction(context, (JSObjectRef) toCYON, object, 0, NULL));
383 _assert(value != NULL);
384 return CYPoolCString(pool, context, value);
385 }
386
387 JSValueRef toJSON(CYGetProperty(context, object, toJSON_s));
388 if (CYIsCallable(context, toJSON)) {
389 JSValueRef arguments[1] = {CYCastJSValue(context, CYJSString(""))};
390 return _jsccall(CYPoolCCYON, pool, context, CYCallAsFunction(context, (JSObjectRef) toJSON, object, 1, arguments));
391 }
392
393 if (JSObjectIsFunction(context, object)) {
394 JSValueRef toString(CYGetProperty(context, object, toString_s));
395 if (CYIsCallable(context, toString)) {
396 JSValueRef arguments[1] = {CYCastJSValue(context, CYJSString(""))};
397 JSValueRef value(CYCallAsFunction(context, (JSObjectRef) toString, object, 1, arguments));
398 _assert(value != NULL);
399 return CYPoolCString(pool, context, value);
400 }
401 }
402
403 std::ostringstream str;
404
405 str << '{';
406
407 // XXX: this is, sadly, going to leak
408 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context, object));
409
410 bool comma(false);
411
412 for (size_t index(0), count(JSPropertyNameArrayGetCount(names)); index != count; ++index) {
413 if (comma)
414 str << ',';
415 else
416 comma = true;
417
418 JSStringRef name(JSPropertyNameArrayGetNameAtIndex(names, index));
419 CYUTF8String string(CYPoolUTF8String(pool, context, name));
420
421 if (CYIsKey(string))
422 str << string.data;
423 else
424 CYStringify(str, string.data, string.size);
425
426 str << ':';
427
428 try {
429 JSValueRef value(CYGetProperty(context, object, name));
430 str << CYPoolCCYON(pool, context, value);
431 } catch (const CYException &error) {
432 str << "@error";
433 }
434 }
435
436 JSPropertyNameArrayRelease(names);
437
438 str << '}';
439
440 std::string string(str.str());
441 return pool.strmemdup(string.c_str(), string.size());
442 }
443
444 static JSValueRef Array_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
445 CYPool pool;
446 std::ostringstream str;
447
448 str << '[';
449
450 JSValueRef length(CYGetProperty(context, _this, length_s));
451 bool comma(false);
452
453 for (size_t index(0), count(CYCastDouble(context, length)); index != count; ++index) {
454 if (comma)
455 str << ',';
456 else
457 comma = true;
458
459 try {
460 JSValueRef value(CYGetProperty(context, _this, index));
461 if (!JSValueIsUndefined(context, value))
462 str << CYPoolCCYON(pool, context, value);
463 else {
464 str << ',';
465 comma = false;
466 }
467 } catch (const CYException &error) {
468 str << "@error";
469 }
470 }
471
472 str << ']';
473
474 std::string value(str.str());
475 return CYCastJSValue(context, CYJSString(CYUTF8String(value.c_str(), value.size())));
476 } CYCatch(NULL) }
477
478 static JSValueRef String_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
479 CYPool pool;
480 std::ostringstream str;
481
482 CYUTF8String string(CYPoolUTF8String(pool, context, CYJSString(context, _this)));
483 CYStringify(str, string.data, string.size);
484
485 std::string value(str.str());
486 return CYCastJSValue(context, CYJSString(CYUTF8String(value.c_str(), value.size())));
487 } CYCatch(NULL) }
488
489 JSObjectRef CYMakePointer(JSContextRef context, void *pointer, size_t length, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
490 Pointer *internal(new Pointer(pointer, context, owner, length, type));
491 return JSObjectMake(context, Pointer_, internal);
492 }
493
494 static JSObjectRef CYMakeFunctor(JSContextRef context, void (*function)(), const char *type) {
495 return JSObjectMake(context, Functor_, new cy::Functor(type, function));
496 }
497
498 static JSObjectRef CYMakeFunctor(JSContextRef context, const char *symbol, const char *type, void **cache) {
499 cy::Functor *internal;
500 if (*cache != NULL)
501 internal = reinterpret_cast<cy::Functor *>(*cache);
502 else {
503 void (*function)()(reinterpret_cast<void (*)()>(CYCastSymbol(symbol)));
504 if (function == NULL)
505 return NULL;
506
507 internal = new cy::Functor(type, function);
508 *cache = internal;
509 }
510
511 ++internal->count_;
512 return JSObjectMake(context, Functor_, internal);
513 }
514
515 static bool CYGetOffset(CYPool &pool, JSContextRef context, JSStringRef value, ssize_t &index) {
516 return CYGetOffset(CYPoolCString(pool, context, value), index);
517 }
518
519 void *CYCastPointer_(JSContextRef context, JSValueRef value) {
520 switch (JSValueGetType(context, value)) {
521 case kJSTypeNull:
522 return NULL;
523 case kJSTypeObject: {
524 JSObjectRef object((JSObjectRef) value);
525 if (JSValueIsObjectOfClass(context, value, Pointer_)) {
526 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
527 return internal->value_;
528 }
529 JSValueRef toPointer(CYGetProperty(context, object, toPointer_s));
530 if (CYIsCallable(context, toPointer)) {
531 JSValueRef value(CYCallAsFunction(context, (JSObjectRef) toPointer, object, 0, NULL));
532 _assert(value != NULL);
533 return CYCastPointer_(context, value);
534 }
535 } default:
536 double number(CYCastDouble(context, value));
537 if (std::isnan(number))
538 throw CYJSError(context, "cannot convert value to pointer");
539 return reinterpret_cast<void *>(static_cast<uintptr_t>(static_cast<long long>(number)));
540 }
541 }
542
543 void CYPoolFFI(CYPool *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) {
544 switch (type->primitive) {
545 case sig::boolean_P:
546 *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
547 break;
548
549 #define CYPoolFFI_(primitive, native) \
550 case sig::primitive ## _P: \
551 *reinterpret_cast<native *>(data) = CYCastDouble(context, value); \
552 break;
553
554 CYPoolFFI_(uchar, unsigned char)
555 CYPoolFFI_(char, char)
556 CYPoolFFI_(ushort, unsigned short)
557 CYPoolFFI_(short, short)
558 CYPoolFFI_(ulong, unsigned long)
559 CYPoolFFI_(long, long)
560 CYPoolFFI_(uint, unsigned int)
561 CYPoolFFI_(int, int)
562 CYPoolFFI_(ulonglong, unsigned long long)
563 CYPoolFFI_(longlong, long long)
564 CYPoolFFI_(float, float)
565 CYPoolFFI_(double, double)
566
567 case sig::array_P: {
568 uint8_t *base(reinterpret_cast<uint8_t *>(data));
569 JSObjectRef aggregate(JSValueIsObject(context, value) ? (JSObjectRef) value : NULL);
570 for (size_t index(0); index != type->data.data.size; ++index) {
571 ffi_type *field(ffi->elements[index]);
572
573 JSValueRef rhs;
574 if (aggregate == NULL)
575 rhs = value;
576 else {
577 rhs = CYGetProperty(context, aggregate, index);
578 if (JSValueIsUndefined(context, rhs))
579 throw CYJSError(context, "unable to extract array value");
580 }
581
582 CYPoolFFI(pool, context, type->data.data.type, field, base, rhs);
583 // XXX: alignment?
584 base += field->size;
585 }
586 } break;
587
588 case sig::pointer_P:
589 *reinterpret_cast<void **>(data) = CYCastPointer<void *>(context, value);
590 break;
591
592 case sig::string_P:
593 _assert(pool != NULL);
594 *reinterpret_cast<const char **>(data) = CYPoolCString(*pool, context, value);
595 break;
596
597 case sig::struct_P: {
598 uint8_t *base(reinterpret_cast<uint8_t *>(data));
599 JSObjectRef aggregate(JSValueIsObject(context, value) ? (JSObjectRef) value : NULL);
600 for (size_t index(0); index != type->data.signature.count; ++index) {
601 sig::Element *element(&type->data.signature.elements[index]);
602 ffi_type *field(ffi->elements[index]);
603
604 JSValueRef rhs;
605 if (aggregate == NULL)
606 rhs = value;
607 else {
608 rhs = CYGetProperty(context, aggregate, index);
609 if (JSValueIsUndefined(context, rhs)) {
610 if (element->name != NULL)
611 rhs = CYGetProperty(context, aggregate, CYJSString(element->name));
612 else
613 goto undefined;
614 if (JSValueIsUndefined(context, rhs)) undefined:
615 throw CYJSError(context, "unable to extract structure value");
616 }
617 }
618
619 CYPoolFFI(pool, context, element->type, field, base, rhs);
620 // XXX: alignment?
621 base += field->size;
622 }
623 } break;
624
625 case sig::void_P:
626 break;
627
628 default:
629 if (hooks_ != NULL && hooks_->PoolFFI != NULL)
630 if ((*hooks_->PoolFFI)(pool, context, type, ffi, data, value))
631 return;
632
633 CYThrow("unimplemented signature code: '%c''\n", type->primitive);
634 }
635 }
636
637 JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) {
638 switch (type->primitive) {
639 case sig::boolean_P:
640 return CYCastJSValue(context, *reinterpret_cast<bool *>(data));
641
642 #define CYFromFFI_(primitive, native) \
643 case sig::primitive ## _P: \
644 return CYCastJSValue(context, *reinterpret_cast<native *>(data)); \
645
646 CYFromFFI_(uchar, unsigned char)
647 CYFromFFI_(char, char)
648 CYFromFFI_(ushort, unsigned short)
649 CYFromFFI_(short, short)
650 CYFromFFI_(ulong, unsigned long)
651 CYFromFFI_(long, long)
652 CYFromFFI_(uint, unsigned int)
653 CYFromFFI_(int, int)
654 CYFromFFI_(ulonglong, unsigned long long)
655 CYFromFFI_(longlong, long long)
656 CYFromFFI_(float, float)
657 CYFromFFI_(double, double)
658
659 case sig::array_P:
660 if (void *pointer = data)
661 return CYMakePointer(context, pointer, type->data.data.size, type->data.data.type, NULL, owner);
662 else goto null;
663
664 case sig::pointer_P:
665 if (void *pointer = *reinterpret_cast<void **>(data))
666 return CYMakePointer(context, pointer, _not(size_t), type->data.data.type, NULL, owner);
667 else goto null;
668
669 case sig::string_P:
670 if (char *utf8 = *reinterpret_cast<char **>(data))
671 return CYCastJSValue(context, utf8);
672 else goto null;
673
674 case sig::struct_P:
675 return CYMakeStruct(context, data, type, ffi, owner);
676 case sig::void_P:
677 return CYJSUndefined(context);
678
679 null:
680 return CYJSNull(context);
681 default:
682 if (hooks_ != NULL && hooks_->FromFFI != NULL)
683 if (JSValueRef value = (*hooks_->FromFFI)(context, type, ffi, data, initialize, owner))
684 return value;
685
686 CYThrow("unimplemented signature code: '%c''\n", type->primitive);
687 }
688 }
689
690 void CYExecuteClosure(ffi_cif *cif, void *result, void **arguments, void *arg, JSValueRef (*adapter)(JSContextRef, size_t, JSValueRef[], JSObjectRef)) {
691 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
692
693 JSContextRef context(internal->context_);
694
695 size_t count(internal->cif_.nargs);
696 JSValueRef values[count];
697
698 for (size_t index(0); index != count; ++index)
699 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
700
701 JSValueRef value(adapter(context, count, values, internal->function_));
702 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
703 }
704
705 static JSValueRef FunctionAdapter_(JSContextRef context, size_t count, JSValueRef values[], JSObjectRef function) {
706 return CYCallAsFunction(context, function, NULL, count, values);
707 }
708
709 static void FunctionClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
710 CYExecuteClosure(cif, result, arguments, arg, &FunctionAdapter_);
711 }
712
713 Closure_privateData *CYMakeFunctor_(JSContextRef context, JSObjectRef function, const char *type, void (*callback)(ffi_cif *, void *, void **, void *)) {
714 // XXX: in case of exceptions this will leak
715 // XXX: in point of fact, this may /need/ to leak :(
716 Closure_privateData *internal(new Closure_privateData(context, function, type));
717
718 #if defined(__APPLE__) && defined(__arm__)
719 void *executable;
720 ffi_closure *writable(reinterpret_cast<ffi_closure *>(ffi_closure_alloc(sizeof(ffi_closure), &executable)));
721
722 ffi_status status(ffi_prep_closure_loc(writable, &internal->cif_, callback, internal, executable));
723 _assert(status == FFI_OK);
724
725 internal->value_ = executable;
726 #else
727 ffi_closure *closure((ffi_closure *) _syscall(mmap(
728 NULL, sizeof(ffi_closure),
729 PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE,
730 -1, 0
731 )));
732
733 ffi_status status(ffi_prep_closure(closure, &internal->cif_, callback, internal));
734 _assert(status == FFI_OK);
735
736 _syscall(mprotect(closure, sizeof(*closure), PROT_READ | PROT_EXEC));
737
738 internal->value_ = closure;
739 #endif
740
741 return internal;
742 }
743
744 static JSObjectRef CYMakeFunctor(JSContextRef context, JSObjectRef function, const char *type) {
745 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &FunctionClosure_));
746 JSObjectRef object(JSObjectMake(context, Functor_, internal));
747 // XXX: see above notes about needing to leak
748 JSValueProtect(CYGetJSContext(context), object);
749 return object;
750 }
751
752 JSObjectRef CYGetCachedObject(JSContextRef context, JSStringRef name) {
753 return CYCastJSObject(context, CYGetProperty(context, CYCastJSObject(context, CYGetProperty(context, CYGetGlobalObject(context), cy_s)), name));
754 }
755
756 static JSObjectRef CYMakeFunctor(JSContextRef context, JSValueRef value, const char *type) {
757 JSObjectRef Function(CYGetCachedObject(context, CYJSString("Function")));
758
759 bool function(_jsccall(JSValueIsInstanceOfConstructor, context, value, Function));
760 if (function) {
761 JSObjectRef function(CYCastJSObject(context, value));
762 return CYMakeFunctor(context, function, type);
763 } else {
764 void (*function)()(CYCastPointer<void (*)()>(context, value));
765 return CYMakeFunctor(context, function, type);
766 }
767 }
768
769 static bool Index_(CYPool &pool, JSContextRef context, Struct_privateData *internal, JSStringRef property, ssize_t &index, uint8_t *&base) {
770 Type_privateData *typical(internal->type_);
771 sig::Type *type(typical->type_);
772 if (type == NULL)
773 return false;
774
775 const char *name(CYPoolCString(pool, context, property));
776 size_t length(strlen(name));
777 double number(CYCastDouble(name, length));
778
779 size_t count(type->data.signature.count);
780
781 if (std::isnan(number)) {
782 if (property == NULL)
783 return false;
784
785 sig::Element *elements(type->data.signature.elements);
786
787 for (size_t local(0); local != count; ++local) {
788 sig::Element *element(&elements[local]);
789 if (element->name != NULL && strcmp(name, element->name) == 0) {
790 index = local;
791 goto base;
792 }
793 }
794
795 return false;
796 } else {
797 index = static_cast<ssize_t>(number);
798 if (index != number || index < 0 || static_cast<size_t>(index) >= count)
799 return false;
800 }
801
802 base:
803 ffi_type **elements(typical->GetFFI()->elements);
804
805 base = reinterpret_cast<uint8_t *>(internal->value_);
806 for (ssize_t local(0); local != index; ++local)
807 base += elements[local]->size;
808
809 return true;
810 }
811
812 static JSValueRef Pointer_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
813 CYPool pool;
814 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
815
816 if (JSStringIsEqual(property, length_s))
817 return internal->length_ == _not(size_t) ? CYJSUndefined(context) : CYCastJSValue(context, internal->length_);
818
819 Type_privateData *typical(internal->type_);
820
821 if (typical->type_ == NULL)
822 return NULL;
823
824 ssize_t offset;
825 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
826 offset = 0;
827 else if (!CYGetOffset(pool, context, property, offset))
828 return NULL;
829
830 ffi_type *ffi(typical->GetFFI());
831
832 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
833 base += ffi->size * offset;
834
835 JSObjectRef owner(internal->GetOwner() ?: object);
836 return CYFromFFI(context, typical->type_, ffi, base, false, owner);
837 } CYCatch(NULL) }
838
839 static bool Pointer_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
840 CYPool pool;
841 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
842 Type_privateData *typical(internal->type_);
843
844 if (typical->type_ == NULL)
845 return false;
846
847 ssize_t offset;
848 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
849 offset = 0;
850 else if (!CYGetOffset(pool, context, property, offset))
851 return false;
852
853 ffi_type *ffi(typical->GetFFI());
854
855 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
856 base += ffi->size * offset;
857
858 CYPoolFFI(NULL, context, typical->type_, ffi, base, value);
859 return true;
860 } CYCatch(false) }
861
862 static JSValueRef Struct_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
863 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(_this)));
864 Type_privateData *typical(internal->type_);
865 return CYMakePointer(context, internal->value_, _not(size_t), typical->type_, typical->ffi_, _this);
866 } CYCatch(NULL) }
867
868 static JSValueRef Struct_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
869 CYPool pool;
870 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
871 Type_privateData *typical(internal->type_);
872
873 ssize_t index;
874 uint8_t *base;
875
876 if (!Index_(pool, context, internal, property, index, base))
877 return NULL;
878
879 JSObjectRef owner(internal->GetOwner() ?: object);
880
881 return CYFromFFI(context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, false, owner);
882 } CYCatch(NULL) }
883
884 static bool Struct_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
885 CYPool pool;
886 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
887 Type_privateData *typical(internal->type_);
888
889 ssize_t index;
890 uint8_t *base;
891
892 if (!Index_(pool, context, internal, property, index, base))
893 return false;
894
895 CYPoolFFI(NULL, context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, value);
896 return true;
897 } CYCatch(false) }
898
899 static void Struct_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
900 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
901 Type_privateData *typical(internal->type_);
902 sig::Type *type(typical->type_);
903
904 if (type == NULL)
905 return;
906
907 size_t count(type->data.signature.count);
908 sig::Element *elements(type->data.signature.elements);
909
910 char number[32];
911
912 for (size_t index(0); index != count; ++index) {
913 const char *name;
914 name = elements[index].name;
915
916 if (name == NULL) {
917 sprintf(number, "%zu", index);
918 name = number;
919 }
920
921 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
922 }
923 }
924
925 JSValueRef CYCallFunction(CYPool &pool, JSContextRef context, size_t setups, void *setup[], size_t count, const JSValueRef arguments[], bool initialize, sig::Signature *signature, ffi_cif *cif, void (*function)()) {
926 if (setups + count != signature->count - 1)
927 throw CYJSError(context, "incorrect number of arguments to ffi function");
928
929 size_t size(setups + count);
930 void *values[size];
931 memcpy(values, setup, sizeof(void *) * setups);
932
933 for (size_t index(setups); index != size; ++index) {
934 sig::Element *element(&signature->elements[index + 1]);
935 ffi_type *ffi(cif->arg_types[index]);
936 // XXX: alignment?
937 values[index] = new(pool) uint8_t[ffi->size];
938 CYPoolFFI(&pool, context, element->type, ffi, values[index], arguments[index - setups]);
939 }
940
941 uint8_t value[cif->rtype->size];
942
943 if (hooks_ != NULL && hooks_->CallFunction != NULL)
944 (*hooks_->CallFunction)(context, cif, function, value, values);
945 else
946 ffi_call(cif, function, value, values);
947
948 return CYFromFFI(context, signature->elements[0].type, cif->rtype, value, initialize);
949 }
950
951 static JSValueRef Functor_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
952 CYPool pool;
953 cy::Functor *internal(reinterpret_cast<cy::Functor *>(JSObjectGetPrivate(object)));
954 return CYCallFunction(pool, context, 0, NULL, count, arguments, false, &internal->signature_, &internal->cif_, internal->GetValue());
955 } CYCatch(NULL) }
956
957 JSObjectRef CYMakeType(JSContextRef context, const char *type) {
958 Type_privateData *internal(new Type_privateData(type));
959 return JSObjectMake(context, Type_privateData::Class_, internal);
960 }
961
962 JSObjectRef CYMakeType(JSContextRef context, sig::Type *type) {
963 Type_privateData *internal(new Type_privateData(type));
964 return JSObjectMake(context, Type_privateData::Class_, internal);
965 }
966
967 static JSValueRef All_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
968 JSObjectRef global(CYGetGlobalObject(context));
969 JSObjectRef cycript(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Cycript"))));
970 JSObjectRef alls(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("alls"))));
971
972 for (size_t i(0), count(CYArrayLength(context, alls)); i != count; ++i)
973 if (JSObjectRef space = CYCastJSObject(context, CYArrayGet(context, alls, count - i - 1)))
974 if (JSValueRef value = CYGetProperty(context, space, property))
975 if (!JSValueIsUndefined(context, value))
976 return value;
977
978 CYPool pool;
979 CYUTF8String name(CYPoolUTF8String(pool, context, property));
980
981 size_t length(name.size);
982 char keyed[length + 2];
983 memcpy(keyed + 1, name.data, length + 1);
984
985 static const char *modes = "0124";
986 for (size_t i(0); i != 4; ++i) {
987 char mode(modes[i]);
988 keyed[0] = mode;
989
990 if (CYBridgeEntry *entry = CYBridgeHash(keyed, length + 1))
991 switch (mode) {
992 case '0':
993 return JSEvaluateScript(CYGetJSContext(context), CYJSString(entry->value_), NULL, NULL, 0, NULL);
994
995 case '1':
996 return CYMakeFunctor(context, name.data, entry->value_, &entry->cache_);
997
998 case '2':
999 if (void *symbol = CYCastSymbol(name.data)) {
1000 // XXX: this is horrendously inefficient
1001 sig::Signature signature;
1002 sig::Parse(pool, &signature, entry->value_, &Structor_);
1003 ffi_cif cif;
1004 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
1005 return CYFromFFI(context, signature.elements[0].type, cif.rtype, symbol);
1006 } else return NULL;
1007
1008 // XXX: implement case 3
1009 case '4':
1010 return CYMakeType(context, entry->value_);
1011 }
1012 }
1013
1014 return NULL;
1015 } CYCatch(NULL) }
1016
1017 static void All_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1018 JSObjectRef global(CYGetGlobalObject(context));
1019 JSObjectRef cycript(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Cycript"))));
1020 JSObjectRef alls(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("alls"))));
1021
1022 for (size_t i(0), count(CYArrayLength(context, alls)); i != count; ++i)
1023 if (JSObjectRef space = CYCastJSObject(context, CYArrayGet(context, alls, count - i - 1))) {
1024 JSPropertyNameArrayRef subset(JSObjectCopyPropertyNames(context, space));
1025 for (size_t index(0), count(JSPropertyNameArrayGetCount(subset)); index != count; ++index)
1026 JSPropertyNameAccumulatorAddName(names, JSPropertyNameArrayGetNameAtIndex(subset, index));
1027 JSPropertyNameArrayRelease(subset);
1028 }
1029 }
1030
1031 static JSObjectRef Pointer_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1032 if (count != 2)
1033 throw CYJSError(context, "incorrect number of arguments to Pointer constructor");
1034
1035 CYPool pool;
1036
1037 void *value(CYCastPointer<void *>(context, arguments[0]));
1038 const char *type(CYPoolCString(pool, context, arguments[1]));
1039
1040 sig::Signature signature;
1041 sig::Parse(pool, &signature, type, &Structor_);
1042
1043 return CYMakePointer(context, value, _not(size_t), signature.elements[0].type, NULL, NULL);
1044 } CYCatch(NULL) }
1045
1046 static JSObjectRef Type_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1047 if (count != 1)
1048 throw CYJSError(context, "incorrect number of arguments to Type constructor");
1049 CYPool pool;
1050 const char *type(CYPoolCString(pool, context, arguments[0]));
1051 return CYMakeType(context, type);
1052 } CYCatch(NULL) }
1053
1054 static JSValueRef Type_callAsFunction_arrayOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1055 if (count != 1)
1056 throw CYJSError(context, "incorrect number of arguments to Type.arrayOf");
1057 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
1058
1059 CYPool pool;
1060 size_t index(CYGetIndex(pool, context, CYJSString(context, arguments[0])));
1061 if (index == _not(size_t))
1062 throw CYJSError(context, "invalid array size used with Type.arrayOf");
1063
1064 sig::Type type;
1065 type.name = NULL;
1066 type.flags = 0;
1067
1068 type.primitive = sig::array_P;
1069 type.data.data.type = internal->type_;
1070 type.data.data.size = index;
1071
1072 return CYMakeType(context, &type);
1073 } CYCatch(NULL) }
1074
1075 static JSValueRef Type_callAsFunction_constant(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1076 if (count != 0)
1077 throw CYJSError(context, "incorrect number of arguments to Type.constant");
1078 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
1079
1080 sig::Type type(*internal->type_);
1081 type.flags |= JOC_TYPE_CONST;
1082 return CYMakeType(context, &type);
1083 } CYCatch(NULL) }
1084
1085 static JSValueRef Type_callAsFunction_pointerTo(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1086 if (count != 0)
1087 throw CYJSError(context, "incorrect number of arguments to Type.pointerTo");
1088 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
1089
1090 sig::Type type;
1091 type.name = NULL;
1092 type.flags = 0;
1093
1094 type.primitive = sig::pointer_P;
1095 type.data.data.type = internal->type_;
1096 type.data.data.size = 0;
1097
1098 return CYMakeType(context, &type);
1099 } CYCatch(NULL) }
1100
1101 static JSValueRef Type_callAsFunction_withName(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1102 if (count != 1)
1103 throw CYJSError(context, "incorrect number of arguments to Type.withName");
1104 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
1105
1106 CYPool pool;
1107 const char *name(CYPoolCString(pool, context, arguments[0]));
1108
1109 sig::Type type(*internal->type_);
1110 type.name = name;
1111 return CYMakeType(context, &type);
1112 } CYCatch(NULL) }
1113
1114 static JSValueRef Type_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1115 if (count != 1)
1116 throw CYJSError(context, "incorrect number of arguments to type cast function");
1117 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
1118
1119 sig::Type *type(internal->type_);
1120 ffi_type *ffi(internal->GetFFI());
1121 // XXX: alignment?
1122 uint8_t value[ffi->size];
1123 CYPool pool;
1124 CYPoolFFI(&pool, context, type, ffi, value, arguments[0]);
1125 return CYFromFFI(context, type, ffi, value);
1126 } CYCatch(NULL) }
1127
1128 static JSObjectRef Type_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1129 if (count != 0)
1130 throw CYJSError(context, "incorrect number of arguments to Type allocator");
1131 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
1132
1133 sig::Type *type(internal->type_);
1134 size_t length;
1135
1136 if (type->primitive != sig::array_P)
1137 length = _not(size_t);
1138 else {
1139 length = type->data.data.size;
1140 type = type->data.data.type;
1141 }
1142
1143 void *value(malloc(internal->GetFFI()->size));
1144 return CYMakePointer(context, value, length, type, NULL, NULL);
1145 } CYCatch(NULL) }
1146
1147 static JSObjectRef Functor_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1148 if (count != 2)
1149 throw CYJSError(context, "incorrect number of arguments to Functor constructor");
1150 CYPool pool;
1151 const char *type(CYPoolCString(pool, context, arguments[1]));
1152 return CYMakeFunctor(context, arguments[0], type);
1153 } CYCatch(NULL) }
1154
1155 static JSValueRef CYValue_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1156 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
1157 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
1158 } CYCatch(NULL) }
1159
1160 static JSValueRef CYValue_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1161 return CYValue_callAsFunction_valueOf(context, object, _this, count, arguments, exception);
1162 }
1163
1164 static JSValueRef CYValue_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1165 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
1166 char string[32];
1167 sprintf(string, "%p", internal->value_);
1168 return CYCastJSValue(context, string);
1169 } CYCatch(NULL) }
1170
1171 static JSValueRef Pointer_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1172 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(_this)));
1173 if (internal->length_ != _not(size_t)) {
1174 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1175 JSObjectRef toCYON(CYCastJSObject(context, CYGetProperty(context, Array, toCYON_s)));
1176 return CYCallAsFunction(context, toCYON, _this, count, arguments);
1177 } else {
1178 char string[32];
1179 sprintf(string, "%p", internal->value_);
1180 return CYCastJSValue(context, string);
1181 }
1182 } CYCatch(NULL) }
1183
1184 static JSValueRef Functor_getProperty_type(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1185 cy::Functor *internal(reinterpret_cast<cy::Functor *>(JSObjectGetPrivate(object)));
1186 CYPool pool;
1187 return CYCastJSValue(context, Unparse(pool, &internal->signature_));
1188 } CYCatch(NULL) }
1189
1190 static JSValueRef Type_getProperty_alignment(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1191 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
1192 return CYCastJSValue(context, internal->GetFFI()->alignment);
1193 } CYCatch(NULL) }
1194
1195 static JSValueRef Type_getProperty_name(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1196 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
1197 return CYCastJSValue(context, internal->type_->name);
1198 } CYCatch(NULL) }
1199
1200 static JSValueRef Type_getProperty_size(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1201 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
1202 return CYCastJSValue(context, internal->GetFFI()->size);
1203 } CYCatch(NULL) }
1204
1205 static JSValueRef Type_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1206 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
1207 CYPool pool;
1208 const char *type(sig::Unparse(pool, internal->type_));
1209 return CYCastJSValue(context, CYJSString(type));
1210 } CYCatch(NULL) }
1211
1212 static JSValueRef Type_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1213 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
1214 CYPool pool;
1215 const char *type(sig::Unparse(pool, internal->type_));
1216 std::ostringstream str;
1217 CYStringify(str, type, strlen(type));
1218 char *cyon(pool.strcat("new Type(", str.str().c_str(), ")", NULL));
1219 return CYCastJSValue(context, CYJSString(cyon));
1220 } CYCatch(NULL) }
1221
1222 static JSValueRef Type_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1223 return Type_callAsFunction_toString(context, object, _this, count, arguments, exception);
1224 }
1225
1226 static JSStaticFunction Pointer_staticFunctions[4] = {
1227 {"toCYON", &Pointer_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1228 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1229 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1230 {NULL, NULL, 0}
1231 };
1232
1233 static JSStaticFunction Struct_staticFunctions[2] = {
1234 {"$cya", &Struct_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1235 {NULL, NULL, 0}
1236 };
1237
1238 static JSStaticFunction Functor_staticFunctions[4] = {
1239 {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1240 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1241 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1242 {NULL, NULL, 0}
1243 };
1244
1245 namespace cy {
1246 JSStaticFunction const * const Functor::StaticFunctions = Functor_staticFunctions;
1247 }
1248
1249 static JSStaticValue Functor_staticValues[2] = {
1250 {"type", &Functor_getProperty_type, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1251 {NULL, NULL, NULL, 0}
1252 };
1253
1254 static JSStaticValue Type_staticValues[4] = {
1255 {"alignment", &Type_getProperty_alignment, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1256 {"name", &Type_getProperty_name, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1257 {"size", &Type_getProperty_size, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1258 {NULL, NULL, NULL, 0}
1259 };
1260
1261 static JSStaticFunction Type_staticFunctions[8] = {
1262 {"arrayOf", &Type_callAsFunction_arrayOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1263 {"constant", &Type_callAsFunction_constant, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1264 {"pointerTo", &Type_callAsFunction_pointerTo, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1265 {"withName", &Type_callAsFunction_withName, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1266 {"toCYON", &Type_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1267 {"toJSON", &Type_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1268 {"toString", &Type_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1269 {NULL, NULL, 0}
1270 };
1271
1272 static JSObjectRef (*JSObjectMakeArray$)(JSContextRef, size_t, const JSValueRef[], JSValueRef *);
1273
1274 void CYSetArgs(int argc, const char *argv[]) {
1275 JSContextRef context(CYGetJSContext());
1276 JSValueRef args[argc];
1277 for (int i(0); i != argc; ++i)
1278 args[i] = CYCastJSValue(context, argv[i]);
1279
1280 JSObjectRef array;
1281 if (JSObjectMakeArray$ != NULL)
1282 array = _jsccall(*JSObjectMakeArray$, context, argc, args);
1283 else {
1284 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array")));
1285 JSValueRef value(CYCallAsFunction(context, Array, NULL, argc, args));
1286 array = CYCastJSObject(context, value);
1287 }
1288
1289 JSObjectRef System(CYGetCachedObject(context, CYJSString("System")));
1290 CYSetProperty(context, System, CYJSString("args"), array);
1291 }
1292
1293 JSObjectRef CYGetGlobalObject(JSContextRef context) {
1294 return JSContextGetGlobalObject(context);
1295 }
1296
1297 const char *CYExecute(CYPool &pool, CYUTF8String code) {
1298 JSContextRef context(CYGetJSContext());
1299 JSValueRef exception(NULL);
1300
1301 void *handle;
1302 if (hooks_ != NULL && hooks_->ExecuteStart != NULL)
1303 handle = (*hooks_->ExecuteStart)(context);
1304 else
1305 handle = NULL;
1306
1307 try {
1308
1309 JSValueRef result;
1310 try {
1311 result = JSEvaluateScript(context, CYJSString(code), NULL, NULL, 0, &exception);
1312 } catch (const char *error) {
1313 return error;
1314 }
1315
1316 if (exception != NULL) error:
1317 return CYPoolCString(pool, context, CYJSString(context, exception));
1318
1319 if (JSValueIsUndefined(context, result))
1320 return NULL;
1321
1322 const char *json;
1323 try {
1324 json = CYPoolCCYON(pool, context, result, &exception);
1325 } catch (const char *error) {
1326 return error;
1327 }
1328
1329 if (exception != NULL)
1330 goto error;
1331
1332 CYSetProperty(context, CYGetGlobalObject(context), Result_, result);
1333
1334 return json;
1335
1336 } catch (...) {
1337 if (hooks_ != NULL && hooks_->ExecuteEnd != NULL)
1338 (*hooks_->ExecuteEnd)(context, handle);
1339 throw;
1340 }
1341 }
1342
1343 extern "C" void CydgetSetupContext(JSGlobalContextRef context) {
1344 CYSetupContext(context);
1345 }
1346
1347 static bool initialized_ = false;
1348
1349 void CYInitializeDynamic() {
1350 if (!initialized_)
1351 initialized_ = true;
1352 else return;
1353
1354 JSObjectMakeArray$ = reinterpret_cast<JSObjectRef (*)(JSContextRef, size_t, const JSValueRef[], JSValueRef *)>(dlsym(RTLD_DEFAULT, "JSObjectMakeArray"));
1355
1356 JSClassDefinition definition;
1357
1358 definition = kJSClassDefinitionEmpty;
1359 definition.className = "All";
1360 definition.getProperty = &All_getProperty;
1361 definition.getPropertyNames = &All_getPropertyNames;
1362 All_ = JSClassCreate(&definition);
1363
1364 definition = kJSClassDefinitionEmpty;
1365 definition.className = "Context";
1366 definition.finalize = &CYFinalize;
1367 Context_ = JSClassCreate(&definition);
1368
1369 definition = kJSClassDefinitionEmpty;
1370 definition.className = "Functor";
1371 definition.staticFunctions = cy::Functor::StaticFunctions;
1372 definition.staticValues = Functor_staticValues;
1373 definition.callAsFunction = &Functor_callAsFunction;
1374 definition.finalize = &CYFinalize;
1375 Functor_ = JSClassCreate(&definition);
1376
1377 definition = kJSClassDefinitionEmpty;
1378 definition.className = "Pointer";
1379 definition.staticFunctions = Pointer_staticFunctions;
1380 definition.getProperty = &Pointer_getProperty;
1381 definition.setProperty = &Pointer_setProperty;
1382 definition.finalize = &CYFinalize;
1383 Pointer_ = JSClassCreate(&definition);
1384
1385 definition = kJSClassDefinitionEmpty;
1386 definition.className = "Struct";
1387 definition.staticFunctions = Struct_staticFunctions;
1388 definition.getProperty = &Struct_getProperty;
1389 definition.setProperty = &Struct_setProperty;
1390 definition.getPropertyNames = &Struct_getPropertyNames;
1391 definition.finalize = &CYFinalize;
1392 Struct_ = JSClassCreate(&definition);
1393
1394 definition = kJSClassDefinitionEmpty;
1395 definition.className = "Type";
1396 definition.staticValues = Type_staticValues;
1397 definition.staticFunctions = Type_staticFunctions;
1398 definition.callAsFunction = &Type_callAsFunction;
1399 definition.callAsConstructor = &Type_callAsConstructor;
1400 definition.finalize = &CYFinalize;
1401 Type_privateData::Class_ = JSClassCreate(&definition);
1402
1403 definition = kJSClassDefinitionEmpty;
1404 definition.className = "Global";
1405 //definition.getProperty = &Global_getProperty;
1406 Global_ = JSClassCreate(&definition);
1407
1408 Array_s = JSStringCreateWithUTF8CString("Array");
1409 cy_s = JSStringCreateWithUTF8CString("$cy");
1410 length_s = JSStringCreateWithUTF8CString("length");
1411 message_s = JSStringCreateWithUTF8CString("message");
1412 name_s = JSStringCreateWithUTF8CString("name");
1413 pop_s = JSStringCreateWithUTF8CString("pop");
1414 prototype_s = JSStringCreateWithUTF8CString("prototype");
1415 push_s = JSStringCreateWithUTF8CString("push");
1416 splice_s = JSStringCreateWithUTF8CString("splice");
1417 toCYON_s = JSStringCreateWithUTF8CString("toCYON");
1418 toJSON_s = JSStringCreateWithUTF8CString("toJSON");
1419 toPointer_s = JSStringCreateWithUTF8CString("toPointer");
1420 toString_s = JSStringCreateWithUTF8CString("toString");
1421
1422 Result_ = JSStringCreateWithUTF8CString("_");
1423
1424 if (hooks_ != NULL && hooks_->Initialize != NULL)
1425 (*hooks_->Initialize)();
1426 }
1427
1428 void CYThrow(JSContextRef context, JSValueRef value) {
1429 if (value != NULL)
1430 throw CYJSError(context, value);
1431 }
1432
1433 const char *CYJSError::PoolCString(CYPool &pool) const {
1434 // XXX: this used to be CYPoolCString
1435 return CYPoolCCYON(pool, context_, value_);
1436 }
1437
1438 JSValueRef CYJSError::CastJSValue(JSContextRef context) const {
1439 // XXX: what if the context is different?
1440 return value_;
1441 }
1442
1443 JSValueRef CYCastJSError(JSContextRef context, const char *message) {
1444 JSObjectRef Error(CYGetCachedObject(context, CYJSString("Error")));
1445 JSValueRef arguments[1] = {CYCastJSValue(context, message)};
1446 return _jsccall(JSObjectCallAsConstructor, context, Error, 1, arguments);
1447 }
1448
1449 JSValueRef CYPoolError::CastJSValue(JSContextRef context) const {
1450 return CYCastJSError(context, message_);
1451 }
1452
1453 CYJSError::CYJSError(JSContextRef context, const char *format, ...) {
1454 _assert(context != NULL);
1455
1456 CYPool pool;
1457
1458 va_list args;
1459 va_start(args, format);
1460 // XXX: there might be a beter way to think about this
1461 const char *message(pool.vsprintf(64, format, args));
1462 va_end(args);
1463
1464 value_ = CYCastJSError(context, message);
1465 }
1466
1467 JSGlobalContextRef CYGetJSContext(JSContextRef context) {
1468 return reinterpret_cast<Context *>(JSObjectGetPrivate(CYCastJSObject(context, CYGetProperty(context, CYGetGlobalObject(context), cy_s))))->context_;
1469 }
1470
1471 extern "C" void CYSetupContext(JSGlobalContextRef context) {
1472 CYInitializeDynamic();
1473
1474 JSObjectRef global(CYGetGlobalObject(context));
1475
1476 JSObjectRef cy(JSObjectMake(context, Context_, new Context(context)));
1477 CYSetProperty(context, global, cy_s, cy, kJSPropertyAttributeDontEnum);
1478
1479 /* Cache Globals {{{ */
1480 JSObjectRef Array(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Array"))));
1481 CYSetProperty(context, cy, CYJSString("Array"), Array);
1482
1483 JSObjectRef Array_prototype(CYCastJSObject(context, CYGetProperty(context, Array, prototype_s)));
1484 CYSetProperty(context, cy, CYJSString("Array_prototype"), Array_prototype);
1485
1486 JSObjectRef Error(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Error"))));
1487 CYSetProperty(context, cy, CYJSString("Error"), Error);
1488
1489 JSObjectRef Function(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Function"))));
1490 CYSetProperty(context, cy, CYJSString("Function"), Function);
1491
1492 JSObjectRef Function_prototype(CYCastJSObject(context, CYGetProperty(context, Function, prototype_s)));
1493 CYSetProperty(context, cy, CYJSString("Function_prototype"), Function_prototype);
1494
1495 JSObjectRef Object(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Object"))));
1496 CYSetProperty(context, cy, CYJSString("Object"), Object);
1497
1498 JSObjectRef Object_prototype(CYCastJSObject(context, CYGetProperty(context, Object, prototype_s)));
1499 CYSetProperty(context, cy, CYJSString("Object_prototype"), Object_prototype);
1500
1501 JSObjectRef String(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("String"))));
1502 CYSetProperty(context, cy, CYJSString("String"), String);
1503
1504 JSObjectRef String_prototype(CYCastJSObject(context, CYGetProperty(context, String, prototype_s)));
1505 CYSetProperty(context, cy, CYJSString("String_prototype"), String_prototype);
1506 /* }}} */
1507
1508 CYSetProperty(context, Array_prototype, toCYON_s, &Array_callAsFunction_toCYON, kJSPropertyAttributeDontEnum);
1509 CYSetProperty(context, String_prototype, toCYON_s, &String_callAsFunction_toCYON, kJSPropertyAttributeDontEnum);
1510
1511 JSObjectRef cycript(JSObjectMake(context, NULL, NULL));
1512 CYSetProperty(context, global, CYJSString("Cycript"), cycript);
1513 CYSetProperty(context, cycript, CYJSString("gc"), &Cycript_gc_callAsFunction);
1514
1515 JSObjectRef Functor(JSObjectMakeConstructor(context, Functor_, &Functor_new));
1516 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Functor, prototype_s)), Function_prototype);
1517 CYSetProperty(context, cycript, CYJSString("Functor"), Functor);
1518
1519 CYSetProperty(context, cycript, CYJSString("Pointer"), JSObjectMakeConstructor(context, Pointer_, &Pointer_new));
1520 CYSetProperty(context, cycript, CYJSString("Type"), JSObjectMakeConstructor(context, Type_privateData::Class_, &Type_new));
1521
1522 JSObjectRef all(JSObjectMake(context, All_, NULL));
1523 CYSetProperty(context, cycript, CYJSString("all"), all);
1524
1525 JSObjectRef alls(_jsccall(JSObjectCallAsConstructor, context, Array, 0, NULL));
1526 CYSetProperty(context, cycript, CYJSString("alls"), alls);
1527
1528 if (true) {
1529 JSObjectRef last(NULL), curr(global);
1530
1531 goto next; for (JSValueRef next;;) {
1532 if (JSValueIsNull(context, next))
1533 break;
1534 last = curr;
1535 curr = CYCastJSObject(context, next);
1536 next:
1537 next = JSObjectGetPrototype(context, curr);
1538 }
1539
1540 JSObjectSetPrototype(context, last, all);
1541 }
1542
1543 CYSetProperty(context, global, CYJSString("$cyq"), &$cyq, kJSPropertyAttributeDontEnum);
1544
1545 JSObjectRef System(JSObjectMake(context, NULL, NULL));
1546 CYSetProperty(context, cy, CYJSString("System"), System);
1547
1548 CYSetProperty(context, global, CYJSString("system"), System);
1549 CYSetProperty(context, System, CYJSString("args"), CYJSNull(context));
1550 //CYSetProperty(context, System, CYJSString("global"), global);
1551 CYSetProperty(context, System, CYJSString("print"), &System_print);
1552
1553 if (CYBridgeEntry *entry = CYBridgeHash("1dlerror", 8))
1554 entry->cache_ = new cy::Functor(entry->value_, reinterpret_cast<void (*)()>(&dlerror));
1555
1556 if (hooks_ != NULL && hooks_->SetupContext != NULL)
1557 (*hooks_->SetupContext)(context);
1558
1559 CYArrayPush(context, alls, cycript);
1560 }
1561
1562 JSGlobalContextRef CYGetJSContext() {
1563 CYInitializeDynamic();
1564
1565 static JSGlobalContextRef context_;
1566
1567 if (context_ == NULL) {
1568 context_ = JSGlobalContextCreate(Global_);
1569 CYSetupContext(context_);
1570 }
1571
1572 return context_;
1573 }