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