载入中...
搜索中...
未找到
Runtime.cpp
浏览该文件的文档.
1#include "common/Runtime.h"
2
3#include "common/Assert.h"
4#include "common/Capability.h"
5#include "common/Module.h"
12#include "common/config.h"
13
14#include <squirrel.h>
15
16#include <algorithm>
17#include <cstdarg>
18#include <cstdlib>
19#include <sstream>
20#include <utility>
21
22#if defined(EVENGINE_ANDROID)
23#include <android/log.h>
24#endif
25
26namespace eve {
27namespace {
28
29thread_local std::vector<Runtime*> runtime_stack;
30
31#if defined(EVENGINE_ANDROID)
32void androidScriptPrint(HSQUIRRELVM, const SQChar* format, ...) {
33 va_list args;
34 va_start(args, format);
35 __android_log_vprint(ANDROID_LOG_INFO, "EVEngine", format, args);
36 va_end(args);
37}
38
39void androidScriptError(HSQUIRRELVM, const SQChar* format, ...) {
40 va_list args;
41 va_start(args, format);
42 __android_log_vprint(ANDROID_LOG_ERROR, "EVEngine", format, args);
43 va_end(args);
44}
45#endif
46
47const char* stageName(ScriptStage stage) {
48 switch (stage) {
49 case ScriptStage::Compile: return "compile";
50 case ScriptStage::Execute: return "execute";
51 case ScriptStage::Reflect: return "reflect";
52 case ScriptStage::Unload: return "unload";
53 case ScriptStage::Shutdown: return "shutdown";
54 }
55 return "unknown";
56}
57
58std::string valueString(HSQUIRRELVM vm, SQInteger index) {
59 switch (sq_gettype(vm, index)) {
60 case OT_NULL: return "null";
61 case OT_BOOL: {
62 SQBool value = SQFalse;
63 return SQ_SUCCEEDED(sq_getbool(vm, index, &value)) && value ? "true" : "false";
64 }
65 case OT_INTEGER: {
66 SQInteger value = 0;
67 if (SQ_SUCCEEDED(sq_getinteger(vm, index, &value))) return std::to_string(value);
68 break;
69 }
70 case OT_FLOAT: {
71 SQFloat value = 0;
72 if (SQ_SUCCEEDED(sq_getfloat(vm, index, &value))) {
74 }
75 break;
76 }
77 case OT_STRING: {
78 const SQChar* value = nullptr;
79 if (SQ_SUCCEEDED(sq_getstring(vm, index, &value)) && value) return value;
80 break;
81 }
82 default: break;
83 }
84 return {};
85}
86
87ReflectedValue valueFromStack(HSQUIRRELVM vm, SQInteger index) {
88 ReflectedValue out;
89 switch (sq_gettype(vm, index)) {
90 case OT_BOOL: {
91 SQBool value = SQFalse;
92 if (SQ_SUCCEEDED(sq_getbool(vm, index, &value))) {
93 out.kind = ReflectedValueKind::Bool;
94 out.boolean = value != SQFalse;
95 }
96 break;
97 }
98 case OT_INTEGER: {
99 SQInteger value = 0;
100 if (SQ_SUCCEEDED(sq_getinteger(vm, index, &value))) {
101 out.kind = ReflectedValueKind::Integer;
102 out.integer = value;
103 }
104 break;
105 }
106 case OT_FLOAT: {
107 SQFloat value = 0;
108 if (SQ_SUCCEEDED(sq_getfloat(vm, index, &value))) {
109 out.kind = ReflectedValueKind::Float;
110 out.floating = value;
111 }
112 break;
113 }
114 case OT_STRING: {
115 const SQChar* value = nullptr;
116 if (SQ_SUCCEEDED(sq_getstring(vm, index, &value)) && value) {
117 out.kind = ReflectedValueKind::String;
118 out.text = value;
119 }
120 break;
121 }
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;
125 case OT_NULL: break;
126 default: out.kind = ReflectedValueKind::Other; break;
127 }
128 return out;
129}
130
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: {
138 char* end = nullptr;
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;
141 }
142 default: return 0;
143 }
144}
145
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: {
153 char* end = nullptr;
154 const double parsed = std::strtod(value.text.c_str(), &end);
155 return (end && end != value.text.c_str()) ? parsed : 0.0;
156 }
157 default: return 0.0;
158 }
159}
160
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;
170 }
171}
172
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: {
180 return reflectedFloatString(value.floating);
181 }
182 default: return {};
183 }
184}
185
190void pushConvertedValue(HSQUIRRELVM v, SQObjectType currentType,
191 const ReflectedValue& value) {
192 switch (currentType) {
193 case OT_BOOL:
194 sq_pushbool(v, valueToBool(value) ? SQTrue : SQFalse);
195 return;
196 case OT_INTEGER:
197 sq_pushinteger(v, static_cast<SQInteger>(valueToInteger(value)));
198 return;
199 case OT_FLOAT:
200 sq_pushfloat(v, static_cast<SQFloat>(valueToDouble(value)));
201 return;
202 case OT_STRING: {
203 const std::string text = valueToText(value);
204 sq_pushstring(v, text.c_str(), static_cast<SQInteger>(text.size()));
205 return;
206 }
207 default: break;
208 }
209 switch (value.kind) {
210 case ReflectedValueKind::Bool:
211 sq_pushbool(v, value.asBool() ? SQTrue : SQFalse);
212 return;
213 case ReflectedValueKind::Integer:
214 sq_pushinteger(v, SQInteger(value.asInt()));
215 return;
216 case ReflectedValueKind::Float:
217 sq_pushfloat(v, SQFloat(value.asFloat()));
218 return;
219 case ReflectedValueKind::String:
220 sq_pushstring(v, value.asString().c_str(), -1);
221 return;
222 default:
223 sq_pushnull(v);
224 return;
225 }
226}
227
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); // duplicate the class for iteration
234 sq_pushnull(squirrel);
235 while (SQ_SUCCEEDED(sq_next(squirrel, -2))) {
236 if (sq_gettype(squirrel, -2) != OT_STRING) {
237 sq_pop(squirrel, 2);
238 continue;
239 }
240 const SQChar* memberName = nullptr;
241 if (!SQ_SUCCEEDED(sq_getstring(squirrel, -2, &memberName)) || !memberName) {
242 sq_pop(squirrel, 2);
243 continue;
244 }
245 ReflectedMember member;
246 member.name = memberName;
247 member.type = static_cast<ssq::Type>(sq_gettype(squirrel, -1));
248 member.method = member.type == ssq::Type::CLOSURE ||
249 member.type == ssq::Type::NATIVECLOSURE;
250
251 // sq_getattributes consumes the key at the stack top and replaces it
252 // with the attribute table (or null).
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)) &&
262 attributeName) {
263 ReflectedAttribute attribute;
264 attribute.name = attributeName;
265 attribute.type =
266 static_cast<ssq::Type>(sq_gettype(squirrel, -1));
267 attribute.value = valueString(squirrel, -1);
268 member.attributes.push_back(std::move(attribute));
269 }
270 }
271 sq_pop(squirrel, 2);
272 }
273 }
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;
278 });
279 members.push_back(std::move(member));
280 sq_pop(squirrel, 2);
281 }
282 sq_settop(squirrel, top);
283 std::sort(members.begin(), members.end(),
284 [](const ReflectedMember& a, const ReflectedMember& b) {
285 return a.name < b.name;
286 });
287 return members;
288}
289
290SQUserPointer objectIdentity(const HSQOBJECT& object) {
291 return reinterpret_cast<SQUserPointer>(object._unVal.pRefCounted);
292}
293
294std::unique_ptr<ssq::VM> createVm(size_t stackSize, ssq::Libs::Flag libraries) {
295 // Validate before constructing the VM: with assertions compiled out the
296 // check must not be the only thing standing between a bad stack size and a
297 // half-constructed runtime.
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)
301 // Android has no terminal attached to the app process. Route Squirrel's
302 // print/error callbacks to logcat so application diagnostics and CI startup
303 // markers remain observable.
304 vm->setPrintFunc(&androidScriptPrint, &androidScriptError);
305#endif
306 return vm;
307}
308
310SQInteger scriptErrorHook(HSQUIRRELVM vm) {
311 script::ScriptErrorContext ctx = script::captureScriptError(vm);
312 script::setLastScriptError(vm, std::move(ctx));
313 return 0;
314}
315
316} // namespace
317
318namespace script {
319
321 if (!vm) return;
322 // Line numbers in sq_stackinfos require debug info at compile time.
323 sq_enabledebuginfo(vm, SQTrue);
324 // Call the hook for try/catch as well, while the throw-site stack is live.
325 // load.nut's eve_frame catch would otherwise print only the error string.
326 sq_notifyallexceptions(vm, SQTrue);
327 sq_newclosure(vm, &scriptErrorHook, 0); // pushes the closure
328 sq_seterrorhandler(vm); // pops the closure
329}
330
331} // namespace script
332
335 std::string source_text;
336 bool from_file = false;
337 std::unique_ptr<ssq::Script> compiled;
338 std::unordered_map<std::string, ssq::Class> class_objects;
339};
340
341ScriptException::ScriptException(ScriptStage stage, std::string source, uint64_t scriptId,
342 const std::string& message)
343 : std::runtime_error([&] {
344 std::ostringstream out;
345 out << "Script " << stageName(stage);
346 if (!source.empty()) out << " failed in '" << source << "'";
347 if (scriptId != 0) out << " [id=" << scriptId << "]";
348 out << ": " << message;
349 return out.str();
350 }()),
351 stage_(stage), source_(std::move(source)), script_id_(scriptId) {}
352
353ScriptException::ScriptException(ScriptStage stage, std::string source, uint64_t scriptId,
355 : std::runtime_error([&] {
356 std::ostringstream out;
357 out << "Script " << stageName(stage);
358 if (!source.empty()) out << " failed in '" << source << "'";
359 if (scriptId != 0) out << " [id=" << scriptId << "]";
361 return out.str();
362 }()),
363 stage_(stage),
364 source_(std::move(source)),
365 script_id_(scriptId),
366 line_(context.line),
367 column_(context.column),
368 function_(context.function),
369 stack_trace_(script::formatStackTrace(context.stack)),
370 reported_(context.reported) {
371 if (!stack_trace_.empty() && stack_trace_.back() == '\n') stack_trace_.pop_back();
372}
373
374const ReflectedAttribute* ReflectedMember::findAttribute(const std::string& name) const noexcept {
375 for (const auto& attribute : attributes) {
376 if (attribute.name == name) return &attribute;
377 }
378 return nullptr;
379}
380
381float ReflectedMember::attrFloat(const std::string& name, float def) const noexcept {
382 const ReflectedAttribute* attribute = findAttribute(name);
383 if (!attribute) return def;
384 char* end = nullptr;
385 const double value = std::strtod(attribute->value.c_str(), &end);
386 if (end && end != attribute->value.c_str() && *end == '\0')
387 return static_cast<float>(value);
388 return def;
389}
390
391bool ReflectedMember::attrBool(const std::string& name, bool def) const noexcept {
392 const ReflectedAttribute* attribute = findAttribute(name);
393 if (!attribute) return def;
394 if (attribute->value == "true" || attribute->value == "1" ||
395 attribute->value == "yes")
396 return true;
397 if (attribute->value == "false" || attribute->value == "0" ||
398 attribute->value == "no")
399 return false;
400 return def;
401}
402
403std::string ReflectedMember::attrString(const std::string& name,
404 const std::string& def) const {
406 return attribute ? attribute->value : def;
407}
408
409std::vector<std::string> ReflectedMember::attrOptions(const std::string& name) const {
410 std::vector<std::string> options;
412 if (!attribute) return options;
413 std::string rest = attribute->value;
414 while (true) {
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)
420 options.push_back(piece.substr(first, last - first + 1));
421 if (comma == std::string::npos) break;
422 rest = rest.substr(comma + 1);
423 }
424 return options;
425}
426
428 : vm_(runtime.handle()), top_(vm_ ? sq_gettop(vm_) : 0) {}
429
431 if (vm_) sq_settop(vm_, top_);
432}
433
435 : vm_(std::exchange(other.vm_, nullptr)), top_(other.top_) {}
436
438 if (this == &other) return *this;
439 if (vm_) sq_settop(vm_, top_);
440 vm_ = std::exchange(other.vm_, nullptr);
441 top_ = other.top_;
442 return *this;
443}
444
445Runtime::Scope::Scope(Runtime& runtime) : runtime_(&runtime) { runtime_stack.push_back(&runtime); }
446
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());
451}
452
454 : runtime_(std::exchange(other.runtime_, nullptr)) {}
455
456Runtime::Runtime(size_t stackSize, ssq::Libs::Flag libraries)
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();
462}
463
465
467 if (initialized_) return;
468 auto scope = enter();
469 auto stack = guard();
470 try {
472 exposeReflection(*this, table("eve"));
473 table("eve").addFunc("lastScriptError", [this]() {
475 });
476 initialized_ = true;
477 } catch (const std::exception& error) {
479 fail(ScriptStage::Execute, "<module reflection>", 0, error);
480 }
481}
482
483void Runtime::installErrorHandler() {
484 if (!vm_) return;
486}
487
488void Runtime::shutdown() noexcept {
489 if (shutting_down_ || stopped_) return;
490 shutting_down_ = true;
491 unloadAll();
492 try {
493 cap::forEach<script::ISquirrelRootReleaser>([](script::ISquirrelRootReleaser* owner) {
494 if (owner) owner->releaseSquirrelRoots();
495 });
496 } catch (...) {
497 }
500 while (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);
504 }
505 classes_.clear();
506 class_owners_.clear();
507 class_identities_.clear();
508 initialized_ = false;
509 script_compiler_.reset();
510 script_modules_.reset();
511 // A published script provider holds a rooted ssq::Object, which must not outlive
512 // its VM: release every one before the VM goes away.
514 vm_.reset();
515 stopped_ = true;
516 shutting_down_ = false;
517}
518
519bool Runtime::initialized() const noexcept { return initialized_; }
520ssq::VM& Runtime::vm() noexcept { return *vm_; }
521const ssq::VM& Runtime::vm() const noexcept { return *vm_; }
522HSQUIRRELVM Runtime::handle() const noexcept { return vm_ ? vm_->getHandle() : nullptr; }
523script::ScriptModuleResolver& Runtime::scriptModules() noexcept { return *script_modules_; }
525 return *script_modules_;
526}
527script::ScriptCompiler& Runtime::scriptCompiler() noexcept { return *script_compiler_; }
528const script::ScriptCompiler& Runtime::scriptCompiler() const noexcept { return *script_compiler_; }
529ssq::Table Runtime::root() const { return ssq::Table(static_cast<const ssq::Object&>(*vm_)); }
530ssq::Table Runtime::table(const char* name) const {
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));
534}
535
537 return runtime_stack.empty() ? nullptr : runtime_stack.back();
538}
539
540size_t Runtime::stackDepth() noexcept { return runtime_stack.size(); }
541
542Runtime::ScriptId Runtime::compileSource(std::string source, std::string sourceName) {
543 if (stopped_) throw ScriptException(ScriptStage::Compile, sourceName, 0, "runtime is shut down");
544 auto scope = enter();
545 auto stack = guard();
546 const ScriptId id = next_script_id_++;
547 auto record = std::make_unique<ScriptRecord>();
548 record->info.id = id;
549 record->info.source = sourceName;
550 record->source_text = std::move(source);
551 try {
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));
555 (void)inserted;
556 notifyLifecycle(it->second->info);
557 return id;
558 } catch (const std::exception& error) {
559 script::ScriptErrorContext ctx = compileErrorContext(error.what(), record->source_text);
560 fail(ScriptStage::Compile, sourceName, id, std::move(ctx));
561 }
562}
563
565 const bool validPath = !path.empty();
566 EV_PARAM_CHECK(validPath, "script file path must not be empty");
567 if (stopped_) throw ScriptException(ScriptStage::Compile, path, 0, "runtime is shut down");
568 auto scope = enter();
569 auto stack = guard();
570 const ScriptId id = next_script_id_++;
571 auto record = std::make_unique<ScriptRecord>();
572 record->info.id = id;
573 record->info.source = path;
574 record->source_text = path;
575 record->from_file = true;
576 try {
577 record->compiled = std::make_unique<ssq::Script>(script_compiler_->compileFile(path));
578 auto [it, inserted] = scripts_.emplace(id, std::move(record));
579 (void)inserted;
580 notifyLifecycle(it->second->info);
581 return id;
582 } catch (const std::exception& error) {
583 script::ScriptErrorContext ctx = compileErrorContext(error.what(), {});
584 fail(ScriptStage::Compile, path, id, std::move(ctx));
585 }
586}
587
589 auto found = scripts_.find(id);
590 if (found == scripts_.end())
591 throw ScriptException(ScriptStage::Execute, {}, id, "unknown script");
592 ScriptRecord& record = *found->second;
593 if (!record.compiled || record.info.state == ScriptState::Unloaded)
594 throw ScriptException(ScriptStage::Execute, record.info.source, id, "script is unloaded");
595
596 auto scope = enter();
597 auto stack = guard();
598 const auto before = rootClasses();
599 record.info.state = ScriptState::Running;
600 record.info.error.clear();
601 notifyLifecycle(record.info);
602 try {
603 script_modules_->instantiateDependencies(record.info.source);
604 // Drive the Squirrel call directly instead of ssq::VM::run(): when a
605 // DevTool hook replaces the VM's error handler, ssq never populates its
606 // stored RuntimeException and would dereference a null unique_ptr on
607 // failure. The raw call reports through the installed handler (which
608 // captures the live stack) and lets us throw an enriched ScriptException.
610 sq_pushobject(vm, record.compiled->getRaw());
611 sq_pushroottable(vm);
612 const SQRESULT result = sq_call(vm, 1, SQFalse, SQTrue);
613 if (SQ_FAILED(result)) {
615 if (const auto* pending = script::peekLastScriptError(vm)) ctx = *pending;
616 if (ctx.empty()) ctx.message = "script error";
617 try {
618 discoverClasses(record, before);
619 } catch (...) {
620 }
621 record.info.state = ScriptState::Failed;
622 record.info.error = script::formatScriptError(ctx);
623 notifyLifecycle(record.info);
624 fail(ScriptStage::Execute, record.info.source, id, std::move(ctx));
625 }
626 discoverClasses(record, before);
627 record.info.state = ScriptState::Loaded;
628 notifyLifecycle(record.info);
629 return record.info;
630 } catch (const ScriptException&) {
631 throw;
632 } catch (const std::exception& error) {
633 try {
634 discoverClasses(record, before);
635 } catch (...) {
636 }
637 record.info.state = ScriptState::Failed;
638 record.info.error = error.what();
639 notifyLifecycle(record.info);
640 fail(ScriptStage::Execute, record.info.source, id, error);
641 }
642}
643
644Runtime::ScriptId Runtime::runSource(std::string source, std::string sourceName) {
645 const ScriptId id = compileSource(std::move(source), std::move(sourceName));
646 execute(id);
647 return id;
648}
649
651 const ScriptId id = compileFile(path);
652 execute(id);
653 return id;
654}
655
656const ReflectedClass& Runtime::reflectClass(const std::string& name, const std::string& source) {
657 const bool validName = !name.empty();
658 EV_PARAM_CHECK(validName, "reflected class name must not be empty");
659 auto scope = enter();
660 auto stack = guard();
661 try {
662 ssq::Class cls = vm_->findClass(name.c_str());
663 classes_[name] = inspectClass(name, cls, source);
664 return classes_.at(name);
665 } catch (const std::exception& error) {
666 fail(ScriptStage::Reflect, source.empty() ? name : source, 0, error);
667 }
668}
669
670ssq::Object Runtime::createInstance(const std::string& name, const std::string& source) {
671 const bool validName = !name.empty();
672 EV_PARAM_CHECK(validName, "instance class name must not be empty");
673 auto scope = enter();
674 auto stack = guard();
675 const std::string label = source.empty() ? name : source;
676 HSQUIRRELVM squirrel = handle();
677 const SQInteger top = sq_gettop(squirrel);
678 sq_pushroottable(squirrel); // [root]
679 sq_pushstring(squirrel, name.c_str(), -1); // [root, name]
680 if (SQ_FAILED(sq_get(squirrel, -2)) ||
681 sq_gettype(squirrel, -1) != OT_CLASS) {
682 sq_settop(squirrel, top);
684 ctx.message = "class not found: " + name;
685 fail(ScriptStage::Reflect, label, 0, std::move(ctx));
686 }
687 sq_createinstance(squirrel, -1); // [root, class, instance]
688 ssq::Object instance(squirrel);
689 sq_getstackobj(squirrel, -1, &instance.getRaw());
690 sq_addref(squirrel, &instance.getRaw()); // root the instance
691 // Call the default constructor with `this` = the new instance.
692 sq_pushobject(squirrel, instance.getRaw()); // [.., instance, instance]
693 sq_pushstring(squirrel, "constructor", -1); // [.., instance, instance, "constructor"]
694 if (SQ_SUCCEEDED(sq_get(squirrel, -2)) &&
695 (sq_gettype(squirrel, -1) == OT_CLOSURE ||
696 sq_gettype(squirrel, -1) == OT_NATIVECLOSURE)) {
697 // sq_call expects [closure, this, args...] with params including `this`.
698 sq_pushobject(squirrel, instance.getRaw()); // [.., instance, ctor, this]
699 if (SQ_FAILED(sq_call(squirrel, 1, SQTrue, SQTrue))) {
701 if (ctx.empty()) ctx.message = "constructor failed";
702 sq_settop(squirrel, top);
703 fail(ScriptStage::Reflect, label, 0, std::move(ctx));
704 }
705 }
706 sq_settop(squirrel, top);
707 return instance;
708}
709
710std::vector<ReflectedMember> Runtime::reflectInstance(const ssq::Object& instance) const {
711 std::vector<ReflectedMember> members;
712 if (instance.getType() != ssq::Type::INSTANCE) return members;
713 Runtime* self = const_cast<Runtime*>(this);
714 auto scope = self->enter();
715 auto stack = self->guard();
716 HSQUIRRELVM squirrel = handle();
717 const SQInteger top = sq_gettop(squirrel);
718
719 // Walk the instance's class chain (derived → base) and merge member
720 // metadata; derived members win when a name is overridden.
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);
724 return members;
725 }
726 while (sq_gettype(squirrel, -1) == OT_CLASS) {
727 const SQInteger classTop = sq_gettop(squirrel);
728 for (ReflectedMember& member : collectClassMembersFromStack(squirrel, -1)) {
729 if (!member.method) {
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);
736 }
737 auto existing =
738 std::find_if(members.begin(), members.end(),
739 [&](const ReflectedMember& m) { return m.name == member.name; });
740 if (existing != members.end())
741 *existing = std::move(member);
742 else
743 members.push_back(std::move(member));
744 }
745 sq_settop(squirrel, classTop);
746 // Move to the base class; a missing base ends the chain.
747 if (!SQ_SUCCEEDED(sq_getbase(squirrel, -1)) ||
748 sq_gettype(squirrel, -1) != OT_CLASS) {
749 sq_settop(squirrel, top);
750 break;
751 }
752 sq_remove(squirrel, -2); // drop the derived class, keep the base on top
753 }
754 return members;
755}
756
757ReflectedValue Runtime::readProperty(const ssq::Object& instance,
758 const std::string& name) const {
759 if (name.empty()) return {};
760 Runtime* self = const_cast<Runtime*>(this);
761 auto scope = self->enter();
762 auto stack = self->guard();
763 HSQUIRRELVM squirrel = handle();
764 sq_pushobject(squirrel, instance.getRaw());
765 sq_pushstring(squirrel, name.c_str(), -1);
766 if (SQ_FAILED(sq_get(squirrel, -2))) {
767 return {};
768 }
769 ReflectedValue value = valueFromStack(squirrel, -1);
770 return value;
771}
772
773bool Runtime::writeProperty(const ssq::Object& instance, const std::string& name,
774 const ReflectedValue& value) const {
775 if (name.empty() || value.empty()) return false;
776 Runtime* self = const_cast<Runtime*>(this);
777 auto scope = self->enter();
778 auto stack = self->guard();
779 HSQUIRRELVM squirrel = handle();
780 sq_pushobject(squirrel, instance.getRaw()); // [instance]
781 sq_pushstring(squirrel, name.c_str(), -1); // [instance, name]
782 if (SQ_FAILED(sq_get(squirrel, -2))) { // [instance, current]
783 return false;
784 }
785 const SQObjectType currentType = sq_gettype(squirrel, -1);
786 sq_pop(squirrel, 1); // [instance]
787 if (currentType == OT_CLOSURE || currentType == OT_NATIVECLOSURE ||
788 currentType == OT_CLASS) {
789 return false;
790 }
791 sq_pushstring(squirrel, name.c_str(), -1); // [instance, name]
792 switch (currentType) {
793 case OT_BOOL:
794 sq_pushbool(squirrel, valueToBool(value) ? SQTrue : SQFalse);
795 break;
796 case OT_INTEGER:
797 sq_pushinteger(squirrel, static_cast<SQInteger>(valueToInteger(value)));
798 break;
799 case OT_FLOAT:
800 sq_pushfloat(squirrel, static_cast<SQFloat>(valueToDouble(value)));
801 break;
802 case OT_STRING: {
803 const std::string text = valueToText(value);
804 sq_pushstring(squirrel, text.c_str(), static_cast<SQInteger>(text.size()));
805 break;
806 }
807 default: {
808 // Null/unsupported slot: take the type of the incoming value.
809 switch (value.kind) {
810 case ReflectedValueKind::Bool:
811 sq_pushbool(squirrel, value.asBool() ? SQTrue : SQFalse);
812 break;
813 case ReflectedValueKind::Integer:
814 sq_pushinteger(squirrel, SQInteger(value.asInt()));
815 break;
816 case ReflectedValueKind::Float:
817 sq_pushfloat(squirrel, SQFloat(value.asFloat()));
818 break;
819 case ReflectedValueKind::String:
820 sq_pushstring(squirrel, value.asString().c_str(), -1);
821 break;
822 default: sq_pushnull(squirrel); break;
823 }
824 break;
825 }
826 }
827 // [instance, name, value] — sq_set pops the value and assigns the slot.
828 const bool ok = SQ_SUCCEEDED(sq_set(squirrel, -3));
829 return ok;
830}
831
832ssq::Object Runtime::readObjectProperty(const ssq::Object& instance,
833 const std::string& name) const {
834 if (name.empty()) return {};
835 Runtime* self = const_cast<Runtime*>(this);
836 auto scope = self->enter();
837 auto stack = self->guard();
838 HSQUIRRELVM squirrel = handle();
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) {
843 return {};
844 }
845 ssq::Object out(squirrel);
846 sq_getstackobj(squirrel, -1, &out.getRaw());
847 sq_addref(squirrel, &out.getRaw());
848 return out;
849}
850
851size_t Runtime::arraySize(const ssq::Object& instance,
852 const std::string& name) const {
853 Runtime* self = const_cast<Runtime*>(this);
854 auto scope = self->enter();
855 auto stack = self->guard();
856 HSQUIRRELVM squirrel = handle();
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) {
861 return 0;
862 }
863 const SQInteger len = sq_getsize(squirrel, -1);
864 return len > 0 ? size_t(len) : 0;
865}
866
867ReflectedValue Runtime::arrayGet(const ssq::Object& instance,
868 const std::string& name, size_t index) const {
869 Runtime* self = const_cast<Runtime*>(this);
870 auto scope = self->enter();
871 auto stack = self->guard();
872 HSQUIRRELVM squirrel = handle();
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) {
877 return {};
878 }
879 sq_pushinteger(squirrel, static_cast<SQInteger>(index));
880 if (SQ_FAILED(sq_get(squirrel, -2))) {
881 return {};
882 }
883 const ReflectedValue value = valueFromStack(squirrel, -1);
884 return value;
885}
886
887bool Runtime::arraySet(const ssq::Object& instance, const std::string& name,
888 size_t index, const ReflectedValue& value) const {
889 Runtime* self = const_cast<Runtime*>(this);
890 auto scope = self->enter();
891 auto stack = self->guard();
892 HSQUIRRELVM squirrel = handle();
893 sq_pushobject(squirrel, instance.getRaw()); // [instance]
894 sq_pushstring(squirrel, name.c_str(), -1); // [instance, name]
895 if (SQ_FAILED(sq_get(squirrel, -2)) ||
896 sq_gettype(squirrel, -1) != OT_ARRAY) { // [instance, array]
897 return false;
898 }
899 sq_pushinteger(squirrel, static_cast<SQInteger>(index)); // [.., array, idx]
900 if (SQ_FAILED(sq_get(squirrel, -2))) { // [.., array, current]
901 return false;
902 }
903 const SQObjectType currentType = sq_gettype(squirrel, -1);
904 sq_pop(squirrel, 1); // [.., array]
905 sq_pushinteger(squirrel, static_cast<SQInteger>(index)); // [.., array, idx]
906 pushConvertedValue(squirrel, currentType, value); // [.., array, idx, val]
907 const bool ok = SQ_SUCCEEDED(sq_set(squirrel, -3));
908 return ok;
909}
910
911bool Runtime::arrayAppend(const ssq::Object& instance, const std::string& name,
912 const ReflectedValue& value) const {
913 Runtime* self = const_cast<Runtime*>(this);
914 auto scope = self->enter();
915 auto stack = self->guard();
916 HSQUIRRELVM squirrel = handle();
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) {
921 return false;
922 }
923 pushConvertedValue(squirrel, OT_NULL, value); // value on top
924 const bool ok = SQ_SUCCEEDED(sq_arrayappend(squirrel, -2));
925 return ok;
926}
927
928bool Runtime::arrayRemove(const ssq::Object& instance, const std::string& name,
929 size_t index) const {
930 Runtime* self = const_cast<Runtime*>(this);
931 auto scope = self->enter();
932 auto stack = self->guard();
933 HSQUIRRELVM squirrel = handle();
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) {
938 return false;
939 }
940 // arr.remove(index) via the Squirrel array method.
941 sq_pushstring(squirrel, "remove", -1);
942 if (SQ_FAILED(sq_get(squirrel, -2))) { // [.., array, remove]
943 return false;
944 }
945 sq_push(squirrel, -2); // [.., array, remove, this]
946 sq_pushinteger(squirrel, static_cast<SQInteger>(index)); // [.., this, idx]
947 const bool ok = SQ_SUCCEEDED(sq_call(squirrel, 2, SQFalse, SQTrue));
948 return ok;
949}
950
951std::vector<std::string> Runtime::tableKeys(const ssq::Object& instance,
952 const std::string& name) const {
953 std::vector<std::string> keys;
954 Runtime* self = const_cast<Runtime*>(this);
955 auto scope = self->enter();
956 auto stack = self->guard();
957 HSQUIRRELVM squirrel = handle();
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) {
962 return keys;
963 }
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)
969 keys.push_back(key);
970 }
971 sq_pop(squirrel, 2);
972 }
973 std::sort(keys.begin(), keys.end());
974 return keys;
975}
976
977ReflectedValue Runtime::tableGet(const ssq::Object& instance,
978 const std::string& name,
979 const std::string& key) const {
980 Runtime* self = const_cast<Runtime*>(this);
981 auto scope = self->enter();
982 auto stack = self->guard();
983 HSQUIRRELVM squirrel = handle();
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) {
988 return {};
989 }
990 sq_pushstring(squirrel, key.c_str(), -1);
991 if (SQ_FAILED(sq_get(squirrel, -2))) {
992 return {};
993 }
994 const ReflectedValue value = valueFromStack(squirrel, -1);
995 return value;
996}
997
998bool Runtime::tableSet(const ssq::Object& instance, const std::string& name,
999 const std::string& key, const ReflectedValue& value) const {
1000 Runtime* self = const_cast<Runtime*>(this);
1001 auto scope = self->enter();
1002 auto stack = self->guard();
1003 HSQUIRRELVM squirrel = handle();
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) {
1008 return false;
1009 }
1010 sq_pushstring(squirrel, key.c_str(), -1);
1011 SQObjectType currentType = OT_NULL;
1012 if (SQ_SUCCEEDED(sq_get(squirrel, -2))) { // [.., table, current]
1013 currentType = sq_gettype(squirrel, -1);
1014 sq_pop(squirrel, 1); // [.., table]
1015 }
1016 sq_pushstring(squirrel, key.c_str(), -1); // [.., table, key]
1017 pushConvertedValue(squirrel, currentType, value); // [.., table, key, val]
1018 bool ok = SQ_SUCCEEDED(sq_set(squirrel, -3));
1019 if (!ok) {
1020 // Squirrel 3.1's sq_set only updates existing keys; a missing key
1021 // needs sq_newslot to insert (v->Set raises "index does not exist").
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) {
1027 return false;
1028 }
1029 sq_pushstring(squirrel, key.c_str(), -1);
1030 pushConvertedValue(squirrel, OT_NULL, value);
1031 ok = SQ_SUCCEEDED(sq_newslot(squirrel, -3, SQFalse));
1032 }
1033 return ok;
1034}
1035
1036bool Runtime::tableRemove(const ssq::Object& instance, const std::string& name,
1037 const std::string& key) const {
1038 Runtime* self = const_cast<Runtime*>(this);
1039 auto scope = self->enter();
1040 auto stack = self->guard();
1041 HSQUIRRELVM squirrel = handle();
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) {
1046 return false;
1047 }
1048 sq_pushstring(squirrel, key.c_str(), -1);
1049 const bool ok = SQ_SUCCEEDED(sq_deleteslot(squirrel, -2, SQFalse));
1050 return ok;
1051}
1052
1054 auto found = scripts_.find(id);
1055 if (found == scripts_.end())
1056 throw ScriptException(ScriptStage::Compile, {}, id, "unknown script");
1057 const bool fromFile = found->second->from_file;
1058 const std::string input = found->second->source_text;
1059 const std::string source = found->second->info.source;
1060 unload(id);
1061 return fromFile ? runFile(input) : runSource(input, source);
1062}
1063
1065 auto found = scripts_.find(id);
1066 if (found == scripts_.end()) return false;
1067 ScriptRecord& record = *found->second;
1068 if (record.info.state == ScriptState::Unloaded) return false;
1069 auto scope = enter();
1070 auto stack = guard();
1071 record.info.state = ScriptState::Unloading;
1072 notifyLifecycle(record.info);
1073 try {
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);
1083 sq_pop(handle(), 1);
1084 }
1085 classes_.erase(pair.first);
1086 class_owners_.erase(owner);
1087 class_identities_.erase(pair.first);
1088 }
1089 record.class_objects.clear();
1090 record.compiled.reset();
1091 record.info.state = ScriptState::Unloaded;
1092 notifyLifecycle(record.info);
1093 return true;
1094 } catch (const std::exception& error) {
1095 record.info.state = ScriptState::Failed;
1096 record.info.error = error.what();
1097 notifyLifecycle(record.info);
1098 fail(ScriptStage::Unload, record.info.source, id, error);
1099 }
1100}
1101
1102void Runtime::unloadAll() noexcept {
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());
1107 for (ScriptId id : ids) {
1108 try {
1109 unload(id);
1110 } catch (...) {
1111 }
1112 }
1113 scripts_.clear();
1114}
1115
1116bool Runtime::contains(ScriptId id) const noexcept { return scripts_.count(id) != 0; }
1117
1118const ScriptInfo* Runtime::script(ScriptId id) const noexcept {
1119 auto found = scripts_.find(id);
1120 return found == scripts_.end() ? nullptr : &found->second->info;
1121}
1122
1123std::vector<ScriptInfo> Runtime::scripts() const {
1124 std::vector<ScriptInfo> result;
1125 result.reserve(scripts_.size());
1126 for (const auto& pair : scripts_) result.push_back(pair.second->info);
1127 std::sort(result.begin(), result.end(), [](const ScriptInfo& a, const ScriptInfo& b) {
1128 return a.id < b.id;
1129 });
1130 return result;
1131}
1132
1133const ReflectedClass* Runtime::reflectedClass(const std::string& name) const noexcept {
1134 auto found = classes_.find(name);
1135 return found == classes_.end() ? nullptr : &found->second;
1136}
1137
1138std::vector<ReflectedClass> Runtime::reflectedClasses() const {
1139 std::vector<ReflectedClass> result;
1140 result.reserve(classes_.size());
1141 for (const auto& pair : classes_) result.push_back(pair.second);
1142 std::sort(result.begin(), result.end(), [](const ReflectedClass& a, const ReflectedClass& b) {
1143 return a.name < b.name;
1144 });
1145 return result;
1146}
1147
1149 auto scope = enter();
1150 auto stack = guard();
1151 const auto after = rootClasses();
1152 size_t scanned = 0;
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;
1156 try {
1157 ssq::Class cls = vm_->findClass(pair.first.c_str());
1158 std::string source;
1159 auto clsInfo = classes_.find(pair.first);
1160 if (clsInfo != classes_.end()) source = clsInfo->second.source;
1161 if (source.empty()) source = "<runtime scan>";
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;
1165 ++scanned;
1166 } catch (...) {
1167 // Not a script class (e.g. native class): skip.
1168 }
1169 }
1170 // Resolve base names against the current root set (also covers classes
1171 // replaced by hot reload whose base relationship changed).
1172 for (const auto& pair : after) {
1173 auto info = classes_.find(pair.first);
1174 if (info == classes_.end()) continue;
1175 try {
1176 const ssq::Class cls = vm_->findClass(pair.first.c_str());
1177 StackGuard stackGuard(*this);
1178 sq_pushobject(handle(), cls.getRaw());
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;
1187 break;
1188 }
1189 }
1190 }
1191 }
1192 } catch (...) {
1193 }
1194 }
1195 return scanned;
1196}
1197
1198ssq::Class Runtime::findClass(const std::string& name) const {
1199 const bool validName = !name.empty();
1200 EV_PARAM_CHECK(validName, "class name must not be empty");
1201 return vm_->findClass(name.c_str());
1202}
1203
1204std::string Runtime::classNameOf(const ssq::Object& instance) const {
1205 if (instance.getType() != ssq::Type::INSTANCE) return {};
1206 Runtime* self = const_cast<Runtime*>(this);
1207 auto scope = self->enter();
1208 auto stack = self->guard();
1209 HSQUIRRELVM squirrel = handle();
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);
1215 return {};
1216 }
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;
1223 }
1224 return {};
1225}
1226
1227void Runtime::notifyLifecycle(const ScriptInfo& info) noexcept {
1228 if (!lifecycle_handler_) return;
1229 try {
1230 lifecycle_handler_(info);
1231 } catch (...) {
1232 }
1233}
1234
1235script::ScriptErrorContext Runtime::compileErrorContext(const std::string& what,
1236 const std::string& sourceText) {
1237 script::ScriptErrorContext ctx;
1238 ctx.message = what;
1239 if (!script::parseCompileError(what, &ctx.source, &ctx.line, &ctx.column, &ctx.message))
1240 return ctx;
1241 const std::string lineText = script::sourceLineText(sourceText, ctx.line);
1242 if (lineText.empty()) return ctx;
1243 std::string hint = std::to_string(ctx.line) + " | " + lineText;
1244 if (ctx.column > 0) {
1245 hint += "\n";
1246 const size_t caret = static_cast<size_t>(ctx.column > 1 ? ctx.column - 1 : 0);
1247 hint.append(caret, ' ');
1248 hint += '^';
1249 }
1250 ctx.hint = std::move(hint);
1251 return ctx;
1252}
1253
1254[[noreturn]] void Runtime::fail(ScriptStage stage, const std::string& source, ScriptId id,
1255 script::ScriptErrorContext context) {
1256 ScriptException wrapped(stage, source, id, context);
1257 if (error_handler_) {
1258 try {
1259 error_handler_(wrapped);
1260 } catch (...) {
1261 }
1262 }
1263 throw wrapped;
1264}
1265
1266[[noreturn]] void Runtime::fail(ScriptStage stage, const std::string& source, ScriptId id,
1267 const std::exception& error) {
1268 script::ScriptErrorContext ctx = script::takeLastScriptError(handle());
1269 const char* what = error.what();
1270 const std::string message = what ? what : "";
1271 // notifyallexceptions records every caught throw (e.g. file_exists). Only
1272 // keep that snapshot when it actually describes this failure.
1273 if (ctx.empty() ||
1274 (ctx.message != message && message.find(ctx.message) == std::string::npos &&
1275 ctx.message.find(message) == std::string::npos)) {
1276 ctx = {};
1277 ctx.message = message;
1278 }
1279 fail(stage, source, id, std::move(ctx));
1280}
1281
1282std::unordered_map<std::string, SQUserPointer> Runtime::rootClasses() const {
1283 std::unordered_map<std::string, SQUserPointer> result;
1284 StackGuard stack(*const_cast<Runtime*>(this));
1285 HSQUIRRELVM squirrel = handle();
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;
1291 HSQOBJECT object;
1292 if (SQ_SUCCEEDED(sq_getstring(squirrel, -2, &name)) && name &&
1293 SQ_SUCCEEDED(sq_getstackobj(squirrel, -1, &object)))
1294 result[name] = objectIdentity(object);
1295 }
1296 sq_pop(squirrel, 2);
1297 }
1298 return result;
1299}
1300
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;
1315 }
1316 std::sort(record.info.classes.begin(), record.info.classes.end());
1317
1318 // Resolve base class names after every newly defined class is registered.
1319 for (const std::string& name : record.info.classes) {
1320 auto info = classes_.find(name);
1321 auto cls = record.class_objects.find(name);
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;
1332 break;
1333 }
1334 }
1335 }
1336 }
1337 }
1338}
1339
1340ReflectedClass Runtime::inspectClass(const std::string& name, const ssq::Class& cls,
1341 const std::string& source) const {
1342 ReflectedClass info;
1343 info.name = name;
1344 info.source = source;
1345 info.members = collectClassMembers(cls);
1346 return info;
1347}
1348
1349std::vector<ReflectedMember> Runtime::collectClassMembers(const ssq::Class& cls) const {
1350 std::vector<ReflectedMember> members;
1351 Runtime* self = const_cast<Runtime*>(this);
1352 auto scope = self->enter();
1353 auto stack = self->guard();
1354 HSQUIRRELVM squirrel = handle();
1355 const SQInteger top = sq_gettop(squirrel);
1356 sq_pushobject(squirrel, cls.getRaw());
1357 members = collectClassMembersFromStack(squirrel, -1);
1358 sq_settop(squirrel, top);
1359 return members;
1360}
1361
1362} // namespace eve
double m[16]
EVEngine assertion entry point, backed by zeroerr.
#define EV_PARAM_CHECK(cond,...)
Validate a function parameter / public API precondition.
Definition Assert.h:30
std::vector< QuestEvent > pending
struct SQVM * HSQUIRRELVM
HSQUIRRELVM vm
Definition ECS.cpp:38
HSQOBJECT cls
Definition ECS.cpp:39
SQObjectPtr key
Definition ECS.cpp:155
ScriptComponentRecord record
Definition ECS.cpp:228
std::string name
Definition ECS.cpp:154
EvpackChunkInput input
Definition Evpack.cpp:170
std::string message
float v
std::int32_t first
JobScope scope
std::string label
std::string id
Poco::JSON::Object::Ptr result
MeleePoint3 b
Definition MeleeHit.cpp:41
MeleePoint3 a
Definition MeleeHit.cpp:40
std::shared_ptr< OceanGpuSpectrum > owner
std::string error
Definition Package.cpp:174
std::string script
Definition PlayHost.cpp:117
std::string path
Definition PlayHost.cpp:111
Object::Ptr value
std::map< std::string, double > attributes
std::string attribute
bool found
std::string text
ScriptStructure out
std::string_view source
size_t end
const SquirrelValueOptions & options
Explicit Value/Owned/Borrowed semantics at the Squirrel boundary.
Json object
float(ui::Theme::* member)[4]
std::map< std::string, std::span< const std::uint8_t > > members
uint32_t index
const VegetationPresetContext & context
uint64_t identity
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.
Definition Module.cpp:204
Pushes this Runtime on the current thread's runtime stack.
Definition Runtime.h:220
Scope(Runtime &runtime)
Scope.
Definition Runtime.cpp:445
Restores the native Squirrel stack when a binding operation leaves scope.
Definition Runtime.h:196
StackGuard & operator=(StackGuard &&other) noexcept
Operator =.
Definition Runtime.cpp:437
~StackGuard()
Stack guard.
Definition Runtime.cpp:430
StackGuard(Runtime &runtime) noexcept
Stack guard.
Definition Runtime.cpp:427
EVENGINE_API_FOUNDATION public API.
Definition Runtime.h:189
void shutdown() noexcept
Tears down the VM and detaches the runtime; idempotent and noexcept.
Definition Runtime.cpp:488
ssq::Class findClass(const std::string &name) const
Finds a script class by name (throws if it does not exist).
Definition Runtime.cpp:1198
ScriptId runFile(const std::string &path)
Convenience: compileFile() then execute().
Definition Runtime.cpp:650
void unloadAll() noexcept
Unloads every script.
Definition Runtime.cpp:1102
static Runtime * current() noexcept
The runtime currently at the top of this thread's runtime stack, or nullptr.
Definition Runtime.cpp:536
ssq::Table table(const char *name) const
Looks up a named global table.
Definition Runtime.cpp:530
bool contains(ScriptId id) const noexcept
True if a script with the given id is tracked.
Definition Runtime.cpp:1116
ScriptId compileSource(std::string source, std::string sourceName="buffer")
Compiles script source without running it.
Definition Runtime.cpp:542
bool arrayRemove(const ssq::Object &instance, const std::string &name, size_t index) const
Removes one element of an array member (shifts the rest).
Definition Runtime.cpp:928
bool unload(ScriptId id)
Unloads a script and removes its declared classes; false if unknown/unloaded.
Definition Runtime.cpp:1064
ScriptId reload(ScriptId id)
Recompiles and re-runs a script from its original source.
Definition Runtime.cpp:1053
Runtime(size_t stackSize=2048, ssq::Libs::Flag libraries=ssq::Libs::ALL)
Creates a script runtime with its own Squirrel VM.
Definition Runtime.cpp:456
std::vector< ReflectedMember > reflectInstance(const ssq::Object &instance) const
Inspects a live instance: own + inherited members with current values.
Definition Runtime.cpp:710
std::vector< ReflectedClass > reflectedClasses() const
All reflected classes, sorted by name.
Definition Runtime.cpp:1138
script::ScriptModuleResolver & scriptModules() noexcept
Script module provider registry and dependency resolver for this VM.
Definition Runtime.cpp:523
ssq::Object createInstance(const std::string &name, const std::string &source={})
Creates a live instance of a script class (default constructor).
Definition Runtime.cpp:670
const ReflectedClass * reflectedClass(const std::string &name) const noexcept
Reflected class by name, or nullptr.
Definition Runtime.cpp:1133
ReflectedValue tableGet(const ssq::Object &instance, const std::string &name, const std::string &key) const
Value of a table member key; empty when missing.
Definition Runtime.cpp:977
bool writeProperty(const ssq::Object &instance, const std::string &name, const ReflectedValue &value) const
Writes one property of a live instance.
Definition Runtime.cpp:773
ssq::Object readObjectProperty(const ssq::Object &instance, const std::string &name) const
Reads a live object-valued property (nested instance).
Definition Runtime.cpp:832
static size_t stackDepth() noexcept
Depth of the thread-local runtime stack.
Definition Runtime.cpp:540
ScriptId runSource(std::string source, std::string sourceName="buffer")
Convenience: compileSource() then execute().
Definition Runtime.cpp:644
StackGuard guard() noexcept
RAII guard that restores the Squirrel stack top on scope exit.
Definition Runtime.h:277
bool initialized() const noexcept
True once initialize() has completed successfully.
Definition Runtime.cpp:519
bool tableRemove(const ssq::Object &instance, const std::string &name, const std::string &key) const
Removes a key from a table member.
Definition Runtime.cpp:1036
size_t scanClasses()
Scans the root table for script classes and refreshes reflection.
Definition Runtime.cpp:1148
script::ScriptCompiler & scriptCompiler() noexcept
Unified EveScript compiler, metadata store, and binding contracts.
Definition Runtime.cpp:527
ScriptId compileFile(const std::string &path)
Compiles a script file without running it.
Definition Runtime.cpp:564
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).
Definition Runtime.cpp:998
void initialize()
Exposes registered engine modules into the script root table. Safe to call more than once.
Definition Runtime.cpp:466
bool arrayAppend(const ssq::Object &instance, const std::string &name, const ReflectedValue &value) const
Appends an element to an array member.
Definition Runtime.cpp:911
uint64_t ScriptId
Definition Runtime.h:191
const ReflectedClass & reflectClass(const std::string &name, const std::string &source={})
Reflects a class by name, storing its inspected members.
Definition Runtime.cpp:656
const ScriptInfo * script(ScriptId id) const noexcept
Script metadata for an id, or nullptr if unknown.
Definition Runtime.cpp:1118
std::string classNameOf(const ssq::Object &instance) const
Name of the script class of a live instance ("" when unknown).
Definition Runtime.cpp:1204
HSQUIRRELVM handle() const noexcept
Raw Squirrel VM handle; nullptr after shutdown.
Definition Runtime.cpp:522
ReflectedValue readProperty(const ssq::Object &instance, const std::string &name) const
Reads one property of a live instance.
Definition Runtime.cpp:757
size_t arraySize(const ssq::Object &instance, const std::string &name) const
Element count of an array member (0 when missing/not an array).
Definition Runtime.cpp:851
bool arraySet(const ssq::Object &instance, const std::string &name, size_t index, const ReflectedValue &value) const
Replaces one element of an array member.
Definition Runtime.cpp:887
ssq::Table root() const
Root script table of the VM.
Definition Runtime.cpp:529
Scope enter()
Pushes this runtime on the thread-local runtime stack (RAII pop).
Definition Runtime.h:279
ssq::VM & vm() noexcept
Underlying SimpleSquirrel VM (requires a live, initialized runtime).
Definition Runtime.cpp:520
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.
Definition Runtime.cpp:867
std::vector< ScriptInfo > scripts() const
Metadata for all tracked scripts, sorted by id.
Definition Runtime.cpp:1123
std::vector< std::string > tableKeys(const ssq::Object &instance, const std::string &name) const
String keys of a table member.
Definition Runtime.cpp:951
const ScriptInfo & execute(ScriptId id)
Runs a previously compiled script; throws ScriptException on failure.
Definition Runtime.cpp:588
Exception raised at the public Runtime boundary.
Definition Runtime.h:61
ScriptStage stage() const noexcept
Stage.
Definition Runtime.h:77
const std::string & source() const noexcept
Source.
Definition Runtime.h:79
ScriptException(ScriptStage stage, std::string source, uint64_t scriptId, const std::string &message)
Script exception.
Definition Runtime.cpp:341
uint64_t scriptId() const noexcept
Script id.
Definition Runtime.h:81
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::unordered_map< const void *, size_t > ids
Definition Snapshot.cpp:109
SQInteger top
Definition Snapshot.cpp:115
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.
Definition Runtime.cpp:320
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).
Definition Build.cpp:16
std::string reflectedFloatString(double value)
Shortest round-trip float formatting (portable).
Definition Runtime.h:33
ScriptStage
ScriptStage public API.
Definition Runtime.h:52
void exposeReflection(Runtime &runtime, ssq::Table eveTable)
Exposes the Runtime reflection API to scripts as eve.reflect.
EVENGINE_API_FOUNDATION_INLINE public API.
Definition Runtime.h:107
EVENGINE_API_FOUNDATION_INLINE public API.
Definition Runtime.h:172
EVENGINE_API_FOUNDATION public API.
Definition Runtime.h:152
bool attrBool(const std::string &name, bool def=false) const noexcept
Boolean attribute value; def when missing or not boolean.
Definition Runtime.cpp:391
float attrFloat(const std::string &name, float def=0.f) const noexcept
Numeric attribute value; def when missing or not numeric.
Definition Runtime.cpp:381
const ReflectedAttribute * findAttribute(const std::string &name) const noexcept
Looks up an attribute by name; nullptr when absent.
Definition Runtime.cpp:374
std::string name
Definition Runtime.h:153
std::string attrString(const std::string &name, const std::string &def={}) const
Raw string attribute value; def when missing.
Definition Runtime.cpp:403
std::vector< std::string > attrOptions(const std::string &name) const
Comma-separated string attribute split into trimmed options.
Definition Runtime.cpp:409
Typed snapshot of one live instance property.
Definition Runtime.h:132
std::unique_ptr< ssq::Script > compiled
Definition Runtime.cpp:337
std::unordered_map< std::string, ssq::Class > class_objects
Definition Runtime.cpp:338
EVENGINE_API_FOUNDATION_INLINE public API.
Definition Runtime.h:180
Structured snapshot of a script error: message, throw site and stack.
Definition ScriptError.h:46
bool empty() const noexcept
True when no error payload was captured.
Definition ScriptError.h:57
std::string message
Raw error value ("kaboom", "42", ...).
Definition ScriptError.h:47
glm::uvec4 info