]> git.saurik.com Git - cycript.git/blob - Execute.cpp
Port Error.toCYON() to JS and write Date.toCYON().
[cycript.git] / Execute.cpp
1 /* Cycript - Optimizing JavaScript Compiler/Runtime
2 * Copyright (C) 2009-2015 Jay Freeman (saurik)
3 */
4
5 /* GNU Affero General Public License, Version 3 {{{ */
6 /*
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
16
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 **/
20 /* }}} */
21
22 #include "cycript.hpp"
23
24 #include <iostream>
25 #include <set>
26 #include <map>
27 #include <iomanip>
28 #include <sstream>
29 #include <cmath>
30
31 #include <dlfcn.h>
32 #include <dirent.h>
33 #include <fcntl.h>
34 #include <unistd.h>
35
36 #include <sys/mman.h>
37 #include <sys/stat.h>
38
39 #include "sig/parse.hpp"
40 #include "sig/ffi_type.hpp"
41
42 #include "Code.hpp"
43 #include "Decode.hpp"
44 #include "Error.hpp"
45 #include "Execute.hpp"
46 #include "Internal.hpp"
47 #include "JavaScript.hpp"
48 #include "Pooling.hpp"
49 #include "String.hpp"
50
51 static std::vector<CYHook *> &GetHooks() {
52 static std::vector<CYHook *> hooks;
53 return hooks;
54 }
55
56 CYRegisterHook::CYRegisterHook(CYHook *hook) {
57 GetHooks().push_back(hook);
58 }
59
60 /* JavaScript Properties {{{ */
61 bool CYHasProperty(JSContextRef context, JSObjectRef object, JSStringRef name) {
62 return JSObjectHasProperty(context, object, name);
63 }
64
65 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, size_t index) {
66 return _jsccall(JSObjectGetPropertyAtIndex, context, object, index);
67 }
68
69 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, JSStringRef name) {
70 return _jsccall(JSObjectGetProperty, context, object, name);
71 }
72
73 void CYSetProperty(JSContextRef context, JSObjectRef object, size_t index, JSValueRef value) {
74 _jsccall(JSObjectSetPropertyAtIndex, context, object, index, value);
75 }
76
77 void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef value, JSPropertyAttributes attributes) {
78 _jsccall(JSObjectSetProperty, context, object, name, value, attributes);
79 }
80
81 void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef (*callback)(JSContextRef, JSObjectRef, JSObjectRef, size_t, const JSValueRef[], JSValueRef *), JSPropertyAttributes attributes) {
82 CYSetProperty(context, object, name, JSObjectMakeFunctionWithCallback(context, name, callback), attributes);
83 }
84
85 void CYSetPrototype(JSContextRef context, JSObjectRef object, JSValueRef value) {
86 JSObjectSetPrototype(context, object, value);
87 _assert(CYIsStrictEqual(context, JSObjectGetPrototype(context, object), value));
88 }
89 /* }}} */
90 /* JavaScript Strings {{{ */
91 JSStringRef CYCopyJSString(const char *value) {
92 return value == NULL ? NULL : JSStringCreateWithUTF8CString(value);
93 }
94
95 JSStringRef CYCopyJSString(JSStringRef value) {
96 return value == NULL ? NULL : JSStringRetain(value);
97 }
98
99 JSStringRef CYCopyJSString(CYUTF8String value) {
100 // XXX: this is very wrong; it needs to convert to UTF16 and then create from there
101 return CYCopyJSString(value.data);
102 }
103
104 JSStringRef CYCopyJSString(JSContextRef context, JSValueRef value) {
105 if (JSValueIsNull(context, value))
106 return NULL;
107 return _jsccall(JSValueToStringCopy, context, value);
108 }
109
110 static CYUTF16String CYCastUTF16String(JSStringRef value) {
111 return CYUTF16String(JSStringGetCharactersPtr(value), JSStringGetLength(value));
112 }
113
114 CYUTF8String CYPoolUTF8String(CYPool &pool, JSContextRef context, JSStringRef value) {
115 return CYPoolUTF8String(pool, CYCastUTF16String(value));
116 }
117
118 const char *CYPoolCString(CYPool &pool, JSContextRef context, JSStringRef value) {
119 CYUTF8String utf8(CYPoolUTF8String(pool, context, value));
120 _assert(memchr(utf8.data, '\0', utf8.size) == NULL);
121 return utf8.data;
122 }
123
124 const char *CYPoolCString(CYPool &pool, JSContextRef context, JSValueRef value) {
125 return JSValueIsNull(context, value) ? NULL : CYPoolCString(pool, context, CYJSString(context, value));
126 }
127 /* }}} */
128 /* Index Offsets {{{ */
129 size_t CYGetIndex(CYPool &pool, JSContextRef context, JSStringRef value) {
130 return CYGetIndex(CYPoolUTF8String(pool, context, value));
131 }
132 /* }}} */
133
134 static JSClassRef All_;
135 static JSClassRef Context_;
136 JSClassRef Functor_;
137 static JSClassRef Global_;
138 static JSClassRef Pointer_;
139 static JSClassRef Struct_;
140
141 JSStringRef Array_s;
142 JSStringRef cy_s;
143 JSStringRef cyi_s;
144 JSStringRef length_s;
145 JSStringRef message_s;
146 JSStringRef name_s;
147 JSStringRef pop_s;
148 JSStringRef prototype_s;
149 JSStringRef push_s;
150 JSStringRef splice_s;
151 JSStringRef toCYON_s;
152 JSStringRef toJSON_s;
153 JSStringRef toPointer_s;
154 JSStringRef toString_s;
155 JSStringRef weak_s;
156
157 static JSStringRef Result_;
158
159 void CYFinalize(JSObjectRef object) {
160 CYData *internal(reinterpret_cast<CYData *>(JSObjectGetPrivate(object)));
161 _assert(internal->count_ != _not(unsigned));
162 if (--internal->count_ == 0)
163 delete internal;
164 }
165
166 void Structor_(CYPool &pool, sig::Type *&type) {
167 if (
168 type->primitive == sig::pointer_P &&
169 type->data.data.type->primitive == sig::struct_P &&
170 type->data.data.type->name != NULL &&
171 strcmp(type->data.data.type->name, "_objc_class") == 0
172 ) {
173 type->primitive = sig::typename_P;
174 type->data.data.type = NULL;
175 return;
176 }
177
178 if (type->primitive != sig::struct_P || type->name == NULL)
179 return;
180
181 size_t length(strlen(type->name));
182 char keyed[length + 2];
183 memcpy(keyed + 1, type->name, length + 1);
184
185 static const char *modes = "34";
186 for (size_t i(0); i != 2; ++i) {
187 char mode(modes[i]);
188 keyed[0] = mode;
189
190 if (CYBridgeEntry *entry = CYBridgeHash(keyed, length + 1))
191 switch (mode) {
192 case '3':
193 sig::Parse(pool, &type->data.signature, entry->value_, &Structor_);
194 break;
195
196 case '4': {
197 sig::Signature signature;
198 sig::Parse(pool, &signature, entry->value_, &Structor_);
199 type = signature.elements[0].type;
200 } break;
201 }
202 }
203 }
204
205 JSClassRef Type_privateData::Class_;
206
207 struct Context :
208 CYData
209 {
210 JSGlobalContextRef context_;
211
212 Context(JSGlobalContextRef context) :
213 context_(context)
214 {
215 }
216 };
217
218 struct Pointer :
219 CYOwned
220 {
221 Type_privateData *type_;
222 size_t length_;
223
224 Pointer(void *value, JSContextRef context, JSObjectRef owner, size_t length, sig::Type *type) :
225 CYOwned(value, context, owner),
226 type_(new(*pool_) Type_privateData(type)),
227 length_(length)
228 {
229 }
230 };
231
232 struct Struct_privateData :
233 CYOwned
234 {
235 Type_privateData *type_;
236
237 Struct_privateData(JSContextRef context, JSObjectRef owner) :
238 CYOwned(NULL, context, owner)
239 {
240 }
241 };
242
243 JSObjectRef CYMakeStruct(JSContextRef context, void *data, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
244 Struct_privateData *internal(new Struct_privateData(context, owner));
245 CYPool &pool(*internal->pool_);
246 Type_privateData *typical(new(pool) Type_privateData(type, ffi));
247 internal->type_ = typical;
248
249 if (owner != NULL)
250 internal->value_ = data;
251 else {
252 size_t size(typical->GetFFI()->size);
253 void *copy(internal->pool_->malloc<void>(size));
254 memcpy(copy, data, size);
255 internal->value_ = copy;
256 }
257
258 return JSObjectMake(context, Struct_, internal);
259 }
260
261 static void *CYCastSymbol(const char *name) {
262 for (CYHook *hook : GetHooks())
263 if (hook->CastSymbol != NULL)
264 if (void *value = (*hook->CastSymbol)(name))
265 return value;
266 return dlsym(RTLD_DEFAULT, name);
267 }
268
269 JSValueRef CYCastJSValue(JSContextRef context, bool value) {
270 return JSValueMakeBoolean(context, value);
271 }
272
273 JSValueRef CYCastJSValue(JSContextRef context, double value) {
274 return JSValueMakeNumber(context, value);
275 }
276
277 #define CYCastJSValue_(Type_) \
278 JSValueRef CYCastJSValue(JSContextRef context, Type_ value) { \
279 return JSValueMakeNumber(context, static_cast<double>(value)); \
280 }
281
282 CYCastJSValue_(int)
283 CYCastJSValue_(unsigned int)
284 CYCastJSValue_(long int)
285 CYCastJSValue_(long unsigned int)
286 CYCastJSValue_(long long int)
287 CYCastJSValue_(long long unsigned int)
288
289 JSValueRef CYJSUndefined(JSContextRef context) {
290 return JSValueMakeUndefined(context);
291 }
292
293 double CYCastDouble(JSContextRef context, JSValueRef value) {
294 return _jsccall(JSValueToNumber, context, value);
295 }
296
297 bool CYCastBool(JSContextRef context, JSValueRef value) {
298 return JSValueToBoolean(context, value);
299 }
300
301 JSValueRef CYJSNull(JSContextRef context) {
302 return JSValueMakeNull(context);
303 }
304
305 JSValueRef CYCastJSValue(JSContextRef context, JSStringRef value) {
306 return value == NULL ? CYJSNull(context) : JSValueMakeString(context, value);
307 }
308
309 JSValueRef CYCastJSValue(JSContextRef context, const char *value) {
310 return CYCastJSValue(context, CYJSString(value));
311 }
312
313 JSObjectRef CYCastJSObject(JSContextRef context, JSValueRef value) {
314 return _jsccall(JSValueToObject, context, value);
315 }
316
317 JSValueRef CYCallAsFunction(JSContextRef context, JSObjectRef function, JSObjectRef _this, size_t count, const JSValueRef arguments[]) {
318 return _jsccall(JSObjectCallAsFunction, context, function, _this, count, arguments);
319 }
320
321 bool CYIsCallable(JSContextRef context, JSValueRef value) {
322 return value != NULL && JSValueIsObject(context, value) && JSObjectIsFunction(context, (JSObjectRef) value);
323 }
324
325 bool CYIsEqual(JSContextRef context, JSValueRef lhs, JSValueRef rhs) {
326 return _jsccall(JSValueIsEqual, context, lhs, rhs);
327 }
328
329 bool CYIsStrictEqual(JSContextRef context, JSValueRef lhs, JSValueRef rhs) {
330 return JSValueIsStrictEqual(context, lhs, rhs);
331 }
332
333 size_t CYArrayLength(JSContextRef context, JSObjectRef array) {
334 return CYCastDouble(context, CYGetProperty(context, array, length_s));
335 }
336
337 JSValueRef CYArrayGet(JSContextRef context, JSObjectRef array, size_t index) {
338 return _jsccall(JSObjectGetPropertyAtIndex, context, array, index);
339 }
340
341 void CYArrayPush(JSContextRef context, JSObjectRef array, JSValueRef value) {
342 JSValueRef arguments[1];
343 arguments[0] = value;
344 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
345 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, push_s)), array, 1, arguments);
346 }
347
348 static JSValueRef System_print(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
349 FILE *file(stdout);
350
351 if (count == 0)
352 fputc('\n', file);
353 else {
354 CYPool pool;
355 CYUTF8String string(CYPoolUTF8String(pool, context, CYJSString(context, arguments[0])));
356 fwrite(string.data, string.size, 1, file);
357 }
358
359 fflush(file);
360 return CYJSUndefined(context);
361 } CYCatch(NULL) }
362
363 static void (*JSSynchronousGarbageCollectForDebugging$)(JSContextRef);
364
365 _visible void CYGarbageCollect(JSContextRef context) {
366 (JSSynchronousGarbageCollectForDebugging$ ?: &JSGarbageCollect)(context);
367 }
368
369 static JSValueRef Cycript_compile_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
370 CYPool pool;
371 CYUTF8String before(CYPoolUTF8String(pool, context, CYJSString(context, arguments[0])));
372 std::stringbuf value(std::string(before.data, before.size));
373 CYUTF8String after(CYPoolCode(pool, value));
374 return CYCastJSValue(context, CYJSString(after));
375 } CYCatch_(NULL, "SyntaxError") }
376
377 static JSValueRef Cycript_gc_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
378 CYGarbageCollect(context);
379 return CYJSUndefined(context);
380 } CYCatch(NULL) }
381
382 const char *CYPoolCCYON(CYPool &pool, JSContextRef context, JSValueRef value, std::set<void *> &objects, JSValueRef *exception) { CYTry {
383 switch (JSType type = JSValueGetType(context, value)) {
384 case kJSTypeUndefined:
385 return "undefined";
386 case kJSTypeNull:
387 return "null";
388 case kJSTypeBoolean:
389 return CYCastBool(context, value) ? "true" : "false";
390
391 case kJSTypeNumber: {
392 std::ostringstream str;
393 CYNumerify(str, CYCastDouble(context, value));
394 std::string value(str.str());
395 return pool.strmemdup(value.c_str(), value.size());
396 } break;
397
398 case kJSTypeString: {
399 std::ostringstream str;
400 CYUTF8String string(CYPoolUTF8String(pool, context, CYJSString(context, value)));
401 CYStringify(str, string.data, string.size);
402 std::string value(str.str());
403 return pool.strmemdup(value.c_str(), value.size());
404 } break;
405
406 case kJSTypeObject:
407 return CYPoolCCYON(pool, context, (JSObjectRef) value, objects);
408 default:
409 throw CYJSError(context, "JSValueGetType() == 0x%x", type);
410 }
411 } CYCatch(NULL) }
412
413 const char *CYPoolCCYON(CYPool &pool, JSContextRef context, JSValueRef value, std::set<void *> &objects) {
414 return _jsccall(CYPoolCCYON, pool, context, value, objects);
415 }
416
417 const char *CYPoolCCYON(CYPool &pool, JSContextRef context, JSValueRef value, std::set<void *> *objects) {
418 if (objects != NULL)
419 return CYPoolCCYON(pool, context, value, *objects);
420 else {
421 std::set<void *> objects;
422 return CYPoolCCYON(pool, context, value, objects);
423 }
424 }
425
426 const char *CYPoolCCYON(CYPool &pool, JSContextRef context, JSObjectRef object, std::set<void *> &objects) {
427 JSValueRef toCYON(CYGetProperty(context, object, toCYON_s));
428 if (CYIsCallable(context, toCYON)) {
429 // XXX: this needs to be abstracted behind some kind of function
430 JSValueRef arguments[1] = {CYCastJSValue(context, reinterpret_cast<uintptr_t>(&objects))};
431 JSValueRef value(CYCallAsFunction(context, (JSObjectRef) toCYON, object, 1, arguments));
432 _assert(value != NULL);
433 return CYPoolCString(pool, context, value);
434 }
435
436 JSValueRef toJSON(CYGetProperty(context, object, toJSON_s));
437 if (CYIsCallable(context, toJSON)) {
438 JSValueRef arguments[1] = {CYCastJSValue(context, CYJSString(""))};
439 return _jsccall(CYPoolCCYON, pool, context, CYCallAsFunction(context, (JSObjectRef) toJSON, object, 1, arguments), objects);
440 }
441
442 if (JSObjectIsFunction(context, object)) {
443 JSValueRef toString(CYGetProperty(context, object, toString_s));
444 if (CYIsCallable(context, toString)) {
445 JSValueRef arguments[1] = {CYCastJSValue(context, CYJSString(""))};
446 JSValueRef value(CYCallAsFunction(context, (JSObjectRef) toString, object, 1, arguments));
447 _assert(value != NULL);
448 return CYPoolCString(pool, context, value);
449 }
450 }
451
452 _assert(objects.insert(object).second);
453
454 std::ostringstream str;
455
456 str << '{';
457
458 // XXX: this is, sadly, going to leak
459 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context, object));
460
461 bool comma(false);
462
463 for (size_t index(0), count(JSPropertyNameArrayGetCount(names)); index != count; ++index) {
464 if (comma)
465 str << ',';
466 else
467 comma = true;
468
469 JSStringRef name(JSPropertyNameArrayGetNameAtIndex(names, index));
470 CYUTF8String string(CYPoolUTF8String(pool, context, name));
471
472 if (CYIsKey(string))
473 str << string.data;
474 else
475 CYStringify(str, string.data, string.size);
476
477 str << ':';
478
479 try {
480 JSValueRef value(CYGetProperty(context, object, name));
481 str << CYPoolCCYON(pool, context, value, objects);
482 } catch (const CYException &error) {
483 str << "@error";
484 }
485 }
486
487 JSPropertyNameArrayRelease(names);
488
489 str << '}';
490
491 std::string string(str.str());
492 return pool.strmemdup(string.c_str(), string.size());
493 }
494
495 std::set<void *> *CYCastObjects(JSContextRef context, JSObjectRef _this, size_t count, const JSValueRef arguments[]) {
496 if (count == 0)
497 return NULL;
498 return CYCastPointer<std::set<void *> *>(context, arguments[0]);
499 }
500
501 static JSValueRef Array_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
502 std::set<void *> *objects(CYCastObjects(context, _this, count, arguments));
503 // XXX: this is horribly inefficient
504 std::set<void *> backup;
505 if (objects == NULL)
506 objects = &backup;
507
508 CYPool pool;
509 std::ostringstream str;
510
511 str << '[';
512
513 JSValueRef length(CYGetProperty(context, _this, length_s));
514 bool comma(false);
515
516 for (size_t index(0), count(CYCastDouble(context, length)); index != count; ++index) {
517 if (comma)
518 str << ',';
519 else
520 comma = true;
521
522 try {
523 JSValueRef value(CYGetProperty(context, _this, index));
524 if (!JSValueIsUndefined(context, value))
525 str << CYPoolCCYON(pool, context, value, *objects);
526 else {
527 str << ',';
528 comma = false;
529 }
530 } catch (const CYException &error) {
531 str << "@error";
532 }
533 }
534
535 str << ']';
536
537 std::string value(str.str());
538 return CYCastJSValue(context, CYJSString(CYUTF8String(value.c_str(), value.size())));
539 } CYCatch(NULL) }
540
541 static JSValueRef String_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
542 CYPool pool;
543 std::ostringstream str;
544
545 CYUTF8String string(CYPoolUTF8String(pool, context, CYJSString(context, _this)));
546 CYStringify(str, string.data, string.size);
547
548 std::string value(str.str());
549 return CYCastJSValue(context, CYJSString(CYUTF8String(value.c_str(), value.size())));
550 } CYCatch(NULL) }
551
552 JSObjectRef CYMakePointer(JSContextRef context, void *pointer, size_t length, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
553 Pointer *internal(new Pointer(pointer, context, owner, length, type));
554 return JSObjectMake(context, Pointer_, internal);
555 }
556
557 static JSObjectRef CYMakeFunctor(JSContextRef context, void (*function)(), const sig::Signature &signature) {
558 return JSObjectMake(context, Functor_, new cy::Functor(signature, function));
559 }
560
561 static JSObjectRef CYMakeFunctor(JSContextRef context, const char *symbol, const char *encoding, void **cache) {
562 cy::Functor *internal;
563 if (*cache != NULL)
564 internal = reinterpret_cast<cy::Functor *>(*cache);
565 else {
566 void (*function)()(reinterpret_cast<void (*)()>(CYCastSymbol(symbol)));
567 if (function == NULL)
568 return NULL;
569
570 internal = new cy::Functor(encoding, function);
571 *cache = internal;
572 }
573
574 ++internal->count_;
575 return JSObjectMake(context, Functor_, internal);
576 }
577
578 static bool CYGetOffset(CYPool &pool, JSContextRef context, JSStringRef value, ssize_t &index) {
579 return CYGetOffset(CYPoolCString(pool, context, value), index);
580 }
581
582 void *CYCastPointer_(JSContextRef context, JSValueRef value) {
583 if (value == NULL)
584 return NULL;
585 else switch (JSValueGetType(context, value)) {
586 case kJSTypeNull:
587 return NULL;
588 case kJSTypeObject: {
589 JSObjectRef object((JSObjectRef) value);
590 if (JSValueIsObjectOfClass(context, value, Pointer_)) {
591 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
592 return internal->value_;
593 }
594 JSValueRef toPointer(CYGetProperty(context, object, toPointer_s));
595 if (CYIsCallable(context, toPointer)) {
596 JSValueRef value(CYCallAsFunction(context, (JSObjectRef) toPointer, object, 0, NULL));
597 _assert(value != NULL);
598 return CYCastPointer_(context, value);
599 }
600 } default:
601 double number(CYCastDouble(context, value));
602 if (std::isnan(number))
603 throw CYJSError(context, "cannot convert value to pointer");
604 return reinterpret_cast<void *>(static_cast<uintptr_t>(static_cast<long long>(number)));
605 }
606 }
607
608 void CYPoolFFI(CYPool *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) {
609 switch (type->primitive) {
610 case sig::boolean_P:
611 *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
612 break;
613
614 #define CYPoolFFI_(primitive, native) \
615 case sig::primitive ## _P: \
616 *reinterpret_cast<native *>(data) = CYCastDouble(context, value); \
617 break;
618
619 CYPoolFFI_(uchar, unsigned char)
620 CYPoolFFI_(char, char)
621 CYPoolFFI_(ushort, unsigned short)
622 CYPoolFFI_(short, short)
623 CYPoolFFI_(ulong, unsigned long)
624 CYPoolFFI_(long, long)
625 CYPoolFFI_(uint, unsigned int)
626 CYPoolFFI_(int, int)
627 CYPoolFFI_(ulonglong, unsigned long long)
628 CYPoolFFI_(longlong, long long)
629 CYPoolFFI_(float, float)
630 CYPoolFFI_(double, double)
631
632 case sig::array_P: {
633 uint8_t *base(reinterpret_cast<uint8_t *>(data));
634 JSObjectRef aggregate(JSValueIsObject(context, value) ? (JSObjectRef) value : NULL);
635 for (size_t index(0); index != type->data.data.size; ++index) {
636 ffi_type *field(ffi->elements[index]);
637
638 JSValueRef rhs;
639 if (aggregate == NULL)
640 rhs = value;
641 else {
642 rhs = CYGetProperty(context, aggregate, index);
643 if (JSValueIsUndefined(context, rhs))
644 throw CYJSError(context, "unable to extract array value");
645 }
646
647 CYPoolFFI(pool, context, type->data.data.type, field, base, rhs);
648 // XXX: alignment?
649 base += field->size;
650 }
651 } break;
652
653 case sig::pointer_P:
654 *reinterpret_cast<void **>(data) = CYCastPointer<void *>(context, value);
655 break;
656
657 case sig::string_P:
658 _assert(pool != NULL);
659 *reinterpret_cast<const char **>(data) = CYPoolCString(*pool, context, value);
660 break;
661
662 case sig::struct_P: {
663 uint8_t *base(reinterpret_cast<uint8_t *>(data));
664 JSObjectRef aggregate(JSValueIsObject(context, value) ? (JSObjectRef) value : NULL);
665 for (size_t index(0); index != type->data.signature.count; ++index) {
666 sig::Element *element(&type->data.signature.elements[index]);
667 ffi_type *field(ffi->elements[index]);
668
669 JSValueRef rhs;
670 if (aggregate == NULL)
671 rhs = value;
672 else {
673 rhs = CYGetProperty(context, aggregate, index);
674 if (JSValueIsUndefined(context, rhs)) {
675 if (element->name != NULL)
676 rhs = CYGetProperty(context, aggregate, CYJSString(element->name));
677 else
678 goto undefined;
679 if (JSValueIsUndefined(context, rhs)) undefined:
680 throw CYJSError(context, "unable to extract structure value");
681 }
682 }
683
684 CYPoolFFI(pool, context, element->type, field, base, rhs);
685 // XXX: alignment?
686 base += field->size;
687 }
688 } break;
689
690 case sig::void_P:
691 break;
692
693 default:
694 for (CYHook *hook : GetHooks())
695 if (hook->PoolFFI != NULL)
696 if ((*hook->PoolFFI)(pool, context, type, ffi, data, value))
697 return;
698
699 CYThrow("unimplemented signature code: '%c''\n", type->primitive);
700 }
701 }
702
703 JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) {
704 switch (type->primitive) {
705 case sig::boolean_P:
706 return CYCastJSValue(context, *reinterpret_cast<bool *>(data));
707
708 #define CYFromFFI_(primitive, native) \
709 case sig::primitive ## _P: \
710 return CYCastJSValue(context, *reinterpret_cast<native *>(data)); \
711
712 CYFromFFI_(uchar, unsigned char)
713 CYFromFFI_(char, char)
714 CYFromFFI_(ushort, unsigned short)
715 CYFromFFI_(short, short)
716 CYFromFFI_(ulong, unsigned long)
717 CYFromFFI_(long, long)
718 CYFromFFI_(uint, unsigned int)
719 CYFromFFI_(int, int)
720 CYFromFFI_(ulonglong, unsigned long long)
721 CYFromFFI_(longlong, long long)
722 CYFromFFI_(float, float)
723 CYFromFFI_(double, double)
724
725 case sig::array_P:
726 if (void *pointer = data)
727 return CYMakePointer(context, pointer, type->data.data.size, type->data.data.type, NULL, owner);
728 else goto null;
729
730 case sig::pointer_P:
731 if (void *pointer = *reinterpret_cast<void **>(data))
732 return CYMakePointer(context, pointer, _not(size_t), type->data.data.type, NULL, owner);
733 else goto null;
734
735 case sig::string_P:
736 if (char *utf8 = *reinterpret_cast<char **>(data))
737 return CYCastJSValue(context, utf8);
738 else goto null;
739
740 case sig::struct_P:
741 return CYMakeStruct(context, data, type, ffi, owner);
742 case sig::void_P:
743 return CYJSUndefined(context);
744
745 null:
746 return CYJSNull(context);
747 default:
748 for (CYHook *hook : GetHooks())
749 if (hook->FromFFI != NULL)
750 if (JSValueRef value = (*hook->FromFFI)(context, type, ffi, data, initialize, owner))
751 return value;
752
753 CYThrow("unimplemented signature code: '%c''\n", type->primitive);
754 }
755 }
756
757 void CYExecuteClosure(ffi_cif *cif, void *result, void **arguments, void *arg) {
758 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
759
760 JSContextRef context(internal->context_);
761
762 size_t count(internal->cif_.nargs);
763 JSValueRef values[count];
764
765 for (size_t index(0); index != count; ++index)
766 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
767
768 JSValueRef value(internal->adapter_(context, count, values, internal->function_));
769 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
770 }
771
772 static JSValueRef FunctionAdapter_(JSContextRef context, size_t count, JSValueRef values[], JSObjectRef function) {
773 return CYCallAsFunction(context, function, NULL, count, values);
774 }
775
776 Closure_privateData *CYMakeFunctor_(JSContextRef context, JSObjectRef function, const sig::Signature &signature, JSValueRef (*adapter)(JSContextRef, size_t, JSValueRef[], JSObjectRef)) {
777 // XXX: in case of exceptions this will leak
778 // XXX: in point of fact, this may /need/ to leak :(
779 Closure_privateData *internal(new Closure_privateData(context, function, adapter, signature));
780
781 #if defined(__APPLE__) && (defined(__arm__) || defined(__arm64__))
782 void *executable;
783 ffi_closure *writable(reinterpret_cast<ffi_closure *>(ffi_closure_alloc(sizeof(ffi_closure), &executable)));
784
785 ffi_status status(ffi_prep_closure_loc(writable, &internal->cif_, &CYExecuteClosure, internal, executable));
786 _assert(status == FFI_OK);
787
788 internal->value_ = executable;
789 #else
790 ffi_closure *closure((ffi_closure *) _syscall(mmap(
791 NULL, sizeof(ffi_closure),
792 PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE,
793 -1, 0
794 )));
795
796 ffi_status status(ffi_prep_closure(closure, &internal->cif_, &CYExecuteClosure, internal));
797 _assert(status == FFI_OK);
798
799 _syscall(mprotect(closure, sizeof(*closure), PROT_READ | PROT_EXEC));
800
801 internal->value_ = closure;
802 #endif
803
804 return internal;
805 }
806
807 static JSObjectRef CYMakeFunctor(JSContextRef context, JSObjectRef function, const sig::Signature &signature) {
808 Closure_privateData *internal(CYMakeFunctor_(context, function, signature, &FunctionAdapter_));
809 JSObjectRef object(JSObjectMake(context, Functor_, internal));
810 // XXX: see above notes about needing to leak
811 JSValueProtect(CYGetJSContext(context), object);
812 return object;
813 }
814
815 JSValueRef CYGetCachedValue(JSContextRef context, JSStringRef name) {
816 return CYGetProperty(context, CYCastJSObject(context, CYGetProperty(context, CYGetGlobalObject(context), cy_s)), name);
817 }
818
819 JSObjectRef CYGetCachedObject(JSContextRef context, JSStringRef name) {
820 return CYCastJSObject(context, CYGetCachedValue(context, name));
821 }
822
823 static JSObjectRef CYMakeFunctor(JSContextRef context, JSValueRef value, const sig::Signature &signature) {
824 JSObjectRef Function(CYGetCachedObject(context, CYJSString("Function")));
825
826 bool function(_jsccall(JSValueIsInstanceOfConstructor, context, value, Function));
827 if (function) {
828 JSObjectRef function(CYCastJSObject(context, value));
829 return CYMakeFunctor(context, function, signature);
830 } else {
831 void (*function)()(CYCastPointer<void (*)()>(context, value));
832 return CYMakeFunctor(context, function, signature);
833 }
834 }
835
836 static bool Index_(CYPool &pool, JSContextRef context, Struct_privateData *internal, JSStringRef property, ssize_t &index, uint8_t *&base) {
837 Type_privateData *typical(internal->type_);
838 sig::Type *type(typical->type_);
839 if (type == NULL)
840 return false;
841
842 const char *name(CYPoolCString(pool, context, property));
843 size_t length(strlen(name));
844 double number(CYCastDouble(name, length));
845
846 size_t count(type->data.signature.count);
847
848 if (std::isnan(number)) {
849 if (property == NULL)
850 return false;
851
852 sig::Element *elements(type->data.signature.elements);
853
854 for (size_t local(0); local != count; ++local) {
855 sig::Element *element(&elements[local]);
856 if (element->name != NULL && strcmp(name, element->name) == 0) {
857 index = local;
858 goto base;
859 }
860 }
861
862 return false;
863 } else {
864 index = static_cast<ssize_t>(number);
865 if (index != number || index < 0 || static_cast<size_t>(index) >= count)
866 return false;
867 }
868
869 base:
870 ffi_type **elements(typical->GetFFI()->elements);
871
872 base = reinterpret_cast<uint8_t *>(internal->value_);
873 for (ssize_t local(0); local != index; ++local)
874 base += elements[local]->size;
875
876 return true;
877 }
878
879 static JSValueRef Pointer_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
880 CYPool pool;
881 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
882
883 if (JSStringIsEqual(property, length_s))
884 return internal->length_ == _not(size_t) ? CYJSUndefined(context) : CYCastJSValue(context, internal->length_);
885
886 Type_privateData *typical(internal->type_);
887 if (typical->type_ == NULL)
888 return NULL;
889 sig::Type &type(*typical->type_);
890
891 ssize_t offset;
892 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
893 offset = 0;
894 else if (!CYGetOffset(pool, context, property, offset))
895 return NULL;
896
897 if (type.primitive == sig::function_P)
898 return CYMakeFunctor(context, reinterpret_cast<void (*)()>(internal->value_), type.data.signature);
899
900 ffi_type *ffi(typical->GetFFI());
901
902 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
903 base += ffi->size * offset;
904
905 JSObjectRef owner(internal->GetOwner() ?: object);
906 return CYFromFFI(context, &type, ffi, base, false, owner);
907 } CYCatch(NULL) }
908
909 static bool Pointer_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
910 CYPool pool;
911 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
912 Type_privateData *typical(internal->type_);
913
914 if (typical->type_ == NULL)
915 return false;
916
917 ssize_t offset;
918 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
919 offset = 0;
920 else if (!CYGetOffset(pool, context, property, offset))
921 return false;
922
923 ffi_type *ffi(typical->GetFFI());
924
925 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
926 base += ffi->size * offset;
927
928 CYPoolFFI(NULL, context, typical->type_, ffi, base, value);
929 return true;
930 } CYCatch(false) }
931
932 static JSValueRef Struct_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
933 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(_this)));
934 Type_privateData *typical(internal->type_);
935 return CYMakePointer(context, internal->value_, _not(size_t), typical->type_, typical->ffi_, _this);
936 } CYCatch(NULL) }
937
938 static JSValueRef Struct_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
939 CYPool pool;
940 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
941 Type_privateData *typical(internal->type_);
942
943 ssize_t index;
944 uint8_t *base;
945
946 if (!Index_(pool, context, internal, property, index, base))
947 return NULL;
948
949 JSObjectRef owner(internal->GetOwner() ?: object);
950
951 return CYFromFFI(context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, false, owner);
952 } CYCatch(NULL) }
953
954 static bool Struct_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
955 CYPool pool;
956 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
957 Type_privateData *typical(internal->type_);
958
959 ssize_t index;
960 uint8_t *base;
961
962 if (!Index_(pool, context, internal, property, index, base))
963 return false;
964
965 CYPoolFFI(NULL, context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, value);
966 return true;
967 } CYCatch(false) }
968
969 static void Struct_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
970 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
971 Type_privateData *typical(internal->type_);
972 sig::Type *type(typical->type_);
973
974 if (type == NULL)
975 return;
976
977 size_t count(type->data.signature.count);
978 sig::Element *elements(type->data.signature.elements);
979
980 char number[32];
981
982 for (size_t index(0); index != count; ++index) {
983 const char *name;
984 name = elements[index].name;
985
986 if (name == NULL) {
987 sprintf(number, "%zu", index);
988 name = number;
989 }
990
991 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
992 }
993 }
994
995 void CYCallFunction(CYPool &pool, JSContextRef context, ffi_cif *cif, void (*function)(), void *value, void **values) {
996 ffi_call(cif, function, value, values);
997 }
998
999 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)()) {
1000 if (setups + count != signature->count - 1)
1001 throw CYJSError(context, "incorrect number of arguments to ffi function");
1002
1003 size_t size(setups + count);
1004 void *values[size];
1005 memcpy(values, setup, sizeof(void *) * setups);
1006
1007 for (size_t index(setups); index != size; ++index) {
1008 sig::Element *element(&signature->elements[index + 1]);
1009 ffi_type *ffi(cif->arg_types[index]);
1010 // XXX: alignment?
1011 values[index] = new(pool) uint8_t[ffi->size];
1012 CYPoolFFI(&pool, context, element->type, ffi, values[index], arguments[index - setups]);
1013 }
1014
1015 uint8_t value[cif->rtype->size];
1016
1017 void (*call)(CYPool &, JSContextRef, ffi_cif *, void (*)(), void *, void **) = &CYCallFunction;
1018 // XXX: this only supports one hook, but it is a bad idea anyway
1019 for (CYHook *hook : GetHooks())
1020 if (hook->CallFunction != NULL)
1021 call = hook->CallFunction;
1022
1023 call(pool, context, cif, function, value, values);
1024 return CYFromFFI(context, signature->elements[0].type, cif->rtype, value, initialize);
1025 }
1026
1027 static JSValueRef Functor_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1028 CYPool pool;
1029 cy::Functor *internal(reinterpret_cast<cy::Functor *>(JSObjectGetPrivate(object)));
1030 return CYCallFunction(pool, context, 0, NULL, count, arguments, false, &internal->signature_, &internal->cif_, internal->GetValue());
1031 } CYCatch(NULL) }
1032
1033 JSObjectRef CYMakeType(JSContextRef context, const char *encoding) {
1034 Type_privateData *internal(new Type_privateData(encoding));
1035 return JSObjectMake(context, Type_privateData::Class_, internal);
1036 }
1037
1038 JSObjectRef CYMakeType(JSContextRef context, sig::Type *type) {
1039 Type_privateData *internal(new Type_privateData(type));
1040 return JSObjectMake(context, Type_privateData::Class_, internal);
1041 }
1042
1043 JSObjectRef CYMakeType(JSContextRef context, sig::Signature *signature) {
1044 CYPool pool;
1045
1046 sig::Type type;
1047 type.name = NULL;
1048 type.flags = 0;
1049
1050 type.primitive = sig::function_P;
1051 sig::Copy(pool, type.data.signature, *signature);
1052
1053 return CYMakeType(context, &type);
1054 }
1055
1056 static bool All_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
1057 JSObjectRef global(CYGetGlobalObject(context));
1058 JSObjectRef cycript(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Cycript"))));
1059 JSObjectRef alls(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("alls"))));
1060
1061 for (size_t i(0), count(CYArrayLength(context, alls)); i != count; ++i)
1062 if (JSObjectRef space = CYCastJSObject(context, CYArrayGet(context, alls, count - i - 1)))
1063 if (CYHasProperty(context, space, property))
1064 return true;
1065
1066 CYPool pool;
1067 CYUTF8String name(CYPoolUTF8String(pool, context, property));
1068
1069 size_t length(name.size);
1070 char keyed[length + 2];
1071 memcpy(keyed + 1, name.data, length + 1);
1072
1073 static const char *modes = "0124";
1074 for (size_t i(0); i != 4; ++i) {
1075 keyed[0] = modes[i];
1076 if (CYBridgeHash(keyed, length + 1) != NULL)
1077 return true;
1078 }
1079
1080 return false;
1081 }
1082
1083 static JSValueRef All_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1084 JSObjectRef global(CYGetGlobalObject(context));
1085 JSObjectRef cycript(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Cycript"))));
1086 JSObjectRef alls(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("alls"))));
1087
1088 for (size_t i(0), count(CYArrayLength(context, alls)); i != count; ++i)
1089 if (JSObjectRef space = CYCastJSObject(context, CYArrayGet(context, alls, count - i - 1)))
1090 if (JSValueRef value = CYGetProperty(context, space, property))
1091 if (!JSValueIsUndefined(context, value))
1092 return value;
1093
1094 CYPool pool;
1095 CYUTF8String name(CYPoolUTF8String(pool, context, property));
1096
1097 size_t length(name.size);
1098 char keyed[length + 2];
1099 memcpy(keyed + 1, name.data, length + 1);
1100
1101 static const char *modes = "0124";
1102 for (size_t i(0); i != 4; ++i) {
1103 char mode(modes[i]);
1104 keyed[0] = mode;
1105
1106 if (CYBridgeEntry *entry = CYBridgeHash(keyed, length + 1))
1107 switch (mode) {
1108 case '0':
1109 return JSEvaluateScript(CYGetJSContext(context), CYJSString(entry->value_), NULL, NULL, 0, NULL);
1110
1111 case '1':
1112 return CYMakeFunctor(context, name.data, entry->value_, &entry->cache_);
1113
1114 case '2':
1115 if (void *symbol = CYCastSymbol(name.data)) {
1116 // XXX: this is horrendously inefficient
1117 sig::Signature signature;
1118 sig::Parse(pool, &signature, entry->value_, &Structor_);
1119 ffi_cif cif;
1120 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
1121 return CYFromFFI(context, signature.elements[0].type, cif.rtype, symbol);
1122 } else return NULL;
1123
1124 // XXX: implement case 3
1125 case '4':
1126 return CYMakeType(context, entry->value_);
1127 }
1128 }
1129
1130 return NULL;
1131 } CYCatch(NULL) }
1132
1133 static void All_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1134 JSObjectRef global(CYGetGlobalObject(context));
1135 JSObjectRef cycript(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Cycript"))));
1136 JSObjectRef alls(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("alls"))));
1137
1138 for (size_t i(0), count(CYArrayLength(context, alls)); i != count; ++i)
1139 if (JSObjectRef space = CYCastJSObject(context, CYArrayGet(context, alls, count - i - 1))) {
1140 JSPropertyNameArrayRef subset(JSObjectCopyPropertyNames(context, space));
1141 for (size_t index(0), count(JSPropertyNameArrayGetCount(subset)); index != count; ++index)
1142 JSPropertyNameAccumulatorAddName(names, JSPropertyNameArrayGetNameAtIndex(subset, index));
1143 JSPropertyNameArrayRelease(subset);
1144 }
1145 }
1146
1147 static JSObjectRef Pointer_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 Pointer constructor");
1150
1151 CYPool pool;
1152
1153 void *value(CYCastPointer<void *>(context, arguments[0]));
1154 const char *type(CYPoolCString(pool, context, arguments[1]));
1155
1156 sig::Signature signature;
1157 sig::Parse(pool, &signature, type, &Structor_);
1158
1159 return CYMakePointer(context, value, _not(size_t), signature.elements[0].type, NULL, NULL);
1160 } CYCatch(NULL) }
1161
1162 static JSObjectRef Type_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1163 CYPool pool;
1164
1165 if (false) {
1166 } else if (count == 1) {
1167 const char *type(CYPoolCString(pool, context, arguments[0]));
1168 return CYMakeType(context, type);
1169 } else if (count == 2) {
1170 JSObjectRef types(CYCastJSObject(context, arguments[0]));
1171 size_t count(CYArrayLength(context, types));
1172
1173 JSObjectRef names(CYCastJSObject(context, arguments[1]));
1174
1175 sig::Type type;
1176 type.name = NULL;
1177 type.flags = 0;
1178
1179 type.primitive = sig::struct_P;
1180 type.data.signature.elements = new(pool) sig::Element[count];
1181 type.data.signature.count = count;
1182
1183 for (size_t i(0); i != count; ++i) {
1184 sig::Element &element(type.data.signature.elements[i]);
1185 element.offset = _not(size_t);
1186
1187 JSValueRef name(CYArrayGet(context, names, i));
1188 if (JSValueIsUndefined(context, name))
1189 element.name = NULL;
1190 else
1191 element.name = CYPoolCString(pool, context, name);
1192
1193 JSObjectRef object(CYCastJSObject(context, CYArrayGet(context, types, i)));
1194 _assert(JSValueIsObjectOfClass(context, object, Type_privateData::Class_));
1195 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
1196 element.type = internal->type_;
1197 }
1198
1199 return CYMakeType(context, &type);
1200 } else {
1201 throw CYJSError(context, "incorrect number of arguments to Type constructor");
1202 }
1203 } CYCatch(NULL) }
1204
1205 static JSValueRef Type_callAsFunction_$With(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], sig::Primitive primitive, JSValueRef *exception) { CYTry {
1206 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
1207
1208 CYPool pool;
1209
1210 sig::Type type;
1211 type.name = NULL;
1212 type.flags = 0;
1213
1214 type.primitive = primitive;
1215 type.data.signature.elements = new(pool) sig::Element[1 + count];
1216 type.data.signature.count = 1 + count;
1217
1218 type.data.signature.elements[0].name = NULL;
1219 type.data.signature.elements[0].type = internal->type_;
1220 type.data.signature.elements[0].offset = _not(size_t);
1221
1222 for (size_t i(0); i != count; ++i) {
1223 sig::Element &element(type.data.signature.elements[i + 1]);
1224 element.name = NULL;
1225 element.offset = _not(size_t);
1226
1227 JSObjectRef object(CYCastJSObject(context, arguments[i]));
1228 _assert(JSValueIsObjectOfClass(context, object, Type_privateData::Class_));
1229 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
1230
1231 element.type = internal->type_;
1232 }
1233
1234 return CYMakeType(context, &type);
1235 } CYCatch(NULL) }
1236
1237 static JSValueRef Type_callAsFunction_arrayOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1238 if (count != 1)
1239 throw CYJSError(context, "incorrect number of arguments to Type.arrayOf");
1240 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
1241
1242 CYPool pool;
1243 size_t index(CYGetIndex(pool, context, CYJSString(context, arguments[0])));
1244 if (index == _not(size_t))
1245 throw CYJSError(context, "invalid array size used with Type.arrayOf");
1246
1247 sig::Type type;
1248 type.name = NULL;
1249 type.flags = 0;
1250
1251 type.primitive = sig::array_P;
1252 type.data.data.type = internal->type_;
1253 type.data.data.size = index;
1254
1255 return CYMakeType(context, &type);
1256 } CYCatch(NULL) }
1257
1258 static JSValueRef Type_callAsFunction_blockWith(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1259 return Type_callAsFunction_$With(context, object, _this, count, arguments, sig::block_P, exception);
1260 }
1261
1262 static JSValueRef Type_callAsFunction_constant(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1263 if (count != 0)
1264 throw CYJSError(context, "incorrect number of arguments to Type.constant");
1265 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
1266
1267 sig::Type type(*internal->type_);
1268 type.flags |= JOC_TYPE_CONST;
1269 return CYMakeType(context, &type);
1270 } CYCatch(NULL) }
1271
1272 static JSValueRef Type_callAsFunction_long(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1273 if (count != 0)
1274 throw CYJSError(context, "incorrect number of arguments to Type.long");
1275 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
1276
1277 sig::Type type(*internal->type_);
1278
1279 switch (type.primitive) {
1280 case sig::short_P: type.primitive = sig::int_P; break;
1281 case sig::int_P: type.primitive = sig::long_P; break;
1282 case sig::long_P: type.primitive = sig::longlong_P; break;
1283 default: throw CYJSError(context, "invalid type argument to Type.long");
1284 }
1285
1286 return CYMakeType(context, &type);
1287 } CYCatch(NULL) }
1288
1289 static JSValueRef Type_callAsFunction_short(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1290 if (count != 0)
1291 throw CYJSError(context, "incorrect number of arguments to Type.short");
1292 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
1293
1294 sig::Type type(*internal->type_);
1295
1296 switch (type.primitive) {
1297 case sig::int_P: type.primitive = sig::short_P; break;
1298 case sig::long_P: type.primitive = sig::int_P; break;
1299 case sig::longlong_P: type.primitive = sig::long_P; break;
1300 default: throw CYJSError(context, "invalid type argument to Type.short");
1301 }
1302
1303 return CYMakeType(context, &type);
1304 } CYCatch(NULL) }
1305
1306 static JSValueRef Type_callAsFunction_signed(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1307 if (count != 0)
1308 throw CYJSError(context, "incorrect number of arguments to Type.signed");
1309 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
1310
1311 sig::Type type(*internal->type_);
1312
1313 switch (type.primitive) {
1314 case sig::char_P: case sig::uchar_P: type.primitive = sig::char_P; break;
1315 case sig::short_P: case sig::ushort_P: type.primitive = sig::short_P; break;
1316 case sig::int_P: case sig::uint_P: type.primitive = sig::int_P; break;
1317 case sig::long_P: case sig::ulong_P: type.primitive = sig::long_P; break;
1318 case sig::longlong_P: case sig::ulonglong_P: type.primitive = sig::longlong_P; break;
1319 default: throw CYJSError(context, "invalid type argument to Type.signed");
1320 }
1321
1322 return CYMakeType(context, &type);
1323 } CYCatch(NULL) }
1324
1325 static JSValueRef Type_callAsFunction_unsigned(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1326 if (count != 0)
1327 throw CYJSError(context, "incorrect number of arguments to Type.unsigned");
1328 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
1329
1330 sig::Type type(*internal->type_);
1331
1332 switch (type.primitive) {
1333 case sig::char_P: case sig::uchar_P: type.primitive = sig::uchar_P; break;
1334 case sig::short_P: case sig::ushort_P: type.primitive = sig::ushort_P; break;
1335 case sig::int_P: case sig::uint_P: type.primitive = sig::uint_P; break;
1336 case sig::long_P: case sig::ulong_P: type.primitive = sig::ulong_P; break;
1337 case sig::longlong_P: case sig::ulonglong_P: type.primitive = sig::ulonglong_P; break;
1338 default: throw CYJSError(context, "invalid type argument to Type.unsigned");
1339 }
1340
1341 return CYMakeType(context, &type);
1342 } CYCatch(NULL) }
1343
1344 static JSValueRef Type_callAsFunction_functionWith(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1345 return Type_callAsFunction_$With(context, object, _this, count, arguments, sig::function_P, exception);
1346 }
1347
1348 static JSValueRef Type_callAsFunction_pointerTo(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1349 if (count != 0)
1350 throw CYJSError(context, "incorrect number of arguments to Type.pointerTo");
1351 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
1352
1353 sig::Type type;
1354 type.name = NULL;
1355
1356 if (internal->type_->primitive == sig::char_P) {
1357 type.flags = internal->type_->flags;
1358 type.primitive = sig::string_P;
1359 type.data.data.type = NULL;
1360 type.data.data.size = 0;
1361 } else {
1362 type.flags = 0;
1363 type.primitive = sig::pointer_P;
1364 type.data.data.type = internal->type_;
1365 type.data.data.size = 0;
1366 }
1367
1368 return CYMakeType(context, &type);
1369 } CYCatch(NULL) }
1370
1371 static JSValueRef Type_callAsFunction_withName(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1372 if (count != 1)
1373 throw CYJSError(context, "incorrect number of arguments to Type.withName");
1374 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
1375
1376 CYPool pool;
1377 const char *name(CYPoolCString(pool, context, arguments[0]));
1378
1379 sig::Type type(*internal->type_);
1380 type.name = name;
1381 return CYMakeType(context, &type);
1382 } CYCatch(NULL) }
1383
1384 static JSValueRef Type_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1385 if (count != 1)
1386 throw CYJSError(context, "incorrect number of arguments to type cast function");
1387 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
1388
1389 if (internal->type_->primitive == sig::function_P)
1390 return CYMakeFunctor(context, arguments[0], internal->type_->data.signature);
1391
1392 sig::Type *type(internal->type_);
1393 ffi_type *ffi(internal->GetFFI());
1394 // XXX: alignment?
1395 uint8_t value[ffi->size];
1396 CYPool pool;
1397 CYPoolFFI(&pool, context, type, ffi, value, arguments[0]);
1398 return CYFromFFI(context, type, ffi, value);
1399 } CYCatch(NULL) }
1400
1401 static JSObjectRef Type_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1402 if (count != 0)
1403 throw CYJSError(context, "incorrect number of arguments to Type allocator");
1404 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
1405
1406 sig::Type *type(internal->type_);
1407 size_t length;
1408
1409 if (type->primitive != sig::array_P)
1410 length = _not(size_t);
1411 else {
1412 length = type->data.data.size;
1413 type = type->data.data.type;
1414 }
1415
1416 void *value(calloc(1, internal->GetFFI()->size));
1417 return CYMakePointer(context, value, length, type, NULL, NULL);
1418 } CYCatch(NULL) }
1419
1420 static JSObjectRef Functor_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1421 if (count != 2)
1422 throw CYJSError(context, "incorrect number of arguments to Functor constructor");
1423 CYPool pool;
1424 const char *encoding(CYPoolCString(pool, context, arguments[1]));
1425 sig::Signature signature;
1426 sig::Parse(pool, &signature, encoding, &Structor_);
1427 return CYMakeFunctor(context, arguments[0], signature);
1428 } CYCatch(NULL) }
1429
1430 static JSValueRef CYValue_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1431 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
1432 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
1433 } CYCatch(NULL) }
1434
1435 static JSValueRef CYValue_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1436 return CYValue_callAsFunction_valueOf(context, object, _this, count, arguments, exception);
1437 }
1438
1439 static JSValueRef CYValue_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1440 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
1441 char string[32];
1442 sprintf(string, "%p", internal->value_);
1443 return CYCastJSValue(context, string);
1444 } CYCatch(NULL) }
1445
1446 static JSValueRef Pointer_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1447 std::set<void *> *objects(CYCastObjects(context, _this, count, arguments));
1448
1449 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(_this)));
1450 if (internal->length_ != _not(size_t)) {
1451 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1452 JSObjectRef toCYON(CYCastJSObject(context, CYGetProperty(context, Array, toCYON_s)));
1453 return CYCallAsFunction(context, toCYON, _this, count, arguments);
1454 } else if (internal->type_->type_ == NULL) pointer: {
1455 char string[32];
1456 sprintf(string, "%p", internal->value_);
1457 return CYCastJSValue(context, string);
1458 } try {
1459 JSValueRef value(CYGetProperty(context, _this, cyi_s));
1460 if (JSValueIsUndefined(context, value))
1461 goto pointer;
1462 CYPool pool;
1463 return CYCastJSValue(context, pool.strcat("&", CYPoolCCYON(pool, context, value, objects), NULL));
1464 } catch (const CYException &e) {
1465 goto pointer;
1466 }
1467 } CYCatch(NULL) }
1468
1469 static JSValueRef Pointer_getProperty_type(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1470 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
1471 return CYMakeType(context, internal->type_->type_);
1472 } CYCatch(NULL) }
1473
1474 static JSValueRef Functor_getProperty_type(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1475 cy::Functor *internal(reinterpret_cast<cy::Functor *>(JSObjectGetPrivate(object)));
1476 return CYMakeType(context, &internal->signature_);
1477 } CYCatch(NULL) }
1478
1479 static JSValueRef Type_getProperty_alignment(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1480 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
1481 return CYCastJSValue(context, internal->GetFFI()->alignment);
1482 } CYCatch(NULL) }
1483
1484 static JSValueRef Type_getProperty_name(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1485 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
1486 return CYCastJSValue(context, internal->type_->name);
1487 } CYCatch(NULL) }
1488
1489 static JSValueRef Type_getProperty_size(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1490 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
1491 return CYCastJSValue(context, internal->GetFFI()->size);
1492 } CYCatch(NULL) }
1493
1494 static JSValueRef Type_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1495 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
1496 CYPool pool;
1497 const char *type(sig::Unparse(pool, internal->type_));
1498 return CYCastJSValue(context, CYJSString(type));
1499 } CYCatch(NULL) }
1500
1501 static JSValueRef Type_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1502 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
1503 CYLocalPool pool;
1504 std::stringbuf out;
1505 CYOptions options;
1506 CYOutput output(out, options);
1507 (new(pool) CYTypeExpression(Decode(pool, internal->type_)))->Output(output, CYNoFlags);
1508 return CYCastJSValue(context, CYJSString(out.str().c_str()));
1509 } CYCatch(NULL) }
1510
1511 static JSValueRef Type_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1512 return Type_callAsFunction_toString(context, object, _this, count, arguments, exception);
1513 }
1514
1515 static JSStaticFunction Pointer_staticFunctions[4] = {
1516 {"toCYON", &Pointer_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1517 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1518 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1519 {NULL, NULL, 0}
1520 };
1521
1522 static JSStaticValue Pointer_staticValues[2] = {
1523 {"type", &Pointer_getProperty_type, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1524 {NULL, NULL, NULL, 0}
1525 };
1526
1527 static JSStaticFunction Struct_staticFunctions[2] = {
1528 {"$cya", &Struct_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1529 {NULL, NULL, 0}
1530 };
1531
1532 static JSStaticFunction Functor_staticFunctions[4] = {
1533 {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1534 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1535 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1536 {NULL, NULL, 0}
1537 };
1538
1539 namespace cy {
1540 JSStaticFunction const * const Functor::StaticFunctions = Functor_staticFunctions;
1541 }
1542
1543 static JSStaticValue Functor_staticValues[2] = {
1544 {"type", &Functor_getProperty_type, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1545 {NULL, NULL, NULL, 0}
1546 };
1547
1548 namespace cy {
1549 JSStaticValue const * const Functor::StaticValues = Functor_staticValues;
1550 }
1551
1552 static JSStaticValue Type_staticValues[4] = {
1553 {"alignment", &Type_getProperty_alignment, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1554 {"name", &Type_getProperty_name, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1555 {"size", &Type_getProperty_size, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1556 {NULL, NULL, NULL, 0}
1557 };
1558
1559 static JSStaticFunction Type_staticFunctions[14] = {
1560 {"arrayOf", &Type_callAsFunction_arrayOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1561 {"blockWith", &Type_callAsFunction_blockWith, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1562 {"constant", &Type_callAsFunction_constant, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1563 {"functionWith", &Type_callAsFunction_functionWith, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1564 {"long", &Type_callAsFunction_long, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1565 {"pointerTo", &Type_callAsFunction_pointerTo, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1566 {"short", &Type_callAsFunction_short, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1567 {"signed", &Type_callAsFunction_signed, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1568 {"withName", &Type_callAsFunction_withName, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1569 {"toCYON", &Type_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1570 {"toJSON", &Type_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1571 {"toString", &Type_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1572 {"unsigned", &Type_callAsFunction_unsigned, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1573 {NULL, NULL, 0}
1574 };
1575
1576 static JSObjectRef (*JSObjectMakeArray$)(JSContextRef, size_t, const JSValueRef[], JSValueRef *);
1577
1578 _visible void CYSetArgs(int argc, const char *argv[]) {
1579 JSContextRef context(CYGetJSContext());
1580 JSValueRef args[argc];
1581 for (int i(0); i != argc; ++i)
1582 args[i] = CYCastJSValue(context, argv[i]);
1583
1584 JSObjectRef array;
1585 if (JSObjectMakeArray$ != NULL)
1586 array = _jsccall(*JSObjectMakeArray$, context, argc, args);
1587 else {
1588 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array")));
1589 JSValueRef value(CYCallAsFunction(context, Array, NULL, argc, args));
1590 array = CYCastJSObject(context, value);
1591 }
1592
1593 JSObjectRef System(CYGetCachedObject(context, CYJSString("System")));
1594 CYSetProperty(context, System, CYJSString("args"), array);
1595 }
1596
1597 JSObjectRef CYGetGlobalObject(JSContextRef context) {
1598 return JSContextGetGlobalObject(context);
1599 }
1600
1601 // XXX: this is neither exceptin safe nor even terribly sane
1602 class ExecutionHandle {
1603 private:
1604 JSContextRef context_;
1605 std::vector<void *> handles_;
1606
1607 public:
1608 ExecutionHandle(JSContextRef context) :
1609 context_(context)
1610 {
1611 handles_.resize(GetHooks().size());
1612 for (size_t i(0); i != GetHooks().size(); ++i) {
1613 CYHook *hook(GetHooks()[i]);
1614 if (hook->ExecuteStart != NULL)
1615 handles_[i] = (*hook->ExecuteStart)(context_);
1616 else
1617 handles_[i] = NULL;
1618 }
1619 }
1620
1621 ~ExecutionHandle() {
1622 for (size_t i(GetHooks().size()); i != 0; --i) {
1623 CYHook *hook(GetHooks()[i-1]);
1624 if (hook->ExecuteEnd != NULL)
1625 (*hook->ExecuteEnd)(context_, handles_[i-1]);
1626 }
1627 }
1628 };
1629
1630 static volatile bool cancel_;
1631
1632 static bool CYShouldTerminate(JSContextRef context, void *arg) {
1633 return cancel_;
1634 }
1635
1636 _visible const char *CYExecute(JSContextRef context, CYPool &pool, CYUTF8String code) {
1637 ExecutionHandle handle(context);
1638
1639 cancel_ = false;
1640 if (&JSContextGroupSetExecutionTimeLimit != NULL)
1641 JSContextGroupSetExecutionTimeLimit(JSContextGetGroup(context), 0.5, &CYShouldTerminate, NULL);
1642
1643 try {
1644 JSValueRef result(_jsccall(JSEvaluateScript, context, CYJSString(code), NULL, NULL, 0));
1645 if (JSValueIsUndefined(context, result))
1646 return NULL;
1647
1648 std::set<void *> objects;
1649 const char *json(_jsccall(CYPoolCCYON, pool, context, result, objects));
1650 CYSetProperty(context, CYGetGlobalObject(context), Result_, result);
1651
1652 return json;
1653 } catch (const CYException &error) {
1654 return pool.strcat("throw ", error.PoolCString(pool), NULL);
1655 }
1656 }
1657
1658 _visible void CYCancel() {
1659 cancel_ = true;
1660 }
1661
1662 static bool initialized_ = false;
1663
1664 void CYInitializeDynamic() {
1665 if (!initialized_)
1666 initialized_ = true;
1667 else return;
1668
1669 JSObjectMakeArray$ = reinterpret_cast<JSObjectRef (*)(JSContextRef, size_t, const JSValueRef[], JSValueRef *)>(dlsym(RTLD_DEFAULT, "JSObjectMakeArray"));
1670 JSSynchronousGarbageCollectForDebugging$ = reinterpret_cast<void (*)(JSContextRef)>(dlsym(RTLD_DEFAULT, "JSSynchronousGarbageCollectForDebugging"));
1671
1672 JSClassDefinition definition;
1673
1674 definition = kJSClassDefinitionEmpty;
1675 definition.className = "All";
1676 definition.hasProperty = &All_hasProperty;
1677 definition.getProperty = &All_getProperty;
1678 definition.getPropertyNames = &All_getPropertyNames;
1679 All_ = JSClassCreate(&definition);
1680
1681 definition = kJSClassDefinitionEmpty;
1682 definition.className = "Context";
1683 definition.finalize = &CYFinalize;
1684 Context_ = JSClassCreate(&definition);
1685
1686 definition = kJSClassDefinitionEmpty;
1687 definition.className = "Functor";
1688 definition.staticFunctions = cy::Functor::StaticFunctions;
1689 definition.staticValues = Functor_staticValues;
1690 definition.callAsFunction = &Functor_callAsFunction;
1691 definition.finalize = &CYFinalize;
1692 Functor_ = JSClassCreate(&definition);
1693
1694 definition = kJSClassDefinitionEmpty;
1695 definition.className = "Pointer";
1696 definition.staticFunctions = Pointer_staticFunctions;
1697 definition.staticValues = Pointer_staticValues;
1698 definition.getProperty = &Pointer_getProperty;
1699 definition.setProperty = &Pointer_setProperty;
1700 definition.finalize = &CYFinalize;
1701 Pointer_ = JSClassCreate(&definition);
1702
1703 definition = kJSClassDefinitionEmpty;
1704 definition.className = "Struct";
1705 definition.staticFunctions = Struct_staticFunctions;
1706 definition.getProperty = &Struct_getProperty;
1707 definition.setProperty = &Struct_setProperty;
1708 definition.getPropertyNames = &Struct_getPropertyNames;
1709 definition.finalize = &CYFinalize;
1710 Struct_ = JSClassCreate(&definition);
1711
1712 definition = kJSClassDefinitionEmpty;
1713 definition.className = "Type";
1714 definition.staticValues = Type_staticValues;
1715 definition.staticFunctions = Type_staticFunctions;
1716 definition.callAsFunction = &Type_callAsFunction;
1717 definition.callAsConstructor = &Type_callAsConstructor;
1718 definition.finalize = &CYFinalize;
1719 Type_privateData::Class_ = JSClassCreate(&definition);
1720
1721 definition = kJSClassDefinitionEmpty;
1722 definition.className = "Global";
1723 //definition.getProperty = &Global_getProperty;
1724 Global_ = JSClassCreate(&definition);
1725
1726 Array_s = JSStringCreateWithUTF8CString("Array");
1727 cy_s = JSStringCreateWithUTF8CString("$cy");
1728 cyi_s = JSStringCreateWithUTF8CString("$cyi");
1729 length_s = JSStringCreateWithUTF8CString("length");
1730 message_s = JSStringCreateWithUTF8CString("message");
1731 name_s = JSStringCreateWithUTF8CString("name");
1732 pop_s = JSStringCreateWithUTF8CString("pop");
1733 prototype_s = JSStringCreateWithUTF8CString("prototype");
1734 push_s = JSStringCreateWithUTF8CString("push");
1735 splice_s = JSStringCreateWithUTF8CString("splice");
1736 toCYON_s = JSStringCreateWithUTF8CString("toCYON");
1737 toJSON_s = JSStringCreateWithUTF8CString("toJSON");
1738 toPointer_s = JSStringCreateWithUTF8CString("toPointer");
1739 toString_s = JSStringCreateWithUTF8CString("toString");
1740 weak_s = JSStringCreateWithUTF8CString("weak");
1741
1742 Result_ = JSStringCreateWithUTF8CString("_");
1743
1744 for (CYHook *hook : GetHooks())
1745 if (hook->Initialize != NULL)
1746 (*hook->Initialize)();
1747 }
1748
1749 void CYThrow(JSContextRef context, JSValueRef value) {
1750 if (value != NULL)
1751 throw CYJSError(context, value);
1752 }
1753
1754 const char *CYJSError::PoolCString(CYPool &pool) const {
1755 std::set<void *> objects;
1756 // XXX: this used to be CYPoolCString
1757 return CYPoolCCYON(pool, context_, value_, objects);
1758 }
1759
1760 JSValueRef CYJSError::CastJSValue(JSContextRef context, const char *name) const {
1761 // XXX: what if the context is different? or the name? I dunno. ("epic" :/)
1762 return value_;
1763 }
1764
1765 JSValueRef CYCastJSError(JSContextRef context, const char *name, const char *message) {
1766 JSObjectRef Error(CYGetCachedObject(context, CYJSString(name)));
1767 JSValueRef arguments[1] = {CYCastJSValue(context, message)};
1768 return _jsccall(JSObjectCallAsConstructor, context, Error, 1, arguments);
1769 }
1770
1771 JSValueRef CYPoolError::CastJSValue(JSContextRef context, const char *name) const {
1772 return CYCastJSError(context, name, message_);
1773 }
1774
1775 CYJSError::CYJSError(JSContextRef context, const char *format, ...) {
1776 _assert(context != NULL);
1777
1778 CYPool pool;
1779
1780 va_list args;
1781 va_start(args, format);
1782 // XXX: there might be a beter way to think about this
1783 const char *message(pool.vsprintf(64, format, args));
1784 va_end(args);
1785
1786 value_ = CYCastJSError(context, "Error", message);
1787 }
1788
1789 JSGlobalContextRef CYGetJSContext(JSContextRef context) {
1790 return reinterpret_cast<Context *>(JSObjectGetPrivate(CYCastJSObject(context, CYGetProperty(context, CYGetGlobalObject(context), cy_s))))->context_;
1791 }
1792
1793 struct CYFile {
1794 void *data_;
1795 size_t size_;
1796
1797 CYFile(void *data, size_t size) :
1798 data_(data),
1799 size_(size)
1800 {
1801 }
1802 };
1803
1804 static void CYFileExit(void *data) {
1805 CYFile *file(reinterpret_cast<CYFile *>(data));
1806 _syscall(munmap(file->data_, file->size_));
1807 }
1808
1809 static void *CYPoolFile(CYPool &pool, const char *path, size_t *psize) {
1810 int fd(_syscall_(open(path, O_RDONLY), 1, ENOENT));
1811 if (fd == -1)
1812 return NULL;
1813
1814 struct stat stat;
1815 _syscall(fstat(fd, &stat));
1816 size_t size(stat.st_size);
1817
1818 *psize = size;
1819
1820 void *base;
1821 _syscall(base = mmap(NULL, size, PROT_READ, MAP_SHARED, fd, 0));
1822
1823 CYFile *file(new (pool) CYFile(base, size));
1824 pool.atexit(&CYFileExit, file);
1825
1826 _syscall(close(fd));
1827 return base;
1828 }
1829
1830 static CYUTF8String CYPoolFileUTF8String(CYPool &pool, const char *path) {
1831 CYUTF8String data;
1832 data.data = reinterpret_cast<char *>(CYPoolFile(pool, path, &data.size));
1833 return data;
1834 }
1835
1836 static const char *CYPoolLibraryPath(CYPool &pool) {
1837 Dl_info addr;
1838 _assert(dladdr(reinterpret_cast<void *>(&CYPoolLibraryPath), &addr) != 0);
1839 char *lib(pool.strdup(addr.dli_fname));
1840
1841 char *slash(strrchr(lib, '/'));
1842 _assert(slash != NULL);
1843 *slash = '\0';
1844
1845 return lib;
1846 }
1847
1848 static JSValueRef require(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1849 _assert(count == 1);
1850 CYPool pool;
1851
1852 const char *lib(CYPoolLibraryPath(pool));
1853
1854 CYJSString property("exports");
1855 JSObjectRef module;
1856
1857 const char *name(CYPoolCString(pool, context, arguments[0]));
1858 const char *path(pool.strcat(lib, "/cycript0.9/", name, ".cy", NULL));
1859
1860 CYJSString key(path);
1861 JSObjectRef modules(CYGetCachedObject(context, CYJSString("modules")));
1862 JSValueRef cache(CYGetProperty(context, modules, key));
1863
1864 if (!JSValueIsUndefined(context, cache))
1865 module = CYCastJSObject(context, cache);
1866 else {
1867 CYUTF8String code(CYPoolFileUTF8String(pool, path));
1868
1869 if (code.data == NULL) {
1870 if (strchr(name, '/') == NULL && (
1871 #ifdef __APPLE__
1872 dlopen(pool.strcat("/System/Library/Frameworks/", name, ".framework/", name, NULL), RTLD_LAZY | RTLD_GLOBAL) != NULL ||
1873 dlopen(pool.strcat("/System/Library/PrivateFrameworks/", name, ".framework/", name, NULL), RTLD_LAZY | RTLD_GLOBAL) != NULL ||
1874 #endif
1875 false))
1876 return CYJSUndefined(NULL);
1877
1878 CYThrow("Can't find module: %s", name);
1879 }
1880
1881 module = JSObjectMake(context, NULL, NULL);
1882 CYSetProperty(context, modules, key, module);
1883
1884 JSObjectRef exports(JSObjectMake(context, NULL, NULL));
1885 CYSetProperty(context, module, property, exports);
1886
1887 std::stringstream wrap;
1888 wrap << "(function (exports, require, module) { " << code << "\n});";
1889 code = CYPoolCode(pool, *wrap.rdbuf());
1890
1891 JSValueRef value(_jsccall(JSEvaluateScript, context, CYJSString(code), NULL, NULL, 0));
1892 JSObjectRef function(CYCastJSObject(context, value));
1893
1894 JSValueRef arguments[3] = { exports, JSObjectMakeFunctionWithCallback(context, CYJSString("require"), &require), module };
1895 CYCallAsFunction(context, function, NULL, 3, arguments);
1896 }
1897
1898 return CYGetProperty(context, module, property);
1899 } CYCatch(NULL) }
1900
1901 static bool CYRunScript(JSGlobalContextRef context, const char *path) {
1902 CYPool pool;
1903 CYUTF8String code(CYPoolFileUTF8String(pool, path));
1904 if (code.data == NULL)
1905 return false;
1906
1907 CYStream stream(code.data, code.data + code.size);
1908 code = CYPoolCode(pool, stream);
1909 _jsccall(JSEvaluateScript, context, CYJSString(code), NULL, NULL, 0);
1910 return true;
1911 }
1912
1913 extern "C" void CYDestroyWeak(JSWeakObjectMapRef weak, void *data) {
1914 }
1915
1916 extern "C" void CYSetupContext(JSGlobalContextRef context) {
1917 CYInitializeDynamic();
1918
1919 JSObjectRef global(CYGetGlobalObject(context));
1920
1921 JSObjectRef cy(JSObjectMake(context, Context_, new Context(context)));
1922 CYSetProperty(context, global, cy_s, cy, kJSPropertyAttributeDontEnum);
1923
1924 /* Cache Globals {{{ */
1925 JSObjectRef Array(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Array"))));
1926 CYSetProperty(context, cy, CYJSString("Array"), Array);
1927
1928 JSObjectRef Array_prototype(CYCastJSObject(context, CYGetProperty(context, Array, prototype_s)));
1929 CYSetProperty(context, cy, CYJSString("Array_prototype"), Array_prototype);
1930
1931 JSObjectRef Boolean(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Boolean"))));
1932 CYSetProperty(context, cy, CYJSString("Boolean"), Boolean);
1933
1934 JSObjectRef Boolean_prototype(CYCastJSObject(context, CYGetProperty(context, Boolean, prototype_s)));
1935 CYSetProperty(context, cy, CYJSString("Boolean_prototype"), Boolean_prototype);
1936
1937 JSObjectRef Error(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Error"))));
1938 CYSetProperty(context, cy, CYJSString("Error"), Error);
1939
1940 JSObjectRef Function(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Function"))));
1941 CYSetProperty(context, cy, CYJSString("Function"), Function);
1942
1943 JSObjectRef Function_prototype(CYCastJSObject(context, CYGetProperty(context, Function, prototype_s)));
1944 CYSetProperty(context, cy, CYJSString("Function_prototype"), Function_prototype);
1945
1946 JSObjectRef Number(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Number"))));
1947 CYSetProperty(context, cy, CYJSString("Number"), Number);
1948
1949 JSObjectRef Number_prototype(CYCastJSObject(context, CYGetProperty(context, Number, prototype_s)));
1950 CYSetProperty(context, cy, CYJSString("Number_prototype"), Number_prototype);
1951
1952 JSObjectRef Object(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Object"))));
1953 CYSetProperty(context, cy, CYJSString("Object"), Object);
1954
1955 JSObjectRef Object_prototype(CYCastJSObject(context, CYGetProperty(context, Object, prototype_s)));
1956 CYSetProperty(context, cy, CYJSString("Object_prototype"), Object_prototype);
1957
1958 JSObjectRef String(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("String"))));
1959 CYSetProperty(context, cy, CYJSString("String"), String);
1960
1961 JSObjectRef String_prototype(CYCastJSObject(context, CYGetProperty(context, String, prototype_s)));
1962 CYSetProperty(context, cy, CYJSString("String_prototype"), String_prototype);
1963
1964 JSObjectRef SyntaxError(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("SyntaxError"))));
1965 CYSetProperty(context, cy, CYJSString("SyntaxError"), SyntaxError);
1966 /* }}} */
1967
1968 CYSetProperty(context, Array_prototype, toCYON_s, &Array_callAsFunction_toCYON, kJSPropertyAttributeDontEnum);
1969 CYSetProperty(context, String_prototype, toCYON_s, &String_callAsFunction_toCYON, kJSPropertyAttributeDontEnum);
1970
1971 JSObjectRef cycript(JSObjectMake(context, NULL, NULL));
1972 CYSetProperty(context, global, CYJSString("Cycript"), cycript);
1973 CYSetProperty(context, cycript, CYJSString("compile"), &Cycript_compile_callAsFunction);
1974 CYSetProperty(context, cycript, CYJSString("gc"), &Cycript_gc_callAsFunction);
1975
1976 JSObjectRef Functor(JSObjectMakeConstructor(context, Functor_, &Functor_new));
1977 CYSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Functor, prototype_s)), Function_prototype);
1978 CYSetProperty(context, cycript, CYJSString("Functor"), Functor);
1979
1980 CYSetProperty(context, cycript, CYJSString("Pointer"), JSObjectMakeConstructor(context, Pointer_, &Pointer_new));
1981 CYSetProperty(context, cycript, CYJSString("Type"), JSObjectMakeConstructor(context, Type_privateData::Class_, &Type_new));
1982
1983 JSObjectRef modules(JSObjectMake(context, NULL, NULL));
1984 CYSetProperty(context, cy, CYJSString("modules"), modules);
1985
1986 JSObjectRef all(JSObjectMake(context, All_, NULL));
1987 CYSetProperty(context, cycript, CYJSString("all"), all);
1988
1989 JSObjectRef alls(_jsccall(JSObjectCallAsConstructor, context, Array, 0, NULL));
1990 CYSetProperty(context, cycript, CYJSString("alls"), alls);
1991
1992 if (true) {
1993 JSObjectRef last(NULL), curr(global);
1994
1995 goto next; for (JSValueRef next;;) {
1996 if (JSValueIsNull(context, next))
1997 break;
1998 last = curr;
1999 curr = CYCastJSObject(context, next);
2000 next:
2001 next = JSObjectGetPrototype(context, curr);
2002 }
2003
2004 CYSetPrototype(context, last, all);
2005 }
2006
2007 JSObjectRef System(JSObjectMake(context, NULL, NULL));
2008 CYSetProperty(context, cy, CYJSString("System"), System);
2009
2010 CYSetProperty(context, all, CYJSString("require"), &require, kJSPropertyAttributeDontEnum);
2011
2012 CYSetProperty(context, global, CYJSString("system"), System);
2013 CYSetProperty(context, System, CYJSString("args"), CYJSNull(context));
2014 //CYSetProperty(context, System, CYJSString("global"), global);
2015 CYSetProperty(context, System, CYJSString("print"), &System_print);
2016
2017 #ifdef __APPLE__
2018 if (&JSWeakObjectMapCreate != NULL) {
2019 JSWeakObjectMapRef weak(JSWeakObjectMapCreate(context, NULL, &CYDestroyWeak));
2020 CYSetProperty(context, cy, weak_s, CYCastJSValue(context, reinterpret_cast<uintptr_t>(weak)));
2021 }
2022 #endif
2023
2024 if (CYBridgeEntry *entry = CYBridgeHash("1dlerror", 8))
2025 entry->cache_ = new cy::Functor(entry->value_, reinterpret_cast<void (*)()>(&dlerror));
2026
2027 CYRunScript(context, "libcycript.cy");
2028
2029 for (CYHook *hook : GetHooks())
2030 if (hook->SetupContext != NULL)
2031 (*hook->SetupContext)(context);
2032
2033 CYArrayPush(context, alls, cycript);
2034 }
2035
2036 static JSGlobalContextRef context_;
2037
2038 _visible JSGlobalContextRef CYGetJSContext() {
2039 CYInitializeDynamic();
2040
2041 if (context_ == NULL) {
2042 context_ = JSGlobalContextCreate(Global_);
2043 CYSetupContext(context_);
2044 }
2045
2046 return context_;
2047 }
2048
2049 _visible void CYDestroyContext() {
2050 if (context_ == NULL)
2051 return;
2052 JSGlobalContextRelease(context_);
2053 context_ = NULL;
2054 }