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