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