forked from ftk/quickjspp
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathquickjspp.hpp
491 lines (410 loc) · 14.7 KB
/
quickjspp.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
#pragma once
extern "C" {
#include "quickjs/quickjs.h"
#include "quickjs/quickjs-libc.h"
}
#include <algorithm>
#include <tuple>
#include <functional>
#include <unordered_map>
#include <cassert>
#include <memory>
namespace qjs {
namespace detail {
class exception {};
template <typename R>
struct js_traits
{
//static R unwrap(JSContext * ctx, JSValue v);
//static JSValue wrap(JSContext * ctx, R value)
};
// identity
template <>
struct js_traits<JSValue>
{
static JSValue unwrap(JSContext * ctx, JSValue v) noexcept
{
return v;
}
static JSValue wrap(JSContext * ctx, JSValue v) noexcept
{
return v;
}
};
template <>
struct js_traits<int32_t>
{
static int32_t unwrap(JSContext * ctx, JSValue v)
{
int32_t r;
if(JS_ToInt32(ctx, &r, v))
throw exception{};
return r;
}
static JSValue wrap(JSContext * ctx, int32_t i) noexcept
{
return JS_NewInt32(ctx, i);
}
};
/*
template <typename Arg1, typename... Args>
std::tuple<Arg1, Args...> to_tuple_impl(JSContext * ctx, JSValue * argv)
{
if constexpr (sizeof...(Args) == 0)
return std::make_tuple<Arg1>(js_traits<std::decay_t<Arg1>>::unwrap(ctx, *argv));
else // todo:rewrite
return std::tuple_cat(std::make_tuple<Arg1>(js_traits<std::decay_t<Arg1>>::unwrap(ctx, *argv)),
to_tuple_impl<Args...>(ctx, argv + 1));
}
*/
template <class Tuple, std::size_t... I>
Tuple unwrap_args_impl(JSContext * ctx, JSValue * argv, std::index_sequence<I...>)
{
return Tuple{js_traits<std::decay_t<std::tuple_element_t<I, Tuple>>>::unwrap(ctx, argv[I])...};
}
template <typename... Args>
std::tuple<Args...> unwrap_args(JSContext * ctx, JSValue * argv)
{
return unwrap_args_impl<std::tuple<Args...>>(ctx, argv, std::make_index_sequence<sizeof...(Args)>());
}
// free function
template <auto F>
struct fwrapper
{
const char * name = nullptr;
};
template <typename R, typename... Args, R (* F)(Args...)>
struct js_traits<fwrapper<F>>
{
static JSValue wrap(JSContext * ctx, fwrapper<F> fw)
{
return JS_NewCFunction(ctx, [](JSContext * ctx, JSValue this_value, int argc,
JSValue * argv) noexcept -> JSValue {
//if(argc < sizeof...(Args))
//return JS_EXCEPTION;
try
{
if constexpr (std::is_same_v<R, void>)
{
std::apply(F, detail::unwrap_args<Args...>(ctx, argv));
return JS_UNDEFINED;
} else
return js_traits<R>::wrap(ctx,
std::apply(F, detail::unwrap_args<Args...>(ctx, argv))
);
} catch(detail::exception) // todo: inspect exception
{
return JS_EXCEPTION;
}
}, fw.name, sizeof...(Args));
}
};
// class member function
template <typename R, class T, typename... Args, R (T::*F)(Args...)>
struct js_traits<fwrapper<F>>
{
static JSValue wrap(JSContext * ctx, fwrapper<F> fw)
{
return JS_NewCFunction(ctx, [](JSContext * ctx, JSValue this_value, int argc,
JSValue * argv) noexcept -> JSValue {
//if(argc < sizeof...(Args))
//return JS_EXCEPTION;
try
{
const auto& this_sp = js_traits<std::shared_ptr<T>>::unwrap(ctx, this_value);
if constexpr (std::is_same_v<R, void>)
{
std::apply(F, std::tuple_cat(std::make_tuple(this_sp.get()),
detail::unwrap_args<Args...>(ctx, argv)));
return JS_UNDEFINED;
} else
return js_traits<R>::wrap(ctx,
std::apply(F, std::tuple_cat(std::make_tuple(this_sp.get()),
detail::unwrap_args<Args...>(ctx,
argv)))
);
} catch(detail::exception)
{
return JS_EXCEPTION;
}
}, fw.name, sizeof...(Args));
}
};
// class constructor
template <class T, typename... Args>
struct ctor_wrapper
{
const char * name = nullptr;
};
template <class T, typename... Args>
struct js_traits<ctor_wrapper<T, Args...>>
{
static JSValue wrap(JSContext * ctx, ctor_wrapper<T, Args...> cw)
{
return JS_NewCFunction2(ctx, [](JSContext * ctx, JSValue this_value, int argc,
JSValue * argv) noexcept -> JSValue {
try
{
return js_traits<std::shared_ptr<T>>::wrap(ctx,
std::apply(std::make_shared<T, Args...>,
detail::unwrap_args<Args...>(ctx, argv))
);
} catch(detail::exception)
{
return JS_EXCEPTION;
}
}, cw.name, sizeof...(Args), JS_CFUNC_constructor, 0);
}
};
// SP<T> class
template <class T>
struct js_traits<std::shared_ptr<T>>
{
inline static JSClassID QJSClassId;
static void register_class(JSContext * ctx, const char * name, JSValue proto)
{
JSClassDef def{
name,
// destructor
[](JSRuntime * rt, JSValue obj) noexcept {
auto pptr = reinterpret_cast<std::shared_ptr<T> *>(JS_GetOpaque(obj, QJSClassId));
if(!pptr)
{
assert(false && "bad destructor");
}
delete pptr;
}
};
if(QJSClassId == 0)
{
int e = JS_NewClass(JS_GetRuntime(ctx), JS_NewClassID(&QJSClassId), &def);
if(e < 0)
throw exception{};
}
JS_SetClassProto(ctx, QJSClassId, proto);
}
static JSValue wrap(JSContext * ctx, std::shared_ptr<T> ptr)
{
if(QJSClassId == 0) // not registered
throw exception{};
auto pptr = new std::shared_ptr<T>(std::move(ptr));
auto jsobj = JS_NewObjectClass(ctx, QJSClassId);
JS_SetOpaque(jsobj, pptr);
return jsobj;
}
static const std::shared_ptr<T>& unwrap(JSContext * ctx, JSValue v)
{
auto ptr = reinterpret_cast<std::shared_ptr<T> *>(JS_GetOpaque2(ctx, v, QJSClassId));
if(!ptr)
throw exception{};
return *ptr;
}
};
// properties
template <typename Key>
struct js_property_traits
{
// static void set_property(JSContext * ctx, JSValue this_obj, R key, JSValue value)
// static JSValue get_property(JSContext * ctx, JSValue this_obj, R key)
};
template <>
struct js_property_traits<const char *>
{
static void set_property(JSContext * ctx, JSValue this_obj, const char * name, JSValue value)
{
int err = JS_SetPropertyStr(ctx, this_obj, name, value);
if(err < 0)
throw exception{};
}
static JSValue get_property(JSContext * ctx, JSValue this_obj, const char * name) noexcept
{
return JS_GetPropertyStr(ctx, this_obj, name);
}
};
template <typename Key>
struct property_proxy
{
JSContext * ctx;
JSValue this_obj;
Key key;
operator JSValue() const
{
return js_property_traits<Key>::get_property(ctx, this_obj, key);
}
template <typename Value>
property_proxy& operator =(Value value)
{
js_property_traits<Key>::set_property(ctx, this_obj, key,
js_traits<Value>::wrap(ctx, std::move(value)));
return *this;
}
};
}
class Value
{
public:
JSValue v;
JSContext * ctx = nullptr;
public:
template <typename T>
Value(JSContext * ctx, T val) : ctx(ctx)
{
v = detail::js_traits<T>::wrap(ctx, val);
}
Value(const Value& rhs)
{
ctx = rhs.ctx;
v = JS_DupValue(ctx, rhs.v);
}
Value(Value&& rhs)
{
std::swap(ctx, rhs.ctx);
v = rhs.v;
}
~Value()
{
if(ctx) JS_FreeValue(ctx, v);
}
template <typename T>
T cast() const
{
return detail::js_traits<T>::unwrap(ctx, v);
}
JSValue release() // dont call freevalue
{
ctx = nullptr;
return v;
}
operator JSValue()&&
{
return release();
}
// access properties
template <typename Key>
detail::property_proxy<Key> operator [](Key key)
{
return {ctx, v, std::move(key)};
}
};
class Runtime
{
public:
JSRuntime * rt;
Runtime()
{
rt = JS_NewRuntime();
if(!rt)
throw detail::exception{};
}
Runtime(const Runtime&) = delete;
~Runtime()
{
JS_FreeRuntime(rt);
}
};
class Context
{
public:
JSContext * ctx;
class Module
{
friend class Context;
JSModuleDef * m;
JSContext * ctx;
const char * name;
std::vector<std::pair<const char *, JSValue>> exports;
public:
Module(JSContext * ctx, const char * name) : ctx(ctx), name(name)
{
m = JS_NewCModule(ctx, name, [](JSContext * ctx, JSModuleDef * m) noexcept {
auto context = reinterpret_cast<Context *>(JS_GetContextOpaque(ctx));
if(!context)
return -1;
auto it = std::find_if(context->modules.cbegin(), context->modules.cend(),
[m](const Module& module) { return module.m == m; });
if(it == context->modules.end())
return -1;
for(const auto& e : it->exports)
{
if(JS_SetModuleExport(ctx, m, e.first, e.second) != 0)
return -1;
}
return 0;
});
if(!m)
throw detail::exception{};
}
Module& add(const char * name, JSValue value)
{
exports.push_back({name, value});
JS_AddModuleExport(ctx, m, name);
return *this;
}
Module& add(const char * name, Value value)
{
return add(name, value.release());
}
template <typename T>
Module& add(const char * name, T value)
{
return add(name, detail::js_traits<T>::wrap(ctx, std::move(value)));
}
//Module(const Module&) = delete;
};
std::vector<Module> modules;
private:
public:
Context(Runtime& rt) : Context(rt.rt)
{}
Context(JSRuntime * rt)
{
ctx = JS_NewContext(rt);
if(!ctx)
throw detail::exception{};
JS_SetContextOpaque(ctx, this);
}
Context(JSContext * ctx) : ctx{ctx}
{
JS_SetContextOpaque(ctx, this);
}
Context(const Context&) = delete;
~Context()
{
JS_FreeContext(ctx);
}
Module& addModule(const char * name)
{
modules.emplace_back(ctx, name);
return modules.back();
}
Value global()
{
return Value{ctx, JS_GetGlobalObject(ctx)};
}
Value newObject()
{
return Value{ctx, JS_NewObject(ctx)};
}
template <class T>
void registerClass(const char * name, JSValue proto)
{
detail::js_traits<std::shared_ptr<T>>::register_class(ctx, name, proto);
}
Value eval(std::string_view buffer, const char * filename, unsigned eval_flags = 0)
{
JSValue v = JS_Eval(ctx, buffer.data(), buffer.size(), filename, eval_flags);
//if(JS_IsException(v))
//throw detail::exception{};
return Value{ctx, v};
}
Value evalFile(const char * filename, unsigned eval_flags = 0)
{
size_t buf_len;
auto deleter = [this](void * p) { js_free(ctx, p); };
auto buf = std::unique_ptr<uint8_t, decltype(deleter)>{js_load_file(ctx, &buf_len, filename), deleter};
if(!buf)
throw std::runtime_error{std::string{"evalFile: can't read file: "} + filename};
return eval({reinterpret_cast<char *>(buf.get()), buf_len}, filename, eval_flags);
}
};
}