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