]> git.saurik.com Git - cycript.git/blob - Library.cpp
80a17f7510ed3c11733a4390ebe59e8301a329e2
[cycript.git] / Library.cpp
1 /* Cycript - Inlining/Optimizing JavaScript Compiler
2 * Copyright (C) 2009 Jay Freeman (saurik)
3 */
4
5 /* Modified BSD License {{{ */
6 /*
7 * Redistribution and use in source and binary
8 * forms, with or without modification, are permitted
9 * provided that the following conditions are met:
10 *
11 * 1. Redistributions of source code must retain the
12 * above copyright notice, this list of conditions
13 * and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the
15 * above copyright notice, this list of conditions
16 * and the following disclaimer in the documentation
17 * and/or other materials provided with the
18 * distribution.
19 * 3. The name of the author may not be used to endorse
20 * or promote products derived from this software
21 * without specific prior written permission.
22 *
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS''
24 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
25 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
26 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
28 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
31 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
34 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
35 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
36 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
37 */
38 /* }}} */
39
40 #include <sqlite3.h>
41
42 #include "Internal.hpp"
43
44 #include <dlfcn.h>
45 #include <iconv.h>
46
47 #include "cycript.hpp"
48
49 #include "sig/parse.hpp"
50 #include "sig/ffi_type.hpp"
51
52 #include "Pooling.hpp"
53
54 #include <sys/mman.h>
55
56 #include <iostream>
57 #include <ext/stdio_filebuf.h>
58 #include <set>
59 #include <map>
60 #include <iomanip>
61 #include <sstream>
62 #include <cmath>
63
64 #include "Parser.hpp"
65 #include "Cycript.tab.hh"
66
67 #include "Error.hpp"
68 #include "JavaScript.hpp"
69 #include "String.hpp"
70
71 #ifdef __OBJC__
72 #define CYCatch_ \
73 catch (NSException *error) { \
74 CYThrow(context, error, exception); \
75 return NULL; \
76 }
77 #else
78 #define CYCatch_
79 #endif
80
81 char *sqlite3_column_pooled(apr_pool_t *pool, sqlite3_stmt *stmt, int n) {
82 if (const unsigned char *value = sqlite3_column_text(stmt, n))
83 return apr_pstrdup(pool, (const char *) value);
84 else return NULL;
85 }
86
87 struct CYHooks *hooks_;
88
89 /* JavaScript Properties {{{ */
90 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, size_t index) {
91 JSValueRef exception(NULL);
92 JSValueRef value(JSObjectGetPropertyAtIndex(context, object, index, &exception));
93 CYThrow(context, exception);
94 return value;
95 }
96
97 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, JSStringRef name) {
98 JSValueRef exception(NULL);
99 JSValueRef value(JSObjectGetProperty(context, object, name, &exception));
100 CYThrow(context, exception);
101 return value;
102 }
103
104 void CYSetProperty(JSContextRef context, JSObjectRef object, size_t index, JSValueRef value) {
105 JSValueRef exception(NULL);
106 JSObjectSetPropertyAtIndex(context, object, index, value, &exception);
107 CYThrow(context, exception);
108 }
109
110 void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef value, JSPropertyAttributes attributes) {
111 JSValueRef exception(NULL);
112 JSObjectSetProperty(context, object, name, value, attributes, &exception);
113 CYThrow(context, exception);
114 }
115 /* }}} */
116 /* JavaScript Strings {{{ */
117 JSStringRef CYCopyJSString(const char *value) {
118 return value == NULL ? NULL : JSStringCreateWithUTF8CString(value);
119 }
120
121 JSStringRef CYCopyJSString(JSStringRef value) {
122 return value == NULL ? NULL : JSStringRetain(value);
123 }
124
125 JSStringRef CYCopyJSString(CYUTF8String value) {
126 // XXX: this is very wrong
127 return CYCopyJSString(value.data);
128 }
129
130 JSStringRef CYCopyJSString(JSContextRef context, JSValueRef value) {
131 if (JSValueIsNull(context, value))
132 return NULL;
133 JSValueRef exception(NULL);
134 JSStringRef string(JSValueToStringCopy(context, value, &exception));
135 CYThrow(context, exception);
136 return string;
137 }
138
139 static CYUTF16String CYCastUTF16String(JSStringRef value) {
140 return CYUTF16String(JSStringGetCharactersPtr(value), JSStringGetLength(value));
141 }
142
143 static CYUTF8String CYPoolUTF8String(apr_pool_t *pool, JSContextRef context, JSStringRef value) {
144 _assert(pool != NULL);
145
146 CYUTF16String utf16(CYCastUTF16String(value));
147 const char *in(reinterpret_cast<const char *>(utf16.data));
148
149 #ifdef __APPLE__
150 iconv_t conversion(_syscall(iconv_open("UTF-8", "UCS-2-INTERNAL")));
151 #else
152 iconv_t conversion(_syscall(iconv_open("UTF-8", "UCS-2")));
153 #endif
154
155 size_t size(JSStringGetMaximumUTF8CStringSize(value));
156 char *out(new(pool) char[size]);
157 CYUTF8String utf8(out, size);
158
159 size = utf16.size * 2;
160 _syscall(iconv(conversion, const_cast<char **>(&in), &size, &out, &utf8.size));
161
162 *out = '\0';
163 utf8.size = out - utf8.data;
164
165 _syscall(iconv_close(conversion));
166
167 return utf8;
168 }
169
170 const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSStringRef value) {
171 CYUTF8String utf8(CYPoolUTF8String(pool, context, value));
172 _assert(memchr(utf8.data, '\0', utf8.size) == NULL);
173 return utf8.data;
174 }
175
176 const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
177 return JSValueIsNull(context, value) ? NULL : CYPoolCString(pool, context, CYJSString(context, value));
178 }
179 /* }}} */
180
181 /* Index Offsets {{{ */
182 size_t CYGetIndex(const CYUTF8String &value) {
183 if (value.data[0] != '0') {
184 char *end;
185 size_t index(strtoul(value.data, &end, 10));
186 if (value.data + value.size == end)
187 return index;
188 } else if (value.data[1] == '\0')
189 return 0;
190 return _not(size_t);
191 }
192
193 size_t CYGetIndex(apr_pool_t *pool, JSContextRef context, JSStringRef value) {
194 return CYGetIndex(CYPoolUTF8String(pool, context, value));
195 }
196
197 bool CYGetOffset(const char *value, ssize_t &index) {
198 if (value[0] != '0') {
199 char *end;
200 index = strtol(value, &end, 10);
201 if (value + strlen(value) == end)
202 return true;
203 } else if (value[1] == '\0') {
204 index = 0;
205 return true;
206 }
207
208 return false;
209 }
210 /* }}} */
211
212 /* JavaScript *ify {{{ */
213 void CYStringify(std::ostringstream &str, const char *data, size_t size) {
214 unsigned quot(0), apos(0);
215 for (const char *value(data), *end(data + size); value != end; ++value)
216 if (*value == '"')
217 ++quot;
218 else if (*value == '\'')
219 ++apos;
220
221 bool single(quot > apos);
222
223 str << (single ? '\'' : '"');
224
225 for (const char *value(data), *end(data + size); value != end; ++value)
226 switch (*value) {
227 case '\\': str << "\\\\"; break;
228 case '\b': str << "\\b"; break;
229 case '\f': str << "\\f"; break;
230 case '\n': str << "\\n"; break;
231 case '\r': str << "\\r"; break;
232 case '\t': str << "\\t"; break;
233 case '\v': str << "\\v"; break;
234
235 case '"':
236 if (!single)
237 str << "\\\"";
238 else goto simple;
239 break;
240
241 case '\'':
242 if (single)
243 str << "\\'";
244 else goto simple;
245 break;
246
247 default:
248 if (*value < 0x20 || *value >= 0x7f)
249 str << "\\x" << std::setbase(16) << std::setw(2) << std::setfill('0') << unsigned(*value);
250 else simple:
251 str << *value;
252 }
253
254 str << (single ? '\'' : '"');
255 }
256
257 void CYNumerify(std::ostringstream &str, double value) {
258 char string[32];
259 // XXX: I want this to print 1e3 rather than 1000
260 sprintf(string, "%.17g", value);
261 str << string;
262 }
263
264 bool CYIsKey(CYUTF8String value) {
265 const char *data(value.data);
266 size_t size(value.size);
267
268 if (size == 0)
269 return false;
270
271 if (DigitRange_[data[0]]) {
272 size_t index(CYGetIndex(value));
273 if (index == _not(size_t))
274 return false;
275 } else {
276 if (!WordStartRange_[data[0]])
277 return false;
278 for (size_t i(1); i != size; ++i)
279 if (!WordEndRange_[data[i]])
280 return false;
281 }
282
283 return true;
284 }
285 /* }}} */
286
287 static JSGlobalContextRef Context_;
288 static JSObjectRef System_;
289
290 static JSClassRef Functor_;
291 static JSClassRef Pointer_;
292 static JSClassRef Runtime_;
293 static JSClassRef Struct_;
294
295 static JSStringRef Result_;
296
297 JSObjectRef Array_;
298 JSObjectRef Error_;
299 JSObjectRef Function_;
300 JSObjectRef String_;
301
302 JSStringRef length_;
303 JSStringRef message_;
304 JSStringRef name_;
305 JSStringRef prototype_;
306 JSStringRef toCYON_;
307 JSStringRef toJSON_;
308
309 JSObjectRef Object_prototype_;
310 JSObjectRef Function_prototype_;
311
312 JSObjectRef Array_prototype_;
313 JSObjectRef Array_pop_;
314 JSObjectRef Array_push_;
315 JSObjectRef Array_splice_;
316
317 sqlite3 *Bridge_;
318
319 void CYFinalize(JSObjectRef object) {
320 delete reinterpret_cast<CYData *>(JSObjectGetPrivate(object));
321 }
322
323 struct CStringMapLess :
324 std::binary_function<const char *, const char *, bool>
325 {
326 _finline bool operator ()(const char *lhs, const char *rhs) const {
327 return strcmp(lhs, rhs) < 0;
328 }
329 };
330
331 void Structor_(apr_pool_t *pool, const char *name, const char *types, sig::Type *&type) {
332 if (name == NULL)
333 return;
334
335 sqlite3_stmt *statement;
336
337 _sqlcall(sqlite3_prepare(Bridge_,
338 "select "
339 "\"bridge\".\"mode\", "
340 "\"bridge\".\"value\" "
341 "from \"bridge\" "
342 "where"
343 " \"bridge\".\"mode\" in (3, 4) and"
344 " \"bridge\".\"name\" = ?"
345 " limit 1"
346 , -1, &statement, NULL));
347
348 _sqlcall(sqlite3_bind_text(statement, 1, name, -1, SQLITE_STATIC));
349
350 int mode;
351 const char *value;
352
353 if (_sqlcall(sqlite3_step(statement)) == SQLITE_DONE) {
354 mode = -1;
355 value = NULL;
356 } else {
357 mode = sqlite3_column_int(statement, 0);
358 value = sqlite3_column_pooled(pool, statement, 1);
359 }
360
361 _sqlcall(sqlite3_finalize(statement));
362
363 switch (mode) {
364 default:
365 _assert(false);
366 case -1:
367 break;
368
369 case 3: {
370 sig::Parse(pool, &type->data.signature, value, &Structor_);
371 } break;
372
373 case 4: {
374 sig::Signature signature;
375 sig::Parse(pool, &signature, value, &Structor_);
376 type = signature.elements[0].type;
377 } break;
378 }
379 }
380
381 JSClassRef Type_privateData::Class_;
382
383 struct Pointer :
384 CYOwned
385 {
386 Type_privateData *type_;
387
388 Pointer(void *value, JSContextRef context, JSObjectRef owner, sig::Type *type) :
389 CYOwned(value, context, owner),
390 type_(new(pool_) Type_privateData(type))
391 {
392 }
393 };
394
395 struct Struct_privateData :
396 CYOwned
397 {
398 Type_privateData *type_;
399
400 Struct_privateData(JSContextRef context, JSObjectRef owner) :
401 CYOwned(NULL, context, owner)
402 {
403 }
404 };
405
406 typedef std::map<const char *, Type_privateData *, CStringMapLess> TypeMap;
407 static TypeMap Types_;
408
409 JSObjectRef CYMakeStruct(JSContextRef context, void *data, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
410 Struct_privateData *internal(new Struct_privateData(context, owner));
411 apr_pool_t *pool(internal->pool_);
412 Type_privateData *typical(new(pool) Type_privateData(type, ffi));
413 internal->type_ = typical;
414
415 if (owner != NULL)
416 internal->value_ = data;
417 else {
418 size_t size(typical->GetFFI()->size);
419 void *copy(apr_palloc(internal->pool_, size));
420 memcpy(copy, data, size);
421 internal->value_ = copy;
422 }
423
424 return JSObjectMake(context, Struct_, internal);
425 }
426
427 JSValueRef CYCastJSValue(JSContextRef context, bool value) {
428 return JSValueMakeBoolean(context, value);
429 }
430
431 JSValueRef CYCastJSValue(JSContextRef context, double value) {
432 return JSValueMakeNumber(context, value);
433 }
434
435 #define CYCastJSValue_(Type_) \
436 JSValueRef CYCastJSValue(JSContextRef context, Type_ value) { \
437 return JSValueMakeNumber(context, static_cast<double>(value)); \
438 }
439
440 CYCastJSValue_(int)
441 CYCastJSValue_(unsigned int)
442 CYCastJSValue_(long int)
443 CYCastJSValue_(long unsigned int)
444 CYCastJSValue_(long long int)
445 CYCastJSValue_(long long unsigned int)
446
447 JSValueRef CYJSUndefined(JSContextRef context) {
448 return JSValueMakeUndefined(context);
449 }
450
451 double CYCastDouble(const char *value, size_t size) {
452 char *end;
453 double number(strtod(value, &end));
454 if (end != value + size)
455 return NAN;
456 return number;
457 }
458
459 double CYCastDouble(const char *value) {
460 return CYCastDouble(value, strlen(value));
461 }
462
463 double CYCastDouble(JSContextRef context, JSValueRef value) {
464 JSValueRef exception(NULL);
465 double number(JSValueToNumber(context, value, &exception));
466 CYThrow(context, exception);
467 return number;
468 }
469
470 bool CYCastBool(JSContextRef context, JSValueRef value) {
471 return JSValueToBoolean(context, value);
472 }
473
474 JSValueRef CYJSNull(JSContextRef context) {
475 return JSValueMakeNull(context);
476 }
477
478 JSValueRef CYCastJSValue(JSContextRef context, JSStringRef value) {
479 return value == NULL ? CYJSNull(context) : JSValueMakeString(context, value);
480 }
481
482 JSValueRef CYCastJSValue(JSContextRef context, const char *value) {
483 return CYCastJSValue(context, CYJSString(value));
484 }
485
486 JSObjectRef CYCastJSObject(JSContextRef context, JSValueRef value) {
487 JSValueRef exception(NULL);
488 JSObjectRef object(JSValueToObject(context, value, &exception));
489 CYThrow(context, exception);
490 return object;
491 }
492
493 JSValueRef CYCallAsFunction(JSContextRef context, JSObjectRef function, JSObjectRef _this, size_t count, JSValueRef arguments[]) {
494 JSValueRef exception(NULL);
495 JSValueRef value(JSObjectCallAsFunction(context, function, _this, count, arguments, &exception));
496 CYThrow(context, exception);
497 return value;
498 }
499
500 bool CYIsCallable(JSContextRef context, JSValueRef value) {
501 return value != NULL && JSValueIsObject(context, value) && JSObjectIsFunction(context, (JSObjectRef) value);
502 }
503
504 static JSValueRef System_print(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
505 if (count == 0)
506 printf("\n");
507 else {
508 CYPool pool;
509 printf("%s\n", CYPoolCString(pool, context, arguments[0]));
510 }
511
512 return CYJSUndefined(context);
513 } CYCatch }
514
515 static size_t Nonce_(0);
516
517 static JSValueRef $cyq(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
518 CYPool pool;
519 const char *name(apr_psprintf(pool, "%s%zu", CYPoolCString(pool, context, arguments[0]), Nonce_++));
520 return CYCastJSValue(context, name);
521 }
522
523 static JSValueRef Cycript_gc_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
524 JSGarbageCollect(context);
525 return CYJSUndefined(context);
526 }
527
528 const char *CYPoolCCYON(apr_pool_t *pool, JSContextRef context, JSValueRef value, JSValueRef *exception) { CYTry {
529 switch (JSType type = JSValueGetType(context, value)) {
530 case kJSTypeUndefined:
531 return "undefined";
532 case kJSTypeNull:
533 return "null";
534 case kJSTypeBoolean:
535 return CYCastBool(context, value) ? "true" : "false";
536
537 case kJSTypeNumber: {
538 std::ostringstream str;
539 CYNumerify(str, CYCastDouble(context, value));
540 std::string value(str.str());
541 return apr_pstrmemdup(pool, value.c_str(), value.size());
542 } break;
543
544 case kJSTypeString: {
545 std::ostringstream str;
546 CYUTF8String string(CYPoolUTF8String(pool, context, CYJSString(context, value)));
547 CYStringify(str, string.data, string.size);
548 std::string value(str.str());
549 return apr_pstrmemdup(pool, value.c_str(), value.size());
550 } break;
551
552 case kJSTypeObject:
553 return CYPoolCCYON(pool, context, (JSObjectRef) value);
554 default:
555 throw CYJSError(context, "JSValueGetType() == 0x%x", type);
556 }
557 } CYCatch }
558
559 const char *CYPoolCCYON(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
560 JSValueRef exception(NULL);
561 const char *cyon(CYPoolCCYON(pool, context, value, &exception));
562 CYThrow(context, exception);
563 return cyon;
564 }
565
566 const char *CYPoolCCYON(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
567 JSValueRef toCYON(CYGetProperty(context, object, toCYON_));
568 if (CYIsCallable(context, toCYON)) {
569 JSValueRef value(CYCallAsFunction(context, (JSObjectRef) toCYON, object, 0, NULL));
570 return CYPoolCString(pool, context, value);
571 }
572
573 JSValueRef toJSON(CYGetProperty(context, object, toJSON_));
574 if (CYIsCallable(context, toJSON)) {
575 JSValueRef arguments[1] = {CYCastJSValue(context, CYJSString(""))};
576 JSValueRef exception(NULL);
577 const char *cyon(CYPoolCCYON(pool, context, CYCallAsFunction(context, (JSObjectRef) toJSON, object, 1, arguments), &exception));
578 CYThrow(context, exception);
579 return cyon;
580 }
581
582 std::ostringstream str;
583
584 str << '{';
585
586 // XXX: this is, sadly, going to leak
587 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context, object));
588
589 bool comma(false);
590
591 for (size_t index(0), count(JSPropertyNameArrayGetCount(names)); index != count; ++index) {
592 JSStringRef name(JSPropertyNameArrayGetNameAtIndex(names, index));
593 JSValueRef value(CYGetProperty(context, object, name));
594
595 if (comma)
596 str << ',';
597 else
598 comma = true;
599
600 CYUTF8String string(CYPoolUTF8String(pool, context, name));
601 if (CYIsKey(string))
602 str << string.data;
603 else
604 CYStringify(str, string.data, string.size);
605
606 str << ':' << CYPoolCCYON(pool, context, value);
607 }
608
609 str << '}';
610
611 JSPropertyNameArrayRelease(names);
612
613 std::string string(str.str());
614 return apr_pstrmemdup(pool, string.c_str(), string.size());
615 }
616
617 static JSValueRef Array_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
618 CYPool pool;
619 std::ostringstream str;
620
621 str << '[';
622
623 JSValueRef length(CYGetProperty(context, _this, length_));
624 bool comma(false);
625
626 for (size_t index(0), count(CYCastDouble(context, length)); index != count; ++index) {
627 JSValueRef value(CYGetProperty(context, _this, index));
628
629 if (comma)
630 str << ',';
631 else
632 comma = true;
633
634 if (!JSValueIsUndefined(context, value))
635 str << CYPoolCCYON(pool, context, value);
636 else {
637 str << ',';
638 comma = false;
639 }
640 }
641
642 str << ']';
643
644 std::string value(str.str());
645 return CYCastJSValue(context, CYJSString(CYUTF8String(value.c_str(), value.size())));
646 } CYCatch }
647
648 JSObjectRef CYMakePointer(JSContextRef context, void *pointer, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
649 Pointer *internal(new Pointer(pointer, context, owner, type));
650 return JSObjectMake(context, Pointer_, internal);
651 }
652
653 static JSObjectRef CYMakeFunctor(JSContextRef context, void (*function)(), const char *type) {
654 cy::Functor *internal(new cy::Functor(type, function));
655 return JSObjectMake(context, Functor_, internal);
656 }
657
658 static bool CYGetOffset(apr_pool_t *pool, JSContextRef context, JSStringRef value, ssize_t &index) {
659 return CYGetOffset(CYPoolCString(pool, context, value), index);
660 }
661
662 void *CYCastPointer_(JSContextRef context, JSValueRef value) {
663 switch (JSValueGetType(context, value)) {
664 case kJSTypeNull:
665 return NULL;
666 /*case kJSTypeObject:
667 if (JSValueIsObjectOfClass(context, value, Pointer_)) {
668 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate((JSObjectRef) value)));
669 return internal->value_;
670 }*/
671 default:
672 double number(CYCastDouble(context, value));
673 if (std::isnan(number))
674 throw CYJSError(context, "cannot convert value to pointer");
675 return reinterpret_cast<void *>(static_cast<uintptr_t>(static_cast<long long>(number)));
676 }
677 }
678
679 void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) {
680 switch (type->primitive) {
681 case sig::boolean_P:
682 *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
683 break;
684
685 #define CYPoolFFI_(primitive, native) \
686 case sig::primitive ## _P: \
687 *reinterpret_cast<native *>(data) = CYCastDouble(context, value); \
688 break;
689
690 CYPoolFFI_(uchar, unsigned char)
691 CYPoolFFI_(char, char)
692 CYPoolFFI_(ushort, unsigned short)
693 CYPoolFFI_(short, short)
694 CYPoolFFI_(ulong, unsigned long)
695 CYPoolFFI_(long, long)
696 CYPoolFFI_(uint, unsigned int)
697 CYPoolFFI_(int, int)
698 CYPoolFFI_(ulonglong, unsigned long long)
699 CYPoolFFI_(longlong, long long)
700 CYPoolFFI_(float, float)
701 CYPoolFFI_(double, double)
702
703 case sig::pointer_P:
704 *reinterpret_cast<void **>(data) = CYCastPointer<void *>(context, value);
705 break;
706
707 case sig::string_P:
708 *reinterpret_cast<const char **>(data) = CYPoolCString(pool, context, value);
709 break;
710
711 case sig::struct_P: {
712 uint8_t *base(reinterpret_cast<uint8_t *>(data));
713 JSObjectRef aggregate(JSValueIsObject(context, value) ? (JSObjectRef) value : NULL);
714 for (size_t index(0); index != type->data.signature.count; ++index) {
715 sig::Element *element(&type->data.signature.elements[index]);
716 ffi_type *field(ffi->elements[index]);
717
718 JSValueRef rhs;
719 if (aggregate == NULL)
720 rhs = value;
721 else {
722 rhs = CYGetProperty(context, aggregate, index);
723 if (JSValueIsUndefined(context, rhs)) {
724 if (element->name != NULL)
725 rhs = CYGetProperty(context, aggregate, CYJSString(element->name));
726 else
727 goto undefined;
728 if (JSValueIsUndefined(context, rhs)) undefined:
729 throw CYJSError(context, "unable to extract structure value");
730 }
731 }
732
733 CYPoolFFI(pool, context, element->type, field, base, rhs);
734 // XXX: alignment?
735 base += field->size;
736 }
737 } break;
738
739 case sig::void_P:
740 break;
741
742 default:
743 if (hooks_ != NULL && hooks_->PoolFFI != NULL)
744 if ((*hooks_->PoolFFI)(pool, context, type, ffi, data, value))
745 return;
746
747 fprintf(stderr, "CYPoolFFI(%c)\n", type->primitive);
748 _assert(false);
749 }
750 }
751
752 JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) {
753 switch (type->primitive) {
754 case sig::boolean_P:
755 return CYCastJSValue(context, *reinterpret_cast<bool *>(data));
756
757 #define CYFromFFI_(primitive, native) \
758 case sig::primitive ## _P: \
759 return CYCastJSValue(context, *reinterpret_cast<native *>(data)); \
760
761 CYFromFFI_(uchar, unsigned char)
762 CYFromFFI_(char, char)
763 CYFromFFI_(ushort, unsigned short)
764 CYFromFFI_(short, short)
765 CYFromFFI_(ulong, unsigned long)
766 CYFromFFI_(long, long)
767 CYFromFFI_(uint, unsigned int)
768 CYFromFFI_(int, int)
769 CYFromFFI_(ulonglong, unsigned long long)
770 CYFromFFI_(longlong, long long)
771 CYFromFFI_(float, float)
772 CYFromFFI_(double, double)
773
774 case sig::pointer_P:
775 if (void *pointer = *reinterpret_cast<void **>(data))
776 return CYMakePointer(context, pointer, type->data.data.type, ffi, owner);
777 else goto null;
778
779 case sig::string_P:
780 if (char *utf8 = *reinterpret_cast<char **>(data))
781 return CYCastJSValue(context, utf8);
782 else goto null;
783
784 case sig::struct_P:
785 return CYMakeStruct(context, data, type, ffi, owner);
786 case sig::void_P:
787 return CYJSUndefined(context);
788
789 null:
790 return CYJSNull(context);
791 default:
792 if (hooks_ != NULL && hooks_->FromFFI != NULL)
793 if (JSValueRef value = (*hooks_->FromFFI)(context, type, ffi, data, initialize, owner))
794 return value;
795
796 fprintf(stderr, "CYFromFFI(%c)\n", type->primitive);
797 _assert(false);
798 }
799 }
800
801 static void FunctionClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
802 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
803
804 JSContextRef context(internal->context_);
805
806 size_t count(internal->cif_.nargs);
807 JSValueRef values[count];
808
809 for (size_t index(0); index != count; ++index)
810 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
811
812 JSValueRef value(CYCallAsFunction(context, internal->function_, NULL, count, values));
813 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
814 }
815
816 Closure_privateData *CYMakeFunctor_(JSContextRef context, JSObjectRef function, const char *type, void (*callback)(ffi_cif *, void *, void **, void *)) {
817 // XXX: in case of exceptions this will leak
818 // XXX: in point of fact, this may /need/ to leak :(
819 Closure_privateData *internal(new Closure_privateData(CYGetJSContext(), function, type));
820
821 ffi_closure *closure((ffi_closure *) _syscall(mmap(
822 NULL, sizeof(ffi_closure),
823 PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE,
824 -1, 0
825 )));
826
827 ffi_status status(ffi_prep_closure(closure, &internal->cif_, callback, internal));
828 _assert(status == FFI_OK);
829
830 _syscall(mprotect(closure, sizeof(*closure), PROT_READ | PROT_EXEC));
831
832 internal->value_ = closure;
833
834 return internal;
835 }
836
837 static JSObjectRef CYMakeFunctor(JSContextRef context, JSObjectRef function, const char *type) {
838 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &FunctionClosure_));
839 return JSObjectMake(context, Functor_, internal);
840 }
841
842 static JSObjectRef CYMakeFunctor(JSContextRef context, JSValueRef value, const char *type) {
843 JSValueRef exception(NULL);
844 bool function(JSValueIsInstanceOfConstructor(context, value, Function_, &exception));
845 CYThrow(context, exception);
846
847 if (function) {
848 JSObjectRef function(CYCastJSObject(context, value));
849 return CYMakeFunctor(context, function, type);
850 } else {
851 void (*function)()(CYCastPointer<void (*)()>(context, value));
852 return CYMakeFunctor(context, function, type);
853 }
854 }
855
856 static bool Index_(apr_pool_t *pool, JSContextRef context, Struct_privateData *internal, JSStringRef property, ssize_t &index, uint8_t *&base) {
857 Type_privateData *typical(internal->type_);
858 sig::Type *type(typical->type_);
859 if (type == NULL)
860 return false;
861
862 const char *name(CYPoolCString(pool, context, property));
863 size_t length(strlen(name));
864 double number(CYCastDouble(name, length));
865
866 size_t count(type->data.signature.count);
867
868 if (std::isnan(number)) {
869 if (property == NULL)
870 return false;
871
872 sig::Element *elements(type->data.signature.elements);
873
874 for (size_t local(0); local != count; ++local) {
875 sig::Element *element(&elements[local]);
876 if (element->name != NULL && strcmp(name, element->name) == 0) {
877 index = local;
878 goto base;
879 }
880 }
881
882 return false;
883 } else {
884 index = static_cast<ssize_t>(number);
885 if (index != number || index < 0 || static_cast<size_t>(index) >= count)
886 return false;
887 }
888
889 base:
890 ffi_type **elements(typical->GetFFI()->elements);
891
892 base = reinterpret_cast<uint8_t *>(internal->value_);
893 for (ssize_t local(0); local != index; ++local)
894 base += elements[local]->size;
895
896 return true;
897 }
898
899 static JSValueRef Pointer_getIndex(JSContextRef context, JSObjectRef object, size_t index, JSValueRef *exception) { CYTry {
900 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
901 Type_privateData *typical(internal->type_);
902
903 ffi_type *ffi(typical->GetFFI());
904
905 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
906 base += ffi->size * index;
907
908 JSObjectRef owner(internal->GetOwner() ?: object);
909 return CYFromFFI(context, typical->type_, ffi, base, false, owner);
910 } CYCatch }
911
912 static JSValueRef Pointer_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
913 CYPool pool;
914 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
915 Type_privateData *typical(internal->type_);
916
917 if (typical->type_ == NULL)
918 return NULL;
919
920 ssize_t offset;
921 if (!CYGetOffset(pool, context, property, offset))
922 return NULL;
923
924 return Pointer_getIndex(context, object, offset, exception);
925 }
926
927 static JSValueRef Pointer_getProperty_$cyi(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
928 return Pointer_getIndex(context, object, 0, exception);
929 }
930
931 static bool Pointer_setIndex(JSContextRef context, JSObjectRef object, size_t index, JSValueRef value, JSValueRef *exception) { CYTry {
932 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
933 Type_privateData *typical(internal->type_);
934
935 ffi_type *ffi(typical->GetFFI());
936
937 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
938 base += ffi->size * index;
939
940 CYPoolFFI(NULL, context, typical->type_, ffi, base, value);
941 return true;
942 } CYCatch }
943
944 static bool Pointer_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
945 CYPool pool;
946 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
947 Type_privateData *typical(internal->type_);
948
949 if (typical->type_ == NULL)
950 return NULL;
951
952 ssize_t offset;
953 if (!CYGetOffset(pool, context, property, offset))
954 return NULL;
955
956 return Pointer_setIndex(context, object, offset, value, exception);
957 }
958
959 static bool Pointer_setProperty_$cyi(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
960 return Pointer_setIndex(context, object, 0, value, exception);
961 }
962
963 static JSValueRef Struct_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
964 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(_this)));
965 Type_privateData *typical(internal->type_);
966 return CYMakePointer(context, internal->value_, typical->type_, typical->ffi_, _this);
967 }
968
969 static JSValueRef Struct_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
970 CYPool pool;
971 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
972 Type_privateData *typical(internal->type_);
973
974 ssize_t index;
975 uint8_t *base;
976
977 if (!Index_(pool, context, internal, property, index, base))
978 return NULL;
979
980 JSObjectRef owner(internal->GetOwner() ?: object);
981
982 return CYFromFFI(context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, false, owner);
983 } CYCatch }
984
985 static bool Struct_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
986 CYPool pool;
987 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
988 Type_privateData *typical(internal->type_);
989
990 ssize_t index;
991 uint8_t *base;
992
993 if (!Index_(pool, context, internal, property, index, base))
994 return false;
995
996 CYPoolFFI(NULL, context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, value);
997 return true;
998 } CYCatch }
999
1000 static void Struct_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1001 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
1002 Type_privateData *typical(internal->type_);
1003 sig::Type *type(typical->type_);
1004
1005 if (type == NULL)
1006 return;
1007
1008 size_t count(type->data.signature.count);
1009 sig::Element *elements(type->data.signature.elements);
1010
1011 char number[32];
1012
1013 for (size_t index(0); index != count; ++index) {
1014 const char *name;
1015 name = elements[index].name;
1016
1017 if (name == NULL) {
1018 sprintf(number, "%lu", index);
1019 name = number;
1020 }
1021
1022 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1023 }
1024 }
1025
1026 JSValueRef CYCallFunction(apr_pool_t *pool, JSContextRef context, size_t setups, void *setup[], size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception, sig::Signature *signature, ffi_cif *cif, void (*function)()) { CYTry {
1027 if (setups + count != signature->count - 1)
1028 throw CYJSError(context, "incorrect number of arguments to ffi function");
1029
1030 size_t size(setups + count);
1031 void *values[size];
1032 memcpy(values, setup, sizeof(void *) * setups);
1033
1034 for (size_t index(setups); index != size; ++index) {
1035 sig::Element *element(&signature->elements[index + 1]);
1036 ffi_type *ffi(cif->arg_types[index]);
1037 // XXX: alignment?
1038 values[index] = new(pool) uint8_t[ffi->size];
1039 CYPoolFFI(pool, context, element->type, ffi, values[index], arguments[index - setups]);
1040 }
1041
1042 uint8_t value[cif->rtype->size];
1043
1044 if (hooks_ != NULL && hooks_->CallFunction != NULL)
1045 (*hooks_->CallFunction)(context, cif, function, value, values);
1046 else
1047 ffi_call(cif, function, value, values);
1048
1049 return CYFromFFI(context, signature->elements[0].type, cif->rtype, value, initialize);
1050 } CYCatch }
1051
1052 static JSValueRef Functor_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1053 CYPool pool;
1054 cy::Functor *internal(reinterpret_cast<cy::Functor *>(JSObjectGetPrivate(object)));
1055 return CYCallFunction(pool, context, 0, NULL, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
1056 }
1057
1058 static JSObjectRef CYMakeType(JSContextRef context, const char *type) {
1059 Type_privateData *internal(new Type_privateData(NULL, type));
1060 return JSObjectMake(context, Type_privateData::Class_, internal);
1061 }
1062
1063 static JSObjectRef CYMakeType(JSContextRef context, sig::Type *type) {
1064 Type_privateData *internal(new Type_privateData(type));
1065 return JSObjectMake(context, Type_privateData::Class_, internal);
1066 }
1067
1068 static void *CYCastSymbol(const char *name) {
1069 return dlsym(RTLD_DEFAULT, name);
1070 }
1071
1072 static JSValueRef Runtime_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1073 CYPool pool;
1074 CYUTF8String name(CYPoolUTF8String(pool, context, property));
1075
1076 if (hooks_ != NULL && hooks_->RuntimeProperty != NULL)
1077 if (JSValueRef value = (*hooks_->RuntimeProperty)(context, name))
1078 return value;
1079
1080 sqlite3_stmt *statement;
1081
1082 _sqlcall(sqlite3_prepare(Bridge_,
1083 "select "
1084 "\"bridge\".\"mode\", "
1085 "\"bridge\".\"value\" "
1086 "from \"bridge\" "
1087 "where"
1088 " \"bridge\".\"name\" = ?"
1089 " limit 1"
1090 , -1, &statement, NULL));
1091
1092 _sqlcall(sqlite3_bind_text(statement, 1, name.data, name.size, SQLITE_STATIC));
1093
1094 int mode;
1095 const char *value;
1096
1097 if (_sqlcall(sqlite3_step(statement)) == SQLITE_DONE) {
1098 mode = -1;
1099 value = NULL;
1100 } else {
1101 mode = sqlite3_column_int(statement, 0);
1102 value = sqlite3_column_pooled(pool, statement, 1);
1103 }
1104
1105 _sqlcall(sqlite3_finalize(statement));
1106
1107 switch (mode) {
1108 default:
1109 _assert(false);
1110 case -1:
1111 return NULL;
1112
1113 case 0:
1114 return JSEvaluateScript(CYGetJSContext(), CYJSString(value), NULL, NULL, 0, NULL);
1115 case 1:
1116 return CYMakeFunctor(context, reinterpret_cast<void (*)()>(CYCastSymbol(name.data)), value);
1117
1118 case 2: {
1119 // XXX: this is horrendously inefficient
1120 sig::Signature signature;
1121 sig::Parse(pool, &signature, value, &Structor_);
1122 ffi_cif cif;
1123 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
1124 return CYFromFFI(context, signature.elements[0].type, cif.rtype, CYCastSymbol(name.data));
1125 }
1126
1127 // XXX: implement case 3
1128 case 4:
1129 return CYMakeType(context, value);
1130 }
1131 } CYCatch }
1132
1133 static JSObjectRef Pointer_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1134 if (count != 2)
1135 throw CYJSError(context, "incorrect number of arguments to Functor constructor");
1136
1137 CYPool pool;
1138
1139 void *value(CYCastPointer<void *>(context, arguments[0]));
1140 const char *type(CYPoolCString(pool, context, arguments[1]));
1141
1142 sig::Signature signature;
1143 sig::Parse(pool, &signature, type, &Structor_);
1144
1145 return CYMakePointer(context, value, signature.elements[0].type, NULL, NULL);
1146 } CYCatch }
1147
1148 static JSObjectRef Type_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1149 if (count != 1)
1150 throw CYJSError(context, "incorrect number of arguments to Type constructor");
1151 CYPool pool;
1152 const char *type(CYPoolCString(pool, context, arguments[0]));
1153 return CYMakeType(context, type);
1154 } CYCatch }
1155
1156 static JSValueRef Type_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1157 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
1158
1159 sig::Type type;
1160
1161 if (JSStringIsEqualToUTF8CString(property, "$cyi")) {
1162 type.primitive = sig::pointer_P;
1163 type.data.data.size = 0;
1164 } else {
1165 CYPool pool;
1166 size_t index(CYGetIndex(pool, context, property));
1167 if (index == _not(size_t))
1168 return NULL;
1169 type.primitive = sig::array_P;
1170 type.data.data.size = index;
1171 }
1172
1173 type.name = NULL;
1174 type.flags = 0;
1175
1176 type.data.data.type = internal->type_;
1177
1178 return CYMakeType(context, &type);
1179 } CYCatch }
1180
1181 static JSValueRef Type_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1182 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
1183
1184 if (count != 1)
1185 throw CYJSError(context, "incorrect number of arguments to type cast function");
1186 sig::Type *type(internal->type_);
1187 ffi_type *ffi(internal->GetFFI());
1188 // XXX: alignment?
1189 uint8_t value[ffi->size];
1190 CYPool pool;
1191 CYPoolFFI(pool, context, type, ffi, value, arguments[0]);
1192 return CYFromFFI(context, type, ffi, value);
1193 } CYCatch }
1194
1195 static JSObjectRef Type_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1196 if (count != 0)
1197 throw CYJSError(context, "incorrect number of arguments to type cast function");
1198 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
1199
1200 sig::Type *type(internal->type_);
1201 size_t size;
1202
1203 if (type->primitive != sig::array_P)
1204 size = 0;
1205 else {
1206 size = type->data.data.size;
1207 type = type->data.data.type;
1208 }
1209
1210 void *value(malloc(internal->GetFFI()->size));
1211 return CYMakePointer(context, value, type, NULL, NULL);
1212 } CYCatch }
1213
1214 static JSObjectRef Functor_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1215 if (count != 2)
1216 throw CYJSError(context, "incorrect number of arguments to Functor constructor");
1217 CYPool pool;
1218 const char *type(CYPoolCString(pool, context, arguments[1]));
1219 return CYMakeFunctor(context, arguments[0], type);
1220 } CYCatch }
1221
1222 static JSValueRef CYValue_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1223 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
1224 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
1225 } CYCatch }
1226
1227 static JSValueRef CYValue_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1228 return CYValue_callAsFunction_valueOf(context, object, _this, count, arguments, exception);
1229 }
1230
1231 static JSValueRef CYValue_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1232 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
1233 char string[32];
1234 sprintf(string, "%p", internal->value_);
1235
1236 return CYCastJSValue(context, string);
1237 } CYCatch }
1238
1239 static JSValueRef Type_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1240 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
1241 CYPool pool;
1242 const char *type(sig::Unparse(pool, internal->type_));
1243 return CYCastJSValue(context, CYJSString(type));
1244 } CYCatch }
1245
1246 static JSValueRef Type_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1247 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
1248 CYPool pool;
1249 const char *type(sig::Unparse(pool, internal->type_));
1250 size_t size(strlen(type));
1251 char *cyon(new(pool) char[12 + size + 1]);
1252 memcpy(cyon, "new Type(\"", 10);
1253 cyon[12 + size] = '\0';
1254 cyon[12 + size - 2] = '"';
1255 cyon[12 + size - 1] = ')';
1256 memcpy(cyon + 10, type, size);
1257 return CYCastJSValue(context, CYJSString(cyon));
1258 } CYCatch }
1259
1260 static JSValueRef Type_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1261 return Type_callAsFunction_toString(context, object, _this, count, arguments, exception);
1262 }
1263
1264 static JSStaticValue Pointer_staticValues[2] = {
1265 {"$cyi", &Pointer_getProperty_$cyi, &Pointer_setProperty_$cyi, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1266 {NULL, NULL, NULL, 0}
1267 };
1268
1269 static JSStaticFunction Pointer_staticFunctions[4] = {
1270 {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1271 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1272 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1273 {NULL, NULL, 0}
1274 };
1275
1276 static JSStaticFunction Struct_staticFunctions[2] = {
1277 {"$cya", &Struct_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1278 {NULL, NULL, 0}
1279 };
1280
1281 static JSStaticFunction Functor_staticFunctions[4] = {
1282 {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1283 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1284 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1285 {NULL, NULL, 0}
1286 };
1287
1288 namespace cy {
1289 JSStaticFunction const * const Functor::StaticFunctions = Functor_staticFunctions;
1290 }
1291
1292 static JSStaticFunction Type_staticFunctions[4] = {
1293 {"toCYON", &Type_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1294 {"toJSON", &Type_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1295 {"toString", &Type_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1296 {NULL, NULL, 0}
1297 };
1298
1299 void CYSetArgs(int argc, const char *argv[]) {
1300 JSContextRef context(CYGetJSContext());
1301 JSValueRef args[argc];
1302 for (int i(0); i != argc; ++i)
1303 args[i] = CYCastJSValue(context, argv[i]);
1304 #ifdef __APPLE__
1305 JSValueRef exception(NULL);
1306 JSObjectRef array(JSObjectMakeArray(context, argc, args, &exception));
1307 CYThrow(context, exception);
1308 #else
1309 JSValueRef value(CYCallAsFunction(context, Array_, NULL, argc, args));
1310 JSObjectRef array(CYCastJSObject(context, value));
1311 #endif
1312 CYSetProperty(context, System_, CYJSString("args"), array);
1313 }
1314
1315 JSObjectRef CYGetGlobalObject(JSContextRef context) {
1316 return JSContextGetGlobalObject(context);
1317 }
1318
1319 const char *CYExecute(apr_pool_t *pool, const char *code) {
1320 JSContextRef context(CYGetJSContext());
1321 JSValueRef exception(NULL), result;
1322
1323 void *handle;
1324 if (hooks_ != NULL && hooks_->ExecuteStart != NULL)
1325 handle = (*hooks_->ExecuteStart)(context);
1326 else
1327 handle = NULL;
1328
1329 const char *json;
1330
1331 try {
1332 result = JSEvaluateScript(context, CYJSString(code), NULL, NULL, 0, &exception);
1333 } catch (const char *error) {
1334 return error;
1335 }
1336
1337 if (exception != NULL) { error:
1338 result = exception;
1339 exception = NULL;
1340 }
1341
1342 if (JSValueIsUndefined(context, result))
1343 return NULL;
1344
1345 try {
1346 json = CYPoolCCYON(pool, context, result, &exception);
1347 } catch (const char *error) {
1348 return error;
1349 }
1350
1351 if (exception != NULL)
1352 goto error;
1353
1354 CYSetProperty(context, CYGetGlobalObject(context), Result_, result);
1355
1356 if (hooks_ != NULL && hooks_->ExecuteEnd != NULL)
1357 (*hooks_->ExecuteEnd)(context, handle);
1358 return json;
1359 }
1360
1361 static apr_pool_t *Pool_;
1362
1363 static bool initialized_;
1364
1365 void CYInitialize() {
1366 if (!initialized_)
1367 initialized_ = true;
1368 else return;
1369
1370 _aprcall(apr_initialize());
1371 _aprcall(apr_pool_create(&Pool_, NULL));
1372 _sqlcall(sqlite3_open("/usr/lib/libcycript.db", &Bridge_));
1373 }
1374
1375 apr_pool_t *CYGetGlobalPool() {
1376 CYInitialize();
1377 return Pool_;
1378 }
1379
1380 void CYThrow(JSContextRef context, JSValueRef value) {
1381 if (value != NULL)
1382 throw CYJSError(context, value);
1383 }
1384
1385 const char *CYJSError::PoolCString(apr_pool_t *pool) const {
1386 return CYPoolCString(pool, context_, value_);
1387 }
1388
1389 JSValueRef CYJSError::CastJSValue(JSContextRef context) const {
1390 // XXX: what if the context is different?
1391 return value_;
1392 }
1393
1394 void CYThrow(const char *format, ...) {
1395 va_list args;
1396 va_start (args, format);
1397 throw CYPoolError(format, args);
1398 // XXX: does this matter? :(
1399 va_end (args);
1400 }
1401
1402 const char *CYPoolError::PoolCString(apr_pool_t *pool) const {
1403 return apr_pstrdup(pool, message_);
1404 }
1405
1406 CYPoolError::CYPoolError(const char *format, ...) {
1407 va_list args;
1408 va_start (args, format);
1409 message_ = apr_pvsprintf(pool_, format, args);
1410 va_end (args);
1411 }
1412
1413 CYPoolError::CYPoolError(const char *format, va_list args) {
1414 message_ = apr_pvsprintf(pool_, format, args);
1415 }
1416
1417 JSValueRef CYPoolError::CastJSValue(JSContextRef context) const {
1418 return CYCastJSValue(context, message_);
1419 }
1420
1421 CYJSError::CYJSError(JSContextRef context, const char *format, ...) {
1422 if (context == NULL)
1423 context = CYGetJSContext();
1424
1425 CYPool pool;
1426
1427 va_list args;
1428 va_start (args, format);
1429 const char *message(apr_pvsprintf(pool, format, args));
1430 va_end (args);
1431
1432 JSValueRef arguments[1] = {CYCastJSValue(context, CYJSString(message))};
1433
1434 JSValueRef exception(NULL);
1435 value_ = JSObjectCallAsConstructor(context, Error_, 1, arguments, &exception);
1436 CYThrow(context, exception);
1437 }
1438
1439 void CYObjectiveC(JSContextRef context, JSObjectRef global);
1440
1441 JSGlobalContextRef CYGetJSContext() {
1442 CYInitialize();
1443
1444 if (Context_ == NULL) {
1445 JSClassDefinition definition;
1446
1447 definition = kJSClassDefinitionEmpty;
1448 definition.className = "Functor";
1449 definition.staticFunctions = cy::Functor::StaticFunctions;
1450 definition.callAsFunction = &Functor_callAsFunction;
1451 definition.finalize = &CYFinalize;
1452 Functor_ = JSClassCreate(&definition);
1453
1454 definition = kJSClassDefinitionEmpty;
1455 definition.className = "Pointer";
1456 definition.staticValues = Pointer_staticValues;
1457 definition.staticFunctions = Pointer_staticFunctions;
1458 definition.getProperty = &Pointer_getProperty;
1459 definition.setProperty = &Pointer_setProperty;
1460 definition.finalize = &CYFinalize;
1461 Pointer_ = JSClassCreate(&definition);
1462
1463 definition = kJSClassDefinitionEmpty;
1464 definition.className = "Struct";
1465 definition.staticFunctions = Struct_staticFunctions;
1466 definition.getProperty = &Struct_getProperty;
1467 definition.setProperty = &Struct_setProperty;
1468 definition.getPropertyNames = &Struct_getPropertyNames;
1469 definition.finalize = &CYFinalize;
1470 Struct_ = JSClassCreate(&definition);
1471
1472 definition = kJSClassDefinitionEmpty;
1473 definition.className = "Type";
1474 definition.staticFunctions = Type_staticFunctions;
1475 definition.getProperty = &Type_getProperty;
1476 definition.callAsFunction = &Type_callAsFunction;
1477 definition.callAsConstructor = &Type_callAsConstructor;
1478 definition.finalize = &CYFinalize;
1479 Type_privateData::Class_ = JSClassCreate(&definition);
1480
1481 definition = kJSClassDefinitionEmpty;
1482 definition.className = "Runtime";
1483 definition.getProperty = &Runtime_getProperty;
1484 Runtime_ = JSClassCreate(&definition);
1485
1486 definition = kJSClassDefinitionEmpty;
1487 //definition.getProperty = &Global_getProperty;
1488 JSClassRef Global(JSClassCreate(&definition));
1489
1490 JSGlobalContextRef context(JSGlobalContextCreate(Global));
1491 Context_ = context;
1492 JSObjectRef global(CYGetGlobalObject(context));
1493
1494 JSObjectSetPrototype(context, global, JSObjectMake(context, Runtime_, NULL));
1495
1496 Array_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Array")));
1497 JSValueProtect(context, Array_);
1498
1499 Error_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Error")));
1500 JSValueProtect(context, Error_);
1501
1502 Function_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Function")));
1503 JSValueProtect(context, Function_);
1504
1505 String_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("String")));
1506 JSValueProtect(context, String_);
1507
1508 length_ = JSStringCreateWithUTF8CString("length");
1509 message_ = JSStringCreateWithUTF8CString("message");
1510 name_ = JSStringCreateWithUTF8CString("name");
1511 prototype_ = JSStringCreateWithUTF8CString("prototype");
1512 toCYON_ = JSStringCreateWithUTF8CString("toCYON");
1513 toJSON_ = JSStringCreateWithUTF8CString("toJSON");
1514
1515 JSObjectRef Object(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Object"))));
1516 Object_prototype_ = CYCastJSObject(context, CYGetProperty(context, Object, prototype_));
1517 JSValueProtect(context, Object_prototype_);
1518
1519 Array_prototype_ = CYCastJSObject(context, CYGetProperty(context, Array_, prototype_));
1520 Array_pop_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("pop")));
1521 Array_push_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("push")));
1522 Array_splice_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("splice")));
1523
1524 CYSetProperty(context, Array_prototype_, toCYON_, JSObjectMakeFunctionWithCallback(context, toCYON_, &Array_callAsFunction_toCYON), kJSPropertyAttributeDontEnum);
1525
1526 JSValueProtect(context, Array_prototype_);
1527 JSValueProtect(context, Array_pop_);
1528 JSValueProtect(context, Array_push_);
1529 JSValueProtect(context, Array_splice_);
1530
1531 JSObjectRef Functor(JSObjectMakeConstructor(context, Functor_, &Functor_new));
1532
1533 Function_prototype_ = (JSObjectRef) CYGetProperty(context, Function_, prototype_);
1534 JSValueProtect(context, Function_prototype_);
1535
1536 JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Functor, prototype_), Function_prototype_);
1537
1538 CYSetProperty(context, global, CYJSString("Functor"), Functor);
1539 CYSetProperty(context, global, CYJSString("Pointer"), JSObjectMakeConstructor(context, Pointer_, &Pointer_new));
1540 CYSetProperty(context, global, CYJSString("Type"), JSObjectMakeConstructor(context, Type_privateData::Class_, &Type_new));
1541
1542 JSObjectRef cycript(JSObjectMake(context, NULL, NULL));
1543 CYSetProperty(context, global, CYJSString("Cycript"), cycript);
1544 CYSetProperty(context, cycript, CYJSString("gc"), JSObjectMakeFunctionWithCallback(context, CYJSString("gc"), &Cycript_gc_callAsFunction));
1545
1546 CYSetProperty(context, global, CYJSString("$cyq"), JSObjectMakeFunctionWithCallback(context, CYJSString("$cyq"), &$cyq));
1547
1548 System_ = JSObjectMake(context, NULL, NULL);
1549 JSValueProtect(context, System_);
1550
1551 CYSetProperty(context, global, CYJSString("system"), System_);
1552 CYSetProperty(context, System_, CYJSString("args"), CYJSNull(context));
1553 //CYSetProperty(context, System_, CYJSString("global"), global);
1554
1555 CYSetProperty(context, System_, CYJSString("print"), JSObjectMakeFunctionWithCallback(context, CYJSString("print"), &System_print));
1556
1557 Result_ = JSStringCreateWithUTF8CString("_");
1558
1559 // XXX: this is very wrong and sad
1560 #ifdef __APPLE__
1561 CYObjectiveC(context, global);
1562 #endif
1563 }
1564
1565 return Context_;
1566 }