12#include "common/config.h"
22#if defined(EVENGINE_ANDROID)
23#include <android/log.h>
29thread_local std::vector<Runtime*> runtime_stack;
31#if defined(EVENGINE_ANDROID)
32void androidScriptPrint(
HSQUIRRELVM,
const SQChar* format, ...) {
34 va_start(args, format);
35 __android_log_vprint(ANDROID_LOG_INFO,
"EVEngine", format, args);
39void androidScriptError(
HSQUIRRELVM,
const SQChar* format, ...) {
41 va_start(args, format);
42 __android_log_vprint(ANDROID_LOG_ERROR,
"EVEngine", format, args);
59 switch (sq_gettype(
vm,
index)) {
60 case OT_NULL:
return "null";
62 SQBool
value = SQFalse;
78 const SQChar*
value =
nullptr;
89 switch (sq_gettype(
vm,
index)) {
91 SQBool
value = SQFalse;
93 out.kind = ReflectedValueKind::Bool;
101 out.kind = ReflectedValueKind::Integer;
109 out.kind = ReflectedValueKind::Float;
115 const SQChar*
value =
nullptr;
117 out.kind = ReflectedValueKind::String;
122 case OT_ARRAY:
out.kind = ReflectedValueKind::Array;
break;
123 case OT_TABLE:
out.kind = ReflectedValueKind::Table;
break;
124 case OT_INSTANCE:
out.kind = ReflectedValueKind::Instance;
break;
126 default:
out.kind = ReflectedValueKind::Other;
break;
132int64_t valueToInteger(
const ReflectedValue&
value) {
133 switch (
value.kind) {
134 case ReflectedValueKind::Integer:
return value.integer;
135 case ReflectedValueKind::Float:
return static_cast<int64_t
>(
value.floating);
136 case ReflectedValueKind::Bool:
return value.boolean ? 1 : 0;
137 case ReflectedValueKind::String: {
139 const long long parsed = std::strtoll(
value.text.c_str(), &
end, 10);
140 return (
end &&
end !=
value.text.c_str()) ?
static_cast<int64_t
>(parsed) : 0;
147double valueToDouble(
const ReflectedValue&
value) {
148 switch (
value.kind) {
149 case ReflectedValueKind::Integer:
return static_cast<double>(
value.integer);
150 case ReflectedValueKind::Float:
return value.floating;
151 case ReflectedValueKind::Bool:
return value.boolean ? 1.0 : 0.0;
152 case ReflectedValueKind::String: {
154 const double parsed = std::strtod(
value.text.c_str(), &
end);
155 return (
end &&
end !=
value.text.c_str()) ? parsed : 0.0;
162bool valueToBool(
const ReflectedValue&
value) {
163 switch (
value.kind) {
164 case ReflectedValueKind::Bool:
return value.boolean;
165 case ReflectedValueKind::Integer:
return value.integer != 0;
166 case ReflectedValueKind::Float:
return value.floating != 0.0;
167 case ReflectedValueKind::String:
168 return value.text ==
"true" ||
value.text ==
"1";
169 default:
return false;
174std::string valueToText(
const ReflectedValue&
value) {
175 switch (
value.kind) {
176 case ReflectedValueKind::String:
return value.text;
177 case ReflectedValueKind::Bool:
return value.boolean ?
"true" :
"false";
178 case ReflectedValueKind::Integer:
return std::to_string(
value.integer);
179 case ReflectedValueKind::Float: {
190void pushConvertedValue(
HSQUIRRELVM v, SQObjectType currentType,
191 const ReflectedValue&
value) {
192 switch (currentType) {
194 sq_pushbool(
v, valueToBool(
value) ? SQTrue : SQFalse);
197 sq_pushinteger(
v,
static_cast<SQInteger
>(valueToInteger(
value)));
200 sq_pushfloat(
v,
static_cast<SQFloat
>(valueToDouble(
value)));
203 const std::string
text = valueToText(
value);
204 sq_pushstring(
v,
text.c_str(),
static_cast<SQInteger
>(
text.size()));
209 switch (
value.kind) {
210 case ReflectedValueKind::Bool:
211 sq_pushbool(
v,
value.asBool() ? SQTrue : SQFalse);
213 case ReflectedValueKind::Integer:
214 sq_pushinteger(
v, SQInteger(
value.asInt()));
216 case ReflectedValueKind::Float:
217 sq_pushfloat(
v, SQFloat(
value.asFloat()));
219 case ReflectedValueKind::String:
220 sq_pushstring(
v,
value.asString().c_str(), -1);
229std::vector<ReflectedMember> collectClassMembersFromStack(
HSQUIRRELVM squirrel,
230 SQInteger classIndex) {
231 std::vector<ReflectedMember>
members;
232 const SQInteger
top = sq_gettop(squirrel);
233 sq_push(squirrel, classIndex);
234 sq_pushnull(squirrel);
235 while (SQ_SUCCEEDED(sq_next(squirrel, -2))) {
236 if (sq_gettype(squirrel, -2) != OT_STRING) {
240 const SQChar* memberName =
nullptr;
241 if (!SQ_SUCCEEDED(sq_getstring(squirrel, -2, &memberName)) || !memberName) {
247 member.type =
static_cast<ssq::Type
>(sq_gettype(squirrel, -1));
249 member.type == ssq::Type::NATIVECLOSURE;
253 const SQInteger memberTop = sq_gettop(squirrel);
254 sq_push(squirrel, -2);
255 if (SQ_SUCCEEDED(sq_getattributes(squirrel, -5)) &&
256 sq_gettype(squirrel, -1) == OT_TABLE) {
257 sq_pushnull(squirrel);
258 while (SQ_SUCCEEDED(sq_next(squirrel, -2))) {
259 if (sq_gettype(squirrel, -2) == OT_STRING) {
260 const SQChar* attributeName =
nullptr;
261 if (SQ_SUCCEEDED(sq_getstring(squirrel, -2, &attributeName)) &&
266 static_cast<ssq::Type
>(sq_gettype(squirrel, -1));
267 attribute.value = valueString(squirrel, -1);
274 sq_settop(squirrel, memberTop);
275 std::sort(
member.attributes.begin(),
member.attributes.end(),
276 [](
const ReflectedAttribute&
a,
const ReflectedAttribute&
b) {
277 return a.name < b.name;
282 sq_settop(squirrel,
top);
284 [](
const ReflectedMember&
a,
const ReflectedMember&
b) {
285 return a.name < b.name;
290SQUserPointer objectIdentity(
const HSQOBJECT&
object) {
291 return reinterpret_cast<SQUserPointer
>(
object._unVal.pRefCounted);
294std::unique_ptr<ssq::VM> createVm(
size_t stackSize, ssq::Libs::Flag libraries) {
298 EV_PARAM_CHECK(stackSize > 0,
"Runtime stack size must be positive");
299 auto vm = std::make_unique<ssq::VM>(stackSize, libraries);
300#if defined(EVENGINE_ANDROID)
304 vm->setPrintFunc(&androidScriptPrint, &androidScriptError);
323 sq_enabledebuginfo(
vm, SQTrue);
326 sq_notifyallexceptions(
vm, SQTrue);
327 sq_newclosure(
vm, &scriptErrorHook, 0);
328 sq_seterrorhandler(
vm);
343 :
std::runtime_error([&] {
344 std::ostringstream
out;
345 out <<
"Script " << stageName(
stage);
351 stage_(stage), source_(std::move(
source)), script_id_(scriptId) {}
355 :
std::runtime_error([&] {
356 std::ostringstream
out;
357 out <<
"Script " << stageName(
stage);
364 source_(std::move(
source)),
365 script_id_(scriptId),
371 if (!stack_trace_.empty() && stack_trace_.back() ==
'\n') stack_trace_.pop_back();
387 return static_cast<float>(
value);
404 const std::string& def)
const {
410 std::vector<std::string>
options;
415 const size_t comma = rest.find(
',');
416 std::string piece = comma == std::string::npos ? rest : rest.substr(0, comma);
417 const size_t first = piece.find_first_not_of(
" \t\r\n");
418 const size_t last = piece.find_last_not_of(
" \t\r\n");
419 if (
first != std::string::npos)
421 if (comma == std::string::npos)
break;
422 rest = rest.substr(comma + 1);
428 : vm_(runtime.handle()), top_(vm_ ? sq_gettop(vm_) : 0) {}
431 if (vm_) sq_settop(vm_, top_);
435 : vm_(std::exchange(other.vm_,
nullptr)), top_(other.top_) {}
438 if (
this == &other)
return *
this;
439 if (vm_) sq_settop(vm_, top_);
440 vm_ = std::exchange(other.vm_,
nullptr);
448 if (!runtime_)
return;
449 auto it = std::find(runtime_stack.rbegin(), runtime_stack.rend(), runtime_);
450 if (it != runtime_stack.rend()) runtime_stack.erase(std::next(it).base());
454 : runtime_(std::exchange(other.runtime_,
nullptr)) {}
457 : vm_(createVm(stackSize, libraries)) {
458 script_modules_ = std::make_unique<script::ScriptModuleResolver>(
handle());
459 script_modules_->registerDefaultProviders();
460 script_compiler_ = std::make_unique<script::ScriptCompiler>(*vm_, *script_modules_);
461 installErrorHandler();
467 if (initialized_)
return;
469 auto stack =
guard();
473 table(
"eve").addFunc(
"lastScriptError", [
this]() {
477 }
catch (
const std::exception&
error) {
483void Runtime::installErrorHandler() {
489 if (shutting_down_ || stopped_)
return;
490 shutting_down_ =
true;
501 auto it = std::find(runtime_stack.begin(), runtime_stack.end(),
this);
502 if (it == runtime_stack.end())
break;
503 runtime_stack.erase(it);
506 class_owners_.clear();
507 class_identities_.clear();
508 initialized_ =
false;
509 script_compiler_.reset();
510 script_modules_.reset();
516 shutting_down_ =
false;
525 return *script_modules_;
529ssq::Table
Runtime::root()
const {
return ssq::Table(
static_cast<const ssq::Object&
>(*vm_)); }
531 const bool validName =
name !=
nullptr &&
name[0] !=
'\0';
532 EV_PARAM_CHECK(validName,
"table name must not be null or empty");
533 return ssq::Table(vm_->find(
name));
537 return runtime_stack.empty() ? nullptr : runtime_stack.back();
545 auto stack =
guard();
546 const ScriptId id = next_script_id_++;
547 auto record = std::make_unique<ScriptRecord>();
549 record->info.source = sourceName;
552 record->compiled = std::make_unique<ssq::Script>(
553 script_compiler_->compileSource(
record->source_text, sourceName));
554 auto [it, inserted] = scripts_.emplace(
id, std::move(
record));
556 notifyLifecycle(it->second->info);
558 }
catch (
const std::exception&
error) {
565 const bool validPath = !
path.empty();
569 auto stack =
guard();
570 const ScriptId id = next_script_id_++;
571 auto record = std::make_unique<ScriptRecord>();
577 record->compiled = std::make_unique<ssq::Script>(script_compiler_->compileFile(
path));
578 auto [it, inserted] = scripts_.emplace(
id, std::move(
record));
580 notifyLifecycle(it->second->info);
582 }
catch (
const std::exception&
error) {
589 auto found = scripts_.find(
id);
590 if (
found == scripts_.end())
597 auto stack =
guard();
598 const auto before = rootClasses();
600 record.info.error.clear();
601 notifyLifecycle(
record.info);
603 script_modules_->instantiateDependencies(
record.info.source);
610 sq_pushobject(
vm,
record.compiled->getRaw());
611 sq_pushroottable(
vm);
612 const SQRESULT
result = sq_call(
vm, 1, SQFalse, SQTrue);
618 discoverClasses(
record, before);
623 notifyLifecycle(
record.info);
626 discoverClasses(
record, before);
628 notifyLifecycle(
record.info);
632 }
catch (
const std::exception&
error) {
634 discoverClasses(
record, before);
639 notifyLifecycle(
record.info);
657 const bool validName = !
name.empty();
658 EV_PARAM_CHECK(validName,
"reflected class name must not be empty");
660 auto stack =
guard();
662 ssq::Class
cls = vm_->findClass(
name.c_str());
664 return classes_.at(
name);
665 }
catch (
const std::exception&
error) {
671 const bool validName = !
name.empty();
672 EV_PARAM_CHECK(validName,
"instance class name must not be empty");
674 auto stack =
guard();
677 const SQInteger
top = sq_gettop(squirrel);
678 sq_pushroottable(squirrel);
679 sq_pushstring(squirrel,
name.c_str(), -1);
680 if (SQ_FAILED(sq_get(squirrel, -2)) ||
681 sq_gettype(squirrel, -1) != OT_CLASS) {
682 sq_settop(squirrel,
top);
687 sq_createinstance(squirrel, -1);
688 ssq::Object instance(squirrel);
689 sq_getstackobj(squirrel, -1, &instance.getRaw());
690 sq_addref(squirrel, &instance.getRaw());
692 sq_pushobject(squirrel, instance.getRaw());
693 sq_pushstring(squirrel,
"constructor", -1);
694 if (SQ_SUCCEEDED(sq_get(squirrel, -2)) &&
695 (sq_gettype(squirrel, -1) == OT_CLOSURE ||
696 sq_gettype(squirrel, -1) == OT_NATIVECLOSURE)) {
698 sq_pushobject(squirrel, instance.getRaw());
699 if (SQ_FAILED(sq_call(squirrel, 1, SQTrue, SQTrue))) {
702 sq_settop(squirrel,
top);
706 sq_settop(squirrel,
top);
711 std::vector<ReflectedMember>
members;
712 if (instance.getType() != ssq::Type::INSTANCE)
return members;
715 auto stack = self->
guard();
717 const SQInteger
top = sq_gettop(squirrel);
721 sq_pushobject(squirrel, instance.getRaw());
722 if (SQ_FAILED(sq_getclass(squirrel, -1)) || sq_gettype(squirrel, -1) != OT_CLASS) {
723 sq_settop(squirrel,
top);
726 while (sq_gettype(squirrel, -1) == OT_CLASS) {
727 const SQInteger classTop = sq_gettop(squirrel);
730 const SQInteger readTop = sq_gettop(squirrel);
731 sq_pushobject(squirrel, instance.getRaw());
732 sq_pushstring(squirrel,
member.name.c_str(), -1);
733 if (SQ_SUCCEEDED(sq_get(squirrel, -2)))
734 member.value = valueFromStack(squirrel, -1);
735 sq_settop(squirrel, readTop);
741 *existing = std::move(
member);
745 sq_settop(squirrel, classTop);
747 if (!SQ_SUCCEEDED(sq_getbase(squirrel, -1)) ||
748 sq_gettype(squirrel, -1) != OT_CLASS) {
749 sq_settop(squirrel,
top);
752 sq_remove(squirrel, -2);
758 const std::string&
name)
const {
759 if (
name.empty())
return {};
762 auto stack = self->
guard();
764 sq_pushobject(squirrel, instance.getRaw());
765 sq_pushstring(squirrel,
name.c_str(), -1);
766 if (SQ_FAILED(sq_get(squirrel, -2))) {
775 if (
name.empty() ||
value.empty())
return false;
778 auto stack = self->
guard();
780 sq_pushobject(squirrel, instance.getRaw());
781 sq_pushstring(squirrel,
name.c_str(), -1);
782 if (SQ_FAILED(sq_get(squirrel, -2))) {
785 const SQObjectType currentType = sq_gettype(squirrel, -1);
787 if (currentType == OT_CLOSURE || currentType == OT_NATIVECLOSURE ||
788 currentType == OT_CLASS) {
791 sq_pushstring(squirrel,
name.c_str(), -1);
792 switch (currentType) {
794 sq_pushbool(squirrel, valueToBool(
value) ? SQTrue : SQFalse);
797 sq_pushinteger(squirrel,
static_cast<SQInteger
>(valueToInteger(
value)));
800 sq_pushfloat(squirrel,
static_cast<SQFloat
>(valueToDouble(
value)));
803 const std::string
text = valueToText(
value);
804 sq_pushstring(squirrel,
text.c_str(),
static_cast<SQInteger
>(
text.size()));
809 switch (
value.kind) {
810 case ReflectedValueKind::Bool:
811 sq_pushbool(squirrel,
value.asBool() ? SQTrue : SQFalse);
813 case ReflectedValueKind::Integer:
814 sq_pushinteger(squirrel, SQInteger(
value.asInt()));
816 case ReflectedValueKind::Float:
817 sq_pushfloat(squirrel, SQFloat(
value.asFloat()));
819 case ReflectedValueKind::String:
820 sq_pushstring(squirrel,
value.asString().c_str(), -1);
822 default: sq_pushnull(squirrel);
break;
828 const bool ok = SQ_SUCCEEDED(sq_set(squirrel, -3));
833 const std::string&
name)
const {
834 if (
name.empty())
return {};
837 auto stack = self->
guard();
839 sq_pushobject(squirrel, instance.getRaw());
840 sq_pushstring(squirrel,
name.c_str(), -1);
841 if (SQ_FAILED(sq_get(squirrel, -2)) ||
842 sq_gettype(squirrel, -1) != OT_INSTANCE) {
845 ssq::Object
out(squirrel);
846 sq_getstackobj(squirrel, -1, &
out.getRaw());
847 sq_addref(squirrel, &
out.getRaw());
852 const std::string&
name)
const {
855 auto stack = self->
guard();
857 sq_pushobject(squirrel, instance.getRaw());
858 sq_pushstring(squirrel,
name.c_str(), -1);
859 if (SQ_FAILED(sq_get(squirrel, -2)) ||
860 sq_gettype(squirrel, -1) != OT_ARRAY) {
863 const SQInteger len = sq_getsize(squirrel, -1);
864 return len > 0 ? size_t(len) : 0;
868 const std::string&
name,
size_t index)
const {
871 auto stack = self->
guard();
873 sq_pushobject(squirrel, instance.getRaw());
874 sq_pushstring(squirrel,
name.c_str(), -1);
875 if (SQ_FAILED(sq_get(squirrel, -2)) ||
876 sq_gettype(squirrel, -1) != OT_ARRAY) {
879 sq_pushinteger(squirrel,
static_cast<SQInteger
>(
index));
880 if (SQ_FAILED(sq_get(squirrel, -2))) {
891 auto stack = self->
guard();
893 sq_pushobject(squirrel, instance.getRaw());
894 sq_pushstring(squirrel,
name.c_str(), -1);
895 if (SQ_FAILED(sq_get(squirrel, -2)) ||
896 sq_gettype(squirrel, -1) != OT_ARRAY) {
899 sq_pushinteger(squirrel,
static_cast<SQInteger
>(
index));
900 if (SQ_FAILED(sq_get(squirrel, -2))) {
903 const SQObjectType currentType = sq_gettype(squirrel, -1);
905 sq_pushinteger(squirrel,
static_cast<SQInteger
>(
index));
906 pushConvertedValue(squirrel, currentType,
value);
907 const bool ok = SQ_SUCCEEDED(sq_set(squirrel, -3));
915 auto stack = self->
guard();
917 sq_pushobject(squirrel, instance.getRaw());
918 sq_pushstring(squirrel,
name.c_str(), -1);
919 if (SQ_FAILED(sq_get(squirrel, -2)) ||
920 sq_gettype(squirrel, -1) != OT_ARRAY) {
923 pushConvertedValue(squirrel, OT_NULL,
value);
924 const bool ok = SQ_SUCCEEDED(sq_arrayappend(squirrel, -2));
929 size_t index)
const {
932 auto stack = self->
guard();
934 sq_pushobject(squirrel, instance.getRaw());
935 sq_pushstring(squirrel,
name.c_str(), -1);
936 if (SQ_FAILED(sq_get(squirrel, -2)) ||
937 sq_gettype(squirrel, -1) != OT_ARRAY) {
941 sq_pushstring(squirrel,
"remove", -1);
942 if (SQ_FAILED(sq_get(squirrel, -2))) {
945 sq_push(squirrel, -2);
946 sq_pushinteger(squirrel,
static_cast<SQInteger
>(
index));
947 const bool ok = SQ_SUCCEEDED(sq_call(squirrel, 2, SQFalse, SQTrue));
952 const std::string&
name)
const {
953 std::vector<std::string> keys;
956 auto stack = self->
guard();
958 sq_pushobject(squirrel, instance.getRaw());
959 sq_pushstring(squirrel,
name.c_str(), -1);
960 if (SQ_FAILED(sq_get(squirrel, -2)) ||
961 sq_gettype(squirrel, -1) != OT_TABLE) {
964 sq_pushnull(squirrel);
965 while (SQ_SUCCEEDED(sq_next(squirrel, -2))) {
966 if (sq_gettype(squirrel, -2) == OT_STRING) {
967 const SQChar*
key =
nullptr;
968 if (SQ_SUCCEEDED(sq_getstring(squirrel, -2, &
key)) &&
key)
973 std::sort(keys.begin(), keys.end());
978 const std::string&
name,
979 const std::string&
key)
const {
982 auto stack = self->
guard();
984 sq_pushobject(squirrel, instance.getRaw());
985 sq_pushstring(squirrel,
name.c_str(), -1);
986 if (SQ_FAILED(sq_get(squirrel, -2)) ||
987 sq_gettype(squirrel, -1) != OT_TABLE) {
990 sq_pushstring(squirrel,
key.c_str(), -1);
991 if (SQ_FAILED(sq_get(squirrel, -2))) {
1002 auto stack = self->
guard();
1004 sq_pushobject(squirrel, instance.getRaw());
1005 sq_pushstring(squirrel,
name.c_str(), -1);
1006 if (SQ_FAILED(sq_get(squirrel, -2)) ||
1007 sq_gettype(squirrel, -1) != OT_TABLE) {
1010 sq_pushstring(squirrel,
key.c_str(), -1);
1011 SQObjectType currentType = OT_NULL;
1012 if (SQ_SUCCEEDED(sq_get(squirrel, -2))) {
1013 currentType = sq_gettype(squirrel, -1);
1014 sq_pop(squirrel, 1);
1016 sq_pushstring(squirrel,
key.c_str(), -1);
1017 pushConvertedValue(squirrel, currentType,
value);
1018 bool ok = SQ_SUCCEEDED(sq_set(squirrel, -3));
1022 sq_settop(squirrel, stack.top());
1023 sq_pushobject(squirrel, instance.getRaw());
1024 sq_pushstring(squirrel,
name.c_str(), -1);
1025 if (SQ_FAILED(sq_get(squirrel, -2)) ||
1026 sq_gettype(squirrel, -1) != OT_TABLE) {
1029 sq_pushstring(squirrel,
key.c_str(), -1);
1030 pushConvertedValue(squirrel, OT_NULL,
value);
1031 ok = SQ_SUCCEEDED(sq_newslot(squirrel, -3, SQFalse));
1037 const std::string&
key)
const {
1040 auto stack = self->
guard();
1042 sq_pushobject(squirrel, instance.getRaw());
1043 sq_pushstring(squirrel,
name.c_str(), -1);
1044 if (SQ_FAILED(sq_get(squirrel, -2)) ||
1045 sq_gettype(squirrel, -1) != OT_TABLE) {
1048 sq_pushstring(squirrel,
key.c_str(), -1);
1049 const bool ok = SQ_SUCCEEDED(sq_deleteslot(squirrel, -2, SQFalse));
1054 auto found = scripts_.find(
id);
1055 if (
found == scripts_.end())
1057 const bool fromFile =
found->second->from_file;
1058 const std::string
input =
found->second->source_text;
1065 auto found = scripts_.find(
id);
1066 if (
found == scripts_.end())
return false;
1070 auto stack =
guard();
1072 notifyLifecycle(
record.info);
1074 for (
const auto& pair :
record.class_objects) {
1075 auto owner = class_owners_.find(pair.first);
1076 if (
owner == class_owners_.end() ||
owner->second !=
id)
continue;
1077 ssq::Object currentObject = vm_->find(pair.first.c_str());
1078 if (currentObject.getType() == ssq::Type::CLASS &&
1079 objectIdentity(currentObject.getRaw()) == objectIdentity(pair.second.getRaw())) {
1080 sq_pushroottable(
handle());
1081 sq_pushstring(
handle(), pair.first.c_str(),
static_cast<SQInteger
>(pair.first.size()));
1082 sq_rawdeleteslot(
handle(), -2, SQFalse);
1085 classes_.erase(pair.first);
1086 class_owners_.erase(
owner);
1087 class_identities_.erase(pair.first);
1089 record.class_objects.clear();
1092 notifyLifecycle(
record.info);
1094 }
catch (
const std::exception&
error) {
1097 notifyLifecycle(
record.info);
1103 std::vector<ScriptId>
ids;
1104 ids.reserve(scripts_.size());
1105 for (
const auto& pair : scripts_)
ids.push_back(pair.first);
1106 std::reverse(
ids.begin(),
ids.end());
1119 auto found = scripts_.find(
id);
1120 return found == scripts_.end() ? nullptr : &
found->second->info;
1124 std::vector<ScriptInfo>
result;
1125 result.reserve(scripts_.size());
1126 for (
const auto& pair : scripts_)
result.push_back(pair.second->info);
1135 return found == classes_.end() ? nullptr : &
found->second;
1139 std::vector<ReflectedClass>
result;
1140 result.reserve(classes_.size());
1141 for (
const auto& pair : classes_)
result.push_back(pair.second);
1143 return a.name < b.name;
1150 auto stack =
guard();
1151 const auto after = rootClasses();
1153 for (
const auto& pair : after) {
1154 auto old = class_identities_.find(pair.first);
1155 if (old != class_identities_.end() && old->second == pair.second)
continue;
1157 ssq::Class
cls = vm_->findClass(pair.first.c_str());
1159 auto clsInfo = classes_.find(pair.first);
1160 if (clsInfo != classes_.end())
source = clsInfo->second.source;
1162 classes_[pair.first] = inspectClass(pair.first,
cls,
source);
1163 class_identities_[pair.first] = pair.second;
1164 if (!class_owners_.count(pair.first)) class_owners_[pair.first] = 0;
1172 for (
const auto& pair : after) {
1173 auto info = classes_.find(pair.first);
1174 if (
info == classes_.end())
continue;
1176 const ssq::Class
cls = vm_->findClass(pair.first.c_str());
1179 if (SQ_SUCCEEDED(sq_getbase(
handle(), -1)) &&
1180 sq_gettype(
handle(), -1) == OT_CLASS) {
1181 HSQOBJECT baseObject;
1182 if (SQ_SUCCEEDED(sq_getstackobj(
handle(), -1, &baseObject))) {
1183 const SQUserPointer
identity = objectIdentity(baseObject);
1184 for (
const auto& candidate : after) {
1185 if (candidate.second ==
identity) {
1186 info->second.base = candidate.first;
1199 const bool validName = !
name.empty();
1201 return vm_->findClass(
name.c_str());
1205 if (instance.getType() != ssq::Type::INSTANCE)
return {};
1208 auto stack = self->
guard();
1210 const SQInteger
top = sq_gettop(squirrel);
1211 sq_pushobject(squirrel, instance.getRaw());
1212 if (SQ_FAILED(sq_getclass(squirrel, -1)) ||
1213 sq_gettype(squirrel, -1) != OT_CLASS) {
1214 sq_settop(squirrel,
top);
1217 HSQOBJECT classObject;
1218 sq_getstackobj(squirrel, -1, &classObject);
1219 sq_settop(squirrel,
top);
1220 const SQUserPointer
identity = objectIdentity(classObject);
1221 for (
const auto& pair : rootClasses()) {
1222 if (pair.second ==
identity)
return pair.first;
1228 if (!lifecycle_handler_)
return;
1230 lifecycle_handler_(
info);
1235script::ScriptErrorContext Runtime::compileErrorContext(
const std::string& what,
1236 const std::string& sourceText) {
1237 script::ScriptErrorContext ctx;
1242 if (lineText.empty())
return ctx;
1243 std::string hint = std::to_string(ctx.line) +
" | " + lineText;
1244 if (ctx.column > 0) {
1246 const size_t caret =
static_cast<size_t>(ctx.column > 1 ? ctx.column - 1 : 0);
1247 hint.append(caret,
' ');
1250 ctx.hint = std::move(hint);
1254[[noreturn]]
void Runtime::fail(
ScriptStage stage,
const std::string&
source, ScriptId
id,
1255 script::ScriptErrorContext
context) {
1257 if (error_handler_) {
1259 error_handler_(wrapped);
1266[[noreturn]]
void Runtime::fail(
ScriptStage stage,
const std::string&
source, ScriptId
id,
1267 const std::exception&
error) {
1269 const char* what =
error.what();
1270 const std::string
message = what ? what :
"";
1274 (ctx.message !=
message &&
message.find(ctx.message) == std::string::npos &&
1275 ctx.message.find(
message) == std::string::npos)) {
1279 fail(stage,
source,
id, std::move(ctx));
1282std::unordered_map<std::string, SQUserPointer> Runtime::rootClasses()
const {
1283 std::unordered_map<std::string, SQUserPointer>
result;
1284 StackGuard stack(*
const_cast<Runtime*
>(
this));
1286 sq_pushroottable(squirrel);
1287 sq_pushnull(squirrel);
1288 while (SQ_SUCCEEDED(sq_next(squirrel, -2))) {
1289 if (sq_gettype(squirrel, -2) == OT_STRING && sq_gettype(squirrel, -1) == OT_CLASS) {
1290 const SQChar*
name =
nullptr;
1292 if (SQ_SUCCEEDED(sq_getstring(squirrel, -2, &
name)) &&
name &&
1293 SQ_SUCCEEDED(sq_getstackobj(squirrel, -1, &
object)))
1296 sq_pop(squirrel, 2);
1301void Runtime::discoverClasses(
1302 ScriptRecord&
record,
const std::unordered_map<std::string, SQUserPointer>& before) {
1303 const auto after = rootClasses();
1304 for (
const auto& pair : after) {
1305 auto old = before.find(pair.first);
1306 if (old != before.end() && old->second == pair.second)
continue;
1307 ssq::Class
cls = vm_->findClass(pair.first.c_str());
1308 record.class_objects.insert_or_assign(pair.first,
cls);
1309 if (std::find(
record.info.classes.begin(),
record.info.classes.end(), pair.first) ==
1310 record.info.classes.end())
1311 record.info.classes.push_back(pair.first);
1312 classes_[pair.first] = inspectClass(pair.first,
cls,
record.info.source);
1313 class_owners_[pair.first] =
record.info.id;
1314 class_identities_[pair.first] = pair.second;
1316 std::sort(
record.info.classes.begin(),
record.info.classes.end());
1322 if (
info == classes_.end() ||
cls ==
record.class_objects.end())
continue;
1323 StackGuard stack(*
this);
1324 sq_pushobject(
handle(),
cls->second.getRaw());
1325 if (SQ_SUCCEEDED(sq_getbase(
handle(), -1)) && sq_gettype(
handle(), -1) == OT_CLASS) {
1326 HSQOBJECT baseObject;
1327 if (SQ_SUCCEEDED(sq_getstackobj(
handle(), -1, &baseObject))) {
1328 const SQUserPointer
identity = objectIdentity(baseObject);
1329 for (
const auto& candidate : after) {
1330 if (candidate.second ==
identity) {
1331 info->second.base = candidate.first;
1340ReflectedClass Runtime::inspectClass(
const std::string&
name,
const ssq::Class&
cls,
1341 const std::string&
source)
const {
1342 ReflectedClass
info;
1345 info.members = collectClassMembers(
cls);
1349std::vector<ReflectedMember> Runtime::collectClassMembers(
const ssq::Class&
cls)
const {
1350 std::vector<ReflectedMember>
members;
1352 auto scope = self->enter();
1353 auto stack = self->guard();
1355 const SQInteger
top = sq_gettop(squirrel);
1356 sq_pushobject(squirrel,
cls.getRaw());
1357 members = collectClassMembersFromStack(squirrel, -1);
1358 sq_settop(squirrel,
top);
EVEngine assertion entry point, backed by zeroerr.
#define EV_PARAM_CHECK(cond,...)
Validate a function parameter / public API precondition.
std::vector< QuestEvent > pending
struct SQVM * HSQUIRRELVM
ScriptComponentRecord record
std::shared_ptr< OceanGpuSpectrum > owner
std::map< std::string, double > attributes
const SquirrelValueOptions & options
Explicit Value/Owned/Borrowed semantics at the Squirrel boundary.
float(ui::Theme::* member)[4]
std::map< std::string, std::span< const std::uint8_t > > members
const VegetationPresetContext & context
static void detach(Runtime *runtime)
Clears the active runtime if it matches; called during shutdown.
static void expose(Runtime &runtime)
Installs the eve table and defers native class method bindings.
Pushes this Runtime on the current thread's runtime stack.
Scope(Runtime &runtime)
Scope.
Restores the native Squirrel stack when a binding operation leaves scope.
StackGuard & operator=(StackGuard &&other) noexcept
Operator =.
~StackGuard()
Stack guard.
StackGuard(Runtime &runtime) noexcept
Stack guard.
EVENGINE_API_FOUNDATION public API.
void shutdown() noexcept
Tears down the VM and detaches the runtime; idempotent and noexcept.
ssq::Class findClass(const std::string &name) const
Finds a script class by name (throws if it does not exist).
ScriptId runFile(const std::string &path)
Convenience: compileFile() then execute().
void unloadAll() noexcept
Unloads every script.
static Runtime * current() noexcept
The runtime currently at the top of this thread's runtime stack, or nullptr.
ssq::Table table(const char *name) const
Looks up a named global table.
bool contains(ScriptId id) const noexcept
True if a script with the given id is tracked.
ScriptId compileSource(std::string source, std::string sourceName="buffer")
Compiles script source without running it.
bool arrayRemove(const ssq::Object &instance, const std::string &name, size_t index) const
Removes one element of an array member (shifts the rest).
bool unload(ScriptId id)
Unloads a script and removes its declared classes; false if unknown/unloaded.
ScriptId reload(ScriptId id)
Recompiles and re-runs a script from its original source.
Runtime(size_t stackSize=2048, ssq::Libs::Flag libraries=ssq::Libs::ALL)
Creates a script runtime with its own Squirrel VM.
std::vector< ReflectedMember > reflectInstance(const ssq::Object &instance) const
Inspects a live instance: own + inherited members with current values.
std::vector< ReflectedClass > reflectedClasses() const
All reflected classes, sorted by name.
script::ScriptModuleResolver & scriptModules() noexcept
Script module provider registry and dependency resolver for this VM.
ssq::Object createInstance(const std::string &name, const std::string &source={})
Creates a live instance of a script class (default constructor).
const ReflectedClass * reflectedClass(const std::string &name) const noexcept
Reflected class by name, or nullptr.
ReflectedValue tableGet(const ssq::Object &instance, const std::string &name, const std::string &key) const
Value of a table member key; empty when missing.
bool writeProperty(const ssq::Object &instance, const std::string &name, const ReflectedValue &value) const
Writes one property of a live instance.
ssq::Object readObjectProperty(const ssq::Object &instance, const std::string &name) const
Reads a live object-valued property (nested instance).
static size_t stackDepth() noexcept
Depth of the thread-local runtime stack.
ScriptId runSource(std::string source, std::string sourceName="buffer")
Convenience: compileSource() then execute().
StackGuard guard() noexcept
RAII guard that restores the Squirrel stack top on scope exit.
bool initialized() const noexcept
True once initialize() has completed successfully.
bool tableRemove(const ssq::Object &instance, const std::string &name, const std::string &key) const
Removes a key from a table member.
size_t scanClasses()
Scans the root table for script classes and refreshes reflection.
script::ScriptCompiler & scriptCompiler() noexcept
Unified EveScript compiler, metadata store, and binding contracts.
ScriptId compileFile(const std::string &path)
Compiles a script file without running it.
bool tableSet(const ssq::Object &instance, const std::string &name, const std::string &key, const ReflectedValue &value) const
Sets a key of a table member (creates the key when missing).
void initialize()
Exposes registered engine modules into the script root table. Safe to call more than once.
bool arrayAppend(const ssq::Object &instance, const std::string &name, const ReflectedValue &value) const
Appends an element to an array member.
const ReflectedClass & reflectClass(const std::string &name, const std::string &source={})
Reflects a class by name, storing its inspected members.
const ScriptInfo * script(ScriptId id) const noexcept
Script metadata for an id, or nullptr if unknown.
std::string classNameOf(const ssq::Object &instance) const
Name of the script class of a live instance ("" when unknown).
HSQUIRRELVM handle() const noexcept
Raw Squirrel VM handle; nullptr after shutdown.
ReflectedValue readProperty(const ssq::Object &instance, const std::string &name) const
Reads one property of a live instance.
size_t arraySize(const ssq::Object &instance, const std::string &name) const
Element count of an array member (0 when missing/not an array).
bool arraySet(const ssq::Object &instance, const std::string &name, size_t index, const ReflectedValue &value) const
Replaces one element of an array member.
ssq::Table root() const
Root script table of the VM.
Scope enter()
Pushes this runtime on the thread-local runtime stack (RAII pop).
ssq::VM & vm() noexcept
Underlying SimpleSquirrel VM (requires a live, initialized runtime).
ReflectedValue arrayGet(const ssq::Object &instance, const std::string &name, size_t index) const
Element value of an array member; empty when out of range.
std::vector< ScriptInfo > scripts() const
Metadata for all tracked scripts, sorted by id.
std::vector< std::string > tableKeys(const ssq::Object &instance, const std::string &name) const
String keys of a table member.
const ScriptInfo & execute(ScriptId id)
Runs a previously compiled script; throws ScriptException on failure.
Exception raised at the public Runtime boundary.
ScriptStage stage() const noexcept
Stage.
const std::string & source() const noexcept
Source.
ScriptException(ScriptStage stage, std::string source, uint64_t scriptId, const std::string &message)
Script exception.
uint64_t scriptId() const noexcept
Script id.
static ScriptProviderRegistry & instance()
Process-lifetime registry; clearAll is the only reset.
void clearAll()
Drop every published provider and release its VM reference.
Releases C++-owned Squirrel roots before Runtime destroys its VM.
Unified Runtime compiler facade for metadata, diagnostics, and module preparation.
Owns providers, the static dependency graph, compiled closures, and module instances.
std::string formatScriptError(const ScriptErrorContext &ctx)
Formats a context into a human-readable multi-line report.
void clearLastScriptError(HSQUIRRELVM vm)
Drops any recorded error for a VM.
std::string sourceLineText(const std::string &sourceText, int line)
Extracts one 1-based line from script source text.
ScriptErrorContext takeLastScriptError(HSQUIRRELVM vm)
Consumes and clears the last recorded error for a VM.
void installScriptErrorHook(HSQUIRRELVM vm)
Install the engine's script error hook on a VM.
std::string formatLastScriptError(HSQUIRRELVM vm)
Formats the last captured error for a VM without consuming it.
const ScriptErrorContext * peekLastScriptError(HSQUIRRELVM vm)
Peeks at the last recorded error for a VM without clearing it.
bool parseCompileError(const std::string &text, std::string *source, int *line, int *column, std::string *message)
Parses the ssq compile message "Compile error at source:line:column msg".
void setLastScriptError(HSQUIRRELVM vm, ScriptErrorContext ctx)
Records the last error for a VM (thread-local, synchronous consumers).
std::string formatStackTrace(const std::vector< ScriptFrame > &frames)
Formats just the call-stack portion of a context.
ScriptErrorContext captureScriptError(HSQUIRRELVM vm)
Captures the pending runtime error from inside the Squirrel error handler.
Build metadata (engine git commit, build time, third-party version).
std::string reflectedFloatString(double value)
Shortest round-trip float formatting (portable).
ScriptStage
ScriptStage public API.
void exposeReflection(Runtime &runtime, ssq::Table eveTable)
Exposes the Runtime reflection API to scripts as eve.reflect.
EVENGINE_API_FOUNDATION_INLINE public API.
EVENGINE_API_FOUNDATION_INLINE public API.
EVENGINE_API_FOUNDATION public API.
bool attrBool(const std::string &name, bool def=false) const noexcept
Boolean attribute value; def when missing or not boolean.
float attrFloat(const std::string &name, float def=0.f) const noexcept
Numeric attribute value; def when missing or not numeric.
const ReflectedAttribute * findAttribute(const std::string &name) const noexcept
Looks up an attribute by name; nullptr when absent.
std::string attrString(const std::string &name, const std::string &def={}) const
Raw string attribute value; def when missing.
std::vector< std::string > attrOptions(const std::string &name) const
Comma-separated string attribute split into trimmed options.
Typed snapshot of one live instance property.
std::unique_ptr< ssq::Script > compiled
std::unordered_map< std::string, ssq::Class > class_objects
EVENGINE_API_FOUNDATION_INLINE public API.
Structured snapshot of a script error: message, throw site and stack.
bool empty() const noexcept
True when no error payload was captured.
std::string message
Raw error value ("kaboom", "42", ...).