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