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