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