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