scripting: library scope for imported scripts (#13054) d24376c1d6 * scripting: scope-aware module resolution so versioned library scripts coexist * scripting: 64-bit library scope on FileAsset (new uint64 core type) read by ScriptAsset::scope * scripting: unresolved library: require errors instead of rebinding to caller scope * scripting: use lib: qualifier prefix instead of library: * scripting: scoped setScriptSource overload, scope resolution maps, and scope tests * scripting: plumb library scope from editor assets to the workspace via a cancellation-proof setScriptScope work * scripting: recycle setScriptScope work directly, it has no consumer to ring * scripting: infer resolves requires with the caller's scope, divergence from parse-time edges races module rechecks * scripting: library scope flows into the editor VM and host proxies so lib: requires resolve * scripting: scope-aware require autocomplete and derive proxy scope from the library link for older imports * scripting: LibraryFolder core type roots a library's scope, scripts derive it by parentage and the panel synthesizes the internal tree * editor: show the library version suffix on the library folder instead of every script row * editor: deleting any part of an imported library removes the whole library, confirmed and journaled * scripting: colon-free scoped chunknames, tooling parses trace locations as chunkname:line * editor: library folder is the per-library container in custom and source views, holds artboards, uses the library icon * editor: unify the library tree item onto LibraryAsset itself, scope and panel and inspector all hang off the one core object * editor: source view data pass includes libraries, it previously kept only group items * editor: regenerate the preview runtime file when blob bytes arrive after it was generated * core: reseed nextObjectId when chunked sync completes, the connected reseed walks an empty object set * core: corrupt-scrubbed objects keep their ids consumed and log, regenerated content collided with their server copies * core: abandon rejected changesets, a persisted reject replays on every connect and loops forever * code: derived char ids fall back to a fresh reserved range when occupied, files written without per-rune reservation collide on split * editor: definition jump opens the file's library proxy tab, the internalCore instance has no workspace wiring so it rendered unhighlighted * core,editor: strip temporary id allocation diagnostics * docs: cut comments down to why-only one liners * core: drop the sync complete reseed, ready always follows sync so the connected reseed sees every consumed id * runtime: clear the registered module's key from each dependent's missing set, the wrong receiver left dependents pending * tests: drop the draco checkout dependency, a synthetic scoped storm covers the race and scope tests use a generic library * defs: scope keys declare uint64 in both def sets, the editor generator folds uint64 to a Dart int like uint8 * runtime: scope the require cache key so it destructs before luaL_error longjmps, five strings leaked per failed require * code: char id fallback checks only the derived id, range checking tripped on legitimate overlap splits and detached runs * editor tests: stub library 999 details, library assets now surface in the panel so the update tracker checks them * core: abandon on reject moves to its own PR * scripting: lib: requires resolve through per caller import edges, a serialized LibraryAsset is the edge so files carry their own pins * scripting: source storms defer the check flush and the checker pool widens to eight * editor: busy state stacks across compiles and checks so the spinner holds until reports land * fix(libraries): nested edges derive their caller scope from the owning core * editor: warn when a script name shadows a reserved module pattern * editor: scripts covered by the library confirmation skip their own delete prompt * editor: badge reserved script names in the asset tree like invalid view model names * editor: reserved script name badge tips immediately like the data tree * editor: reserved name badge moves to the icon overlay, the icon slot ignores pointers so its tip never hovered * core_generator: derived properties serialize through their overridden getters * fix(editor): script-less files skip the problem report round trip, the busy spinner froze settle-based tests * fix(editor): empty problem clear skips the notify, and the badge halo joins the color baseline * test(editor): first connect report assertion polls, the fixed delay flaked under CI load * test(editor): drop shadowed mock_rive_api import, the analyze gate failed shard 0 on every run Co-authored-by: Luigi Rosso <luigi-rosso@users.noreply.github.com>
diff --git a/.rive_head b/.rive_head index bdd52fd..2b4e3f6 100644 --- a/.rive_head +++ b/.rive_head
@@ -1 +1 @@ -5868c1ba5fcb10129151e094e5d6fc2eec9b478f +d24376c1d692b4687141dbcff2bc4b84f3de8c66
diff --git a/dev/core_generator/lib/src/field_type.dart b/dev/core_generator/lib/src/field_type.dart index d8d4ae4..114e3c3 100644 --- a/dev/core_generator/lib/src/field_type.dart +++ b/dev/core_generator/lib/src/field_type.dart
@@ -3,6 +3,7 @@ export 'package:core_generator/src/field_types/double_field_type.dart'; export 'package:core_generator/src/field_types/string_field_type.dart'; export 'package:core_generator/src/field_types/uint_field_type.dart'; +export 'package:core_generator/src/field_types/uint64_field_type.dart'; Map<String, FieldType> _types = <String, FieldType>{};
diff --git a/dev/core_generator/lib/src/field_types/initialize.dart b/dev/core_generator/lib/src/field_types/initialize.dart index 976fc5f..b3e247d 100644 --- a/dev/core_generator/lib/src/field_types/initialize.dart +++ b/dev/core_generator/lib/src/field_types/initialize.dart
@@ -12,6 +12,7 @@ StringFieldType(), BytesFieldType(), UintFieldType(), + Uint64FieldType(), // Must come after UintFieldType: its registryType resolves `uint`. Uint8FieldType(), DoubleFieldType(),
diff --git a/dev/core_generator/lib/src/field_types/uint64_field_type.dart b/dev/core_generator/lib/src/field_types/uint64_field_type.dart new file mode 100644 index 0000000..3d2fdb0 --- /dev/null +++ b/dev/core_generator/lib/src/field_types/uint64_field_type.dart
@@ -0,0 +1,18 @@ +import '../field_type.dart'; + +class Uint64FieldType extends FieldType { + Uint64FieldType() + : super( + 'uint64', + 'CoreUint64Type', + cppName: 'uint64_t', + ); + + @override + String get defaultValue => '0'; + + // We do this to fix up CoreContext.invalidProperyKey + @override + String? convertCpp(String value) => + value.replaceAll('CoreContext.', 'Core::'); +}
diff --git a/dev/defs/assets/file_asset.json b/dev/defs/assets/file_asset.json index 74a3f18..f82d9d8 100644 --- a/dev/defs/assets/file_asset.json +++ b/dev/defs/assets/file_asset.json
@@ -65,6 +65,28 @@ }, "description": "Whether to export the asset regardless of it being used.", "runtime": false + }, + "scopeLibraryId": { + "type": "uint64", + "initialValue": "0", + "key": { + "int": 1037, + "string": "scopelibraryid" + }, + "description": "Backend library id of the library version this asset belongs to (its scope). Zero is the reserved root scope: the host file itself. Named distinctly from LibraryAsset.libraryId, which is a library's own identity.", + "journal": false, + "derived": true + }, + "scopeLibraryVersionId": { + "type": "uint64", + "initialValue": "0", + "key": { + "int": 1038, + "string": "scopelibraryversionid" + }, + "description": "Backend library version id of the library version this asset belongs to (its scope). Zero is the reserved root scope.", + "journal": false, + "derived": true } } } \ No newline at end of file
diff --git a/dev/defs/assets/library_asset.json b/dev/defs/assets/library_asset.json new file mode 100644 index 0000000..ea7a0c2 --- /dev/null +++ b/dev/defs/assets/library_asset.json
@@ -0,0 +1,28 @@ +{ + "name": "LibraryAsset", + "key": { + "int": 558, + "string": "libraryasset" + }, + "extends": "assets/file_asset.json", + "properties": { + "libraryId": { + "type": "uint64", + "initialValue": "0", + "key": { + "int": 798, + "string": "libraryid" + }, + "description": "Backend library id this asset points at: the import target. With Asset.name as the label and the derived scope as the caller, a LibraryAsset is one import edge." + }, + "libraryVersionId": { + "type": "uint64", + "initialValue": "0", + "key": { + "int": 799, + "string": "libraryversionid" + }, + "description": "Backend library version id this asset points at: the import target version." + } + } +} \ No newline at end of file
diff --git a/include/rive/assets/library_asset.hpp b/include/rive/assets/library_asset.hpp new file mode 100644 index 0000000..726fda0 --- /dev/null +++ b/include/rive/assets/library_asset.hpp
@@ -0,0 +1,20 @@ +#ifndef _RIVE_LIBRARY_ASSET_HPP_ +#define _RIVE_LIBRARY_ASSET_HPP_ +#include "rive/generated/assets/library_asset_base.hpp" +namespace rive +{ +// One import edge: the derived scope is the caller, name the label, and +// libraryId/libraryVersionId the target library version. +class LibraryAsset : public LibraryAssetBase +{ +public: + bool decode(SimpleArray<uint8_t>&, Factory*) override { return true; } + std::string fileExtension() const override { return "library"; } + +protected: + // Pure data, nothing for asset resolution to load. + bool addsToBackboard() override { return false; } +}; +} // namespace rive + +#endif
diff --git a/include/rive/assets/script_asset.hpp b/include/rive/assets/script_asset.hpp index cb0a963..b5ce4d8 100644 --- a/include/rive/assets/script_asset.hpp +++ b/include/rive/assets/script_asset.hpp
@@ -4,6 +4,8 @@ #include "rive/generated/assets/script_asset_base.hpp" #include "rive/simple_array.hpp" #include <stdio.h> +#include <cstdint> +#include <functional> #ifdef WITH_RIVE_SCRIPTING #include <unordered_set> #endif @@ -180,11 +182,26 @@ } }; +// Library version a module belongs to, (0,0) is the host file. +struct ScopeKey +{ + uint64_t libraryId = 0; + uint64_t libraryVersionId = 0; + bool isRoot() const { return libraryId == 0 && libraryVersionId == 0; } + bool operator==(const ScopeKey& o) const + { + return libraryId == o.libraryId && + libraryVersionId == o.libraryVersionId; + } + bool operator!=(const ScopeKey& o) const { return !(*this == o); } +}; + class ModuleDetails { public: virtual ~ModuleDetails() = default; virtual std::string moduleName() = 0; + virtual ScopeKey scope() { return ScopeKey{}; } virtual void registrationComplete(int ref) {} virtual Span<uint8_t> moduleBytecode() { return Span<uint8_t>(); } virtual bool isProtocolScript() = 0; @@ -243,6 +260,10 @@ { return folderPath() == "" ? name() : folderPath() + "/" + name(); } + ScopeKey scope() override + { + return ScopeKey{scopeLibraryId(), scopeLibraryVersionId()}; + } bool isProtocolScript() override { return !isModule(); } private: @@ -257,4 +278,16 @@ }; } // namespace rive +namespace std +{ +template <> struct hash<rive::ScopeKey> +{ + size_t operator()(const rive::ScopeKey& k) const + { + return hash<uint64_t>()(k.libraryId) ^ + (hash<uint64_t>()(k.libraryVersionId) << 1); + } +}; +} // namespace std + #endif \ No newline at end of file
diff --git a/include/rive/core/field_types/core_uint64_type.hpp b/include/rive/core/field_types/core_uint64_type.hpp new file mode 100644 index 0000000..4ab5726 --- /dev/null +++ b/include/rive/core/field_types/core_uint64_type.hpp
@@ -0,0 +1,20 @@ +#ifndef _RIVE_CORE_UINT64_TYPE_HPP_ +#define _RIVE_CORE_UINT64_TYPE_HPP_ + +#include <cstdint> + +namespace rive +{ +class BinaryReader; +class CoreUint64Type +{ +public: + // Shares the uint id, both are LEB128 varints on the wire. + static const int id = 0; + static uint64_t deserialize(BinaryReader& reader); +#ifdef WITH_RIVE_TOOLS + static uint64_t deserializeRev(BinaryReader& reader); +#endif +}; +} // namespace rive +#endif
diff --git a/include/rive/generated/assets/file_asset_base.hpp b/include/rive/generated/assets/file_asset_base.hpp index 15e3cd6..2bfa4d1 100644 --- a/include/rive/generated/assets/file_asset_base.hpp +++ b/include/rive/generated/assets/file_asset_base.hpp
@@ -4,6 +4,7 @@ #include "rive/assets/asset.hpp" #include "rive/core/field_types/core_bytes_type.hpp" #include "rive/core/field_types/core_string_type.hpp" +#include "rive/core/field_types/core_uint64_type.hpp" #include "rive/core/field_types/core_uint_type.hpp" #include "rive/span.hpp" namespace rive @@ -35,10 +36,14 @@ static const uint16_t assetIdPropertyKey = 204; static const uint16_t cdnUuidPropertyKey = 359; static const uint16_t cdnBaseUrlPropertyKey = 362; + static const uint16_t scopeLibraryIdPropertyKey = 1037; + static const uint16_t scopeLibraryVersionIdPropertyKey = 1038; protected: uint32_t m_AssetId = 0; std::string m_CdnBaseUrl = "https://public.rive.app/cdn/uuid"; + uint64_t m_ScopeLibraryId = 0; + uint64_t m_ScopeLibraryVersionId = 0; public: inline uint32_t assetId() const { return m_AssetId; } @@ -68,11 +73,40 @@ notifyPropertyChanged(cdnBaseUrlPropertyKey); } + inline uint64_t scopeLibraryId() const { return m_ScopeLibraryId; } + void scopeLibraryId(uint64_t value) + { + if (m_ScopeLibraryId == value) + { + return; + } + m_ScopeLibraryId = value; + scopeLibraryIdChanged(); + notifyPropertyChanged(scopeLibraryIdPropertyKey); + } + + inline uint64_t scopeLibraryVersionId() const + { + return m_ScopeLibraryVersionId; + } + void scopeLibraryVersionId(uint64_t value) + { + if (m_ScopeLibraryVersionId == value) + { + return; + } + m_ScopeLibraryVersionId = value; + scopeLibraryVersionIdChanged(); + notifyPropertyChanged(scopeLibraryVersionIdPropertyKey); + } + void copy(const FileAssetBase& object) { m_AssetId = object.m_AssetId; copyCdnUuid(object); m_CdnBaseUrl = object.m_CdnBaseUrl; + m_ScopeLibraryId = object.m_ScopeLibraryId; + m_ScopeLibraryVersionId = object.m_ScopeLibraryVersionId; Asset::copy(object); } @@ -89,6 +123,12 @@ case cdnBaseUrlPropertyKey: m_CdnBaseUrl = CoreStringType::deserialize(reader); return true; + case scopeLibraryIdPropertyKey: + m_ScopeLibraryId = CoreUint64Type::deserialize(reader); + return true; + case scopeLibraryVersionIdPropertyKey: + m_ScopeLibraryVersionId = CoreUint64Type::deserialize(reader); + return true; } return Asset::deserialize(propertyKey, reader); } @@ -97,6 +137,8 @@ virtual void assetIdChanged() {} virtual void cdnUuidChanged() {} virtual void cdnBaseUrlChanged() {} + virtual void scopeLibraryIdChanged() {} + virtual void scopeLibraryVersionIdChanged() {} }; } // namespace rive
diff --git a/include/rive/generated/assets/library_asset_base.hpp b/include/rive/generated/assets/library_asset_base.hpp new file mode 100644 index 0000000..eab4f2b --- /dev/null +++ b/include/rive/generated/assets/library_asset_base.hpp
@@ -0,0 +1,92 @@ +#ifndef _RIVE_LIBRARY_ASSET_BASE_HPP_ +#define _RIVE_LIBRARY_ASSET_BASE_HPP_ +#include "rive/assets/file_asset.hpp" +#include "rive/core/field_types/core_uint64_type.hpp" +namespace rive +{ +class LibraryAssetBase : public FileAsset +{ +protected: + typedef FileAsset Super; + +public: + static const uint16_t typeKey = 558; + + /// Helper to quickly determine if a core object extends another without + /// RTTI at runtime. + bool isTypeOf(uint16_t typeKey) const override + { + switch (typeKey) + { + case LibraryAssetBase::typeKey: + case FileAssetBase::typeKey: + case AssetBase::typeKey: + return true; + default: + return false; + } + } + + uint16_t coreType() const override { return typeKey; } + + static const uint16_t libraryIdPropertyKey = 798; + static const uint16_t libraryVersionIdPropertyKey = 799; + +protected: + uint64_t m_LibraryId = 0; + uint64_t m_LibraryVersionId = 0; + +public: + inline uint64_t libraryId() const { return m_LibraryId; } + void libraryId(uint64_t value) + { + if (m_LibraryId == value) + { + return; + } + m_LibraryId = value; + libraryIdChanged(); + notifyPropertyChanged(libraryIdPropertyKey); + } + + inline uint64_t libraryVersionId() const { return m_LibraryVersionId; } + void libraryVersionId(uint64_t value) + { + if (m_LibraryVersionId == value) + { + return; + } + m_LibraryVersionId = value; + libraryVersionIdChanged(); + notifyPropertyChanged(libraryVersionIdPropertyKey); + } + + Core* clone() const override; + void copy(const LibraryAssetBase& object) + { + m_LibraryId = object.m_LibraryId; + m_LibraryVersionId = object.m_LibraryVersionId; + FileAsset::copy(object); + } + + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override + { + switch (propertyKey) + { + case libraryIdPropertyKey: + m_LibraryId = CoreUint64Type::deserialize(reader); + return true; + case libraryVersionIdPropertyKey: + m_LibraryVersionId = CoreUint64Type::deserialize(reader); + return true; + } + return FileAsset::deserialize(propertyKey, reader); + } + +protected: + virtual void libraryIdChanged() {} + virtual void libraryVersionIdChanged() {} +}; +} // namespace rive + +#endif \ No newline at end of file
diff --git a/include/rive/generated/core_registry.hpp b/include/rive/generated/core_registry.hpp index bd577f7..74534c3 100644 --- a/include/rive/generated/core_registry.hpp +++ b/include/rive/generated/core_registry.hpp
@@ -115,6 +115,7 @@ #include "rive/assets/folder.hpp" #include "rive/assets/font_asset.hpp" #include "rive/assets/image_asset.hpp" +#include "rive/assets/library_asset.hpp" #include "rive/assets/manifest_asset.hpp" #include "rive/assets/script_asset.hpp" #include "rive/assets/shader_asset.hpp" @@ -894,6 +895,8 @@ return new ShaderAsset(); case FontAssetBase::typeKey: return new FontAsset(); + case LibraryAssetBase::typeKey: + return new LibraryAsset(); case AudioAssetBase::typeKey: return new AudioAsset(); case FileAssetContentsBase::typeKey: @@ -3138,6 +3141,24 @@ break; } } + static void setUint64(Core* object, int propertyKey, uint64_t value) + { + switch (propertyKey) + { + case FileAssetBase::scopeLibraryIdPropertyKey: + object->as<FileAssetBase>()->scopeLibraryId(value); + break; + case FileAssetBase::scopeLibraryVersionIdPropertyKey: + object->as<FileAssetBase>()->scopeLibraryVersionId(value); + break; + case LibraryAssetBase::libraryIdPropertyKey: + object->as<LibraryAssetBase>()->libraryId(value); + break; + case LibraryAssetBase::libraryVersionIdPropertyKey: + object->as<LibraryAssetBase>()->libraryVersionId(value); + break; + } + } static uint32_t getUint(Core* object, int propertyKey) { switch (propertyKey) @@ -4394,6 +4415,21 @@ } return 0.0f; } + static uint64_t getUint64(Core* object, int propertyKey) + { + switch (propertyKey) + { + case FileAssetBase::scopeLibraryIdPropertyKey: + return object->as<FileAssetBase>()->scopeLibraryId(); + case FileAssetBase::scopeLibraryVersionIdPropertyKey: + return object->as<FileAssetBase>()->scopeLibraryVersionId(); + case LibraryAssetBase::libraryIdPropertyKey: + return object->as<LibraryAssetBase>()->libraryId(); + case LibraryAssetBase::libraryVersionIdPropertyKey: + return object->as<LibraryAssetBase>()->libraryVersionId(); + } + return 0; + } static int propertyFieldId(int propertyKey) { switch (propertyKey) @@ -4975,6 +5011,11 @@ case FileAssetContentsBase::bytesPropertyKey: case FileAssetContentsBase::signaturePropertyKey: return CoreBytesType::id; + case FileAssetBase::scopeLibraryIdPropertyKey: + case FileAssetBase::scopeLibraryVersionIdPropertyKey: + case LibraryAssetBase::libraryIdPropertyKey: + case LibraryAssetBase::libraryVersionIdPropertyKey: + return CoreUint64Type::id; default: return -1; } @@ -6165,6 +6206,14 @@ return object->is<NestedTriggerBase>(); case EventBase::triggerPropertyKey: return object->is<EventBase>(); + case FileAssetBase::scopeLibraryIdPropertyKey: + return object->is<FileAssetBase>(); + case FileAssetBase::scopeLibraryVersionIdPropertyKey: + return object->is<FileAssetBase>(); + case LibraryAssetBase::libraryIdPropertyKey: + return object->is<LibraryAssetBase>(); + case LibraryAssetBase::libraryVersionIdPropertyKey: + return object->is<LibraryAssetBase>(); } return false; }
diff --git a/include/rive/lua/rive_lua_libs.hpp b/include/rive/lua/rive_lua_libs.hpp index 90943f6..4773230 100644 --- a/include/rive/lua/rive_lua_libs.hpp +++ b/include/rive/lua/rive_lua_libs.hpp
@@ -1512,6 +1512,21 @@ // detached-root ancestor's recursion), so they are skipped. void advanceDetachedViewModels(); + // Require cache key for a module in a scope, bare name for root. + static std::string scopedKey(const std::string& name, ScopeKey scope); + // Pin libraryName required from caller to the target library version. + void addImport(ScopeKey caller, + const std::string& libraryName, + ScopeKey target); + // Require cache key for a require string relative to the caller. + std::string resolveRequire(const std::string& requirerChunkname, + const std::string& request); + // Chunkname baked into bytecode for traces, bare name for root. + static std::string readableChunkname(const std::string& name, + ScopeKey scope); + // Seeds scope for modules with no ModuleDetails, like the editor VM. + void setChunknameScope(const std::string& chunkname, ScopeKey scope); + // Ore GPU context for this VM, derived from the render factory. Null when // there is no render context, or it is not GPU-backed. Returned as void* so // callers that include ore headers cast to ore::Context*. @@ -1578,6 +1593,14 @@ // Called when a module successfully registers void onModuleRegistered(ModuleDetails* moduleDetails); + // Scope for a require string relative to the caller, outPath gets the + // module path portion. + ScopeKey resolveImport(ScopeKey caller, + const std::string& request, + std::string& outPath); + // Scope for a chunkname, root if unknown. + ScopeKey scopeOf(const std::string& chunkname); + private: Factory* m_renderContext = nullptr; uint64_t m_ownerId = 0; @@ -1594,6 +1617,12 @@ std::vector<ModuleDetails*> m_modulesToRegister; std::unordered_map<std::string, ModuleDetails*> m_moduleLookup; std::unordered_set<ModuleDetails*> m_pendingModules; + // Chunkname to details, so require can find the caller's scope. + std::unordered_map<std::string, ModuleDetails*> m_moduleByChunkname; + std::unordered_map<ScopeKey, std::unordered_map<std::string, ScopeKey>> + m_pins; + // Seeded via setChunknameScope for modules with no ModuleDetails. + std::unordered_map<std::string, ScopeKey> m_chunknameScopes; // Detached view model instances tracked for end-of-frame advance, keyed by // instance pointer. Each entry keeps a strong reference alive and counts
diff --git a/include/rive/lua/scripting_vm.hpp b/include/rive/lua/scripting_vm.hpp index 1a4310b..495d352 100644 --- a/include/rive/lua/scripting_vm.hpp +++ b/include/rive/lua/scripting_vm.hpp
@@ -53,34 +53,35 @@ // retries void performRegistration(); + // name is the require cache key, chunkname the trace label baked into + // the bytecode, defaulting to name. static bool registerModule(lua_State* state, const char* name, - Span<uint8_t> bytecode); + Span<uint8_t> bytecode, + const char* chunkname = nullptr); static void unregisterModule(lua_State* state, const char* name); bool registerModule(const char* name, Span<uint8_t> bytecode); void unregisterModule(const char* name); static bool registerScript(lua_State* state, const char* name, - Span<uint8_t> bytecode); + Span<uint8_t> bytecode, + const char* chunkname = nullptr); bool registerScript(const char* name, Span<uint8_t> bytecode); - // Loads bytecode into the VM, creating a sandboxed thread and - // deserializing the bytecode into an unexecuted closure. Pushes the - // module thread onto the stack. Returns true on success. + // Loads bytecode into an unexecuted sandboxed thread pushed onto the + // stack. name is the chunkname baked into the proto. static bool loadModule(lua_State* state, const char* name, Span<uint8_t> bytecode); - // Executes a previously loaded module thread (on top of stack from - // loadModule). Runs lua_resume, validates the result, and for utility - // modules registers into the require cache. On success, the module - // result (table/function) replaces the thread on the stack. - // Returns true on success. + // Executes a thread from loadModule and registers utility modules under + // name. The result replaces the thread on the stack. static bool executeModule(lua_State* state, const char* name, - bool isUtility); + bool isUtility, + const char* chunkname = nullptr); static void dumpStack(lua_State* state);
diff --git a/src/core/field_types/core_uint64_type.cpp b/src/core/field_types/core_uint64_type.cpp new file mode 100644 index 0000000..32f60d6 --- /dev/null +++ b/src/core/field_types/core_uint64_type.cpp
@@ -0,0 +1,16 @@ +#include "rive/core/field_types/core_uint64_type.hpp" +#include "rive/core/binary_reader.hpp" + +using namespace rive; + +uint64_t CoreUint64Type::deserialize(BinaryReader& reader) +{ + return reader.readVarUint64(); +} + +#ifdef WITH_RIVE_TOOLS +uint64_t CoreUint64Type::deserializeRev(BinaryReader& reader) +{ + return deserialize(reader); +} +#endif
diff --git a/src/file.cpp b/src/file.cpp index df82440..cc203af 100644 --- a/src/file.cpp +++ b/src/file.cpp
@@ -70,6 +70,7 @@ #include "rive/assets/file_asset.hpp" #include "rive/assets/audio_asset.hpp" #include "rive/assets/blob_asset.hpp" +#include "rive/assets/library_asset.hpp" #include "rive/assets/script_asset.hpp" #include "rive/assets/shader_asset.hpp" #include "rive/assets/file_asset_contents.hpp" @@ -340,6 +341,7 @@ case BlobAsset::typeKey: case ScriptAsset::typeKey: case ShaderAsset::typeKey: + case LibraryAsset::typeKey: { auto fa = object->as<FileAsset>(); m_fileAssets.push_back(rcp<FileAsset>(fa)); @@ -676,12 +678,17 @@ { // Check if we have any script assets in the file std::vector<ScriptAsset*> scripts; + std::vector<LibraryAsset*> libraries; for (auto asset : m_fileAssets) { if (asset->is<ScriptAsset>()) { scripts.push_back(asset->as<ScriptAsset>()); } + else if (asset->is<LibraryAsset>()) + { + libraries.push_back(asset->as<LibraryAsset>()); + } } // Only make the ScriptingVM if we have any script assets if (!scripts.empty()) @@ -703,6 +710,16 @@ { initializeLuaData(vm->state(), m_ViewModels); } + // Import edges are data, registered before any module executes. + for (auto library : libraries) + { + vm->context()->addImport( + ScopeKey{library->scopeLibraryId(), + library->scopeLibraryVersionId()}, + library->name(), + ScopeKey{library->libraryId(), + library->libraryVersionId()}); + } for (auto scriptAsset : scripts) { // At runtime, if the script is verified, add it to be
diff --git a/src/generated/assets/library_asset_base.cpp b/src/generated/assets/library_asset_base.cpp new file mode 100644 index 0000000..1b333a5 --- /dev/null +++ b/src/generated/assets/library_asset_base.cpp
@@ -0,0 +1,11 @@ +#include "rive/generated/assets/library_asset_base.hpp" +#include "rive/assets/library_asset.hpp" + +using namespace rive; + +Core* LibraryAssetBase::clone() const +{ + auto cloned = new LibraryAsset(); + cloned->copy(*this); + return cloned; +}
diff --git a/src/lua/rive_lua_libs.cpp b/src/lua/rive_lua_libs.cpp index 457bc07..3bbf8f8 100644 --- a/src/lua/rive_lua_libs.cpp +++ b/src/lua/rive_lua_libs.cpp
@@ -449,20 +449,27 @@ lua_settop(L, 1); const char* path = luaL_checkstring(L, 1); - if (checkRegisteredModules(L, path) == 1) + ScriptingContext* context = + static_cast<ScriptingContext*>(lua_getthreaddata(L)); + + // Scoped so the string is destroyed before luaL_error longjmps. { - return 1; + std::string cacheKey = path; + if (context != nullptr && requirerChunkname != nullptr) + { + cacheKey = context->resolveRequire(requirerChunkname, path); + } + + if (checkRegisteredModules(L, cacheKey.c_str()) == 1) + { + return 1; + } } // Record missing dependency if we're registering a module - if (requirerChunkname) + if (requirerChunkname != nullptr && context != nullptr) { - ScriptingContext* context = - static_cast<ScriptingContext*>(lua_getthreaddata(L)); - if (context) - { - context->recordMissingDependency(requirerChunkname, path); - } + context->recordMissingDependency(requirerChunkname, path); } luaL_error(L, "require could not find a script named %s", path); @@ -640,8 +647,13 @@ // loadModule). On success, replaces the thread with the module result. // If isUtility, also registers the result in the require cache. // Returns true on success. -bool ScriptingVM::executeModule(lua_State* L, const char* name, bool isUtility) +bool ScriptingVM::executeModule(lua_State* L, + const char* name, + bool isUtility, + const char* chunkname) { + const char* display = chunkname != nullptr ? chunkname : name; + // The module thread should be on top of the stack. lua_State* ML = lua_tothread(L, -1); if (ML == nullptr) @@ -654,22 +666,24 @@ { if (lua_gettop(ML) == 0) { - lua_pushfstring(ML, "%s:1: module must return a value", name); + lua_pushfstring(ML, "%s:1: module must return a value", display); } else if (!lua_istable(ML, -1) && !lua_isfunction(ML, -1)) { lua_pushfstring(ML, "%s:1: module must return a table or function", - name); + display); } } else if (status == LUA_YIELD) { - lua_pushfstring(ML, "%s:1: module can not yield", name); + lua_pushfstring(ML, "%s:1: module can not yield", display); } else if (!lua_isstring(ML, -1)) { - lua_pushfstring(ML, "%s:1: unknown error while running module", name); + lua_pushfstring(ML, + "%s:1: unknown error while running module", + display); } // add ML result to L stack @@ -741,10 +755,101 @@ void ScriptingVM::dumpStack(lua_State* state) { dump_stack(state); } +std::string ScriptingContext::scopedKey(const std::string& name, ScopeKey scope) +{ + if (scope.isRoot()) + { + return name; + } + // 0x1F cannot occur in a module path, so no escaping needed. + return name + '\x1f' + std::to_string(scope.libraryId) + ':' + + std::to_string(scope.libraryVersionId); +} + +std::string ScriptingContext::readableChunkname(const std::string& name, + ScopeKey scope) +{ + if (scope.isRoot()) + { + return name; + } + // Colon free, tooling parses trace locations as chunkname:line. + return std::to_string(scope.libraryId) + '-' + + std::to_string(scope.libraryVersionId) + '/' + name; +} + +ScopeKey ScriptingContext::scopeOf(const std::string& chunkname) +{ + auto it = m_moduleByChunkname.find(chunkname); + if (it != m_moduleByChunkname.end()) + { + return it->second->scope(); + } + auto seeded = m_chunknameScopes.find(chunkname); + return seeded != m_chunknameScopes.end() ? seeded->second : ScopeKey{}; +} + +void ScriptingContext::setChunknameScope(const std::string& chunkname, + ScopeKey scope) +{ + m_chunknameScopes[chunkname] = scope; +} + +ScopeKey ScriptingContext::resolveImport(ScopeKey caller, + const std::string& request, + std::string& outPath) +{ + static const std::string kLibraryPrefix = "lib:"; + if (request.compare(0, kLibraryPrefix.size(), kLibraryPrefix) == 0) + { + std::string rest = request.substr(kLibraryPrefix.size()); + size_t slash = rest.find('/'); + std::string libraryName = + slash == std::string::npos ? rest : rest.substr(0, slash); + outPath = + slash == std::string::npos ? std::string() : rest.substr(slash + 1); + auto callerIt = m_pins.find(caller); + if (callerIt != m_pins.end()) + { + auto pinIt = callerIt->second.find(libraryName); + if (pinIt != callerIt->second.end()) + { + return pinIt->second; + } + } + // Sentinel scope so an unpinned library errors instead of rebinding + // to a same named module in the caller's scope. + return ScopeKey{~uint64_t(0), ~uint64_t(0)}; + } + outPath = request; + return caller; +} + +std::string ScriptingContext::resolveRequire( + const std::string& requirerChunkname, + const std::string& request) +{ + ScopeKey caller = scopeOf(requirerChunkname); + std::string path; + ScopeKey target = resolveImport(caller, request, path); + return scopedKey(path, target); +} + +void ScriptingContext::addImport(ScopeKey caller, + const std::string& libraryName, + ScopeKey target) +{ + m_pins[caller][libraryName] = target; +} + void ScriptingContext::addModule(ModuleDetails* moduleDetails) { m_modulesToRegister.push_back(moduleDetails); - m_moduleLookup[moduleDetails->moduleName()] = moduleDetails; + ScopeKey scope = moduleDetails->scope(); + m_moduleLookup[scopedKey(moduleDetails->moduleName(), scope)] = + moduleDetails; + m_moduleByChunkname[readableChunkname(moduleDetails->moduleName(), scope)] = + moduleDetails; } bool ScriptingContext::tryRegisterModule(lua_State* state, @@ -757,14 +862,18 @@ return false; } #endif - const std::string& name = moduleDetails->moduleName(); + ScopeKey scope = moduleDetails->scope(); + std::string cacheKey = scopedKey(moduleDetails->moduleName(), scope); + std::string chunkname = + readableChunkname(moduleDetails->moduleName(), scope); bool registerSuccess = false; int functionRef = 0; if (moduleDetails->isProtocolScript()) { if (ScriptingVM::registerScript(state, - name.c_str(), - moduleDetails->moduleBytecode())) + cacheKey.c_str(), + moduleDetails->moduleBytecode(), + chunkname.c_str())) { // registerScript leaves the function on the stack if (static_cast<lua_Type>(lua_type(state, -1)) == LUA_TFUNCTION) @@ -778,8 +887,9 @@ else { if (ScriptingVM::registerModule(state, - name.c_str(), - moduleDetails->moduleBytecode())) + cacheKey.c_str(), + moduleDetails->moduleBytecode(), + chunkname.c_str())) { registerSuccess = true; } @@ -805,10 +915,11 @@ { continue; } - std::string moduleName = moduleDetails->moduleName(); + std::string cacheKey = + scopedKey(moduleDetails->moduleName(), moduleDetails->scope()); // Skip if already registered - if (checkRegisteredModules(state, moduleName.c_str()) == 1) + if (checkRegisteredModules(state, cacheKey.c_str()) == 1) { lua_pop(state, 1); continue; @@ -894,24 +1005,33 @@ const std::string& requiringModule, const std::string& missingModule) { - if (!requiringModule.empty()) + if (requiringModule.empty()) { - ModuleDetails* moduleDetails = m_moduleLookup[requiringModule]; - if (moduleDetails != nullptr) - { - moduleDetails->addMissingDependency(missingModule); - m_pendingModules.insert(moduleDetails); - } + return; } + auto it = m_moduleByChunkname.find(requiringModule); + if (it == m_moduleByChunkname.end()) + { + return; + } + ModuleDetails* moduleDetails = it->second; + // The topological sort looks up m_moduleLookup by scoped key. + std::string path; + ScopeKey target = + resolveImport(moduleDetails->scope(), missingModule, path); + moduleDetails->addMissingDependency(scopedKey(path, target)); + m_pendingModules.insert(moduleDetails); } void ScriptingContext::onModuleRegistered(ModuleDetails* moduleDetails) { + std::string key = + scopedKey(moduleDetails->moduleName(), moduleDetails->scope()); for (ModuleDetails* module : m_modulesToRegister) { if (!module->missingDependencies().empty()) { - moduleDetails->clearMissingDependency(moduleDetails->moduleName()); + module->clearMissingDependency(key); } } auto it = m_pendingModules.find(moduleDetails); @@ -1060,7 +1180,8 @@ bool ScriptingVM::registerScript(lua_State* state, const char* name, - Span<uint8_t> bytecode) + Span<uint8_t> bytecode, + const char* chunkname) { // Check if already registered - leave module on stack for caller to use if (checkRegisteredModules(state, name) == 1) @@ -1068,12 +1189,12 @@ return true; } - if (!loadModule(state, name, bytecode)) + if (!loadModule(state, chunkname != nullptr ? chunkname : name, bytecode)) { return false; } - if (!executeModule(state, name, false)) + if (!executeModule(state, name, false, chunkname)) { return false; } @@ -1083,7 +1204,8 @@ bool ScriptingVM::registerModule(lua_State* state, const char* name, - Span<uint8_t> bytecode) + Span<uint8_t> bytecode, + const char* chunkname) { // Check if already registered if (checkRegisteredModules(state, name) == 1) @@ -1092,12 +1214,12 @@ return true; } - if (!loadModule(state, name, bytecode)) + if (!loadModule(state, chunkname != nullptr ? chunkname : name, bytecode)) { return false; } - if (!executeModule(state, name, true)) + if (!executeModule(state, name, true, chunkname)) { return false; }
diff --git a/tests/unit_tests/assets/double_library_with_image.riv b/tests/unit_tests/assets/double_library_with_image.riv index cfe9b4c..327613e 100644 --- a/tests/unit_tests/assets/double_library_with_image.riv +++ b/tests/unit_tests/assets/double_library_with_image.riv Binary files differ
diff --git a/tests/unit_tests/assets/library_data_enum_test.riv b/tests/unit_tests/assets/library_data_enum_test.riv index 970dbd6..b7f93af 100644 --- a/tests/unit_tests/assets/library_data_enum_test.riv +++ b/tests/unit_tests/assets/library_data_enum_test.riv Binary files differ
diff --git a/tests/unit_tests/assets/library_export_animation_test.riv b/tests/unit_tests/assets/library_export_animation_test.riv index d66dc75..02ab6de 100644 --- a/tests/unit_tests/assets/library_export_animation_test.riv +++ b/tests/unit_tests/assets/library_export_animation_test.riv Binary files differ
diff --git a/tests/unit_tests/assets/library_export_state_machine_test.riv b/tests/unit_tests/assets/library_export_state_machine_test.riv index ecc50ff..9c11096 100644 --- a/tests/unit_tests/assets/library_export_state_machine_test.riv +++ b/tests/unit_tests/assets/library_export_state_machine_test.riv Binary files differ
diff --git a/tests/unit_tests/assets/library_export_test.riv b/tests/unit_tests/assets/library_export_test.riv index b7afbf9..6810557 100644 --- a/tests/unit_tests/assets/library_export_test.riv +++ b/tests/unit_tests/assets/library_export_test.riv Binary files differ
diff --git a/tests/unit_tests/assets/library_scope_edge_test.riv b/tests/unit_tests/assets/library_scope_edge_test.riv new file mode 100644 index 0000000..5d501f5 --- /dev/null +++ b/tests/unit_tests/assets/library_scope_edge_test.riv Binary files differ
diff --git a/tests/unit_tests/assets/library_view_model_test.riv b/tests/unit_tests/assets/library_view_model_test.riv index 5a3446b..f2db66b 100644 --- a/tests/unit_tests/assets/library_view_model_test.riv +++ b/tests/unit_tests/assets/library_view_model_test.riv Binary files differ
diff --git a/tests/unit_tests/assets/library_vmtest_1_host.riv b/tests/unit_tests/assets/library_vmtest_1_host.riv index ffaf355..639e2ea 100644 --- a/tests/unit_tests/assets/library_vmtest_1_host.riv +++ b/tests/unit_tests/assets/library_vmtest_1_host.riv Binary files differ
diff --git a/tests/unit_tests/assets/library_with_image.riv b/tests/unit_tests/assets/library_with_image.riv index 0000ab5..920d41a 100644 --- a/tests/unit_tests/assets/library_with_image.riv +++ b/tests/unit_tests/assets/library_with_image.riv Binary files differ
diff --git a/tests/unit_tests/assets/nested_library_scope_test.riv b/tests/unit_tests/assets/nested_library_scope_test.riv new file mode 100644 index 0000000..04359a7 --- /dev/null +++ b/tests/unit_tests/assets/nested_library_scope_test.riv Binary files differ
diff --git a/tests/unit_tests/assets/scope_probe.riv b/tests/unit_tests/assets/scope_probe.riv new file mode 100644 index 0000000..5ca9541 --- /dev/null +++ b/tests/unit_tests/assets/scope_probe.riv Binary files differ
diff --git a/tests/unit_tests/runtime/library_asset_test.cpp b/tests/unit_tests/runtime/library_asset_test.cpp index 2cc3566..d46d6e9 100644 --- a/tests/unit_tests/runtime/library_asset_test.cpp +++ b/tests/unit_tests/runtime/library_asset_test.cpp
@@ -9,6 +9,11 @@ #include <rive/shapes/shape.hpp> #include <rive/assets/image_asset.hpp> #include <rive/assets/font_asset.hpp> +#include <rive/assets/library_asset.hpp> +#include <rive/assets/script_asset.hpp> +#ifdef WITH_RIVE_SCRIPTING +#include <rive/lua/rive_lua_libs.hpp> +#endif #include <rive/animation/nested_simple_animation.hpp> #include <rive/animation/nested_state_machine.hpp> #include <rive/relative_local_asset_loader.hpp> @@ -143,6 +148,96 @@ // } // we are literally just loading files here. +TEST_CASE("Library import edge deserializes with script scope", "[libraries]") +{ + // created by library_import_export_test.dart in rive_core. + auto file = ReadRiveFile("assets/library_scope_edge_test.riv"); + + rive::LibraryAsset* library = nullptr; + rive::ScriptAsset* script = nullptr; + for (auto asset : file->assets()) + { + if (asset->is<rive::LibraryAsset>()) + { + library = asset->as<rive::LibraryAsset>(); + } + else if (asset->is<rive::ScriptAsset>()) + { + script = asset->as<rive::ScriptAsset>(); + } + } + + // The edge: label, target identity, root caller scope. + REQUIRE(library != nullptr); + REQUIRE(library->name() == "FruitsLib"); + REQUIRE(library->libraryId() == 9); + REQUIRE(library->libraryVersionId() == 4); + REQUIRE(library->scopeLibraryId() == 0); + REQUIRE(library->scopeLibraryVersionId() == 0); + + // The script carries its scope on the wire. + REQUIRE(script != nullptr); + REQUIRE(script->scope().libraryId == 9); + REQUIRE(script->scope().libraryVersionId == 4); + +#ifdef WITH_RIVE_SCRIPTING + // A file with scripts made a VM, which seeded the edge as a pin. + REQUIRE(file->scriptingVM() != nullptr); +#endif +} + +TEST_CASE("Nested library edge keeps its outer caller scope", "[libraries]") +{ + // created by library_import_export_test.dart in rive_core. + auto file = ReadRiveFile("assets/nested_library_scope_test.riv"); + + rive::LibraryAsset* outer = nullptr; + rive::LibraryAsset* inner = nullptr; + rive::ScriptAsset* mesh = nullptr; + for (auto asset : file->assets()) + { + if (asset->is<rive::LibraryAsset>()) + { + auto library = asset->as<rive::LibraryAsset>(); + (library->libraryId() == 20 ? outer : inner) = library; + } + else if (asset->is<rive::ScriptAsset>() && asset->name() == "mesh") + { + mesh = asset->as<rive::ScriptAsset>(); + } + } + + // The host imported the outer library, the outer imported the inner: + // the inner edge's caller is the outer library, not the host. + REQUIRE(outer != nullptr); + REQUIRE(outer->scopeLibraryId() == 0); + REQUIRE(inner != nullptr); + REQUIRE(inner->libraryId() == 21); + REQUIRE(inner->libraryVersionId() == 4); + REQUIRE(inner->scopeLibraryId() == 20); + REQUIRE(inner->scopeLibraryVersionId() == 6); + + // The inner library's module carries the inner scope. + REQUIRE(mesh != nullptr); + REQUIRE(mesh->scope().libraryId == 21); + REQUIRE(mesh->scope().libraryVersionId == 4); + +#ifdef WITH_RIVE_SCRIPTING + REQUIRE(file->scriptingVM() != nullptr); + auto context = file->scriptingVM()->context(); + // The inner pin landed in the outer library's import table. + context->setChunknameScope("outer_probe", rive::ScopeKey{20, 6}); + CHECK(context->resolveRequire("outer_probe", "lib:InnerLib/mesh") == + rive::ScriptingContext::scopedKey("mesh", rive::ScopeKey{21, 4})); + // The host only pinned the outer library; the inner label must not + // leak into its table. + CHECK(context->resolveRequire("host_probe", "lib:InnerLib/mesh") != + rive::ScriptingContext::scopedKey("mesh", rive::ScopeKey{21, 4})); + CHECK(context->resolveRequire("host_probe", "lib:OuterLib/useb") == + rive::ScriptingContext::scopedKey("useb", rive::ScopeKey{20, 6})); +#endif +} + TEST_CASE("File with library including image", "[libraries]") { // created by library_import_export_test.dart in rive_core.
diff --git a/tests/unit_tests/runtime/scripting/scripting_scope_test.cpp b/tests/unit_tests/runtime/scripting/scripting_scope_test.cpp new file mode 100644 index 0000000..09f65d3 --- /dev/null +++ b/tests/unit_tests/runtime/scripting/scripting_scope_test.cpp
@@ -0,0 +1,300 @@ +#include "catch.hpp" +#include "rive_file_reader.hpp" +#include "scripting_test_utilities.hpp" +#include <climits> +#include <cstdlib> +#include <cstring> +#include <memory> +#include <string> +#include <vector> + +using namespace rive; + +namespace +{ +std::vector<uint8_t> compileLuau(const char* src) +{ + size_t size = 0; + char* bytecode = luau_compile(src, strlen(src), nullptr, &size); + REQUIRE(bytecode != nullptr); + std::vector<uint8_t> out((uint8_t*)bytecode, (uint8_t*)bytecode + size); + free(bytecode); + return out; +} + +// Inline source with an explicit scope so tests can register one name under +// different library versions. +class ScopeTestModule : public ModuleDetails +{ +public: + ScopeTestModule(std::string name, + ScopeKey scope, + const char* src, + bool isModule = true) : + m_name(std::move(name)), + m_scope(scope), + m_bytecode(compileLuau(src)), + m_isModule(isModule) + {} + std::string moduleName() override { return m_name; } + ScopeKey scope() override { return m_scope; } + Span<uint8_t> moduleBytecode() override + { + return Span<uint8_t>(m_bytecode.data(), m_bytecode.size()); + } + bool isProtocolScript() override { return !m_isModule; } + bool verified() const override { return true; } + +private: + std::string m_name; + ScopeKey m_scope; + std::vector<uint8_t> m_bytecode; + bool m_isModule; +}; + +class ScopeTestContext : public ScriptingContext +{ +public: + ScopeTestContext(Factory* factory) : ScriptingContext(factory) {} + void printBeginLine(lua_State*) override {} + void print(Span<const char>) override {} + void printEndLine() override {} + void printError(lua_State* state) override + { + const char* error = lua_tostring(state, -1); + if (error != nullptr) + { + errors.push_back(error); + } + } + int pCall(lua_State* state, int nargs, int nresults) override + { + return lua_pcall(state, nargs, nresults, 0); + } + std::vector<std::string> errors; +}; + +// Reads the integer field `field` of the module cached under `key` in _MODULES. +// Returns INT_MIN when the module or field is absent. +int cachedIntField(lua_State* L, const std::string& key, const char* field) +{ + luaL_findtable(L, LUA_REGISTRYINDEX, "_MODULES", 1); + lua_getfield(L, -1, key.c_str()); + int result = INT_MIN; + if (lua_istable(L, -1)) + { + lua_getfield(L, -1, field); + if (lua_isnumber(L, -1)) + { + result = (int)lua_tointeger(L, -1); + } + lua_pop(L, 1); + } + lua_pop(L, 2); // module result + _MODULES table + return result; +} +} // namespace + +TEST_CASE("two versions of one module coexist", "[scripting][scope]") +{ + SerializingFactory factory; + auto ctxOwned = std::make_unique<ScopeTestContext>(&factory); + ScopeTestContext* ctx = ctxOwned.get(); + auto vm = make_rcp<ScriptingVM>(std::move(ctxOwned)); + lua_State* L = vm->state(); + + ScopeKey v1{1, 1}; + ScopeKey v2{1, 2}; + // Same module name, two library versions, different bodies. + ScopeTestModule fooV1("utils/math", v1, "return { v = 1 }"); + ScopeTestModule fooV2("utils/math", v2, "return { v = 2 }"); + // Same caller name in each version; each bare-requires "utils/math". + ScopeTestModule callerA("caller", v1, "return require('utils/math')"); + ScopeTestModule callerB("caller", v2, "return require('utils/math')"); + + ctx->addModule(&fooV1); + ctx->addModule(&fooV2); + ctx->addModule(&callerA); + ctx->addModule(&callerB); + ctx->performRegistration(L); + + // Both versions coexist under distinct scoped keys. + CHECK(cachedIntField(L, + ScriptingContext::scopedKey("utils/math", v1), + "v") == 1); + CHECK(cachedIntField(L, + ScriptingContext::scopedKey("utils/math", v2), + "v") == 2); + // Each caller's bare require bound its own version (relative scope). + CHECK(cachedIntField(L, ScriptingContext::scopedKey("caller", v1), "v") == + 1); + CHECK(cachedIntField(L, ScriptingContext::scopedKey("caller", v2), "v") == + 2); + CHECK(ctx->errors.empty()); +} + +TEST_CASE("qualified library require resolves via pins", "[scripting][scope]") +{ + SerializingFactory factory; + auto ctxOwned = std::make_unique<ScopeTestContext>(&factory); + ScopeTestContext* ctx = ctxOwned.get(); + auto vm = make_rcp<ScriptingVM>(std::move(ctxOwned)); + lua_State* L = vm->state(); + + ScopeKey geo{7, 3}; + ScopeTestModule libMesh("mesh", geo, "return { v = 42 }"); + // Host has its own 'mesh' at root scope; must not collide with the + // library's. + ScopeTestModule hostMesh("mesh", ScopeKey{}, "return { v = 7 }"); + ScopeTestModule app("app", + ScopeKey{}, + "local d = require('lib:geo/mesh')\n" + "local h = require('mesh')\n" + "return { v = d.v, host = h.v }"); + + ctx->addImport(ScopeKey{}, "geo", geo); // host pins geo -> (7,3) + ctx->addModule(&libMesh); + ctx->addModule(&hostMesh); + ctx->addModule(&app); + ctx->performRegistration(L); + + // Qualified require reached the library's mesh; bare require stayed at host + // root. + CHECK(cachedIntField(L, "app", "v") == 42); + CHECK(cachedIntField(L, "app", "host") == 7); + CHECK(ctx->errors.empty()); +} + +TEST_CASE("per caller pins diverge on the same label", "[scripting][scope]") +{ + // The diamond: host pins A to v2, library B pins A to v1. The label is + // per caller, both resolve to their own version. + SerializingFactory factory; + auto ctxOwned = std::make_unique<ScopeTestContext>(&factory); + ScopeTestContext* ctx = ctxOwned.get(); + auto vm = make_rcp<ScriptingVM>(std::move(ctxOwned)); + lua_State* L = vm->state(); + + ScopeKey aV1{7, 1}; + ScopeKey aV2{7, 2}; + ScopeKey b{8, 1}; + ScopeTestModule meshV1("mesh", aV1, "return { v = 1 }"); + ScopeTestModule meshV2("mesh", aV2, "return { v = 2 }"); + ScopeTestModule bUses("uses", b, "return require('lib:A/mesh')"); + ScopeTestModule app("app", + ScopeKey{}, + "return { v = require('lib:A/mesh').v }"); + + ctx->addImport(ScopeKey{}, "A", aV2); + ctx->addImport(b, "A", aV1); + ctx->addModule(&meshV1); + ctx->addModule(&meshV2); + ctx->addModule(&bUses); + ctx->addModule(&app); + ctx->performRegistration(L); + + CHECK(cachedIntField(L, "app", "v") == 2); + CHECK(cachedIntField(L, ScriptingContext::scopedKey("uses", b), "v") == 1); + CHECK(ctx->errors.empty()); +} + +TEST_CASE("unresolved library require errors, never rebinds to caller scope", + "[scripting][scope]") +{ + // An unpinned library require must fail, not rebind to a same named + // module in the caller's scope. + SerializingFactory factory; + auto ctxOwned = std::make_unique<ScopeTestContext>(&factory); + ScopeTestContext* ctx = ctxOwned.get(); + auto vm = make_rcp<ScriptingVM>(std::move(ctxOwned)); + lua_State* L = vm->state(); + + // Host has its own 'mesh'; no geo pin is ever registered. + ScopeTestModule hostMesh("mesh", ScopeKey{}, "return { v = 7 }"); + ScopeTestModule app("app", + ScopeKey{}, + "return { v = require('lib:geo/mesh').v }"); + ctx->addModule(&hostMesh); + ctx->addModule(&app); + ctx->performRegistration(L); + + // app must NOT have resolved (would be cached if it had); it errored. + CHECK(cachedIntField(L, "app", "v") == INT_MIN); + REQUIRE(!ctx->errors.empty()); + bool reportedMissing = false; + for (const auto& error : ctx->errors) + { + if (error.find("lib:geo/mesh") != std::string::npos) + { + reportedMissing = true; + } + } + CHECK(reportedMissing); +} + +TEST_CASE("ScriptAsset scope reads serialized FileAsset scope props", + "[scripting][scope]") +{ + ScriptAsset asset; + CHECK(asset.scope().isRoot()); // default (0,0) = host/root + + asset.scopeLibraryId(7); + asset.scopeLibraryVersionId(3); + CHECK(asset.scope().libraryId == 7); + CHECK(asset.scope().libraryVersionId == 3); + CHECK(!asset.scope().isRoot()); +} + +TEST_CASE("scoped module errors use readable names", "[scripting][scope]") +{ + SerializingFactory factory; + auto ctxOwned = std::make_unique<ScopeTestContext>(&factory); + ScopeTestContext* ctx = ctxOwned.get(); + auto vm = make_rcp<ScriptingVM>(std::move(ctxOwned)); + lua_State* L = vm->state(); + + ScopeKey v1{1, 1}; + ScopeTestModule bad("thing", v1, "error('boom')"); + ctx->addModule(&bad); + ctx->performRegistration(L); + + REQUIRE(!ctx->errors.empty()); + bool sawReadable = false; + for (const auto& error : ctx->errors) + { + if (error.find("1-1/thing") != std::string::npos) + { + sawReadable = true; + } + // The internal scoped-key delimiter must never leak into traces. + CHECK(error.find('\x1f') == std::string::npos); + } + CHECK(sawReadable); +} + +TEST_CASE("exported file resolves lib: requires through import edges", + "[scripting][scope][libraries]") +{ + // Exported by the editor: draco imported as a library, a host module + // scope_probe that lib:-requires it, bare-requires it under pcall, and + // records the outcomes. The whole scope pipeline in one file: edge and + // scope props deserialize, registerScripts seeds the pins, scoped cache + // keys isolate the library, the edge resolves the qualified require. + auto file = ReadRiveFile("assets/scope_probe.riv"); + REQUIRE(file->scriptingVM() != nullptr); + lua_State* L = file->scriptingVM()->state(); + + // Qualified require resolved and returned the real module. + CHECK(cachedIntField(L, "scope_probe", "lib") == 1); + CHECK(cachedIntField(L, "scope_probe", "hasDecode") == 1); + // Same request twice hits the scoped cache, not a re-execution. + CHECK(cachedIntField(L, "scope_probe", "cached") == 1); + // A bare require from the host never leaks into the library scope. + auto bc = compileLuau("local ok = pcall(require, 'draco')\n" + "return { ok = ok and 1 or 0 }"); + REQUIRE(ScriptingVM::registerModule(L, + "leak_probe", + Span<uint8_t>(bc.data(), bc.size()), + "leak_probe")); + CHECK(cachedIntField(L, "leak_probe", "ok") == 0); +}