载入中...
搜索中...
未找到
ScriptModule.cpp
浏览该文件的文档.
2
3#include "common/Capability.h"
7
8#include <squirrel.h>
9
10#include <algorithm>
11#include <fstream>
12#include <optional>
13#include <sstream>
14#include <unordered_map>
15#include <unordered_set>
16#include <utility>
17
18namespace eve::script {
19namespace {
20
21std::string normalizedPath(std::string value, bool& escaped) {
22 std::replace(value.begin(), value.end(), '\\', '/');
23 std::vector<std::string> parts;
24 size_t begin = 0;
25 while (begin <= value.size()) {
26 const size_t end = value.find('/', begin);
27 const std::string part = value.substr(begin, end - begin);
28 if (part.empty() || part == ".") {
29 } else if (part == "..") {
30 if (parts.empty()) {
31 escaped = true;
32 return {};
33 }
34 parts.pop_back();
35 } else {
36 parts.push_back(part);
37 }
38 if (end == std::string::npos) break;
39 begin = end + 1;
40 }
41 std::ostringstream out;
42 for (size_t i = 0; i < parts.size(); ++i) {
43 if (i) out << '/';
44 out << parts[i];
45 }
46 return out.str();
47}
48
49std::string hashSource(std::string_view source) {
50 uint64_t hash = 1469598103934665603ull;
51 for (const unsigned char c : source) {
52 hash ^= c;
53 hash *= 1099511628211ull;
54 }
55 std::ostringstream out;
56 out << std::hex << hash;
57 return out.str();
58}
59
60class GameFileProvider final : public IScriptModuleProvider {
61public:
62 ScriptModuleStatus resolve(const ScriptModuleRequest& request, std::string& canonicalUri,
63 std::string& error) override {
65 return canonicalUri.rfind("game:/", 0) == 0 ? ScriptModuleStatus::Found : ScriptModuleStatus::NotHandled;
66 }
67
68 ScriptModuleStatus load(std::string_view canonicalUri, ScriptModuleSource& source, std::string& error) override {
69 if (canonicalUri.rfind("game:/", 0) != 0) return ScriptModuleStatus::NotHandled;
70 const std::string path(canonicalUri.substr(6));
71 std::vector<uint8_t> bytes;
72 if (auto* filesystem = eve::cap::query<eve::service::IFileSystem>();
73 filesystem && filesystem->readFile(path, bytes)) {
74 source.utf8Source.assign(reinterpret_cast<const char*>(bytes.data()), bytes.size());
75 } else {
76 std::ifstream input(path, std::ios::binary);
77 if (!input) {
78 error = "script module not found: " + std::string(canonicalUri);
80 }
81 source.utf8Source.assign(std::istreambuf_iterator<char>(input), {});
82 }
83 source.canonicalUri = std::string(canonicalUri);
84 source.debugOrigin = path;
85 source.contentHash = hashSource(source.utf8Source);
87 }
88};
89
90} // namespace
91
94 ProviderId id = 0;
95 int priority = 0;
96 };
97 struct Module {
100 HSQOBJECT closure{};
101 HSQOBJECT exports{};
103 std::vector<std::string> dependencies;
104 };
105
106 explicit Impl(SQVM* inVm) : vm(inVm) { sq_setmodulehandlers(vm, &dependencyCallback, &importCallback, this); }
108 sq_setmodulehandlers(vm, nullptr, nullptr, nullptr);
109 for (auto& [_, module] : modules) {
110 if (!sq_isnull(module.closure)) sq_release(vm, &module.closure);
111 if (!sq_isnull(module.exports)) sq_release(vm, &module.exports);
112 }
113 }
114
115 static SQRESULT dependencyCallback(HSQUIRRELVM, const SQChar* importer, const SQChar* specifier,
116 SQUserPointer user) {
117 auto& self = *static_cast<Impl*>(user);
118 try {
119 const std::string dependency = self.ensureCompiled(importer, specifier);
120 auto& edges = self.dependencies[importer];
121 if (std::find(edges.begin(), edges.end(), dependency) == edges.end()) edges.push_back(dependency);
122 return SQ_OK;
123 } catch (const std::exception& error) {
124 self.recordCompilationFailure(error.what());
125 return SQ_ERROR;
126 }
127 }
128
129 static SQRESULT importCallback(HSQUIRRELVM vm, const SQChar* importer, const SQChar* specifier, SQUserPointer user,
130 HSQOBJECT* exports) {
131 auto& self = *static_cast<Impl*>(user);
132 try {
133 const std::string canonical = self.resolve({importer, specifier});
134 const auto found = self.modules.find(canonical);
135 if (found == self.modules.end() || found->second.state != Module::State::Ready)
136 throw std::runtime_error("module was not instantiated before import: " + canonical);
137 *exports = found->second.exports;
138 return SQ_OK;
139 } catch (const std::exception& error) {
140 self.recordCompilationFailure(error.what());
141 return sq_throwerror(vm, error.what());
142 }
143 }
144
148
149 std::string resolve(const ScriptModuleRequest& request) {
150 std::string attempts;
151 for (const auto& entry : providerSnapshot()) {
152 std::string canonical;
153 std::string error;
154 const auto status = entry.provider->resolve(request, canonical, error);
155 if (status == ScriptModuleStatus::Found) return canonical;
157 throw std::runtime_error(error.empty() ? "module resolution failed" : error);
158 if (!attempts.empty()) attempts += ", ";
159 attempts += std::to_string(entry.metadata.id);
160 }
161 throw std::runtime_error("no script module provider handled '" + request.specifier + "' imported by '" +
162 request.importerUri + "' (providers: " + attempts + ")");
163 }
164
165 ScriptModuleSource load(const std::string& canonical) {
166 for (const auto& entry : providerSnapshot()) {
168 std::string error;
169 const auto status = entry.provider->load(canonical, source, error);
170 if (status == ScriptModuleStatus::NotHandled) continue;
172 throw std::runtime_error(error.empty() ? "module load failed" : error);
173 if (source.canonicalUri != canonical)
174 throw std::runtime_error("module provider returned inconsistent identity: " + source.canonicalUri +
175 " != " + canonical);
176 return source;
177 }
178 throw std::runtime_error("no script module provider can load: " + canonical);
179 }
180
181 std::string ensureCompiled(std::string_view importer, std::string_view specifier) {
182 const std::string canonical = resolve({std::string(importer), std::string(specifier)});
183 if (const auto found = modules.find(canonical); found != modules.end()) {
184 if (found->second.state == Module::State::Compiling)
185 throw std::runtime_error("cyclic script import: " + canonical);
186 return canonical;
187 }
188
189 Module& module = modules[canonical];
190 sq_resetobject(&module.closure);
191 sq_resetobject(&module.exports);
192 module.source = load(canonical);
193 module.state = Module::State::Compiling;
194 const SQInteger top = sq_gettop(vm);
195 if (SQ_FAILED(sq_compilebuffer(vm, module.source.utf8Source.c_str(),
196 static_cast<SQInteger>(module.source.utf8Source.size()), canonical.c_str(),
197 SQTrue))) {
198 sq_settop(vm, top);
199 modules.erase(canonical);
201 std::string failure = std::move(*pendingCompilationFailure);
203 throw std::runtime_error(std::move(failure));
204 }
205 throw std::runtime_error("failed to compile script module: " + canonical);
206 }
207 sq_getstackobj(vm, -1, &module.closure);
208 sq_addref(vm, &module.closure);
209 sq_settop(vm, top);
210 module.dependencies = dependencies[canonical];
211 module.state = Module::State::Compiled;
212 return canonical;
213 }
214
215 void instantiate(const std::string& canonical) {
216 auto found = modules.find(canonical);
217 if (found == modules.end()) throw std::runtime_error("unknown script module: " + canonical);
218 instantiateModule(canonical, found->second);
219 }
220
221 void instantiateModule(const std::string& canonical, Module& module) {
222 if (module.state == Module::State::Ready) return;
224 throw std::runtime_error("cyclic script module instantiation: " + canonical);
225 module.state = Module::State::Instantiating;
226 for (const std::string& dependency : module.dependencies) instantiate(dependency);
227
228 const SQInteger top = sq_gettop(vm);
229 sq_newtable(vm); // env
230 sq_pushroottable(vm); // env, root
231 sq_setdelegate(vm, -2); // env
232 sq_pushstring(vm, "__exports", -1); // env, key
233 sq_newtable(vm); // env, key, exports
234 sq_getstackobj(vm, -1, &module.exports);
235 sq_addref(vm, &module.exports);
236 sq_newslot(vm, -3, SQFalse); // env
237 // The derivable count only works when the callable is the first value above the
238 // recorded height: the `env` table below stays, so `top` is not the right base.
239 const SQInteger callTop = sq_gettop(vm);
240 sq_pushobject(vm, module.closure); // env, closure
241 sq_push(vm, -2); // env, closure, env
242 sq_setclosureroot(vm, -2); // env, closure
243 sq_push(vm, -2); // env, closure, env(this)
244 // The parameter count is derived from the pushes (R-FACE-7), and the failure now
245 // carries the script error: a module body that threw used to reach the caller as
246 // "failed to instantiate" with no way to tell why.
247 const SQInteger params = sq_gettop(vm) - callTop - 1; // receiver + arguments
248 if (SQ_FAILED(sq_call(vm, params, SQFalse, SQTrue))) {
249 const std::string detail = reportScriptCallFailure(vm, "script.instantiate");
250 sq_settop(vm, top);
251 module.state = Module::State::Compiled;
252 sq_release(vm, &module.exports);
253 sq_resetobject(&module.exports);
254 throw std::runtime_error("failed to instantiate script module: " + canonical + ": " + detail);
255 }
256 sq_settop(vm, top);
257 module.state = Module::State::Ready;
258 }
259
260 void release(Module& module) {
261 if (!sq_isnull(module.closure)) sq_release(vm, &module.closure);
262 if (!sq_isnull(module.exports)) sq_release(vm, &module.exports);
263 sq_resetobject(&module.closure);
264 sq_resetobject(&module.exports);
265 }
266
267 std::vector<std::string> reloadAffected(const std::string& canonical) {
268 if (modules.find(canonical) == modules.end()) return {};
269
270 std::unordered_set<std::string> affected{canonical};
271 bool changed = true;
272 while (changed) {
273 changed = false;
274 for (const auto& [importer, edges] : dependencies) {
275 if (affected.count(importer) || modules.find(importer) == modules.end()) continue;
276 if (std::any_of(edges.begin(), edges.end(), [&](const auto& edge) { return affected.count(edge); })) {
277 affected.insert(importer);
278 changed = true;
279 }
280 }
281 }
282
283 std::vector<std::string> order(affected.begin(), affected.end());
284 std::sort(order.begin(), order.end());
285 const auto previousEdges = dependencies;
286 std::unordered_set<std::string> previousKeys;
287 for (const auto& [uri, _] : modules) previousKeys.insert(uri);
288
289 std::unordered_map<std::string, Module> previous;
290 for (const std::string& uri : order) {
291 auto found = modules.find(uri);
292 if (found == modules.end()) continue;
293 previous.emplace(uri, std::move(found->second));
294 modules.erase(found);
295 dependencies.erase(uri);
296 }
297
298 try {
299 for (const std::string& uri : order) ensureCompiled("game:/__hot_reload__.nut", uri);
300 for (const std::string& uri : order) instantiate(uri);
301 } catch (...) {
302 for (auto it = modules.begin(); it != modules.end();) {
303 if (affected.count(it->first) || !previousKeys.count(it->first)) {
304 release(it->second);
305 it = modules.erase(it);
306 } else {
307 ++it;
308 }
309 }
310 for (auto& [uri, module] : previous) modules.emplace(uri, std::move(module));
311 dependencies = previousEdges;
312 throw;
313 }
314
315 for (auto& [_, module] : previous) release(module);
316 return order;
317 }
318
319 SQVM* vm = nullptr;
322
323 std::vector<eve::cap::ProviderRegistry<IScriptModuleProvider, ProviderEntry>::Record> providerSnapshot() const {
324 auto records = providers.snapshot();
325 std::sort(records.begin(), records.end(), [](const auto& a, const auto& b) {
326 if (a.metadata.priority != b.metadata.priority) return a.metadata.priority > b.metadata.priority;
327 return a.metadata.id < b.metadata.id;
328 });
329 return records;
330 }
331 std::unordered_map<std::string, Module> modules;
332 std::unordered_map<std::string, std::vector<std::string>> dependencies;
333 std::optional<std::string> pendingCompilationFailure;
334};
335
336ScriptModuleResolver::ScriptModuleResolver(SQVM* vm) : impl_(std::make_unique<Impl>(vm)) {}
338
340 int priority) {
341 if (!provider) return 0;
342 const ProviderId id = impl_->nextProviderId++;
343 auto registered =
344 impl_->providers.publish(std::to_string(id), std::move(provider), Impl::ProviderEntry{id, priority});
345 if (!registered.ok()) return 0;
346 return id;
347}
348
350 auto entry = impl_->providers.acquire(std::to_string(id));
351 if (!entry.ok()) return false;
352 return impl_->providers.withdraw(entry.value().handle).ok();
353}
354
355void ScriptModuleResolver::registerDefaultProviders() { registerProvider(std::make_shared<GameFileProvider>()); }
356
357void ScriptModuleResolver::beginCompilation(std::string_view importerUri) {
358 impl_->pendingCompilationFailure.reset();
359 impl_->dependencies.erase(std::string(importerUri));
360}
361
363 std::optional<std::string> failure = std::move(impl_->pendingCompilationFailure);
364 impl_->pendingCompilationFailure.reset();
365 return failure;
366}
367
368void ScriptModuleResolver::prepareDependencies(std::string_view importerUri) {
369 enum class Visit { Visiting, Ready };
370 std::unordered_map<std::string, Visit> visits;
371 std::vector<std::string> stack;
372 const auto verify = [&](const auto& self, const std::string& uri) -> void {
373 if (const auto seen = visits.find(uri); seen != visits.end()) {
374 if (seen->second == Visit::Ready) return;
375 std::string cycle;
376 const auto begin = std::find(stack.begin(), stack.end(), uri);
377 for (auto it = begin; it != stack.end(); ++it) {
378 if (!cycle.empty()) cycle += " -> ";
379 cycle += *it;
380 }
381 if (!cycle.empty()) cycle += " -> ";
382 throw std::runtime_error("cyclic script import: " + cycle + uri);
383 }
384
385 visits.emplace(uri, Visit::Visiting);
386 stack.push_back(uri);
387 const auto edges = impl_->dependencies.find(uri);
388 if (edges != impl_->dependencies.end()) {
389 for (const std::string& dependency : edges->second) {
390 if (impl_->modules.find(dependency) == impl_->modules.end())
391 throw std::runtime_error("script dependency was not compiled: " + dependency);
392 self(self, dependency);
393 }
394 }
395 stack.pop_back();
396 visits[uri] = Visit::Ready;
397 };
398
399 const std::string root(importerUri);
400 const auto edges = impl_->dependencies.find(root);
401 if (edges == impl_->dependencies.end()) return;
402 for (const std::string& dependency : edges->second) verify(verify, dependency);
403}
404
405void ScriptModuleResolver::instantiateDependencies(std::string_view importerUri) {
406 const auto found = impl_->dependencies.find(std::string(importerUri));
407 if (found == impl_->dependencies.end()) return;
408 for (const std::string& dependency : found->second) impl_->instantiate(dependency);
409}
410
411void ScriptModuleResolver::invalidate(std::string_view canonicalUri) {
412 std::unordered_set<std::string> invalid{std::string(canonicalUri)};
413 bool changed = true;
414 while (changed) {
415 changed = false;
416 for (const auto& [importer, deps] : impl_->dependencies) {
417 if (!invalid.count(importer) &&
418 std::any_of(deps.begin(), deps.end(), [&](const auto& dep) { return invalid.count(dep); })) {
419 invalid.insert(importer);
420 changed = true;
421 }
422 }
423 }
424 for (const std::string& uri : invalid) {
425 const auto found = impl_->modules.find(uri);
426 if (found == impl_->modules.end()) continue;
427 if (!sq_isnull(found->second.closure)) sq_release(impl_->vm, &found->second.closure);
428 if (!sq_isnull(found->second.exports)) sq_release(impl_->vm, &found->second.exports);
429 impl_->modules.erase(found);
430 impl_->dependencies.erase(uri);
431 }
432}
433
434void ScriptModuleResolver::reload(std::string_view canonicalUri) {
435 if (impl_->reloadAffected(std::string(canonicalUri)).empty())
436 throw std::runtime_error("cannot reload unknown script module: " + std::string(canonicalUri));
437}
438
439std::vector<std::string> ScriptModuleResolver::reloadAffected(std::string_view canonicalUri) {
440 return impl_->reloadAffected(std::string(canonicalUri));
441}
442
443std::vector<std::string> ScriptModuleResolver::dependencies(std::string_view importerUri) const {
444 const auto found = impl_->dependencies.find(std::string(importerUri));
445 return found == impl_->dependencies.end() ? std::vector<std::string>{} : found->second;
446}
447
448std::vector<std::string> ScriptModuleResolver::reverseDependencies(std::string_view canonicalUri) const {
449 std::vector<std::string> result;
450 for (const auto& [importer, dependencies] : impl_->dependencies) {
451 if (std::find(dependencies.begin(), dependencies.end(), canonicalUri) != dependencies.end())
452 result.push_back(importer);
453 }
454 std::sort(result.begin(), result.end());
455 return result;
456}
457
459 std::string scheme = "game:";
460 std::string path;
461 const size_t schemeEnd = request.specifier.find(":/");
462 if (schemeEnd != std::string::npos) {
463 scheme = request.specifier.substr(0, schemeEnd + 1);
464 path = request.specifier.substr(schemeEnd + 2);
465 } else if (request.specifier.rfind("./", 0) == 0 || request.specifier.rfind("../", 0) == 0) {
466 std::string importer = request.importerUri;
467 const size_t importerScheme = importer.find(":/");
468 if (importerScheme != std::string::npos) {
469 scheme = importer.substr(0, importerScheme + 1);
470 importer = importer.substr(importerScheme + 2);
471 }
472 const size_t slash = importer.find_last_of("/\\");
473 path = (slash == std::string::npos ? std::string() : importer.substr(0, slash + 1)) + request.specifier;
474 } else {
475 path = request.specifier;
476 }
477 bool escaped = false;
478 path = normalizedPath(path, escaped);
479 if (escaped || path.empty()) {
480 error = escaped ? "script import escapes its module root: " + request.specifier : "empty script module path";
481 return false;
482 }
483 output = scheme + "/" + path;
484 return true;
485}
486
487} // namespace eve::script
int root
Definition AnimSmr.cpp:119
std::vector< eve::artifact::PartView > parts
std::string output
int priority
struct SQVM * HSQUIRRELVM
bool changed
HSQUIRRELVM vm
Definition ECS.cpp:38
EvpackChunkInput input
Definition Evpack.cpp:170
std::string message
const GltfImportRequest & request
wgpu::PopErrorScopeStatus status
std::int32_t c
std::vector< Edge > edges
std::string id
Poco::JSON::Object::Ptr result
std::vector< RecipeParam > params
std::uint64_t bytes
MeleePoint3 b
Definition MeleeHit.cpp:41
MeleePoint3 a
Definition MeleeHit.cpp:40
std::vector< std::int32_t > order
std::shared_ptr< const OceanSprayFrame > previous
std::string error
Definition Package.cpp:174
std::string path
Definition PlayHost.cpp:111
std::string uri
Object::Ptr value
std::string hash
int detail
bool found
ScriptStructure out
std::string_view source
size_t begin
size_t end
The single Squirrel projection for common Result, Status and Value.
Instance-owned publication mechanism shared by capability and domain registries. @ownership The regis...
void instantiateDependencies(std::string_view importerUri)
Instantiates the importer's dependencies in topological order.
ProviderId registerProvider(std::shared_ptr< IScriptModuleProvider > provider, int priority=0)
Registers a provider. Higher priorities are tried first.
std::vector< std::string > dependencies(std::string_view importerUri) const
Returns canonical direct dependencies for an importer.
void beginCompilation(std::string_view importerUri)
Clears prior diagnostics and dependency edges before compiling an importer.
std::optional< std::string > takeCompilationFailure()
Consumes the native failure captured while resolving the current compilation.
std::vector< std::string > reverseDependencies(std::string_view canonicalUri) const
Returns canonical importers that directly depend on a module.
std::vector< std::string > reloadAffected(std::string_view canonicalUri)
Transactionally reloads a module and every cached module that imports it.
void invalidate(std::string_view canonicalUri)
Invalidates a module and all reverse dependencies.
void reload(std::string_view canonicalUri)
Transactionally reloads one module, retaining the prior generation on failure.
~ScriptModuleResolver()
Script module resolver.
void registerDefaultProviders()
Installs the default game:/ provider backed by IFileSystem and disk fallback.
ScriptModuleResolver(SQVM *vm)
Script module resolver.
static bool canonicalize(const ScriptModuleRequest &request, std::string &output, std::string &error)
Normalizes a logical module URI and rejects root traversal.
bool unregisterProvider(ProviderId id)
Removes a provider; existing compiled module records remain valid.
void prepareDependencies(std::string_view importerUri)
Compiles all imports discovered while compiling an importer.
SQInteger top
Definition Snapshot.cpp:115
ScriptModuleStatus
Result of asking a provider to resolve or load a script module.
std::string reportScriptCallFailure(HSQUIRRELVM vm, const char *what)
Report a failed engine-to-script call, consuming the VM's script error.
Logical module request emitted by an EveScript import declaration.
void instantiate(const std::string &canonical)
static SQRESULT dependencyCallback(HSQUIRRELVM, const SQChar *importer, const SQChar *specifier, SQUserPointer user)
std::string ensureCompiled(std::string_view importer, std::string_view specifier)
std::unordered_map< std::string, Module > modules
std::optional< std::string > pendingCompilationFailure
std::vector< eve::cap::ProviderRegistry< IScriptModuleProvider, ProviderEntry >::Record > providerSnapshot() const
std::unordered_map< std::string, std::vector< std::string > > dependencies
eve::cap::ProviderRegistry< IScriptModuleProvider, ProviderEntry > providers
static SQRESULT importCallback(HSQUIRRELVM vm, const SQChar *importer, const SQChar *specifier, SQUserPointer user, HSQOBJECT *exports)
ScriptModuleSource load(const std::string &canonical)
std::vector< std::string > reloadAffected(const std::string &canonical)
void instantiateModule(const std::string &canonical, Module &module)
std::string resolve(const ScriptModuleRequest &request)
void recordCompilationFailure(std::string message)
UTF-8 source and stable identity returned by a module provider.