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