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