Skip to content
Navigation Menu
{{ message }}
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJscEngine.hpp
More file actions
374 lines (314 loc) · 13.7 KB
/
Copy pathJscEngine.hpp
File metadata and controls
374 lines (314 loc) · 13.7 KB
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
#pragma once
#include <type_traits>
#include "../../src/Native.h"
#include "../../src/Scope.h"
#include "../../src/Utils.h"
#include "../../src/utils/Helper.hpp"
#include "JscEngine.h"
#include "JscHelper.hpp"
#include "JscReference.hpp"
namespace script::jsc_backend {
template <typename T>
bool JscEngine::registerNativeClassImpl(const ClassDefine<T>* classDefine) {
Tracer traceRegister(this, classDefine->className);
internal::validateClassDefine(classDefine);
Local<Value> object;
ClassRegistryData registry{};
if (classDefine->instanceDefine.constructor) {
// make it constexpr if, save some binary size
if constexpr (!std::is_same_v<T, void>) {
defineInstance(classDefine, object, registry);
} else {
// validateClassDefine will make sure this won't happen
std::terminate();
}
} else {
object = Object::newObject();
}
registerStaticDefine(classDefine->staticDefine, object.asObject());
auto ns = ::script::internal::getNamespaceObject(this, classDefine->getNameSpace(), getGlobal())
.asObject();
ns.set(classDefine->className, object);
classRegistry_.emplace(const_cast<ClassDefine<T>*>(classDefine), registry);
return true;
}
template <typename T>
void JscEngine::defineInstance(const ClassDefine<T>* classDefine, Local<Value>& object,
JscEngine::ClassRegistryData& registry) {
JSClassDefinition instanceDefine = kJSClassDefinitionEmpty;
instanceDefine.attributes = kJSClassAttributeNone;
instanceDefine.className = classDefine->className.c_str();
instanceDefine.finalize = [](JSObjectRef thiz) {
auto* t = static_cast<ScriptClass*>(JSObjectGetPrivate(thiz));
auto engine = script::internal::scriptDynamicCast<JscEngine*>(t->getScriptEngine());
if (!engine->isDestroying()) {
utils::Message dtor([](auto& msg) {},
[](auto& msg) { delete static_cast<ScriptClass*>(msg.ptr0); });
dtor.tag = engine;
dtor.ptr0 = t;
engine->messageQueue()->postMessage(dtor);
} else {
delete t;
}
};
auto clazz = JSClassCreate(&instanceDefine);
registry.instanceClass = clazz;
JSClassDefinition staticDefine = kJSClassDefinitionEmpty;
staticDefine.callAsConstructor = createConstructor<T>();
staticDefine.hasInstance = [](JSContextRef ctx, JSObjectRef constructor,
JSValueRef possibleInstance, JSValueRef* exception) -> bool {
auto engine = static_cast<JscEngine*>(JSObjectGetPrivate(JSContextGetGlobalObject(ctx)));
auto def = static_cast<ClassDefine<T>*>(JSObjectGetPrivate(constructor));
return engine->isInstanceOfImpl(make<Local<Value>>(possibleInstance), def);
};
auto staticClass = JSClassCreate(&staticDefine);
object =
Local<Object>(JSObjectMake(context_, staticClass, const_cast<ClassDefine<T>*>(classDefine)));
// not used anymore
JSClassRelease(staticClass);
registry.constructor = object.asObject();
auto prototype = defineInstancePrototype(classDefine);
object.asObject().set("prototype", prototype);
registry.prototype = prototype;
}
template <typename T>
JSObjectCallAsConstructorCallback JscEngine::createConstructor() {
return [](JSContextRef ctx, JSObjectRef constructor, size_t argumentCount,
const JSValueRef arguments[], JSValueRef* exception) {
auto engine = static_cast<JscEngine*>(JSObjectGetPrivate(JSContextGetGlobalObject(ctx)));
auto def = static_cast<ClassDefine<T>*>(JSObjectGetPrivate(constructor));
Tracer trace(engine, def->className);
auto it = engine->classRegistry_.find(def);
assert(it != engine->classRegistry_.end());
ClassRegistryData& registry = it->second;
auto object = JSObjectMake(ctx, registry.instanceClass, nullptr);
auto callbackInfo = newArguments(engine, object, arguments, argumentCount);
try {
StackFrameScope stack;
T* thiz;
if (argumentCount == 2 && engine->isConstructorMarkSymbol(arguments[0]) &&
JSValueIsObjectOfClass(engine->context_, arguments[1], externalClass_)) {
// this logic is for
// ScriptClass::ScriptClass(const ClassDefine<T> &define)
auto obj = JSValueToObject(engine->context_, arguments[1], exception);
checkException(*exception);
thiz = static_cast<T*>(JSObjectGetPrivate(obj));
} else {
// this logic is for
// ScriptClass::ScriptClass(const Local<Object>& thiz)
thiz = def->instanceDefine.constructor(callbackInfo);
}
if (thiz) {
thiz->internalState_.classDefine = def;
JSObjectSetPrivate(object, thiz);
JSObjectSetPrototype(ctx, object,
toJsc(engine->context_, registry.prototype.get().asValue()));
return object;
} else {
throw Exception("constructor returns null");
}
} catch (Exception& e) {
*exception = toJsc(engine->context_, e.exception());
// can't return undefined, just return empty object;
return object;
}
};
}
template <typename T>
Local<Object> JscEngine::defineInstancePrototype(const ClassDefine<T>* classDefine) {
Local<Object> proto = Object::newObject();
defineInstanceFunction(classDefine, proto);
if (!classDefine->instanceDefine.properties.empty()) {
auto jsObject = getGlobal().get("Object").asObject();
auto jsObject_def = jsObject.get("defineProperty").asFunction();
auto get = String::newString("get");
auto set = String::newString("set");
defineInstanceProperties(classDefine, [&get, &set, &jsObject, &jsObject_def, &proto](
const Local<String>& name, const Local<Value>& getter,
const Local<Value>& setter) {
auto desc = Object::newObject();
if (!getter.isNull()) desc.set(get, getter);
if (!setter.isNull()) desc.set(set, setter);
// set prop to prototype
jsObject_def.call(jsObject, {proto, name, desc});
});
}
return proto;
}
template <typename T>
void JscEngine::defineInstanceFunction(const ClassDefine<T>* classDefine,
Local<Object>& prototypeObject) {
struct ContextData {
typename internal::InstanceDefine<T>::FunctionDefine* functionDefine;
JscEngine* engine;
const ClassDefine<T>* classDefine;
};
for (auto& f : classDefine->instanceDefine.functions) {
StackFrameScope stack;
JSClassDefinition jsFunc = kJSClassDefinitionEmpty;
jsFunc.className = "anonymous";
jsFunc.callAsFunction = [](JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject,
size_t argumentCount, const JSValueRef arguments[],
JSValueRef* exception) {
auto data = static_cast<ContextData*>(JSObjectGetPrivate(function));
auto fp = data->functionDefine;
auto engine = data->engine;
auto def = data->classDefine;
auto& callback = fp->callback;
Tracer trace(engine, fp->traceName);
auto args = newArguments(engine, thisObject, arguments, argumentCount);
try {
auto* t = static_cast<T*>(JSObjectGetPrivate(thisObject));
if (!t || t->internalState_.classDefine != def) {
throw Exception(u8"call function on wrong receiver");
}
auto returnVal = callback(t, args);
return toJsc(engine->context_, returnVal);
} catch (Exception& e) {
*exception = jsc_backend::JscEngine::toJsc(engine->context_, e.exception());
return JSValueMakeUndefined(currentEngineContextChecked());
}
};
jsFunc.finalize = [](JSObjectRef function) {
delete static_cast<ContextData*>(JSObjectGetPrivate(function));
};
auto funcClazz = JSClassCreate(&jsFunc);
Local<Function> funcObj(JSObjectMake(
currentEngineContextChecked(), funcClazz,
new ContextData{const_cast<typename internal::InstanceDefine<T>::FunctionDefine*>(&f), this,
classDefine}));
// not used anymore
JSClassRelease(funcClazz);
auto name = String::newString(f.name);
prototypeObject.set(name, funcObj);
}
}
template <typename T, typename ConsumeLambda>
void JscEngine::defineInstanceProperties(const ClassDefine<T>* classDefine,
ConsumeLambda consumerLambda) {
struct ContextData {
typename internal::InstanceDefine<T>::PropertyDefine* propertyDefine;
JscEngine* engine;
const ClassDefine<T>* classDefine;
};
for (auto& p : classDefine->instanceDefine.properties) {
StackFrameScope stack;
Local<Value> getter;
Local<Value> setter;
if (p.getter) {
JSClassDefinition jsFunc = kJSClassDefinitionEmpty;
jsFunc.className = "getter";
jsFunc.callAsFunction = [](JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject,
size_t argumentCount, const JSValueRef arguments[],
JSValueRef* exception) {
auto data = static_cast<ContextData*>(JSObjectGetPrivate(function));
auto pp = data->propertyDefine;
auto engine = data->engine;
auto def = data->classDefine;
Tracer trace(engine, pp->traceName);
try {
auto* t = static_cast<T*>(JSObjectGetPrivate(thisObject));
if (!t || t->internalState_.classDefine != def) {
throw Exception(u8"call function on wrong receiver");
}
auto value = (pp->getter)(t);
return toJsc(engine->context_, value);
} catch (Exception& e) {
*exception = jsc_backend::JscEngine::toJsc(engine->context_, e.exception());
return JSValueMakeUndefined(engine->context_);
}
};
jsFunc.finalize = [](JSObjectRef function) {
delete static_cast<ContextData*>(JSObjectGetPrivate(function));
};
auto funcClazz = JSClassCreate(&jsFunc);
getter = Local<Function>(JSObjectMake(
currentEngineContextChecked(), funcClazz,
new ContextData{const_cast<typename internal::InstanceDefine<T>::PropertyDefine*>(&p),
this, classDefine}));
JSClassRelease(funcClazz);
}
if (p.setter) {
JSClassDefinition jsFunc = kJSClassDefinitionEmpty;
jsFunc.className = "setter";
jsFunc.callAsFunction = [](JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject,
size_t argumentCount, const JSValueRef arguments[],
JSValueRef* exception) {
auto data = static_cast<ContextData*>(JSObjectGetPrivate(function));
auto pp = data->propertyDefine;
auto engine = data->engine;
auto def = data->classDefine;
Tracer trace(engine, pp->traceName);
auto args = newArguments(engine, thisObject, arguments, argumentCount);
if (args.size() > 0) {
try {
auto* t = static_cast<T*>(JSObjectGetPrivate(thisObject));
if (!t || t->internalState_.classDefine != def) {
throw Exception(u8"call function on wrong receiver");
}
(pp->setter)(t, args[0]);
} catch (Exception& e) {
*exception = jsc_backend::JscEngine::toJsc(engine->context_, e.exception());
}
}
return JSValueMakeUndefined(engine->context_);
};
jsFunc.finalize = [](JSObjectRef function) {
delete static_cast<ContextData*>(JSObjectGetPrivate(function));
};
auto funcClazz = JSClassCreate(&jsFunc);
setter = Local<Function>(JSObjectMake(
context_, funcClazz,
new ContextData{const_cast<typename internal::InstanceDefine<T>::PropertyDefine*>(&p),
this, classDefine}));
JSClassRelease(funcClazz);
}
consumerLambda(String::newString(p.name), getter, setter);
}
}
template <typename T>
Local<Object> JscEngine::newNativeClassImpl(const ClassDefine<T>* classDefine, size_t size,
const Local<Value>* args) {
auto it = classRegistry_.find(const_cast<ClassDefine<T>*>(classDefine));
if (it == classRegistry_.end()) {
registerNativeClassImpl(classDefine);
it = classRegistry_.find(const_cast<ClassDefine<T>*>(classDefine));
}
if (it != classRegistry_.end() && !it->second.constructor.isEmpty()) {
return jsc_backend::toJscValues<Local<Object>>(
context_, size, args, [this, &it, size](JSValueRef* array) {
JSValueRef jscException = nullptr;
Local<Value> ret(JSObjectCallAsConstructor(
context_, toJsc(context_, it->second.constructor.get()), size, array, &jscException));
jsc_backend::JscEngine::checkException(jscException);
return ret.asObject();
});
}
throw Exception("can't create native class");
}
template <typename T>
bool JscEngine::isInstanceOfImpl(const Local<Value>& value, const ClassDefine<T>* classDefine) {
if (!value.isObject()) return false;
auto it = classRegistry_.find(const_cast<ClassDefine<T>*>(classDefine));
if (it != classRegistry_.end() && !it->second.constructor.isEmpty()) {
return JSValueIsObjectOfClass(context_, toJsc(context_, value), it->second.instanceClass);
}
return false;
}
template <typename T>
T* JscEngine::getNativeInstanceImpl(const Local<Value>& value, const ClassDefine<T>* classDefine) {
if (value.isObject() && isInstanceOfImpl(value, classDefine)) {
return reinterpret_cast<T*>(JSObjectGetPrivate(value.asObject().val_));
}
return nullptr;
}
inline typename RefTypeMap<Value>::jscType JscEngine::toJsc(JSGlobalContextRef context,
const Local<Value>& ref) {
if (ref.isNull()) {
return Local<Value>(
const_cast<typename Local<Value>::InternalLocalRef>(JSValueMakeUndefined(context)))
.val_;
}
return ref.val_;
}
} // namespace script::jsc_backend
You can’t perform that action at this time.
