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