From e3a16808d67874dfbc774daac06047b4aa6f6610 Mon Sep 17 00:00:00 2001 From: Xein Date: Wed, 11 Nov 2026 18:38:54 +0100 Subject: [PATCH 1/8] lua engine types --- .gitignore | 2 + editor/Assets/ProjectContext.cs | 14 ++++ editor/Engine/ToastEngine.cs | 11 ++- editor/Install/BuildInfo.cs | 29 ++++++++ engine/assets/lua/node.d.lua | 15 ++-- engine/assets/lua/signal.d.lua | 3 +- engine/assets/lua/toast.d.lua | 69 +------------------ engine/ffi/engine.h | 2 + engine/src/toast/assets/asset_registry.cpp | 22 ++++++ engine/src/toast/assets/asset_registry.hpp | 3 + engine/src/toast/engine.cpp | 20 ++++++ engine/src/toast/scripting/lua_state.cpp | 6 +- engine/src/toast/scripting/node_proxy.cpp | 22 ++++++ engine/src/toast/scripting/node_proxy.hpp | 1 + tools/CMakeLists.txt | 17 ----- .../Output/Templates/types.d.lua.scriban | 2 +- tools/reflection_generator/README.md | 8 --- tools/reflection_generator/Rules/LuaTypes.cs | 14 +++- .../reflection_generator.csproj | 5 -- 19 files changed, 156 insertions(+), 109 deletions(-) create mode 100644 editor/Install/BuildInfo.cs diff --git a/.gitignore b/.gitignore index 89abb3898..40a19dd49 100644 --- a/.gitignore +++ b/.gitignore @@ -14,6 +14,8 @@ logs/ **[Oo]bj** **[Tt]arget** !**/CrashTarget.cs +!**/BuildInfo.cs +!editor/LuaEditor/Graph/GraphBuilder.cs [Oo]ut engine/include/ vcpkg_installed/ diff --git a/editor/Assets/ProjectContext.cs b/editor/Assets/ProjectContext.cs index e1f9157eb..3aed5e7d4 100644 --- a/editor/Assets/ProjectContext.cs +++ b/editor/Assets/ProjectContext.cs @@ -75,6 +75,17 @@ public static void Initialize(string projectPath, string corePath) { DataSchemaStubGenerator.StartWatching(); } + // use runtime names so the stubs match registered asset types + public static void GenerateAssetTypeStubs(Action? log = null) { + var path = Path.Combine(CachePath, "lua", "asset_types.d.lua"); + if (!ToastEngine.IsEngineReady) { + log?.Invoke("Engine not ready, asset_types.d.lua not regenerated yet"); + return; + } + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + if (!ToastEngine.GenerateAssetTypeStubs(path)) log?.Invoke($"warning: failed to write {path}"); + } + public static void SyncLuaDefinitions(Action? log = null) { var src = Path.Combine(CorePath, "lua"); var dst = Path.Combine(CachePath, "lua"); @@ -96,6 +107,9 @@ public static void SyncLuaDefinitions(Action? log = null) { UIBindStubGenerator.Generate(); DataSchemaStubGenerator.Generate(); + // asset markers are unavailable until the engine starts + GenerateAssetTypeStubs(log); + var luarc = Path.Combine(ProjectPath, ".luarc.json"); if (File.Exists(luarc)) return; File.WriteAllText(luarc, diff --git a/editor/Engine/ToastEngine.cs b/editor/Engine/ToastEngine.cs index f9c8b871f..121295d8a 100644 --- a/editor/Engine/ToastEngine.cs +++ b/editor/Engine/ToastEngine.cs @@ -126,6 +126,8 @@ public ToastEngine(string toastPath) { toast_init(); IsEngineReady = true; DataSchemaStubGenerator.Generate(); + // fresh projects need asset markers after engine startup + ProjectContext.GenerateAssetTypeStubs(); toast_create_avalonia_window(); ReflectionDatabase.Update(); @@ -236,7 +238,7 @@ public static T OnTickThread(Func work) { failure = new OperationCanceledException("The engine stopped before the work could run"); finished.Set(); })); - + // The loop may have ended before the adding to the queue if (!engine.m_ticking) engine.CancelPendingTickWork(); finished.Wait(); @@ -645,6 +647,13 @@ public static bool GenerateDataSchemaStubs(string outPath) { return IsEngineReady && toast_generate_data_schema_stubs(outPath) != 0; } + [LibraryImport(EngineLib, StringMarshalling = StringMarshalling.Utf8)] + private static partial int toast_generate_asset_type_stubs(string outPath); + + public static bool GenerateAssetTypeStubs(string outPath) { + return IsEngineReady && toast_generate_asset_type_stubs(outPath) != 0; + } + private delegate IntPtr GameCreate(); private delegate void GameDestroy(IntPtr game); diff --git a/editor/Install/BuildInfo.cs b/editor/Install/BuildInfo.cs new file mode 100644 index 000000000..2d0cf1536 --- /dev/null +++ b/editor/Install/BuildInfo.cs @@ -0,0 +1,29 @@ +using System; +using System.IO; + +namespace editor.Install; + +public static class BuildInfo { + public static string InstallRoot { get; } = + Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "..")); + + public static string ToastPath { get; } = + Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "..", "toast_engine")); + + public static string EditorExe => Environment.ProcessPath ?? Path.Combine(AppContext.BaseDirectory, "editor"); + + public static Version? Version { get; } = ReadVersion(); + + public static string UpdateRepo => + Environment.GetEnvironmentVariable("TOAST_UPDATE_REPO") is { Length: > 0 } r ? r : "nullptr-studios/toast-engine"; + + private static Version? ReadVersion() { + try { + var file = Path.Combine(InstallRoot, "version.txt"); + if (!File.Exists(file)) return null; + return System.Version.TryParse(File.ReadAllText(file).Trim().TrimStart('v'), out var v) ? v : null; + } catch { + return null; + } + } +} diff --git a/engine/assets/lua/node.d.lua b/engine/assets/lua/node.d.lua index f0bebce9a..7989e29f3 100644 --- a/engine/assets/lua/node.d.lua +++ b/engine/assets/lua/node.d.lua @@ -47,18 +47,21 @@ function NodeProxy:parent() end ---@return Node function NodeProxy:root() end ----@param type TypeMarker|string ----@return Node[] [All matches in depth-first order] +---@generic T : Node +---@param type TypeMarker|string +---@return T[] [All matches in depth-first order] function NodeProxy:searchType(type) end ----@param type? TypeMarker|string ----@return Node[] +---@generic T : Node +---@param type? TypeMarker|string +---@return T[] function NodeProxy:getChildren(type) end ---Creates a new child node of the given type and attaches it to this node ---Only valid on nodes in the root or global state; calls the child's init lifecycle ----@param type string? [C++ class name, e.g. "toast::Node3D"; defaults to "toast::Node"] ----@return Node? [The new child node, or an empty box if the type is not registered] +---@generic T : Node +---@param type? TypeMarker|string +---@return T? [The new child node, or an empty box if the type is not registered] function NodeProxy:create(type) end --- probably shouldnt use in lua - dante diff --git a/engine/assets/lua/signal.d.lua b/engine/assets/lua/signal.d.lua index 97468849e..4e168c76f 100644 --- a/engine/assets/lua/signal.d.lua +++ b/engine/assets/lua/signal.d.lua @@ -15,8 +15,9 @@ function Signal:clear() end function Signal:fire() end +-- the concrete signal type depends on the argument count ---@param ... string ----@return Signal +---@return any function Signal:create(...) end ---@class Signal0 diff --git a/engine/assets/lua/toast.d.lua b/engine/assets/lua/toast.d.lua index 9eaba3f98..dcaf6b094 100644 --- a/engine/assets/lua/toast.d.lua +++ b/engine/assets/lua/toast.d.lua @@ -116,73 +116,10 @@ function tracy.Message(text) end ---Placeholder declaring a typed Node/Asset reference in an exported variable, ---e.g. `target = Node` or `mesh = Mesh`. The inspector shows a matching picker. ----@class TypeMarker +---@class TypeMarker --- (The generic Node marker and one marker per node type are emitted into types.d.lua --- by the reflection generator.) +-- concrete markers come from the engine so their names stay in sync ---Marker for a reference to any asset type. ----@type TypeMarker +---@type TypeMarker Asset = nil - --- Asset type markers, one per registered asset type ----@type TypeMarker -Mesh = nil ----@type TypeMarker -Texture = nil ----@type TypeMarker -Data = nil ----@type TypeMarker -Material = nil ----@type TypeMarker -Schema = nil ----@type TypeMarker -Prefab = nil ----@type TypeMarker -Script = nil ----@type TypeMarker -Curve = nil ----@type TypeMarker -AudioStrings = nil ----@type TypeMarker -AudioBank = nil ----@type TypeMarker -Haptic = nil ----@type TypeMarker -Action = nil ----@type TypeMarker -InputLayout = nil ----@type TypeMarker -InputSettings = nil ----@type TypeMarker -AudioEvent = nil ----@type TypeMarker -AudioBus = nil ----@type TypeMarker -AudioPort = nil ----@type TypeMarker -AudioSnapshot = nil ----@type TypeMarker -AudioVca = nil ----@type TypeMarker -VoxelModel = nil ----@type TypeMarker -VoxelPalette = nil ----@type TypeMarker -MaterialInstance = nil ----@type TypeMarker -Shader = nil ----@type TypeMarker -UIElement = nil ----@type TypeMarker -UIStyle = nil ----@type TypeMarker -Font = nil ----@type TypeMarker -UIImage = nil ----@type TypeMarker -ColorScheme = nil ----@type TypeMarker -Localization = nil ----@type TypeMarker -ImageLocalization = nil diff --git a/engine/ffi/engine.h b/engine/ffi/engine.h index f8d8075b5..cd8fa71c3 100644 --- a/engine/ffi/engine.h +++ b/engine/ffi/engine.h @@ -90,6 +90,8 @@ TOAST_C_API int toast_bake_asset(const char* uid, const char* out_path) NOEXCEPT */ TOAST_C_API int toast_generate_data_schema_stubs(const char* out_path) NOEXCEPT; +TOAST_C_API int toast_generate_asset_type_stubs(const char* out_path) NOEXCEPT; + // clang-format off /// sets all five URI roots; must be called before toast_init() /// @param assets content addressed by UID (assets://) diff --git a/engine/src/toast/assets/asset_registry.cpp b/engine/src/toast/assets/asset_registry.cpp index 7d015e755..b68103c9d 100644 --- a/engine/src/toast/assets/asset_registry.cpp +++ b/engine/src/toast/assets/asset_registry.cpp @@ -2,6 +2,10 @@ #include "types.hpp" +#include +#include +#include + namespace assets { std::unordered_map AssetRegistry::s_raw; @@ -112,6 +116,8 @@ void AssetRegistry::init() { s_lua_names["image_localization"] = "ImageLocalization"; s_lua_names["voxel_model"] = "VoxelModel"; s_lua_names["voxel_palette"] = "VoxelPalette"; + s_lua_names["animation"] = "Animation"; + s_lua_names["physics_material"] = "PhysicsMaterial"; } void AssetRegistry::registerLuaName(std::string_view type, std::string_view lua_name) { @@ -122,6 +128,22 @@ auto AssetRegistry::registeredLuaNames() -> const std::unordered_map std::string { + std::vector names; + names.reserve(s_lua_names.size()); + for (const auto& [type, lua_name] : s_lua_names) { + names.push_back(lua_name); + } + std::ranges::sort(names); + + std::string out = "-- generated from registered asset types\n"; + for (const auto& name : names) { + // separate annotations keep the marker from replacing its class + out += std::format("\n---@class {0} : Asset\n\n---@type TypeMarker<{0}>\n{0} = nil\n", name); + } + return out; +} + void AssetRegistry::registerRaw(std::string_view type, RawLoader loader) { s_raw[std::string(type)] = std::move(loader); } diff --git a/engine/src/toast/assets/asset_registry.hpp b/engine/src/toast/assets/asset_registry.hpp index 78ffc66b2..c64373b7c 100644 --- a/engine/src/toast/assets/asset_registry.hpp +++ b/engine/src/toast/assets/asset_registry.hpp @@ -41,6 +41,9 @@ class TOAST_API AssetRegistry { [[nodiscard]] static auto registeredLuaNames() -> const std::unordered_map&; + [[nodiscard]] + static auto luaStubs() -> std::string; + private: static std::unordered_map s_raw; static std::unordered_map s_toml; diff --git a/engine/src/toast/engine.cpp b/engine/src/toast/engine.cpp index 0f13805c7..94d240447 100644 --- a/engine/src/toast/engine.cpp +++ b/engine/src/toast/engine.cpp @@ -2,6 +2,7 @@ #include "application.hpp" #include "assets/asset_manager.hpp" +#include "assets/asset_registry.hpp" #include "assets/data_schema_codegen.hpp" #include "assets/prefab.hpp" #include "audio/audio_system.hpp" @@ -1408,6 +1409,25 @@ auto toast_generate_data_schema_stubs(const char* out_path) noexcept -> int { } } +auto toast_generate_asset_type_stubs(const char* out_path) noexcept -> int { + ZoneScoped; + if (!out_path) { + return 0; + } + try { + std::ofstream out(out_path, std::ios::binary | std::ios::trunc); + if (!out.is_open()) { + TOAST_ERROR("Engine", "toast_generate_asset_type_stubs: cannot open {}", out_path); + return 0; + } + out << assets::AssetRegistry::luaStubs(); + return out.good() ? 1 : 0; + } catch (const std::exception& e) { + TOAST_ERROR("Engine", "toast_generate_asset_type_stubs: {}", e.what()); + return 0; + } +} + void toast_haptics_test(const char* toml_text) noexcept { if (toml_text == nullptr) { return; diff --git a/engine/src/toast/scripting/lua_state.cpp b/engine/src/toast/scripting/lua_state.cpp index 6aa8f56a0..9c9279cec 100644 --- a/engine/src/toast/scripting/lua_state.cpp +++ b/engine/src/toast/scripting/lua_state.cpp @@ -967,7 +967,11 @@ void LuaState::registerApi(lua_State* state) noexcept { overload(&NodeProxy::getChildren), overload(&NodeProxy::getChildren) ) - .addFunction("create", &NodeProxy::create) + .addFunction( + "create", + overload(&NodeProxy::create), + overload(&NodeProxy::create) + ) .addFunction("addDependsOn", &NodeProxy::addDependsOn) .addFunction("interactsWith", &NodeProxy::interactsWith) .addFunction("call", &NodeProxy::call) diff --git a/engine/src/toast/scripting/node_proxy.cpp b/engine/src/toast/scripting/node_proxy.cpp index 0fc850a88..e648aa2e3 100644 --- a/engine/src/toast/scripting/node_proxy.cpp +++ b/engine/src/toast/scripting/node_proxy.cpp @@ -1166,6 +1166,18 @@ auto NodeProxy::create(const std::string& type, lua_State* l) -> luabridge::LuaR return {l, NodeProxy(result)}; } +auto NodeProxy::create(const TypeMarker& type, lua_State* l) -> luabridge::LuaRef { + if (!m_box.exists()) { + luaL_error(l, "NodeProxy::create: node reference is dead"); + return {l}; + } + const toast::NodeInfo* info = resolveMarker(type, "create", l); + if (!info) { + return {l}; + } + return create(std::string(info->type), l); +} + void NodeProxy::addDependsOn(const NodeProxy& other) { if (!m_box.exists() || !other.m_box.exists()) { return; @@ -1338,6 +1350,16 @@ auto nodeProxyDispatchMethod(NodeProxy& np, std::string_view name, lua_State* l, return 1; } if (name == "create") { + if (n_args >= 1 && lua_isuserdata(l, args_base)) { + auto marker = luabridge::Stack::get(l, args_base); + if (!marker) { + luaL_error(l, "create: expected a node type"); + return 0; + } + result = np.create(*marker, l); + result.push(l); + return 1; + } const char* type_name = n_args >= 1 ? lua_tostring(l, args_base) : "toast::Node"; result = np.create(type_name ? type_name : "toast::Node", l); result.push(l); diff --git a/engine/src/toast/scripting/node_proxy.hpp b/engine/src/toast/scripting/node_proxy.hpp index 92d8a8819..19a95f29f 100644 --- a/engine/src/toast/scripting/node_proxy.hpp +++ b/engine/src/toast/scripting/node_proxy.hpp @@ -80,6 +80,7 @@ class NodeProxy { auto getChildren(const std::string& type, lua_State* l) -> std::vector; auto getChildren(const TypeMarker& type, lua_State* l) -> std::vector; auto create(const std::string& type, lua_State* l) -> luabridge::LuaRef; + auto create(const TypeMarker& type, lua_State* l) -> luabridge::LuaRef; void addDependsOn(const NodeProxy& other); void interactsWith(const NodeProxy& other); diff --git a/tools/CMakeLists.txt b/tools/CMakeLists.txt index 153261819..f0edb309f 100644 --- a/tools/CMakeLists.txt +++ b/tools/CMakeLists.txt @@ -30,20 +30,3 @@ add_custom_target(kenzo ALL ) add_dependencies(reflection_generator packer) - -if (BUILD_TESTING) - find_program(DOTNET dotnet) - if (DOTNET) - add_test( - NAME refgen_unit_tests - COMMAND ${DOTNET} test "${CMAKE_CURRENT_SOURCE_DIR}/reflection_generator/tests/ReflectionGenerator.Tests" - WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/reflection_generator" - ) - set_tests_properties(refgen_unit_tests PROPERTIES - LABELS "reflection_generator;dotnet" - TIMEOUT 300 - ) - else() - message(WARNING "dotnet not found; skipping reflection_generator unit tests") - endif() -endif() diff --git a/tools/reflection_generator/Output/Templates/types.d.lua.scriban b/tools/reflection_generator/Output/Templates/types.d.lua.scriban index 0225d9742..9d12c89c4 100644 --- a/tools/reflection_generator/Output/Templates/types.d.lua.scriban +++ b/tools/reflection_generator/Output/Templates/types.d.lua.scriban @@ -15,7 +15,7 @@ ---@field {{ signal.name }} {{ signal.lua_type }} {{ end ~}} ----@type TypeMarker +---@type TypeMarker<{{ node.name }}> {{ node.name }} = nil {{ end ~}} diff --git a/tools/reflection_generator/README.md b/tools/reflection_generator/README.md index a95e964ef..a5b4f4f3f 100644 --- a/tools/reflection_generator/README.md +++ b/tools/reflection_generator/README.md @@ -70,11 +70,3 @@ Add a template and a view, render it from a writer in `Output` and call the writ - Attributes are written sorted by name and a repeated name keeps its last arguments, in the c++ and in the json. - The json keys have to match `editor/Engine/ReflectionDatabase.cs`. - Unknown field types fall back to `int_t`. The code compiles and the inspector widget will be wrong. - -## Tests - -```bash -dotnet test tests/ReflectionGenerator.Tests -``` - -Every header in `tests/ReflectionGenerator.Tests/Fixtures` is parsed and compared with the json in `Expected`, then rendered through every template. To add a case drop a `.hpp` in `Fixtures` and write what it should produce in `Expected`. diff --git a/tools/reflection_generator/Rules/LuaTypes.cs b/tools/reflection_generator/Rules/LuaTypes.cs index eb7cf11d8..6e040f02e 100644 --- a/tools/reflection_generator/Rules/LuaTypes.cs +++ b/tools/reflection_generator/Rules/LuaTypes.cs @@ -29,7 +29,15 @@ private static string ForHandleOrBox(string typeName) if (inner.StartsWith("Box<", StringComparison.Ordinal)) { return inner["Box<".Length..].TrimEnd('>').Bare(); } - return inner.Contains("Handle<") ? "Asset" : "any"; + return inner.Contains("Handle<") ? ForHandle(inner) : "any"; + } + + // asset handles need the same type names as runtime markers + private static string ForHandle(string type) + { + var afterBracket = type[(type.IndexOf("Handle<", StringComparison.Ordinal) + "Handle<".Length)..].TrimStart(); + var name = new string(afterBracket.TakeWhile(c => char.IsLetterOrDigit(c) || c is '_' or ':').ToArray()); + return name.Length == 0 ? "Asset" : name.Bare(); } // parameters, return values and signal arguments @@ -53,7 +61,7 @@ public static string ForCppType(string cpp) var inner = type.Split("Box<").ElementAtOrDefault(1) ?? "Node"; return inner.TrimEnd('>', '&', ' ').Bare(); } - if (type.Contains("Handle<")) return "Asset"; + if (type.Contains("Handle<")) return ForHandle(type); if (type.Contains("physics::RayHit")) return "RayHit"; if (type.Contains("bool")) return "boolean"; if (type.Contains("float") || type.Contains("double")) return "number"; @@ -101,7 +109,7 @@ public static (string Lua, bool Readable)? ForEventField(string cpp, IReadOnlyCo return ForEventField(element, enumNames) is { } inner ? (inner.Lua + "[]", inner.Readable) : null; } if (bare.StartsWith("assets::Handle<", StringComparison.Ordinal) || bare.StartsWith("Handle<", StringComparison.Ordinal)) { - return ("Asset", true); + return (ForHandle(bare), true); } if (enumNames.Contains(bare.Bare())) return ("integer", true); diff --git a/tools/reflection_generator/reflection_generator.csproj b/tools/reflection_generator/reflection_generator.csproj index 4f9262752..7591bda73 100644 --- a/tools/reflection_generator/reflection_generator.csproj +++ b/tools/reflection_generator/reflection_generator.csproj @@ -14,11 +14,6 @@ nullptr Studios - - - - - From 3e67ef38b72c6642d9ebd577d6f0720430e4a1f1 Mon Sep 17 00:00:00 2001 From: Xein Date: Wed, 11 Nov 2026 18:38:54 +0100 Subject: [PATCH 2/8] lua graph core --- editor/LuaEditor/Graph/Fragments.cs | 86 ++ editor/LuaEditor/Graph/GraphBuilder.cs | 575 +++++++++++++ editor/LuaEditor/Graph/GraphOps.cs | 634 ++++++++++++++ editor/LuaEditor/Graph/GraphSaver.cs | 444 ++++++++++ editor/LuaEditor/Graph/GraphSignature.cs | 204 +++++ editor/LuaEditor/Graph/GraphStructure.cs | 181 ++++ editor/LuaEditor/Graph/LuaGraph.cs | 82 ++ editor/LuaEditor/Graph/LuaWriter.cs | 319 +++++++ editor/LuaEditor/Graph/Model.cs | 812 ++++++++++++++++++ editor/LuaEditor/Graph/ScriptInfo.cs | 96 +++ editor/LuaEditor/Graph/StackGuard.cs | 32 + editor/LuaEditor/Graph/Typer.cs | 720 ++++++++++++++++ editor/LuaEditor/Graph/Variables.cs | 144 ++++ editor/LuaEditor/Syntax/LuaDocument.cs | 112 +++ editor/LuaEditor/Syntax/TextEdit.cs | 7 + editor/LuaEditor/Syntax/TriviaScanner.cs | 41 + editor/LuaEditor/Types/AnnotationParser.cs | 245 ++++++ editor/LuaEditor/Types/Annotations.cs | 33 + editor/LuaEditor/Types/CallResolver.cs | 151 ++++ editor/LuaEditor/Types/Declarations.cs | 26 + .../LuaEditor/Types/DefinitionFileReader.cs | 239 ++++++ editor/LuaEditor/Types/EquatableArray.cs | 46 + editor/LuaEditor/Types/LuaRc.cs | 62 ++ editor/LuaEditor/Types/LuaType.cs | 53 ++ editor/LuaEditor/Types/TypeChecker.cs | 188 ++++ editor/LuaEditor/Types/TypeExprParser.cs | 331 +++++++ editor/LuaEditor/Types/TypeFormatter.cs | 100 +++ editor/LuaEditor/Types/TypeUniverse.cs | 217 +++++ editor/LuaEditor/Types/TypeUniverseLoader.cs | 63 ++ editor/Resources/lua/stdlib/LICENSE | 21 + editor/Resources/lua/stdlib/README.md | 9 + editor/Resources/lua/stdlib/basic.lua | 477 ++++++++++ editor/Resources/lua/stdlib/builtin.lua | 16 + editor/Resources/lua/stdlib/coroutine.lua | 96 +++ editor/Resources/lua/stdlib/debug.lua | 274 ++++++ editor/Resources/lua/stdlib/io.lua | 265 ++++++ editor/Resources/lua/stdlib/math.lua | 381 ++++++++ editor/Resources/lua/stdlib/os.lua | 244 ++++++ editor/Resources/lua/stdlib/package.lua | 107 +++ editor/Resources/lua/stdlib/string.lua | 219 +++++ editor/Resources/lua/stdlib/table.lua | 177 ++++ editor/Resources/lua/stdlib/utf8.lua | 87 ++ editor/editor.csproj | 4 +- 43 files changed, 8619 insertions(+), 1 deletion(-) create mode 100644 editor/LuaEditor/Graph/Fragments.cs create mode 100644 editor/LuaEditor/Graph/GraphBuilder.cs create mode 100644 editor/LuaEditor/Graph/GraphOps.cs create mode 100644 editor/LuaEditor/Graph/GraphSaver.cs create mode 100644 editor/LuaEditor/Graph/GraphSignature.cs create mode 100644 editor/LuaEditor/Graph/GraphStructure.cs create mode 100644 editor/LuaEditor/Graph/LuaGraph.cs create mode 100644 editor/LuaEditor/Graph/LuaWriter.cs create mode 100644 editor/LuaEditor/Graph/Model.cs create mode 100644 editor/LuaEditor/Graph/ScriptInfo.cs create mode 100644 editor/LuaEditor/Graph/StackGuard.cs create mode 100644 editor/LuaEditor/Graph/Typer.cs create mode 100644 editor/LuaEditor/Graph/Variables.cs create mode 100644 editor/LuaEditor/Syntax/LuaDocument.cs create mode 100644 editor/LuaEditor/Syntax/TextEdit.cs create mode 100644 editor/LuaEditor/Syntax/TriviaScanner.cs create mode 100644 editor/LuaEditor/Types/AnnotationParser.cs create mode 100644 editor/LuaEditor/Types/Annotations.cs create mode 100644 editor/LuaEditor/Types/CallResolver.cs create mode 100644 editor/LuaEditor/Types/Declarations.cs create mode 100644 editor/LuaEditor/Types/DefinitionFileReader.cs create mode 100644 editor/LuaEditor/Types/EquatableArray.cs create mode 100644 editor/LuaEditor/Types/LuaRc.cs create mode 100644 editor/LuaEditor/Types/LuaType.cs create mode 100644 editor/LuaEditor/Types/TypeChecker.cs create mode 100644 editor/LuaEditor/Types/TypeExprParser.cs create mode 100644 editor/LuaEditor/Types/TypeFormatter.cs create mode 100644 editor/LuaEditor/Types/TypeUniverse.cs create mode 100644 editor/LuaEditor/Types/TypeUniverseLoader.cs create mode 100644 editor/Resources/lua/stdlib/LICENSE create mode 100644 editor/Resources/lua/stdlib/README.md create mode 100644 editor/Resources/lua/stdlib/basic.lua create mode 100644 editor/Resources/lua/stdlib/builtin.lua create mode 100644 editor/Resources/lua/stdlib/coroutine.lua create mode 100644 editor/Resources/lua/stdlib/debug.lua create mode 100644 editor/Resources/lua/stdlib/io.lua create mode 100644 editor/Resources/lua/stdlib/math.lua create mode 100644 editor/Resources/lua/stdlib/os.lua create mode 100644 editor/Resources/lua/stdlib/package.lua create mode 100644 editor/Resources/lua/stdlib/string.lua create mode 100644 editor/Resources/lua/stdlib/table.lua create mode 100644 editor/Resources/lua/stdlib/utf8.lua diff --git a/editor/LuaEditor/Graph/Fragments.cs b/editor/LuaEditor/Graph/Fragments.cs new file mode 100644 index 000000000..934cb22ab --- /dev/null +++ b/editor/LuaEditor/Graph/Fragments.cs @@ -0,0 +1,86 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using editor.LuaEditor.Syntax; +using editor.LuaEditor.Types; + +namespace editor.LuaEditor.Graph; + +public sealed record PasteResult(IReadOnlyList Statements, IReadOnlyList Errors); + +public static class Fragments { + public static string Copy(IEnumerable statements) { + var list = statements.ToList(); + if (list.Count == 0) return ""; + var graph = list[0].Graph; + var text = new LuaWriter(graph.Document).Statements(list, 0); + return text.Length == 0 ? "" : text + graph.Document.Eol; + } + + public static string? CopyExpression(ExprNode root) { + var graph = root.Graph; + var holder = new ReturnStatement(graph); + var pin = holder.AddValue(); + try { + pin.Connect(root.Result); + return new LuaWriter(graph.Document).Expression(pin); + } catch (InvalidOperationException) { + return null; + } finally { + pin.Clear(); + graph.Unregister(holder); + } + } + + public static List BuildLoose(LuaGraph graph, string expression) { + var document = LuaDocument.Parse("return " + expression); + if (document.HasErrors) return []; + var before = graph.Nodes.Count; + try { + var built = StackGuard.Run(() => new GraphBuilder(graph, document).BuildFragment(LuaGraph.VisibleFromBlock(graph.Module, graph.Module.Statements.Count))); + if (built is [ReturnStatement { Values: [{ Source: { Binding: null, Owner: ExprNode root } } pin] } holder]) { + pin.Clear(); + graph.Unregister(holder); + var nodes = graph.Nodes.Skip(before).OfType().Where(n => n != root).Prepend(root).ToList(); + return nodes; + } + } catch (Exception e) when (e is InvalidOperationException or ArgumentException or NullReferenceException) { + } + graph.ForgetNodesAfter(before); + return []; + } + + public static PasteResult Paste(LuaGraph graph, string luaText, Block into, int index) { + if (index < 0 || index > into.Statements.Count) return Failure("the place to paste at is outside the block"); + var document = LuaDocument.Parse(luaText); + if (document.HasErrors) return new PasteResult([], document.Errors); + + List built; + try { + var nodesBefore = graph.Nodes.Count; + try { + built = StackGuard.Run(() => new GraphBuilder(graph, document).BuildFragment(LuaGraph.VisibleFromBlock(into, index))); + } catch { + graph.ForgetNodesAfter(nodesBefore); + throw; + } + } catch (Exception e) when (e is InvalidOperationException or ArgumentException or NullReferenceException) { + return Failure("could not read the pasted text: " + e.Message); + } + + var inserted = new List(); + try { + foreach (var statement in built) { + graph.Insert(into, index + inserted.Count, statement); + inserted.Add(statement); + } + } catch (Exception e) when (e is InvalidOperationException or ArgumentException) { + foreach (var statement in inserted) graph.Discard(statement); + foreach (var statement in built.Skip(inserted.Count)) graph.Discard(statement); + return Failure(e.Message); + } + return new PasteResult(built, []); + + static PasteResult Failure(string message) => new([], [new Diagnostic(DiagnosticSeverity.Error, message, new SourceLocation("", 1))]); + } +} diff --git a/editor/LuaEditor/Graph/GraphBuilder.cs b/editor/LuaEditor/Graph/GraphBuilder.cs new file mode 100644 index 000000000..f25e8ad7a --- /dev/null +++ b/editor/LuaEditor/Graph/GraphBuilder.cs @@ -0,0 +1,575 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using editor.LuaEditor.Syntax; +using Loretta.CodeAnalysis; +using Loretta.CodeAnalysis.Lua; +using Loretta.CodeAnalysis.Lua.Syntax; +using Loretta.CodeAnalysis.Text; + +namespace editor.LuaEditor.Graph; + +internal sealed class GraphBuilder { + private static readonly Dictionary s_binary = new() { + ["+"] = BinaryKind.Add, ["-"] = BinaryKind.Sub, ["*"] = BinaryKind.Mul, ["/"] = BinaryKind.Div, ["//"] = BinaryKind.FloorDiv, + ["%"] = BinaryKind.Mod, ["^"] = BinaryKind.Pow, [".."] = BinaryKind.Concat, ["=="] = BinaryKind.Eq, ["~="] = BinaryKind.Ne, + ["<"] = BinaryKind.Lt, ["<="] = BinaryKind.Le, [">"] = BinaryKind.Gt, [">="] = BinaryKind.Ge, ["and"] = BinaryKind.And, + ["or"] = BinaryKind.Or, ["&"] = BinaryKind.BitAnd, ["|"] = BinaryKind.BitOr, ["~"] = BinaryKind.BitXor, ["<<"] = BinaryKind.Shl, + [">>"] = BinaryKind.Shr, + }; + + private static readonly Dictionary s_unary = new() { + ["-"] = UnaryKind.Neg, ["not"] = UnaryKind.Not, ["#"] = UnaryKind.Len, ["~"] = UnaryKind.BitNot, + }; + + private sealed class Scope(Scope? parent) { + private readonly Dictionary m_names = []; + + public Scope? Parent { get; } = parent; + + public void Declare(Binding binding) => m_names[binding.Name] = binding; + + public Binding? Find(string name) { + for (var scope = this; scope is not null; scope = scope.Parent) + if (scope.m_names.TryGetValue(name, out var found)) return found; + return null; + } + } + + private readonly LuaGraph m_graph; + private readonly LuaDocument m_doc; + private readonly List<(InputPin Pin, Binding Binding, Statement? Statement)> m_refs = []; + private readonly List m_bindings = []; + private Scope m_scope = new(null); + private Statement? m_statement; + + public GraphBuilder(LuaGraph graph, LuaDocument doc) { + m_graph = graph; + m_doc = doc; + } + + public void Build() { + var module = m_graph.Module; + module.OpenEnd = 0; + module.CloseStart = m_doc.Text.Length; + BuildBlock(module, m_doc.Root.Statements, m_doc.Root.EndOfFileToken); + Finish(); + GraphSaver.Snapshot(m_graph); + } + + public List BuildFragment(IEnumerable visibleNearestFirst) { + foreach (var binding in visibleNearestFirst.Reverse()) m_scope.Declare(binding); + var holder = new Block("fragment"); + BuildBlock(holder, m_doc.Root.Statements, m_doc.Root.EndOfFileToken); + Finish(); + var statements = holder.Statements.ToList(); + foreach (var statement in statements) { + holder.Remove(statement); + Detach(statement); + } + return statements; + } + + // pasted nodes must not point into clipboard source spans + private static void Detach(Statement statement) { + statement.Source = null; + statement.Spans.Clear(); + statement.LeadingLinesSpan = null; + statement.Baseline = null; + switch (statement) { + case CommentStatement comment: + comment.LineSpan = null; + break; + case CastStatement cast: + cast.LineSpan = null; + break; + case FunctionDecl function: + function.Entry.ParamsSpan = null; + break; + } + foreach (var pin in statement.Inputs) DetachPin(pin); + foreach (var block in statement.ChildBlocks) DetachBlock(block); + } + + private static void DetachBlock(Block block) { + block.OpenEnd = -1; + block.CloseStart = -1; + block.Original = []; + foreach (var statement in block.Statements) Detach(statement); + } + + private static void DetachPin(InputPin pin) { + pin.Origin = null; + if (pin.Source is not { Binding: null } source || source.Owner is not ExprNode node) return; + foreach (var input in node.Inputs) DetachPin(input); + if (node is FunctionNode function) { + function.Entry.ParamsSpan = null; + DetachBlock(function.Entry.Body); + } + } + + private void Finish() { + foreach (var binding in m_bindings) binding.IsMutable = binding.Assignments > 0; + foreach (var (pin, binding, statement) in m_refs) { + if (binding.IsMutable) { + var get = New(new VariableGet(m_graph, binding), statement); + pin.Connect(get.Result); + } else { + pin.Connect(binding.Output); + } + } + } + + private T New(T node, Statement? owner = null) where T : GraphNode { + node.OwnerStatement = owner ?? m_statement; + return node; + } + + private void Declare(Binding binding) { + m_scope.Declare(binding); + m_bindings.Add(binding); + } + + private void Push() => m_scope = new Scope(m_scope); + + private void Pop() => m_scope = m_scope.Parent!; + + private static TextSpan Bounds(IEnumerable nodes) { + var list = nodes.ToList(); + return TextSpan.FromBounds(list[0].Span.Start, list[^1].Span.End); + } + + private void BuildBlock(Block block, StatementListSyntax list, SyntaxToken closeToken) { + var carried = new List(); + foreach (var syntax in list.Statements) { + var attached = EmitLeadingLines(block, TriviaScanner.LeadingLines(syntax.GetFirstToken()), true); + var statement = BuildStatement(syntax); + if (statement is null) { + carried.AddRange(attached); + continue; + } + if (carried.Count > 0) { + attached = [.. carried, .. attached]; + carried.Clear(); + } + if (attached.Count > 0) { + statement.LeadingLines.AddRange(attached.Select(l => l.Text)); + statement.LeadingLinesSpan = TextSpan.FromBounds(attached[0].Span.Start, attached[^1].Span.End); + } + block.Add(statement); + } + EmitLeadingLines(block, TriviaScanner.LeadingLines(closeToken), false); + } + + private List EmitLeadingLines(Block block, IReadOnlyList lines, bool attach) { + var group = new List(); + void Flush() { + if (group.Count == 0) return; + var comment = new CommentStatement(m_graph, group.Select(l => l.Text)) { LineSpan = TextSpan.FromBounds(group[0].Span.Start, group[^1].Span.End) }; + block.Add(comment); + group.Clear(); + } + + foreach (var line in lines) { + switch (line.Kind) { + case TriviaLineKind.Blank: + Flush(); + break; + case TriviaLineKind.Cast: + Flush(); + var parts = line.Text["---@cast".Length..].Trim().Split(new[] { ' ', '\t' }, 2, StringSplitOptions.RemoveEmptyEntries); + var cast = new CastStatement(m_graph, parts.ElementAtOrDefault(0) ?? "", parts.ElementAtOrDefault(1) ?? "") { LineSpan = line.Span, Target = m_scope.Find(parts.ElementAtOrDefault(0) ?? "") }; + block.Add(cast); + break; + default: + group.Add(line); + break; + } + } + if (attach) return group; + Flush(); + return []; + } + + private Statement? BuildStatement(StatementSyntax syntax) { + var saved = m_statement; + try { + var statement = BuildStatementCore(syntax); + if (statement is not null) statement.Source = syntax; + return statement; + } finally { + m_statement = saved; + } + } + + private T Begin(T statement) where T : Statement { + m_statement = statement; + return statement; + } + + private Statement? BuildStatementCore(StatementSyntax syntax) { + switch (syntax) { + case EmptyStatementSyntax: + return null; + case LocalVariableDeclarationStatementSyntax local: + return BuildLocal(local); + case LocalFunctionDeclarationStatementSyntax localFunction: + return BuildLocalFunction(localFunction); + case FunctionDeclarationStatementSyntax function: + return BuildFunctionDeclaration(function); + case AssignmentStatementSyntax assignment: + return BuildAssignment(assignment); + case ExpressionStatementSyntax { Expression: FunctionCallExpressionSyntax or MethodCallExpressionSyntax } expression: { + var s = Begin(new CallStatement(m_graph)); + BindExpr(s.Call, expression.Expression); + return s; + } + case IfStatementSyntax @if: + return BuildIf(@if); + case WhileStatementSyntax @while: { + var s = Begin(new WhileStatement(m_graph)); + BindExpr(s.Condition, @while.Condition); + Scoped(s.Body, @while.Body, @while.DoKeyword, @while.EndKeyword); + return s; + } + case RepeatUntilStatementSyntax repeat: { + var s = Begin(new RepeatStatement(m_graph)); + s.Body.OpenEnd = repeat.RepeatKeyword.Span.End; + s.Body.CloseStart = repeat.UntilKeyword.Span.Start; + // repeat conditions can read locals from the loop body + Push(); + BuildBlock(s.Body, repeat.Body, repeat.UntilKeyword); + BindExpr(s.Condition, repeat.Condition); + Pop(); + return s; + } + case NumericForStatementSyntax numeric: + return BuildNumericFor(numeric); + case GenericForStatementSyntax generic: + return BuildGenericFor(generic); + case DoStatementSyntax @do: { + var s = Begin(new DoStatement(m_graph)); + Scoped(s.Body, @do.Body, @do.DoKeyword, @do.EndKeyword); + return s; + } + case ReturnStatementSyntax @return: { + var s = Begin(new ReturnStatement(m_graph)); + foreach (var value in @return.Expressions) BindExpr(s.AddValue(), value); + return s; + } + case BreakStatementSyntax: + return Begin(new BreakStatement(m_graph)); + case GotoStatementSyntax @goto: { + var s = Begin(new GotoStatement(m_graph, @goto.LabelName.Text)); + s.Spans["label"] = @goto.LabelName.Span; + return s; + } + case GotoLabelStatementSyntax label: { + var s = Begin(new LabelStatement(m_graph, label.Identifier.Text)); + s.Spans["name"] = label.Identifier.Span; + return s; + } + default: + m_graph.Warn($"line {m_doc.LineOf(syntax.Span.Start)}: {syntax.GetType().Name} is kept as text"); + return Begin(new RawStatement(m_graph, syntax.ToString())); + } + } + + private void Scoped(Block block, StatementListSyntax body, SyntaxToken open, SyntaxToken close, Action? declare = null) { + block.OpenEnd = open.Span.End; + block.CloseStart = close.Span.Start; + Push(); + declare?.Invoke(); + BuildBlock(block, body, close); + Pop(); + } + + private Statement BuildLocal(LocalVariableDeclarationStatementSyntax syntax) { + var s = Begin(new LocalDecl(m_graph)); + if (syntax.EqualsValues is not null) + foreach (var value in syntax.EqualsValues.Values) BindExpr(s.AddValue(), value); + // a redeclared local still uses the outer binding in its initializer + var created = new List(); + foreach (var name in syntax.Names) { + var binding = s.AddName(name.Name); + if (!string.IsNullOrEmpty(name.AttributeName)) binding.Attribute = name.AttributeName; + created.Add(binding); + } + s.Spans["names"] = Bounds(syntax.Names); + foreach (var binding in created) Declare(binding); + return s; + } + + private Statement BuildLocalFunction(LocalFunctionDeclarationStatementSyntax syntax) { + var s = Begin(new FunctionDecl(m_graph, true, syntax.Name.Name)); + Declare(s.FunctionBinding!); + s.Spans["name"] = syntax.Name.Span; + BuildFunctionBody(s.Entry, syntax.Parameters, syntax.Body, false, syntax.EndKeyword); + return s; + } + + private Statement BuildFunctionDeclaration(FunctionDeclarationStatementSyntax syntax) { + var path = new List(); + var isMethod = false; + void Flatten(FunctionNameSyntax name) { + switch (name) { + case SimpleFunctionNameSyntax simple: + path.Add(simple.Name.Text); + break; + case MemberFunctionNameSyntax member: + Flatten(member.BaseName); + path.Add(member.Name.Text); + break; + case MethodFunctionNameSyntax method: + Flatten(method.BaseName); + path.Add(method.Name.Text); + isMethod = true; + break; + } + } + Flatten(syntax.Name); + + var s = Begin(new FunctionDecl(m_graph, false, path[0])); + s.Path.Clear(); + s.Path.AddRange(path); + s.IsMethod = isMethod; + s.Spans["name"] = syntax.Name.Span; + if (path.Count > 1) { + ResolveName(s.Root, path[0]); + } else if (m_scope.Find(path[0]) is { } existing) { + s.AssignedBinding = existing; + existing.Assignments++; + } + BuildFunctionBody(s.Entry, syntax.Parameters, syntax.Body, isMethod, syntax.EndKeyword); + return s; + } + + private void BuildFunctionBody(FunctionEntry entry, ParameterListSyntax parameters, StatementListSyntax body, bool isMethod, SyntaxToken end) { + entry.ParamsSpan = parameters.Span; + entry.Body.OpenEnd = parameters.CloseParenthesisToken.Span.End; + entry.Body.CloseStart = end.Span.Start; + var outer = m_statement; + Push(); + if (isMethod) Declare(entry.AddParam("self", BindingKind.Self)); + foreach (var parameter in parameters.Parameters) { + switch (parameter) { + case NamedParameterSyntax named: + Declare(entry.AddParam(named.Name, BindingKind.Param)); + break; + case VarArgParameterSyntax: + entry.IsVararg = true; + break; + } + } + BuildBlock(entry.Body, body, end); + Pop(); + m_statement = outer; + } + + private Statement BuildAssignment(AssignmentStatementSyntax syntax) { + var s = Begin(new AssignStatement(m_graph)); + foreach (var variable in syntax.Variables) { + switch (variable) { + case IdentifierNameSyntax identifier: + if (m_scope.Find(identifier.Name) is { } binding) s.AddBindingTarget(binding); + else s.AddGlobalTarget(identifier.Name); + break; + case MemberAccessExpressionSyntax member: { + var target = s.AddMemberTarget(member.MemberName.Text); + BindExpr(target.Object!, member.Expression); + break; + } + case ElementAccessExpressionSyntax element: { + var target = s.AddIndexTarget(); + BindExpr(target.Object!, element.Expression); + BindExpr(target.Key!, element.KeyExpression); + break; + } + default: + throw new InvalidOperationException($"cannot assign to {variable.GetType().Name}"); + } + } + s.Spans["targets"] = Bounds(syntax.Variables); + foreach (var value in syntax.EqualsValues.Values) BindExpr(s.AddValue(), value); + return s; + } + + private Statement BuildIf(IfStatementSyntax syntax) { + var s = Begin(new IfStatement(m_graph)); + var keywords = new List(); + keywords.AddRange(syntax.ElseIfClauses.Select(c => c.ElseIfKeyword)); + if (syntax.ElseClause is not null) keywords.Add(syntax.ElseClause.ElseKeyword); + keywords.Add(syntax.EndKeyword); + + var first = s.AddClause(); + BindExpr(first.Condition, syntax.Condition); + Scoped(first.Body, syntax.Body, syntax.ThenKeyword, keywords[0]); + var next = 1; + foreach (var clause in syntax.ElseIfClauses) { + var c = s.AddClause(); + BindExpr(c.Condition, clause.Condition); + Scoped(c.Body, clause.Body, clause.ThenKeyword, keywords[next++]); + } + if (syntax.ElseClause is not null) Scoped(s.AddElse(), syntax.ElseClause.ElseBody, syntax.ElseClause.ElseKeyword, syntax.EndKeyword); + return s; + } + + private Statement BuildNumericFor(NumericForStatementSyntax syntax) { + var s = Begin(new NumericFor(m_graph, syntax.Identifier.Name)); + s.Spans["var"] = syntax.Identifier.Span; + BindExpr(s.Start, syntax.InitialValue); + BindExpr(s.Limit, syntax.FinalValue); + if (syntax.StepValue is not null) BindExpr(s.Step, syntax.StepValue); + Scoped(s.Body, syntax.Body, syntax.DoKeyword, syntax.EndKeyword, () => Declare(s.Var)); + return s; + } + + private Statement BuildGenericFor(GenericForStatementSyntax syntax) { + var s = Begin(new GenericFor(m_graph)); + foreach (var expression in syntax.Expressions) BindExpr(s.AddExpr(), expression); + var vars = syntax.Identifiers.Select(i => s.AddVar(i.Name)).ToList(); + s.Spans["vars"] = Bounds(syntax.Identifiers); + Scoped(s.Body, syntax.Body, syntax.DoKeyword, syntax.EndKeyword, () => vars.ForEach(Declare)); + return s; + } + + private void ResolveName(InputPin pin, string name) { + if (m_scope.Find(name) is { } binding) { + m_refs.Add((pin, binding, m_statement)); + return; + } + pin.Connect(New(new GlobalGet(m_graph, name)).Result); + } + + private static bool IsMultiValue(ExpressionSyntax expression) { + while (expression is ParenthesizedExpressionSyntax paren) expression = paren.Expression; + return expression is FunctionCallExpressionSyntax or MethodCallExpressionSyntax or VarArgExpressionSyntax; + } + + private void BindExpr(InputPin pin, ExpressionSyntax expression) { + pin.Origin = expression; + switch (expression) { + case LiteralExpressionSyntax literal: + BindLiteral(pin, literal); + return; + case VarArgExpressionSyntax: + pin.Connect(New(new VarargNode(m_graph)).Result); + return; + case IdentifierNameSyntax identifier: + ResolveName(pin, identifier.Name); + return; + case ParenthesizedExpressionSyntax paren: + if (IsMultiValue(paren.Expression)) { + var node = New(new ParenNode(m_graph)); + pin.Connect(node.Result); + BindExpr(node.Inner, paren.Expression); + } else { + BindExpr(pin, paren.Expression); + } + pin.Origin = expression; + return; + case MemberAccessExpressionSyntax member: { + var node = New(new MemberGet(m_graph, member.MemberName.Text)); + pin.Connect(node.Result); + BindExpr(node.Object, member.Expression); + return; + } + case ElementAccessExpressionSyntax element: { + var node = New(new IndexGet(m_graph)); + pin.Connect(node.Result); + BindExpr(node.Object, element.Expression); + BindExpr(node.Key, element.KeyExpression); + return; + } + case FunctionCallExpressionSyntax call: { + var node = New(new CallNode(m_graph, CallStyle.Function, null)); + pin.Connect(node.Result); + BindExpr(node.Target, call.Expression); + BindArguments(node, call.Argument); + return; + } + case MethodCallExpressionSyntax method: { + var node = New(new CallNode(m_graph, CallStyle.Method, method.Identifier.Text)); + pin.Connect(node.Result); + BindExpr(node.Target, method.Expression); + BindArguments(node, method.Argument); + return; + } + case AnonymousFunctionExpressionSyntax function: { + var node = New(new FunctionNode(m_graph) { SourceSpan = function.Span }); + pin.Connect(node.Result); + BuildFunctionBody(node.Entry, function.Parameters, function.Body, false, function.EndKeyword); + return; + } + case TableConstructorExpressionSyntax table: + BindTable(pin, table); + return; + case BinaryExpressionSyntax binary when s_binary.TryGetValue(binary.OperatorToken.Text, out var kind): { + var node = New(new BinaryOp(m_graph, kind)); + pin.Connect(node.Result); + BindExpr(node.Left, binary.Left); + BindExpr(node.Right, binary.Right); + return; + } + case UnaryExpressionSyntax unary when s_unary.TryGetValue(unary.OperatorToken.Text, out var kind): { + var node = New(new UnaryOp(m_graph, kind)); + pin.Connect(node.Result); + BindExpr(node.Operand, unary.Operand); + return; + } + default: + m_graph.Warn($"line {m_doc.LineOf(expression.Span.Start)}: {expression.GetType().Name} is kept as text"); + pin.Connect(New(new RawExpression(m_graph, expression.ToString())).Result); + return; + } + } + + private void BindLiteral(InputPin pin, LiteralExpressionSyntax literal) { + var text = literal.Token.Text; + var kind = literal.Token.Kind().ToString(); + if (text == "nil") { + pin.SetConstant(LuaConstant.Nil); + } else if (text is "true" or "false") { + pin.SetConstant(text == "true" ? LuaConstant.True : LuaConstant.False); + } else if (kind.Contains("String")) { + pin.SetConstant(new LuaConstant(ConstantKind.String, text)); + } else { + pin.SetConstant(LuaConstant.Number(text)); + } + } + + private void BindArguments(CallNode node, FunctionArgumentSyntax argument) { + switch (argument) { + case ExpressionListFunctionArgumentSyntax list: + foreach (var expression in list.Expressions) BindExpr(node.AddArg(), expression); + break; + case StringFunctionArgumentSyntax text: + BindExpr(node.AddArg(), text.Expression); + break; + case TableConstructorFunctionArgumentSyntax table: + BindExpr(node.AddArg(), table.TableConstructor); + break; + } + } + + private void BindTable(InputPin pin, TableConstructorExpressionSyntax table) { + var node = New(new TableNode(m_graph)); + pin.Connect(node.Result); + foreach (var field in table.Fields) { + switch (field) { + case UnkeyedTableFieldSyntax unkeyed: + BindExpr(node.AddPositional().Value, unkeyed.Value); + break; + case IdentifierKeyedTableFieldSyntax named: + BindExpr(node.AddNamed(named.Identifier.Text).Value, named.Value); + break; + case ExpressionKeyedTableFieldSyntax keyed: { + var added = node.AddKeyed(); + BindExpr(added.Key!, keyed.Key); + BindExpr(added.Value, keyed.Value); + break; + } + } + } + } +} diff --git a/editor/LuaEditor/Graph/GraphOps.cs b/editor/LuaEditor/Graph/GraphOps.cs new file mode 100644 index 000000000..cfdd655dd --- /dev/null +++ b/editor/LuaEditor/Graph/GraphOps.cs @@ -0,0 +1,634 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.RegularExpressions; + +namespace editor.LuaEditor.Graph; + +public sealed partial class LuaGraph { + + public LocalDecl NewLocal(string name) { + if (!LuaWriter.IsIdentifier(name)) throw new ArgumentException($"\"{name}\" is not a valid name", nameof(name)); + var declaration = new LocalDecl(this); + declaration.AddName(name); + declaration.AddValue(); + return declaration; + } + + public CallStatement NewCallStatement(string globalFunction, params LuaConstant[] arguments) { + var call = new CallNode(this, CallStyle.Function, null); + call.Target.Connect(new GlobalGet(this, globalFunction).Result); + foreach (var argument in arguments) call.AddArg().SetConstant(argument); + var statement = new CallStatement(this); + statement.Call.Connect(call.Result); + Adopt(statement); + return statement; + } + + public CallNode NewMethodCall(string method) { + if (!LuaWriter.IsIdentifier(method)) throw new ArgumentException($"\"{method}\" cannot be written after a colon", nameof(method)); + return new CallNode(this, CallStyle.Method, method); + } + + public void SetConstant(InputPin pin, LuaConstant constant) { + var previous = pin.Source; + pin.SetConstant(constant); + Prune(previous); + } + + public void Disconnect(InputPin pin) { + var previous = pin.Source; + pin.Clear(); + Prune(previous); + } + + public void Connect(OutputPin from, InputPin to) { + if (from.Owner.Graph != this || to.Owner.Graph != this) throw new InvalidOperationException("both pins must belong to this graph"); + if (DependsOn(from.Owner, to.Owner)) throw new InvalidOperationException("that connection would make a value depend on itself"); + + var site = to.Owner.OwnerStatement; + var source = from; + VariableGet? get = null; + if (from.Binding is { IsMutable: true } mutable) { + get = new VariableGet(this, mutable) { OwnerStatement = site }; + source = get.Result; + } + + var previous = to.Source; + var previousConstant = to.Constant; + to.Connect(source); + if (site is not null) AdoptUnowned(source.Owner, site); + // moving an expression can put its names out of scope + var problem = site is null ? null : SiteProblem([site]); + if (problem is not null) { + if (previous is not null) to.Connect(previous); + else if (previousConstant is not null) to.SetConstant(previousConstant); + else to.Clear(); + if (get is not null) Unregister(get); + throw new InvalidOperationException(problem); + } + Prune(previous); + } + + private static bool DependsOn(GraphNode node, GraphNode target) { + if (node == target) return true; + return node.Inputs.Any(p => p.Source is { Binding: null } source && source.Owner is ExprNode child && DependsOn(child, target)); + } + + public T Insert(Block block, int index, T statement) where T : Statement { + if (statement.Parent is not null) throw new ArgumentException("the statement is already in a block; use Move", nameof(statement)); + if (index < 0 || index > block.Statements.Count) throw new ArgumentOutOfRangeException(nameof(index)); + block.Insert(index, statement); + Adopt(statement); + var problem = PlacementProblem(block, statement); + if (problem is not null) { + block.Remove(statement); + throw new InvalidOperationException(problem); + } + RefreshMutability(); + return statement; + } + + internal string? PlacementProblem(Block block, Statement statement) + => ReturnProblem(block) + ?? SiteProblem(WithDescendants(statement)) + ?? SiteProblem(SitesAfter(statement), DeclaredNames(statement)); + + public void Remove(Statement statement) { + var parent = statement.Parent ?? throw new InvalidOperationException("the statement is not in a block"); + var inside = WithDescendants(statement).ToHashSet(); + // a method declaration cannot lose its table + foreach (var binding in DeclaredBy(statement)) { + var outside = binding.Output.Consumers.Where(c => !(c.Owner.OwnerStatement is { } s && inside.Contains(s))).ToList(); + var declared = outside.Select(c => c.Owner).OfType().FirstOrDefault(f => f.Parent is not null); + if (declared is not null) throw new InvalidOperationException($"{declared.Name} is declared on {binding.Name}; remove or move it first"); + // removing a value must not leave a call on nil + if (outside.Any(IsPrefixPosition)) throw new InvalidOperationException($"{binding.Name} is still used as a function or a table; remove those uses first"); + } + foreach (var binding in DeclaredBy(statement).Where(b => b.IsMutable)) { + if (StillUsedOutside(binding, statement)) + throw new InvalidOperationException($"{binding.Name} is assigned or read elsewhere; remove those first"); + } + parent.Remove(statement); + RemoveTree(statement); + foreach (var cast in Nodes.OfType().Where(c => c.Target is { } target && !m_nodes.Contains(target.Declarer)).ToList()) cast.Target = null; + RefreshMutability(); + } + + internal LocalDecl CaptureCallResults(CallStatement statement, IReadOnlyList names) { + var block = statement.Parent ?? throw new InvalidOperationException("wire the call into the flow first"); + var call = statement.CallNode ?? throw new InvalidOperationException("the statement has no call"); + var index = block.IndexOf(statement); + var capture = new LocalDecl(this); + foreach (var name in names) capture.AddName(name); + capture.AddValue().Connect(call.Result); + capture.LeadingLines.AddRange(statement.LeadingLines); + statement.Call.Clear(); + block.Remove(statement); + Unregister(statement); + Insert(block, index, capture); + return capture; + } + + public void Move(Statement statement, Block to, int index) { + var from = statement.Parent ?? throw new InvalidOperationException("the statement is not in a block"); + if (IsInside(to, statement)) throw new InvalidOperationException("a statement cannot be moved into itself"); + var fromIndex = from.IndexOf(statement); + from.Remove(statement); + if (from == to && index > fromIndex) index--; + if (index < 0 || index > to.Statements.Count) { + from.Insert(fromIndex, statement); + throw new ArgumentOutOfRangeException(nameof(index)); + } + to.Insert(index, statement); + var names = DeclaredNames(statement); + var problem = ReturnProblem(to) + ?? SiteProblem(WithDescendants(statement)) + ?? SiteProblem(SitesAfter(statement), names) + ?? SiteProblem(SitesFrom(from, fromIndex), names); + if (problem is not null) { + to.Remove(statement); + from.Insert(fromIndex, statement); + throw new InvalidOperationException(problem); + } + } + + private static bool IsPrefixPosition(InputPin pin) => pin.Owner switch { + CallNode call => pin == call.Target, + MemberGet member => pin == member.Object, + IndexGet index => pin == index.Object, + AssignStatement assign => assign.Targets.Any(t => t.Object == pin || t.Key == pin), + _ => false, + }; + + private static Statement? OwnerStatementOf(Block block) => block.Owner switch { + Statement s => s, + FunctionEntry { Owner: FunctionDecl declaration } => declaration, + FunctionEntry { Owner: FunctionNode node } => node.OwnerStatement, + _ => null, + }; + + private static bool IsInside(Block block, Statement statement) { + var current = block; + while (current is not null) { + var owner = OwnerStatementOf(current); + if (owner == statement) return true; + current = owner?.Parent; + } + return false; + } + + internal static List Flatten(IEnumerable statements) { + var result = new List(); + foreach (var statement in statements) { + if (statement is SequenceStatement sequence) result.AddRange(sequence.Branches.SelectMany(b => Flatten(b.Statements))); + else result.Add(statement); + } + return result; + } + + private static bool IsPlacement(Statement s) => s is not (CommentStatement or CastStatement); + + private static string? ReturnProblem(Block block) { + var effective = block; + while (effective.Owner is SequenceStatement { Parent: { } parent }) effective = parent; + var flat = Flatten(effective.Statements); + for (var i = 0; i < flat.Count; i++) + if (flat[i] is ReturnStatement && flat.Skip(i + 1).Any(IsPlacement)) return "a return must be the last statement of its block"; + return null; + } + + private void Adopt(Statement statement) { + void Walk(InputPin pin, Statement owner) { + if (pin.Source is not { Binding: null } source || source.Owner is not ExprNode node) return; + node.OwnerStatement = owner; + foreach (var input in node.Inputs) Walk(input, owner); + if (node is FunctionNode function) foreach (var inner in function.Entry.Body.Statements) Adopt(inner); + } + foreach (var pin in statement.Inputs) Walk(pin, statement); + foreach (var block in statement.ChildBlocks) foreach (var inner in block.Statements) Adopt(inner); + } + + private static void AdoptUnowned(GraphNode node, Statement site) { + if (node is not ExprNode) return; + node.OwnerStatement ??= site; + foreach (var input in node.Inputs) + if (input.Source is { Binding: null } source) AdoptUnowned(source.Owner, site); + } + + private static IEnumerable DeclaredBy(Statement s) => s switch { + LocalDecl local => local.Names, + FunctionDecl { FunctionBinding: { } binding } => [binding], + // sequence branches share a scope in the saved script + SequenceStatement sequence => sequence.Branches.SelectMany(b => b.Statements).SelectMany(DeclaredBy), + _ => [], + }; + + private static ISet DeclaredNames(Statement s) => DeclaredBy(s).Select(b => b.Name).ToHashSet(); + + private bool StillUsedOutside(Binding binding, Statement removed) { + var inside = WithDescendants(removed).ToHashSet(); + return Nodes.OfType().Any(g => g.Binding == binding && g.Result.Consumers.Any(c => c.Owner.OwnerStatement is { } s && !inside.Contains(s))) + || Nodes.OfType().Any(a => !inside.Contains(a) && a.Parent is not null && a.Targets.Any(t => t.Binding == binding)) + || Nodes.OfType().Any(f => !inside.Contains(f) && f.Parent is not null && f.AssignedBinding == binding); + } + + private void RemoveTree(Statement statement) { + foreach (var block in statement.ChildBlocks.ToList()) + foreach (var child in block.Statements.ToList()) RemoveTree(child); + foreach (var pin in statement.Inputs.ToList()) { + var source = pin.Source; + pin.Clear(); + Prune(source); + } + foreach (var output in statement.Outputs) foreach (var consumer in output.Consumers.ToList()) consumer.Clear(); + if (statement is FunctionDecl function) Unregister(function.Entry); + Unregister(statement); + } + + private void Prune(OutputPin? output) { + if (output is null || output.Binding is not null || output.Owner is not ExprNode node) return; + if (node.Outputs.Any(o => o.Consumers.Count > 0)) return; + foreach (var pin in node.Inputs.ToList()) { + var source = pin.Source; + pin.Clear(); + Prune(source); + } + if (node is FunctionNode function) { + foreach (var statement in function.Entry.Body.Statements.ToList()) RemoveTree(statement); + Unregister(function.Entry); + } + Unregister(node); + } + + private static IEnumerable VisibleAt(Statement site) + => site.Parent is { } block ? VisibleFromBlock(block, block.IndexOf(site)) : []; + + internal static IEnumerable VisibleFromBlock(Block block, int index) { + var current = block; + var position = index; + while (current is not null) { + for (var i = position - 1; i >= 0; i--) + foreach (var binding in DeclaredBy(current.Statements[i]).Reverse()) yield return binding; + + Statement? next; + switch (current.Owner) { + case FunctionEntry entry: + foreach (var parameter in Enumerable.Reverse(entry.Params)) yield return parameter; + if (entry.Self is { } self) yield return self; + if (entry.Owner is FunctionDecl { FunctionBinding: { } own }) yield return own; + next = OwnerStatementOf(current); + break; + case NumericFor numeric: + yield return numeric.Var; + next = numeric; + break; + case GenericFor generic: + foreach (var variable in Enumerable.Reverse(generic.Vars)) yield return variable; + next = generic; + break; + case SequenceStatement sequence: + for (var b = sequence.Branches.IndexOf(current) - 1; b >= 0; b--) + foreach (var binding in Enumerable.Reverse(sequence.Branches[b].Statements.SelectMany(DeclaredBy))) yield return binding; + next = sequence; + break; + case Statement owner: + next = owner; + break; + default: + yield break; + } + if (next?.Parent is not { } parent) yield break; + current = parent; + position = parent.IndexOf(next); + } + } + + private static IEnumerable VisibleTo(InputPin pin, Statement site) { + var visible = VisibleAt(site); + if (site is RepeatStatement repeat && pin == repeat.Condition) + visible = Enumerable.Reverse(repeat.Body.Statements.SelectMany(DeclaredBy)).Concat(visible); + return visible; + } + + private static Binding? BindingRead(InputPin pin) => pin.Source?.Binding ?? (pin.Source?.Owner as VariableGet)?.Binding; + + private static IEnumerable WithDescendants(Statement statement) { + yield return statement; + foreach (var block in statement.ChildBlocks) + foreach (var child in block.Statements) + foreach (var inner in WithDescendants(child)) yield return inner; + foreach (var pin in statement.Inputs) + foreach (var closure in ClosuresIn(pin)) + foreach (var child in closure.Entry.Body.Statements) + foreach (var inner in WithDescendants(child)) yield return inner; + } + + internal static IEnumerable ClosuresIn(InputPin pin) { + if (pin.Source is not { Binding: null } source || source.Owner is not ExprNode node) yield break; + if (node is FunctionNode function) { + yield return function; + yield break; + } + foreach (var input in node.Inputs) + foreach (var closure in ClosuresIn(input)) yield return closure; + } + + private static IEnumerable PinsOf(Statement site) { + IEnumerable Tree(InputPin pin) { + yield return pin; + if (pin.Source is { Binding: null } source && source.Owner is ExprNode node && node is not FunctionNode) + foreach (var input in node.Inputs) + foreach (var inner in Tree(input)) yield return inner; + } + return site.Inputs.SelectMany(Tree); + } + + private static IEnumerable SitesFrom(Block block, int index) { + var current = block; + var position = index; + while (current is not null) { + for (var i = position; i < current.Statements.Count; i++) + foreach (var inner in WithDescendants(current.Statements[i])) yield return inner; + switch (current.Owner) { + case SequenceStatement sequence when sequence.Parent is { } parent: + for (var b = sequence.Branches.IndexOf(current) + 1; b < sequence.Branches.Count; b++) + foreach (var statement in sequence.Branches[b].Statements) + foreach (var inner in WithDescendants(statement)) yield return inner; + current = parent; + position = parent.IndexOf(sequence) + 1; + continue; + case RepeatStatement repeat: + yield return repeat; + break; + } + yield break; + } + } + + private static IEnumerable SitesAfter(Statement statement) + => statement.Parent is { } block ? SitesFrom(block, block.IndexOf(statement) + 1) : []; + + private static string? SiteProblem(IEnumerable sites, ISet? onlyNames = null) { + foreach (var site in sites.Distinct()) { + if (site.Parent is null) continue; + List? visible = null; + List Visible() => visible ??= VisibleAt(site).ToList(); + + foreach (var pin in PinsOf(site)) { + var binding = BindingRead(pin); + var name = binding?.Name ?? (pin.Source is { Binding: null, Owner: GlobalGet global } ? global.Name : null); + if (name is null || (onlyNames is not null && !onlyNames.Contains(name))) continue; + // repeat conditions can read locals from the loop body + var scope = site is RepeatStatement ? VisibleTo(((RepeatStatement)site).Condition, site).ToList() : Visible(); + if (binding is not null) { + if (NameResolution(binding, scope) is { } problem) return problem; + } else if (scope.Any(v => v.Name == name)) { + return $"{name} would stop referring to the global of that name"; + } + } + + var statementProblem = StatementProblem(site, onlyNames, Visible); + if (statementProblem is not null) return statementProblem; + } + return null; + } + + private static string? NameResolution(Binding binding, ICollection scope) { + if (!scope.Contains(binding)) return $"{binding.Name} is not in scope there"; + return scope.First(v => v.Name == binding.Name) != binding ? $"{binding.Name} would refer to a different name there" : null; + } + + private static string? StatementProblem(Statement site, ISet? onlyNames, Func> visible) { + bool Wanted(string? name) => name is not null && (onlyNames is null || onlyNames.Contains(name)); + + switch (site) { + case AssignStatement assign: + foreach (var target in assign.Targets) { + if (target.Binding is { } binding && Wanted(binding.Name)) { + if (NameResolution(binding, visible()) is { } problem) return problem; + if (binding.Attribute is not null) return $"{binding.Name} is declared <{binding.Attribute}> and cannot be assigned"; + } else if (target.Kind == TargetKind.Global && Wanted(target.Name) && visible().Any(v => v.Name == target.Name)) { + return $"{target.Name} would stop referring to the global of that name"; + } + } + break; + case FunctionDecl { IsLocal: false } function when function.Path.Count == 1: + if (function.AssignedBinding is { } assigned) { + if (Wanted(assigned.Name) && NameResolution(assigned, visible()) is { } problem) return problem; + } else if (Wanted(function.Path[0]) && visible().Any(v => v.Name == function.Path[0])) { + return $"{function.Path[0]} would stop referring to the global function of that name"; + } + break; + case CastStatement { Target: { } target } when Wanted(target.Name): + if (NameResolution(target, visible()) is { } castProblem) return castProblem; + break; + } + if (onlyNames is not null) return null; + + switch (site) { + case BreakStatement when !InLoop(site): + return "break needs a loop around it"; + case GotoStatement @goto when !LabelInReach(site, @goto.Label): + return $"there is no label {@goto.Label} in reach of this goto"; + } + foreach (var pin in PinsOf(site)) { + if (pin.Source is { Binding: null, Owner: VarargNode } && !VarargAllowed(site)) return "... can only be used inside a function that takes ..."; + } + return null; + } + + private static IEnumerable<(Block Block, GraphNode? Owner)> EnclosingBlocks(Statement site) { + var block = site.Parent; + while (block is not null) { + yield return (block, block.Owner); + if (block.Owner is FunctionEntry) yield break; + block = OwnerStatementOf(block)?.Parent; + } + } + + private static bool InLoop(Statement site) + => EnclosingBlocks(site).Any(e => e.Owner is WhileStatement or RepeatStatement or NumericFor or GenericFor); + + private static bool LabelInReach(Statement site, string label) + => EnclosingBlocks(site).Any(e => Flatten(e.Block.Statements).OfType().Any(l => l.Name == label)); + + private static bool VarargAllowed(Statement site) { + var function = EnclosingBlocks(site).Select(e => e.Owner).OfType().FirstOrDefault(); + return function is null || function.IsVararg; + } + + private static IEnumerable RegionOf(Binding binding) => binding.Declarer switch { + LocalDecl declaration => WithDescendants(declaration).Concat(SitesAfter(declaration)), + FunctionDecl declaration => WithDescendants(declaration).Concat(SitesAfter(declaration)), + FunctionEntry entry => entry.Body.Statements.SelectMany(WithDescendants), + Statement loop => WithDescendants(loop), + _ => [], + }; + + public void Rename(Binding binding, string newName) { + if (!LuaWriter.IsIdentifier(newName)) throw new ArgumentException($"\"{newName}\" is not a valid name", nameof(newName)); + if (binding.Kind == BindingKind.Self) throw new InvalidOperationException("self comes from the colon in the function's name and cannot be renamed"); + var old = binding.Name; + if (old == newName) return; + + var casts = Nodes.OfType().Where(c => c.Target == binding).ToList(); + var annotated = binding is { Kind: BindingKind.Param, Declarer: FunctionEntry { Owner: FunctionDecl declaration } } ? declaration : null; + var annotations = annotated?.LeadingLines.ToList(); + + binding.Name = newName; + foreach (var cast in casts) cast.Variable = newName; + if (annotated is not null) { + for (var i = 0; i < annotated.LeadingLines.Count; i++) { + var line = annotated.LeadingLines[i]; + foreach (var suffix in new[] { " ", "? " }) { + var prefix = $"---@param {old}{suffix}"; + if (line.StartsWith(prefix, StringComparison.Ordinal)) annotated.LeadingLines[i] = $"---@param {newName}{suffix}" + line[prefix.Length..]; + } + } + } + + var problem = SiteProblem(RegionOf(binding), new HashSet { newName }); + if (problem is null) return; + binding.Name = old; + foreach (var cast in casts) cast.Variable = old; + if (annotated is not null && annotations is not null) { + annotated.LeadingLines.Clear(); + annotated.LeadingLines.AddRange(annotations); + } + throw new InvalidOperationException(problem); + } + + private void RefreshMutability() { + var counts = new Dictionary(); + foreach (var statement in Nodes.OfType().Where(s => s.Parent is not null)) { + switch (statement) { + case AssignStatement assign: + foreach (var target in assign.Targets.Where(t => t.Binding is not null)) counts[target.Binding!] = counts.GetValueOrDefault(target.Binding!) + 1; + break; + case FunctionDecl { AssignedBinding: { } assigned }: + counts[assigned] = counts.GetValueOrDefault(assigned) + 1; + break; + } + } + + var bindings = Nodes.SelectMany(n => n switch { + LocalDecl l => l.Names, + FunctionDecl { FunctionBinding: { } f } => [f], + NumericFor numeric => [numeric.Var], + GenericFor generic => generic.Vars, + FunctionEntry entry => entry.Params.Concat(entry.Self is null ? [] : [entry.Self]), + _ => Enumerable.Empty(), + }).ToList(); + + foreach (var binding in bindings) { + binding.Assignments = counts.GetValueOrDefault(binding); + var mutable = binding.Assignments > 0; + if (mutable == binding.IsMutable) continue; + binding.IsMutable = mutable; + if (mutable) { + foreach (var consumer in binding.Output.Consumers.ToList()) { + var get = new VariableGet(this, binding) { OwnerStatement = consumer.Owner.OwnerStatement }; + consumer.Connect(get.Result); + } + } else { + foreach (var get in Nodes.OfType().Where(g => g.Binding == binding).ToList()) { + foreach (var consumer in get.Result.Consumers.ToList()) consumer.Connect(binding.Output); + Unregister(get); + } + } + } + } + + private static InputPin Unwrapped(InputPin pin) => pin.Source is { Binding: null, Owner: ParenNode paren } ? paren.Inner : pin; + + private static bool SamePureValue(InputPin x, InputPin y) { + x = Unwrapped(x); + y = Unwrapped(y); + if (x.Constant is not null || y.Constant is not null) return x.Constant is not null && x.Constant == y.Constant; + if (x.Source is not { } a || y.Source is not { } b) return false; + if (a == b) return true; + if (BindingRead(x) is { } bx && BindingRead(y) is { } by) return bx == by; + return (a.Owner, b.Owner) switch { + (GlobalGet gx, GlobalGet gy) => gx.Name == gy.Name, + (MemberGet mx, MemberGet my) => mx.Name == my.Name && SamePureValue(mx.Object, my.Object), + (IndexGet ix, IndexGet iy) => SamePureValue(ix.Object, iy.Object) && SamePureValue(ix.Key, iy.Key), + _ => false, + }; + } + + public void SetCallStyle(CallNode call, CallStyle style) { + if (call.Style == style) return; + if (style == CallStyle.Function) { + ToDotForm(call); + return; + } + + var member = call.Target.Source is { Binding: null, Owner: MemberGet m } ? m : null; + if (member is null || call.Args.Count == 0) throw new InvalidOperationException("only a call written as object.name(object, ...) can use the colon form"); + var self = call.Args[0]; + if (!SamePureValue(member.Object, self)) throw new InvalidOperationException("the first argument is not the object the method is taken from, so the colon form would change the call"); + if (!LuaWriter.IsIdentifier(member.Name)) throw new InvalidOperationException($"\"{member.Name}\" cannot be written after a colon"); + + var objectSource = member.Object.Source; + var objectConstant = member.Object.Constant; + var selfSource = self.Source; + call.RemoveArgAt(0); + call.Target.Clear(); + if (objectSource is not null) call.Target.Connect(objectSource); + else if (objectConstant is not null) call.Target.SetConstant(objectConstant); + Prune(member.Result); + Prune(selfSource); + call.Style = CallStyle.Method; + call.Method = member.Name; + call.Target.Name = "object"; + } + + private void ToDotForm(CallNode call) { + var name = call.Method ?? throw new InvalidOperationException("a method call needs a name"); + var member = new MemberGet(this, name) { OwnerStatement = call.OwnerStatement }; + var objectSource = call.Target.Source; + var objectConstant = call.Target.Constant; + if (objectSource is not null) member.Object.Connect(objectSource); + else if (objectConstant is not null) member.Object.SetConstant(objectConstant); + + var self = call.InsertArg(0, "self"); + if (objectSource is { Binding: null, Index: 0, Owner: CallNode or VarargNode }) { + // parentheses stop the receiver from expanding into multiple arguments + var paren = new ParenNode(this) { OwnerStatement = call.OwnerStatement }; + paren.Inner.Connect(objectSource); + self.Connect(paren.Result); + } else if (objectSource is not null) { + self.Connect(objectSource); + } else if (objectConstant is not null) { + self.SetConstant(objectConstant); + } + + call.Target.Clear(); + call.Target.Connect(member.Result); + call.Style = CallStyle.Function; + call.Method = null; + call.Target.Name = "function"; + } + + private static bool IsDocLine(string line) => line.StartsWith("---", StringComparison.Ordinal); + + public void SetStatementComment(Statement statement, string? text) { + var annotations = statement.LeadingLines.Where(IsDocLine).ToList(); + // comment text must never become executable code + var comment = string.IsNullOrEmpty(text) + ? [] + : Regex.Split(text, "\r\n|\r|\n").Select(l => l.Length == 0 ? "--" : "-- " + l).ToList(); + statement.LeadingLines.Clear(); + statement.LeadingLines.AddRange(comment); + statement.LeadingLines.AddRange(annotations); + } + + public void SetAnnotationLines(Statement statement, IReadOnlyList lines) { + if (lines.Any(l => !IsDocLine(l) || l.Contains('\n') || l.Contains('\r'))) throw new ArgumentException("annotation lines are single lines starting with ---", nameof(lines)); + var comment = statement.LeadingLines.Where(l => !IsDocLine(l)).ToList(); + statement.LeadingLines.Clear(); + statement.LeadingLines.AddRange(comment); + statement.LeadingLines.AddRange(lines); + } +} diff --git a/editor/LuaEditor/Graph/GraphSaver.cs b/editor/LuaEditor/Graph/GraphSaver.cs new file mode 100644 index 000000000..77698f60a --- /dev/null +++ b/editor/LuaEditor/Graph/GraphSaver.cs @@ -0,0 +1,444 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using editor.LuaEditor.Syntax; +using editor.LuaEditor.Types; +using Loretta.CodeAnalysis.Text; + +namespace editor.LuaEditor.Graph; + +public sealed record SaveResult(string Text, IReadOnlyList Edits, IReadOnlyList Errors); + +internal sealed record PartDef(TextSpan Span, Func Write, Func> Closures); + +internal static class GraphSaver { + + public static void Snapshot(LuaGraph graph) { + var writer = new LuaWriter(graph.Document); + foreach (var function in graph.Nodes.OfType()) function.OriginalParams = writer.ParamsText(function.Entry); + foreach (var block in AllBlocks(graph)) block.Original = block.Statements.ToList(); + + foreach (var statement in graph.AllStatements()) { + switch (statement) { + case CommentStatement comment: + statement.Baseline = new StatementBaseline("K", [new PartBaseline(comment.LineSpan ?? default, string.Join("\n", comment.Lines))], []); + break; + case CastStatement cast: + statement.Baseline = new StatementBaseline("Q", [new PartBaseline(cast.LineSpan ?? default, CastText(cast))], []); + break; + default: + if (statement.Source is null) break; + statement.Baseline = new StatementBaseline(ShapeOf(statement), + PartsOf(statement, writer).Select(p => new PartBaseline(p.Span, p.Write(true, 0), p.Closures())).ToList(), + statement.LeadingLines.ToList()); + break; + } + } + } + + private static IEnumerable AllBlocks(LuaGraph graph) + => new[] { graph.Module } + .Concat(graph.AllStatements().SelectMany(s => s.ChildBlocks)) + .Concat(graph.Nodes.OfType().Select(f => f.Entry.Body)); + + private static string CastText(CastStatement cast) => $"{cast.Variable} {cast.TypeText}"; + + private static string ShapeOf(Statement statement) => statement switch { + LocalDecl l => $"L{l.Names.Count}:{l.Values.Count}", + AssignStatement a => $"A{string.Join(",", a.Targets.Select(t => (int)t.Kind))}:{a.Values.Count}", + CallStatement => "C", + IfStatement i => $"I{i.Clauses.Count}:{i.Else is not null}", + WhileStatement => "W", + RepeatStatement => "R", + NumericFor n => $"N{!n.Step.IsEmpty}", + GenericFor g => $"G{g.Vars.Count}:{g.Exprs.Count}", + DoStatement => "D", + FunctionDecl f => $"F{f.IsLocal}:{f.Path.Count}:{f.IsMethod}:{f.Entry.Params.Count}:{f.Entry.IsVararg}", + ReturnStatement r => $"T{r.Values.Count}", + BreakStatement => "B", + GotoStatement => "O", + LabelStatement => "Y", + _ => "X", + }; + + private static PartDef Expression(InputPin pin, LuaWriter writer) + => new(pin.Origin?.Span ?? default, (placeholder, level) => writer.ExpressionAt(pin, level, placeholder), () => ClosuresIn(pin)); + + private static PartDef Text(TextSpan span, Func text) => new(span, (_, _) => text(), () => []); + + private static IEnumerable ValueParts(IEnumerable pins, LuaWriter writer) + => pins.Where(p => !p.IsEmpty).Select(p => Expression(p, writer)); + + private static List PartsOf(Statement statement, LuaWriter writer) { + TextSpan Span(string key) => statement.Spans.GetValueOrDefault(key); + var parts = new List(); + switch (statement) { + case LocalDecl local: + parts.Add(Text(Span("names"), () => writer.NamesText(local))); + parts.AddRange(ValueParts(local.Values, writer)); + break; + case AssignStatement assign: + parts.Add(new PartDef(Span("targets"), (placeholder, level) => writer.Targets(assign, level, placeholder), + () => assign.Targets.SelectMany(t => new[] { t.Object, t.Key }).Where(p => p is not null).SelectMany(p => ClosuresIn(p!)).ToList())); + parts.AddRange(ValueParts(assign.Values, writer)); + break; + case CallStatement call: + parts.Add(Expression(call.Call, writer)); + break; + case IfStatement @if: + parts.AddRange(@if.Clauses.Select(c => Expression(c.Condition, writer))); + break; + case WhileStatement @while: + parts.Add(Expression(@while.Condition, writer)); + break; + case RepeatStatement repeat: + parts.Add(Expression(repeat.Condition, writer)); + break; + case NumericFor numeric: + parts.Add(Text(Span("var"), () => numeric.Var.Name)); + parts.Add(Expression(numeric.Start, writer)); + parts.Add(Expression(numeric.Limit, writer)); + if (!numeric.Step.IsEmpty) parts.Add(Expression(numeric.Step, writer)); + break; + case GenericFor generic: + parts.Add(Text(Span("vars"), () => writer.ForVarsText(generic))); + parts.AddRange(ValueParts(generic.Exprs, writer)); + break; + case FunctionDecl function: + parts.Add(Text(Span("name"), () => writer.FunctionNameText(function))); + parts.Add(Text(function.Entry.ParamsSpan ?? default, () => writer.ParamsText(function.Entry))); + break; + case ReturnStatement @return: + parts.AddRange(ValueParts(@return.Values, writer)); + break; + case GotoStatement @goto: + parts.Add(Text(Span("label"), () => @goto.Label)); + break; + case LabelStatement label: + parts.Add(Text(Span("name"), () => label.Name)); + break; + case RawStatement raw: + parts.Add(Text(statement.Source?.Span ?? default, () => raw.Text)); + break; + } + return parts; + } + + private static IReadOnlyList ClosuresIn(InputPin pin) => LuaGraph.ClosuresIn(pin).ToList(); + + public static SaveResult Save(LuaGraph graph) => StackGuard.Run(() => SaveCore(graph)); + + private static SaveResult Failure(LuaGraph graph, IReadOnlyList edits, string message) + => new(graph.Document.Text, edits, [new Diagnostic(DiagnosticSeverity.Error, message, new SourceLocation("", 1))]); + + private static SaveResult SaveCore(LuaGraph graph) { + var doc = graph.Document; + var saver = new Saver(graph); + try { + saver.SaveBlock(graph.Module); + if (saver.Edits.Count == 0) return new SaveResult(doc.Text, saver.Edits, []); + var text = doc.Apply(saver.Edits); + + var check = LuaDocument.Parse(text); + if (check.HasErrors) + return new SaveResult(doc.Text, saver.Edits, check.Errors.Select(e => e with { Message = "the saved text would not parse: " + e.Message }).ToList()); + + // reject saves that change which declaration a name refers to + if (!LuaGraph.TryBuild(check, graph.Universe, out var rebuilt, out var rebuildErrors)) + return Failure(graph, saver.Edits, "the saved text could not be read back: " + string.Join("; ", rebuildErrors.Select(e => e.Message))); + var expected = GraphSignature.Of(graph); + var actual = GraphSignature.Of(rebuilt!); + if (expected != actual) return Failure(graph, saver.Edits, "the saved text would mean something different from the graph: " + FirstDifference(expected, actual)); + return new SaveResult(text, saver.Edits, []); + } catch (Exception e) when (e is ArgumentException or InvalidOperationException or ArgumentOutOfRangeException or NullReferenceException or KeyNotFoundException) { + return Failure(graph, saver.Edits, "could not save: " + e.Message); + } + } + + private static string FirstDifference(string expected, string actual) { + var a = expected.Split('\n'); + var b = actual.Split('\n'); + for (var i = 0; i < Math.Max(a.Length, b.Length); i++) { + var left = i < a.Length ? a[i] : "(end)"; + var right = i < b.Length ? b[i] : "(end)"; + if (left != right) return $"graph \"{Shorten(left)}\" but text \"{Shorten(right)}\""; + } + return "unknown"; + } + + private static string Shorten(string text) => text.Length <= 120 ? text : text[..120] + "..."; + + private sealed class Saver { + private readonly LuaGraph m_graph; + private readonly LuaDocument m_doc; + private readonly LuaWriter m_writer; + private readonly string m_text; + + public Saver(LuaGraph graph) { + m_graph = graph; + m_doc = graph.Document; + m_text = m_doc.Text; + m_writer = new LuaWriter(m_doc) { VerbatimClosure = ClosureText, VerbatimStatement = StatementText }; + } + + public List Edits { get; } = []; + + private string Eol => m_doc.Eol; + + private int LevelOf(string indent) { + var unit = m_doc.IndentUnit; + if (unit == "\t") return indent.Count(c => c == '\t'); + return indent.Length / Math.Max(1, unit.Length); + } + + private bool OnlyWhitespaceBefore(int position) { + for (var i = m_doc.LineStart(position); i < position; i++) + if (m_text[i] is not (' ' or '\t')) return false; + return true; + } + + private int LineStartIfAlone(int position) => OnlyWhitespaceBefore(position) ? m_doc.LineStart(position) : position; + + private int SourceStart(Statement s) => s.Source is not null ? s.Source.Span.Start : (s switch { + CommentStatement c => c.LineSpan!.Value.Start, + CastStatement c => c.LineSpan!.Value.Start, + _ => throw new InvalidOperationException($"{s.GetType().Name} has no place in the text"), + }); + + private int StartOf(Statement s) => LineStartIfAlone(s.LeadingLinesSpan?.Start ?? SourceStart(s)); + + private int EndOfLine(int position) { + var i = position; + while (i < m_text.Length && m_text[i] != '\n') i++; + return i < m_text.Length ? i + 1 : i; + } + + private int EndOf(Statement s) => s.Source is not null ? s.Source.FullSpan.End : EndOfLine(s switch { + CommentStatement c => c.LineSpan!.Value.End, + CastStatement c => c.LineSpan!.Value.End, + _ => throw new InvalidOperationException(), + }); + + private int LevelAt(Statement s) => LevelOf(m_doc.IndentOfLineAt(SourceStart(s))); + + private string? ClosureText(FunctionNode function, int level) { + if (function.SourceSpan is not { } span || function.OriginalParams is null) return null; + if (m_writer.ParamsText(function.Entry) != function.OriginalParams) return null; + if (LevelOf(m_doc.IndentOfLineAt(span.Start)) != level) return null; + return BlockUnchanged(function.Entry.Body) ? m_text.Substring(span.Start, span.Length) : null; + } + + private string? StatementText(Statement statement, int level) { + if (statement.Baseline is null || statement.Source is null || statement is CommentStatement or CastStatement or SequenceStatement) return null; + var start = SourceStart(statement); + if (!OnlyWhitespaceBefore(start) || LevelOf(m_doc.IndentOfLineAt(start)) != level) return null; + if (!StatementUnchanged(statement)) return null; + + var from = StartOf(statement); + while (from > 0) { + var previous = m_doc.LineStart(from - 1); + if (m_text[previous..from].Trim().Length != 0) break; + from = previous; + } + var to = statement.Source.FullSpan.End; + while (to > from && m_text[to - 1] is '\n' or '\r') to--; + return m_text[from..to]; + } + + private bool StatementUnchanged(Statement statement) { + var probe = new Saver(m_graph); + try { + probe.SaveStatement(statement); + } catch (InvalidOperationException) { + return false; + } + return probe.Edits.Count == 0; + } + + private bool BlockUnchanged(Block block) { + var probe = new Saver(m_graph); + try { + probe.SaveBlock(block); + } catch (InvalidOperationException) { + return false; + } + return probe.Edits.Count == 0; + } + + public void SaveBlock(Block block) { + var original = block.Original; + var current = LuaGraph.Flatten(block.Statements); + var originalIndex = new Dictionary(); + for (var i = 0; i < original.Count; i++) originalIndex[original[i]] = i; + + var kept = current.Where(originalIndex.ContainsKey).ToList(); + var stable = LongestIncreasing(kept.Select(s => originalIndex[s]).ToList()).Select(i => kept[i]).ToHashSet(); + + if (original.Count == 0) { + if (current.Count > 0) FillEmptyBlock(block); + return; + } + + // inserts must precede deletions at the same offset + Statement? anchor = null; + var indent = BlockIndent(block); + foreach (var statement in current) { + if (stable.Contains(statement)) { + anchor = statement; + continue; + } + Edits.Add(InsertAfter(block, anchor, statement, indent)); + } + + for (var i = 0; i < current.Count; i++) { + var statement = current[i]; + if (!stable.Contains(statement)) continue; + var originalPrevious = originalIndex[statement] > 0 ? original[originalIndex[statement] - 1] : null; + var previous = i > 0 ? current[i - 1] : null; + + // a blank line keeps this comment separate from the next statement + if (previous is CommentStatement && stable.Contains(previous) && previous != originalPrevious) Edits.Add(TextEdit.Insert(StartOf(statement), Eol)); + + SaveStatement(statement); + + // without a separator this becomes a call on the previous expression + if (previous is not null && previous != originalPrevious && m_text[SourceStart(statement)] == '(') + Edits.Add(TextEdit.Insert(SourceStart(statement), ";")); + } + + foreach (var statement in original.Where(s => !stable.Contains(s))) Edits.Add(new TextEdit(StartOf(statement), EndOf(statement) - StartOf(statement), "")); + } + + private string BlockIndent(Block block) { + foreach (var statement in block.Original) { + var start = SourceStart(statement); + if (OnlyWhitespaceBefore(start)) return m_doc.IndentOfLineAt(start); + } + if (block.Owner is null) return ""; + return m_doc.IndentOfLineAt(Math.Max(0, block.OpenEnd - 1)) + m_doc.IndentUnit; + } + + private string Written(Statement statement, string indent) => m_writer.StatementWithLeading(statement, LevelOf(indent)); + + private TextEdit InsertAfter(Block block, Statement? anchor, Statement statement, string indent) { + var text = Written(statement, indent); + if (text.Length == 0) return TextEdit.Insert(0, ""); + // a blank line keeps this comment separate from the next statement + var gap = statement is CommentStatement ? Eol : ""; + + if (anchor is not null) { + var position = EndOf(anchor); + // a blank line keeps this comment separate from the next statement + var lead = anchor is CommentStatement ? Eol : ""; + if (position == 0 || m_text[position - 1] == '\n') return TextEdit.Insert(position, lead + text + Eol + gap); + var followedByLine = position >= m_text.Length || m_text[position] is '\n' or '\r'; + return TextEdit.Insert(position, Eol + lead + text + (followedByLine ? "" : Eol)); + } + + var first = block.Original[0]; + var at = StartOf(first); + if (at == SourceStart(first) && !OnlyWhitespaceBefore(at)) return TextEdit.Insert(at, text.TrimStart(' ', '\t') + Eol + indent); + return TextEdit.Insert(at, text + Eol + gap); + } + + private void FillEmptyBlock(Block block) { + var indent = BlockIndent(block); + var body = m_writer.Statements(LuaGraph.Flatten(block.Statements), LevelOf(indent)); + if (body.Length == 0) return; + if (block.Owner is null) { + Edits.Add(new TextEdit(block.OpenEnd, block.CloseStart - block.OpenEnd, body + Eol)); + return; + } + var parentIndent = m_doc.IndentOfLineAt(Math.Max(0, block.OpenEnd - 1)); + Edits.Add(new TextEdit(block.OpenEnd, block.CloseStart - block.OpenEnd, Eol + body + Eol + parentIndent)); + } + + private static List LongestIncreasing(List values) { + var best = new int[values.Count]; + var previous = new int[values.Count]; + var end = -1; + for (var i = 0; i < values.Count; i++) { + best[i] = 1; + previous[i] = -1; + for (var j = 0; j < i; j++) + if (values[j] < values[i] && best[j] + 1 > best[i]) { + best[i] = best[j] + 1; + previous[i] = j; + } + if (end < 0 || best[i] > best[end]) end = i; + } + var result = new List(); + for (var i = end; i >= 0; i = previous[i]) result.Add(i); + result.Reverse(); + return result; + } + + private static bool SameClosures(IReadOnlyList current, IReadOnlyList? baseline) + => baseline is not null && current.Count == baseline.Count && current.Zip(baseline).All(p => ReferenceEquals(p.First, p.Second)); + + public void SaveStatement(Statement statement) { + var baseline = statement.Baseline; + if (baseline is null) throw new InvalidOperationException($"{statement.GetType().Name} was not part of the loaded file"); + + switch (statement) { + case CommentStatement comment: { + if (string.Join("\n", comment.Lines) != baseline.Parts[0].Text) { + var span = comment.LineSpan!.Value; + Edits.Add(new TextEdit(span.Start, span.Length, string.Join(Eol + m_doc.IndentOfLineAt(span.Start), comment.Lines))); + } + return; + } + case CastStatement cast: { + if (CastText(cast) != baseline.Parts[0].Text) { + var span = cast.LineSpan!.Value; + Edits.Add(new TextEdit(span.Start, span.Length, $"---@cast {CastText(cast)}".TrimEnd())); + } + return; + } + } + + SaveLeadingLines(statement, baseline); + var level = LevelAt(statement); + var current = PartsOf(statement, m_writer); + if (ShapeOf(statement) != baseline.Shape || current.Count != baseline.Parts.Count) { + var source = statement.Source!; + Edits.Add(new TextEdit(source.Span.Start, source.Span.Length, m_writer.Statement(statement, level))); + return; + } + + for (var i = 0; i < current.Count; i++) { + var closures = current[i].Closures(); + if (current[i].Write(true, 0) == baseline.Parts[i].Text && SameClosures(closures, baseline.Parts[i].Closures)) { + foreach (var closure in closures) SaveBlock(closure.Entry.Body); + continue; + } + var span = baseline.Parts[i].Span; + var text = current[i].Write(false, level); + // without a separator this becomes a call on the previous expression + if (i == 0 && statement is CallStatement or AssignStatement && text.StartsWith('(') && !baseline.Parts[0].Text.StartsWith('(')) text = ";" + text; + Edits.Add(new TextEdit(span.Start, span.Length, text)); + } + foreach (var child in statement.ChildBlocks) SaveBlock(child); + } + + private void SaveLeadingLines(Statement statement, StatementBaseline baseline) { + if (statement.LeadingLines.SequenceEqual(baseline.LeadingLines)) return; + var start = SourceStart(statement); + var indent = m_doc.IndentOfLineAt(start); + if (statement.LeadingLinesSpan is { } span) { + if (statement.LeadingLines.Count > 0) { + Edits.Add(new TextEdit(span.Start, span.Length, string.Join(Eol + indent, statement.LeadingLines))); + } else { + var from = LineStartIfAlone(span.Start); + var to = LineStartIfAlone(start); + if (to > from) Edits.Add(new TextEdit(from, to - from, "")); + } + } else if (statement.LeadingLines.Count > 0) { + if (!OnlyWhitespaceBefore(start)) + throw new InvalidOperationException("a comment cannot go above a statement that shares its line with other code"); + var position = m_doc.LineStart(start); + Edits.Add(TextEdit.Insert(position, string.Concat(statement.LeadingLines.Select(l => indent + l + Eol)))); + } + } + } +} diff --git a/editor/LuaEditor/Graph/GraphSignature.cs b/editor/LuaEditor/Graph/GraphSignature.cs new file mode 100644 index 000000000..4491080d2 --- /dev/null +++ b/editor/LuaEditor/Graph/GraphSignature.cs @@ -0,0 +1,204 @@ +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace editor.LuaEditor.Graph; + +internal static class GraphSignature { + public static string Of(LuaGraph graph) { + var writer = new Writer(); + writer.Block(graph.Module); + return writer.ToString(); + } + + // external bindings need the same identity on both sides + public static bool SameExpression(InputPin first, InputPin second) { + var writer = new Writer(identifyBindings: true); + return writer.Expression(first) == writer.Expression(second); + } + + private sealed class Writer(bool identifyBindings = false) { + private readonly StringBuilder m_sb = new(); + private readonly Dictionary m_ids = []; + + public override string ToString() => m_sb.ToString(); + + private void Line(string text) => m_sb.Append(text).Append('\n'); + + private void Declare(Binding binding) => m_ids[binding] = m_ids.Count + 1; + + private string Name(Binding binding) { + if (m_ids.TryGetValue(binding, out var id)) return "$" + id; + if (!identifyBindings) return "?" + binding.Name; + Declare(binding); + return "$" + m_ids[binding]; + } + + public void Block(Block block) { + Line("{"); + foreach (var statement in block.Statements) Statement(statement); + Line("}"); + } + + private void Statement(Statement statement) { + if (statement is SequenceStatement sequence) { + foreach (var branch in sequence.Branches) foreach (var inner in branch.Statements) Statement(inner); + return; + } + foreach (var line in statement.LeadingLines) Line("lead " + line); + + switch (statement) { + case LocalDecl local: { + var values = string.Join(", ", local.Values.Select(Expression)); + foreach (var name in local.Names) Declare(name); + Line($"local {string.Join(", ", local.Names.Select(n => Name(n) + (n.Attribute is null ? "" : "<" + n.Attribute + ">")))} = {values}"); + break; + } + case AssignStatement assign: { + var targets = string.Join(", ", assign.Targets.Select(t => t.Kind switch { + TargetKind.Binding => Name(t.Binding!), + TargetKind.Global => "@" + t.Name, + TargetKind.Member => Expression(t.Object!) + "." + t.Name, + _ => Expression(t.Object!) + "[" + Expression(t.Key!) + "]", + })); + Line($"assign {targets} = {string.Join(", ", assign.Values.Select(Expression))}"); + break; + } + case CallStatement call: + Line("call " + Expression(call.Call)); + break; + case IfStatement @if: + for (var i = 0; i < @if.Clauses.Count; i++) { + Line((i == 0 ? "if " : "elseif ") + Expression(@if.Clauses[i].Condition)); + Block(@if.Clauses[i].Body); + } + if (@if.Else is not null) { + Line("else"); + Block(@if.Else); + } + break; + case WhileStatement @while: + Line("while " + Expression(@while.Condition)); + Block(@while.Body); + break; + case RepeatStatement repeat: + Line("repeat"); + Line("{"); + foreach (var inner in repeat.Body.Statements) Statement(inner); + Line("until " + Expression(repeat.Condition)); + Line("}"); + break; + case NumericFor numeric: + Line($"for {Expression(numeric.Start)}, {Expression(numeric.Limit)}, {(numeric.Step.IsEmpty ? "" : Expression(numeric.Step))}"); + Declare(numeric.Var); + Line("var " + Name(numeric.Var)); + Block(numeric.Body); + break; + case GenericFor generic: + Line("forin " + string.Join(", ", generic.Exprs.Select(Expression))); + foreach (var variable in generic.Vars) Declare(variable); + Line("vars " + string.Join(", ", generic.Vars.Select(Name))); + Block(generic.Body); + break; + case DoStatement @do: + Line("do"); + Block(@do.Body); + break; + case FunctionDecl function: + FunctionDeclaration(function); + break; + case ReturnStatement @return: + Line("return " + string.Join(", ", @return.Values.Select(Expression))); + break; + case BreakStatement: + Line("break"); + break; + case GotoStatement @goto: + Line("goto " + @goto.Label); + break; + case LabelStatement label: + Line("label " + label.Name); + break; + case CastStatement cast: + Line($"cast {(cast.Target is null ? "@" + cast.Variable : Name(cast.Target))} {cast.TypeText}"); + break; + case CommentStatement comment: + Line("comment " + string.Join("|", comment.Lines)); + break; + case RawStatement raw: + Line("raw " + raw.Text); + break; + } + } + + private void FunctionDeclaration(FunctionDecl function) { + var target = function.Path.Count > 1 + ? Expression(function.Root) + "." + string.Join(".", function.Path.Skip(1)) + : function.IsLocal ? "local" : (function.AssignedBinding is { } assigned ? Name(assigned) : "@" + function.Path[0]); + if (function.FunctionBinding is { } own) Declare(own); + Line($"function {target} method={function.IsMethod}"); + Entry(function.Entry); + } + + private void Entry(FunctionEntry entry) { + if (entry.Self is { } self) Declare(self); + foreach (var parameter in entry.Params) Declare(parameter); + Line($"params {entry.Self is not null} {entry.Params.Count} vararg={entry.IsVararg}"); + Block(entry.Body); + } + + public string Expression(InputPin pin) { + if (pin.Constant is { } constant) return constant.Raw; + if (pin.Source is not { } source) return "nil"; + if (source.Binding is { } binding) return Name(binding); + var text = Node(source.Owner); + return source.Owner is CallNode && source.Index > 0 ? $"@select({source.Index + 1}, {text})" : text; + } + + private string Node(GraphNode node) { + switch (node) { + case GlobalGet global: + return "@" + global.Name; + case VariableGet get: + return Name(get.Binding); + case VarargNode: + return "..."; + case RawExpression raw: + return "raw(" + raw.Text + ")"; + case ParenNode paren: + // only calls and varargs change arity when parenthesized + return paren.Inner.Source is { Binding: null, Index: 0, Owner: CallNode or VarargNode } + ? "paren(" + Expression(paren.Inner) + ")" + : Expression(paren.Inner); + case MemberGet member: + return Expression(member.Object) + "." + member.Name; + case IndexGet index: + return Expression(index.Object) + "[" + Expression(index.Key) + "]"; + case CallNode call: + return call.Style == CallStyle.Method + ? $"{Expression(call.Target)}:{call.Method}({string.Join(", ", call.Args.Select(Expression))})" + : $"{Expression(call.Target)}({string.Join(", ", call.Args.Select(Expression))})"; + case BinaryOp binary: + return $"({Expression(binary.Left)} {binary.Op} {Expression(binary.Right)})"; + case UnaryOp unary: + // parsing turns negative constants into unary expressions + if (unary.Op == UnaryKind.Neg && unary.Operand.Constant is { Kind: ConstantKind.Number } number && !number.Raw.StartsWith('-')) return "-" + number.Raw; + return $"({unary.Op} {Expression(unary.Operand)})"; + case TableNode table: + return "{" + string.Join(", ", table.Fields.Select(f => f.Kind switch { + TableFieldKind.Positional => Expression(f.Value), + TableFieldKind.Named => f.Name + "=" + Expression(f.Value), + _ => "[" + Expression(f.Key!) + "]=" + Expression(f.Value), + })) + "}"; + case FunctionNode function: { + var inner = new Writer { }; + foreach (var (b, id) in m_ids) inner.m_ids[b] = id; + inner.Entry(function.Entry); + return "function<" + inner.m_sb.ToString().Replace("\n", ";") + ">"; + } + default: + return node.GetType().Name; + } + } + } +} diff --git a/editor/LuaEditor/Graph/GraphStructure.cs b/editor/LuaEditor/Graph/GraphStructure.cs new file mode 100644 index 000000000..98c95164c --- /dev/null +++ b/editor/LuaEditor/Graph/GraphStructure.cs @@ -0,0 +1,181 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace editor.LuaEditor.Graph; + +public sealed partial class LuaGraph { + + public SequenceStatement GroupAsSequence(Block block, IReadOnlyList startIndices) { + if (startIndices.Count == 0) throw new ArgumentException("a sequence needs at least one branch", nameof(startIndices)); + for (var i = 0; i < startIndices.Count; i++) { + if (startIndices[i] < 0 || startIndices[i] >= block.Statements.Count) throw new ArgumentException($"{startIndices[i]} is not a statement of the block", nameof(startIndices)); + if (i > 0 && startIndices[i] <= startIndices[i - 1]) throw new ArgumentException("the start indices must increase", nameof(startIndices)); + } + + var sequence = new SequenceStatement(this); + var statements = block.Statements.ToList(); + for (var i = 0; i < startIndices.Count; i++) { + var end = i + 1 < startIndices.Count ? startIndices[i + 1] : statements.Count; + var branch = sequence.AddBranch(); + for (var s = startIndices[i]; s < end; s++) { + block.Remove(statements[s]); + branch.Add(statements[s]); + } + } + block.Insert(startIndices[0], sequence); + return sequence; + } + + public void MaterializeSharedValues() { + for (var guard = 0; guard < 10_000; guard++) { + var shared = Nodes.OfType().FirstOrDefault(n => n.OwnerStatement?.Parent is not null && HasEffects(n) && n.Outputs.Sum(o => o.Consumers.Count) >= 2); + if (shared is null) return; + Materialize(shared); + } + } + + private static bool HasEffects(GraphNode node) + => node is CallNode or TableNode or FunctionNode or RawExpression + || node.Inputs.Any(p => p.Source is { Binding: null } source && HasEffects(source.Owner)); + + internal bool TryRestoreSharedValue(OutputPin output, InputPin input) { + if (input.Source == output) return false; + if (output.Owner is not ExprNode || input.Source?.Owner is not ExprNode previous || + output.Consumers.FirstOrDefault() is not { } original || + HasEffects(output.Owner) || HasEffects(previous) || !GraphSignature.SameExpression(original, input)) return false; + try { + Connect(output, input); + return true; + } catch (InvalidOperationException) { + return false; + } + } + + private static IEnumerable BlocksAround(Statement statement) { + var block = statement.Parent; + while (block is not null) { + yield return block; + block = OwnerStatementOf(block)?.Parent; + } + } + + private static Statement? AncestorIn(Block block, Statement statement) { + Statement? current = statement; + while (current is not null) { + if (current.Parent == block) return current; + current = current.Parent is { } parent ? OwnerStatementOf(parent) : null; + } + return null; + } + + private static string? EvaluationProblem(InputPin pin) { + var owner = pin.Owner; + switch (owner) { + case WhileStatement @while when pin == @while.Condition: + case RepeatStatement repeat when pin == repeat.Condition: + return "a loop condition is evaluated again every time round, so its value cannot be kept in a local"; + case IfStatement @if when @if.Clauses.FindIndex(c => c.Condition == pin) > 0: + return "an elseif condition is only evaluated when the earlier ones failed, so its value cannot be kept in a local"; + case BinaryOp { Op: BinaryKind.And or BinaryKind.Or } logic when pin == logic.Right: + return "the right side of and/or is only evaluated sometimes, so its value cannot be kept in a local"; + } + if (owner is ExprNode node) + foreach (var consumer in node.Outputs.SelectMany(o => o.Consumers)) + if (EvaluationProblem(consumer) is { } problem) return problem; + return null; + } + + private static bool GivesAllValues(InputPin pin) { + if (pin.Source is not { Binding: null, Index: 0, Owner: CallNode or VarargNode }) return false; + return pin.Owner switch { + CallNode call => call.Args.Count > 0 && call.Args[^1] == pin, + ReturnStatement r => r.Values.Count > 0 && r.Values[^1] == pin, + LocalDecl l => l.Values.Count > 0 && l.Values[^1] == pin, + AssignStatement a => a.Values.Count > 0 && a.Values[^1] == pin, + GenericFor g => g.Exprs.Count > 0 && g.Exprs[^1] == pin, + TableNode t => t.Fields.Count > 0 && t.Fields[^1].Kind == TableFieldKind.Positional && t.Fields[^1].Value == pin, + _ => false, + }; + } + + private HashSet NamesInUse() { + var used = new HashSet(Nodes.OfType().Select(g => g.Name)); + foreach (var node in Nodes) { + switch (node) { + case LocalDecl local: + foreach (var name in local.Names) used.Add(name.Name); + break; + case FunctionEntry entry: + foreach (var parameter in entry.Params) used.Add(parameter.Name); + if (entry.Self is { } self) used.Add(self.Name); + break; + case NumericFor numeric: + used.Add(numeric.Var.Name); + break; + case GenericFor generic: + foreach (var variable in generic.Vars) used.Add(variable.Name); + break; + case FunctionDecl function: + used.Add(function.Path[0]); + if (function.FunctionBinding is { } binding) used.Add(binding.Name); + break; + case AssignStatement assign: + foreach (var target in assign.Targets.Where(t => t.Kind == TargetKind.Global)) used.Add(target.Name!); + break; + } + } + return used; + } + + private void Materialize(ExprNode node) { + var consumers = node.Outputs.SelectMany(o => o.Consumers).ToList(); + foreach (var consumer in consumers) { + if (EvaluationProblem(consumer) is { } problem) throw new InvalidOperationException(problem); + if (GivesAllValues(consumer)) throw new InvalidOperationException("this call's values are all used in one place and the call is also used somewhere else; wrap one use in parentheses to take only the first value"); + } + + var statements = consumers.Select(c => c.Owner.OwnerStatement).Append(node.OwnerStatement).OfType().Distinct().ToList(); + var block = BlocksAround(statements[0]).First(b => statements.All(s => AncestorIn(b, s) is not null)); + var index = statements.Select(s => block.IndexOf(AncestorIn(block, s)!)).Min(); + + var used = NamesInUse(); + string Fresh() { + var number = 1; + while (used.Contains("v" + number)) number++; + used.Add("v" + number); + return "v" + number; + } + + // shared results must not evaluate the call more than once + var last = node.Outputs.Where(o => o.Consumers.Count > 0).Max(o => o.Index); + var declaration = new LocalDecl(this); + for (var i = 0; i <= last; i++) declaration.AddName(node.Outputs[i].Consumers.Count > 0 ? Fresh() : "_"); + var value = declaration.AddValue(); + value.Connect(node.Outputs[0]); + + try { + Insert(block, index, declaration); + } catch (InvalidOperationException) { + value.Clear(); + Discard(declaration); + throw; + } + foreach (var output in node.Outputs) + foreach (var consumer in output.Consumers.Where(c => c != value).ToList()) consumer.Connect(declaration.Outputs[output.Index]); + } + + internal void Discard(Statement statement) { + statement.Parent?.Remove(statement); + RemoveTree(statement); + RefreshMutability(); + } + + internal void ForgetNodesAfter(int count) { + foreach (var node in m_nodes.Skip(count).ToList()) { + foreach (var pin in node.Inputs) pin.Clear(); + foreach (var output in node.Outputs) foreach (var consumer in output.Consumers.ToList()) consumer.Clear(); + m_nodes.Remove(node); + } + } +} diff --git a/editor/LuaEditor/Graph/LuaGraph.cs b/editor/LuaEditor/Graph/LuaGraph.cs new file mode 100644 index 000000000..ffad8f475 --- /dev/null +++ b/editor/LuaEditor/Graph/LuaGraph.cs @@ -0,0 +1,82 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using editor.LuaEditor.Syntax; +using editor.LuaEditor.Types; + +namespace editor.LuaEditor.Graph; + +public sealed partial class LuaGraph { + private readonly List m_nodes = []; + private readonly List m_warnings = []; + private int m_nextId = 1; + + private LuaGraph(LuaDocument document, TypeUniverse universe) { + Document = document; + Universe = universe; + Module = new Block("module"); + } + + public LuaDocument Document { get; private set; } + + public TypeUniverse Universe { get; } + + public Block Module { get; } + + public IReadOnlyList Nodes => m_nodes; + + public IReadOnlyList Warnings => m_warnings; + + public IReadOnlyList Diagnostics { get; private set; } = []; + + public IEnumerable Wires => m_nodes.SelectMany(n => n.Inputs).Where(p => p.Source is not null).Select(p => new Wire(p.Source!, p)); + + public IEnumerable AllStatements() => m_nodes.OfType(); + + internal int Register(GraphNode node) { + m_nodes.Add(node); + return m_nextId++; + } + + internal void Unregister(GraphNode node) => m_nodes.Remove(node); + + public void Analyze() => StackGuard.Run(() => { + Typer.Run(this); + return 0; + }); + + public SaveResult Save() => StackGuard.Run(() => { + try { + MaterializeSharedValues(); + } catch (InvalidOperationException e) { + return new SaveResult(Document.Text, [], [new Diagnostic(DiagnosticSeverity.Error, "a value used in two places cannot be kept in a local there: " + e.Message, new SourceLocation("", 1))]); + } + return GraphSaver.Save(this); + }); + + internal void Warn(string message) => m_warnings.Add(message); + + internal void SetDiagnostics(IReadOnlyList diagnostics) => Diagnostics = diagnostics; + + public static bool TryBuild(LuaDocument document, TypeUniverse universe, out LuaGraph? graph, out IReadOnlyList errors) { + if (document.HasErrors) { + graph = null; + errors = document.Errors; + return false; + } + try { + var built = new LuaGraph(document, universe); + StackGuard.Run(() => { + new GraphBuilder(built, document).Build(); + return 0; + }); + graph = built; + errors = []; + return true; + } catch (Exception e) when (e is InvalidOperationException or ArgumentException or NullReferenceException or InvalidCastException) { + graph = null; + errors = [new Diagnostic(DiagnosticSeverity.Error, $"could not build the graph: {e.Message}", new SourceLocation("", 1))]; + return false; + } + } +} diff --git a/editor/LuaEditor/Graph/LuaWriter.cs b/editor/LuaEditor/Graph/LuaWriter.cs new file mode 100644 index 000000000..7e9d494f0 --- /dev/null +++ b/editor/LuaEditor/Graph/LuaWriter.cs @@ -0,0 +1,319 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using editor.LuaEditor.Syntax; + +namespace editor.LuaEditor.Graph; + +public sealed class LuaWriter { + private static readonly HashSet s_keywords = [ + "and", "break", "do", "else", "elseif", "end", "false", "for", "function", "goto", "if", "in", "local", "nil", "not", "or", + "repeat", "return", "then", "true", "until", "while", + ]; + + private const int UnaryPrecedence = 12; + private const int PowerPrecedence = 14; + private const int AtomPrecedence = 100; + + private readonly string m_eol; + private readonly string m_unit; + + internal Func? VerbatimClosure { get; set; } + + internal Func? VerbatimStatement { get; set; } + + public LuaWriter(LuaDocument style) : this(style.Eol, style.IndentUnit) { } + + public LuaWriter(string eol, string indentUnit) { + m_eol = eol; + m_unit = indentUnit; + } + + public static string File(LuaGraph graph) { + var writer = new LuaWriter(graph.Document); + var text = writer.Block(graph.Module, 0); + return text.Length == 0 ? "" : text + graph.Document.Eol; + } + + public static bool IsIdentifier(string name) { + if (name.Length == 0 || s_keywords.Contains(name) || !(char.IsAsciiLetter(name[0]) || name[0] == '_')) return false; + return name.All(c => char.IsAsciiLetterOrDigit(c) || c == '_'); + } + + private string Ind(int level) => level <= 0 ? "" : string.Concat(Enumerable.Repeat(m_unit, level)); + + public string Block(Block block, int indent) => Statements(block.Statements, indent); + + public string Statements(IReadOnlyList statements, int indent) { + var sb = new StringBuilder(); + for (var i = 0; i < statements.Count; i++) { + var statement = statements[i]; + if (VerbatimStatement?.Invoke(statement, indent) is { } verbatim) { + if (sb.Length > 0) sb.Append(m_eol); + sb.Append(verbatim); + continue; + } + var text = Statement(statement, indent); + if (text.Length == 0 && statement.LeadingLines.Count == 0) continue; + if (sb.Length > 0) sb.Append(m_eol); + foreach (var line in statement.LeadingLines) sb.Append(Ind(indent)).Append(line).Append(m_eol); + if (text.Length > 0) sb.Append(Ind(indent)).Append(text); + else if (statement.LeadingLines.Count > 0) sb.Length -= m_eol.Length; + // a blank line keeps this comment separate from the next statement + if (statement is CommentStatement && i < statements.Count - 1) sb.Append(m_eol); + } + return sb.ToString(); + } + + public string Statement(Statement statement, int indent) { + switch (statement) { + case LocalDecl local: { + var names = string.Join(", ", local.Names.Select(n => n.Attribute is { Length: > 0 } a ? $"{n.Name} <{a}>" : n.Name)); + var text = "local " + names; + if (local.Values.Count > 0) text += " = " + ExpressionList(local.Values, indent, false); + return text; + } + case AssignStatement assign: { + var text = Targets(assign, indent, false) + " = " + ExpressionList(assign.Values, indent, false); + return text.StartsWith('(') ? ";" + text : text; + } + case CallStatement call: { + var text = Expr(call.Call, indent, false, 0); + return text.StartsWith('(') ? ";" + text : text; + } + case IfStatement @if: + return WriteIf(@if, indent); + case WhileStatement @while: + return $"while {Expr(@while.Condition, indent, false, 0)} do" + Body(@while.Body, indent) + "end"; + case RepeatStatement repeat: + return "repeat" + Body(repeat.Body, indent) + $"until {Expr(repeat.Condition, indent, false, 0)}"; + case NumericFor numeric: + return NumericForHeader(numeric, indent, false) + Body(numeric.Body, indent) + "end"; + case GenericFor generic: + return $"{GenericForHeader(generic, indent, false)}" + Body(generic.Body, indent) + "end"; + case DoStatement @do: + return "do" + Body(@do.Body, indent) + "end"; + case FunctionDecl function: + return FunctionHeader(function) + Body(function.Entry.Body, indent) + "end"; + case ReturnStatement @return: + return @return.Values.Count == 0 ? "return" : "return " + ExpressionList(@return.Values, indent, false); + case BreakStatement: + return "break"; + case GotoStatement @goto: + return "goto " + @goto.Label; + case LabelStatement label: + return $"::{label.Name}::"; + case CastStatement cast: + return $"---@cast {cast.Variable} {cast.TypeText}".TrimEnd(); + case CommentStatement comment: + return string.Join(m_eol + Ind(indent), comment.Lines); + case SequenceStatement sequence: { + var parts = sequence.Branches.Select(b => Block(b, indent)).Where(t => t.Length > 0).ToList(); + var joined = string.Join(m_eol, parts); + var prefix = Ind(indent); + return prefix.Length > 0 && joined.StartsWith(prefix, StringComparison.Ordinal) ? joined[prefix.Length..] : joined; + } + case RawStatement raw: + return raw.Text; + default: + throw new InvalidOperationException($"no Lua form for {statement.GetType().Name}"); + } + } + + internal string NamesText(LocalDecl local) + => string.Join(", ", local.Names.Select(n => n.Attribute is { Length: > 0 } a ? $"{n.Name} <{a}>" : n.Name)); + + internal string Targets(AssignStatement assign, int indent, bool placeholder) + => string.Join(", ", assign.Targets.Select(t => t.Kind switch { + TargetKind.Binding => t.Binding!.Name, + TargetKind.Global => t.Name!, + TargetKind.Member => MemberText(Prefix(t.Object!, indent, placeholder), t.Name!), + _ => Prefix(t.Object!, indent, placeholder) + "[" + Expr(t.Key!, indent, placeholder, 0) + "]", + })); + + internal string ForVarsText(GenericFor generic) => string.Join(", ", generic.Vars.Select(v => v.Name)); + + internal string FunctionNameText(FunctionDecl function) { + if (function.IsLocal) return function.FunctionBinding!.Name; + var root = function.Path.Count > 1 ? NameOf(function.Root) : function.Path[0]; + if (function.Path.Count == 1) return function.AssignedBinding?.Name ?? function.Path[0]; + var sb = new StringBuilder(root); + for (var i = 1; i < function.Path.Count; i++) sb.Append(function.IsMethod && i == function.Path.Count - 1 ? ':' : '.').Append(function.Path[i]); + return sb.ToString(); + } + + internal string ParamsText(FunctionEntry entry) { + var names = entry.Params.Select(p => p.Name).ToList(); + if (entry.IsVararg) names.Add("..."); + return "(" + string.Join(", ", names) + ")"; + } + + private string FunctionHeader(FunctionDecl function) + => (function.IsLocal ? "local function " : "function ") + FunctionNameText(function) + ParamsText(function.Entry); + + internal string NumericForHeader(NumericFor numeric, int indent, bool placeholder) { + var text = $"for {numeric.Var.Name} = {Expr(numeric.Start, indent, placeholder, 0)}, {Expr(numeric.Limit, indent, placeholder, 0)}"; + if (!numeric.Step.IsEmpty) text += ", " + Expr(numeric.Step, indent, placeholder, 0); + return text + " do"; + } + + internal string GenericForHeader(GenericFor generic, int indent, bool placeholder) + => $"for {ForVarsText(generic)} in {ExpressionList(generic.Exprs, indent, placeholder)} do"; + + private string WriteIf(IfStatement statement, int indent) { + var sb = new StringBuilder(); + for (var i = 0; i < statement.Clauses.Count; i++) { + var clause = statement.Clauses[i]; + sb.Append(i == 0 ? "if " : Ind(indent) + "elseif ").Append(Expr(clause.Condition, indent, false, 0)).Append(" then"); + sb.Append(Body(clause.Body, indent, endsLine: false)); + } + if (statement.Else is not null) sb.Append(Ind(indent)).Append("else").Append(Body(statement.Else, indent, endsLine: false)); + return sb.Append(Ind(indent)).Append("end").ToString(); + } + + private string Body(Block body, int indent, bool endsLine = true) { + var text = Block(body, indent + 1); + return m_eol + (text.Length > 0 ? text + m_eol : "") + (endsLine ? Ind(indent) : ""); + } + + public string Expression(InputPin pin) => Expr(pin, 0, false, 0); + + public string Expression(InputPin pin, bool bodyPlaceholder) => Expr(pin, 0, bodyPlaceholder, 0); + + internal string ExpressionAt(InputPin pin, int indent, bool placeholder) => Expr(pin, indent, placeholder, 0); + + internal string StatementWithLeading(Statement statement, int indent) { + var text = new StringBuilder(); + foreach (var line in statement.LeadingLines) text.Append(Ind(indent)).Append(line).Append(m_eol); + var body = Statement(statement, indent); + if (body.Length > 0) text.Append(Ind(indent)).Append(body); + else if (text.Length > 0) text.Length -= m_eol.Length; + return text.ToString(); + } + + internal string ExpressionList(IEnumerable pins, int indent, bool placeholder) + => string.Join(", ", pins.Select(p => Expr(p, indent, placeholder, 0))); + + private static int PrecedenceOf(BinaryKind op) => op switch { + BinaryKind.Or => 1, + BinaryKind.And => 2, + BinaryKind.Lt or BinaryKind.Gt or BinaryKind.Le or BinaryKind.Ge or BinaryKind.Ne or BinaryKind.Eq => 3, + BinaryKind.BitOr => 4, + BinaryKind.BitXor => 5, + BinaryKind.BitAnd => 6, + BinaryKind.Shl or BinaryKind.Shr => 7, + BinaryKind.Concat => 9, + BinaryKind.Add or BinaryKind.Sub => 10, + BinaryKind.Mul or BinaryKind.Div or BinaryKind.FloorDiv or BinaryKind.Mod => 11, + _ => PowerPrecedence, + }; + + // preserve the concat grouping produced by the parser + private static bool RightAssociative(BinaryKind op) => op == BinaryKind.Pow; + + private static string OperatorText(BinaryKind op) => op switch { + BinaryKind.Add => "+", BinaryKind.Sub => "-", BinaryKind.Mul => "*", BinaryKind.Div => "/", BinaryKind.FloorDiv => "//", + BinaryKind.Mod => "%", BinaryKind.Pow => "^", BinaryKind.Concat => "..", BinaryKind.Eq => "==", BinaryKind.Ne => "~=", + BinaryKind.Lt => "<", BinaryKind.Le => "<=", BinaryKind.Gt => ">", BinaryKind.Ge => ">=", BinaryKind.And => "and", + BinaryKind.Or => "or", BinaryKind.BitAnd => "&", BinaryKind.BitOr => "|", BinaryKind.BitXor => "~", BinaryKind.Shl => "<<", + _ => ">>", + }; + + // negative constants need grouping before exponentiation + private static int Precedence(InputPin pin) => pin.Constant is { Kind: ConstantKind.Number, Raw: ['-', ..] } ? UnaryPrecedence : pin.Source?.Owner switch { + BinaryOp binary when pin.Source.Binding is null => PrecedenceOf(binary.Op), + UnaryOp when pin.Source.Binding is null => UnaryPrecedence, + _ => AtomPrecedence, + }; + + private string Expr(InputPin pin, int indent, bool placeholder, int minPrecedence) { + var text = Raw(pin, indent, placeholder); + return Precedence(pin) < minPrecedence ? "(" + text + ")" : text; + } + + private string Prefix(InputPin pin, int indent, bool placeholder) { + var text = Raw(pin, indent, placeholder); + return IsPrefixForm(pin) ? text : "(" + text + ")"; + } + + private static bool IsPrefixForm(InputPin pin) { + if (pin.Source is not { } source) return false; + if (source.Binding is not null) return true; + return source.Owner is GlobalGet or VariableGet or MemberGet or IndexGet or ParenNode || (source.Owner is CallNode && source.Index == 0); + } + + private string NameOf(InputPin pin) => pin.Source switch { + { Binding: { } binding } => binding.Name, + { Owner: GlobalGet global } => global.Name, + { Owner: VariableGet get } => get.Binding.Name, + _ => Raw(pin, 0, false), + }; + + private string Raw(InputPin pin, int indent, bool placeholder) { + if (pin.Constant is { } constant) return constant.Raw; + if (pin.Source is not { } source) return "nil"; + if (source.Binding is { } binding) return binding.Name; + + var text = Node(source.Owner, indent, placeholder); + return source.Owner is CallNode && source.Index > 0 ? $"select({source.Index + 1}, {text})" : text; + } + + private string Node(GraphNode node, int indent, bool placeholder) { + switch (node) { + case GlobalGet global: + return global.Name; + case VariableGet get: + return get.Binding.Name; + case VarargNode: + return "..."; + case RawExpression raw: + return raw.Text; + case ParenNode paren: + return paren.Inner.IsEmpty || paren.Inner.Constant is not null || paren.Inner.Source is { Binding: not null } + ? Expr(paren.Inner, indent, placeholder, 0) + : "(" + Expr(paren.Inner, indent, placeholder, 0) + ")"; + case MemberGet member: + return MemberText(Prefix(member.Object, indent, placeholder), member.Name); + case IndexGet index: + return Prefix(index.Object, indent, placeholder) + "[" + Expr(index.Key, indent, placeholder, 0) + "]"; + case CallNode call: { + var args = ExpressionList(call.Args, indent, placeholder); + return call.Style == CallStyle.Method + ? $"{Prefix(call.Target, indent, placeholder)}:{call.Method}({args})" + : $"{Prefix(call.Target, indent, placeholder)}({args})"; + } + case BinaryOp binary: { + var p = PrecedenceOf(binary.Op); + var right = RightAssociative(binary.Op); + // exponentiation accepts a unary expression on the right + var rightMinimum = binary.Op == BinaryKind.Pow ? UnaryPrecedence : (right ? p : p + 1); + return $"{Expr(binary.Left, indent, placeholder, right ? p + 1 : p)} {OperatorText(binary.Op)} {Expr(binary.Right, indent, placeholder, rightMinimum)}"; + } + case UnaryOp unary: { + var operand = Expr(unary.Operand, indent, placeholder, UnaryPrecedence); + var op = unary.Op switch { UnaryKind.Neg => "-", UnaryKind.Not => "not ", UnaryKind.Len => "#", _ => "~" }; + // adjacent minus signs would start a lua comment + return op + (operand.StartsWith('-') || operand.StartsWith('~') ? " " : "") + operand; + } + case TableNode table: + return "{" + string.Join(", ", table.Fields.Select(f => f.Kind switch { + TableFieldKind.Positional => Expr(f.Value, indent, placeholder, 0), + TableFieldKind.Named => $"{f.Name} = {Expr(f.Value, indent, placeholder, 0)}", + _ => $"[{Expr(f.Key!, indent, placeholder, 0)}] = {Expr(f.Value, indent, placeholder, 0)}", + })) + "}"; + case FunctionNode function: { + if (!placeholder && VerbatimClosure?.Invoke(function, indent) is { } verbatim) return verbatim; + var header = "function" + ParamsText(function.Entry); + if (placeholder) return header + " end"; + var body = Block(function.Entry.Body, indent + 1); + return header + (body.Length == 0 ? " end" : m_eol + body + m_eol + Ind(indent) + "end"); + } + default: + throw new InvalidOperationException($"no Lua form for {node.GetType().Name}"); + } + } + + private static string MemberText(string prefix, string name) + => IsIdentifier(name) ? prefix + "." + name : prefix + "[\"" + name.Replace("\\", "\\\\").Replace("\"", "\\\"") + "\"]"; +} diff --git a/editor/LuaEditor/Graph/Model.cs b/editor/LuaEditor/Graph/Model.cs new file mode 100644 index 000000000..b470cf845 --- /dev/null +++ b/editor/LuaEditor/Graph/Model.cs @@ -0,0 +1,812 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Text; +using editor.LuaEditor.Types; +using Loretta.CodeAnalysis; +using Loretta.CodeAnalysis.Text; +using DiagnosticSeverity = editor.LuaEditor.Types.DiagnosticSeverity; + +namespace editor.LuaEditor.Graph; + +public enum ConstantKind { Nil, Boolean, Number, String } + +public sealed record LuaConstant(ConstantKind Kind, string Raw) { + public static readonly LuaConstant Nil = new(ConstantKind.Nil, "nil"); + public static readonly LuaConstant True = new(ConstantKind.Boolean, "true"); + public static readonly LuaConstant False = new(ConstantKind.Boolean, "false"); + + public static LuaConstant Number(string raw) => new(ConstantKind.Number, raw); + + public static LuaConstant Integer(long value) => new(ConstantKind.Number, value.ToString(CultureInfo.InvariantCulture)); + + public static LuaConstant Float(double value) { + // lua has no literals for infinity or nan + if (double.IsNaN(value)) return new LuaConstant(ConstantKind.Number, "(0/0)"); + if (double.IsPositiveInfinity(value)) return new LuaConstant(ConstantKind.Number, "math.huge"); + if (double.IsNegativeInfinity(value)) return new LuaConstant(ConstantKind.Number, "(-math.huge)"); + var text = value.ToString("R", CultureInfo.InvariantCulture); + return new LuaConstant(ConstantKind.Number, text.Contains('.') || text.Contains('E') ? text : text + ".0"); + } + + public static LuaConstant String(string value) { + var sb = new StringBuilder("\""); + foreach (var c in value) { + sb.Append(c switch { + '"' => "\\\"", + '\\' => "\\\\", + '\n' => "\\n", + '\r' => "\\r", + '\t' => "\\t", + // fixed width escapes keep the next digit out of the escape + '\0' => "\\000", + _ => c.ToString(), + }); + } + return new LuaConstant(ConstantKind.String, sb.Append('"').ToString()); + } + + public LuaType ValueType => Kind switch { + ConstantKind.Nil => LuaType.Nil, + ConstantKind.Boolean => LuaType.Boolean, + ConstantKind.String => LuaType.String, + _ => IsIntegerLiteral(Raw) ? LuaType.Integer : LuaType.Number, + }; + + private static bool IsIntegerLiteral(string raw) { + if (raw.StartsWith("0x", StringComparison.OrdinalIgnoreCase)) return !raw.Contains('.') && !raw.Contains('p') && !raw.Contains('P'); + return !raw.Contains('.') && !raw.Contains('e') && !raw.Contains('E'); + } +} + +public enum CallStyle { Function, Method } + +public enum BinaryKind { Add, Sub, Mul, Div, FloorDiv, Mod, Pow, Concat, Eq, Ne, Lt, Le, Gt, Ge, And, Or, BitAnd, BitOr, BitXor, Shl, Shr } + +public enum UnaryKind { Neg, Not, Len, BitNot } + +public enum BindingKind { Local, Param, LoopVar, LocalFunction, Self } + +public enum TableFieldKind { Positional, Named, Keyed } + +public enum TargetKind { Binding, Global, Member, Index } + +public sealed class Binding { + internal Binding(string name, BindingKind kind, GraphNode declarer, int outputIndex) { + m_name = name; + Kind = kind; + Declarer = declarer; + OutputIndex = outputIndex; + declarer.Outputs[outputIndex].Binding = this; + } + + private string m_name; + + public string Name { + get => m_name; + set { + m_name = value; + Output.Name = value; + } + } + public BindingKind Kind { get; internal set; } + public GraphNode Declarer { get; internal set; } + public int OutputIndex { get; internal set; } + + public string? Attribute { get; set; } + + public bool IsMutable { get; internal set; } + + public int Assignments { get; internal set; } + public bool IsDeclared { get; internal set; } + + public LuaType Type { get; internal set; } = LuaType.Unknown; + public OutputPin Output => Declarer.Outputs[OutputIndex]; +} + +public sealed class OutputPin { + private readonly List m_consumers = []; + + internal OutputPin(GraphNode owner, int index, string name) { + Owner = owner; + Index = index; + Name = name; + } + + public GraphNode Owner { get; } + public int Index { get; internal set; } + public string Name { get; set; } + public LuaType Type { get; internal set; } = LuaType.Unknown; + + public Binding? Binding { get; internal set; } + + public IReadOnlyList Consumers => m_consumers; + + internal void AddConsumer(InputPin pin) => m_consumers.Add(pin); + + internal void RemoveConsumer(InputPin pin) => m_consumers.Remove(pin); +} + +public sealed class InputPin { + internal InputPin(GraphNode owner, string name) { + Owner = owner; + Name = name; + } + + public GraphNode Owner { get; } + public string Name { get; set; } + public OutputPin? Source { get; private set; } + public LuaConstant? Constant { get; private set; } + public bool IsEmpty => Source is null && Constant is null; + + public LuaType? Expected { get; internal set; } + + public LuaType ActualType => ActualOverride ?? Source?.Type ?? Constant?.ValueType ?? LuaType.Nil; + + internal LuaType? ActualOverride { get; set; } + + internal SyntaxNode? Origin { get; set; } + + public void Connect(OutputPin source) { + Clear(); + Source = source; + source.AddConsumer(this); + } + + public void SetConstant(LuaConstant constant) { + Clear(); + Constant = constant; + } + + public void Clear() { + Source?.RemoveConsumer(this); + Source = null; + Constant = null; + } +} + +public abstract class GraphNode { + private readonly List m_inputs = []; + private readonly List m_outputs = []; + + protected GraphNode(LuaGraph graph) { + Graph = graph; + Id = graph.Register(this); + } + + public LuaGraph Graph { get; } + public int Id { get; } + public IReadOnlyList Inputs => m_inputs; + public IReadOnlyList Outputs => m_outputs; + + public bool IsExpanded { get; set; } + + public Statement? OwnerStatement { get; internal set; } + + protected InputPin AddInput(string name) { + var pin = new InputPin(this, name); + m_inputs.Add(pin); + return pin; + } + + protected OutputPin AddOutput(string name) { + var pin = new OutputPin(this, m_outputs.Count, name); + m_outputs.Add(pin); + return pin; + } + + internal void SetInputOrder(IEnumerable order) { + var list = order.ToList(); + m_inputs.Clear(); + m_inputs.AddRange(list); + } + + internal void RemoveInput(InputPin pin) { + pin.Clear(); + m_inputs.Remove(pin); + } + + internal void RemoveOutputAt(int index) { + m_outputs.RemoveAt(index); + for (var i = index; i < m_outputs.Count; i++) { + m_outputs[i].Index = i; + if (m_outputs[i].Binding is { } binding) binding.OutputIndex = i; + } + } + + internal InputPin NewInput(string name) => AddInput(name); + + internal OutputPin NewOutput(string name) => AddOutput(name); +} + +public abstract class ExprNode : GraphNode { + protected ExprNode(LuaGraph graph, string resultName) : base(graph) { + AddOutput(resultName); + } + + public OutputPin Result => Outputs[0]; +} + +public sealed class GlobalGet : ExprNode { + public GlobalGet(LuaGraph graph, string name) : base(graph, name) { + Name = name; + } + + public string Name { get; set; } +} + +public sealed class VariableGet : ExprNode { + public VariableGet(LuaGraph graph, Binding binding) : base(graph, binding.Name) { + Binding = binding; + } + + public Binding Binding { get; } +} + +public sealed class VarargNode : ExprNode { + public VarargNode(LuaGraph graph) : base(graph, "...") { } +} + +public sealed class MemberGet : ExprNode { + public MemberGet(LuaGraph graph, string name) : base(graph, name) { + Name = name; + Object = AddInput("object"); + } + + public InputPin Object { get; } + public string Name { get; set; } +} + +public sealed class IndexGet : ExprNode { + public IndexGet(LuaGraph graph) : base(graph, "value") { + Object = AddInput("object"); + Key = AddInput("key"); + } + + public InputPin Object { get; } + public InputPin Key { get; } +} + +public sealed class CallNode : ExprNode { + private readonly List m_args = []; + + public CallNode(LuaGraph graph, CallStyle style, string? method) : base(graph, "result") { + Style = style; + Method = method; + Target = AddInput(style == CallStyle.Method ? "object" : "function"); + } + + public CallStyle Style { get; internal set; } + + public string? Method { get; set; } + + public InputPin Target { get; } + + public IReadOnlyList Args => m_args; + public int ReturnCount { get; internal set; } + + public InputPin AddArg(string? name = null) { + var pin = AddInput(name ?? "arg" + (m_args.Count + 1)); + m_args.Add(pin); + return pin; + } + + public InputPin InsertArg(int index, string name) { + var pin = AddInput(name); + m_args.Insert(index, pin); + SetInputOrder(new[] { Target }.Concat(m_args)); + return pin; + } + + internal void RemoveArgAt(int index) { + var pin = m_args[index]; + m_args.RemoveAt(index); + RemoveInput(pin); + } + + internal void EnsureOutputs(int count) { + while (Outputs.Count < count) AddOutput("result" + (Outputs.Count + 1)); + } +} + +public sealed class BinaryOp : ExprNode { + public BinaryOp(LuaGraph graph, BinaryKind op) : base(graph, "result") { + Op = op; + Left = AddInput("a"); + Right = AddInput("b"); + } + + public BinaryKind Op { get; set; } + public InputPin Left { get; } + public InputPin Right { get; } +} + +public sealed class UnaryOp : ExprNode { + public UnaryOp(LuaGraph graph, UnaryKind op) : base(graph, "result") { + Op = op; + Operand = AddInput("value"); + } + + public UnaryKind Op { get; set; } + public InputPin Operand { get; } +} + +public sealed class ParenNode : ExprNode { + public ParenNode(LuaGraph graph) : base(graph, "value") { + Inner = AddInput("value"); + } + + public InputPin Inner { get; } +} + +public sealed class TableField { + internal TableField(TableFieldKind kind, string? name, InputPin? key, InputPin value) { + Kind = kind; + Name = name; + Key = key; + Value = value; + } + + public TableFieldKind Kind { get; } + public string? Name { get; set; } + public InputPin? Key { get; } + public InputPin Value { get; } +} + +public enum TableFlavor { Table, Array, Dictionary } + +public sealed class TableNode : ExprNode { + private readonly List m_fields = []; + + public TableNode(LuaGraph graph) : base(graph, "table") { } + + public TableFlavor? DeclaredFlavor { get; set; } + + public LuaType? DeclaredType { get; set; } + + public LuaType? TargetType { get; internal set; } + + public TableFlavor Flavor => DeclaredFlavor + ?? TargetType switch { + ArrayType => (TableFlavor?)TableFlavor.Array, + TableType => TableFlavor.Dictionary, + _ => null + } + ?? (m_fields.Count > 0 && m_fields.All(f => f.Kind == TableFieldKind.Positional) ? TableFlavor.Array + : m_fields.Count > 0 && m_fields.All(f => f.Kind == TableFieldKind.Keyed) ? TableFlavor.Dictionary + : TableFlavor.Table); + + public IReadOnlyList Fields => m_fields; + + public TableField AddPositional() { + var field = new TableField(TableFieldKind.Positional, null, null, AddInput("[" + (m_fields.Count + 1) + "]")); + m_fields.Add(field); + return field; + } + + public TableField AddNamed(string name) { + var field = new TableField(TableFieldKind.Named, name, null, AddInput(name)); + m_fields.Add(field); + return field; + } + + public TableField AddKeyed() { + var key = AddInput("key"); + var field = new TableField(TableFieldKind.Keyed, null, key, AddInput("value")); + m_fields.Add(field); + return field; + } + + internal void RemoveFieldAt(int index) { + var field = m_fields[index]; + m_fields.RemoveAt(index); + if (field.Key is not null) RemoveInput(field.Key); + RemoveInput(field.Value); + } +} + +public sealed class FunctionNode : ExprNode { + public FunctionNode(LuaGraph graph) : base(graph, "function") { + Entry = new FunctionEntry(graph, this); + } + + public FunctionEntry Entry { get; } + + internal TextSpan? SourceSpan { get; set; } + + internal string? OriginalParams { get; set; } +} + +public sealed class RawExpression : ExprNode { + public RawExpression(LuaGraph graph, string text) : base(graph, "raw") { + Text = text; + } + + public string Text { get; set; } +} + +public sealed class FunctionEntry : GraphNode { + public FunctionEntry(LuaGraph graph, GraphNode owner) : base(graph) { + Owner = owner; + Body = new Block("body") { Owner = this }; + } + + public GraphNode Owner { get; } + public Binding? Self { get; internal set; } + public List Params { get; } = []; + public bool IsVararg { get; set; } + + internal TextSpan? ParamsSpan { get; set; } + + public Block Body { get; } + + internal void RemoveParam(Binding binding) { + Params.Remove(binding); + RemoveOutputAt(binding.OutputIndex); + } + + internal Binding AddParam(string name, BindingKind kind) { + var pin = AddOutput(name); + var binding = new Binding(name, kind, this, pin.Index); + if (kind == BindingKind.Self) Self = binding; + else Params.Add(binding); + return binding; + } +} + +public sealed class Block { + private readonly List m_statements = []; + + public Block(string role) { + Role = role; + } + + public string Role { get; } + public GraphNode? Owner { get; internal set; } + public IReadOnlyList Statements => m_statements; + + internal int OpenEnd { get; set; } = -1; + + internal int CloseStart { get; set; } = -1; + + public void Insert(int index, Statement statement) { + statement.Parent?.Remove(statement); + m_statements.Insert(index, statement); + statement.Parent = this; + } + + public void Add(Statement statement) => Insert(m_statements.Count, statement); + + public bool Remove(Statement statement) { + if (!m_statements.Remove(statement)) return false; + statement.Parent = null; + return true; + } + + public int IndexOf(Statement statement) => m_statements.IndexOf(statement); + + internal IReadOnlyList Original { get; set; } = []; +} + +public abstract class Statement : GraphNode { + protected Statement(LuaGraph graph) : base(graph) { + OwnerStatement = this; + } + + public Block? Parent { get; internal set; } + + public bool IsFloating { get; set; } + + public List LeadingLines { get; } = []; + + public virtual IEnumerable ChildBlocks => []; + + internal SyntaxNode? Source { get; set; } + internal TextSpan? LeadingLinesSpan { get; set; } + internal Dictionary Spans { get; } = []; + internal StatementBaseline? Baseline { get; set; } +} + +public sealed class LocalDecl : Statement { + public LocalDecl(LuaGraph graph) : base(graph) { } + + public List Names { get; } = []; + public List Values { get; } = []; + + public Binding AddName(string name) { + var pin = AddOutput(name); + var binding = new Binding(name, BindingKind.Local, this, pin.Index); + Names.Add(binding); + return binding; + } + + public InputPin AddValue() { + var pin = AddInput("value" + (Values.Count + 1)); + Values.Add(pin); + return pin; + } +} + +public sealed class AssignTarget { + internal AssignTarget(TargetKind kind, Binding? binding, string? name, InputPin? obj, InputPin? key) { + Kind = kind; + Binding = binding; + Name = name; + Object = obj; + Key = key; + } + + public TargetKind Kind { get; } + public Binding? Binding { get; } + public string? Name { get; set; } + public InputPin? Object { get; } + public InputPin? Key { get; } +} + +public sealed class AssignStatement : Statement { + public AssignStatement(LuaGraph graph) : base(graph) { } + + public List Targets { get; } = []; + public List Values { get; } = []; + + public AssignTarget AddBindingTarget(Binding binding) { + var target = new AssignTarget(TargetKind.Binding, binding, binding.Name, null, null); + Targets.Add(target); + binding.Assignments++; + return target; + } + + public AssignTarget AddGlobalTarget(string name) { + var target = new AssignTarget(TargetKind.Global, null, name, null, null); + Targets.Add(target); + return target; + } + + public AssignTarget AddMemberTarget(string name) { + var target = new AssignTarget(TargetKind.Member, null, name, AddInput("object"), null); + Targets.Add(target); + return target; + } + + public AssignTarget AddIndexTarget() { + var target = new AssignTarget(TargetKind.Index, null, null, AddInput("object"), AddInput("key")); + Targets.Add(target); + return target; + } + + public InputPin AddValue() { + var pin = AddInput("value" + (Values.Count + 1)); + Values.Add(pin); + return pin; + } +} + +public sealed class CallStatement : Statement { + public CallStatement(LuaGraph graph) : base(graph) { + Call = AddInput("call"); + } + + public InputPin Call { get; } + public CallNode? CallNode => Call.Source?.Owner as CallNode; +} + +public sealed class IfClause { + internal IfClause(InputPin condition, Block body) { + Condition = condition; + Body = body; + } + + public InputPin Condition { get; } + public Block Body { get; } +} + +public sealed class IfStatement : Statement { + public IfStatement(LuaGraph graph) : base(graph) { } + + public List Clauses { get; } = []; + public Block? Else { get; set; } + + public IfClause AddClause() { + var block = new Block(Clauses.Count == 0 ? "then" : "elseif") { Owner = this }; + var clause = new IfClause(AddInput(Clauses.Count == 0 ? "condition" : "condition" + (Clauses.Count + 1)), block); + Clauses.Add(clause); + return clause; + } + + public Block AddElse() => Else ??= new Block("else") { Owner = this }; + + public override IEnumerable ChildBlocks => Clauses.Select(c => c.Body).Concat(Else is null ? [] : [Else]); +} + +public sealed class WhileStatement : Statement { + public WhileStatement(LuaGraph graph) : base(graph) { + Condition = AddInput("condition"); + Body = new Block("body") { Owner = this }; + } + + public InputPin Condition { get; } + public Block Body { get; } + public override IEnumerable ChildBlocks => [Body]; +} + +public sealed class RepeatStatement : Statement { + public RepeatStatement(LuaGraph graph) : base(graph) { + Condition = AddInput("until"); + Body = new Block("body") { Owner = this }; + } + + public InputPin Condition { get; } + public Block Body { get; } + public override IEnumerable ChildBlocks => [Body]; +} + +public sealed class NumericFor : Statement { + public NumericFor(LuaGraph graph, string varName) : base(graph) { + Var = new Binding(varName, BindingKind.LoopVar, this, AddOutput(varName).Index); + Start = AddInput("start"); + Limit = AddInput("limit"); + Step = AddInput("step"); + Body = new Block("body") { Owner = this }; + } + + public Binding Var { get; } + public InputPin Start { get; } + public InputPin Limit { get; } + + public InputPin Step { get; } + + public Block Body { get; } + public override IEnumerable ChildBlocks => [Body]; +} + +public sealed class GenericFor : Statement { + public GenericFor(LuaGraph graph) : base(graph) { + Body = new Block("body") { Owner = this }; + } + + public List Vars { get; } = []; + public List Exprs { get; } = []; + public Block Body { get; } + public override IEnumerable ChildBlocks => [Body]; + + public Binding AddVar(string name) { + var binding = new Binding(name, BindingKind.LoopVar, this, AddOutput(name).Index); + Vars.Add(binding); + return binding; + } + + public InputPin AddExpr() { + var pin = AddInput("iterator" + (Exprs.Count + 1)); + Exprs.Add(pin); + return pin; + } +} + +public sealed class DoStatement : Statement { + public DoStatement(LuaGraph graph) : base(graph) { + Body = new Block("body") { Owner = this }; + } + + public Block Body { get; } + public override IEnumerable ChildBlocks => [Body]; +} + +public sealed class FunctionDecl : Statement { + public FunctionDecl(LuaGraph graph, bool isLocal, string name) : base(graph) { + IsLocal = isLocal; + Entry = new FunctionEntry(graph, this); + Path = [name]; + Root = AddInput("table"); + if (isLocal) FunctionBinding = new Binding(name, BindingKind.LocalFunction, this, AddOutput(name).Index); + } + + public bool IsLocal { get; } + + public List Path { get; } + + public bool IsMethod { get; set; } + + public InputPin Root { get; } + + public Binding? AssignedBinding { get; internal set; } + + public Binding? FunctionBinding { get; private set; } + + internal void AdoptLocalBinding(Binding binding) { + binding.Output.Binding = null; + binding.OutputIndex = FunctionBinding!.OutputIndex; + binding.Declarer = this; + binding.Kind = BindingKind.LocalFunction; + binding.Output.Binding = binding; + FunctionBinding = binding; + } + public FunctionEntry Entry { get; } + public string Name => IsLocal ? FunctionBinding!.Name : Path[^1]; + public override IEnumerable ChildBlocks => [Entry.Body]; +} + +public sealed class ReturnStatement : Statement { + public ReturnStatement(LuaGraph graph) : base(graph) { } + + public List Values { get; } = []; + + public InputPin AddValue() { + var pin = AddInput("value" + (Values.Count + 1)); + Values.Add(pin); + return pin; + } +} + +public sealed class BreakStatement : Statement { + public BreakStatement(LuaGraph graph) : base(graph) { } +} + +public sealed class GotoStatement : Statement { + public GotoStatement(LuaGraph graph, string label) : base(graph) { + Label = label; + } + + public string Label { get; set; } +} + +public sealed class LabelStatement : Statement { + public LabelStatement(LuaGraph graph, string name) : base(graph) { + Name = name; + } + + public string Name { get; set; } +} + +public sealed class CastStatement : Statement { + public Binding? Target { get; internal set; } + + public CastStatement(LuaGraph graph, string variable, string typeText) : base(graph) { + Variable = variable; + TypeText = typeText; + } + + public string Variable { get; set; } + + public string TypeText { get; set; } + + internal TextSpan? LineSpan { get; set; } +} + +public sealed class CommentStatement : Statement { + public CommentStatement(LuaGraph graph, IEnumerable lines) : base(graph) { + Lines.AddRange(lines); + } + + public List Lines { get; } = []; + internal TextSpan? LineSpan { get; set; } +} + +public sealed class SequenceStatement : Statement { + public SequenceStatement(LuaGraph graph) : base(graph) { } + + public List Branches { get; } = []; + public override IEnumerable ChildBlocks => Branches; + + public Block AddBranch() { + var block = new Block("branch") { Owner = this }; + Branches.Add(block); + return block; + } +} + +public sealed class RawStatement : Statement { + public RawStatement(LuaGraph graph, string text) : base(graph) { + Text = text; + } + + public string Text { get; set; } +} + +public sealed record Wire(OutputPin From, InputPin To); + +public sealed record GraphDiagnostic(DiagnosticSeverity Severity, string Message, GraphNode Node, InputPin? Pin); + +internal sealed record PartBaseline(TextSpan Span, string Text, IReadOnlyList? Closures = null); + +internal sealed record StatementBaseline(string Shape, IReadOnlyList Parts, IReadOnlyList LeadingLines); diff --git a/editor/LuaEditor/Graph/ScriptInfo.cs b/editor/LuaEditor/Graph/ScriptInfo.cs new file mode 100644 index 000000000..022384b24 --- /dev/null +++ b/editor/LuaEditor/Graph/ScriptInfo.cs @@ -0,0 +1,96 @@ +using System.Collections.Generic; +using System.Linq; +using editor.LuaEditor.Types; + +namespace editor.LuaEditor.Graph; + +internal sealed record ScriptField(string Name, AssignStatement Statement, AnnotationBlock Annotations, InputPin Value); + +internal sealed class ScriptInfo { + public const string UnnamedClass = "__script"; + + private ScriptInfo(LocalDecl declaration, Binding table, ClassTag? classTag, AnnotationBlock classAnnotations) { + Declaration = declaration; + Table = table; + ClassTag = classTag; + ClassAnnotations = classAnnotations; + } + + public LocalDecl Declaration { get; } + public Binding Table { get; } + public ClassTag? ClassTag { get; } + public AnnotationBlock ClassAnnotations { get; } + public List Fields { get; } = []; + public List Methods { get; } = []; + + public string ClassName => ClassTag?.Name ?? UnnamedClass; + + public static AnnotationBlock AnnotationsOf(Statement statement) + => AnnotationParser.Parse(statement.LeadingLines.Where(l => l.StartsWith("---", System.StringComparison.Ordinal)).ToList()); + + public bool IsTable(InputPin pin) + => pin.Source is { } source && (source.Binding == Table || (source.Owner is VariableGet get && get.Binding == Table)); + + public static ScriptInfo? Find(LuaGraph graph) { + var module = graph.Module; + var last = module.Statements.LastOrDefault(s => s is not CommentStatement and not CastStatement); + LocalDecl? declaration = null; + Binding? table = null; + if (last is ReturnStatement { Values.Count: 1 } ret && ret.Values[0].Source is { Binding: { Declarer: LocalDecl returned } binding }) { + declaration = returned; + table = binding; + } + if (declaration is null) { + declaration = module.Statements.OfType().FirstOrDefault(d => d.Names.Count == 1 && AnnotationsOf(d).Tags.OfType().Any()); + table = declaration?.Names[0]; + } + if (declaration is null || table is null) return null; + + var annotations = AnnotationsOf(declaration); + var info = new ScriptInfo(declaration, table, annotations.Tags.OfType().FirstOrDefault(), annotations); + foreach (var statement in module.Statements) { + switch (statement) { + case AssignStatement { Targets.Count: 1, Values.Count: >= 1 } assign + when assign.Targets[0] is { Kind: TargetKind.Member, Object: { } owner } target && info.IsTable(owner): + info.Fields.Add(new ScriptField(target.Name!, assign, AnnotationsOf(assign), assign.Values[0])); + break; + case FunctionDecl { IsLocal: false, Path.Count: 2 } function when info.IsTable(function.Root): + info.Methods.Add(function); + break; + } + } + return info; + } + + public static FunctionType SignatureOf(FunctionEntry entry, AnnotationBlock annotations) { + var parameters = entry.Params.Select(p => { + var tag = annotations.Tags.OfType().FirstOrDefault(t => t.Name == p.Name); + return new Param(p.Name, tag?.Type ?? LuaType.Any, tag?.Optional ?? false); + }).ToList(); + LuaType? vararg = entry.IsVararg ? annotations.Tags.OfType().FirstOrDefault(t => t.Name == "...")?.Type ?? LuaType.Any : null; + var returnTags = annotations.Tags.OfType().ToList(); + var returns = returnTags.Where(r => !r.Vararg).Select(r => r.Type).ToList(); + // unannotated functions may return any type + var varargReturn = returnTags.FirstOrDefault(r => r.Vararg)?.Type ?? (returnTags.Count == 0 ? LuaType.Any : null); + return new FunctionType(parameters, returns, vararg, varargReturn); + } + + public static MemberDecl MemberOf(FunctionDecl function, AnnotationBlock annotations, string name, bool isMethod) + => new(name, SignatureOf(function.Entry, annotations), annotations.Doc, annotations.Tags.OfType().FirstOrDefault()?.Unit, isMethod, + annotations.Tags.OfType().SelectMany(g => g.Params).DistinctBy(g => g.Name).ToList(), + annotations.Tags.OfType().Select(o => o.Signature).ToList(), new SourceLocation("", 0)); + + public DeclarationFile ToDeclarations(IReadOnlyDictionary fieldTypes) { + var location = new SourceLocation("", 0); + var members = new List(); + foreach (var field in Fields) { + var type = field.Annotations.Tags.OfType().FirstOrDefault()?.Type ?? fieldTypes.GetValueOrDefault(field.Name, LuaType.Any); + members.Add(new MemberDecl(field.Name, type, field.Annotations.Doc, field.Annotations.Tags.OfType().FirstOrDefault()?.Unit, false, [], [], location)); + } + foreach (var method in Methods) members.RemoveAll(m => m.Name == method.Name); + foreach (var method in Methods) members.Add(MemberOf(method, AnnotationsOf(method), method.Name, method.IsMethod)); + var bases = ClassTag?.Bases ?? []; + var declaration = new ClassDecl(ClassName, ClassTag?.Generics ?? [], bases, members, ClassAnnotations.Doc, location); + return new DeclarationFile("script", [declaration], [], [], [], []); + } +} diff --git a/editor/LuaEditor/Graph/StackGuard.cs b/editor/LuaEditor/Graph/StackGuard.cs new file mode 100644 index 000000000..1805e1009 --- /dev/null +++ b/editor/LuaEditor/Graph/StackGuard.cs @@ -0,0 +1,32 @@ +using System; +using System.Runtime.ExceptionServices; +using System.Threading; + +namespace editor.LuaEditor.Graph; + +// long expression chains can overflow the default stack +internal static class StackGuard { + private const int StackBytes = 256 * 1024 * 1024; + + [ThreadStatic] + private static bool s_inside; + + public static T Run(Func work) { + if (s_inside) return work(); + + T? result = default; + ExceptionDispatchInfo? failure = null; + var thread = new Thread(() => { + s_inside = true; + try { + result = work(); + } catch (Exception e) { + failure = ExceptionDispatchInfo.Capture(e); + } + }, StackBytes); + thread.Start(); + thread.Join(); + failure?.Throw(); + return result!; + } +} diff --git a/editor/LuaEditor/Graph/Typer.cs b/editor/LuaEditor/Graph/Typer.cs new file mode 100644 index 000000000..cd92f0d7c --- /dev/null +++ b/editor/LuaEditor/Graph/Typer.cs @@ -0,0 +1,720 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using editor.LuaEditor.Types; + +namespace editor.LuaEditor.Graph; + +internal sealed class Typer { + private sealed class Env(Env? parent) { + private readonly Dictionary m_types = []; + + public Env? Parent { get; } = parent; + + public LuaType? Get(Binding binding) { + for (var env = this; env is not null; env = env.Parent) + if (env.m_types.TryGetValue(binding, out var type)) return type; + return null; + } + + public void Set(Binding binding, LuaType type) => m_types[binding] = type; + + public void CopyTo(Env target, Env? stop) { + var seen = new HashSet(); + for (var env = this; env is not null && env != stop; env = env.Parent) + foreach (var (binding, type) in env.m_types) + if (seen.Add(binding)) target.Set(binding, type); + } + } + + private readonly LuaGraph m_graph; + private readonly TypeUniverse m_universe; + private readonly TypeChecker m_checker; + private readonly CallResolver m_resolver; + private readonly ScriptInfo? m_script; + private readonly List m_diagnostics = []; + private readonly Dictionary m_functions = []; + private readonly Dictionary m_returnCounts = []; + private Env m_env = new(null); + private IReadOnlyList? m_returns; + + private Typer(LuaGraph graph, TypeUniverse universe, ScriptInfo? script) { + m_graph = graph; + m_universe = universe; + m_script = script; + m_checker = new TypeChecker(universe); + m_resolver = new CallResolver(m_checker, universe); + } + + public static void Run(LuaGraph graph) { + var first = new Typer(graph, graph.Universe, null); + first.WalkBlock(graph.Module, new Env(null)); + var script = ScriptInfo.Find(graph); + var universe = graph.Universe; + if (script is not null) { + var fieldTypes = new Dictionary(); + foreach (var field in script.Fields) fieldTypes[field.Name] = FieldTypeFrom(field.Value.ActualType); + universe = universe.Extend(script.ToDeclarations(fieldTypes)); + } + var second = new Typer(graph, universe, script); + second.WalkBlock(graph.Module, new Env(null)); + foreach (var loose in graph.Nodes.OfType().Where(n => n.OwnerStatement is null).ToList()) second.TypeOutput(loose.Result); + second.TypeTableTargets(script); + graph.SetDiagnostics(second.m_diagnostics); + } + + internal static LuaType FieldTypeFrom(LuaType value) => value switch { + NamedType { Name: "TypeMarker", Args: [var target] } => target, + _ when value == LuaType.Nil || value == LuaType.Unknown => LuaType.Any, + _ => value + }; + + private static LuaType Widen(LuaType type) => type == LuaType.Nil || type == LuaType.Unknown ? LuaType.Any : type; + + private static bool IsAny(LuaType type) => type is PrimitiveType { Kind: PrimitiveKind.Any or PrimitiveKind.Unknown }; + + private static bool HasNil(LuaType type) => type == LuaType.Nil || (type is UnionType u && u.Members.Contains(LuaType.Nil)); + + private LuaType NonNil(LuaType type) => HasNil(type) ? m_checker.NarrowNonNil(type) : type; + + private void Report(DiagnosticSeverity severity, string message, GraphNode node, InputPin? pin) => m_diagnostics.Add(new GraphDiagnostic(severity, message, node, pin)); + + private void Check(InputPin pin, LuaType expected) { + pin.Expected = expected; + var result = m_checker.Check(pin.ActualType, expected); + if (result.Kind == Compat.Allowed) return; + Report(result.Kind == Compat.Warning ? DiagnosticSeverity.Warning : DiagnosticSeverity.Error, result.Reason ?? $"{pin.ActualType} does not fit {expected}", pin.Owner, pin); + } + + private void WarnIfNullable(InputPin pin, LuaType type, GraphNode node) { + if (type is UnionType union && union.Members.Contains(LuaType.Nil) && !union.Members.Any(IsAny)) + Report(DiagnosticSeverity.Warning, $"{type} may be nil here", node, pin); + } + + private void WalkBlock(Block block, Env env) { + var saved = m_env; + m_env = env; + foreach (var statement in block.Statements) WalkStatement(statement); + m_env = saved; + } + + private void WalkStatement(Statement statement) { + switch (statement) { + case LocalDecl local: + WalkLocal(local); + break; + case AssignStatement assign: + WalkAssign(assign); + break; + case CallStatement call: + Value(call.Call); + break; + case IfStatement @if: + WalkIf(@if); + break; + case WhileStatement @while: { + Value(@while.Condition); + var body = new Env(m_env); + Narrow(@while.Condition, true, body); + WalkBlock(@while.Body, body); + break; + } + case RepeatStatement repeat: { + var body = new Env(m_env); + WalkBlock(repeat.Body, body); + var saved = m_env; + m_env = body; + Value(repeat.Condition); + m_env = saved; + break; + } + case NumericFor numeric: + WalkNumericFor(numeric); + break; + case GenericFor generic: + WalkGenericFor(generic); + break; + case DoStatement @do: + WalkBlock(@do.Body, new Env(m_env)); + break; + case FunctionDecl function: + WalkFunctionDecl(function); + break; + case ReturnStatement @return: + for (var i = 0; i < @return.Values.Count; i++) { + Value(@return.Values[i]); + if (m_returns is not null && i < m_returns.Count) Check(@return.Values[i], m_returns[i]); + } + break; + case CastStatement cast: + ApplyCast(cast); + break; + case SequenceStatement sequence: + foreach (var branch in sequence.Branches) WalkBlock(branch, m_env); + break; + } + } + + private void WalkLocal(LocalDecl local) { + var annotations = ScriptInfo.AnnotationsOf(local); + var declared = annotations.Tags.OfType().FirstOrDefault()?.Type; + var values = local.Values.Select(Value).ToList(); + for (var i = 0; i < local.Names.Count; i++) { + var binding = local.Names[i]; + LuaType? valueType = null; + if (i < local.Values.Count && (i < local.Values.Count - 1 || local.Names.Count <= local.Values.Count || !IsMultiValue(local.Values[^1]))) { + valueType = values[i]; + } else if (local.Values.Count > 0 && local.Values[^1].Source is { Owner: CallNode multi }) { + var index = i - (local.Values.Count - 1); + valueType = index < multi.Outputs.Count ? multi.Outputs[index].Type : LuaType.Any; + } + binding.IsDeclared = i == 0 && declared is not null; + binding.Type = (i == 0 ? declared : null) ?? Widen(valueType ?? LuaType.Any); + if (m_script is not null && binding == m_script.Table) binding.Type = new NamedType(m_script.ClassName, []); + binding.Output.Type = binding.Type; + } + } + + private static bool IsMultiValue(InputPin pin) => pin.Source is { Owner: CallNode or VarargNode, Index: 0, Binding: null }; + + private void WalkAssign(AssignStatement assign) { + var expected = new List(); + foreach (var target in assign.Targets) { + switch (target.Kind) { + case TargetKind.Binding: + expected.Add(target.Binding!.IsDeclared && !IsAny(target.Binding.Type) ? LuaType.Optional(target.Binding.Type) : null); + break; + case TargetKind.Member: { + var objectType = Value(target.Object!); + var member = LookupMember(objectType, target.Name!, target.Object!, assign); + expected.Add(member is { Type: not FunctionType } && !IsAny(member.Type) && IsEnforced(objectType, target.Name!) ? LuaType.Optional(member.Type) : null); + break; + } + case TargetKind.Index: + Value(target.Object!); + Value(target.Key!); + expected.Add(null); + break; + default: + expected.Add(null); + break; + } + } + for (var i = 0; i < assign.Values.Count; i++) { + var pin = assign.Values[i]; + var actual = Value(pin); + if (i >= expected.Count || expected[i] is not { } type) continue; + if (actual is NamedType { Name: "TypeMarker", Args: [var target] } && + m_script?.Fields.Any(field => field.Value == pin && !field.Name.StartsWith('_')) == true && + m_checker.Check(target, type).Kind == Compat.Allowed) { + pin.Expected = type; + continue; + } + Check(pin, type); + } + } + + private bool IsEnforced(LuaType receiver, string field) { + if (m_script is null || NonNil(receiver) is not NamedType named) return true; + var declaringClass = m_universe.MembersOf(named.Name).FirstOrDefault(m => m.Decl.Name == field)?.DeclaringClass; + if (declaringClass != m_script.ClassName) return true; + return m_script.Fields.Any(f => f.Name == field && f.Annotations.Tags.OfType().Any()); + } + + private void WalkIf(IfStatement statement) { + var outer = m_env; + var falseSoFar = new Env(outer); + var allExit = true; + foreach (var clause in statement.Clauses) { + m_env = falseSoFar; + Value(clause.Condition); + var branch = new Env(falseSoFar); + Narrow(clause.Condition, true, branch); + WalkBlock(clause.Body, branch); + allExit &= Exits(clause.Body); + var next = new Env(falseSoFar); + Narrow(clause.Condition, false, next); + falseSoFar = next; + } + m_env = outer; + if (statement.Else is not null) { + WalkBlock(statement.Else, new Env(falseSoFar)); + return; + } + if (allExit) falseSoFar.CopyTo(outer, outer); + } + + private static bool Exits(Block block) { + var last = block.Statements.LastOrDefault(s => s is not CommentStatement and not CastStatement); + return last switch { + ReturnStatement or BreakStatement or GotoStatement => true, + CallStatement { CallNode: { Style: CallStyle.Function } call } => call.Target.Source?.Owner is GlobalGet { Name: "error" }, + _ => false, + }; + } + + private void WalkNumericFor(NumericFor numeric) { + Value(numeric.Start); + Value(numeric.Limit); + Check(numeric.Start, LuaType.Number); + Check(numeric.Limit, LuaType.Number); + var allIntegers = numeric.Start.ActualType == LuaType.Integer; + if (!numeric.Step.IsEmpty) { + Value(numeric.Step); + Check(numeric.Step, LuaType.Number); + allIntegers &= numeric.Step.ActualType == LuaType.Integer; + } + numeric.Var.Type = allIntegers ? LuaType.Integer : LuaType.Number; + numeric.Var.Output.Type = numeric.Var.Type; + WalkBlock(numeric.Body, new Env(m_env)); + } + + private void WalkGenericFor(GenericFor generic) { + foreach (var expression in generic.Exprs) Value(expression); + var types = new List { LuaType.Any, LuaType.Any }; + if (generic.Exprs.Count > 0 && generic.Exprs[0].Source is { Owner: CallNode { Style: CallStyle.Function, Args.Count: >= 1 } call } + && call.Target.Source?.Owner is GlobalGet { Name: "ipairs" or "pairs" } iterator) { + var collection = NonNil(call.Args[0].ActualType); + switch (collection) { + case ArrayType array: + types = [LuaType.Integer, array.Element]; + break; + case TableType table when iterator.Name == "pairs": + types = [table.Key, table.Value]; + break; + } + } + for (var i = 0; i < generic.Vars.Count; i++) { + generic.Vars[i].Type = i < types.Count ? types[i] : LuaType.Any; + generic.Vars[i].Output.Type = generic.Vars[i].Type; + } + WalkBlock(generic.Body, new Env(m_env)); + } + + private void WalkFunctionDecl(FunctionDecl function) { + var annotations = ScriptInfo.AnnotationsOf(function); + var signature = ScriptInfo.SignatureOf(function.Entry, annotations); + if (function.Path.Count > 1) Value(function.Root); + + foreach (var parameter in function.Entry.Params) { + var tag = annotations.Tags.OfType().FirstOrDefault(t => t.Name == parameter.Name); + parameter.IsDeclared = tag is not null; + parameter.Type = tag is null ? LuaType.Any : (tag.Optional ? LuaType.Optional(tag.Type) : tag.Type); + parameter.Output.Type = parameter.Type; + } + if (function.Entry.Self is { } self) { + var inScript = m_script is not null && function.Path.Count == 2 && m_script.IsTable(function.Root); + self.Type = inScript ? new NamedType(m_script!.ClassName, []) : LuaType.Any; + self.Output.Type = self.Type; + } + if (function.FunctionBinding is { } binding) { + // recursive calls need the signature before the body is typed + binding.Type = signature; + binding.Output.Type = signature; + m_functions[binding] = ScriptInfo.MemberOf(function, annotations, binding.Name, false); + } + if (function.FunctionBinding is { } local && !annotations.Tags.OfType().Any()) + m_returnCounts[local] = ReturnSites(function.Entry.Body).Select(r => r.Values.Count).DefaultIfEmpty().Max(); + WalkFunctionBody(function.Entry.Body, signature.Returns); + } + + private static IEnumerable ReturnSites(Block block) { + foreach (var statement in block.Statements) { + if (statement is ReturnStatement ret) yield return ret; + if (statement is FunctionDecl) continue; + foreach (var child in statement.ChildBlocks) + foreach (var nested in ReturnSites(child)) yield return nested; + } + } + + private void WalkFunctionBody(Block body, IReadOnlyList? returns) { + var savedReturns = m_returns; + m_returns = returns; + WalkBlock(body, new Env(m_env)); + m_returns = savedReturns; + } + + private void ApplyCast(CastStatement cast) { + if (cast.Target is not { } binding || string.IsNullOrWhiteSpace(cast.TypeText)) return; + var text = cast.TypeText.Trim(); + var mode = text[0] is '+' or '-' ? text[0] : ' '; + if (mode != ' ') text = text[1..].Trim(); + if (!TypeExprParser.TryParsePrefix(text, 0, out var type, out _, out _)) return; + var current = m_env.Get(binding) ?? binding.Type; + m_env.Set(binding, mode switch { + '+' => LuaType.Union(current, type), + '-' => RemoveFrom(current, type), + _ => type, + }); + } + + private static LuaType RemoveFrom(LuaType current, LuaType removed) { + if (current is not UnionType union) return current == removed ? LuaType.Unknown : current; + var remaining = union.Members.Where(m => m != removed).ToArray(); + return remaining.Length == 0 ? LuaType.Unknown : LuaType.Union(remaining); + } + + private static Binding? BindingOf(InputPin pin) => pin.Source?.Binding ?? (pin.Source?.Owner as VariableGet)?.Binding; + + private void Narrow(InputPin condition, bool truthy, Env env) { + if (condition.Source is not { } source) return; + if (BindingOf(condition) is { } binding) { + if (truthy) env.Set(binding, NonNil(env.Get(binding) ?? binding.Type)); + return; + } + switch (source.Owner) { + case UnaryOp { Op: UnaryKind.Not } not: + Narrow(not.Operand, !truthy, env); + break; + case BinaryOp { Op: BinaryKind.And } both when truthy: + Narrow(both.Left, true, env); + Narrow(both.Right, true, env); + break; + case BinaryOp { Op: BinaryKind.Or } either when !truthy: + Narrow(either.Left, false, env); + Narrow(either.Right, false, env); + break; + case BinaryOp { Op: BinaryKind.Eq or BinaryKind.Ne } comparison: { + var holds = truthy == (comparison.Op == BinaryKind.Eq); + NarrowComparison(comparison.Left, comparison.Right, holds, env); + NarrowComparison(comparison.Right, comparison.Left, holds, env); + break; + } + } + } + + private void NarrowComparison(InputPin subject, InputPin other, bool holds, Env env) { + if (other.Constant is { Kind: ConstantKind.Nil } && BindingOf(subject) is { } nilChecked) { + if (!holds) env.Set(nilChecked, NonNil(env.Get(nilChecked) ?? nilChecked.Type)); + return; + } + if (other.Constant is { Kind: ConstantKind.String } name && subject.Source?.Owner is CallNode { Style: CallStyle.Function, Args.Count: 1 } call + && call.Target.Source?.Owner is GlobalGet { Name: "type" } && BindingOf(call.Args[0]) is { } typed && holds) { + env.Set(typed, m_checker.NarrowToTypeName(env.Get(typed) ?? typed.Type, name.Raw.Trim('"', '\''))); + } + } + + private LuaType Value(InputPin pin) { + LuaType type; + LuaType? narrowed = null; + if (pin.Constant is { } constant) { + type = constant.ValueType; + } else if (pin.Source is { } source) { + type = TypeOutput(source); + if (BindingOf(pin) is { } binding) narrowed = m_env.Get(binding); + } else { + type = LuaType.Nil; + } + pin.ActualOverride = narrowed; + return narrowed ?? type; + } + + private LuaType TypeOutput(OutputPin output) { + if (output.Binding is { } binding) return binding.Type; + if (output.Owner is ExprNode node) TypeNode(node); + return output.Type; + } + + private LuaType GlobalType(string name) { + if (m_universe.GlobalType(name) is { } declared) return declared; + if (m_universe.Enums.FirstOrDefault(e => e.TableName == name) is { } table) return new NamedType(table.Name, []); + return LuaType.Any; + } + + private void TypeNode(ExprNode node) { + switch (node) { + case GlobalGet global: + node.Result.Type = GlobalType(global.Name); + break; + case VariableGet get: + node.Result.Type = get.Binding.Type; + break; + case ParenNode paren: + node.Result.Type = Value(paren.Inner); + break; + case MemberGet member: { + var objectType = Value(member.Object); + var found = LookupMember(objectType, member.Name, member.Object, node); + node.Result.Type = found is { IsMethod: true, Type: FunctionType method } + ? WithReceiver(method, NonNil(objectType)) : found?.Type ?? LuaType.Any; + break; + } + case IndexGet index: { + var objectType = NonNil(Value(index.Object)); + Value(index.Key); + node.Result.Type = objectType switch { + ArrayType array => array.Element, + TableType table => table.Value, + _ => LuaType.Any, + }; + break; + } + case CallNode call: + TypeCall(call); + break; + case BinaryOp binary: + TypeBinary(binary); + break; + case UnaryOp unary: + TypeUnary(unary); + break; + case TableNode table: + TypeTable(table); + break; + case FunctionNode function: + WalkClosure(function); + break; + default: + node.Result.Type = LuaType.Any; + break; + } + } + + private void WalkClosure(FunctionNode function) { + foreach (var parameter in function.Entry.Params) { + parameter.Type = LuaType.Any; + parameter.Output.Type = LuaType.Any; + } + WalkFunctionBody(function.Entry.Body, null); + function.Result.Type = new FunctionType(function.Entry.Params.Select(p => new Param(p.Name, LuaType.Any, true)).ToList(), [], null, LuaType.Any); + } + + private void TypeTable(TableNode table) { + var elements = new List(); + var positionalOnly = table.Fields.Count > 0; + foreach (var field in table.Fields) { + if (field.Key is not null) Value(field.Key); + var type = Widen(Value(field.Value)); + if (field.Kind == TableFieldKind.Positional) elements.Add(type); + else positionalOnly = false; + } + table.Result.Type = table.Flavor switch { + TableFlavor.Array => new ArrayType(elements.Count == 0 ? LuaType.Any : LuaType.Union(elements.ToArray())), + TableFlavor.Dictionary => DictionaryType(table), + _ => positionalOnly ? new ArrayType(LuaType.Union(elements.ToArray())) : LuaType.Table + }; + } + + private LuaType DictionaryType(TableNode table) { + var keys = table.Fields.Where(f => f.Key is not null).Select(f => Widen(Value(f.Key!))).ToArray(); + var values = table.Fields.Select(f => Widen(Value(f.Value))).ToArray(); + return new TableType(keys.Length == 0 ? LuaType.Any : LuaType.Union(keys), values.Length == 0 ? LuaType.Any : LuaType.Union(values)); + } + + private static LuaType WithoutNil(LuaType type) => type is UnionType u && u.Members.Count(x => x != LuaType.Nil) == 1 ? u.Members.First(x => x != LuaType.Nil) : type; + + private static LuaType? StoredAs(InputPin consumer, ScriptInfo? script) { + if (consumer.Expected is { } expected && WithoutNil(expected) is ArrayType or TableType) return WithoutNil(expected); + if (consumer.Owner is Statement statement && ScriptInfo.AnnotationsOf(statement).Tags.OfType().FirstOrDefault()?.Type is { } declared && WithoutNil(declared) is ArrayType or TableType) return WithoutNil(declared); + if (script?.Fields.FirstOrDefault(f => f.Value == consumer)?.Annotations.Tags.OfType().FirstOrDefault()?.Type is { } field && WithoutNil(field) is ArrayType or TableType) return WithoutNil(field); + return null; + } + + internal void TypeTableTargets(ScriptInfo? script) { + var tables = m_graph.Nodes.OfType().ToList(); + foreach (var table in tables) table.TargetType = null; + // nested tables need a second pass to inherit the outer type + for (var pass = 0; pass < 2; pass++) + foreach (var table in tables) { + LuaType? target = null; + foreach (var consumer in table.Result.Consumers) { + target = StoredAs(consumer, script); + if (target is null && consumer.Owner is TableNode outer && outer.TargetType is { } outerType && outer.Fields.FirstOrDefault(f => f.Value == consumer) is { } entry) + target = outerType switch { ArrayType arr => WithoutNil(arr.Element), TableType dict => WithoutNil(dict.Value), _ => null } is { } inner && inner is ArrayType or TableType ? inner : null; + if (target is not null) break; + } + table.TargetType = target ?? table.DeclaredType; + } + foreach (var table in tables) { + if (table.TargetType is not { } target) continue; + var element = target switch { ArrayType arr => arr.Element, TableType dict => dict.Value, _ => null }; + var key = (target as TableType)?.Key; + foreach (var field in table.Fields) { + if (element is not null && !IsAny(element)) { + field.Value.Expected = element; + var actual = Value(field.Value); + if (!IsAny(actual) && field.Value.IsEmpty is false && m_checker.Check(actual, element).Kind == Compat.Blocked) + Report(DiagnosticSeverity.Error, $"this {(target is ArrayType ? "array" : "dictionary")} holds {TypeFormatter.Display(element)}, not {TypeFormatter.Display(actual)}", table, field.Value); + } + if (key is not null && field.Key is { } keyPin) { + keyPin.Expected = key; + var actualKey = Value(keyPin); + if (!IsAny(actualKey) && m_checker.Check(actualKey, key).Kind == Compat.Blocked) + Report(DiagnosticSeverity.Error, $"the keys of this dictionary are {TypeFormatter.Display(key)}, not {TypeFormatter.Display(actualKey)}", table, keyPin); + } + } + if (target is ArrayType or TableType) table.Result.Type = target; + } + } + + private static LuaType Substitute(LuaType type, IReadOnlyDictionary map) { + switch (type) { + case NamedType { Args.Count: 0 } n when map.TryGetValue(n.Name, out var replacement): + return replacement; + case NamedType n when n.Args.Count > 0: + return n with { Args = n.Args.Select(a => Substitute(a, map)).ToList() }; + case UnionType u: + return LuaType.Union(u.Members.Select(m => Substitute(m, map)).ToArray()); + case ArrayType a: + return new ArrayType(Substitute(a.Element, map)); + case TableType t: + return new TableType(Substitute(t.Key, map), Substitute(t.Value, map)); + case FunctionType f: + return new FunctionType(f.Params.Select(p => p with { Type = Substitute(p.Type, map) }).ToList(), f.Returns.Select(r => Substitute(r, map)).ToList(), + f.VarargParam is null ? null : Substitute(f.VarargParam, map), f.VarargReturn is null ? null : Substitute(f.VarargReturn, map)); + default: + return type; + } + } + + private MemberDecl? LookupMember(LuaType receiver, string name, InputPin receiverPin, GraphNode node) { + WarnIfNullable(receiverPin, receiver, node); + var type = NonNil(receiver); + string? className = null; + var map = new Dictionary(); + switch (type) { + case NamedType named when m_universe.FindClass(named.Name) is { } info: + className = named.Name; + for (var i = 0; i < info.Generics.Count && i < named.Args.Count; i++) map[info.Generics[i].Name] = named.Args[i]; + break; + case NamedType named when m_universe.FindEnum(named.Name) is not null: + return new MemberDecl(name, named, "", null, false, [], [], new SourceLocation("", 0)); + case PrimitiveType { Kind: PrimitiveKind.String }: + className = "stringlib"; + break; + } + if (className is null) return null; + var found = m_universe.MembersOf(className).FirstOrDefault(m => m.Decl.Name == name)?.Decl; + if (found is null || map.Count == 0) return found; + return found with { Type = Substitute(found.Type, map), Overloads = found.Overloads.Select(o => (FunctionType)Substitute(o, map)).ToList() }; + } + + private static MemberDecl WithoutFirstParam(MemberDecl member) { + if (member.Type is not FunctionType { Params.Count: > 0 } fn) return member; + return member with { + Type = fn with { Params = fn.Params.Skip(1).ToList() }, + Overloads = member.Overloads.Select(o => o.Params.Count > 0 ? o with { Params = o.Params.Skip(1).ToList() } : o).ToList(), + }; + } + + private static FunctionType WithReceiver(FunctionType signature, LuaType receiver) + => signature with { Params = signature.Params.Prepend(new Param("self", receiver, false)).ToList() }; + + private MemberDecl? CalleeOf(CallNode call) { + var callee = Value(call.Target); + var source = call.Target.Source; + if (source is { Binding: null, Owner: GlobalGet global } && m_universe.GlobalDeclOf(global.Name) is { Type: FunctionType type } declared) + return new MemberDecl(global.Name, type, declared.Doc, null, false, declared.Generics, declared.Overloads, declared.Location); + if (source is { Binding: null, Owner: MemberGet member }) { + var found = LookupMember(member.Object.ActualType, member.Name, member.Object, call); + if (found is null || found.Type is not FunctionType) return null; + if (!found.IsMethod) return found; + var receiver = NonNil(member.Object.ActualType); + return found with { + Type = WithReceiver((FunctionType)found.Type, receiver), + Overloads = found.Overloads.Select(o => WithReceiver(o, receiver)).ToList() + }; + } + if (source?.Binding is { } binding && m_functions.TryGetValue(binding, out var local)) return local; + return callee is FunctionType function ? new MemberDecl("function", function, "", null, false, [], [], new SourceLocation("", 0)) : null; + } + + private void TypeCall(CallNode call) { + var argumentTypes = call.Args.Select(Value).ToList(); + MemberDecl? member; + if (call.Style == CallStyle.Method) { + var receiver = Value(call.Target); + member = LookupMember(receiver, call.Method!, call.Target, call); + if (member is not null && !member.IsMethod) member = WithoutFirstParam(member); + } else { + member = CalleeOf(call); + } + + call.ReturnCount = 0; + if (member is null || member.Type is not FunctionType) { + call.Result.Type = LuaType.Any; + foreach (var output in call.Outputs) output.Type = LuaType.Any; + return; + } + + var resolved = m_resolver.Resolve(member, argumentTypes.Cast().ToList()); + var signature = resolved.Signature; + for (var i = 0; i < call.Args.Count; i++) { + var index = i; + var parameter = index < signature.Params.Count ? signature.Params[index] : null; + var expected = parameter is null ? signature.VarargParam : (parameter.Optional ? LuaType.Optional(parameter.Type) : parameter.Type); + call.Args[i].Expected = expected; + var result = index < resolved.ArgResults.Count ? resolved.ArgResults[index] : CompatResult.Ok; + if (result.Kind != Compat.Allowed) + Report(result.Kind == Compat.Warning ? DiagnosticSeverity.Warning : DiagnosticSeverity.Error, result.Reason ?? "argument does not fit", call, call.Args[i]); + } + + var returns = signature.Returns; + var targetBinding = call.Target.Source?.Binding ?? (call.Target.Source?.Owner as VariableGet)?.Binding; + call.ReturnCount = Math.Max(returns.Count, targetBinding is not null ? m_returnCounts.GetValueOrDefault(targetBinding) : 0); + call.EnsureOutputs(Math.Max(1, call.ReturnCount)); + for (var i = 0; i < call.Outputs.Count; i++) + call.Outputs[i].Type = i < returns.Count ? returns[i] : (signature.VarargReturn ?? (i == 0 ? LuaType.Nil : LuaType.Any)); + } + + private static string? OperatorName(BinaryKind op) => op switch { + BinaryKind.Add => "add", BinaryKind.Sub => "sub", BinaryKind.Mul => "mul", BinaryKind.Div => "div", BinaryKind.Mod => "mod", + BinaryKind.Pow => "pow", BinaryKind.FloorDiv => "idiv", BinaryKind.Concat => "concat", _ => null, + }; + + private LuaType? OverloadedResult(string op, LuaType owner, LuaType? operand) { + if (NonNil(owner) is not NamedType named || m_universe.FindClass(named.Name) is null) return null; + foreach (var candidate in m_universe.OperatorsOf(named.Name).Where(o => o.Op == op)) { + if (operand is null) return candidate.Result; + if (candidate.Operand is null) continue; + if (m_checker.Check(operand, candidate.Operand).Kind != Compat.Blocked) return candidate.Result; + } + return null; + } + + private static bool IsNumeric(LuaType type) => type == LuaType.Number || type == LuaType.Integer; + + private void TypeBinary(BinaryOp binary) { + var left = Value(binary.Left); + LuaType right; + if (binary.Op is BinaryKind.And or BinaryKind.Or) { + // short circuit evaluation narrows the right operand + var inner = new Env(m_env); + Narrow(binary.Left, binary.Op == BinaryKind.And, inner); + var saved = m_env; + m_env = inner; + right = Value(binary.Right); + m_env = saved; + } else { + right = Value(binary.Right); + } + + binary.Result.Type = binary.Op switch { + BinaryKind.And => HasNil(left) ? LuaType.Union(LuaType.Nil, right) : (IsAny(left) ? LuaType.Any : right), + BinaryKind.Or => HasNil(left) ? LuaType.Union(NonNil(left), right) : left, + BinaryKind.Eq or BinaryKind.Ne or BinaryKind.Lt or BinaryKind.Le or BinaryKind.Gt or BinaryKind.Ge => LuaType.Boolean, + BinaryKind.Concat => OverloadedResult("concat", left, right) ?? LuaType.String, + BinaryKind.BitAnd or BinaryKind.BitOr or BinaryKind.BitXor or BinaryKind.Shl or BinaryKind.Shr => LuaType.Integer, + _ => Arithmetic(binary.Op, left, right), + }; + } + + private LuaType Arithmetic(BinaryKind op, LuaType left, LuaType right) { + var l = NonNil(left); + var r = NonNil(right); + if (IsNumeric(l) && IsNumeric(r)) + return op is BinaryKind.Div or BinaryKind.Pow ? LuaType.Number : (l == LuaType.Integer && r == LuaType.Integer ? LuaType.Integer : LuaType.Number); + var name = OperatorName(op)!; + return OverloadedResult(name, l, r) ?? OverloadedResult(name, r, l) ?? (l == LuaType.String || r == LuaType.String ? LuaType.Number : LuaType.Any); + } + + private void TypeUnary(UnaryOp unary) { + var operand = NonNil(Value(unary.Operand)); + unary.Result.Type = unary.Op switch { + UnaryKind.Not => LuaType.Boolean, + UnaryKind.Len => OverloadedResult("len", operand, null) ?? LuaType.Integer, + UnaryKind.BitNot => LuaType.Integer, + _ => IsNumeric(operand) ? operand : OverloadedResult("unm", operand, null) ?? LuaType.Any, + }; + } +} diff --git a/editor/LuaEditor/Graph/Variables.cs b/editor/LuaEditor/Graph/Variables.cs new file mode 100644 index 000000000..46e65e694 --- /dev/null +++ b/editor/LuaEditor/Graph/Variables.cs @@ -0,0 +1,144 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using editor.LuaEditor.Types; + +namespace editor.LuaEditor.Graph; + +public enum VariableKind { Field, ModuleLocal, Function } + +public sealed record GraphVariable(string Name, VariableKind Kind, bool Exported, LuaType Type, string? Unit, string Doc, Statement Declaration); + +public sealed partial class LuaGraph { + public IReadOnlyList Variables { + get { + var script = ScriptInfo.Find(this); + var result = new List(); + var seenFields = new HashSet(); + foreach (var statement in Module.Statements) { + switch (statement) { + case AssignStatement assign when script?.Fields.FirstOrDefault(f => f.Statement == assign) is { } field: { + if (!seenFields.Add(field.Name)) break; + var declared = field.Annotations.Tags.OfType().FirstOrDefault()?.Type; + var type = declared ?? Typer.FieldTypeFrom(field.Value.ActualType); + result.Add(new GraphVariable(field.Name, VariableKind.Field, !field.Name.StartsWith('_'), type, UnitOf(field.Annotations), field.Annotations.Doc, assign)); + break; + } + case LocalDecl local when local != script?.Declaration: { + var annotations = ScriptInfo.AnnotationsOf(local); + var declared = annotations.Tags.OfType().FirstOrDefault()?.Type; + for (var i = 0; i < local.Names.Count; i++) { + var type = (i == 0 ? declared : null) ?? (local.Names[i].Type == LuaType.Unknown ? LuaType.Any : local.Names[i].Type); + result.Add(new GraphVariable(local.Names[i].Name, VariableKind.ModuleLocal, false, type, UnitOf(annotations), annotations.Doc, local)); + } + break; + } + case FunctionDecl function: { + var annotations = ScriptInfo.AnnotationsOf(function); + result.Add(new GraphVariable(function.Name, VariableKind.Function, !function.IsLocal && !function.Name.StartsWith('_'), + ScriptInfo.SignatureOf(function.Entry, annotations), UnitOf(annotations), annotations.Doc, function)); + break; + } + } + } + return result; + } + } + + private static string? UnitOf(AnnotationBlock annotations) => annotations.Tags.OfType().FirstOrDefault()?.Unit; + + private static void SetLine(List lines, Func matches, string? newLine, Func? insertBefore = null) { + var first = lines.FindIndex(l => matches(l)); + lines.RemoveAll(l => matches(l)); + if (newLine is null) return; + var at = first; + if (at < 0) { + var before = insertBefore is null ? -1 : lines.FindIndex(l => insertBefore(l)); + at = before >= 0 ? before : lines.Count; + } + lines.Insert(Math.Min(at, lines.Count), newLine); + } + + public void SetDeclaredType(Statement declaration, LuaType? type) + => SetLine(declaration.LeadingLines, l => l.StartsWith("---@type ", StringComparison.Ordinal), type is null ? null : "---@type " + TypeFormatter.Format(type)); + + public void SetUnit(Statement declaration, string? unit) + => SetLine(declaration.LeadingLines, l => l.StartsWith("---@unit", StringComparison.Ordinal), string.IsNullOrWhiteSpace(unit) ? null : "---@unit " + unit.Trim()); + + public void SetDoc(Statement declaration, string? text) { + var lines = declaration.LeadingLines; + bool IsDoc(string l) => l.StartsWith("---", StringComparison.Ordinal) && !l.StartsWith("---@", StringComparison.Ordinal); + var at = lines.FindIndex(IsDoc); + if (at < 0) at = lines.FindIndex(l => l.StartsWith("---", StringComparison.Ordinal)); + if (at < 0) at = lines.Count; + var removedBefore = lines.Take(at).Count(IsDoc); + lines.RemoveAll(IsDoc); + at -= removedBefore; + if (string.IsNullOrEmpty(text)) return; + lines.InsertRange(Math.Min(at, lines.Count), text.Replace("\r\n", "\n").Split('\n').Select(l => "---" + l)); + } + + public void SetParamType(FunctionDecl function, string parameter, LuaType? type) { + if (function.Entry.Params.All(p => p.Name != parameter) && !(parameter == "..." && function.Entry.IsVararg)) + throw new ArgumentException($"{function.Name} has no parameter {parameter}", nameof(parameter)); + SetLine(function.LeadingLines, + l => l.StartsWith($"---@param {parameter} ", StringComparison.Ordinal) || l.StartsWith($"---@param {parameter}? ", StringComparison.Ordinal), + type is null ? null : $"---@param {parameter} {TypeFormatter.Format(type)}", + l => l.StartsWith("---@return", StringComparison.Ordinal)); + } + + public void SetScriptClass(string? name, string? baseName) { + var script = ScriptInfo.Find(this) ?? throw new InvalidOperationException("this file does not define a script class"); + if (name is { Length: > 0 } && !LuaWriter.IsIdentifier(name)) throw new ArgumentException($"\"{name}\" is not a valid class name", nameof(name)); + var lines = script.Declaration.LeadingLines; + lines.RemoveAll(l => l.StartsWith("---@class", StringComparison.Ordinal)); + if (string.IsNullOrEmpty(name)) return; + lines.Insert(0, "---@class " + name + (string.IsNullOrEmpty(baseName) ? "" : " : " + baseName)); + } + + public void AddParam(FunctionDecl function, string name) { + if (!LuaWriter.IsIdentifier(name)) throw new ArgumentException($"\"{name}\" is not a valid name", nameof(name)); + if (function.Entry.Params.Any(p => p.Name == name) || function.Entry.Self?.Name == name) throw new InvalidOperationException($"{function.Name} already has a parameter called {name}"); + function.Entry.AddParam(name, BindingKind.Param); + } + + public void RemoveParam(FunctionDecl function, string name) { + var binding = function.Entry.Params.FirstOrDefault(p => p.Name == name) ?? throw new ArgumentException($"{function.Name} has no parameter {name}", nameof(name)); + if (binding.IsMutable || Nodes.OfType().Any(c => c.Target == binding)) throw new InvalidOperationException($"{name} is assigned or cast in the body; remove that first"); + foreach (var consumer in binding.Output.Consumers.ToList()) Disconnect(consumer); + function.LeadingLines.RemoveAll(l => l.StartsWith($"---@param {name} ", StringComparison.Ordinal) || l.StartsWith($"---@param {name}? ", StringComparison.Ordinal)); + function.Entry.RemoveParam(binding); + } + + public void SetReturnTypes(FunctionDecl function, IReadOnlyList types) { + function.LeadingLines.RemoveAll(l => l.StartsWith("---@return", StringComparison.Ordinal)); + function.LeadingLines.AddRange(types.Select(t => "---@return " + TypeFormatter.Format(t))); + } + + private static bool IsClass(LuaType type, string className) + => type is NamedType named ? named.Name == className : type is UnionType union && union.Members.Any(m => m is NamedType n && n.Name == className); + + public void RenameMember(string oldName, string newName) { + if (!LuaWriter.IsIdentifier(newName)) throw new ArgumentException($"\"{newName}\" is not a valid name", nameof(newName)); + var script = ScriptInfo.Find(this) ?? throw new InvalidOperationException("this file does not define a script class"); + if (!script.Fields.Any(f => f.Name == oldName) && !script.Methods.Any(m => m.Name == oldName)) + throw new InvalidOperationException($"the script has no field or method {oldName}"); + if (script.Fields.Any(f => f.Name == newName) || script.Methods.Any(m => m.Name == newName)) + throw new InvalidOperationException($"the script already has {newName}"); + + foreach (var parent in (script.ClassTag?.Bases ?? []).OfType()) { + var inherited = Universe.MembersOf(parent.Name).Select(m => m.Decl.Name).ToHashSet(); + if (inherited.Contains(oldName)) throw new InvalidOperationException($"{oldName} comes from {parent.Name} and cannot be renamed here"); + if (inherited.Contains(newName)) throw new InvalidOperationException($"{newName} is already a member of {parent.Name}"); + } + + Analyze(); + bool OnScript(InputPin? pin) => pin is not null && IsClass(pin.ActualType, script.ClassName); + var attached = Nodes.Where(n => n.OwnerStatement?.Parent is not null).ToList(); + foreach (var member in attached.OfType().Where(m => m.Name == oldName && OnScript(m.Object))) member.Name = newName; + foreach (var assign in attached.OfType()) + foreach (var target in assign.Targets.Where(t => t.Kind == TargetKind.Member && t.Name == oldName && OnScript(t.Object))) target.Name = newName; + foreach (var call in attached.OfType().Where(c => c.Style == CallStyle.Method && c.Method == oldName && OnScript(c.Target))) call.Method = newName; + foreach (var method in script.Methods.Where(m => m.Name == oldName)) method.Path[^1] = newName; + } +} diff --git a/editor/LuaEditor/Syntax/LuaDocument.cs b/editor/LuaEditor/Syntax/LuaDocument.cs new file mode 100644 index 000000000..307fbcade --- /dev/null +++ b/editor/LuaEditor/Syntax/LuaDocument.cs @@ -0,0 +1,112 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using Loretta.CodeAnalysis; +using Loretta.CodeAnalysis.Lua; +using Loretta.CodeAnalysis.Lua.Syntax; +using TypesDiagnostic = editor.LuaEditor.Types.Diagnostic; +using TypesSeverity = editor.LuaEditor.Types.DiagnosticSeverity; +using TypesLocation = editor.LuaEditor.Types.SourceLocation; + +namespace editor.LuaEditor.Syntax; + +public sealed class LuaDocument { + private static readonly LuaParseOptions s_options = new(LuaSyntaxOptions.Lua54); + + private LuaDocument(string text, SyntaxTree tree, IReadOnlyList errors) { + Text = text; + Tree = tree; + Root = (CompilationUnitSyntax)tree.GetRoot(); + Errors = errors; + Eol = DetectEol(text); + IndentUnit = DetectIndent(text); + } + + public string Text { get; } + public SyntaxTree Tree { get; } + public CompilationUnitSyntax Root { get; } + public IReadOnlyList Errors { get; } + public bool HasErrors => Errors.Count > 0; + + public string Eol { get; } + + public string IndentUnit { get; } + + public static LuaDocument Parse(string text) { + return Graph.StackGuard.Run(() => ParseCore(text)); + } + + private static LuaDocument ParseCore(string text) { + var tree = LuaSyntaxTree.ParseText(text, s_options); + var errors = tree.GetDiagnostics() + .Where(d => d.Severity == Loretta.CodeAnalysis.DiagnosticSeverity.Error) + .Select(d => new TypesDiagnostic(TypesSeverity.Error, d.GetMessage(), new TypesLocation("", d.Location.GetLineSpan().StartLinePosition.Line + 1))) + .ToList(); + return new LuaDocument(text, tree, errors); + } + + public string IndentOfLineAt(int position) { + var start = LineStart(position); + var end = start; + while (end < Text.Length && Text[end] is ' ' or '\t') end++; + return Text[start..end]; + } + + public int LineStart(int position) { + var i = Math.Min(position, Text.Length); + while (i > 0 && Text[i - 1] != '\n') i--; + return i; + } + + public int LineOf(int position) { + var line = 1; + for (var i = 0; i < Math.Min(position, Text.Length); i++) + if (Text[i] == '\n') line++; + return line; + } + + public string Apply(IEnumerable edits) { + var sorted = edits.Select((e, i) => (Edit: e, Order: i)).OrderBy(x => x.Edit.Start).ThenBy(x => x.Edit.Length > 0 ? 1 : 0).ThenBy(x => x.Order).Select(x => x.Edit).ToList(); + var sb = new StringBuilder(Text.Length + 64); + var cursor = 0; + foreach (var edit in sorted) { + if (edit.Start < cursor) throw new ArgumentException($"edits overlap at {edit.Start}"); + if (edit.End > Text.Length) throw new ArgumentException($"edit at {edit.Start} runs past the end of the text"); + sb.Append(Text, cursor, edit.Start - cursor).Append(edit.Text); + cursor = edit.End; + } + return sb.Append(Text, cursor, Text.Length - cursor).ToString(); + } + + private static string DetectEol(string text) { + var crlf = 0; + var lf = 0; + for (var i = 0; i < text.Length; i++) { + if (text[i] != '\n') continue; + if (i > 0 && text[i - 1] == '\r') crlf++; + else lf++; + } + return crlf > lf ? "\r\n" : "\n"; + } + + private static string DetectIndent(string text) { + var tabLines = 0; + var widths = new Dictionary(); + foreach (var raw in text.Split('\n')) { + var line = raw.TrimEnd('\r'); + if (line.Trim().Length == 0) continue; + if (line[0] == '\t') { + tabLines++; + continue; + } + var spaces = 0; + while (spaces < line.Length && line[spaces] == ' ') spaces++; + if (spaces > 0) widths[spaces] = widths.GetValueOrDefault(spaces) + 1; + } + if (tabLines > widths.Values.Sum()) return "\t"; + // continuation indentation should not set the block width + var common = widths.Where(w => w.Value > 1).Select(w => w.Key).DefaultIfEmpty(0).Min(); + return common > 0 ? new string(' ', common) : " "; + } +} diff --git a/editor/LuaEditor/Syntax/TextEdit.cs b/editor/LuaEditor/Syntax/TextEdit.cs new file mode 100644 index 000000000..26a73953e --- /dev/null +++ b/editor/LuaEditor/Syntax/TextEdit.cs @@ -0,0 +1,7 @@ +namespace editor.LuaEditor.Syntax; + +public readonly record struct TextEdit(int Start, int Length, string Text) { + public int End => Start + Length; + + public static TextEdit Insert(int at, string text) => new(at, 0, text); +} diff --git a/editor/LuaEditor/Syntax/TriviaScanner.cs b/editor/LuaEditor/Syntax/TriviaScanner.cs new file mode 100644 index 000000000..499df9c42 --- /dev/null +++ b/editor/LuaEditor/Syntax/TriviaScanner.cs @@ -0,0 +1,41 @@ +using System.Collections.Generic; +using Loretta.CodeAnalysis; +using Loretta.CodeAnalysis.Lua; +using Loretta.CodeAnalysis.Text; + +namespace editor.LuaEditor.Syntax; + +public enum TriviaLineKind { Comment, Annotation, Cast, Blank } + +public sealed record TriviaLine(TriviaLineKind Kind, string Text, TextSpan Span); + +public static class TriviaScanner { + public static IReadOnlyList LeadingLines(SyntaxToken token) { + var lines = new List(); + var lineHasContent = false; + foreach (var trivia in token.LeadingTrivia) { + var text = trivia.ToString(); + switch (trivia.Kind().ToString()) { + case "WhitespaceTrivia": + break; + case "EndOfLineTrivia": + if (!lineHasContent) lines.Add(new TriviaLine(TriviaLineKind.Blank, "", trivia.Span)); + lineHasContent = false; + break; + case "SingleLineCommentTrivia" or "MultiLineCommentTrivia" or "ShebangTrivia": + lines.Add(new TriviaLine(KindOf(text), text.TrimEnd('\r', '\n'), trivia.Span)); + lineHasContent = true; + break; + default: + break; + } + } + return lines; + } + + private static TriviaLineKind KindOf(string text) { + if (text.StartsWith("---@cast", System.StringComparison.Ordinal)) return TriviaLineKind.Cast; + if (text.StartsWith("---@", System.StringComparison.Ordinal)) return TriviaLineKind.Annotation; + return TriviaLineKind.Comment; + } +} diff --git a/editor/LuaEditor/Types/AnnotationParser.cs b/editor/LuaEditor/Types/AnnotationParser.cs new file mode 100644 index 000000000..82cef2340 --- /dev/null +++ b/editor/LuaEditor/Types/AnnotationParser.cs @@ -0,0 +1,245 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace editor.LuaEditor.Types; + +public static class AnnotationParser { + public static AnnotationBlock Parse(IReadOnlyList lines) { + var doc = new List(); + var tags = new List(); + var errors = new List(); + + for (var i = 0; i < lines.Count; i++) { + var body = Body(lines[i]); + if (body.StartsWith('|')) continue; + if (!body.StartsWith('@')) { + doc.Add(body.Trim()); + continue; + } + + var nameEnd = 1; + while (nameEnd < body.Length && !char.IsWhiteSpace(body[nameEnd])) nameEnd++; + var name = body[1..nameEnd]; + var rest = JoinContinuations(body[nameEnd..].Trim(), lines, ref i); + + try { + Tag? tag = name switch { + "meta" => null, + "class" => ParseClass(rest), + "field" => ParseField(rest), + "type" => new TypeTag(ParseType(rest, out _)), + "param" => ParseParam(rest), + "return" => ParseReturn(rest), + "generic" => new GenericTag(ParseGenerics(rest)), + "overload" => ParseType(rest, out _) is FunctionType fn + ? new OverloadTag(fn) + : throw new TypeSyntaxException("@overload needs a fun(...) type", 0), + "alias" => ParseAlias(rest), + "enum" => new EnumTag(FirstWord(StripAttributes(rest))), + "cast" => ParseCast(rest), + "unit" => new UnitTag(rest), + "operator" => ParseOperator(rest), + _ => new UnknownTag(name, rest), + }; + if (tag is not null) tags.Add(tag); + } catch (TypeSyntaxException e) { + errors.Add($"@{name}: {e.Message}"); + } + } + + return new AnnotationBlock(JoinDoc(doc), tags, errors); + } + + private static string JoinContinuations(string rest, IReadOnlyList lines, ref int index) { + while (rest.Count(c => c == '{') > rest.Count(c => c == '}') && index + 1 < lines.Count) rest += " " + Body(lines[++index]).Trim(); + + var members = new List(); + while (index + 1 < lines.Count && Body(lines[index + 1]).TrimStart().StartsWith('|')) { + var member = Body(lines[++index]).TrimStart()[1..].TrimStart('>', '+', '-').Trim(); + if (TypeExprParser.TryParsePrefix(member, 0, out var type, out _, out _)) members.Add(TypeFormatter.Format(type)); + } + if (members.Count == 0) return rest; + var union = string.Join("|", members); + return rest.Length == 0 ? union : $"{rest} {union}"; + } + + private static string Body(string line) { + var trimmed = line.TrimStart(); + return trimmed.StartsWith("---") ? trimmed[3..] : trimmed.TrimStart('-'); + } + + private static string JoinDoc(List lines) { + var parts = new List(); + foreach (var line in lines) { + if (line.Length == 0 && (parts.Count == 0 || parts[^1].Length == 0)) continue; + parts.Add(line); + } + while (parts.Count > 0 && parts[^1].Length == 0) parts.RemoveAt(parts.Count - 1); + return string.Join("\n", parts); + } + + private static LuaType ParseType(string text, out string rest) { + if (!TypeExprParser.TryParsePrefix(text, 0, out var type, out var end, out var error)) + throw new TypeSyntaxException(error ?? "bad type", 0); + rest = text[end..].Trim(); + return type; + } + + private static string CleanDoc(string text) { + text = text.Trim(); + if (text.StartsWith('#')) return text[1..].Trim(); + if (text.StartsWith('[') && text.EndsWith(']')) return text[1..^1].Trim(); + return text; + } + + private static int NameEnd(string text, int start = 0) { + var i = start; + while (i < text.Length && (char.IsLetterOrDigit(text[i]) || text[i] is '_' or '.')) i++; + return i; + } + + private static string FirstWord(string text) => text[..NameEnd(text)]; + + private static string StripAttributes(string text) { + text = text.Trim(); + while (text.StartsWith('(')) { + var close = text.IndexOf(')'); + if (close < 0) break; + text = text[(close + 1)..].TrimStart(); + } + return text; + } + + private static ClassTag ParseClass(string text) { + text = StripAttributes(text); + var end = NameEnd(text); + if (end == 0) throw new TypeSyntaxException("@class needs a name", 0); + var name = text[..end]; + var rest = text[end..]; + + var generics = new List(); + if (rest.StartsWith('<')) { + var close = rest.IndexOf('>'); + if (close < 0) throw new TypeSyntaxException("unclosed generic list", 0); + generics.AddRange(ParseGenerics(rest[1..close])); + rest = rest[(close + 1)..]; + } + + var bases = new List(); + rest = rest.TrimStart(); + if (rest.StartsWith(':')) { + rest = rest[1..]; + while (true) { + bases.Add(ParseType(rest, out rest)); + if (!rest.StartsWith(',')) break; + rest = rest[1..]; + } + } + return new ClassTag(name, generics, bases); + } + + private static FieldTag ParseField(string text) { + var words = text.Split(' ', 2, StringSplitOptions.RemoveEmptyEntries); + if (words.Length == 2 && words[0] is "public" or "private" or "protected" or "package") text = words[1]; + var end = NameEnd(text); + if (end == 0) throw new TypeSyntaxException("@field needs a name", 0); + var name = text[..end]; + var optional = end < text.Length && text[end] == '?'; + var type = ParseType(text[(end + (optional ? 1 : 0))..], out var rest); + return new FieldTag(name, type, optional, CleanDoc(rest)); + } + + private static ParamTag ParseParam(string text) { + string name; + int end; + if (text.StartsWith("...")) { + name = "..."; + end = 3; + } else { + end = NameEnd(text); + if (end == 0) throw new TypeSyntaxException("@param needs a name", 0); + name = text[..end]; + } + var optional = end < text.Length && text[end] == '?'; + var type = ParseType(text[(end + (optional ? 1 : 0))..], out var rest); + return new ParamTag(name, type, optional, CleanDoc(rest)); + } + + private static ReturnTag ParseReturn(string text) { + var type = ParseType(text, out var rest); + var vararg = false; + if (rest.StartsWith("...")) { + vararg = true; + rest = rest[3..].TrimStart(); + } + string? name = null; + var end = NameEnd(rest); + if (end > 0 && (char.IsLetter(rest[0]) || rest[0] == '_')) { + name = rest[..end]; + rest = rest[end..]; + } + return new ReturnTag(type, name, vararg, CleanDoc(rest)); + } + + private static List ParseGenerics(string text) { + var result = new List(); + foreach (var part in SplitTopLevel(text)) { + var colon = part.IndexOf(':'); + var name = (colon < 0 ? part : part[..colon]).Trim(); + if (name.Length == 0) throw new TypeSyntaxException("empty generic name", 0); + var constraint = colon < 0 ? null : TypeExprParser.Parse(part[(colon + 1)..].Trim()); + result.Add(new GenericParam(name, constraint)); + } + return result; + } + + private static IEnumerable SplitTopLevel(string text) { + var depth = 0; + var start = 0; + for (var i = 0; i < text.Length; i++) { + switch (text[i]) { + case '<' or '(' or '{': depth++; break; + case '>' or ')' or '}': depth--; break; + case ',' when depth == 0: + yield return text[start..i]; + start = i + 1; + break; + } + } + yield return text[start..]; + } + + private static AliasTag ParseAlias(string text) { + var end = NameEnd(text); + if (end == 0) throw new TypeSyntaxException("@alias needs a name", 0); + var name = text[..end]; + var rest = text[end..].Trim(); + if (rest.Length == 0) throw new TypeSyntaxException($"@alias {name} has no type", 0); + return new AliasTag(name, ParseType(rest, out _)); + } + + private static OperatorTag ParseOperator(string text) { + var end = NameEnd(text); + if (end == 0) throw new TypeSyntaxException("@operator needs an operator name", 0); + var op = text[..end]; + var rest = text[end..].TrimStart(); + LuaType? operand = null; + if (rest.StartsWith('(')) { + var close = rest.LastIndexOf(')'); + if (close < 0) throw new TypeSyntaxException("unclosed @operator operand", 0); + operand = TypeExprParser.Parse(rest[1..close]); + rest = rest[(close + 1)..].TrimStart(); + } + // missing return annotations follow luals behavior + if (!rest.StartsWith(':')) return new OperatorTag(op, operand, LuaType.Any); + return new OperatorTag(op, operand, ParseType(rest[1..], out _)); + } + + private static CastTag ParseCast(string text) { + var end = NameEnd(text); + if (end == 0) throw new TypeSyntaxException("@cast needs a variable", 0); + var type = text[end..].Trim().TrimStart('+'); + return new CastTag(text[..end], ParseType(type, out _)); + } +} diff --git a/editor/LuaEditor/Types/Annotations.cs b/editor/LuaEditor/Types/Annotations.cs new file mode 100644 index 000000000..d20182a91 --- /dev/null +++ b/editor/LuaEditor/Types/Annotations.cs @@ -0,0 +1,33 @@ +namespace editor.LuaEditor.Types; + +public sealed record GenericParam(string Name, LuaType? Constraint); + +public abstract record Tag; + +public sealed record ClassTag(string Name, EquatableArray Generics, EquatableArray Bases) : Tag; + +public sealed record FieldTag(string Name, LuaType Type, bool Optional, string Doc) : Tag; + +public sealed record TypeTag(LuaType Type) : Tag; + +public sealed record ParamTag(string Name, LuaType Type, bool Optional, string Doc) : Tag; + +public sealed record ReturnTag(LuaType Type, string? Name, bool Vararg, string Doc) : Tag; + +public sealed record GenericTag(EquatableArray Params) : Tag; + +public sealed record OverloadTag(FunctionType Signature) : Tag; + +public sealed record AliasTag(string Name, LuaType Type) : Tag; + +public sealed record EnumTag(string Name) : Tag; + +public sealed record CastTag(string Variable, LuaType Type) : Tag; + +public sealed record UnitTag(string Unit) : Tag; + +public sealed record UnknownTag(string Name, string Text) : Tag; + +public sealed record AnnotationBlock(string Doc, EquatableArray Tags, EquatableArray Errors); + +public sealed record OperatorTag(string Op, LuaType? Operand, LuaType Result) : Tag; diff --git a/editor/LuaEditor/Types/CallResolver.cs b/editor/LuaEditor/Types/CallResolver.cs new file mode 100644 index 000000000..60263d061 --- /dev/null +++ b/editor/LuaEditor/Types/CallResolver.cs @@ -0,0 +1,151 @@ +using System.Collections.Generic; +using System.Linq; + +namespace editor.LuaEditor.Types; + +public sealed record ResolvedCall(FunctionType Signature, IReadOnlyDictionary Bindings, CompatResult Compat, + EquatableArray ArgResults); + +public sealed class CallResolver(TypeChecker checker, TypeUniverse universe) { + private static readonly FunctionType s_empty = new([], [], null, null); + + public ResolvedCall Resolve(MemberDecl member, IReadOnlyList args) { + if (member.Type is not FunctionType main) + return new ResolvedCall(s_empty, new Dictionary(), CompatResult.Block($"{member.Name} is not a function"), []); + + var generics = member.Generics.DistinctBy(g => g.Name).ToDictionary(g => g.Name, g => g.Constraint); + ResolvedCall? best = null; + foreach (var candidate in new[] { main }.Concat(member.Overloads)) { + var call = Evaluate(candidate, generics, args); + if (best is null || call.Compat.Kind < best.Compat.Kind) best = call; + } + return best!; + } + + private ResolvedCall Evaluate(FunctionType fn, Dictionary generics, IReadOnlyList args) { + var bindings = new Dictionary(); + var boundBy = new Dictionary(); + var argErrors = new Dictionary(); + + for (var i = 0; i < args.Count; i++) { + if (args[i] is not { } arg || ParamType(fn, i) is not { } param) continue; + var before = bindings.Keys.ToHashSet(); + if (!TryBind(universe.ResolveAliases(param), universe.ResolveAliases(arg), generics, bindings)) + argErrors[i] = CompatResult.Block($"{arg} does not match the other arguments of this call"); + foreach (var name in bindings.Keys.Where(k => !before.Contains(k))) boundBy[name] = i; + } + + foreach (var (name, constraint) in generics) { + if (!bindings.TryGetValue(name, out var bound)) { + bindings[name] = constraint ?? LuaType.Any; + } else if (constraint is not null && checker.Check(bound, constraint).Kind != Compat.Allowed) { + argErrors[boundBy[name]] = CompatResult.Block($"{bound} is not a {constraint}"); + } + } + + var signature = new FunctionType( + fn.Params.Select(p => p with { Type = Substitute(p.Type, generics, bindings, true) }).ToList(), + fn.Returns.Select(r => Substitute(r, generics, bindings, false)).ToList(), + fn.VarargParam is null ? null : Substitute(fn.VarargParam, generics, bindings, true), + fn.VarargReturn is null ? null : Substitute(fn.VarargReturn, generics, bindings, false)); + + var results = new List(); + for (var i = 0; i < args.Count; i++) { + if (argErrors.TryGetValue(i, out var error)) { + results.Add(error); + } else if (args[i] is not { } arg) { + results.Add(CompatResult.Ok); + } else if (i < signature.Params.Count) { + var p = signature.Params[i]; + results.Add(checker.Check(arg, p.Optional ? LuaType.Optional(p.Type) : p.Type)); + } else if (signature.VarargParam is { } vararg) { + results.Add(checker.Check(arg, vararg)); + } else { + results.Add(CompatResult.Warn("too many arguments")); + } + } + + var compat = results.Aggregate(CompatResult.Ok, CompatResult.Worst); + return new ResolvedCall(signature, bindings, compat, results); + } + + private static LuaType? ParamType(FunctionType fn, int index) + => index < fn.Params.Count ? fn.Params[index].Type : fn.VarargParam; + + private bool TryBind(LuaType param, LuaType arg, Dictionary generics, Dictionary bindings) { + switch (param) { + case NamedType { Args.Count: 0 } n when generics.ContainsKey(n.Name): + return Bind(n.Name, arg, bindings); + case CaptureType c: + return arg is LiteralType { Value: string className } ? Bind(c.Name, new NamedType(className, []), bindings) : true; + case NamedType n when arg is NamedType a && a.Name == n.Name && a.Args.Count == n.Args.Count: + for (var i = 0; i < n.Args.Count; i++) + if (!TryBind(n.Args[i], a.Args[i], generics, bindings)) return false; + return true; + case ArrayType p when arg is ArrayType a: + return TryBind(p.Element, a.Element, generics, bindings); + case UnionType u: + foreach (var member in u.Members) { + if (!Mentions(member, generics) || !ShapeMatches(member, arg, generics)) continue; + return TryBind(member, arg, generics, bindings); + } + return true; + default: + return true; + } + } + + private bool Bind(string name, LuaType type, Dictionary bindings) { + if (!bindings.TryGetValue(name, out var existing)) { + bindings[name] = type; + return true; + } + if (existing == type || checker.Check(type, existing).Kind != Compat.Blocked) return true; + if (checker.Check(existing, type).Kind == Compat.Blocked) return false; + bindings[name] = type; + return true; + } + + private static bool ShapeMatches(LuaType param, LuaType arg, Dictionary generics) => param switch { + NamedType { Args.Count: 0 } n when generics.ContainsKey(n.Name) => true, + CaptureType => arg is LiteralType { Value: string }, + NamedType n => arg is NamedType a && a.Name == n.Name, + ArrayType => arg is ArrayType, + _ => false, + }; + + private static bool Mentions(LuaType type, Dictionary generics) => type switch { + NamedType n => (n.Args.Count == 0 && generics.ContainsKey(n.Name)) || n.Args.Any(a => Mentions(a, generics)), + CaptureType => true, + ArrayType a => Mentions(a.Element, generics), + TableType t => Mentions(t.Key, generics) || Mentions(t.Value, generics), + UnionType u => u.Members.Any(m => Mentions(m, generics)), + FunctionType f => f.Params.Any(p => Mentions(p.Type, generics)) || f.Returns.Any(r => Mentions(r, generics)), + _ => false, + }; + + private static LuaType Substitute(LuaType type, Dictionary generics, Dictionary bindings, bool inParam) { + switch (type) { + case NamedType { Args.Count: 0 } n when generics.ContainsKey(n.Name): + return bindings.GetValueOrDefault(n.Name, LuaType.Any); + case CaptureType c: + return inParam ? LuaType.String : bindings.GetValueOrDefault(c.Name, LuaType.Any); + case NamedType n: + return n.Args.Count == 0 ? n : n with { Args = n.Args.Select(a => Substitute(a, generics, bindings, inParam)).ToList() }; + case UnionType u: + return LuaType.Union(u.Members.Select(m => Substitute(m, generics, bindings, inParam)).ToArray()); + case ArrayType a: + return new ArrayType(Substitute(a.Element, generics, bindings, inParam)); + case TableType t: + return new TableType(Substitute(t.Key, generics, bindings, inParam), Substitute(t.Value, generics, bindings, inParam)); + case FunctionType f: + return new FunctionType( + f.Params.Select(p => p with { Type = Substitute(p.Type, generics, bindings, inParam) }).ToList(), + f.Returns.Select(r => Substitute(r, generics, bindings, inParam)).ToList(), + f.VarargParam is null ? null : Substitute(f.VarargParam, generics, bindings, inParam), + f.VarargReturn is null ? null : Substitute(f.VarargReturn, generics, bindings, inParam)); + default: + return type; + } + } +} diff --git a/editor/LuaEditor/Types/Declarations.cs b/editor/LuaEditor/Types/Declarations.cs new file mode 100644 index 000000000..90dd173cd --- /dev/null +++ b/editor/LuaEditor/Types/Declarations.cs @@ -0,0 +1,26 @@ +namespace editor.LuaEditor.Types; + +public readonly record struct SourceLocation(string Path, int Line); + +public enum DiagnosticSeverity { Info, Warning, Error } + +public sealed record Diagnostic(DiagnosticSeverity Severity, string Message, SourceLocation Location); + +public sealed record MemberDecl(string Name, LuaType Type, string Doc, string? Unit, bool IsMethod, + EquatableArray Generics, EquatableArray Overloads, SourceLocation Location); + +public sealed record ClassDecl(string Name, EquatableArray Generics, EquatableArray Bases, + EquatableArray Members, string Doc, SourceLocation Location, + EquatableArray Operators = default); + +public sealed record OperatorDecl(string Op, LuaType? Operand, LuaType Result); + +public sealed record GlobalDecl(string Name, LuaType Type, string Doc, SourceLocation Location, + EquatableArray Generics = default, EquatableArray Overloads = default); + +public sealed record AliasDecl(string Name, LuaType Type, string Doc, SourceLocation Location); + +public sealed record EnumDecl(string Name, string TableName, EquatableArray<(string Name, object? Value)> Members, string Doc, SourceLocation Location); + +public sealed record DeclarationFile(string Path, EquatableArray Classes, EquatableArray Globals, + EquatableArray Aliases, EquatableArray Enums, EquatableArray Diagnostics); diff --git a/editor/LuaEditor/Types/DefinitionFileReader.cs b/editor/LuaEditor/Types/DefinitionFileReader.cs new file mode 100644 index 000000000..960a3877a --- /dev/null +++ b/editor/LuaEditor/Types/DefinitionFileReader.cs @@ -0,0 +1,239 @@ +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Text.RegularExpressions; + +namespace editor.LuaEditor.Types; + +public static partial class DefinitionFileReader { + [GeneratedRegex(@"^(local\s+)?function\s+([A-Za-z_][\w.]*)([:.])([A-Za-z_]\w*)\s*\(([^)]*)\)")] + private static partial Regex MemberFunction(); + + [GeneratedRegex(@"^(local\s+)?function\s+([A-Za-z_]\w*)\s*\(([^)]*)\)")] + private static partial Regex GlobalFunction(); + + [GeneratedRegex(@"^(local\s+)?([A-Za-z_]\w*)(\.([A-Za-z_]\w*))?\s*=(?!=)")] + private static partial Regex Assignment(); + + [GeneratedRegex(@"^\s*\[?""?([A-Za-z_]\w*)""?\]?\s*=\s*([^,]+?)\s*,?\s*$")] + private static partial Regex EnumEntry(); + + public static DeclarationFile Read(string path, string text) => new Reader(path, text).Run(); + + private sealed class ClassBuilder(string name, SourceLocation location) { + public readonly string Name = name; + public readonly SourceLocation Location = location; + public readonly List Generics = []; + public readonly List Bases = []; + public readonly List Members = []; + public readonly List Operators = []; + public string Doc = ""; + + public ClassDecl Build() => new(Name, Generics, Bases, Members, Doc, Location, Operators); + } + + private sealed class Reader(string path, string text) { + private readonly string[] m_lines = text.Replace("\r\n", "\n").Split('\n'); + private readonly List m_classes = []; + private readonly Dictionary m_classByName = []; + private readonly Dictionary m_localToClass = []; + private readonly List m_globals = []; + private readonly List m_aliases = []; + private readonly List m_enums = []; + private readonly List m_diagnostics = []; + + private static readonly AnnotationBlock s_empty = new("", [], []); + + private SourceLocation At(int index) => new(path, index + 1); + + public DeclarationFile Run() { + var i = 0; + while (i < m_lines.Length) { + var line = m_lines[i].Trim(); + if (line.StartsWith("---")) { + var start = i; + var blockLines = new List(); + while (i < m_lines.Length && m_lines[i].TrimStart().StartsWith("---")) blockLines.Add(m_lines[i++]); + var block = AnnotationParser.Parse(blockLines); + foreach (var error in block.Errors) m_diagnostics.Add(new Diagnostic(DiagnosticSeverity.Warning, error, At(start))); + + var subject = i; + while (subject < m_lines.Length && m_lines[subject].Trim().Length == 0) subject++; + if (subject < m_lines.Length && !m_lines[subject].TrimStart().StartsWith("--")) { + i = Process(block, start, subject); + } else { + Process(block, start, -1); + } + } else if (line.Length == 0 || line.StartsWith("--")) { + i++; + } else { + i = Process(s_empty, i, i); + } + } + + return new DeclarationFile(path, m_classes.Select(c => c.Build()).ToList(), m_globals, m_aliases, m_enums, m_diagnostics); + } + + private int Process(AnnotationBlock block, int blockStart, int subjectIndex) { + var subject = subjectIndex >= 0 ? m_lines[subjectIndex].Trim() : ""; + var next = subjectIndex >= 0 ? subjectIndex + 1 : blockStart + 1; + + foreach (var alias in block.Tags.OfType()) + m_aliases.Add(new AliasDecl(alias.Name, alias.Type, block.Doc, At(blockStart))); + + if (block.Tags.OfType().FirstOrDefault() is { } classTag) { + var builder = DeclareClass(classTag, block.Doc, At(blockStart)); + foreach (var op in block.Tags.OfType()) { + var decl = new OperatorDecl(op.Op, op.Operand, op.Result); + if (!builder.Operators.Contains(decl)) builder.Operators.Add(decl); + } + var line = blockStart; + foreach (var field in block.Tags.OfType()) { + var type = field.Optional ? LuaType.Optional(field.Type) : field.Type; + AddMember(builder, MakeMember(field.Name, type, field.Doc, null, false, [], [], At(line++))); + } + if (Assignment().Match(subject) is { Success: true } m && !m.Groups[3].Success) { + // type markers must not overwrite their class definitions + if (block.Tags.OfType().FirstOrDefault() is { } marker) { + if (!m.Groups[1].Success) AddGlobal(m.Groups[2].Value, marker.Type, block.Doc, At(subjectIndex)); + } else { + m_localToClass[m.Groups[2].Value] = classTag.Name; + if (!m.Groups[1].Success) AddGlobal(m.Groups[2].Value, new NamedType(classTag.Name, []), block.Doc, At(subjectIndex)); + } + } + return next; + } + + if (block.Tags.OfType().FirstOrDefault() is { } enumTag) { + if (Assignment().Match(subject) is { Success: true } m && subject.Contains('{')) return ReadEnum(enumTag, m.Groups[2].Value, block.Doc, blockStart, subjectIndex); + return next; + } + + if (subjectIndex < 0) return next; + + if (MemberFunction().Match(subject) is { Success: true } mf) { + if (mf.Groups[1].Success) return next; + var owner = ResolveOwner(mf.Groups[2].Value, subjectIndex); + var fn = BuildFunction(block, mf.Groups[5].Value); + AddMember(owner, MakeMember(mf.Groups[4].Value, fn, block.Doc, Unit(block), mf.Groups[3].Value == ":", + Generics(block), Overloads(block), At(subjectIndex))); + return next; + } + + if (GlobalFunction().Match(subject) is { Success: true } gf) { + if (!gf.Groups[1].Success) AddGlobal(gf.Groups[2].Value, BuildFunction(block, gf.Groups[3].Value), block.Doc, At(subjectIndex), Generics(block), Overloads(block)); + return next; + } + + if (block.Tags.OfType().FirstOrDefault() is { } typeTag && Assignment().Match(subject) is { Success: true } assign) { + if (assign.Groups[3].Success) { + var owner = ResolveOwner(assign.Groups[2].Value, subjectIndex); + AddMember(owner, MakeMember(assign.Groups[4].Value, typeTag.Type, block.Doc, Unit(block), false, [], [], At(subjectIndex))); + } else if (!assign.Groups[1].Success) { + AddGlobal(assign.Groups[2].Value, typeTag.Type, block.Doc, At(subjectIndex)); + } + } + return next; + } + + private ClassBuilder DeclareClass(ClassTag tag, string doc, SourceLocation location) { + if (!m_classByName.TryGetValue(tag.Name, out var builder)) { + builder = new ClassBuilder(tag.Name, location); + m_classByName[tag.Name] = builder; + m_classes.Add(builder); + } + foreach (var g in tag.Generics) if (builder.Generics.All(existing => existing.Name != g.Name)) builder.Generics.Add(g); + foreach (var b in tag.Bases) if (!builder.Bases.Contains(b)) builder.Bases.Add(b); + if (builder.Doc.Length == 0) builder.Doc = doc; + return builder; + } + + private ClassBuilder ResolveOwner(string owner, int line) { + var name = m_localToClass.GetValueOrDefault(owner, owner); + if (m_classByName.TryGetValue(name, out var builder)) return builder; + + builder = DeclareClass(new ClassTag(name, [], []), "", At(line)); + if (m_globals.All(g => g.Name != owner)) AddGlobal(owner, new NamedType(name, []), "", At(line)); + return builder; + } + + private void AddGlobal(string name, LuaType type, string doc, SourceLocation location, + EquatableArray generics = default, EquatableArray overloads = default) { + m_globals.RemoveAll(g => g.Name == name); + m_globals.Add(new GlobalDecl(name, type, doc, location, generics, overloads)); + } + + private static void AddMember(ClassBuilder owner, MemberDecl member) { + owner.Members.RemoveAll(m => m.Name == member.Name); + owner.Members.Add(member); + } + + private static MemberDecl MakeMember(string name, LuaType type, string doc, string? unit, bool isMethod, + EquatableArray generics, EquatableArray overloads, SourceLocation location) { + if (type is FunctionType { Params.Count: > 0 } fn && fn.Params[0].Name == "self") { + isMethod = true; + type = fn with { Params = fn.Params.Skip(1).ToList() }; + } + return new MemberDecl(name, type, doc, unit, isMethod, generics, overloads, location); + } + + private static FunctionType BuildFunction(AnnotationBlock block, string paramList) { + var tags = block.Tags.OfType().ToList(); + var parameters = new List(); + LuaType? vararg = null; + foreach (var raw in paramList.Split(',')) { + var name = raw.Trim(); + if (name.Length == 0) continue; + var tag = tags.FirstOrDefault(t => t.Name == name); + if (name == "...") vararg = tag?.Type ?? LuaType.Any; + else parameters.Add(new Param(name, tag?.Type ?? LuaType.Any, tag?.Optional ?? false)); + } + + var returns = new List(); + LuaType? varargReturn = null; + foreach (var r in block.Tags.OfType()) { + if (r.Vararg) varargReturn = r.Type; + else returns.Add(r.Type); + } + return new FunctionType(parameters, returns, vararg, varargReturn); + } + + private static string? Unit(AnnotationBlock block) => block.Tags.OfType().FirstOrDefault()?.Unit; + + private static EquatableArray Generics(AnnotationBlock block) + => block.Tags.OfType().SelectMany(g => g.Params).DistinctBy(g => g.Name).ToList(); + + private static EquatableArray Overloads(AnnotationBlock block) + => block.Tags.OfType() + .Select(o => o.Signature is { Params.Count: > 0 } fn && fn.Params[0].Name == "self" + ? fn with { Params = fn.Params.Skip(1).ToList() } + : o.Signature) + .ToList(); + + private int ReadEnum(EnumTag tag, string tableName, string doc, int blockStart, int subjectIndex) { + var members = new List<(string, object?)>(); + var i = subjectIndex; + var line = m_lines[i]; + var body = line[(line.IndexOf('{') + 1)..]; + while (true) { + var close = body.IndexOf('}'); + foreach (var part in (close >= 0 ? body[..close] : body).Split(',')) { + if (EnumEntry().Match(part) is { Success: true } e) members.Add((e.Groups[1].Value, ParseValue(e.Groups[2].Value))); + } + if (close >= 0 || ++i >= m_lines.Length) break; + body = m_lines[i]; + } + m_enums.Add(new EnumDecl(tag.Name, tableName, members, doc, At(blockStart))); + return i + 1; + } + + private static object? ParseValue(string value) { + value = value.Trim(); + if (long.TryParse(value, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out var l)) return l; + if (double.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out var d)) return d; + if (value.Length >= 2 && value[0] is '"' or '\'' && value[^1] == value[0]) return value[1..^1]; + if (value is "true" or "false") return value == "true"; + return null; + } + } +} diff --git a/editor/LuaEditor/Types/EquatableArray.cs b/editor/LuaEditor/Types/EquatableArray.cs new file mode 100644 index 000000000..65dca9075 --- /dev/null +++ b/editor/LuaEditor/Types/EquatableArray.cs @@ -0,0 +1,46 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.CompilerServices; + +namespace editor.LuaEditor.Types; + +// type records need collection equality by value +[CollectionBuilder(typeof(EquatableArray), nameof(EquatableArray.Create))] +public readonly struct EquatableArray : IReadOnlyList, IEquatable> { + private readonly T[]? m_items; + + public EquatableArray(T[] items) { + m_items = items; + } + + private T[] Items => m_items ?? []; + + public int Count => Items.Length; + public T this[int index] => Items[index]; + + public static implicit operator EquatableArray(T[] items) => new(items); + public static implicit operator EquatableArray(List items) => new(items.ToArray()); + + public bool Equals(EquatableArray other) => Items.AsSpan().SequenceEqual(other.Items, EqualityComparer.Default); + public override bool Equals(object? obj) => obj is EquatableArray other && Equals(other); + + public override int GetHashCode() { + var hash = new HashCode(); + foreach (var item in Items) hash.Add(item); + return hash.ToHashCode(); + } + + public static bool operator ==(EquatableArray a, EquatableArray b) => a.Equals(b); + public static bool operator !=(EquatableArray a, EquatableArray b) => !a.Equals(b); + + public IEnumerator GetEnumerator() => ((IEnumerable)Items).GetEnumerator(); + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + + public override string ToString() => $"[{string.Join(", ", Items.Select(i => i?.ToString()))}]"; +} + +public static class EquatableArray { + public static EquatableArray Create(ReadOnlySpan items) => new(items.ToArray()); +} diff --git a/editor/LuaEditor/Types/LuaRc.cs b/editor/LuaEditor/Types/LuaRc.cs new file mode 100644 index 000000000..75846e9e4 --- /dev/null +++ b/editor/LuaEditor/Types/LuaRc.cs @@ -0,0 +1,62 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text.Json; + +namespace editor.LuaEditor.Types; + +public sealed record LuaRc(string RuntimeVersion, EquatableArray Libraries) { + public const string SupportedVersion = "Lua 5.4"; + + private static readonly JsonDocumentOptions s_options = new() { + CommentHandling = JsonCommentHandling.Skip, + AllowTrailingCommas = true, + }; + + public static LuaRc Load(string projectRoot, List diagnostics) { + var path = Path.Combine(projectRoot, ".luarc.json"); + var at = new SourceLocation(path, 1); + if (!File.Exists(path)) { + diagnostics.Add(new Diagnostic(DiagnosticSeverity.Info, "no .luarc.json; only the standard library is loaded", at)); + return new LuaRc(SupportedVersion, []); + } + + JsonDocument doc; + try { + doc = JsonDocument.Parse(File.ReadAllText(path), s_options); + } catch (JsonException e) { + diagnostics.Add(new Diagnostic(DiagnosticSeverity.Error, $".luarc.json is not valid JSON: {e.Message}", at)); + return new LuaRc(SupportedVersion, []); + } catch (Exception e) when (e is IOException or UnauthorizedAccessException) { + diagnostics.Add(new Diagnostic(DiagnosticSeverity.Error, $"cannot read .luarc.json: {e.Message}", at)); + return new LuaRc(SupportedVersion, []); + } + + using (doc) { + var root = doc.RootElement; + var version = Setting(root, "runtime", "version") is { ValueKind: JsonValueKind.String } v ? v.GetString()! : SupportedVersion; + if (version != SupportedVersion) + diagnostics.Add(new Diagnostic(DiagnosticSeverity.Warning, $"runtime.version is \"{version}\"; the graph editor checks against {SupportedVersion}", at)); + + var libraries = new List(); + if (Setting(root, "workspace", "library") is { ValueKind: JsonValueKind.Array } list) { + foreach (var entry in list.EnumerateArray()) { + if (entry.ValueKind != JsonValueKind.String) continue; + var full = Path.GetFullPath(Path.Combine(projectRoot, entry.GetString()!)); + libraries.Add(full); + if (!Directory.Exists(full) && !File.Exists(full)) + diagnostics.Add(new Diagnostic(DiagnosticSeverity.Warning, $"workspace.library entry \"{entry.GetString()}\" does not exist", at)); + } + } + return new LuaRc(version, libraries); + } + } + + private static JsonElement? Setting(JsonElement root, string section, string key) { + if (root.ValueKind != JsonValueKind.Object) return null; + if (root.TryGetProperty($"{section}.{key}", out var dotted)) return dotted; + if (root.TryGetProperty(section, out var nested) && nested.ValueKind == JsonValueKind.Object && nested.TryGetProperty(key, out var value)) + return value; + return null; + } +} diff --git a/editor/LuaEditor/Types/LuaType.cs b/editor/LuaEditor/Types/LuaType.cs new file mode 100644 index 000000000..84e0e5496 --- /dev/null +++ b/editor/LuaEditor/Types/LuaType.cs @@ -0,0 +1,53 @@ +using System.Collections.Generic; + +namespace editor.LuaEditor.Types; + +public enum PrimitiveKind { Nil, Boolean, Number, Integer, String, Table, Function, Thread, Userdata, Any, Unknown } + +public abstract record LuaType { + public static readonly LuaType Nil = new PrimitiveType(PrimitiveKind.Nil); + public static readonly LuaType Boolean = new PrimitiveType(PrimitiveKind.Boolean); + public static readonly LuaType Number = new PrimitiveType(PrimitiveKind.Number); + public static readonly LuaType Integer = new PrimitiveType(PrimitiveKind.Integer); + public static readonly LuaType String = new PrimitiveType(PrimitiveKind.String); + public static readonly LuaType Table = new PrimitiveType(PrimitiveKind.Table); + public static readonly LuaType Function = new PrimitiveType(PrimitiveKind.Function); + public static readonly LuaType Any = new PrimitiveType(PrimitiveKind.Any); + public static readonly LuaType Unknown = new PrimitiveType(PrimitiveKind.Unknown); + + public static LuaType Union(params LuaType[] members) { + var flat = new List(); + foreach (var member in members) Add(flat, member); + return flat.Count == 1 ? flat[0] : new UnionType(flat); + + static void Add(List into, LuaType type) { + if (type is UnionType union) { + foreach (var inner in union.Members) Add(into, inner); + } else if (!into.Contains(type)) { + into.Add(type); + } + } + } + + public static LuaType Optional(LuaType type) => Union(type, Nil); + + public sealed override string ToString() => TypeFormatter.Format(this); +} + +public sealed record PrimitiveType(PrimitiveKind Kind) : LuaType; + +public sealed record LiteralType(object Value) : LuaType; + +public sealed record ArrayType(LuaType Element) : LuaType; + +public sealed record TableType(LuaType Key, LuaType Value) : LuaType; + +public sealed record Param(string Name, LuaType Type, bool Optional); + +public sealed record FunctionType(EquatableArray Params, EquatableArray Returns, LuaType? VarargParam, LuaType? VarargReturn) : LuaType; + +public sealed record UnionType(EquatableArray Members) : LuaType; + +public sealed record NamedType(string Name, EquatableArray Args) : LuaType; + +public sealed record CaptureType(string Name) : LuaType; diff --git a/editor/LuaEditor/Types/TypeChecker.cs b/editor/LuaEditor/Types/TypeChecker.cs new file mode 100644 index 000000000..f8f65587a --- /dev/null +++ b/editor/LuaEditor/Types/TypeChecker.cs @@ -0,0 +1,188 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace editor.LuaEditor.Types; + +public enum Compat { Allowed = 0, Warning = 1, Blocked = 2 } + +public readonly record struct CompatResult(Compat Kind, string? Reason) { + public static readonly CompatResult Ok = new(Compat.Allowed, null); + + public static CompatResult Worst(CompatResult a, CompatResult b) => b.Kind > a.Kind ? b : a; + public static CompatResult Best(CompatResult a, CompatResult b) => b.Kind < a.Kind ? b : a; + + public static CompatResult Warn(string reason) => new(Compat.Warning, reason); + public static CompatResult Block(string reason) => new(Compat.Blocked, reason); +} + +public sealed class TypeChecker(TypeUniverse universe) { + public CompatResult Check(LuaType source, LuaType target) + => CheckResolved(universe.ResolveAliases(source), universe.ResolveAliases(target)); + + private CompatResult CheckResolved(LuaType s, LuaType t) { + if (IsAny(s) || IsAny(t) || IsUnknownName(s) || IsUnknownName(t)) return CompatResult.Ok; + + if (s is UnionType su) { + if (su.Members.Any(IsAny)) return CompatResult.Ok; + if (su.Members.Contains(LuaType.Nil) && !AcceptsNil(t)) { + var rest = LuaType.Union(su.Members.Where(m => m != LuaType.Nil).ToArray()); + var r = CheckResolved(rest, t); + return r.Kind == Compat.Allowed ? CompatResult.Warn($"{s} may be nil but {t} cannot be") : r; + } + return su.Members.Select(m => CheckResolved(m, t)).Aggregate(CompatResult.Ok, CompatResult.Worst); + } + + if (t is UnionType tu) { + var results = tu.Members.Select(m => CheckResolved(s, m)).ToList(); + var best = results.Aggregate(CompatResult.Block(""), CompatResult.Best); + if (best.Kind != Compat.Blocked) return best; + var advice = results.FirstOrDefault(r => r.Reason?.Contains("---@cast", StringComparison.Ordinal) == true); + return advice.Reason is not null ? advice : Cannot(s, t); + } + + if (s is LiteralType ls) return CheckLiteral(ls, t); + + if (t is LiteralType lt) { + return CheckResolved(s, PrimitiveOf(lt)).Kind == Compat.Allowed + ? CompatResult.Warn($"{s} is not checked against the allowed value {t}") + : Cannot(s, t); + } + + if (EnumOf(t) is { } targetEnum) { + return EnumOf(s) is { } sameEnum && sameEnum.Name == targetEnum.Name ? CompatResult.Ok : Cannot(s, t); + } + if (EnumOf(s) is { } sourceEnum) return CheckResolved(EnumValueType(sourceEnum), t); + + return (s, t) switch { + (PrimitiveType ps, PrimitiveType pt) => CheckPrimitives(ps, pt), + (_, PrimitiveType { Kind: PrimitiveKind.Table }) when s is ArrayType or TableType or NamedType => CompatResult.Ok, + (PrimitiveType { Kind: PrimitiveKind.Table }, NamedType or ArrayType or TableType) => CompatResult.Ok, + (FunctionType, PrimitiveType { Kind: PrimitiveKind.Function }) => CompatResult.Ok, + (NamedType ns, NamedType nt) => CheckClasses(ns, nt), + (ArrayType sa, ArrayType ta) => CheckResolved(sa.Element, ta.Element), + (TableType st, TableType tt) => CompatResult.Worst(CheckResolved(st.Key, tt.Key), CheckResolved(st.Value, tt.Value)), + (ArrayType sa, TableType tt) => CompatResult.Worst(CheckResolved(LuaType.Integer, tt.Key), CheckResolved(sa.Element, tt.Value)), + (FunctionType sf, FunctionType tf) => CheckFunctions(sf, tf), + (PrimitiveType { Kind: PrimitiveKind.Function }, FunctionType) => CompatResult.Warn($"the signature of this function is unknown, expected {t}"), + _ => Cannot(s, t), + }; + } + + private bool IsUnknownName(LuaType type) + => type is NamedType n && universe.FindClass(n.Name) is null && universe.FindAlias(n.Name) is null && universe.FindEnum(n.Name) is null; + + private static bool IsAny(LuaType type) => type is PrimitiveType { Kind: PrimitiveKind.Any or PrimitiveKind.Unknown }; + + private static bool AcceptsNil(LuaType type) + => type == LuaType.Nil || IsAny(type) || (type is UnionType u && u.Members.Any(m => m == LuaType.Nil || IsAny(m))); + + private static CompatResult Cannot(LuaType s, LuaType t) => CompatResult.Block($"{s} cannot connect to {t}"); + + private static LuaType PrimitiveOf(LiteralType literal) => literal.Value switch { + string => LuaType.String, + long => LuaType.Integer, + bool => LuaType.Boolean, + _ => LuaType.Number, + }; + + private CompatResult CheckLiteral(LiteralType s, LuaType t) { + if (t is LiteralType lt) return Equals(s.Value, lt.Value) ? CompatResult.Ok : Cannot(s, t); + if (EnumOf(t) is { } e) return e.Members.Any(m => Equals(m.Value, s.Value)) ? CompatResult.Ok : Cannot(s, t); + var r = CheckResolved(PrimitiveOf(s), t); + return r.Kind == Compat.Allowed ? r : Cannot(s, t); + } + + private EnumDecl? EnumOf(LuaType type) + => type is NamedType { Args.Count: 0 } n && universe.FindClass(n.Name) is null ? universe.FindEnum(n.Name) : null; + + private static LuaType EnumValueType(EnumDecl e) { + var kinds = e.Members.Select(m => m.Value switch { + string => LuaType.String, + long => LuaType.Integer, + bool => LuaType.Boolean, + null => LuaType.Any, + _ => LuaType.Number, + }).Distinct().ToArray(); + return kinds.Length == 0 ? LuaType.Integer : LuaType.Union(kinds); + } + + private static CompatResult CheckPrimitives(PrimitiveType s, PrimitiveType t) { + if (s.Kind == t.Kind) return CompatResult.Ok; + if (s.Kind == PrimitiveKind.Integer && t.Kind == PrimitiveKind.Number) return CompatResult.Ok; + if (s.Kind == PrimitiveKind.Number && t.Kind == PrimitiveKind.Integer) + return CompatResult.Block("number cannot connect to integer; round it first (math.floor)"); + return Cannot(s, t); + } + + private CompatResult CheckClasses(NamedType s, NamedType t) { + if (s.Name == t.Name) { + if (t.Args.Count == 0 || s.Args.Count == 0) return CompatResult.Ok; + var same = s.Args.Count == t.Args.Count + && s.Args.Zip(t.Args).All(p => universe.ResolveAliases(p.First) == universe.ResolveAliases(p.Second)); + return same ? CompatResult.Ok : CompatResult.Block($"{s} cannot connect to {t}: the type arguments differ"); + } + if (universe.IsSubclassOf(s.Name, t.Name)) return CompatResult.Ok; + if (universe.FindClass(s.Name) is not null && universe.IsSubclassOf(t.Name, s.Name)) + return CompatResult.Block($"{s} is not always a {t}; use a ---@cast node"); + return Cannot(s, t); + } + + private CompatResult CheckFunctions(FunctionType s, FunctionType t) { + var result = CompatResult.Ok; + for (var i = 0; i < s.Params.Count; i++) { + if (i < t.Params.Count) { + result = CompatResult.Worst(result, CheckResolved(t.Params[i].Type, s.Params[i].Type)); + } else if (t.VarargParam is { } vararg) { + result = CompatResult.Worst(result, CheckResolved(vararg, s.Params[i].Type)); + } else if (!s.Params[i].Optional) { + return CompatResult.Block($"{s} needs more arguments than {t} passes"); + } + } + for (var i = 0; i < t.Returns.Count; i++) { + if (i < s.Returns.Count) result = CompatResult.Worst(result, CheckResolved(s.Returns[i], t.Returns[i])); + else if (s.VarargReturn is { } vret) result = CompatResult.Worst(result, CheckResolved(vret, t.Returns[i])); + else return CompatResult.Block($"{s} returns fewer values than {t}"); + } + return result; + } + + public LuaType NarrowNonNil(LuaType type) { + type = universe.ResolveAliases(type); + return type is UnionType u ? LuaType.Union(u.Members.Where(m => m != LuaType.Nil).ToArray()) : type; + } + + public LuaType NarrowToTypeName(LuaType type, string luaTypeName) { + type = universe.ResolveAliases(type); + if (IsAny(type)) return PrimitiveForName(luaTypeName); + var members = type is UnionType u ? u.Members.ToArray() : [type]; + var kept = members.Where(m => IsAny(m) || TypeNamesOf(m).Contains(luaTypeName)) + .Select(m => IsAny(m) ? PrimitiveForName(luaTypeName) : m).ToArray(); + return kept.Length == 0 ? LuaType.Unknown : LuaType.Union(kept); + } + + private static LuaType PrimitiveForName(string name) => name switch { + "nil" => LuaType.Nil, + "boolean" => LuaType.Boolean, + "number" => LuaType.Number, + "string" => LuaType.String, + "table" => LuaType.Table, + "function" => LuaType.Function, + "userdata" => new PrimitiveType(PrimitiveKind.Userdata), + "thread" => new PrimitiveType(PrimitiveKind.Thread), + _ => LuaType.Unknown, + }; + + private IEnumerable TypeNamesOf(LuaType type) => type switch { + PrimitiveType { Kind: PrimitiveKind.Integer or PrimitiveKind.Number } => ["number"], + PrimitiveType p => [p.Kind.ToString().ToLowerInvariant()], + LiteralType { Value: string } => ["string"], + LiteralType { Value: bool } => ["boolean"], + LiteralType => ["number"], + ArrayType or TableType => ["table"], + FunctionType => ["function"], + NamedType n when EnumOf(n) is { } e => TypeNamesOf(EnumValueType(e)), + NamedType => ["table", "userdata"], + _ => [], + }; +} diff --git a/editor/LuaEditor/Types/TypeExprParser.cs b/editor/LuaEditor/Types/TypeExprParser.cs new file mode 100644 index 000000000..f173ac4e5 --- /dev/null +++ b/editor/LuaEditor/Types/TypeExprParser.cs @@ -0,0 +1,331 @@ +using System; +using System.Collections.Generic; +using System.Globalization; + +namespace editor.LuaEditor.Types; + +public sealed class TypeSyntaxException(string message, int position) : Exception(message) { + public int Position { get; } = position; +} + +public static class TypeExprParser { + public static LuaType Parse(string text) { + var cursor = new Cursor(text, 0); + var type = cursor.ParseUnion(); + cursor.SkipWhitespace(); + if (!cursor.AtEnd) throw new TypeSyntaxException($"unexpected '{text[cursor.Pos]}' after type", cursor.Pos); + return type; + } + + public static bool TryParsePrefix(string text, int start, out LuaType type, out int end, out string? error) { + try { + var cursor = new Cursor(text, start); + type = cursor.ParseUnion(); + end = cursor.Pos; + error = null; + return true; + } catch (TypeSyntaxException e) { + type = LuaType.Unknown; + end = start; + error = e.Message; + return false; + } + } + + private static PrimitiveKind? PrimitiveOf(string name) => name switch { + "nil" => PrimitiveKind.Nil, + "boolean" => PrimitiveKind.Boolean, + "number" => PrimitiveKind.Number, + "integer" => PrimitiveKind.Integer, + "string" => PrimitiveKind.String, + "table" => PrimitiveKind.Table, + "function" => PrimitiveKind.Function, + "thread" => PrimitiveKind.Thread, + "userdata" or "lightuserdata" => PrimitiveKind.Userdata, + "any" => PrimitiveKind.Any, + "unknown" => PrimitiveKind.Unknown, + _ => null, + }; + + private sealed class Cursor(string text, int pos) { + public int Pos = pos; + public bool AtEnd => Pos >= text.Length; + private char Peek(int offset = 0) => Pos + offset < text.Length ? text[Pos + offset] : '\0'; + + public void SkipWhitespace() { + while (!AtEnd && char.IsWhiteSpace(text[Pos])) Pos++; + } + + private TypeSyntaxException Error(string message) => new(message, Pos); + + private void Expect(char c) { + SkipWhitespace(); + if (Peek() != c) throw Error(AtEnd ? $"expected '{c}' but the type ended" : $"expected '{c}' but found '{Peek()}'"); + Pos++; + } + + private bool StartsWith(string s) => string.CompareOrdinal(text, Pos, s, 0, s.Length) == 0; + + public LuaType ParseUnion() { + var members = new List { ParsePostfix() }; + while (true) { + var save = Pos; + SkipWhitespace(); + if (Peek() != '|') { + Pos = save; + break; + } + Pos++; + members.Add(ParsePostfix()); + } + return members.Count == 1 ? members[0] : LuaType.Union(members.ToArray()); + } + + private LuaType ParsePostfix() { + var type = ParsePrimary(); + while (true) { + // spaces distinguish documentation brackets from array suffixes + if (Peek() == '[' && Peek(1) == ']') { + Pos += 2; + type = new ArrayType(type); + } else if (Peek() == '?') { + Pos++; + type = LuaType.Optional(type); + } else { + return type; + } + } + } + + private LuaType ParsePrimary() { + SkipWhitespace(); + if (AtEnd) throw Error("expected a type but the text ended"); + var c = Peek(); + switch (c) { + case '"' or '\'': + return new LiteralType(ReadString(c)); + case '(': { + Pos++; + var inner = ParseUnion(); + // one pin cannot carry several return values + SkipWhitespace(); + while (Peek() == ',') { + Pos++; + ParseUnion(); + SkipWhitespace(); + } + Expect(')'); + return inner; + } + case '`': { + Pos++; + var start = Pos; + while (!AtEnd && Peek() != '`') Pos++; + if (AtEnd) throw Error("unterminated `name`"); + var name = text[start..Pos]; + Pos++; + return new CaptureType(name); + } + case '{': + SkipBalanced('{', '}'); + return LuaType.Table; + } + if (char.IsDigit(c) || (c == '-' && char.IsDigit(Peek(1)))) return ReadNumber(); + if (!IsNameStart(c)) throw Error($"unexpected '{c}'"); + + var nameStart = Pos; + var word = ReadName(); + switch (word) { + case "async": { + SkipWhitespace(); + if (!StartsWith("fun")) throw Error("expected 'fun' after 'async'"); + Pos += 3; + return ParseFunction(); + } + case "fun": + return ParseFunction(); + case "true": + return new LiteralType(true); + case "false": + return new LiteralType(false); + case "table" when Peek() == '<': { + Pos++; + var key = ParseUnion(); + Expect(','); + var value = ParseUnion(); + Expect('>'); + return new TableType(key, value); + } + } + if (PrimitiveOf(word) is { } kind) return new PrimitiveType(kind); + if (word.EndsWith('.')) { + Pos = nameStart; + throw Error($"bad type name '{word}'"); + } + + var args = new List(); + if (Peek() == '<') { + Pos++; + args.Add(ParseUnion()); + while (true) { + SkipWhitespace(); + if (Peek() == ',') { + Pos++; + args.Add(ParseUnion()); + continue; + } + Expect('>'); + break; + } + } + return new NamedType(word, args); + } + + private LuaType ParseFunction() { + Expect('('); + var parameters = new List(); + LuaType? varargParam = null; + SkipWhitespace(); + if (Peek() != ')') { + while (true) { + SkipWhitespace(); + if (StartsWith("...")) { + Pos += 3; + SkipWhitespace(); + if (Peek() == ':') { + Pos++; + varargParam = ParseUnion(); + } else { + varargParam = LuaType.Any; + } + } else { + parameters.Add(ParseParam()); + } + SkipWhitespace(); + if (Peek() == ',') { + Pos++; + continue; + } + break; + } + } + Expect(')'); + + var returns = new List(); + LuaType? varargReturn = null; + var save = Pos; + SkipWhitespace(); + if (Peek() != ':') { + Pos = save; + return new FunctionType(parameters, returns, varargParam, null); + } + Pos++; + while (true) { + SkipWhitespace(); + if (StartsWith("...")) { + Pos += 3; + varargReturn = LuaType.Any; + break; + } + var type = ParseUnion(); + var afterType = Pos; + SkipWhitespace(); + if (StartsWith("...")) { + Pos += 3; + varargReturn = type; + break; + } + returns.Add(type); + if (Peek() == ',') { + var comma = Pos; + Pos++; + if (NamedParamAhead()) { + Pos = comma; + break; + } + continue; + } + Pos = afterType; + break; + } + return new FunctionType(parameters, returns, varargParam, varargReturn); + } + + private bool NamedParamAhead() { + var save = Pos; + SkipWhitespace(); + var found = false; + if (StartsWith("...")) { + Pos += 3; + SkipWhitespace(); + found = Peek() == ':'; + } else if (IsNameStart(Peek())) { + ReadName(); + if (Peek() == '?') Pos++; + SkipWhitespace(); + found = Peek() == ':'; + } + Pos = save; + return found; + } + + private Param ParseParam() { + var start = Pos; + if (IsNameStart(Peek())) { + var name = ReadName(); + var optional = false; + if (Peek() == '?') { + optional = true; + Pos++; + } + SkipWhitespace(); + if (Peek() == ':') { + Pos++; + return new Param(name, ParseUnion(), optional); + } + } + Pos = start; + return new Param("", ParseUnion(), false); + } + + private static bool IsNameStart(char c) => char.IsLetter(c) || c == '_'; + + private string ReadName() { + var start = Pos; + while (!AtEnd && (char.IsLetterOrDigit(Peek()) || Peek() == '_' || (Peek() == '.' && IsNameStart(Peek(1))))) Pos++; + return text[start..Pos]; + } + + private string ReadString(char quote) { + Pos++; + var sb = new System.Text.StringBuilder(); + while (true) { + if (AtEnd) throw Error("unterminated string literal"); + var c = text[Pos++]; + if (c == quote) return sb.ToString(); + if (c == '\\' && !AtEnd) c = text[Pos++]; + sb.Append(c); + } + } + + private LuaType ReadNumber() { + var start = Pos; + if (Peek() == '-') Pos++; + while (!AtEnd && (char.IsDigit(Peek()) || Peek() == '.')) Pos++; + var s = text[start..Pos]; + if (long.TryParse(s, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out var l)) return new LiteralType(l); + if (double.TryParse(s, NumberStyles.Float, CultureInfo.InvariantCulture, out var d)) return new LiteralType(d); + throw Error($"bad number '{s}'"); + } + + private void SkipBalanced(char open, char close) { + var depth = 0; + do { + if (AtEnd) throw Error($"unbalanced '{open}'"); + var c = text[Pos++]; + if (c == open) depth++; + else if (c == close) depth--; + } while (depth > 0); + } + } +} diff --git a/editor/LuaEditor/Types/TypeFormatter.cs b/editor/LuaEditor/Types/TypeFormatter.cs new file mode 100644 index 000000000..af0a6363b --- /dev/null +++ b/editor/LuaEditor/Types/TypeFormatter.cs @@ -0,0 +1,100 @@ +using System; +using System.Globalization; +using System.Linq; +using System.Text; + +namespace editor.LuaEditor.Types; + +public static class TypeFormatter { + public static string Format(LuaType type) { + var sb = new StringBuilder(); + Write(sb, type); + return sb.ToString(); + } + + public static string Display(LuaType type) { + if (type is not UnionType u || !u.Members.Any(m => m is PrimitiveType { Kind: PrimitiveKind.Nil })) return Format(type); + var rest = u.Members.Where(m => m is not PrimitiveType { Kind: PrimitiveKind.Nil }).ToList(); + if (rest.Count == 0) return "nil"; + var text = string.Join("|", rest.Select(Format)); + return (rest.Count > 1 || rest[0] is FunctionType ? "(" + text + ")" : text) + "?"; + } + + private static void Write(StringBuilder sb, LuaType type) { + + switch (type) { + case PrimitiveType p: + sb.Append(p.Kind.ToString().ToLowerInvariant()); + break; + case LiteralType { Value: string s }: + sb.Append('"').Append(s.Replace("\\", "\\\\").Replace("\"", "\\\"")).Append('"'); + break; + case LiteralType { Value: bool b }: + sb.Append(b ? "true" : "false"); + break; + case LiteralType l: + sb.Append(Convert.ToString(l.Value, CultureInfo.InvariantCulture)); + break; + case ArrayType a: + WriteWrapped(sb, a.Element, a.Element is UnionType or FunctionType); + sb.Append("[]"); + break; + case TableType t: + sb.Append("table<"); + Write(sb, t.Key); + sb.Append(", "); + Write(sb, t.Value); + sb.Append('>'); + break; + case UnionType u: + for (var i = 0; i < u.Members.Count; i++) { + if (i > 0) sb.Append('|'); + // parentheses keep union members out of the return type + WriteWrapped(sb, u.Members[i], u.Members[i] is FunctionType && i < u.Members.Count - 1); + } + break; + case NamedType n: + sb.Append(n.Name); + if (n.Args.Count > 0) { + sb.Append('<'); + for (var i = 0; i < n.Args.Count; i++) { + if (i > 0) sb.Append(", "); + Write(sb, n.Args[i]); + } + sb.Append('>'); + } + break; + case CaptureType c: + sb.Append('`').Append(c.Name).Append('`'); + break; + case FunctionType f: + WriteFunction(sb, f); + break; + default: + throw new ArgumentOutOfRangeException(nameof(type), type.GetType().Name, "unknown LuaType"); + } + } + + private static void WriteWrapped(StringBuilder sb, LuaType type, bool wrap) { + if (wrap) sb.Append('('); + Write(sb, type); + if (wrap) sb.Append(')'); + } + + private static void WriteFunction(StringBuilder sb, FunctionType f) { + sb.Append("fun("); + var parts = f.Params.Select(p => { + if (p.Name.Length == 0) return Format(p.Type); + return $"{p.Name}{(p.Optional ? "?" : "")}: {Format(p.Type)}"; + }).ToList(); + if (f.VarargParam is { } vararg) parts.Add(vararg == LuaType.Any ? "..." : $"...: {Format(vararg)}"); + sb.Append(string.Join(", ", parts)).Append(')'); + + var returns = f.Returns.Select(r => WrapReturn(r)).ToList(); + if (f.VarargReturn is { } vret) returns.Add(vret == LuaType.Any ? "..." : $"{WrapReturn(vret)} ..."); + if (returns.Count > 0) sb.Append(": ").Append(string.Join(", ", returns)); + } + + // parentheses keep later returns out of the nested signature + private static string WrapReturn(LuaType type) => type is FunctionType ? $"({Format(type)})" : Format(type); +} diff --git a/editor/LuaEditor/Types/TypeUniverse.cs b/editor/LuaEditor/Types/TypeUniverse.cs new file mode 100644 index 000000000..9e93331f3 --- /dev/null +++ b/editor/LuaEditor/Types/TypeUniverse.cs @@ -0,0 +1,217 @@ +using System.Collections.Generic; +using System.Linq; + +namespace editor.LuaEditor.Types; + +public sealed record ClassInfo(string Name, EquatableArray Generics, EquatableArray Bases, + EquatableArray Members, string Doc, EquatableArray Operators = default); + +public sealed record MemberInfo(MemberDecl Decl, string DeclaringClass); + +public sealed class TypeUniverse { + private readonly Dictionary m_classes; + private readonly Dictionary m_aliases; + private readonly Dictionary m_enums; + private readonly Dictionary m_globals; + private readonly Dictionary> m_memberCache = []; + private readonly List m_files; + + private TypeUniverse(List files, Dictionary classes, Dictionary aliases, + Dictionary enums, Dictionary globals, List diagnostics) { + m_files = files; + m_classes = classes; + m_aliases = aliases; + m_enums = enums; + m_globals = globals; + Diagnostics = diagnostics; + } + + public IReadOnlyList Diagnostics { get; } + public IEnumerable Classes => m_classes.Values; + public IEnumerable Globals => m_globals.Values; + + public ClassInfo? FindClass(string name) => m_classes.GetValueOrDefault(name); + public AliasDecl? FindAlias(string name) => m_aliases.GetValueOrDefault(name); + public EnumDecl? FindEnum(string name) => m_enums.GetValueOrDefault(name); + public LuaType? GlobalType(string name) => m_globals.GetValueOrDefault(name)?.Type; + + public GlobalDecl? GlobalDeclOf(string name) => m_globals.GetValueOrDefault(name); + + public IEnumerable Enums => m_enums.Values; + + public TypeUniverse Extend(DeclarationFile extra) => Build(m_files.Append(extra)); + + public static TypeUniverse Build(IEnumerable input) { + var files = input.ToList(); + var diagnostics = new List(); + var classes = new Dictionary Generics, List Bases, List Members, List Operators)>(); + var order = new List(); + var aliases = new Dictionary(); + var enums = new Dictionary(); + var globals = new Dictionary(); + var redirects = new List<(string From, string Into)>(); + + foreach (var file in files) { + diagnostics.AddRange(file.Diagnostics); + foreach (var decl in file.Classes) { + if (!classes.TryGetValue(decl.Name, out var entry)) { + entry = (decl, [], [], [], []); + classes[decl.Name] = entry; + order.Add(decl.Name); + } + foreach (var g in decl.Generics) if (entry.Generics.All(existing => existing.Name != g.Name)) entry.Generics.Add(g); + foreach (var b in decl.Bases) if (!entry.Bases.Contains(b)) entry.Bases.Add(b); + foreach (var op in decl.Operators) if (!entry.Operators.Contains(op)) entry.Operators.Add(op); + foreach (var member in decl.Members) { + var existing = entry.Members.FindIndex(m => m.Name == member.Name); + if (existing < 0) { + entry.Members.Add(member); + continue; + } + diagnostics.Add(new Diagnostic(DiagnosticSeverity.Info, + $"{decl.Name}.{member.Name} is declared again; the later declaration wins", member.Location)); + entry.Members[existing] = member; + } + } + foreach (var alias in file.Aliases) aliases[alias.Name] = alias; + foreach (var e in file.Enums) enums[e.Name] = e; + foreach (var g in file.Globals) { + if (globals.TryGetValue(g.Name, out var existing) && ImplicitRedirect(existing, g) is var (from, into, kept)) { + redirects.Add((from, into)); + globals[g.Name] = kept; + } else { + globals[g.Name] = g; + } + } + } + + // library globals may use a different name from their class + foreach (var (from, into) in redirects) { + if (from == into || !classes.TryGetValue(from, out var source) || !classes.TryGetValue(into, out var target)) continue; + foreach (var member in source.Members) + if (target.Members.All(m => m.Name != member.Name)) target.Members.Add(member); + classes.Remove(from); + order.Remove(from); + } + + foreach (var name in order) { + var entry = classes[name]; + entry.Bases.RemoveAll(b => { + if (b is NamedType nt && classes.ContainsKey(nt.Name)) return false; + if (b is NamedType unknown) + diagnostics.Add(new Diagnostic(DiagnosticSeverity.Warning, $"{name} derives from unknown class {unknown.Name}", entry.First.Location)); + return true; + }); + } + + var state = new Dictionary(); + foreach (var name in order) Visit(name); + + void Visit(string name) { + if (state.GetValueOrDefault(name) != 0) return; + state[name] = 1; + var entry = classes[name]; + foreach (var b in entry.Bases.ToList()) { + var baseName = ((NamedType)b).Name; + if (state.GetValueOrDefault(baseName) == 1) { + diagnostics.Add(new Diagnostic(DiagnosticSeverity.Error, $"inheritance cycle: {name} derives from {baseName}", entry.First.Location)); + entry.Bases.Remove(b); + continue; + } + Visit(baseName); + } + state[name] = 2; + } + + var infos = order.ToDictionary(n => n, n => { + var e = classes[n]; + return new ClassInfo(n, e.Generics, e.Bases, e.Members, e.First.Doc, e.Operators); + }); + return new TypeUniverse(files, infos, aliases, enums, globals, diagnostics); + } + + private static (string From, string Into, GlobalDecl Kept)? ImplicitRedirect(GlobalDecl existing, GlobalDecl incoming) { + if (existing.Type is not NamedType { Args.Count: 0 } a || incoming.Type is not NamedType { Args.Count: 0 } b || a.Name == b.Name) return null; + if (b.Name == incoming.Name) return (b.Name, a.Name, existing); + if (a.Name == existing.Name) return (a.Name, b.Name, incoming); + return null; + } + + public bool IsSubclassOf(string derived, string baseName) { + if (derived == baseName) return true; + var seen = new HashSet(); + var queue = new Queue(); + queue.Enqueue(derived); + while (queue.Count > 0) { + var current = queue.Dequeue(); + if (!seen.Add(current) || !m_classes.TryGetValue(current, out var info)) continue; + foreach (var b in info.Bases) { + var name = ((NamedType)b).Name; + if (name == baseName) return true; + queue.Enqueue(name); + } + } + return false; + } + + public IReadOnlyList MembersOf(string className) { + if (m_memberCache.TryGetValue(className, out var cached)) return cached; + var result = new List(); + var names = new HashSet(); + var seen = new HashSet(); + var queue = new Queue(); + queue.Enqueue(className); + while (queue.Count > 0) { + var current = queue.Dequeue(); + if (!seen.Add(current) || !m_classes.TryGetValue(current, out var info)) continue; + foreach (var member in info.Members) + if (names.Add(member.Name)) result.Add(new MemberInfo(member, current)); + foreach (var b in info.Bases) queue.Enqueue(((NamedType)b).Name); + } + m_memberCache[className] = result; + return result; + } + + public IReadOnlyList OperatorsOf(string className) { + var result = new List(); + var seenClasses = new HashSet(); + var queue = new Queue(); + queue.Enqueue(className); + while (queue.Count > 0) { + var current = queue.Dequeue(); + if (!seenClasses.Add(current) || !m_classes.TryGetValue(current, out var info)) continue; + foreach (var op in info.Operators) + if (!result.Any(r => r.Op == op.Op && r.Operand == op.Operand)) result.Add(op); + foreach (var b in info.Bases) queue.Enqueue(((NamedType)b).Name); + } + return result; + } + + public LuaType ResolveAliases(LuaType type) => Resolve(type, []); + + private LuaType Resolve(LuaType type, HashSet expanding) { + switch (type) { + case NamedType { Args.Count: 0 } n when m_aliases.TryGetValue(n.Name, out var alias): + if (!expanding.Add(n.Name)) return n; + var resolved = Resolve(alias.Type, expanding); + expanding.Remove(n.Name); + return resolved; + case NamedType n: + return n.Args.Count == 0 ? n : n with { Args = n.Args.Select(a => Resolve(a, expanding)).ToList() }; + case UnionType u: + return LuaType.Union(u.Members.Select(m => Resolve(m, expanding)).ToArray()); + case ArrayType a: + return new ArrayType(Resolve(a.Element, expanding)); + case TableType t: + return new TableType(Resolve(t.Key, expanding), Resolve(t.Value, expanding)); + case FunctionType f: + return new FunctionType( + f.Params.Select(p => p with { Type = Resolve(p.Type, expanding) }).ToList(), + f.Returns.Select(r => Resolve(r, expanding)).ToList(), + f.VarargParam is null ? null : Resolve(f.VarargParam, expanding), + f.VarargReturn is null ? null : Resolve(f.VarargReturn, expanding)); + default: + return type; + } + } +} diff --git a/editor/LuaEditor/Types/TypeUniverseLoader.cs b/editor/LuaEditor/Types/TypeUniverseLoader.cs new file mode 100644 index 000000000..e191385d3 --- /dev/null +++ b/editor/LuaEditor/Types/TypeUniverseLoader.cs @@ -0,0 +1,63 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; + +namespace editor.LuaEditor.Types; + +public static class TypeUniverseLoader { + public static string DefaultStdlibDir => Path.Combine(AppContext.BaseDirectory, "Resources", "lua", "stdlib"); + + public static TypeUniverse Load(string projectRoot, string stdlibDir) { + var diagnostics = new List(); + var rc = LuaRc.Load(projectRoot, diagnostics); + var files = new List(); + + if (Directory.Exists(stdlibDir)) { + ReadAll(LuaFiles(stdlibDir, false, diagnostics), files, diagnostics); + } else { + diagnostics.Add(new Diagnostic(DiagnosticSeverity.Warning, $"standard library definitions not found at {stdlibDir}", + new SourceLocation(stdlibDir, 1))); + } + + foreach (var library in rc.Libraries) { + if (Directory.Exists(library)) ReadAll(LuaFiles(library, true, diagnostics), files, diagnostics); + else if (File.Exists(library)) ReadAll([library], files, diagnostics); + } + + files.Insert(0, new DeclarationFile("(loader)", [], [], [], [], diagnostics)); + return TypeUniverse.Build(files); + } + + // skip links to avoid recursive directory loops + private static List LuaFiles(string root, bool recursive, List diagnostics) { + var result = new List(); + var pending = new Stack(); + pending.Push(root); + while (pending.Count > 0) { + var dir = pending.Pop(); + try { + result.AddRange(Directory.GetFiles(dir, "*.lua")); + if (!recursive) continue; + foreach (var sub in Directory.GetDirectories(dir)) { + if (!File.GetAttributes(sub).HasFlag(FileAttributes.ReparsePoint)) pending.Push(sub); + } + } catch (Exception e) when (e is IOException or UnauthorizedAccessException) { + diagnostics.Add(new Diagnostic(DiagnosticSeverity.Warning, $"cannot read {dir}: {e.Message}", new SourceLocation(dir, 1))); + } + } + return result; + } + + private static void ReadAll(IEnumerable paths, List into, List diagnostics) { + foreach (var path in paths.Order(StringComparer.Ordinal)) { + try { + into.Add(DefinitionFileReader.Read(path, File.ReadAllText(path))); + } catch (IOException e) { + diagnostics.Add(new Diagnostic(DiagnosticSeverity.Warning, $"cannot read {path}: {e.Message}", new SourceLocation(path, 1))); + } catch (UnauthorizedAccessException e) { + diagnostics.Add(new Diagnostic(DiagnosticSeverity.Warning, $"cannot read {path}: {e.Message}", new SourceLocation(path, 1))); + } + } + } +} diff --git a/editor/Resources/lua/stdlib/LICENSE b/editor/Resources/lua/stdlib/LICENSE new file mode 100644 index 000000000..9bfa8ae49 --- /dev/null +++ b/editor/Resources/lua/stdlib/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 最萌小汐 + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/editor/Resources/lua/stdlib/README.md b/editor/Resources/lua/stdlib/README.md new file mode 100644 index 000000000..40710c0de --- /dev/null +++ b/editor/Resources/lua/stdlib/README.md @@ -0,0 +1,9 @@ +# lua standard library + +definitions from lua-language-server 3.19.2 +source directory is `server/meta/Lua 5.4 en-us utf8/` +upstream license is in LICENSE +luajit definitions are not included + +these stay outside project libraries because luals already ships its own copy +adding them to workspace.library would produce duplicate definitions diff --git a/editor/Resources/lua/stdlib/basic.lua b/editor/Resources/lua/stdlib/basic.lua new file mode 100644 index 000000000..98e234d0e --- /dev/null +++ b/editor/Resources/lua/stdlib/basic.lua @@ -0,0 +1,477 @@ +---@meta _ + +--- +---Command-line arguments of Lua Standalone. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-arg"]) +--- +---@type string[] +arg = {} + +--- +---Raises an error if the value of its argument v is false (i.e., `nil` or `false`); otherwise, returns all its arguments. In case of error, `message` is the error object; when absent, it defaults to `"assertion failed!"` +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-assert"]) +--- +---@generic T +---@param v? T +---@param message? any +---@param ... any +---@return T +---@return any ... +function assert(v, message, ...) end + + + + +--- +---This function is a generic interface to the garbage collector. It performs different functions according to its first argument, opt: +--- +---* `"collect"`: Performs a full garbage-collection cycle. This is the default option. +---* `"stop"`: Stops automatic execution of the garbage collector. The collector will run only when explicitly invoked, until a call to restart it. +---* `"restart"`: Restarts automatic execution of the garbage collector. +---* `"count"`: Returns the total memory in use by Lua in Kbytes. The value has a fractional part, so that it multiplied by 1024 gives the exact number of bytes in use by Lua. +---* `"step"`: Performs a garbage-collection step. The step "size" is controlled by arg. With a zero value, the collector will perform one basic (indivisible) step. For non-zero values, the collector will perform as if that amount of memory (in Kbytes) had been allocated by Lua. Returns true if the step finished a collection cycle. +---* `"isrunning"`: Returns a boolean that tells whether the collector is running (i.e., not stopped). +---* `"incremental"`: Change the collector mode to incremental. This option can be followed by three numbers: the garbage-collector pause, the step multiplier, and the step size (see [§2.5.1](command:extension.lua.doc?["en-us/54/manual.html/2.5.1"])). A zero means to not change that value. +---* `"generational"`: Change the collector mode to generational. This option can be followed by two numbers: the garbage-collector minor multiplier and the major multiplier (see [§2.5.2](command:extension.lua.doc?["en-us/54/manual.html/2.5.2"])). A zero means to not change that value. +---See [§2.5](command:extension.lua.doc?["en-us/54/manual.html/2.5"]) for more details about garbage collection and some of these options. +--- +---This function should not be called by a finalizer. +--- +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-collectgarbage54"]) +--- +---@overload fun(opt?: "collect") +---@overload fun(opt: "stop") +---@overload fun(opt: "restart") +---@overload fun(opt: "count"): number +---@overload fun(opt: "step", arg: integer): true +---@overload fun(opt: "isrunning"): boolean +---@overload fun(opt: "incremental", pause?: integer, multiplier?: integer, stepsize?: integer) +---@overload fun(opt: "generational", minor?: integer, major?: integer) +function collectgarbage(...) end + + +--- +---Opens the named file and executes its content as a Lua chunk. When called without arguments, `dofile` executes the content of the standard input (`stdin`). Returns all values returned by the chunk. In case of errors, `dofile` propagates the error to its caller. (That is, `dofile` does not run in protected mode.) +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-dofile"]) +--- +---@param filename? string +---@return any ... +function dofile(filename) end + +--- +---Terminates the last protected function called and returns message as the error object. +--- +---Usually, `error` adds some information about the error position at the beginning of the message, if the message is a string. +--- +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-error"]) +--- +---@param message any +---@param level? integer +function error(message, level) end + +--- +---A global variable (not a function) that holds the global environment (see [§2.2](command:extension.lua.doc?["en-us/54/manual.html/2.2"])). Lua itself does not use this variable; changing its value does not affect any environment, nor vice versa. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-_G"]) +--- +---@class _G +_G = {} + +---@version 5.1 +--- +---Returns the current environment in use by the function. `f` can be a Lua function or a number that specifies the function at that stack level. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-getfenv"]) +--- +---@param f? integer|async fun(...):... +---@return table +---@nodiscard +function getfenv(f) end + +--- +---If object does not have a metatable, returns nil. Otherwise, if the object's metatable has a __metatable field, returns the associated value. Otherwise, returns the metatable of the given object. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-getmetatable"]) +--- +---@param object any +---@return table metatable +---@nodiscard +function getmetatable(object) end + +--- +---Returns three values (an iterator function, the table `t`, and `0`) so that the construction +---```lua +--- for i,v in ipairs(t) do body end +---``` +---will iterate over the key–value pairs `(1,t[1]), (2,t[2]), ...`, up to the first absent index. +--- +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-ipairs"]) +--- +---@generic T: table, V +---@param t T +---@return fun(table: V[], i?: integer):integer, V +---@return T +---@return integer i +function ipairs(t) end + +---@alias loadmode +---| "b" # Only binary chunks. +---| "t" # Only text chunks. +---|>"bt" # Both binary and text. + +--- +---Loads a chunk. +--- +---If `chunk` is a string, the chunk is this string. If `chunk` is a function, `load` calls it repeatedly to get the chunk pieces. Each call to `chunk` must return a string that concatenates with previous results. A return of an empty string, `nil`, or no value signals the end of the chunk. +--- +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-load"]) +--- +---@param chunk string|function +---@param chunkname? string +---@param mode? loadmode +---@param env? table +---@return function? +---@return string? error_message +---@nodiscard +function load(chunk, chunkname, mode, env) end + +--- +---Loads a chunk from file `filename` or from the standard input, if no file name is given. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-loadfile"]) +--- +---@param filename? string +---@param mode? loadmode +---@param env? table +---@return function? +---@return string? error_message +---@nodiscard +function loadfile(filename, mode, env) end + +---@version 5.1 +--- +---Loads a chunk from the given string. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-loadstring"]) +--- +---@param text string +---@param chunkname? string +---@return function? +---@return string? error_message +---@nodiscard +function loadstring(text, chunkname) end + +---@version 5.1 +---@param proxy boolean|table|userdata +---@return userdata +---@nodiscard +function newproxy(proxy) end + +---@version 5.1 +--- +---Creates a module. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-module"]) +--- +---@param name string +---@param ... any +function module(name, ...) end + +--- +---Allows a program to traverse all fields of a table. Its first argument is a table and its second argument is an index in this table. A call to `next` returns the next index of the table and its associated value. When called with `nil` as its second argument, `next` returns an initial index and its associated value. When called with the last index, or with `nil` in an empty table, `next` returns `nil`. If the second argument is absent, then it is interpreted as `nil`. In particular, you can use `next(t)` to check whether a table is empty. +--- +---The order in which the indices are enumerated is not specified, *even for numeric indices*. (To traverse a table in numerical order, use a numerical `for`.) +--- +---The behavior of `next` is undefined if, during the traversal, you assign any value to a non-existent field in the table. You may however modify existing fields. In particular, you may set existing fields to nil. +--- +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-next"]) +--- +---@generic K, V +---@param table table +---@param index? K +---@return K? +---@return V? +---@nodiscard +function next(table, index) end + +--- +---If `t` has a metamethod `__pairs`, calls it with t as argument and returns the first three results from the call. +--- +---Otherwise, returns three values: the [next](command:extension.lua.doc?["en-us/54/manual.html/pdf-next"]) function, the table `t`, and `nil`, so that the construction +---```lua +--- for k,v in pairs(t) do body end +---``` +---will iterate over all key–value pairs of table `t`. +--- +---See function [next](command:extension.lua.doc?["en-us/54/manual.html/pdf-next"]) for the caveats of modifying the table during its traversal. +--- +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-pairs"]) +--- +---@generic T: table, K, V +---@param t T +---@return fun(table: table, index?: K):K, V +---@return T +function pairs(t) end + +--- +---Calls the function `f` with the given arguments in *protected mode*. This means that any error inside `f` is not propagated; instead, `pcall` catches the error and returns a status code. Its first result is the status code (a boolean), which is true if the call succeeds without errors. In such case, `pcall` also returns all results from the call, after this first result. In case of any error, `pcall` returns `false` plus the error object. +--- +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-pcall"]) +--- +---@param f async fun(...):... +---@param arg1? any +---@param ... any +---@return boolean success +---@return any result +---@return any ... +function pcall(f, arg1, ...) end + +--- +---Receives any number of arguments and prints their values to `stdout`, converting each argument to a string following the same rules of [tostring](command:extension.lua.doc?["en-us/54/manual.html/pdf-tostring"]). +---The function print is not intended for formatted output, but only as a quick way to show a value, for instance for debugging. For complete control over the output, use [string.format](command:extension.lua.doc?["en-us/54/manual.html/pdf-string.format"]) and [io.write](command:extension.lua.doc?["en-us/54/manual.html/pdf-io.write"]). +--- +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-print"]) +--- +---@param ... any +function print(...) end + +--- +---Checks whether v1 is equal to v2, without invoking the `__eq` metamethod. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-rawequal"]) +--- +---@param v1 any +---@param v2 any +---@return boolean +---@nodiscard +function rawequal(v1, v2) end + +--- +---Gets the real value of `table[index]`, without invoking the `__index` metamethod. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-rawget"]) +--- +---@param table table +---@param index any +---@return any +---@nodiscard +function rawget(table, index) end + +--- +---Returns the length of the object `v`, without invoking the `__len` metamethod. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-rawlen"]) +--- +---@param v table|string +---@return integer len +---@nodiscard +function rawlen(v) end + +--- +---Sets the real value of `table[index]` to `value`, without using the `__newindex` metavalue. `table` must be a table, `index` any value different from `nil` and `NaN`, and `value` any Lua value. +---This function returns `table`. +--- +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-rawset"]) +--- +---@param table table +---@param index any +---@param value any +---@return table +function rawset(table, index, value) end + +--- +---If `index` is a number, returns all arguments after argument number `index`; a negative number indexes from the end (`-1` is the last argument). Otherwise, `index` must be the string `"#"`, and `select` returns the total number of extra arguments it received. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-select"]) +--- +---@param index integer|"#" +---@param ... any +---@return any +---@nodiscard +function select(index, ...) end + +---@version 5.1 +--- +---Sets the environment to be used by the given function. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-setfenv"]) +--- +---@param f (async fun(...):...)|integer +---@param table table +---@return function +function setfenv(f, table) end + + +---@class metatable +---@field __mode 'v'|'k'|'kv'|nil +---@field __metatable any|nil +---@field __tostring (fun(t):string)|nil +---@field __gc fun(t)|nil +---@field __add (fun(t1,t2):any)|nil +---@field __sub (fun(t1,t2):any)|nil +---@field __mul (fun(t1,t2):any)|nil +---@field __div (fun(t1,t2):any)|nil +---@field __mod (fun(t1,t2):any)|nil +---@field __pow (fun(t1,t2):any)|nil +---@field __unm (fun(t):any)|nil +---@field __idiv (fun(t1,t2):any)|nil +---@field __band (fun(t1,t2):any)|nil +---@field __bor (fun(t1,t2):any)|nil +---@field __bxor (fun(t1,t2):any)|nil +---@field __bnot (fun(t):any)|nil +---@field __shl (fun(t1,t2):any)|nil +---@field __shr (fun(t1,t2):any)|nil +---@field __concat (fun(t1,t2):any)|nil +---@field __len (fun(t):integer)|nil +---@field __eq (fun(t1,t2):boolean)|nil +---@field __lt (fun(t1,t2):boolean)|nil +---@field __le (fun(t1,t2):boolean)|nil +---@field __index table|(fun(t,k):any)|nil +---@field __newindex table|fun(t,k,v)|nil +---@field __call (fun(t,...):...)|nil +---@field __pairs (fun(t):((fun(t,k,v):any,any),any,any))|nil +---@field __close (fun(t,errobj):any)|nil + +--- +---Sets the metatable for the given table. If `metatable` is `nil`, removes the metatable of the given table. If the original metatable has a `__metatable` field, raises an error. +--- +---This function returns `table`. +--- +---To change the metatable of other types from Lua code, you must use the debug library ([§6.10](command:extension.lua.doc?["en-us/54/manual.html/6.10"])). +--- +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-setmetatable"]) +--- +---@param table table +---@param metatable? metatable|table +---@return table +function setmetatable(table, metatable) end + +--- +---When called with no `base`, `tonumber` tries to convert its argument to a number. If the argument is already a number or a string convertible to a number, then `tonumber` returns this number; otherwise, it returns `fail`. +--- +---The conversion of strings can result in integers or floats, according to the lexical conventions of Lua (see [§3.1](command:extension.lua.doc?["en-us/54/manual.html/3.1"])). The string may have leading and trailing spaces and a sign. +--- +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-tonumber"]) +--- +---@overload fun(e: string, base: integer):integer +---@param e any +---@return number? +---@nodiscard +function tonumber(e) end + +--- +---Receives a value of any type and converts it to a string in a human-readable format. +--- +---If the metatable of `v` has a `__tostring` field, then `tostring` calls the corresponding value with `v` as argument, and uses the result of the call as its result. Otherwise, if the metatable of `v` has a `__name` field with a string value, `tostring` may use that string in its final result. +--- +---For complete control of how numbers are converted, use [string.format](command:extension.lua.doc?["en-us/54/manual.html/pdf-string.format"]). +--- +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-tostring"]) +--- +---@param v any +---@return string +---@nodiscard +function tostring(v) end + +---@alias type +---| "nil" +---| "number" +---| "string" +---| "boolean" +---| "table" +---| "function" +---| "thread" +---| "userdata" + +--- +---Returns the type of its only argument, coded as a string. The possible results of this function are `"nil"` (a string, not the value `nil`), `"number"`, `"string"`, `"boolean"`, `"table"`, `"function"`, `"thread"`, and `"userdata"`. +--- +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-type"]) +--- +---@param v any +---@return type type +---@nodiscard +function type(v) end + +--- +---A global variable (not a function) that holds a string containing the running Lua version. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-_VERSION"]) +--- +_VERSION = "Lua 5.4" + +---@version >5.4 +--- +---Emits a warning with a message composed by the concatenation of all its arguments (which should be strings). +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-warn"]) +--- +---@param message string +---@param ... any +function warn(message, ...) end + +--- +---Calls function `f` with the given arguments in protected mode with a new message handler. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-xpcall"]) +--- +---@param f async fun(...):... +---@param msgh function +---@param arg1? any +---@param ... any +---@return boolean success +---@return any result +---@return any ... +function xpcall(f, msgh, arg1, ...) end + +---@version 5.1 +--- +---Returns the elements from the given `list`. This function is equivalent to +---```lua +--- return list[i], list[i+1], ···, list[j] +---``` +--- +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-unpack"]) +--- +---@generic T1, T2, T3, T4, T5, T6, T7, T8, T9, T10 +---@param list { +--- [1]?: T1, +--- [2]?: T2, +--- [3]?: T3, +--- [4]?: T4, +--- [5]?: T5, +--- [6]?: T6, +--- [7]?: T7, +--- [8]?: T8, +--- [9]?: T9, +--- [10]?: T10, +---} +---@param i? integer +---@param j? integer +---@return T1, T2, T3, T4, T5, T6, T7, T8, T9, T10 +---@nodiscard +function unpack(list, i, j) end + +---@version 5.1 +---@generic T1, T2, T3, T4, T5, T6, T7, T8, T9 +---@param list {[1]: T1, [2]: T2, [3]: T3, [4]: T4, [5]: T5, [6]: T6, [7]: T7, [8]: T8, [9]: T9 } +---@return T1, T2, T3, T4, T5, T6, T7, T8, T9 +---@nodiscard +function unpack(list) end diff --git a/editor/Resources/lua/stdlib/builtin.lua b/editor/Resources/lua/stdlib/builtin.lua new file mode 100644 index 000000000..466a0966e --- /dev/null +++ b/editor/Resources/lua/stdlib/builtin.lua @@ -0,0 +1,16 @@ +---@meta _ + +---@class unknown +---@class any +---@class nil +---@class boolean +---@class true: boolean +---@class false: boolean +---@class number +---@class integer: number +---@class thread +---@class table: { [K]: V } +---@class string: stringlib +---@class userdata +---@class lightuserdata +---@class function diff --git a/editor/Resources/lua/stdlib/coroutine.lua b/editor/Resources/lua/stdlib/coroutine.lua new file mode 100644 index 000000000..2b78d6c92 --- /dev/null +++ b/editor/Resources/lua/stdlib/coroutine.lua @@ -0,0 +1,96 @@ +---@meta coroutine + +--- +--- +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-coroutine"]) +--- +---@class coroutinelib +coroutine = {} + +--- +---Creates a new coroutine, with body `f`. `f` must be a function. Returns this new coroutine, an object with type `"thread"`. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-coroutine.create"]) +--- +---@param f async fun(...):... +---@return thread +---@nodiscard +function coroutine.create(f) end + +--- +---Returns true when the coroutine `co` can yield. The default for `co` is the running coroutine. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-coroutine.isyieldable"]) +--- +---@param co? thread +---@return boolean +---@nodiscard +function coroutine.isyieldable(co) end + +---@version >5.4 +--- +---Closes coroutine `co` , closing all its pending to-be-closed variables and putting the coroutine in a dead state. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-coroutine.close"]) +--- +---@param co thread +---@return boolean noerror +---@return any errorobject +function coroutine.close(co) end + +--- +---Starts or continues the execution of coroutine `co`. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-coroutine.resume"]) +--- +---@param co thread +---@param val1? any +---@return boolean success +---@return any ... +function coroutine.resume(co, val1, ...) end + +--- +---Returns the running coroutine plus a boolean, true when the running coroutine is the main one. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-coroutine.running"]) +--- +---@return thread running +---@return boolean ismain +---@nodiscard +function coroutine.running() end + +--- +---Returns the status of coroutine `co`. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-coroutine.status"]) +--- +---@param co thread +---@return +---| '"running"' # Is running. +---| '"suspended"' # Is suspended or not started. +---| '"normal"' # Is active but not running. +---| '"dead"' # Has finished or stopped with an error. +---@nodiscard +function coroutine.status(co) end + +--- +---Creates a new coroutine, with body `f`; `f` must be a function. Returns a function that resumes the coroutine each time it is called. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-coroutine.wrap"]) +--- +---@param f async fun(...):... +---@return fun(...):... +---@nodiscard +function coroutine.wrap(f) end + +--- +---Suspends the execution of the calling coroutine. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-coroutine.yield"]) +--- +---@async +---@return any ... +function coroutine.yield(...) end + +return coroutine diff --git a/editor/Resources/lua/stdlib/debug.lua b/editor/Resources/lua/stdlib/debug.lua new file mode 100644 index 000000000..810c87be8 --- /dev/null +++ b/editor/Resources/lua/stdlib/debug.lua @@ -0,0 +1,274 @@ +---@meta debug + +--- +--- +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-debug"]) +--- +---@class debuglib +debug = {} + +---@class debuginfo +---@field name string +---@field namewhat string +---@field source string +---@field short_src string +---@field linedefined integer +---@field lastlinedefined integer +---@field what string +---@field currentline integer +---@field istailcall boolean +---@field nups integer +---@field nparams integer +---@field isvararg boolean +---@field func function +---@field ftransfer integer +---@field ntransfer integer +---@field activelines table + +--- +---Enters an interactive mode with the user, running each string that the user enters. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-debug.debug"]) +--- +function debug.debug() end + +---@version 5.1 +--- +---Returns the environment of object `o` . +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-debug.getfenv"]) +--- +---@param o any +---@return table +---@nodiscard +function debug.getfenv(o) end + +--- +---Returns the current hook settings of the thread. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-debug.gethook"]) +--- +---@param co? thread +---@return function hook +---@return string mask +---@return integer count +---@nodiscard +function debug.gethook(co) end + +---@alias infowhat string +---|+"n" # `name` and `namewhat` +---|+"S" # `source`, `short_src`, `linedefined`, `lastlinedefined`, and `what` +---|+"l" # `currentline` +---|+"t" # `istailcall` +---|+"u" # `nups`, `nparams`, and `isvararg` +---|+"f" # `func` +---|+"r" # `ftransfer` and `ntransfer` +---|+"L" # `activelines` + +--- +---Returns a table with information about a function. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-debug.getinfo"]) +--- +---@overload fun(f: integer|function, what?: infowhat):debuginfo +---@param thread thread +---@param f integer|async fun(...):... +---@param what? infowhat +---@return debuginfo +---@nodiscard +function debug.getinfo(thread, f, what) end + +--- +---Returns the name and the value of the local variable with index `local` of the function at level `f` of the stack. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-debug.getlocal"]) +--- +---@overload fun(f: integer|async fun(...):..., index: integer):string, any +---@param thread thread +---@param f integer|async fun(...):... +---@param index integer +---@return string name +---@return any value +---@nodiscard +function debug.getlocal(thread, f, index) end + +--- +---Returns the metatable of the given value. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-debug.getmetatable"]) +--- +---@param object any +---@return table metatable +---@nodiscard +function debug.getmetatable(object) end + +--- +---Returns the registry table. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-debug.getregistry"]) +--- +---@return table +---@nodiscard +function debug.getregistry() end + +--- +---Returns the name and the value of the upvalue with index `up` of the function. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-debug.getupvalue"]) +--- +---@param f async fun(...):... +---@param up integer +---@return string name +---@return any value +---@nodiscard +function debug.getupvalue(f, up) end + +--- +---Returns the `n`-th user value associated +---to the userdata `u` plus a boolean, +---`false` if the userdata does not have that value. +--- +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-debug.getuservalue"]) +--- +---@param u userdata +---@param n? integer +---@return any +---@return boolean +---@nodiscard +function debug.getuservalue(u, n) end + +--- +---### **Deprecated in `Lua 5.4.2`** +--- +---Sets a new limit for the C stack. This limit controls how deeply nested calls can go in Lua, with the intent of avoiding a stack overflow. +--- +---In case of success, this function returns the old limit. In case of error, it returns `false`. +--- +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-debug.setcstacklimit"]) +--- +---@deprecated +---@param limit integer +---@return integer|boolean +function debug.setcstacklimit(limit) end + +--- +---Sets the environment of the given `object` to the given `table` . +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-debug.setfenv"]) +--- +---@version 5.1 +---@generic T +---@param object T +---@param env table +---@return T object +function debug.setfenv(object, env) end + +---@alias hookmask string +---|+"c" # Calls hook when Lua calls a function. +---|+"r" # Calls hook when Lua returns from a function. +---|+"l" # Calls hook when Lua enters a new line of code. + +--- +---Sets the given function as a hook. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-debug.sethook"]) +--- +---@overload fun(hook: (async fun(...):...), mask: hookmask, count?: integer) +---@overload fun(thread: thread):... +---@overload fun(...):... +---@param thread thread +---@param hook async fun(...):... +---@param mask hookmask +---@param count? integer +function debug.sethook(thread, hook, mask, count) end + +--- +---Assigns the `value` to the local variable with index `local` of the function at `level` of the stack. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-debug.setlocal"]) +--- +---@overload fun(level: integer, index: integer, value: any):string +---@param thread thread +---@param level integer +---@param index integer +---@param value any +---@return string name +function debug.setlocal(thread, level, index, value) end + +--- +---Sets the metatable for the given value to the given table (which can be `nil`). +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-debug.setmetatable"]) +--- +---@generic T +---@param value T +---@param meta? table +---@return T value +function debug.setmetatable(value, meta) end + +--- +---Assigns the `value` to the upvalue with index `up` of the function. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-debug.setupvalue"]) +--- +---@param f async fun(...):... +---@param up integer +---@param value any +---@return string name +function debug.setupvalue(f, up, value) end + +--- +---Sets the given `value` as +---the `n`-th user value associated to the given `udata`. +---`udata` must be a full userdata. +--- +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-debug.setuservalue"]) +--- +---@param udata userdata +---@param value any +---@param n? integer +---@return userdata udata +function debug.setuservalue(udata, value, n) end + +--- +---Returns a string with a traceback of the call stack. The optional message string is appended at the beginning of the traceback. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-debug.traceback"]) +--- +---@overload fun(message?: any, level?: integer): string +---@param thread thread +---@param message? any +---@param level? integer +---@return string message +---@nodiscard +function debug.traceback(thread, message, level) end + +---@version >5.2, JIT +--- +---Returns a unique identifier (as a light userdata) for the upvalue numbered `n` from the given function. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-debug.upvalueid"]) +--- +---@param f async fun(...):... +---@param n integer +---@return lightuserdata id +---@nodiscard +function debug.upvalueid(f, n) end + +---@version >5.2, JIT +--- +---Make the `n1`-th upvalue of the Lua closure `f1` refer to the `n2`-th upvalue of the Lua closure `f2`. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-debug.upvaluejoin"]) +--- +---@param f1 async fun(...):... +---@param n1 integer +---@param f2 async fun(...):... +---@param n2 integer +function debug.upvaluejoin(f1, n1, f2, n2) end + +return debug diff --git a/editor/Resources/lua/stdlib/io.lua b/editor/Resources/lua/stdlib/io.lua new file mode 100644 index 000000000..4a75a488f --- /dev/null +++ b/editor/Resources/lua/stdlib/io.lua @@ -0,0 +1,265 @@ +---@meta io + +--- +--- +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-io"]) +--- +---@class iolib +--- +---standard input. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-io.stdin"]) +--- +---@field stdin file* +--- +---standard output. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-io.stdout"]) +--- +---@field stdout file* +--- +---standard error. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-io.stderr"]) +--- +---@field stderr file* +io = {} + +---@alias openmode +---|>"r" # Read mode. +---| "w" # Write mode. +---| "a" # Append mode. +---| "r+" # Update mode, all previous data is preserved. +---| "w+" # Update mode, all previous data is erased. +---| "a+" # Append update mode, previous data is preserved, writing is only allowed at the end of file. +---| "rb" # Read mode. (in binary mode.) +---| "wb" # Write mode. (in binary mode.) +---| "ab" # Append mode. (in binary mode.) +---| "r+b" # Update mode, all previous data is preserved. (in binary mode.) +---| "w+b" # Update mode, all previous data is erased. (in binary mode.) +---| "a+b" # Append update mode, previous data is preserved, writing is only allowed at the end of file. (in binary mode.) + +--- +---Close `file` or default output file. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-io.close"]) +--- +---@param file? file* +---@return true? suc +---@return exitcode? exitcode +---@return integer? code +function io.close(file) end + +--- +---Saves any written data to default output file. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-io.flush"]) +--- +function io.flush() end + +--- +---Sets `file` as the default input file. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-io.input"]) +--- +---@overload fun():file* +---@param file string|file* +function io.input(file) end + +--- +--------- +---```lua +---for c in io.lines(filename, ...) do +--- body +---end +---``` +--- +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-io.lines"]) +--- +---@param filename string? +---@param ... readmode +---@return fun():any, ... +function io.lines(filename, ...) end + +--- +---Opens a file, in the mode specified in the string `mode`. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-io.open"]) +--- +---@param filename string +---@param mode? openmode +---@return file*? +---@return string? errmsg +---@nodiscard +function io.open(filename, mode) end + +--- +---Sets `file` as the default output file. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-io.output"]) +--- +---@overload fun():file* +---@param file string|file* +function io.output(file) end + +---@alias popenmode +---| "r" # Read data from this program by `file`. +---| "w" # Write data to this program by `file`. + +--- +---Starts program prog in a separated process. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-io.popen"]) +--- +---@param prog string +---@param mode? popenmode +---@return file*? +---@return string? errmsg +function io.popen(prog, mode) end + +--- +---Reads the `file`, according to the given formats, which specify what to read. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-io.read"]) +--- +---@param ... readmode +---@return any +---@return any ... +---@nodiscard +function io.read(...) end + +--- +---In case of success, returns a handle for a temporary file. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-io.tmpfile"]) +--- +---@return file* +---@nodiscard +function io.tmpfile() end + +---@alias filetype +---| "file" # Is an open file handle. +---| "closed file" # Is a closed file handle. +---| `nil` # Is not a file handle. + +--- +---Checks whether `obj` is a valid file handle. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-io.type"]) +--- +---@param file file* +---@return filetype +---@nodiscard +function io.type(file) end + +--- +---Writes the value of each of its arguments to default output file. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-io.write"]) +--- +---@return file* +---@return string? errmsg +function io.write(...) end + +--- +--- +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-file"]) +--- +---@class file* +local file = {} + +---@alias readmode integer|string +---| "n" # Reads a numeral and returns it as number. +---| "a" # Reads the whole file. +---|>"l" # Reads the next line skipping the end of line. +---| "L" # Reads the next line keeping the end of line. + +---@alias exitcode "exit"|"signal" + +--- +---Close `file`. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-file:close"]) +--- +---@return true? suc +---@return exitcode? exitcode +---@return integer? code +function file:close() end + +--- +---Saves any written data to `file`. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-file:flush"]) +--- +function file:flush() end + +--- +--------- +---```lua +---for c in file:lines(...) do +--- body +---end +---``` +--- +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-file:lines"]) +--- +---@param ... readmode +---@return fun():any, ... +function file:lines(...) end + +--- +---Reads the `file`, according to the given formats, which specify what to read. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-file:read"]) +--- +---@param ... readmode +---@return any +---@return any ... +---@nodiscard +function file:read(...) end + +---@alias seekwhence +---| "set" # Base is beginning of the file. +---|>"cur" # Base is current position. +---| "end" # Base is end of file. + +--- +---Sets and gets the file position, measured from the beginning of the file. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-file:seek"]) +--- +---@param whence? seekwhence +---@param offset? integer +---@return integer offset +---@return string? errmsg +function file:seek(whence, offset) end + +---@alias vbuf +---| "no" # Output operation appears immediately. +---| "full" # Performed only when the buffer is full. +---| "line" # Buffered until a newline is output. + +--- +---Sets the buffering mode for an output file. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-file:setvbuf"]) +--- +---@param mode vbuf +---@param size? integer +function file:setvbuf(mode, size) end + +--- +---Writes the value of each of its arguments to `file`. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-file:write"]) +--- +---@param ... string|number +---@return file*? +---@return string? errmsg +function file:write(...) end + +return io diff --git a/editor/Resources/lua/stdlib/math.lua b/editor/Resources/lua/stdlib/math.lua new file mode 100644 index 000000000..e3b9c7414 --- /dev/null +++ b/editor/Resources/lua/stdlib/math.lua @@ -0,0 +1,381 @@ +---@meta math + +--- +--- +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-math"]) +--- +---@class mathlib +--- +---A value larger than any other numeric value. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-math.huge"]) +--- +---@field huge number +--- +---Miss locale +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-math.maxinteger"]) +--- +---@field maxinteger integer +--- +---Miss locale +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-math.mininteger"]) +--- +---@field mininteger integer +--- +---The value of *π*. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-math.pi"]) +--- +---@field pi number +math = {} + +--- +---Returns the absolute value of `x`. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-math.abs"]) +--- +---@generic Number: number +---@param x Number +---@return Number +---@nodiscard +function math.abs(x) end + +--- +---Returns the arc cosine of `x` (in radians). +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-math.acos"]) +--- +---@param x number +---@return number +---@nodiscard +function math.acos(x) end + +--- +---Returns the arc sine of `x` (in radians). +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-math.asin"]) +--- +---@param x number +---@return number +---@nodiscard +function math.asin(x) end + +--- +---Returns the arc tangent of `y/x` (in radians). +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-math.atan"]) +--- +---@param y number +---@param x? number +---@return number +---@nodiscard +function math.atan(y, x) end + +---@version <5.2 +--- +---Returns the arc tangent of `y/x` (in radians). +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-math.atan2"]) +--- +---@param y number +---@param x number +---@return number +---@nodiscard +function math.atan2(y, x) end + +--- +---Returns the smallest integral value larger than or equal to `x`. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-math.ceil"]) +--- +---@param x number +---@return integer +---@nodiscard +function math.ceil(x) end + +--- +---Returns the cosine of `x` (assumed to be in radians). +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-math.cos"]) +--- +---@param x number +---@return number +---@nodiscard +function math.cos(x) end + +---@version <5.2 +--- +---Returns the hyperbolic cosine of `x` (assumed to be in radians). +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-math.cosh"]) +--- +---@param x number +---@return number +---@nodiscard +function math.cosh(x) end + +--- +---Converts the angle `x` from radians to degrees. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-math.deg"]) +--- +---@param x number +---@return number +---@nodiscard +function math.deg(x) end + +--- +---Returns the value `e^x` (where `e` is the base of natural logarithms). +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-math.exp"]) +--- +---@param x number +---@return number +---@nodiscard +function math.exp(x) end + +--- +---Returns the largest integral value smaller than or equal to `x`. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-math.floor"]) +--- +---@param x number +---@return integer +---@nodiscard +function math.floor(x) end + +--- +---Returns the remainder of the division of `x` by `y` that rounds the quotient towards zero. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-math.fmod"]) +--- +---@param x number +---@param y number +---@return number +---@nodiscard +function math.fmod(x, y) end + +---@version <5.2, >5.5 +--- +---Returns two numbers `m` and `e` such that `x = m * (2 ^ e)`, where `e` is an integer. When `x` is zero, NaN, +inf, or -inf, `m` is equal to `x`; otherwise, the absolute value of `m` is in the range [0.5, 1). +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-math.frexp"]) +--- +---@param x number +---@return number m +---@return number e +---@nodiscard +function math.frexp(x) end + +---@version <5.2, >5.5 +--- +---Returns `m * (2 ^ e)`, where `e` is an integer. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-math.ldexp"]) +--- +---@param m number +---@param e number +---@return number +---@nodiscard +function math.ldexp(m, e) end + +--- +---Returns the logarithm of `x` in the given base. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-math.log"]) +--- +---@param x number +---@param base? integer +---@return number +---@nodiscard +function math.log(x, base) end + +---@version <5.1 +--- +---Returns the base-10 logarithm of x. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-math.log10"]) +--- +---@param x number +---@return number +---@nodiscard +function math.log10(x) end + +--- +---Returns the argument with the maximum value, according to the Lua operator `<`. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-math.max"]) +--- +---@generic Number: number +---@param x Number +---@param ... Number +---@return Number +---@nodiscard +function math.max(x, ...) end + +--- +---Returns the argument with the minimum value, according to the Lua operator `<`. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-math.min"]) +--- +---@generic Number: number +---@param x Number +---@param ... Number +---@return Number +---@nodiscard +function math.min(x, ...) end + +--- +---Returns the integral part of `x` and the fractional part of `x`. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-math.modf"]) +--- +---@param x number +---@return integer +---@return number +---@nodiscard +function math.modf(x) end + +---@version <5.2 +--- +---Returns `x ^ y` . +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-math.pow"]) +--- +---@param x number +---@param y number +---@return number +---@nodiscard +function math.pow(x, y) end + +--- +---Converts the angle `x` from degrees to radians. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-math.rad"]) +--- +---@param x number +---@return number +---@nodiscard +function math.rad(x) end + +--- +---* `math.random()`: Returns a float in the range [0,1). +---* `math.random(n)`: Returns a integer in the range [1, n]. +---* `math.random(m, n)`: Returns a integer in the range [m, n]. +--- +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-math.random"]) +--- +---@overload fun():number +---@overload fun(m: integer):integer +---@param m integer +---@param n integer +---@return integer +---@nodiscard +function math.random(m, n) end + +--- +---* `math.randomseed(x, y)`: Concatenate `x` and `y` into a 128-bit `seed` to reinitialize the pseudo-random generator. +---* `math.randomseed(x)`: Equate to `math.randomseed(x, 0)` . +---* `math.randomseed()`: Generates a seed with a weak attempt for randomness. +--- +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-math.randomseed"]) +--- +---@param x? integer +---@param y? integer +function math.randomseed(x, y) end + +--- +---Returns the sine of `x` (assumed to be in radians). +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-math.sin"]) +--- +---@param x number +---@return number +---@nodiscard +function math.sin(x) end + +---@version <5.2 +--- +---Returns the hyperbolic sine of `x` (assumed to be in radians). +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-math.sinh"]) +--- +---@param x number +---@return number +---@nodiscard +function math.sinh(x) end + +--- +---Returns the square root of `x`. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-math.sqrt"]) +--- +---@param x number +---@return number +---@nodiscard +function math.sqrt(x) end + +--- +---Returns the tangent of `x` (assumed to be in radians). +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-math.tan"]) +--- +---@param x number +---@return number +---@nodiscard +function math.tan(x) end + +---@version <5.2 +--- +---Returns the hyperbolic tangent of `x` (assumed to be in radians). +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-math.tanh"]) +--- +---@param x number +---@return number +---@nodiscard +function math.tanh(x) end + +---@version >5.3 +--- +---Miss locale +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-math.tointeger"]) +--- +---@param x any +---@return integer? +---@nodiscard +function math.tointeger(x) end + +---@version >5.3 +--- +---Miss locale +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-math.type"]) +--- +---@param x any +---@return +---| '"integer"' +---| '"float"' +---| nil +---@nodiscard +function math.type(x) end + +---@version >5.3 +--- +---Miss locale +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-math.ult"]) +--- +---@param m integer +---@param n integer +---@return boolean +---@nodiscard +function math.ult(m, n) end + +return math diff --git a/editor/Resources/lua/stdlib/os.lua b/editor/Resources/lua/stdlib/os.lua new file mode 100644 index 000000000..c5daff4b9 --- /dev/null +++ b/editor/Resources/lua/stdlib/os.lua @@ -0,0 +1,244 @@ +---@meta os + +--- +--- +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-os"]) +--- +---@class oslib +os = {} + +--- +---Returns an approximation of the amount in seconds of CPU time used by the program. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-os.clock"]) +--- +---@return number +---@nodiscard +function os.clock() end + +---@class osdate:osdateparam +--- +---four digits +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-osdate.year"]) +--- +---@field year integer +--- +---1-12 +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-osdate.month"]) +--- +---@field month integer +--- +---1-31 +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-osdate.day"]) +--- +---@field day integer +--- +---0-23 +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-osdate.hour"]) +--- +---@field hour integer +--- +---0-59 +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-osdate.min"]) +--- +---@field min integer +--- +---0-61 +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-osdate.sec"]) +--- +---@field sec integer +--- +---weekday, 1–7, Sunday is 1 +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-osdate.wday"]) +--- +---@field wday integer +--- +---day of the year, 1–366 +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-osdate.yday"]) +--- +---@field yday integer +--- +---daylight saving flag, a boolean +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-osdate.isdst"]) +--- +---@field isdst boolean? + +--- +---Returns a string or a table containing date and time, formatted according to the given string `format`. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-os.date"]) +--- +---@param format? string +---@param time? integer +---@return string|osdate +---@nodiscard +function os.date(format, time) end + +--- +---Returns the difference, in seconds, from time `t1` to time `t2`. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-os.difftime"]) +--- +---@param t2 integer +---@param t1 integer +---@return integer +---@nodiscard +function os.difftime(t2, t1) end + +--- +---Passes `command` to be executed by an operating system shell. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-os.execute"]) +--- +---@param command? string +---@return true? suc +---@return exitcode? exitcode +---@return integer? code +function os.execute(command) end + +--- +---Calls the ISO C function `exit` to terminate the host program. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-os.exit"]) +--- +---@param code? boolean|integer +---@param close? boolean +function os.exit(code, close) end + +--- +---Returns the value of the process environment variable `varname`. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-os.getenv"]) +--- +---@param varname string +---@return string? +---@nodiscard +function os.getenv(varname) end + +--- +---Deletes the file with the given name. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-os.remove"]) +--- +---@param filename string +---@return true? suc +---@return string? errmsg +---@return integer? errcode +function os.remove(filename) end + +--- +---Renames the file or directory named `oldname` to `newname`. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-os.rename"]) +--- +---@param oldname string +---@param newname string +---@return true? suc +---@return string? errmsg +---@return integer? errcode +function os.rename(oldname, newname) end + +---@alias localecategory +---|>"all" +---| "collate" +---| "ctype" +---| "monetary" +---| "numeric" +---| "time" + +--- +---Sets the current locale of the program. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-os.setlocale"]) +--- +---@param locale string|nil +---@param category? localecategory +---@return string localecategory +function os.setlocale(locale, category) end + +---@class osdateparam +--- +---four digits +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-osdate.year"]) +--- +---@field year integer|string +--- +---1-12 +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-osdate.month"]) +--- +---@field month integer|string +--- +---1-31 +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-osdate.day"]) +--- +---@field day integer|string +--- +---0-23 +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-osdate.hour"]) +--- +---@field hour (integer|string)? +--- +---0-59 +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-osdate.min"]) +--- +---@field min (integer|string)? +--- +---0-61 +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-osdate.sec"]) +--- +---@field sec (integer|string)? +--- +---weekday, 1–7, Sunday is 1 +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-osdate.wday"]) +--- +---@field wday (integer|string)? +--- +---day of the year, 1–366 +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-osdate.yday"]) +--- +---@field yday (integer|string)? +--- +---daylight saving flag, a boolean +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-osdate.isdst"]) +--- +---@field isdst boolean? + +--- +---Returns the current time when called without arguments, or a time representing the local date and time specified by the given table. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-os.time"]) +--- +---@param date? osdateparam +---@return integer +---@nodiscard +function os.time(date) end + +--- +---Returns a string with a file name that can be used for a temporary file. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-os.tmpname"]) +--- +---@return string +---@nodiscard +function os.tmpname() end + +return os diff --git a/editor/Resources/lua/stdlib/package.lua b/editor/Resources/lua/stdlib/package.lua new file mode 100644 index 000000000..65a7f2e49 --- /dev/null +++ b/editor/Resources/lua/stdlib/package.lua @@ -0,0 +1,107 @@ +---@meta package + +--- +---Loads the given module, returns any value returned by the searcher(`true` when `nil`). Besides that value, also returns as a second result the loader data returned by the searcher, which indicates how `require` found the module. (For instance, if the module came from a file, this loader data is the file path.) +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-require"]) +--- +---@param modname string +---@return unknown +---@return unknown loaderdata +function require(modname) end + +--- +--- +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-package"]) +--- +---@class packagelib +--- +---The path used by `require` to search for a C loader. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-package.cpath"]) +--- +---@field cpath string +--- +---A table used by `require` to control which modules are already loaded. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-package.loaded"]) +--- +---@field loaded table +--- +---The path used by `require` to search for a Lua loader. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-package.path"]) +--- +---@field path string +--- +---A table to store loaders for specific modules. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-package.preload"]) +--- +---@field preload table +package = {} + +--- +---A string describing some compile-time configurations for packages. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-package.config"]) +--- +package.config = [[ +/ +; +? +! +-]] + +---@version <5.1 +--- +---A table used by `require` to control how to load modules. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-package.loaders"]) +--- +package.loaders = {} + +--- +---Dynamically links the host program with the C library `libname`. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-package.loadlib"]) +--- +---@param libname string +---@param funcname string +---@return any +function package.loadlib(libname, funcname) end + +--- +---A table used by `require` to control how to load modules. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-package.searchers"]) +--- +---@version >5.2 +package.searchers = {} + +--- +---Searches for the given `name` in the given `path`. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-package.searchpath"]) +--- +---@version >5.2,JIT +---@param name string +---@param path string +---@param sep? string +---@param rep? string +---@return string? filename +---@return string? errmsg +---@nodiscard +function package.searchpath(name, path, sep, rep) end + +--- +---Sets a metatable for `module` with its `__index` field referring to the global environment, so that this module inherits values from the global environment. To be used as an option to function `module` . +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-package.seeall"]) +--- +---@version <5.1 +---@param module table +function package.seeall(module) end + +return package diff --git a/editor/Resources/lua/stdlib/string.lua b/editor/Resources/lua/stdlib/string.lua new file mode 100644 index 000000000..8cac0420c --- /dev/null +++ b/editor/Resources/lua/stdlib/string.lua @@ -0,0 +1,219 @@ +---@meta string + +--- +--- +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-string"]) +--- +---@class stringlib +string = {} + +--- +---Returns the internal numeric codes of the characters `s[i], s[i+1], ..., s[j]`. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-string.byte"]) +--- +---@param s string|number +---@param i? integer +---@param j? integer +---@return integer ... +---@nodiscard +function string.byte(s, i, j) end + +--- +---Returns a string with length equal to the number of arguments, in which each character has the internal numeric code equal to its corresponding argument. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-string.char"]) +--- +---@param byte integer +---@param ... integer +---@return string +---@nodiscard +function string.char(byte, ...) end + +--- +---Returns a string containing a binary representation (a *binary chunk*) of the given function. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-string.dump"]) +--- +---@param f async fun(...):... +---@param strip? boolean +---@return string +---@nodiscard +function string.dump(f, strip) end + +--- +---Looks for the first match of `pattern` (see [§6.4.1](command:extension.lua.doc?["en-us/54/manual.html/6.4.1"])) in the string. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-string.find"]) +--- +---@param s string|number +---@param pattern string|number +---@param init? integer +---@param plain? boolean +---@return integer|nil start +---@return integer|nil end +---@return any|nil ... captured +---@nodiscard +function string.find(s, pattern, init, plain) end + +--- +---Returns a formatted version of its variable number of arguments following the description given in its first argument. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-string.format"]) +--- +---@param s string|number +---@param ... any +---@return string +---@nodiscard +function string.format(s, ...) end + +--- +---Returns an iterator function. Each call to that iterator continues matching `pattern` (see [§6.4.1](command:extension.lua.doc?["en-us/54/manual.html/6.4.1"])) over s and returns all captures. +--- +---The following example iterates over all words in string s, printing one per line: +---```lua +--- s = +---"hello world from Lua" +--- for w in string.gmatch(s, "%a+") do +--- print(w) +--- end +---``` +--- +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-string.gmatch"]) +--- +---@param s string|number +---@param pattern string|number +---@param init? integer +---@return fun():string, ... +function string.gmatch(s, pattern, init) end + +--- +---Returns a copy of s where all occurrences of `pattern` (or the first n occurrences if n is given) are replaced by repl (see [§6.4.1](command:extension.lua.doc?["en-us/54/manual.html/6.4.1"])). +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-string.gsub"]) +--- +---@param s string|number +---@param pattern string|number +---@param repl string|number|table|function +---@param n? integer +---@return string +---@return integer count +function string.gsub(s, pattern, repl, n) end + +--- +---Returns its length. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-string.len"]) +--- +---@param s string|number +---@return integer +---@nodiscard +function string.len(s) end + +--- +---Returns a copy of this string with all uppercase letters changed to lowercase. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-string.lower"]) +--- +---@param s string|number +---@return string +---@nodiscard +function string.lower(s) end + +--- +---Looks for the first match of `pattern` (see [§6.4.1](command:extension.lua.doc?["en-us/54/manual.html/6.4.1"])) in the string. If it finds one, `match` returns the captures; otherwise it returns nil. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-string.match"]) +--- +---@param s string|number +---@param pattern string|number +---@param init? integer +---@return any ... +---@nodiscard +function string.match(s, pattern, init) end + +---@version >5.3 +--- +---Returns a binary string containing the values `v1`, `v2`, etc. packed (that is, serialized in binary form) according to the format string `fmt` (see [§6.4.2](command:extension.lua.doc?["en-us/54/manual.html/6.4.2"])). +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-string.pack"]) +--- +---@param fmt string +---@param v1 string|number +---@param v2? string|number +---@param ... string|number +---@return string binary +---@nodiscard +function string.pack(fmt, v1, v2, ...) end + +---@version >5.3 +--- +---Returns the length of a string resulting from `string.pack` with the given format string `fmt`. The format string cannot contain the variable-length options `s` or `z` (see [§6.4.2](command:extension.lua.doc?["en-us/54/manual.html/6.4.2"])). +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-string.packsize"]) +--- +---@param fmt string +---@return integer +---@nodiscard +function string.packsize(fmt) end + +--- +---Returns a string that is the concatenation of `n` copies of the string `s` separated by the string `sep`. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-string.rep"]) +--- +---@param s string|number +---@param n integer +---@param sep? string|number +---@return string +---@nodiscard +function string.rep(s, n, sep) end + +--- +---Returns a string that is the string `s` reversed. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-string.reverse"]) +--- +---@param s string|number +---@return string +---@nodiscard +function string.reverse(s) end + +--- +---Returns the substring of the string that starts at `i` and continues until `j`. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-string.sub"]) +--- +---@param s string|number +---@param i integer +---@param j? integer +---@return string +---@nodiscard +function string.sub(s, i, j) end + +---@version >5.3 +--- +---Returns the values packed in string according to the format string `fmt` (see [§6.4.2](command:extension.lua.doc?["en-us/54/manual.html/6.4.2"])) . +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-string.unpack"]) +--- +---@param fmt string +---@param s string +---@param pos? integer +---@return any ... +---@nodiscard +function string.unpack(fmt, s, pos) end + +--- +---Returns a copy of this string with all lowercase letters changed to uppercase. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-string.upper"]) +--- +---@param s string|number +---@return string +---@nodiscard +function string.upper(s) end + +return string diff --git a/editor/Resources/lua/stdlib/table.lua b/editor/Resources/lua/stdlib/table.lua new file mode 100644 index 000000000..bee8c0f4a --- /dev/null +++ b/editor/Resources/lua/stdlib/table.lua @@ -0,0 +1,177 @@ +---@meta table + +--- +--- +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-table"]) +--- +---@class tablelib +table = {} + +--- +---Given a list where all elements are strings or numbers, returns the string `list[i]..sep..list[i+1] ··· sep..list[j]`. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-table.concat"]) +--- +---@param list table +---@param sep? string +---@param i? integer +---@param j? integer +---@return string +---@nodiscard +function table.concat(list, sep, i, j) end + +---@version >5.5 +--- +---Creates a new empty table, preallocating memory. This preallocation may help performance and save memory when you know in advance how many elements the table will have. Parameter `nseq` is a hint for how many elements the table will have as a sequence. Optional parameter `nrec` is a hint for how many other elements the table will have; its default is zero. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-table.create"]) +--- +---@param nseq integer +---@param nrec? integer +---@return table +---@nodiscard +function table.create(nseq, nrec) end + +--- +---Inserts element `value` at position `pos` in `list`. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-table.insert"]) +--- +---@overload fun(list: table, value: any) +---@param list table +---@param pos integer +---@param value any +function table.insert(list, pos, value) end + +---@version <5.1 +--- +---Returns the largest positive numerical index of the given table, or zero if the table has no positive numerical indices. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-table.maxn"]) +--- +---@param table table +---@return integer +---@nodiscard +function table.maxn(table) end + +---@version >5.3, JIT +--- +---Moves elements from table `a1` to table `a2`. +---```lua +---a2[t],··· = +---a1[f],···,a1[e] +---return a2 +---``` +--- +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-table.move"]) +--- +---@param a1 table +---@param f integer +---@param e integer +---@param t integer +---@param a2? table +---@return table a2 +function table.move(a1, f, e, t, a2) end + +---@version >5.2, JIT +--- +---Returns a new table with all arguments stored into keys `1`, `2`, etc. and with a field `"n"` with the total number of arguments. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-table.pack"]) +--- +---@return table +---@nodiscard +function table.pack(...) end + +--- +---Removes from `list` the element at position `pos`, returning the value of the removed element. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-table.remove"]) +--- +---@param list table +---@param pos? integer +---@return any +function table.remove(list, pos) end + +--- +---Sorts list elements in a given order, *in-place*, from `list[1]` to `list[#list]`. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-table.sort"]) +--- +---@generic T +---@param list T[] +---@param comp? fun(a: T, b: T):boolean +function table.sort(list, comp) end + +---@version >5.2, JIT +--- +---Returns the elements from the given list. This function is equivalent to +---```lua +--- return list[i], list[i+1], ···, list[j] +---``` +---By default, `i` is `1` and `j` is `#list`. +--- +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-table.unpack"]) +--- +---@generic T1, T2, T3, T4, T5, T6, T7, T8, T9, T10 +---@param list { +--- [1]?: T1, +--- [2]?: T2, +--- [3]?: T3, +--- [4]?: T4, +--- [5]?: T5, +--- [6]?: T6, +--- [7]?: T7, +--- [8]?: T8, +--- [9]?: T9, +--- [10]?: T10, +---} +---@param i? integer +---@param j? integer +---@return T1, T2, T3, T4, T5, T6, T7, T8, T9, T10 +---@nodiscard +function table.unpack(list, i, j) end + +---@version <5.1, JIT +--- +---Executes the given f over all elements of table. For each element, f is called with the index and respective value as arguments. If f returns a non-nil value, then the loop is broken, and this value is returned as the final value of foreach. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-table.foreach"]) +--- +---@generic T +---@param list any +---@param callback fun(key: string, value: any):T|nil +---@return T|nil +---@deprecated +function table.foreach(list, callback) end + +---@version <5.1, JIT +--- +---Executes the given f over the numerical indices of table. For each index, f is called with the index and respective value as arguments. Indices are visited in sequential order, from 1 to n, where n is the size of the table. If f returns a non-nil value, then the loop is broken and this value is returned as the result of foreachi. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-table.foreachi"]) +--- +---@generic T +---@param list any +---@param callback fun(key: string, value: any):T|nil +---@return T|nil +---@deprecated +function table.foreachi(list, callback) end + +---@version <5.1, JIT +--- +---Returns the number of elements in the table. This function is equivalent to `#list`. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-table.getn"]) +--- +---@generic T +---@param list T[] +---@return integer +---@nodiscard +---@deprecated +function table.getn(list) end + +return table diff --git a/editor/Resources/lua/stdlib/utf8.lua b/editor/Resources/lua/stdlib/utf8.lua new file mode 100644 index 000000000..e4e2def88 --- /dev/null +++ b/editor/Resources/lua/stdlib/utf8.lua @@ -0,0 +1,87 @@ +---@meta utf8 + +---@version >5.3 +--- +--- +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-utf8"]) +--- +---@class utf8lib +--- +---The pattern which matches exactly one UTF-8 byte sequence, assuming that the subject is a valid UTF-8 string. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-utf8.charpattern"]) +--- +---@field charpattern string +utf8 = {} + +--- +---Receives zero or more integers, converts each one to its corresponding UTF-8 byte sequence and returns a string with the concatenation of all these sequences. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-utf8.char"]) +--- +---@param code integer +---@param ... integer +---@return string +---@nodiscard +function utf8.char(code, ...) end + +--- +---Returns values so that the construction +---```lua +---for p, c in utf8.codes(s) do +--- body +---end +---``` +---will iterate over all UTF-8 characters in string s, with p being the position (in bytes) and c the code point of each character. It raises an error if it meets any invalid byte sequence. +--- +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-utf8.codes"]) +--- +---@param s string +---@param lax? boolean +---@return fun(s: string, p: integer):integer, integer +function utf8.codes(s, lax) end + +--- +---Returns the codepoints (as integers) from all characters in `s` that start between byte position `i` and `j` (both included). +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-utf8.codepoint"]) +--- +---@param s string +---@param i? integer +---@param j? integer +---@param lax? boolean +---@return integer code +---@return integer ... +---@nodiscard +function utf8.codepoint(s, i, j, lax) end + +--- +---Returns the number of UTF-8 characters in string `s` that start between positions `i` and `j` (both inclusive). +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-utf8.len"]) +--- +---@param s string +---@param i? integer +---@param j? integer +---@param lax? boolean +---@return integer? +---@return integer? errpos +---@nodiscard +function utf8.len(s, i, j, lax) end + +--- +---Returns the position (in bytes) where the encoding of the `n`-th character of `s` (counting from position `i`) starts. +--- +---[View documents](command:extension.lua.doc?["en-us/54/manual.html/pdf-utf8.offset"]) +--- +---@param s string +---@param n integer +---@param i? integer +---@return integer p +---@nodiscard +function utf8.offset(s, n, i) end + + +return utf8 diff --git a/editor/editor.csproj b/editor/editor.csproj index 3b8e86899..666f36357 100644 --- a/editor/editor.csproj +++ b/editor/editor.csproj @@ -33,7 +33,8 @@ - + + @@ -60,6 +61,7 @@ runtime; build; native; contentfiles; analyzers; buildtransitive + From 5d97ac7327c25aec2f51f46353a9a6c08a0a9e86 Mon Sep 17 00:00:00 2001 From: Xein Date: Wed, 11 Nov 2026 18:38:55 +0100 Subject: [PATCH 3/8] lua graph editing --- editor/LuaEditor/Editing/GraphDocument.cs | 145 ++ .../Editing/GraphSession.Hierarchy.cs | 154 ++ editor/LuaEditor/Editing/GraphSession.cs | 1522 +++++++++++++++++ editor/LuaEditor/Editing/NodeCatalog.cs | 187 ++ editor/LuaEditor/Editing/NodeDoc.cs | 41 + editor/LuaEditor/Editing/PinStyle.cs | 59 + editor/LuaEditor/Editing/Shortcuts.cs | 67 + editor/LuaEditor/Editing/TypeText.cs | 24 + editor/LuaEditor/Layout/Arrange.cs | 130 ++ editor/LuaEditor/Layout/AutoLayout.cs | 148 ++ editor/LuaEditor/Layout/Geometry.cs | 92 + editor/LuaEditor/Layout/GraphKeys.cs | 190 ++ editor/LuaEditor/Layout/GraphLayout.cs | 231 +++ editor/LuaEditor/Layout/InlineRules.cs | 109 ++ editor/LuaEditor/Layout/LayoutEngine.cs | 246 +++ editor/LuaEditor/Layout/LayoutMeta.cs | 259 +++ editor/LuaEditor/Layout/LayoutPersistence.cs | 490 ++++++ editor/LuaEditor/Layout/NodeShape.cs | 208 +++ editor/LuaEditor/Layout/RegionPacker.cs | 74 + 19 files changed, 4376 insertions(+) create mode 100644 editor/LuaEditor/Editing/GraphDocument.cs create mode 100644 editor/LuaEditor/Editing/GraphSession.Hierarchy.cs create mode 100644 editor/LuaEditor/Editing/GraphSession.cs create mode 100644 editor/LuaEditor/Editing/NodeCatalog.cs create mode 100644 editor/LuaEditor/Editing/NodeDoc.cs create mode 100644 editor/LuaEditor/Editing/PinStyle.cs create mode 100644 editor/LuaEditor/Editing/Shortcuts.cs create mode 100644 editor/LuaEditor/Editing/TypeText.cs create mode 100644 editor/LuaEditor/Layout/Arrange.cs create mode 100644 editor/LuaEditor/Layout/AutoLayout.cs create mode 100644 editor/LuaEditor/Layout/Geometry.cs create mode 100644 editor/LuaEditor/Layout/GraphKeys.cs create mode 100644 editor/LuaEditor/Layout/GraphLayout.cs create mode 100644 editor/LuaEditor/Layout/InlineRules.cs create mode 100644 editor/LuaEditor/Layout/LayoutEngine.cs create mode 100644 editor/LuaEditor/Layout/LayoutMeta.cs create mode 100644 editor/LuaEditor/Layout/LayoutPersistence.cs create mode 100644 editor/LuaEditor/Layout/NodeShape.cs create mode 100644 editor/LuaEditor/Layout/RegionPacker.cs diff --git a/editor/LuaEditor/Editing/GraphDocument.cs b/editor/LuaEditor/Editing/GraphDocument.cs new file mode 100644 index 000000000..01ea94440 --- /dev/null +++ b/editor/LuaEditor/Editing/GraphDocument.cs @@ -0,0 +1,145 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Security.Cryptography; +using System.Text; +using editor.LuaEditor.Graph; +using editor.LuaEditor.Layout; +using editor.LuaEditor.Syntax; +using editor.LuaEditor.Types; + +namespace editor.LuaEditor.Editing; + +public enum ExternalChange { None, Reloaded, Conflict, Broken } + +public sealed class GraphDocument { + private readonly string m_stdlibDir; + private string m_lastHash = ""; + + private GraphDocument(string luaPath, string projectRoot, string stdlibDir) { + LuaPath = luaPath; + ProjectRoot = projectRoot; + m_stdlibDir = stdlibDir; + } + + public string LuaPath { get; } + public string MetaPath => LuaPath + ".meta"; + public string ProjectRoot { get; } + + public GraphSession? Session { get; private set; } + + public string? Error { get; private set; } + + public TypeUniverse Universe { get; private set; } = TypeUniverse.Build([]); + + public static GraphDocument Open(string luaPath, string projectRoot, string stdlibDir) { + var doc = new GraphDocument(luaPath, projectRoot, stdlibDir); + doc.Universe = doc.LoadUniverse(); + doc.Load(File.ReadAllText(luaPath), doc.ReadMeta()); + doc.m_lastHash = Hash(File.ReadAllText(luaPath)); + return doc; + } + + private TypeUniverse LoadUniverse() { + try { + return TypeUniverseLoader.Load(ProjectRoot, m_stdlibDir); + } catch (Exception e) when (e is IOException or UnauthorizedAccessException) { + return TypeUniverse.Build([]); + } + } + + private GraphMeta? ReadMeta() { + try { + return File.Exists(MetaPath) ? GraphMeta.Read(File.ReadAllText(MetaPath)) : null; + } catch (IOException) { + return null; + } + } + + private bool Load(string text, GraphMeta? meta) { + var document = LuaDocument.Parse(text); + if (!LuaGraph.TryBuild(document, Universe, out var graph, out var errors)) { + Session = null; + Error = errors.Count > 0 ? $"line {errors[0].Location.Line}: {errors[0].Message}" : "the script could not be read"; + return false; + } + Session = GraphSession.Open(graph!, meta); + Error = null; + return true; + } + + public bool Save(out string? message) { + message = null; + if (Session is null) { + message = "the script has errors and cannot be saved from the graph"; + return false; + } + var text = Session.SaveText(); + if (text is null) { + message = Session.Message; + return false; + } + try { + var metaText = Session.CaptureLayout().Write(File.Exists(MetaPath) ? File.ReadAllText(MetaPath) : ""); + WriteAtomic(LuaPath, text); + if (metaText is not null) WriteAtomic(MetaPath, metaText); + m_lastHash = Hash(text); + } catch (Exception e) when (e is IOException or UnauthorizedAccessException) { + message = "could not write the file: " + e.Message; + return false; + } + Session.MarkSaved(text); + return true; + } + + private static void WriteAtomic(string path, string content) { + var temp = path + ".tmp"; + File.WriteAllText(temp, content, new UTF8Encoding(false)); + File.Move(temp, path, overwrite: true); + } + + public ExternalChange CheckDisk() { + string text; + try { + text = File.ReadAllText(LuaPath); + } catch (IOException) { + return ExternalChange.None; + } + if (Hash(text) == m_lastHash) return ExternalChange.None; + if (Session is { IsDirty: true }) return ExternalChange.Conflict; + return AcceptDiskVersion() ? ExternalChange.Reloaded : ExternalChange.Broken; + } + + public bool AcceptDiskVersion() { + var text = File.ReadAllText(LuaPath); + m_lastHash = Hash(text); + var meta = Session?.CaptureLayout() ?? ReadMeta(); + return Load(text, meta); + } + + public bool LoadRecovered(string text) { + if (!Load(text, ReadMeta())) return false; + Session!.MarkDirty(); + return true; + } + + public void KeepMine() => m_lastHash = Hash(File.ReadAllText(LuaPath)); + + public void ReloadTypes() { + var text = Session?.SaveText() ?? File.ReadAllText(LuaPath); + var meta = Session?.CaptureLayout() ?? ReadMeta(); + Universe = LoadUniverse(); + Load(text, meta); + } + + private static string Hash(string text) => Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(text))); + + public IReadOnlyList LibraryFolders() { + var folders = new List(); + foreach (var entry in LuaRc.Load(ProjectRoot, []).Libraries) { + var full = Path.GetFullPath(Path.Combine(ProjectRoot, entry)); + if (Directory.Exists(full)) folders.Add(full); + } + return folders; + } +} diff --git a/editor/LuaEditor/Editing/GraphSession.Hierarchy.cs b/editor/LuaEditor/Editing/GraphSession.Hierarchy.cs new file mode 100644 index 000000000..6d60f3f59 --- /dev/null +++ b/editor/LuaEditor/Editing/GraphSession.Hierarchy.cs @@ -0,0 +1,154 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using editor.LuaEditor.Graph; +using editor.LuaEditor.Layout; +using editor.LuaEditor.Types; + +namespace editor.LuaEditor.Editing; + +public sealed partial class GraphSession { + public static IReadOnlyList TickFunctions { get; } = Array.AsReadOnly(new[] { + "load", "init", "begin", "earlyTick", "tick", "physicsTick", "lateTick", "_end", "destroy", + "save", "editorTick", "onEnable", "onDisable", "postPhysics" + }); + + public IEnumerable SourceClasses() { + var pending = new Queue(); + if (ScriptInfo.Find(Graph) is { } script) + foreach (var parent in (script.ClassTag?.Bases ?? []).OfType()) pending.Enqueue(parent.Name); + var seen = new HashSet(StringComparer.Ordinal); + while (pending.TryDequeue(out var name)) { + if (!seen.Add(name) || Universe.FindClass(name) is not { } info) continue; + yield return info; + foreach (var parent in info.Bases.OfType()) pending.Enqueue(parent.Name); + } + } + + public NodeEntry HierarchyEntry(GraphVariable variable, Binding? binding, MemberInfo? native, bool set, bool dot) { + var name = variable.Name; + if (variable.Kind == VariableKind.Function || binding is not null && variable.Type is FunctionType) { + var colon = native?.Decl.IsMethod ?? (variable.Declaration as FunctionDecl)?.IsMethod ?? false; + var dotCall = binding is null && (dot || native is { Decl.IsMethod: false }); + var signature = variable.Type as FunctionType; + if (dotCall && colon && signature is not null) { + var owner = native?.DeclaringClass ?? ScriptInfo.Find(Graph)?.ClassName ?? ScriptInfo.UnnamedClass; + signature = signature with { Params = signature.Params.Prepend(new Param("self", new NamedType(owner, []), false)).ToList() }; + } + if (binding is null && !dotCall && !colon && signature is not null) + signature = signature with { Params = signature.Params.Skip(1).ToList() }; + return new NodeEntry(dotCall || binding is not null ? NodeKind.CallGlobal : NodeKind.CallMethod, name + "()", + native is null ? "Script functions" : "C++ " + native.DeclaringClass, name, + Name: name, Owner: native?.DeclaringClass ?? ScriptOwner, Binding: binding, Signature: signature, DotCall: dotCall); + } + return new NodeEntry(set ? NodeKind.SetVariable : NodeKind.GetVariable, (set ? "Set " : "Get ") + name, + "Variables", name, Name: name, Owner: native is not null ? BaseOwner : variable.Kind.ToString(), + Result: set ? null : variable.Type, FirstInput: set ? variable.Type : null, Binding: binding); + } + + private void BindHierarchyCall(NodeEntry entry, CallNode call, Block? block) { + if (entry.Binding is not null || !IsOwnCall(entry) || ObjectSource(block) is not { } owner) return; + if (entry.DotCall) { + var member = new MemberGet(Graph, entry.Name!); + member.Object.Connect(owner); + call.Target.Connect(member.Result); + if (entry.Signature?.Params.FirstOrDefault()?.Name == "self" && call.Args.Count > 0) call.Args[0].Connect(owner); + } else { + ConnectCore(owner, call.Target); + } + } + + public bool DuplicateField(AssignStatement field, string name) => Edit(() => { + if (ScriptInfo.Find(Graph)?.Fields.Any(f => f.Statement == field) != true) + throw new InvalidOperationException("the field no longer exists"); + var block = field.Parent!; + var index = block.IndexOf(field) + 1; + var result = Fragments.Paste(Graph, Fragments.Copy([field]), block, index); + if (result.Errors.Count > 0) throw new InvalidOperationException(result.Errors[0].Message); + if (block.Statements[index] is not AssignStatement copy) + throw new InvalidOperationException("could not duplicate the field"); + copy.Targets[0].Name = name; + }); + + public static InputPin? VariableDefault(GraphVariable variable, Binding? binding) => + variable.Declaration switch { + AssignStatement assignment when variable.Kind == VariableKind.Field => assignment.Values.FirstOrDefault(), + LocalDecl local when binding is not null && local.Names.IndexOf(binding) is var index && index >= 0 => + local.Values.ElementAtOrDefault(index), + _ => null + }; + + public static LuaConstant? LiteralDefault(InputPin? pin) => pin?.Constant ?? + (pin?.Source?.Owner is UnaryOp { Op: UnaryKind.Neg, Operand.Constant: { Kind: ConstantKind.Number } number } + ? LuaConstant.Number("-" + number.Raw) : null); + + public bool SetVariableDefault(GraphVariable variable, Binding? binding, LuaConstant value) => Edit(() => { + var pin = EnsureVariableDefault(variable, binding); + if (pin.Source is not null && LiteralDefault(pin) is null) + throw new InvalidOperationException("this variable has an expression initializer; use init() for graph initialization"); + Graph.SetConstant(pin, value); + }); + + public bool SetVariableType(GraphVariable variable, Binding? binding, LuaType? type) => Edit(() => { + if (variable.Declaration is LocalDecl local && binding != local.Names[0]) + throw new InvalidOperationException("declare this local on its own line to set its type"); + Graph.SetDeclaredType(variable.Declaration, type); + if (type is null) return; + + var resolved = Universe.ResolveAliases(type); + if (resolved is UnionType union && union.Members.Count(member => member != LuaType.Nil) == 1) + resolved = union.Members.First(member => member != LuaType.Nil); + var initial = VariableDefault(variable, binding); + var isMarker = initial?.Source?.Owner is GlobalGet old && Universe.GlobalType(old.Name) is NamedType { Name: "TypeMarker" }; + var literal = LiteralDefault(initial); + if (initial is { Source: not null } && literal is null && !isMarker) return; + + var value = resolved switch { + PrimitiveType { Kind: PrimitiveKind.Integer } => LuaConstant.Integer(0), + PrimitiveType { Kind: PrimitiveKind.Number } => LuaConstant.Float(0), + PrimitiveType { Kind: PrimitiveKind.Boolean } => LuaConstant.False, + PrimitiveType { Kind: PrimitiveKind.String } => LuaConstant.String(""), + _ => null + }; + if (value is not null) { + if (literal is { Kind: not ConstantKind.Nil } && m_checker.Check(literal.ValueType, resolved).Kind == Compat.Allowed) return; + Graph.SetConstant(EnsureVariableDefault(variable, binding), value); + } else if (variable is { Kind: VariableKind.Field, Exported: true } && resolved is NamedType named && + Universe.GlobalType(named.Name) is NamedType { Name: "TypeMarker", Args: [var target] } && target == resolved && + variable.Declaration.Parent is { } block && + !LuaGraph.VisibleFromBlock(block, block.IndexOf(variable.Declaration)).Any(visible => visible.Name == named.Name)) { + Graph.Connect(new GlobalGet(Graph, named.Name).Result, EnsureVariableDefault(variable, binding)); + } else if (initial is not null && (isMarker || literal is { Kind: not ConstantKind.Nil } && + (resolved is ArrayType or TableType or PrimitiveType { Kind: PrimitiveKind.Table } || + resolved is NamedType reference && Universe.GlobalType(reference.Name) is NamedType { Name: "TypeMarker" }))) { + Graph.SetConstant(initial, LuaConstant.Nil); + } + }); + + private InputPin EnsureVariableDefault(GraphVariable variable, Binding? binding) { + if (VariableDefault(variable, binding) is { } existing) return existing; + if (variable.Declaration is not LocalDecl local || binding is null || local.Names.IndexOf(binding) is not (>= 0 and var index)) + throw new InvalidOperationException("this declaration has no editable default"); + if (local.Values.LastOrDefault()?.Source is { Binding: null, Index: 0, Owner: CallNode or VarargNode }) + throw new InvalidOperationException("this local gets its value from a multi-value initializer"); + while (local.Values.Count <= index) local.AddValue().SetConstant(LuaConstant.Nil); + return local.Values[index]; + } + + public bool MakeLocalFunction(Binding binding) => Edit(() => { + if (binding.Declarer is not LocalDecl { Names.Count: 1 } local || local.Parent != Graph.Module || + binding.Attribute is not null || binding.IsMutable || + local.Values.Any(pin => pin.Source is not null || pin.Constant is { Kind: not ConstantKind.Nil })) + throw new InvalidOperationException("choose an unassigned local with no initial value to create a function"); + var index = Graph.Module.IndexOf(local); + var function = new FunctionDecl(Graph, true, binding.Name); + function.LeadingLines.AddRange(local.LeadingLines); + Graph.SetDeclaredType(function, null); + var oldOutput = binding.Output; + function.AdoptLocalBinding(binding); + foreach (var consumer in oldOutput.Consumers.ToList()) consumer.Connect(binding.Output); + local.Names.Clear(); + Graph.Remove(local); + Graph.Module.Insert(index, function); + }); +} diff --git a/editor/LuaEditor/Editing/GraphSession.cs b/editor/LuaEditor/Editing/GraphSession.cs new file mode 100644 index 000000000..c906201ce --- /dev/null +++ b/editor/LuaEditor/Editing/GraphSession.cs @@ -0,0 +1,1522 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.RegularExpressions; +using editor.LuaEditor.Graph; +using editor.LuaEditor.Layout; +using editor.LuaEditor.Syntax; +using editor.LuaEditor.Types; + +namespace editor.LuaEditor.Editing; + +public readonly record struct InsertPoint(Block Block, int Index); + +internal sealed record SessionSnapshot(string Text, GraphMeta Meta); + +public sealed partial class GraphSession { + private static readonly Regex s_number = new(@"^[+-]?(0[xX][0-9a-fA-F]+|\d+\.?\d*([eE][+-]?\d+)?|\.\d+([eE][+-]?\d+)?)$", RegexOptions.Compiled); + private readonly List m_undo = []; + private readonly List m_redo = []; + private readonly TypeChecker m_checker; + private SessionSnapshot m_current; + private int m_savedStep; + private int m_step; + + public GraphSession(LuaGraph graph, GraphLayout layout) { + Graph = graph; + Layout = layout; + Universe = graph.Universe; + Catalog = new NodeCatalog(Universe); + m_checker = new TypeChecker(Universe); + Graph.Analyze(); + m_current = TakeSnapshot() ?? new SessionSnapshot(graph.Document.Text, LayoutPersistence.Capture(layout)); + } + + public static GraphSession Open(LuaGraph graph, GraphMeta? meta, INodeMeasure? measure = null) + => new(graph, LayoutPersistence.Restore(graph, meta, measure)); + + public LuaGraph Graph { get; private set; } + public GraphLayout Layout { get; private set; } + public TypeUniverse Universe { get; } + public NodeCatalog Catalog { get; } + public List Selection { get; } = []; + + public string? Message { get; private set; } + + public void MarkDirty() { + m_step++; + Raise(); + } + + public bool CanUndo => m_undo.Count > 0; + public bool CanRedo => m_redo.Count > 0; + public bool IsDirty => m_step != m_savedStep; + + public event Action? Changed; + public event Action? SelectionChanged; + + private void Raise() => Changed?.Invoke(); + + private T WithoutFloating(Func action) { + var held = Graph.Nodes.OfType().Where(x => x.IsFloating && x.Parent is not null).Select(x => (Block: x.Parent!, Index: x.Parent!.IndexOf(x), Statement: x)).OrderBy(h => h.Index).ToList(); + foreach (var (block, _, statement) in held.AsEnumerable().Reverse()) block.Remove(statement); + try { + return action(); + } finally { + foreach (var (block, index, statement) in held) block.Insert(Math.Min(index, block.Statements.Count), statement); + } + } + + private SaveResult SaveGraph() => WithoutFloating(() => Graph.Save()); + + private SessionSnapshot? TakeSnapshot() { + var saved = SaveGraph(); + + return saved.Errors.Count > 0 ? null : new SessionSnapshot(saved.Text, LayoutPersistence.Capture(Layout)); + } + + private bool Edit(Action edit, bool structural = true) { + var before = m_current; + var activeFrames = Layout.Embedded.Select(frame => (frame.Key, frame.Value, Call: NodeShape.CallOf(frame.Value))).ToArray(); + try { + edit(); + } catch (Exception e) when (e is InvalidOperationException or ArgumentException) { + Message = e.Message; + // failed edits can leave partially built nodes behind + Restore(before); + Raise(); + return false; + } + + if (structural) { + Layout.Refresh(); + if (activeFrames.Any(frame => !Layout.Embedded.TryGetValue(frame.Key, out var host) || host != frame.Value && (frame.Call is null || NodeShape.CallOf(host) != frame.Call) || + Layout.HostBody(host) is { } containing && Layout.Embedded.ContainsKey(containing))) { + Message = "close the active POE frame first"; + Restore(before); + Raise(); + return false; + } + LayoutEngine.PlaceUnplaced(Layout); + LayoutEngine.PlaceNewRegions(Layout); + Graph.Analyze(); + LayoutEngine.FollowHosts(Layout); + var next = TakeSnapshot(); + if (next is null) { + var errors = SaveGraph().Errors; + Message = errors.Count > 0 ? errors[0].Message : "that edit cannot be written as Lua"; + Restore(before); + Raise(); + return false; + } + m_current = next; + } else { + m_current = before with { Meta = LayoutPersistence.Capture(Layout) }; + } + + m_undo.Add(before); + m_redo.Clear(); + m_step++; + Message = null; + Raise(); + return true; + } + + private void Restore(SessionSnapshot snapshot) { + var document = LuaDocument.Parse(snapshot.Text); + if (!LuaGraph.TryBuild(document, Universe, out var graph, out _)) { + Message = "could not rebuild the graph"; + return; + } + Graph = graph!; + Graph.Analyze(); + Layout = LayoutPersistence.Restore(Graph, snapshot.Meta, Layout.Measure); + m_current = snapshot; + Selection.Clear(); + } + + public void Undo() { + if (m_undo.Count == 0) return; + var target = m_undo[^1]; + m_undo.RemoveAt(m_undo.Count - 1); + m_redo.Add(m_current); + Restore(target); + m_step--; + Raise(); + } + + public void Redo() { + if (m_redo.Count == 0) return; + var target = m_redo[^1]; + m_redo.RemoveAt(m_redo.Count - 1); + m_undo.Add(m_current); + Restore(target); + m_step++; + Raise(); + } + + public string? SaveText() { + var result = SaveGraph(); + if (result.Errors.Count > 0) { + Message = result.Errors[0].Message; + return null; + } + return result.Text; + } + + public GraphMeta CaptureLayout() => LayoutPersistence.Capture(Layout); + + public void MarkSaved(string writtenText) { + var meta = LayoutPersistence.Capture(Layout); + var selected = Selection.Select(Layout.Keys.KeyOf).OfType().ToList(); + Restore(new SessionSnapshot(writtenText, meta)); + Selection.AddRange(selected.Select(Layout.Keys.NodeOf).OfType()); + m_savedStep = m_step; + Message = null; + Raise(); + } + + public bool Reload(string text) { + var document = LuaDocument.Parse(text); + if (document.HasErrors) { + Message = $"line {document.Errors[0].Location.Line}: {document.Errors[0].Message}"; + Raise(); + return false; + } + var meta = LayoutPersistence.Capture(Layout); + Restore(new SessionSnapshot(text, meta)); + m_undo.Clear(); + m_redo.Clear(); + m_step = m_savedStep = 0; + Message = null; + Raise(); + return true; + } + + public void Select(IEnumerable nodes, bool additive = false) { + var set = nodes.Select(InlineRules.Drawn).Distinct().ToList(); + if (!additive) Selection.Clear(); + foreach (var node in set) { + if (additive && Selection.Contains(node)) Selection.Remove(node); + else Selection.Add(node); + } + SelectionChanged?.Invoke(); + Raise(); + } + + public void ClearSelection() { + Selection.Clear(); + SelectionChanged?.Invoke(); + Raise(); + } + + public void SelectAll() { + Selection.Clear(); + foreach (var (node, _) in Layout.Keys.Ordered) + if (!InlineRules.IsMerged(node) && node is not FunctionEntry) Selection.Add(node); + Selection.AddRange(Layout.Loose); + SelectionChanged?.Invoke(); + Raise(); + } + + public CompatResult CanConnect(OutputPin from, InputPin to) { + if (from.Owner == to.Owner) return CompatResult.Block("a node cannot be wired to itself"); + if (to.Owner is Statement && to.Owner.Inputs.Contains(to) is false) return CompatResult.Block("that pin is gone"); + if (Reaches(from.Owner, to.Owner)) return CompatResult.Block("that would make a value depend on itself"); + var expected = to.Expected; + if (expected is null || expected == LuaType.Unknown) return CompatResult.Ok; + return m_checker.Check(from.Type == LuaType.Unknown ? LuaType.Any : from.Type, expected); + } + + private static bool Reaches(GraphNode start, GraphNode target) { + var seen = new HashSet(); + var stack = new Stack(); + stack.Push(start); + while (stack.Count > 0) { + var node = stack.Pop(); + if (!seen.Add(node)) continue; + if (node == target) return true; + foreach (var input in node.Inputs) + if (input.Source is { Binding: null } source) stack.Push(source.Owner); + } + return false; + } + + public bool Connect(OutputPin from, InputPin to, GraphNode? callableHost = null) { + var compat = CanConnect(from, to); + if (compat.Kind == Compat.Blocked) { + Message = compat.Reason; + Raise(); + return false; + } + return Edit(() => { + ConnectCore(from, to); + if (callableHost is null) Layout.CallableWireHosts.Remove(to); + else Layout.CallableWireHosts[to] = callableHost; + }); + } + + public bool ConnectFrameReturn(FunctionDecl function, int index, OutputPin from, GraphNode? callableHost = null) { + var body = function.Entry.Body; + if (!Layout.Embedded.ContainsKey(body) || index < 0) return false; + if (NodeShape.TrailingReturn(body) is { } existing && index < existing.Values.Count) + return Connect(from, existing.Values[index], callableHost); + return Edit(() => { + var ret = NodeShape.TrailingReturn(body) ?? Graph.Insert(body, body.Statements.Count, new ReturnStatement(Graph)); + while (ret.Values.Count <= index) ret.AddValue().SetConstant(LuaConstant.Nil); + var pin = ret.Values[index]; + ConnectCore(from, pin); + if (callableHost is not null) Layout.CallableWireHosts[pin] = callableHost; + }); + } + + public bool ConnectFrameExit(FunctionDecl function, Statement statement) { + var body = function.Entry.Body; + if (!Layout.Embedded.ContainsKey(body)) return false; + var wasFloating = statement.IsFloating; + var at = Layout.Position(statement); + var ok = Edit(() => { + var ret = NodeShape.TrailingReturn(body); + if (statement is ReturnStatement && ret is not null && ret != statement) + throw new InvalidOperationException("the frame already has a return. Use the value inputs on its right rail"); + statement.IsFloating = false; + Graph.Move(statement, body, ret is not null && ret != statement ? body.IndexOf(ret) : body.Statements.Count); + }); + if (ok && wasFloating) { + AdoptLoose(statement, at); + m_current = m_current with { Meta = LayoutPersistence.Capture(Layout) }; + Raise(); + } + return ok; + } + + private void ConnectCore(OutputPin from, InputPin to) { + if (from.Owner is CallNode call && call.OwnerStatement is CallStatement statement && statement.Call.Source?.Owner == call) { + if (statement.IsFloating) throw new InvalidOperationException("wire the call into the flow before using its result"); + var count = Math.Max(call.ReturnCount, from.Index + 1); + var used = Graph.Nodes.SelectMany(node => node.Outputs).Select(pin => pin.Binding?.Name).OfType() + .Concat(Graph.Nodes.OfType().Select(global => global.Name)).ToHashSet(); + var names = new List(); + for (var i = 1; names.Count < count; i++) { + var name = i == 1 ? "result" : "result" + i; + if (used.Add(name)) names.Add(name); + } + var capture = Graph.CaptureCallResults(statement, names); + if (Layout.Local.Remove(statement, out var position)) Layout.Local[capture] = position; + if (Layout.PinnedNodes.Remove(statement)) Layout.PinnedNodes.Add(capture); + if (Layout.ExecReroutes.Remove(statement, out var bends)) Layout.ExecReroutes[capture] = bends; + foreach (var pin in Layout.CallableWireHosts.Where(wire => wire.Value == statement).Select(wire => wire.Key).ToList()) + Layout.CallableWireHosts[pin] = capture; + foreach (var group in Layout.Groups) { + var index = group.Members.IndexOf(statement); + if (index >= 0) group.Members[index] = capture; + } + if (statement.IsExpanded && NodeShape.LocalCalleeOf(capture) is { } callee) { + capture.IsExpanded = true; + Layout.Embedded[callee.Entry.Body] = capture; + } + var selection = Selection.IndexOf(statement); + if (selection >= 0) Selection[selection] = capture; + from = capture.Names[from.Index].Output; + } + if (from.Owner is RawExpression raw && ParseConstant(raw.Text, null) is { } constant) { + Graph.SetConstant(to, constant); + Layout.Loose.Remove(raw); + Layout.Local.Remove(raw); + Graph.Unregister(raw); + return; + } + var wasLoose = from.Owner is ExprNode && Layout.Loose.Contains(from.Owner); + var abs = wasLoose ? Layout.Position(from.Owner) : default; + Graph.Connect(from, to); + if (wasLoose) AdoptLoose(from.Owner, abs); + } + + private void AdoptLoose(GraphNode node, Vec absolute) { + Layout.Refresh(); + Layout.Loose.Remove(node); + Layout.SetPosition(node, absolute); + foreach (var input in node.Inputs) + if (input.Source?.Owner is { } child && Layout.Loose.Contains(child)) AdoptLoose(child, Layout.Position(child)); + } + + public bool Disconnect(InputPin pin) => Edit(() => Graph.Disconnect(pin)); + + public bool MoveWires(OutputPin from, OutputPin to) => Edit(() => { + foreach (var pin in from.Consumers.ToList()) ConnectCore(to, pin); + }); + + public bool SetConstant(InputPin pin, string text) { + var constant = ParseConstantFor(pin, text); + if (constant is null) { + Message = $"\"{text}\" is not a value that fits here"; + Raise(); + return false; + } + return Edit(() => Graph.SetConstant(pin, constant)); + } + + public static LuaConstant? ParseConstantFor(InputPin pin, string text) { + var wantsText = pin.Constant?.Kind == ConstantKind.String || IsTextType(pin.Expected); + if (!wantsText) return ParseConstant(text, pin.Expected); + var t = text.Trim(); + if (t.Length >= 2 && ((t[0] == '"' && t[^1] == '"') || (t[0] == '\'' && t[^1] == '\''))) return new LuaConstant(ConstantKind.String, t); + return LuaConstant.String(text); + } + + private static bool IsTextType(LuaType? type) => type switch { + PrimitiveType { Kind: PrimitiveKind.String } => true, + LiteralType { Value: string } => true, + UnionType u => u.Members.Any(m => m is not PrimitiveType { Kind: PrimitiveKind.Nil }) && u.Members.All(m => m is PrimitiveType { Kind: PrimitiveKind.String or PrimitiveKind.Nil } or LiteralType { Value: string }), + _ => false + }; + + public static string DisplayText(LuaConstant constant) { + if (constant.Kind != ConstantKind.String || constant.Raw.Length < 2) return constant.Raw; + var inner = constant.Raw[1..^1]; + if (inner.StartsWith("[", StringComparison.Ordinal)) return constant.Raw; + return inner.Replace("\\\"", "\"").Replace("\\n", "\n").Replace("\\t", "\t").Replace("\\\\", "\\"); + } + + public sealed record PinChoice(string Label, bool IsCurrent, Action Apply); + + public IReadOnlyList? ChoicesFor(InputPin pin) { + if (pin.Expected is not { } expected) return null; + var resolved = Universe.ResolveAliases(expected); + if (resolved is NamedType named && Universe.FindEnum(named.Name) is { } decl) { + var current = InlineRules.EnumValueOf(pin); + return decl.Members.Select(m => new PinChoice(m.Name, m.Name == current, () => Create(new NodeEntry(NodeKind.Member, decl.TableName + "." + m.Name, "", "", Name: m.Name, Owner: decl.TableName), default, into: pin))).ToList(); + } + if (resolved is UnionType union) { + var options = union.Members.Where(m => m is not PrimitiveType { Kind: PrimitiveKind.Nil }).ToList(); + if (options.Count > 1 && options.All(m => m is LiteralType)) { + return options.Cast().Select(l => { + var constant = l.Value is string s ? LuaConstant.String(s) : l.Value is bool b ? (b ? LuaConstant.True : LuaConstant.False) : LuaConstant.Number(Convert.ToString(l.Value, System.Globalization.CultureInfo.InvariantCulture) ?? "0"); + return new PinChoice(DisplayText(constant), pin.Constant == constant, () => SetConstantValue(pin, constant)); + }).ToList(); + } + } + return null; + } + + public bool SetConstantValue(InputPin pin, LuaConstant constant) => Edit(() => Graph.SetConstant(pin, constant)); + + public static bool IsBoolean(InputPin pin) => pin.Constant?.Kind == ConstantKind.Boolean || pin.Expected is PrimitiveType { Kind: PrimitiveKind.Boolean }; + + public bool Toggle(InputPin pin) => SetConstantValue(pin, pin.Constant?.Raw == "true" ? LuaConstant.False : LuaConstant.True); + + public static LuaConstant? ParseConstant(string text, LuaType? expected) { + var t = text.Trim(); + if (t == "nil") return LuaConstant.Nil; + if (t == "true") return LuaConstant.True; + if (t == "false") return LuaConstant.False; + if (s_number.IsMatch(t)) return LuaConstant.Number(t); + if (t.Length >= 2 && ((t[0] == '"' && t[^1] == '"') || (t[0] == '\'' && t[^1] == '\''))) return new LuaConstant(ConstantKind.String, t); + if (expected is PrimitiveType { Kind: PrimitiveKind.String } || expected is null) return expected is null ? null : LuaConstant.String(text); + return null; + } + + public GraphNode? Create(NodeEntry entry, Vec at, OutputPin? from = null, InputPin? into = null, InsertPoint? insert = null) { + GraphNode? created = null; + var statementCall = entry.Kind is NodeKind.CallGlobal or NodeKind.CallMethod && into is null; + var ok = Edit(() => { + var standalone = from is null || from.Owner.OwnerStatement is null; + var floating = (entry.IsStatement || statementCall) && insert is null && standalone; + created = entry.IsStatement || statementCall + ? CreateStatement(entry, at, from, insert ?? (standalone ? FloatingPlace(at) : InsertionFor(from, at))) + : CreateValue(entry, at, from, into); + if (floating && created is Statement made) { + made.IsFloating = true; + Layout.Loose.Add(made); + Layout.Local[made] = at; + } + }); + + if (!ok) return null; + if (created is not null) { + Layout.Refresh(); + if (InlineRules.Drawn(created) is var drawn && Layout.IsPlaced(drawn)) { + var delta = at - Layout.Position(drawn); + if (drawn is Statement or ExprNode) MoveGroup(drawn, delta); + LayoutEngine.Separate(Layout, [drawn]); + } + Selection.Clear(); + Selection.Add(InlineRules.Drawn(created)); + SelectionChanged?.Invoke(); + RetidyFrameOf(created); + Raise(); + } + return created; + } + + private Statement CreateStatement(NodeEntry entry, Vec at, OutputPin? from, InsertPoint point) { + Statement statement = entry.Kind switch { + NodeKind.If => MakeIf(), + NodeKind.While => MakeWhile(), + NodeKind.Repeat => MakeRepeat(), + NodeKind.NumericFor => MakeNumericFor(point), + NodeKind.GenericFor => MakeGenericFor(point, entry.Name == "pairs"), + NodeKind.SetIndex => MakeSetIndex(), + NodeKind.SetMember => MakeSetMember(entry), + NodeKind.Do => new DoStatement(Graph), + NodeKind.Return => new ReturnStatement(Graph), + NodeKind.Break => new BreakStatement(Graph), + NodeKind.Sequence => MakeSequence(), + NodeKind.Local => MakeLocal(point), + NodeKind.Cast => new CastStatement(Graph, from?.Binding?.Name ?? from?.Name ?? "value", "any"), + NodeKind.Comment => new CommentStatement(Graph, ["-- comment"]), + NodeKind.RawStatement => new RawStatement(Graph, "do end"), + NodeKind.SetVariable => MakeSet(entry), +NodeKind.CallGlobal or NodeKind.CallMethod => MakeCallStatement(entry, point.Block), + _ => throw new InvalidOperationException("that node is not a statement") + }; + BringLocalCalleeIntoScope(statement, point.Block); + Graph.Insert(point.Block, point.Index, statement); + if (statement is AssignStatement { Targets: [{ Object: { } objectPin }] } && entry.Kind == NodeKind.SetVariable && ObjectSource(point.Block) is { } owner) ConnectCore(owner, objectPin); + if (from is not null && PrimaryInput(statement) is { } pin) ConnectCore(from, pin); + return statement; + } + + private IfStatement MakeIf() { + var statement = new IfStatement(Graph); + statement.AddClause().Condition.SetConstant(LuaConstant.True); + return statement; + } + + private WhileStatement MakeWhile() { + var statement = new WhileStatement(Graph); + statement.Condition.SetConstant(LuaConstant.True); + return statement; + } + + private RepeatStatement MakeRepeat() { + var statement = new RepeatStatement(Graph); + statement.Condition.SetConstant(LuaConstant.True); + return statement; + } + + private NumericFor MakeNumericFor(InsertPoint point) { + var statement = new NumericFor(Graph, FreeName(point, ["i", "j", "k", "n"])); + statement.Start.SetConstant(LuaConstant.Integer(1)); + statement.Limit.SetConstant(LuaConstant.Integer(10)); + return statement; + } + + private AssignStatement MakeSetIndex() { + var assign = new AssignStatement(Graph); + assign.AddIndexTarget(); + assign.AddValue(); + return assign; + } + + private AssignStatement MakeSetMember(NodeEntry entry) { + var assign = new AssignStatement(Graph); + assign.AddMemberTarget(entry.Name ?? "name"); + assign.AddValue(); + return assign; + } + + private GenericFor MakeGenericFor(InsertPoint point, bool pairs = false) { + var statement = new GenericFor(Graph); + statement.AddVar(FreeName(point, pairs ? ["key", "k", "_k"] : ["_", "_k", "_i"])); + statement.AddVar(FreeName(point, ["value", "item", "entry"])); + var call = new CallNode(Graph, CallStyle.Function, null); + call.Target.Connect(new GlobalGet(Graph, pairs ? "pairs" : "ipairs").Result); + + call.AddArg("t"); + statement.AddExpr().Connect(call.Result); + return statement; + } + + private SequenceStatement MakeSequence() { + var statement = new SequenceStatement(Graph); + statement.AddBranch(); + statement.AddBranch(); + return statement; + } + + private LocalDecl MakeLocal(InsertPoint point) => Graph.NewLocal(FreeName(point, ["value", "temp", "result", "item"])); + + private CallStatement MakeCallStatement(NodeEntry entry, Block block) { + var call = (CallNode)BuildCall(entry); + BindHierarchyCall(entry, call, block); + var statement = new CallStatement(Graph); + statement.Call.Connect(call.Result); + return statement; + } + + private string FreeName(InsertPoint point, string[] candidates) { + var visible = LuaGraph.VisibleFromBlock(point.Block, Math.Min(point.Index, point.Block.Statements.Count)).Select(b => b.Name).ToHashSet(); + foreach (var name in candidates) + if (!visible.Contains(name)) return name; + for (var i = 2;; i++) + if (!visible.Contains(candidates[0] + i)) return candidates[0] + i; + } + + private GraphNode? CreateValue(NodeEntry entry, Vec at, OutputPin? from, InputPin? into) { + if (entry.Kind == NodeKind.GetVariable) return GetVariable(entry, at, from, into); + if (entry.Kind == NodeKind.GetSelf) return GetSelf(entry, at, into); + if (entry.Kind == NodeKind.Lambda) return MakeLambda(at, into); + if (into is not null && entry.Kind is NodeKind.Number or NodeKind.String or NodeKind.Boolean or NodeKind.Nil) { + var literal = entry.Kind switch { + NodeKind.Number => LuaConstant.Integer(0), + NodeKind.String => LuaConstant.String(""), + NodeKind.Boolean => LuaConstant.False, + _ => LuaConstant.Nil + }; + Graph.SetConstant(into, literal); + return new RawExpression(Graph, literal.Raw); + } + + ExprNode node = entry.Kind switch { + NodeKind.Binary => new BinaryOp(Graph, entry.Binary!.Value), + NodeKind.Unary => new UnaryOp(Graph, entry.Unary!.Value), + NodeKind.Number => new RawExpression(Graph, "0"), + NodeKind.String => new RawExpression(Graph, "\"\""), + NodeKind.Boolean => new RawExpression(Graph, "false"), + NodeKind.Nil => new RawExpression(Graph, "nil"), +NodeKind.MakeTable => MakeTable(entry), + NodeKind.RawExpression => new RawExpression(Graph, "nil"), + NodeKind.Index => new IndexGet(Graph), + NodeKind.GetGlobal => new GlobalGet(Graph, entry.Name!), + NodeKind.Member => MakeMember(entry), + NodeKind.CallGlobal or NodeKind.CallMethod or NodeKind.VectorConstructor => BuildCall(entry), + _ => throw new InvalidOperationException("that node is not a value") + }; + + if (node is CallNode scriptCall) BindHierarchyCall(entry, scriptCall, into?.Owner.OwnerStatement?.Parent ?? BlockAt(at)); + if (from is not null && PrimaryInput(node) is { } input) ConnectCore(from, input); + if (into is not null && entry.Kind is not (NodeKind.Number or NodeKind.String or NodeKind.Boolean or NodeKind.Nil)) ConnectCore(node.Result, into); + else if (into is null) { + Layout.Loose.Add(node); + Layout.Local[node] = at; + } + return node; + } + + private GraphVariable VariableOf(NodeEntry entry) { + if (entry.Binding is { Declarer: Statement declaration } binding) + return new GraphVariable(binding.Name, VariableKind.ModuleLocal, false, binding.Type, null, "", declaration); + if (entry.Owner == BaseOwner && ScriptInfo.Find(Graph) is { } script) return new GraphVariable(entry.Name!, VariableKind.Field, true, entry.Result ?? entry.FirstInput ?? LuaType.Any, null, entry.Doc, script.Declaration); + return Graph.Variables.FirstOrDefault(v => v.Name == entry.Name && v.Kind.ToString() == entry.Owner) ?? throw new InvalidOperationException($"there is no variable called {entry.Name}"); + } + + public const string BaseOwner = "base"; + + public string? BaseClassName => ScriptInfo.Find(Graph)?.ClassTag?.Bases.OfType().FirstOrDefault()?.Name; + + public IReadOnlyList BaseMembers() => BaseClassName is { } name ? Universe.MembersOf(name) : []; + + private AssignStatement MakeSet(NodeEntry entry) { + var variable = VariableOf(entry); + var assign = new AssignStatement(Graph); + if (variable.Kind == VariableKind.Field) assign.AddMemberTarget(variable.Name); + else assign.AddBindingTarget(entry.Binding ?? ((LocalDecl)variable.Declaration).Names.First(n => n.Name == variable.Name)); + assign.AddValue(); + return assign; + } + + private GraphNode? GetVariable(NodeEntry entry, Vec at, OutputPin? from, InputPin? into) { + var variable = VariableOf(entry); + if (variable.Kind == VariableKind.Field) { + var member = new MemberGet(Graph, variable.Name); + var block = into?.Owner.OwnerStatement?.Parent ?? BlockAt(at); + if (from is not null) ConnectCore(from, member.Object); + else if (ObjectSource(block) is { } owner) ConnectCore(owner, member.Object); + if (into is not null) ConnectCore(member.Result, into); + else { + Layout.Loose.Add(member); + Layout.Local[member] = at; + } + return member; + } + var binding = entry.Binding ?? ((LocalDecl)variable.Declaration).Names.First(n => n.Name == variable.Name); + if (into is null) { + var read = new VariableGet(Graph, binding); + Layout.Loose.Add(read); + Layout.Local[read] = at; + return read; + } + ConnectCore(binding.Output, into); + return null; + } + + private OutputPin? ObjectSource(Block? block) { + for (var b = block; b is not null;) { + if (b.Owner is FunctionEntry { Self: { } self }) return self.Output; + var owner = b.Owner is FunctionEntry fe ? (fe.Owner as Statement ?? fe.Owner.OwnerStatement) : b.Owner as Statement; + b = owner?.Parent; + } + return ScriptInfo.Find(Graph)?.Table.Output; + } + + private TableNode MakeTable(NodeEntry entry) { + var table = new TableNode(Graph); + switch (entry.Name) { + case "array": + table.DeclaredFlavor = TableFlavor.Array; + table.AddPositional(); + break; + case "dictionary": + table.DeclaredFlavor = TableFlavor.Dictionary; + table.AddKeyed().Key!.SetConstant(LuaConstant.String("key")); + break; + default: + table.DeclaredFlavor = TableFlavor.Table; + table.AddNamed("field"); + break; + } + return table; + } + + public bool AddTableEntry(TableNode table, TableFieldKind kind) => Edit(() => { + switch (kind) { + case TableFieldKind.Positional: + table.AddPositional(); + break; + case TableFieldKind.Named: + var taken = table.Fields.Select(f => f.Name).ToHashSet(); + var name = "field"; + for (var i = 2; taken.Contains(name); i++) name = "field" + i; + table.AddNamed(name); + break; + default: + var keys = table.Fields.Where(f => f.Key is not null).Select(f => NodeShape.KeyText(f.Key!)).ToHashSet(); + var key = "key"; + for (var i = 2; keys.Contains(key); i++) key = "key" + i; + table.AddKeyed().Key!.SetConstant(LuaConstant.String(key)); + break; + } + }); + + public static TableFieldKind EntryKindOf(TableNode table) => table.Flavor switch { + TableFlavor.Array => TableFieldKind.Positional, + TableFlavor.Dictionary => TableFieldKind.Keyed, + _ => TableFieldKind.Named + }; + + public bool SetTableKey(TableNode table, TableField field, string text) => Edit(() => { + if (field.Key is null) throw new InvalidOperationException("only a dictionary entry has a key"); + text = text.Trim(); + if (text.Length == 0) throw new InvalidOperationException("a key cannot be empty"); + if (table.Fields.Any(f => f != field && f.Key is { } other && NodeShape.KeyText(other) == text)) throw new InvalidOperationException($"the dictionary already has the key {text}"); + var numeric = double.TryParse(text, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out _); + // numeric text can still be a string key + var keyType = (table.TargetType as TableType)?.Key; + if (keyType is PrimitiveType { Kind: PrimitiveKind.Number or PrimitiveKind.Integer } && !numeric) throw new InvalidOperationException($"the keys of this dictionary are numbers, {text} is not one"); + var asString = keyType is PrimitiveType { Kind: PrimitiveKind.String } || !numeric; + Graph.SetConstant(field.Key, asString ? LuaConstant.String(text) : LuaConstant.Number(text)); + }); + + public bool RenameAccess(GraphNode node, string name) => Edit(() => { + if (!LuaWriter.IsIdentifier(name)) throw new InvalidOperationException($"\"{name}\" cannot be used as a field name"); + switch (node) { + case MemberGet member: + member.Name = name; + member.Result.Name = name; + break; + case AssignStatement { Targets: [{ Kind: TargetKind.Member } target] }: + target.Name = name; + break; + default: + throw new InvalidOperationException("that node does not read or write a field by name"); + } + }); + + public static TableNode? TableOfField(GraphVariable variable) => (variable.Declaration as AssignStatement)?.Values.FirstOrDefault()?.Source?.Owner as TableNode; + + public static string TableEntryType(TableField field) { + if (field.Value.Source?.Owner is TableNode inner) return inner.Flavor switch { + TableFlavor.Array => inner.DeclaredType is ArrayType chosen ? TypeFormatter.Format(chosen) : inner.Result.Type is ArrayType made ? TypeFormatter.Format(made) : "any[]", + TableFlavor.Dictionary => inner.DeclaredType is TableType chosen ? TypeFormatter.Format(chosen) : inner.Result.Type is TableType made ? TypeFormatter.Format(made) : "table", + _ => "table" + }; + if (field.Value.Source is { } source) return TypeFormatter.Display(source.Type); + return field.Value.Constant?.Kind switch { + ConstantKind.Number => "number", + ConstantKind.String => "string", + ConstantKind.Boolean => "boolean", + _ => "any" + }; + } + + public bool AddFieldEntry(InputPin fieldValue, TableFieldKind kind) => Edit(() => { + var table = fieldValue.Source?.Owner as TableNode; + if (table is null) { + table = new TableNode(Graph); + Graph.Connect(table.Result, fieldValue); + } + switch (kind) { + case TableFieldKind.Positional: + table.AddPositional(); + break; + case TableFieldKind.Named: + var taken = table.Fields.Select(f => f.Name).ToHashSet(); + var name = "field"; + for (var i = 2; taken.Contains(name); i++) name = "field" + i; + table.AddNamed(name); + break; + default: + table.AddKeyed().Key!.SetConstant(LuaConstant.String("key")); + break; + } + }); + + public bool SetTableEntryType(TableNode table, int index, string typeText) => Edit(() => { + if (index < 0 || index >= table.Fields.Count) return; + var pin = table.Fields[index].Value; + var type = TypeExprParser.Parse(string.IsNullOrWhiteSpace(typeText) ? "any" : typeText); + switch (type) { + case PrimitiveType { Kind: PrimitiveKind.Number or PrimitiveKind.Integer }: + Graph.SetConstant(pin, LuaConstant.Integer(0)); + break; + case PrimitiveType { Kind: PrimitiveKind.String }: + Graph.SetConstant(pin, LuaConstant.String("")); + break; + case PrimitiveType { Kind: PrimitiveKind.Boolean }: + Graph.SetConstant(pin, LuaConstant.False); + break; + case ArrayType or TableType or PrimitiveType { Kind: PrimitiveKind.Table }: + var made = pin.Source?.Owner as TableNode; + if (made is null) { + Graph.Disconnect(pin); + made = new TableNode(Graph); + Graph.Connect(made.Result, pin); + } + made.DeclaredFlavor = type switch { ArrayType => TableFlavor.Array, TableType => TableFlavor.Dictionary, _ => TableFlavor.Table }; + made.DeclaredType = type is ArrayType or TableType ? type : null; + break; + default: + Graph.SetConstant(pin, LuaConstant.Nil); + break; + } + }); + + public bool RemoveTableEntry(TableNode table, int index) => Edit(() => { + + if (index < 0 || index >= table.Fields.Count) return; + var field = table.Fields[index]; + if (field.Key is not null) Graph.Disconnect(field.Key); + Graph.Disconnect(field.Value); + table.RemoveFieldAt(index); + var number = 1; + foreach (var f in table.Fields.Where(f => f.Kind == TableFieldKind.Positional)) f.Value.Name = "[" + number++ + "]"; + }); + + public bool RenameTableField(TableNode table, TableField field, string name) => Edit(() => { + if (!LuaWriter.IsIdentifier(name)) throw new InvalidOperationException($"\"{name}\" cannot be used as a field name"); + if (table.Fields.Any(f => f != field && f.Name == name)) throw new InvalidOperationException($"the table already has a field called {name}"); + field.Name = name; + field.Value.Name = name; + }); + + private MemberGet MakeMember(NodeEntry entry) { + var member = new MemberGet(Graph, entry.Name!); + if (entry.Owner is { } owner && (Universe.GlobalType(owner) is not null || Universe.Enums.Any(e => e.TableName == owner))) member.Object.Connect(new GlobalGet(Graph, owner).Result); + return member; + } + + private ExprNode BuildCall(NodeEntry entry) { + var function = entry.Signature ?? FunctionOf(entry); + if (entry.Kind == NodeKind.CallMethod) { + var method = Graph.NewMethodCall(entry.Name!); + foreach (var p in function?.Params ?? []) method.AddArg(p.Name); + return method; + } + + var call = new CallNode(Graph, CallStyle.Function, null); + if (entry.Binding is { } binding) call.Target.Connect(binding.Output); + if (entry.Binding is not null || entry.DotCall) { + foreach (var param in function?.Params ?? []) call.AddArg(param.Name); + return call; + } + var path = entry.Name!.Split('.'); + var target = new GlobalGet(Graph, path[0]).Result; + foreach (var part in path.Skip(1)) { + var member = new MemberGet(Graph, part); + member.Object.Connect(target); + target = member.Result; + } + call.Target.Connect(target); + if (entry.Kind == NodeKind.VectorConstructor) { + var names = entry.Name == "quat" ? new[] { "x", "y", "z", "w" } : new[] { "x", "y", "z" }; + for (var i = 0; i < entry.Arity; i++) call.AddArg(names[i]).SetConstant(LuaConstant.Integer(i == 3 ? 1 : 0)); + return call; + } + foreach (var p in function?.Params ?? []) call.AddArg(p.Name); + if (function?.VarargParam is not null) call.AddArg("value"); + return call; + } + + private FunctionType? FunctionOf(NodeEntry entry) { + if (entry.Owner == ScriptOwner) return Graph.Variables.FirstOrDefault(v => v.Name == entry.Name && v.Kind == VariableKind.Function)?.Type as FunctionType; + if (entry.Kind == NodeKind.CallMethod) + return Universe.MembersOf(entry.Owner!).FirstOrDefault(m => m.Decl.Name == entry.Name)?.Decl.Type as FunctionType; + var path = entry.Name!.Split('.'); + if (path.Length == 1) return Universe.GlobalType(path[0]) as FunctionType; + var type = Universe.GlobalType(path[0]); + return type is NamedType named ? Universe.MembersOf(named.Name).FirstOrDefault(m => m.Decl.Name == path[1])?.Decl.Type as FunctionType : null; + } + + public IReadOnlyList SelfEntries() { + var table = ScriptInfo.Find(Graph)?.Table.Name; + var list = new List { new(NodeKind.GetSelf, "self", "Variables", "self this object me", Name: "self") }; + if (table is not null) list.Add(new NodeEntry(NodeKind.GetSelf, table, "Variables", table + " script table module", Name: "table")); + return list; + } + + private Block? BlockAt(Vec at) { + foreach (var (body, host) in Layout.Embedded) + if (Layout.IsPlaced(host) && Layout.Bounds(host) is var frame && + at.X >= frame.X && at.X <= frame.Right && at.Y >= frame.Y && at.Y <= frame.Bottom) return body; + foreach (var region in Layout.Keys.Regions) + if (!region.IsModule && Layout.RegionExtent(region) is { } extent && at.X >= extent.X && at.X <= extent.Right && at.Y >= extent.Y && at.Y <= extent.Bottom) return region.Body; + return null; + } + + private GraphNode? MakeLambda(Vec at, InputPin? into) { + var wanted = into?.Expected is UnionType u && u.Members.Count(m => m != LuaType.Nil) == 1 ? u.Members.First(m => m != LuaType.Nil) : into?.Expected; + var names = new List(); + if (wanted is FunctionType signature) { + for (var i = 0; i < signature.Params.Count; i++) { + var name = signature.Params[i].Name; + names.Add(LuaWriter.IsIdentifier(name) && !names.Contains(name) ? name : "arg" + (i + 1)); + } + if (signature.VarargParam is not null) names.Add("..."); + } + var nodes = Fragments.BuildLoose(Graph, "function(" + string.Join(", ", names) + ")\nend"); + if (nodes.Count == 0 || nodes[0] is not FunctionNode function) throw new InvalidOperationException("could not make the function"); + if (into is not null) { + ConnectCore(function.Result, into); + } else { + Layout.Loose.Add(function); + Layout.Local[function] = at; + } + return function; + } + + private GraphNode? GetSelf(NodeEntry entry, Vec at, InputPin? into) { + + var source = entry.Name == "self" ? ObjectSource(into?.Owner.OwnerStatement?.Parent ?? BlockAt(at)) : ScriptInfo.Find(Graph)?.Table.Output; + if (source?.Binding is not { } binding) throw new InvalidOperationException("there is no " + (entry.Name == "self" ? "self" : "script table") + " in this script"); + if (into is not null) { + ConnectCore(source, into); + return null; + } + var read = new VariableGet(Graph, binding); + Layout.Loose.Add(read); + Layout.Local[read] = at; + return read; + } + + public IReadOnlyList VariableEntries() => Graph.Variables.Where(v => v.Kind != VariableKind.Function).SelectMany(v => new[] { + new NodeEntry(NodeKind.GetVariable, "Get " + v.Name, "Variables", "get " + v.Name, Name: v.Name, Owner: v.Kind.ToString(), Result: v.Type), + new NodeEntry(NodeKind.SetVariable, "Set " + v.Name, "Variables", "set " + v.Name, Name: v.Name, Owner: v.Kind.ToString(), FirstInput: v.Type) + }).Concat(BaseMembers().Where(m => m.Decl.Type is not FunctionType).SelectMany(m => new[] { + new NodeEntry(NodeKind.GetVariable, "Get " + m.Decl.Name, "C++ " + m.DeclaringClass, "get " + m.Decl.Name + " c++", Name: m.Decl.Name, Owner: BaseOwner, Result: m.Decl.Type, Doc: m.Decl.Doc), + new NodeEntry(NodeKind.SetVariable, "Set " + m.Decl.Name, "C++ " + m.DeclaringClass, "set " + m.Decl.Name + " c++", Name: m.Decl.Name, Owner: BaseOwner, FirstInput: m.Decl.Type, Doc: m.Decl.Doc) + })).ToList(); + + public const string ScriptOwner = "script"; + + public IReadOnlyList FunctionEntries() => Graph.Variables.Where(v => v.Kind == VariableKind.Function && v.Declaration is FunctionDecl { IsMethod: true }).Select(v => + new NodeEntry(NodeKind.CallMethod, v.Name + "()", "Script functions", "call " + v.Name, Name: v.Name, Owner: ScriptOwner, Result: (v.Type as FunctionType)?.Returns.FirstOrDefault(), Doc: v.Doc)) + .Concat(BaseMembers().Where(m => m.Decl.Type is FunctionType && m.Decl.IsMethod).Select(m => + new NodeEntry(NodeKind.CallMethod, m.Decl.Name + "()", "C++ " + m.DeclaringClass, "call " + m.Decl.Name + " c++", Name: m.Decl.Name, Owner: m.DeclaringClass, Result: (m.Decl.Type as FunctionType)?.Returns.FirstOrDefault(), Doc: m.Decl.Doc))) + .ToList(); + + private static bool IsOwnCall(NodeEntry entry) => entry.Owner == ScriptOwner || entry.Category.StartsWith("C++ ", StringComparison.Ordinal); + + private bool IsScriptObject(LuaType type) => ScriptInfo.Find(Graph)?.ClassName is { } name && type is NamedType named && named.Name == name; + + public NodeEntry? ScriptFunctionEntry(string name) => FunctionEntries().FirstOrDefault(e => e.Name == name); + + public NodeEntry? VariableEntry(string name, bool set) => VariableEntries().FirstOrDefault(e => e.Name == name && (e.Kind == NodeKind.SetVariable) == set); + + public IReadOnlyList Search(string text, LuaType? producing = null, LuaType? expecting = null, bool statementsOnly = false) { + var words = text.Split(' ', StringSplitOptions.RemoveEmptyEntries); + var own = VariableEntries().Where(e => words.All(w => e.Title.Contains(w, StringComparison.OrdinalIgnoreCase) || e.Search.Contains(w, StringComparison.OrdinalIgnoreCase))) + .Where(e => producing is null || e.Kind == NodeKind.SetVariable || e.Kind == NodeKind.GetVariable && e.Owner == nameof(VariableKind.Field)) + .Where(e => expecting is null || e.Kind == NodeKind.GetVariable && (e.Result is null || m_checker.Check(e.Result, expecting).Kind != Compat.Blocked)) + .Where(e => !statementsOnly || e.Kind == NodeKind.SetVariable); + var functions = FunctionEntries().Where(e => words.All(w => e.Title.Contains(w, StringComparison.OrdinalIgnoreCase) || e.Search.Contains(w, StringComparison.OrdinalIgnoreCase))) + .Where(e => (producing is null || IsScriptObject(producing)) && (expecting is null || e.Result is not null && m_checker.Check(e.Result, expecting).Kind != Compat.Blocked)); + var selves = SelfEntries().Where(e => producing is null && !statementsOnly && words.All(w => e.Title.Contains(w, StringComparison.OrdinalIgnoreCase) || e.Search.Contains(w, StringComparison.OrdinalIgnoreCase))); + return selves.Concat(own).Concat(functions).Concat(Catalog.Search(text, producing, expecting, statementsOnly)).ToList(); + } + + public static InputPin? PrimaryInput(GraphNode node) { + switch (node) { + case LocalDecl l: return NodeShape.CallOf(l) is { } call ? PrimaryInput(call) : l.Values.FirstOrDefault(); + case ReturnStatement r: return r.Values.FirstOrDefault() ?? r.AddValue(); + case IfStatement i: return i.Clauses.FirstOrDefault()?.Condition; + case WhileStatement w: return w.Condition; + case RepeatStatement rp: return rp.Condition; + case NumericFor f: return f.Start; + case GenericFor g: return g.Exprs.FirstOrDefault(); + case CallStatement s when s.CallNode is { } c: return PrimaryInput(c); + case CallNode c: return c.Style == CallStyle.Method ? c.Target : c.Args.FirstOrDefault() ?? c.Target; + case BinaryOp b: return b.Left; + case UnaryOp u: return u.Operand; + case MemberGet m: return m.Object; + case IndexGet x: return x.Object; + case ParenNode p: return p.Inner; + case TableNode t: return t.Fields.FirstOrDefault()?.Value ?? t.AddPositional().Value; + default: return node.Inputs.FirstOrDefault(); + } + } + + public InsertPoint InsertionFor(OutputPin? from, Vec at) { + if (from?.Owner.OwnerStatement is { Parent: { } block } statement) return new InsertPoint(block, block.IndexOf(statement) + 1); + return EndOfModule(); + } + + public InsertPoint InsertionNear(Vec at) { + Statement? best = null; + var bestDistance = double.MaxValue; + foreach (var (node, _) in Layout.Keys.Ordered) { + if (node is not Statement s || s.Parent is null || s is FunctionDecl or SequenceStatement || !Layout.IsPlaced(s)) continue; + var b = Layout.Bounds(s); + var dx = Math.Max(Math.Max(b.X - at.X, at.X - b.Right), 0); + var dy = Math.Max(Math.Max(b.Y - at.Y, at.Y - b.Bottom), 0); + var d = dx * dx + dy * dy; + if (d < bestDistance) { + bestDistance = d; + best = s; + } + } + if (best is null || bestDistance > 80 * 80) return EndOfModule(); + var bounds = Layout.Bounds(best); + var index = best.Parent!.IndexOf(best); + var place = at.X >= bounds.X + bounds.W / 2 ? index + 1 : index; + // lua forbids statements after a return or break + while (place > 0 && place <= best.Parent.Statements.Count && best.Parent.Statements[place - 1] is ReturnStatement or BreakStatement or GotoStatement) place--; + return new InsertPoint(best.Parent, place); + } + + public InsertPoint FloatingPlace(Vec at) { + Block? body = null; + foreach (var (shown, host) in Layout.Embedded) + if (Layout.IsPlaced(host) && Layout.Bounds(host) is var r && at.X >= r.X && at.X <= r.Right && at.Y >= r.Y && at.Y <= r.Bottom) body = shown; + if (body is null) + foreach (var region in Layout.Keys.Regions) + if (!region.IsModule && region.Header is FunctionDecl && !Layout.Embedded.ContainsKey(region.Body) && Layout.RegionExtent(region) is { } e && at.X >= e.X - 12 && at.X <= e.Right + 12 && at.Y >= e.Y - 30 && at.Y <= e.Bottom + 12) + body = region.Body; + if (body is null) return EndOfModule(); + var count = body.Statements.Count; + return new InsertPoint(body, count > 0 && body.Statements[^1] is ReturnStatement ? count - 1 : count); + } + + public InsertPoint EndOfModule() { + var module = Graph.Module; + var count = module.Statements.Count; + return new InsertPoint(module, count > 0 && module.Statements[^1] is ReturnStatement ? count - 1 : count); + } + + public bool Delete(IEnumerable nodes) { + var list = nodes.Select(InlineRules.Drawn).Distinct().ToList(); + if (list.Count == 0) return false; + bool Removes(GraphNode target) => list.Contains(target) || + (target as Statement ?? target.OwnerStatement) is { } statement && + list.OfType().Any(owner => owner == statement || Contains(owner, statement)); + if (Layout.Embedded.Values.Any(host => Removes(host) || NodeShape.LocalCalleeOf(host) is { } callee && Removes(callee))) { + Message = "close the active POE frame first"; + Raise(); + return false; + } + string? refused = null; + var ok = Edit(() => { + var statements = list.OfType().Where(s => s.Parent is not null).ToList(); + foreach (var s in statements.Where(s => !statements.Any(o => o != s && Contains(o, s))).ToList()) { + try { + Graph.Remove(s); + } catch (InvalidOperationException e) { + refused ??= e.Message; + } + } + foreach (var e in list.OfType()) { + if (Layout.Loose.Contains(e)) { + foreach (var consumer in e.Result.Consumers.ToList()) Graph.Disconnect(consumer); + Layout.Loose.Remove(e); + Layout.Local.Remove(e); + Graph.Unregister(e); + } else { + foreach (var consumer in e.Result.Consumers.ToList()) Graph.Disconnect(consumer); + } + } + if (refused is not null) throw new InvalidOperationException(refused); + }); + if (!ok) return false; + Selection.Clear(); + SelectionChanged?.Invoke(); + Raise(); + return true; + } + + private static Statement? ParentStatement(Statement s) => s.Parent?.Owner switch { + Statement p => p, + FunctionEntry e => e.Owner as Statement ?? e.Owner.OwnerStatement, + _ => null + }; + + private static bool Contains(Statement outer, Statement inner) { + for (var p = ParentStatement(inner); p is not null; p = ParentStatement(p)) + if (p == outer) return true; + return false; + } + + private string? m_lastCopy; + + public string CopyText() => m_lastCopy = Fragments.Copy(SelectedStatements()); + + private List SelectedStatements() { + var chosen = Selection.OfType().Where(s => s.Parent is not null && s is not FunctionDecl).ToList(); + var top = chosen.Where(s => !chosen.Any(o => o != s && Contains(o, s))).ToList(); + var ordered = new List(); + foreach (var (node, _) in Layout.Keys.Ordered) + if (node is Statement s && top.Contains(s)) ordered.Add(s); + return ordered; + } + + public bool Paste(string luaText, Vec at) { + var point = InsertionNear(at); + IReadOnlyList created = []; + var ok = Edit(() => { + var before = Graph.Nodes.Count; + var result = Fragments.Paste(Graph, luaText, point.Block, point.Index); + if (result.Errors.Count > 0) throw new InvalidOperationException(result.Errors[0].Message); + created = result.Statements; + // pasted nodes must not keep wires to unselected nodes + if (luaText == m_lastCopy) DropOuterWires(before); + }); + if (!ok) return false; + Layout.Refresh(); + Selection.Clear(); + foreach (var s in created) Selection.Add(s); + if (created.Count > 0 && Layout.IsPlaced(created[0])) MoveGroup(created[0], at - Layout.Position(created[0])); + LayoutEngine.Separate(Layout, created); + Raise(); + return true; + } + + private void DropOuterWires(int nodesBefore) { + var fresh = Graph.Nodes.Skip(nodesBefore).ToHashSet(); + foreach (var node in fresh) + foreach (var pin in node.Inputs.ToList()) + if (pin.Source is { } source && !fresh.Contains(source.Owner) && !InlineRules.IsImplicitObject(pin)) Graph.Disconnect(pin); + } + + public bool Duplicate() { + var statements = SelectedStatements(); + if (statements.Count == 0) { + Message = "select statements to duplicate"; + Raise(); + return false; + } + var last = statements[^1]; + var block = last.Parent!; + var text = Fragments.Copy(statements); + var offset = Layout.Position(statements[0]); + IReadOnlyList created = []; + var ok = Edit(() => { + var before = Graph.Nodes.Count; + var result = Fragments.Paste(Graph, text, block, block.IndexOf(last) + 1); + if (result.Errors.Count > 0) throw new InvalidOperationException(result.Errors[0].Message); + created = result.Statements; + DropOuterWires(before); + }); + if (!ok) return false; + Layout.Refresh(); + Selection.Clear(); + Selection.AddRange(created); + _ = offset; + Raise(); + return true; + } + + public void Move(IEnumerable nodes, Vec delta) { + var list = nodes.Select(InlineRules.Drawn).Distinct().ToList(); + var moving = list.Where(node => Layout.IsPlaced(node) && !list.Any(host => host != node && Layout.IsInsideFrameOf(node, host))).ToList(); + foreach (var node in moving) Layout.AnchorFrame(node); + foreach (var node in moving) { + var constrained = Layout.ConstrainFrameMove(node, delta); + delta = new Vec(Math.Max(delta.X, constrained.X), Math.Max(delta.Y, constrained.Y)); + } + foreach (var n in moving) { + Layout.Local[n] += delta; + Layout.PinnedNodes.Add(n); + } + foreach (var (body, host) in Layout.Embedded.ToList()) + if (list.Contains(host)) + foreach (var waiting in Layout.Loose.OfType().Where(x => x.IsFloating && x.Parent == body).ToList()) Layout.Local[waiting] += delta; + LayoutEngine.FollowHosts(Layout); + RefitGroups(list); + Raise(); + } + + public void FinishMove(IEnumerable nodes) { + var selected = nodes.Select(InlineRules.Drawn).Distinct().ToList(); + var list = selected.Where(node => !selected.Any(host => host != node && Layout.IsInsideFrameOf(node, host))).ToList(); + LayoutEngine.Separate(Layout, list, includeInputs: false); + RefitGroups(list); + CommitLayout(); + } + + public static Rect GroupRectAround(Rect nodes) => new(nodes.X - 16, nodes.Y - 36, nodes.W + 32, nodes.H + 52); + + private void RefitGroups(IReadOnlyCollection moved) { + foreach (var group in Layout.Groups) { + if (!group.Members.Any(moved.Contains) || group.Members.All(moved.Contains)) continue; + var bounds = group.Members.Where(Layout.IsPlaced).Select(Layout.Bounds).ToList(); + if (bounds.Count > 0) group.Rect = GroupRectAround(bounds.Aggregate(Rect.Union)); + } + } + + public void FinishResizeGroup(LayoutGroup group) { + var inside = group.Members.Where(m => Layout.IsPlaced(m) && Contains(group.Rect, Layout.Bounds(m))).ToList(); + if (inside.Count == 0) Message = "a comment box keeps at least one node"; + else { + group.Members.Clear(); + group.Members.AddRange(inside); + } + CommitLayout(); + } + + private static bool Contains(Rect outer, Rect inner) => inner.X >= outer.X - 2 && inner.Y >= outer.Y - 2 && inner.Right <= outer.Right + 2 && inner.Bottom <= outer.Bottom + 2; + + public void FinishRegionMove() { + LayoutEngine.PackRegions(Layout); + CommitLayout(); + } + + public void CommitLayout() => Edit(() => { }, structural: false); + + private void MoveGroup(GraphNode node, Vec delta) { + if (delta == default) return; + if (Layout.Loose.Contains(node)) { + Layout.Local[node] += delta; + return; + } + Layout.Local[node] = Layout.Local.GetValueOrDefault(node) + delta; + if (node is not Statement) return; + var key = Layout.Keys.KeyOf(node); + if (key is null) return; + foreach (var (other, otherKey) in Layout.Keys.Ordered) { + if (!otherKey.StartsWith(key + "#", StringComparison.Ordinal) || !Layout.Local.ContainsKey(other)) continue; + Layout.Local[other] += delta; + } + } + + public void MoveRegion(RegionInfo region, Vec delta) { + Layout.MoveRegion(region, delta); + Layout.PinnedRegions.Add(region.Body); + Raise(); + } + + public bool Tidy(RegionInfo? region, bool includePinned = false) => Edit(() => { + var targets = region is null ? Layout.Keys.Regions : [region]; + var selection = region is null && Selection.Count > 0 ? Selection : null; + foreach (var r in targets) { + var chosen = selection?.Where(n => Layout.Keys.RegionOf(n) == r).ToList(); + if (selection is not null && chosen!.Count == 0) continue; + Arrange.Tidy(Layout, r, chosen, includePinned); + } + LayoutEngine.PackRegions(Layout); + }, structural: false); + + public void StraightenSelection(IReadOnlyList<(Slot From, Slot To)> links) { + if (links.Count == 0 || !Arrange.StraightenSelection(Layout, links)) return; + RefitGroups(Selection); + CommitLayout(); + } + + public bool Straighten(OutputPin from, InputPin to) => Edit(() => { + if (!Arrange.Straighten(Layout, from, to)) throw new InvalidOperationException("that would put the node on top of another one"); + var target = InlineRules.Drawn(to.Owner); + Layout.PinnedNodes.Add(target); + }, structural: false); + + public bool Align(AlignEdge edge) => Edit(() => { + Arrange.Align(Layout, Selection, edge); + foreach (var n in Selection) Layout.PinnedNodes.Add(n); + LayoutEngine.FollowHosts(Layout); + if (Layout.Overlaps().Any()) throw new InvalidOperationException("that would put nodes on top of each other"); + }, structural: false); + + public bool Distribute(bool horizontal) => Edit(() => { + Arrange.Distribute(Layout, Selection, horizontal); + foreach (var n in Selection) Layout.PinnedNodes.Add(n); + LayoutEngine.FollowHosts(Layout); + if (Layout.Overlaps().Any()) throw new InvalidOperationException("that would put nodes on top of each other"); + }, structural: false); + + public void MoveProxy(InputPin pin, Vec delta) { + Layout.ProxyOffsets[pin] = Layout.ProxyOffsets.GetValueOrDefault(pin) + delta; + Raise(); + } + + private Vec RerouteBase(object wire) => wire is InputPin pin ? Layout.Position(InlineRules.Drawn(pin.Owner)) : Layout.Position((GraphNode)wire); + + private List? PointsOf(object wire, bool create) { + if (wire is InputPin p) { + if (Layout.Reroutes.TryGetValue(p, out var list)) return list; + return create ? Layout.Reroutes[p] = [] : null; + } + var statement = (Statement)wire; + if (Layout.ExecReroutes.TryGetValue(statement, out var exec)) return exec; + return create ? Layout.ExecReroutes[statement] = [] : null; + } + + private void DropPoints(object wire) { + if (wire is InputPin pin) Layout.Reroutes.Remove(pin); + else Layout.ExecReroutes.Remove((Statement)wire); + } + + public int AddReroute(object wire, Vec world, int index = -1) { + var list = PointsOf(wire, true)!; + if (index < 0 || index > list.Count) index = list.Count; + list.Insert(index, world - RerouteBase(wire)); + CommitLayout(); + return index; + } + + public void MoveReroute(object wire, int index, Vec world) { + if (PointsOf(wire, false) is not { } list || index < 0 || index >= list.Count) return; + list[index] = world - RerouteBase(wire); + Raise(); + } + + public bool RemoveReroute(object wire, int index) => Edit(() => { + if (PointsOf(wire, false) is not { } list || index < 0 || index >= list.Count) return; + list.RemoveAt(index); + if (list.Count == 0) DropPoints(wire); + }, structural: false); + + public LayoutGroup? AddCommentBox(string title = "Comment") { + var members = Selection.Where(n => Layout.IsPlaced(n) && !InlineRules.IsMerged(n)).ToList(); + if (members.Count == 0) return null; + var group = new LayoutGroup { Title = title, Rect = GroupRectAround(members.Select(Layout.Bounds).Aggregate(Rect.Union)) }; + group.Members.AddRange(members); + Edit(() => Layout.Groups.Add(group), structural: false); + return group; + } + + public bool CanOpen(GraphNode node) => node.IsExpanded || (NodeShape.LocalCalleeOf(node) is not null && Layout.HostBody(node) is { } body && !Layout.Embedded.ContainsKey(body)); + + public bool ToggleExpanded(GraphNode node) { + if (!node.IsExpanded) { + string? problem = null; + if (NodeShape.LocalCalleeOf(node) is not { } callee || Layout.Keys.Regions.FirstOrDefault(r => r.Header == callee) is not { } region) problem = "only local function calls can open in POE"; + else if (Layout.HostBody(node) == region.Body) problem = "a function cannot be opened inside itself"; + else if (!CanOpen(node)) problem = "a function cannot be opened inside another opened function; close that one first"; + if (problem is not null) { + Message = problem; + Raise(); + return false; + } + } + return ToggleCore(node); + } + + private bool ToggleCore(GraphNode node) => Edit(() => { + if (node.IsExpanded) { + node.IsExpanded = false; + foreach (var body in Layout.Embedded.Where(e => e.Value == node).Select(e => e.Key).ToList()) { + Layout.Embedded.Remove(body); + Layout.FrameCorners.Remove(body); + } + } else { + var callee = NodeShape.LocalCalleeOf(node) ?? throw new InvalidOperationException("only local function calls can open in POE"); + var region = Layout.Keys.Regions.FirstOrDefault(r => r.Header == callee) ?? throw new InvalidOperationException("that function has no graph here"); + if (Layout.HostBody(node) == region.Body) throw new InvalidOperationException("a function cannot be opened inside itself"); + if (!CanOpen(node)) throw new InvalidOperationException("a function cannot be opened inside another opened function; close that one first"); + if (Layout.Embedded.Values.Any(host => Layout.HostBody(host) == region.Body)) + throw new InvalidOperationException("close the POE frame inside this function first"); + // the same function cannot be edited in two frames + if (Layout.Embedded.TryGetValue(region.Body, out var previous)) previous.IsExpanded = false; + node.IsExpanded = true; + Layout.Embedded[region.Body] = node; + Layout.CollapsedRegions.Remove(region.Body); + } + for (var own = Layout.Keys.RegionOf(node); own is not null; own = Layout.Embedded.TryGetValue(own.Body, out var outer) ? Layout.Keys.RegionOf(outer) : null) + Arrange.Tidy(Layout, own, null, false); + LayoutEngine.PackRegions(Layout); + }, structural: false); + + public bool RemoveCommentBox(LayoutGroup group) => Edit(() => Layout.Groups.Remove(group), structural: false); + + public bool GroupSelectionAsSequence() { + var statements = SelectedStatements(); + if (statements.Count < 2 || statements.Any(s => s.Parent != statements[0].Parent)) { + Message = "select two or more statements in the same block"; + Raise(); + return false; + } + var block = statements[0].Parent!; + var starts = statements.Select(block.IndexOf).OrderBy(i => i).ToList(); + return Edit(() => Graph.GroupAsSequence(block, starts)); + } + + private void RetidyFrameOf(GraphNode? node) { + if (node is null || node is Statement { IsFloating: true } || Layout.Keys.RegionOf(InlineRules.Drawn(node)) is not { } region || !Layout.Embedded.ContainsKey(region.Body)) return; + Arrange.Tidy(Layout, region, null, includePinned: true); + LayoutEngine.FollowHosts(Layout); + m_current = m_current with { Meta = LayoutPersistence.Capture(Layout) }; + Raise(); + } + + public bool ConnectExec(Slot from, Statement to) { + + var floatingTarget = to.IsFloating ? to : null; + var floatingSource = from.Node is Statement { IsFloating: true } fs ? fs : null; + var joined = floatingTarget ?? floatingSource; + var at = joined is null ? default : Layout.Position(joined); + var ok = Edit(() => { + if (from.Kind != SlotKind.ExecOut) throw new InvalidOperationException("drag from an execution output"); + if (floatingSource is not null) { + if (from.Child is not null) throw new InvalidOperationException("wire this node into the script first, then its bodies"); + if (floatingTarget is not null) throw new InvalidOperationException("wire one of them into the script first"); + if (to.Parent is not { } block) throw new InvalidOperationException("that statement is not in the script"); + BringLocalCalleeIntoScope(floatingSource, block); + floatingSource.IsFloating = false; + Graph.Move(floatingSource, block, block.IndexOf(to)); + return; + } + if (floatingTarget is not null) floatingTarget.IsFloating = false; + if (from.Child is { } child) { + BringLocalCalleeIntoScope(to, child); + Graph.Move(to, child, 0); + return; + } + if (from.Node is not Statement source || source.Parent is null) throw new InvalidOperationException("that output does not lead anywhere"); + if (source == to) throw new InvalidOperationException("a statement cannot follow itself"); + BringLocalCalleeIntoScope(to, source.Parent); + Graph.Move(to, source.Parent, source.Parent.IndexOf(source) + 1); + }); + if (ok && joined is not null) { + AdoptLoose(joined, at); + m_current = m_current with { Meta = LayoutPersistence.Capture(Layout) }; + Raise(); + } + if (ok) RetidyFrameOf(joined ?? to); + return ok; + } + + private void BringLocalCalleeIntoScope(Statement call, Block destination) { + if (NodeShape.LocalCalleeOf(call) is not { Parent: { } module } local || module != Graph.Module) return; + var owner = destination.Owner is FunctionEntry entry ? entry.Owner as Statement ?? entry.Owner.OwnerStatement : destination.Owner as Statement; + while (owner?.Parent is not null && owner.Parent != module) owner = ParentStatement(owner); + if (owner is not FunctionDecl method || ScriptInfo.Find(Graph)?.Methods.Contains(method) != true) return; + if (module.IndexOf(local) > module.IndexOf(method)) Graph.Move(local, module, module.IndexOf(method)); + } + + public bool AddFunction(string name) { + var table = ScriptInfo.Find(Graph)?.Table.Name ?? "M"; + return AddText($"function {table}:{name}()\nend\n"); + } + + public bool GroupSelectionAsFunction() { + var chosen = SelectedStatements(); + if (chosen.Count == 0) { + Message = "select statements to move into a function"; + Raise(); + return false; + } + var block = chosen[0].Parent!; + var first = block.IndexOf(chosen[0]); + for (var i = 0; i < chosen.Count; i++) + if (chosen[i].Parent != block || block.IndexOf(chosen[i]) != first + i) { + Message = "the statements must be next to each other to become a function"; + Raise(); + return false; + } + + bool Inside(GraphNode n) => n is Statement s ? chosen.Any(c => c == s || Contains(c, s)) : n.OwnerStatement is { } o && chosen.Any(c => c == o || Contains(c, o)); + bool ModuleLevel(Binding b) => b.Declarer is LocalDecl d && d.Parent == Graph.Module; + var parameters = new List(); + void Need(Binding binding) { + if (binding.Kind != BindingKind.Self && !ModuleLevel(binding) && !Inside(binding.Declarer) && !parameters.Contains(binding.Name)) parameters.Add(binding.Name); + } + var inside = Graph.Nodes.Where(Inside).ToList(); + foreach (var node in inside) { + if (node is VariableGet get) Need(get.Binding); + foreach (var pin in node.Inputs) + if (pin.Source is { Binding: { } binding } && !Inside(pin.Source.Owner) && !InlineRules.IsImplicitObject(pin)) Need(binding); + } + foreach (var declared in inside.OfType()) { + var used = declared.Outputs.Any(o => o.Consumers.Any(c => !Inside(c.Owner))) + || Graph.Nodes.OfType().Any(v => !Inside(v) && v.Binding.Declarer == declared); + if (used) { + Message = "something the statements declare is used after them, so they cannot move into a function"; + Raise(); + return false; + } + } + + var table = ScriptInfo.Find(Graph)?.Table.Name ?? "M"; + var taken = Graph.Variables.Select(v => v.Name).ToHashSet(); + var name = "extracted"; + for (var n = 2; taken.Contains(name); n++) name = "extracted" + n; + var arguments = string.Join(", ", parameters); + var functionText = $"function {table}:{name}({arguments})\n{Fragments.Copy(chosen)}end\n"; + var owner = ObjectSource(block)?.Binding?.Name ?? table; + var callText = $"{owner}:{name}({arguments})\n"; + var ok = Edit(() => { + var end = EndOfModule(); + var made = Fragments.Paste(Graph, functionText, end.Block, end.Index); + if (made.Errors.Count > 0) throw new InvalidOperationException(made.Errors[0].Message); + var call = Fragments.Paste(Graph, callText, block, first); + if (call.Errors.Count > 0) throw new InvalidOperationException(call.Errors[0].Message); + foreach (var statement in chosen) Graph.Remove(statement); + }); + if (ok) Message = null; + return ok; + } + + public bool AddModuleLocal(string name) + => AddText($"local {name} = nil\n"); + + public bool AddField(string name) { + var script = ScriptInfo.Find(Graph); + if (script is null) { + Message = "this script has no table to add a field to"; + Raise(); + return false; + } + var index = script.Declaration.Parent!.IndexOf(script.Declaration) + 1; + return Edit(() => { + var result = Fragments.Paste(Graph, $"{script.Table.Name}.{name} = nil\n", script.Declaration.Parent!, index); + if (result.Errors.Count > 0) throw new InvalidOperationException(result.Errors[0].Message); + }); + } + + private bool AddText(string text) { + var point = EndOfModule(); + return Edit(() => { + var result = Fragments.Paste(Graph, text, point.Block, point.Index); + if (result.Errors.Count > 0) throw new InvalidOperationException(result.Errors[0].Message); + }); + } + + public bool Apply(Action change) => Edit(() => change(Graph)); + + public bool Rename(Binding binding, string newName) => Edit(() => Graph.Rename(binding, newName)); + + public bool CanSwitchCallStyle(CallNode call) => call.Style == CallStyle.Method + ? call.Method is not null + : call.Target.Source is { Binding: null, Owner: MemberGet member } && call.Args.Count > 0 && call.Args[0].Source is { } first && member.Object.Source == first; + + public bool AddCallArgument(CallNode call) => Edit(() => call.AddArg("arg" + (call.Args.Count + 1))); + + public bool RemoveLastCallArgument(CallNode call) => Edit(() => { + if (call.Args.Count == 0) return; + var last = call.Args[^1]; + var source = last.Source; + call.RemoveArgAt(call.Args.Count - 1); + _ = source; + }); + + public bool SetCallStyle(CallNode call, CallStyle style) => Edit(() => Graph.SetCallStyle(call, style)); + + public bool SetComment(Statement statement, string? text) => Edit(() => Graph.SetStatementComment(statement, text)); +} diff --git a/editor/LuaEditor/Editing/NodeCatalog.cs b/editor/LuaEditor/Editing/NodeCatalog.cs new file mode 100644 index 000000000..eb74b8bbe --- /dev/null +++ b/editor/LuaEditor/Editing/NodeCatalog.cs @@ -0,0 +1,187 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using editor.LuaEditor.Graph; +using editor.LuaEditor.Types; + +namespace editor.LuaEditor.Editing; + +public enum NodeKind { + If, While, Repeat, NumericFor, GenericFor, Do, Return, Break, Sequence, Local, Cast, Comment, RawStatement, + Binary, Unary, Number, String, Boolean, Nil, MakeTable, RawExpression, Index, Paren, + CallGlobal, CallMethod, Member, GetGlobal, VectorConstructor, GetVariable, SetVariable, GetSelf, SetIndex, SetMember, Lambda +} + +public sealed record NodeEntry(NodeKind Kind, string Title, string Category, string Search, string? Name = null, string? Owner = null, + BinaryKind? Binary = null, UnaryKind? Unary = null, LuaType? Result = null, LuaType? FirstInput = null, string Doc = "", int Arity = 0, Binding? Binding = null, FunctionType? Signature = null, bool DotCall = false) { + public bool IsStatement => Kind is NodeKind.If or NodeKind.While or NodeKind.Repeat or NodeKind.NumericFor or NodeKind.GenericFor or NodeKind.Do + or NodeKind.Return or NodeKind.Break or NodeKind.Sequence or NodeKind.Local or NodeKind.Cast or NodeKind.Comment or NodeKind.RawStatement or NodeKind.SetVariable or NodeKind.SetIndex or NodeKind.SetMember; +} + +public sealed class NodeCatalog { + private static readonly List s_builtins = MakeBuiltins(); + + private readonly List m_entries = []; + private readonly TypeUniverse m_universe; + private readonly TypeChecker m_checker; + + public NodeCatalog(TypeUniverse universe) { + m_universe = universe; + m_checker = new TypeChecker(universe); + m_entries.AddRange(s_builtins); + AddGlobals(); + AddClasses(); + } + + public IReadOnlyList Entries => m_entries; + + public static NodeEntry Of(NodeKind kind) => s_builtins.First(e => e.Kind == kind); + + public static NodeEntry Operator(BinaryKind op) => s_builtins.First(e => e.Binary == op); + + public static NodeEntry Operator(UnaryKind op) => s_builtins.First(e => e.Unary == op); + + public static NodeEntry Vector(string name) => s_builtins.First(e => e.Kind == NodeKind.VectorConstructor && e.Name == name); + + private static List MakeBuiltins() { + var list = new List { + new(NodeKind.If, "if", "Flow", "if branch else condition"), + new(NodeKind.Sequence, "Sequence", "Flow", "sequence then run in order"), + new(NodeKind.NumericFor, "for i =", "Flow", "for loop range index count"), + new(NodeKind.GenericFor, "for in", "Flow", "foreach for each pairs ipairs loop"), + new(NodeKind.While, "while", "Flow", "while loop"), + new(NodeKind.Repeat, "repeat until", "Flow", "repeat until loop"), + new(NodeKind.Do, "do", "Flow", "do block scope"), + new(NodeKind.Return, "return", "Flow", "return exit"), + new(NodeKind.Break, "break", "Flow", "break leave loop"), + new(NodeKind.Local, "local", "Variables", "local variable declare let"), + new(NodeKind.Cast, "---@cast", "Variables", "cast type convert"), + new(NodeKind.Comment, "-- comment", "Misc", "comment note"), + new(NodeKind.RawStatement, "raw Lua", "Misc", "raw lua code text"), + new(NodeKind.RawExpression, "raw Lua value", "Misc", "raw lua expression code text"), + new(NodeKind.Lambda, "Function function(...) end", "Functions", "function lambda closure callback anonymous fn handler", Result: new PrimitiveType(PrimitiveKind.Function)), + new(NodeKind.MakeTable, "Table", "Tables", "table record struct fields named {} make", Name: "record", Result: LuaType.Table), + new(NodeKind.MakeTable, "Array", "Tables", "array list items positional make {1, 2, 3}", Name: "array", Result: new ArrayType(LuaType.Any)), + new(NodeKind.MakeTable, "Dictionary", "Tables", "dictionary map keys values make {[k] = v}", Name: "dictionary", Result: new TableType(LuaType.Any, LuaType.Any)), + new(NodeKind.Index, "Get item t[key]", "Tables", "get item element index array dictionary key []"), + new(NodeKind.SetIndex, "Set item t[key] = value", "Tables", "set item element index array dictionary key [] ="), + new(NodeKind.Member, "Get field t.name", "Tables", "get field member table record dot", Name: "name"), + new(NodeKind.SetMember, "Set field t.name = value", "Tables", "set field member table record dot =", Name: "name"), + new(NodeKind.CallGlobal, "Add to array table.insert", "Tables", "add append push insert array list item", Name: "table.insert", Arity: 2), + new(NodeKind.CallGlobal, "Remove from array table.remove", "Tables", "remove pop delete array list item", Name: "table.remove", Arity: 2), + new(NodeKind.GenericFor, "For each item ipairs", "Tables", "for each item array list ipairs loop", Name: "ipairs"), + new(NodeKind.GenericFor, "For each pair pairs", "Tables", "for each pair dictionary table pairs key value loop", Name: "pairs"), + + new(NodeKind.Number, "number", "Values", "number constant float integer"), + new(NodeKind.String, "string", "Values", "string text constant"), + new(NodeKind.Boolean, "boolean", "Values", "boolean true false bool"), + new(NodeKind.Nil, "nil", "Values", "nil nothing null"), +new(NodeKind.VectorConstructor, "vec2", "Values", "vec2 vector 2d", Name: "vec2", Arity: 2, Result: new NamedType("vec2", [])), + new(NodeKind.VectorConstructor, "vec3", "Values", "vec3 vector 3d position", Name: "vec3", Arity: 3, Result: new NamedType("vec3", [])), + new(NodeKind.VectorConstructor, "quat", "Values", "quat quaternion rotation", Name: "quat", Arity: 4, Result: new NamedType("quat", [])) + }; + var arithmetic = new (BinaryKind Op, string Title, string Words)[] { + (BinaryKind.Add, "+", "add plus sum +"), (BinaryKind.Sub, "-", "subtract minus -"), + (BinaryKind.Mul, "*", "multiply times *"), (BinaryKind.Div, "/", "divide /"), + (BinaryKind.FloorDiv, "//", "floor divide //"), (BinaryKind.Mod, "%", "modulo remainder %"), + (BinaryKind.Pow, "^", "power exponent ^"), (BinaryKind.Concat, "..", "concat join text .."), + (BinaryKind.Eq, "==", "equal == compare"), (BinaryKind.Ne, "~=", "not equal ~= compare"), + (BinaryKind.Lt, "<", "less < compare"), (BinaryKind.Le, "<=", "less equal <= compare"), + (BinaryKind.Gt, ">", "greater > compare"), (BinaryKind.Ge, ">=", "greater equal >= compare"), + (BinaryKind.And, "and", "and boolean"), (BinaryKind.Or, "or", "or boolean default"), + (BinaryKind.BitAnd, "&", "bit and &"), (BinaryKind.BitOr, "|", "bit or |"), + (BinaryKind.BitXor, "~", "bit xor ~"), (BinaryKind.Shl, "<<", "shift left <<"), (BinaryKind.Shr, ">>", "shift right >>") + }; + foreach (var (op, title, words) in arithmetic) list.Add(new NodeEntry(NodeKind.Binary, title, "Operators", words, Binary: op)); + list.Add(new NodeEntry(NodeKind.Unary, "-", "Operators", "negate minus -", Unary: UnaryKind.Neg)); + list.Add(new NodeEntry(NodeKind.Unary, "not", "Operators", "not ! invert", Unary: UnaryKind.Not)); + list.Add(new NodeEntry(NodeKind.Unary, "#", "Operators", "length count size #", Unary: UnaryKind.Len)); + list.Add(new NodeEntry(NodeKind.Unary, "~", "Operators", "bit not ~", Unary: UnaryKind.BitNot)); + return list; + } + + private void AddGlobals() { + foreach (var global in m_universe.Globals.OrderBy(g => g.Name, StringComparer.Ordinal)) { + if (global.Name is "vec2" or "vec3" or "quat") continue; + if (global.Type is FunctionType function) { + m_entries.Add(Function(global.Name, global.Name, "Functions", function, global.Doc, null)); + continue; + } + + m_entries.Add(new NodeEntry(NodeKind.GetGlobal, global.Name, "Globals", global.Name + " " + global.Doc, Name: global.Name, Result: global.Type, Doc: global.Doc)); + if (global.Type is not NamedType named || m_universe.FindClass(named.Name) is null) continue; + foreach (var member in m_universe.MembersOf(named.Name)) { + var path = global.Name + (member.Decl.IsMethod ? ":" : ".") + member.Decl.Name; + if (member.Decl.Type is FunctionType f) m_entries.Add(Function(path, global.Name + "." + member.Decl.Name, global.Name, f, member.Decl.Doc, global.Name)); + else m_entries.Add(new NodeEntry(NodeKind.Member, global.Name + "." + member.Decl.Name, global.Name, global.Name + "." + member.Decl.Name, Name: member.Decl.Name, Owner: global.Name, Result: member.Decl.Type, Doc: member.Decl.Doc)); + } + } + } + + private static NodeEntry Function(string title, string path, string category, FunctionType function, string doc, string? owner) { + var first = function.Params.Count > 0 ? function.Params[0].Type : null; + var result = function.Returns.Count > 0 ? function.Returns[0] : null; + return new NodeEntry(NodeKind.CallGlobal, title, category, path + " " + doc, Name: path, Owner: owner, Result: result, FirstInput: first, Doc: doc); + } + + private void AddClasses() { + foreach (var cls in m_universe.Classes.OrderBy(c => c.Name, StringComparer.Ordinal)) { + foreach (var member in m_universe.MembersOf(cls.Name).Where(m => m.DeclaringClass == cls.Name)) { + var decl = member.Decl; + if (decl.Type is FunctionType f && decl.IsMethod) { + m_entries.Add(new NodeEntry(NodeKind.CallMethod, cls.Name + ":" + decl.Name, cls.Name, cls.Name + " " + decl.Name + " " + decl.Doc, Name: decl.Name, Owner: cls.Name, + Result: f.Returns.Count > 0 ? f.Returns[0] : null, FirstInput: new NamedType(cls.Name, []), Doc: decl.Doc)); + } else if (decl.Type is not FunctionType) { + m_entries.Add(new NodeEntry(NodeKind.Member, cls.Name + "." + decl.Name, cls.Name, cls.Name + " " + decl.Name + " " + decl.Doc, Name: decl.Name, Owner: cls.Name, + Result: decl.Type, FirstInput: new NamedType(cls.Name, []), Doc: decl.Doc)); + } + } + } + } + + public IReadOnlyList Search(string text, LuaType? producing = null, LuaType? expecting = null, bool statementsOnly = false) { + var words = text.Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); + var scored = new List<(NodeEntry Entry, int Score)>(); + foreach (var entry in m_entries) { + if (statementsOnly && !entry.IsStatement && entry.Kind is not (NodeKind.CallGlobal or NodeKind.CallMethod)) continue; + if (producing is not null && !AcceptsAsFirstInput(entry, producing)) continue; + if (expecting is not null && !Produces(entry, expecting)) continue; + var score = Score(entry, words); + if (score >= 0) scored.Add((entry, score)); + } + return scored.OrderBy(s => s.Score).ThenBy(s => s.Entry.Category, StringComparer.Ordinal).ThenBy(s => s.Entry.Title, StringComparer.Ordinal).Select(s => s.Entry).ToList(); + } + + private static int Score(NodeEntry entry, string[] words) { + if (words.Length == 0) return 5; + var total = 0; + foreach (var word in words) { + if (entry.Title.StartsWith(word, StringComparison.OrdinalIgnoreCase)) total += 0; + else if (entry.Title.Contains(word, StringComparison.OrdinalIgnoreCase)) total += 1; + else if (entry.Search.Contains(word, StringComparison.OrdinalIgnoreCase)) total += 3; + else return -1; + } + return total; + } + + private bool AcceptsAsFirstInput(NodeEntry entry, LuaType produced) { + switch (entry.Kind) { + case NodeKind.Binary or NodeKind.Unary or NodeKind.Index or NodeKind.MakeTable: + case NodeKind.Return or NodeKind.Local or NodeKind.Cast or NodeKind.If or NodeKind.While or NodeKind.Repeat or NodeKind.GenericFor or NodeKind.NumericFor: + return true; + case NodeKind.CallGlobal or NodeKind.CallMethod or NodeKind.Member: + return entry.FirstInput is null ? entry.Kind == NodeKind.CallGlobal : m_checker.Check(produced, entry.FirstInput).Kind != Compat.Blocked; + default: + return false; + } + } + + private static LuaType Strip(LuaType type) => type is UnionType u && u.Members.Count(m => m != LuaType.Nil) == 1 ? u.Members.First(m => m != LuaType.Nil) : type; + + private bool Produces(NodeEntry entry, LuaType expected) { + if (entry.IsStatement) return false; + if (entry.Kind == NodeKind.Lambda) return Strip(expected) is FunctionType or PrimitiveType { Kind: PrimitiveKind.Function or PrimitiveKind.Any or PrimitiveKind.Unknown }; + if (entry.Result is null) return entry.Kind is NodeKind.Binary or NodeKind.Unary or NodeKind.RawExpression or NodeKind.Index or NodeKind.Paren; + return m_checker.Check(entry.Result, expected).Kind != Compat.Blocked; + } +} diff --git a/editor/LuaEditor/Editing/NodeDoc.cs b/editor/LuaEditor/Editing/NodeDoc.cs new file mode 100644 index 000000000..731b2151a --- /dev/null +++ b/editor/LuaEditor/Editing/NodeDoc.cs @@ -0,0 +1,41 @@ +using System.Collections.Generic; +using System.Linq; +using editor.LuaEditor.Graph; +using editor.LuaEditor.Layout; +using editor.LuaEditor.Types; + +namespace editor.LuaEditor.Editing; + +public sealed record DocPin(string Name, string Type, string Color); + +public sealed record NodeDoc(string Title, string Summary, IReadOnlyList Inputs, IReadOnlyList Outputs) { + public static NodeDoc Of(GraphNode node, NodeCatalog catalog) { + var title = NodeShape.TitleOf(node); + var summary = node switch { + IfStatement => "Runs the first branch whose condition is true; else runs the otherwise branch.", + WhileStatement => "Repeats its body while the condition is true.", + RepeatStatement => "Repeats its body until the condition is true.", + NumericFor => "Counts from start to limit, in steps, running the body each time.", + GenericFor => "Runs the body for each entry the iterator gives (pairs, ipairs, ...).", + DoStatement => "A block with a scope of its own.", + ReturnStatement => "Leaves the function, giving back its values.", + BreakStatement => "Leaves the innermost loop.", + SequenceStatement => "Runs its outputs one after the other.", + LocalDecl => "Makes a local variable.", + AssignStatement => "Stores a value in a variable or field.", + FunctionDecl => "A function of this script.", + FunctionEntry => "Where a function begins; its parameters come out here.", + BinaryOp or UnaryOp => "An operator: computes a value from its inputs.", + TableNode => "Makes a table.", + IndexGet => "Reads an entry of a table by key.", + MemberGet => "Reads a field of a table or object.", + VariableGet => "Reads a variable.", + CommentStatement => "A comment.", + _ => "" + }; + if (catalog.Entries.FirstOrDefault(e => e.Doc.Length > 0 && (e.Title == title || e.Name == title)) is { } entry) summary = entry.Doc; + var inputs = node.Inputs.Where(p => p.Name.Length > 0).Select(p => new DocPin(p.Name, p.Expected is { } expected ? TypeFormatter.Display(expected) : "any", PinStyle.ColorOf(p.Expected ?? LuaType.Any))).ToList(); + var outputs = node.Outputs.Select(p => new DocPin(p.Name, TypeFormatter.Display(p.Type), PinStyle.ColorOf(p.Type))).ToList(); + return new NodeDoc(title, summary, inputs, outputs); + } +} diff --git a/editor/LuaEditor/Editing/PinStyle.cs b/editor/LuaEditor/Editing/PinStyle.cs new file mode 100644 index 000000000..62c54f793 --- /dev/null +++ b/editor/LuaEditor/Editing/PinStyle.cs @@ -0,0 +1,59 @@ +using System.Linq; +using editor.LuaEditor.Types; + +namespace editor.LuaEditor.Editing; + +public enum PinShape { Circle, Diamond, Square, Arrow, Hexagon, Triangle, Stack, Pair } + +public static class PinStyle { + public const string Exec = "#fafafa"; + public const string Number = "#00ff40"; + public const string Integer = "#b6ff3d"; + public const string Array = "#00c2a8"; + public const string Text = "#ad73ff"; + public const string Boolean = "#ff1659"; + public const string Table = "#73ffea"; + public const string Function = "#ffa300"; + public const string Object = "#29adff"; + public const string Vector = "#ffec27"; + public const string Nothing = "#a0a0a0"; + public const string Anything = "#d8d8d8"; + + public static string ColorOf(LuaType type) { + type = Strip(type); + return type switch { + PrimitiveType { Kind: PrimitiveKind.Number } => Number, + PrimitiveType { Kind: PrimitiveKind.Integer } => Integer, + ArrayType => Array, + PrimitiveType { Kind: PrimitiveKind.String } => Text, + PrimitiveType { Kind: PrimitiveKind.Boolean } => Boolean, + PrimitiveType { Kind: PrimitiveKind.Table } or TableType => Table, + PrimitiveType { Kind: PrimitiveKind.Function } or FunctionType => Function, + PrimitiveType { Kind: PrimitiveKind.Nil } => Nothing, + PrimitiveType { Kind: PrimitiveKind.Any or PrimitiveKind.Unknown } => Anything, + LiteralType { Value: string } => Text, + LiteralType { Value: bool } => Boolean, + LiteralType => Number, + NamedType { Name: "vec2" or "vec3" or "vec4" or "quat" or "color" } => Vector, + NamedType => Object, + UnionType u => ColorOf(u.Members.FirstOrDefault(m => m is not PrimitiveType { Kind: PrimitiveKind.Nil }) ?? LuaType.Any), + _ => Anything + }; + } + + public static PinShape ShapeOf(LuaType type) => Strip(type) switch { + ArrayType => PinShape.Stack, + TableType => PinShape.Pair, + PrimitiveType { Kind: PrimitiveKind.Table } => PinShape.Diamond, + NamedType { Name: not ("vec2" or "vec3" or "vec4" or "quat" or "color") } => PinShape.Diamond, + PrimitiveType { Kind: PrimitiveKind.Boolean } or LiteralType { Value: bool } => PinShape.Triangle, + PrimitiveType { Kind: PrimitiveKind.Function } or FunctionType => PinShape.Square, + _ => PinShape.Circle + }; + + public static bool IsOptional(LuaType type) => type is UnionType u && u.Members.Any(m => m is PrimitiveType { Kind: PrimitiveKind.Nil }) && u.Members.Any(m => m is not PrimitiveType { Kind: PrimitiveKind.Nil }); + + private static LuaType Strip(LuaType type) => type is UnionType u && u.Members.Count(m => m is not PrimitiveType { Kind: PrimitiveKind.Nil }) == 1 + ? u.Members.First(m => m is not PrimitiveType { Kind: PrimitiveKind.Nil }) + : type; +} diff --git a/editor/LuaEditor/Editing/Shortcuts.cs b/editor/LuaEditor/Editing/Shortcuts.cs new file mode 100644 index 000000000..c7443696c --- /dev/null +++ b/editor/LuaEditor/Editing/Shortcuts.cs @@ -0,0 +1,67 @@ +using System.Collections.Generic; +using System.Linq; + +namespace editor.LuaEditor.Editing; + +public enum CanvasAction { + Branch, Sequence, ForEach, CommentBox, GroupAsFunction, Straighten, + AlignTop, AlignLeft, AlignBottom, AlignRight, Duplicate, Delete, Search, MakeTable, Tidy, + Add, Subtract, Multiply, Divide, Greater, Less, Equal, Not, + Number, Vec2, Vec3, Quat, + Copy, Paste, Cut, SelectAll, Undo, Redo, Save, Find, Home +} + +public sealed record KeyBinding(string Key, bool Ctrl, bool Shift, bool Alt, CanvasAction Action) { + public string Gesture => (Ctrl ? "Ctrl+" : "") + (Shift ? "Shift+" : "") + (Alt ? "Alt+" : "") + Key; +} + +public static class Shortcuts { + public static IReadOnlyList All { get; } = [ + new("B", false, false, false, CanvasAction.Branch), + new("S", false, false, false, CanvasAction.Sequence), + new("F", false, false, false, CanvasAction.ForEach), + new("C", false, false, false, CanvasAction.CommentBox), + new("G", false, false, false, CanvasAction.GroupAsFunction), + new("Q", false, false, false, CanvasAction.Straighten), + new("W", false, true, false, CanvasAction.AlignTop), + new("A", false, true, false, CanvasAction.AlignLeft), + new("S", false, true, false, CanvasAction.AlignBottom), + new("D", false, true, false, CanvasAction.AlignRight), + new("W", true, false, false, CanvasAction.Duplicate), + new("D", true, false, false, CanvasAction.Duplicate), + new("Delete", false, false, false, CanvasAction.Delete), + new("X", false, false, false, CanvasAction.Delete), + new("N", false, false, false, CanvasAction.Search), + new("M", false, false, false, CanvasAction.MakeTable), + new("T", false, false, false, CanvasAction.Tidy), + new("OemPlus", false, true, false, CanvasAction.Add), + new("Add", false, false, false, CanvasAction.Add), + new("OemMinus", false, false, false, CanvasAction.Subtract), + new("Subtract", false, false, false, CanvasAction.Subtract), + new("D8", false, true, false, CanvasAction.Multiply), + new("Multiply", false, false, false, CanvasAction.Multiply), + new("OemQuestion", false, false, false, CanvasAction.Divide), + new("Divide", false, false, false, CanvasAction.Divide), + new("OemPeriod", false, true, false, CanvasAction.Greater), + new("OemComma", false, true, false, CanvasAction.Less), + new("OemPlus", false, false, false, CanvasAction.Equal), + new("D1", false, true, false, CanvasAction.Not), + new("D1", false, false, false, CanvasAction.Number), + new("D2", false, false, false, CanvasAction.Vec2), + new("D3", false, false, false, CanvasAction.Vec3), + new("D4", false, false, false, CanvasAction.Quat), + new("C", true, false, false, CanvasAction.Copy), + new("V", true, false, false, CanvasAction.Paste), + new("X", true, false, false, CanvasAction.Cut), + new("A", true, false, false, CanvasAction.SelectAll), + new("Z", true, false, false, CanvasAction.Undo), + new("Y", true, false, false, CanvasAction.Redo), + new("Z", true, true, false, CanvasAction.Redo), + new("S", true, false, false, CanvasAction.Save), + new("F", true, false, false, CanvasAction.Find), + new("Home", false, false, false, CanvasAction.Home) + ]; + + public static CanvasAction? Find(string key, bool ctrl, bool shift, bool alt) + => All.FirstOrDefault(b => b.Key == key && b.Ctrl == ctrl && b.Shift == shift && b.Alt == alt)?.Action; +} diff --git a/editor/LuaEditor/Editing/TypeText.cs b/editor/LuaEditor/Editing/TypeText.cs new file mode 100644 index 000000000..bbc5d30f5 --- /dev/null +++ b/editor/LuaEditor/Editing/TypeText.cs @@ -0,0 +1,24 @@ +using System.Collections.Generic; +using System.Linq; + +namespace editor.LuaEditor.Editing; + +public static class TypeText { + public static List SplitTopLevel(string text) { + var parts = new List(); + var depth = 0; + var start = 0; + for (var i = 0; i < text.Length; i++) { + switch (text[i]) { + case '(' or '<' or '{' or '[': depth++; break; + case ')' or '>' or '}' or ']': depth--; break; + case ',' when depth == 0: + parts.Add(text[start..i].Trim()); + start = i + 1; + break; + } + } + parts.Add(text[start..].Trim()); + return parts.Where(p => p.Length > 0).ToList(); + } +} diff --git a/editor/LuaEditor/Layout/Arrange.cs b/editor/LuaEditor/Layout/Arrange.cs new file mode 100644 index 000000000..215f877c7 --- /dev/null +++ b/editor/LuaEditor/Layout/Arrange.cs @@ -0,0 +1,130 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using editor.LuaEditor.Graph; + +namespace editor.LuaEditor.Layout; + +public enum AlignEdge { Top, Left, Bottom, Right } + +public static class Arrange { + public static void Tidy(GraphLayout layout, RegionInfo region, IReadOnlyCollection? selection, bool includePinned) { + var ideal = new AutoLayout(layout.Measure, layout.Keys).Region(region); + var nodes = (selection ?? layout.NodesOf(region)).Where(n => layout.Keys.RegionOf(n) == region && ideal.ContainsKey(n) && !InlineRules.IsMerged(n)).ToList(); + var moving = nodes.Where(n => includePinned || !layout.PinnedNodes.Contains(n)).ToList(); + if (moving.Count == 0) return; + + var shift = default(Vec); + if (selection is not null) { + var idealCorner = new Vec(moving.Min(n => ideal[n].X), moving.Min(n => ideal[n].Y)); + var currentCorner = new Vec(moving.Where(layout.IsPlaced).Select(n => layout.Local[n].X).DefaultIfEmpty(idealCorner.X).Min(), + moving.Where(layout.IsPlaced).Select(n => layout.Local[n].Y).DefaultIfEmpty(idealCorner.Y).Min()); + shift = currentCorner - idealCorner; + } + + var fixedNodes = layout.NodesOf(region).Where(n => layout.IsPlaced(n) && !moving.Contains(n) && !InlineRules.IsMerged(n)).ToList(); + var placed = new List(fixedNodes.Select(layout.BoundsLocal)); + foreach (var node in moving.OrderBy(n => ideal[n].X).ThenBy(n => ideal[n].Y)) { + var size = layout.Measure.Measure(node); + var p = ideal[node] + shift; + var guard = 0; + while (guard++ < 10_000) { + var box = new Rect(p.X, p.Y, size.W, size.H).Inflate(4); + var hit = placed.Where(r => r.Intersects(box)).Select(r => (Rect?)r).FirstOrDefault(); + if (hit is null) break; + p = new Vec(p.X, hit.Value.Bottom + 8); + } + layout.Local[node] = p; + placed.Add(new Rect(p.X, p.Y, size.W, size.H)); + } + LayoutEngine.FollowHosts(layout); + } + + public static bool Straighten(GraphLayout layout, OutputPin from, InputPin to) { + var source = InlineRules.Drawn(from.Owner); + var target = InlineRules.Drawn(to.Owner); + if (NodeShape.SlotOf(from) is not { } fromSlot || NodeShape.SlotOf(to) is not { } toSlot) return false; + if (!layout.IsPlaced(source) || !layout.IsPlaced(target)) return false; + var sourceY = layout.Position(source).Y + layout.Measure.PinY(source, fromSlot.Row, true); + var targetY = layout.Position(target).Y + layout.Measure.PinY(target, toSlot.Row, false); + var dy = sourceY - targetY; + if (Math.Abs(dy) < 0.01) return true; + + var moved = layout.Bounds(target).Offset(new Vec(0, dy)); + var region = layout.Keys.RegionOf(target); + if (region is not null && layout.NodesOf(region).Any(n => n != target && layout.IsPlaced(n) && !InlineRules.IsMerged(n) && layout.Bounds(n).Intersects(moved))) return false; + layout.SetPosition(target, layout.Position(target) + new Vec(0, dy)); + return true; + } + + public static bool StraightenSelection(GraphLayout layout, IReadOnlyList<(Slot From, Slot To)> links) { + var groups = new Dictionary>(); + var obstacles = layout.Local.Keys.Where(node => !layout.IsHidden(node) && !InlineRules.IsMerged(node)).ToList(); + bool changed = false; + HashSet Group(GraphNode node) { + if (!groups.TryGetValue(node, out var group)) groups[node] = group = [node]; + return group; + } + double PinY(Slot slot) => layout.Position(slot.Node).Y + layout.Measure.PinY(slot.Node, slot.Row, !slot.IsLeft); + foreach (var (from, to) in links) { + var source = from.Node; + var target = to.Node; + if (source == target || !layout.IsPlaced(source) || !layout.IsPlaced(target) || + layout.IsHidden(source) || layout.IsHidden(target) || layout.HostBody(source) != layout.HostBody(target)) continue; + var start = Group(source); + var end = Group(target); + var dy = PinY(from) - PinY(to); + if (Math.Abs(dy) > 0.01) { + if (start == end) continue; + var delta = new Vec(0, dy); + if (end.Any(node => layout.ConstrainFrameMove(node, delta) != delta)) continue; + if (end.Any(node => obstacles.Any(other => !end.Contains(other) && + !layout.IsInsideFrameOf(node, other) && !layout.IsInsideFrameOf(other, node) && + layout.Bounds(node).Offset(delta).Intersects(layout.Bounds(other))))) continue; + foreach (var node in end) layout.AnchorFrame(node); + foreach (var node in end) layout.Local[node] += delta; + changed = true; + } + if (start != end) { + start.UnionWith(end); + foreach (var node in end) groups[node] = start; + } + if (to.In is { } input) changed |= layout.Reroutes.Remove(input); + else if (to.Node is Statement statement) changed |= layout.ExecReroutes.Remove(statement); + } + LayoutEngine.FollowHosts(layout); + return changed; + } + + public static void Align(GraphLayout layout, IReadOnlyCollection nodes, AlignEdge edge) { + var placed = nodes.Where(layout.IsPlaced).ToList(); + if (placed.Count < 2) return; + var bounds = placed.ToDictionary(n => n, layout.Bounds); + foreach (var node in placed) { + var b = bounds[node]; + var position = layout.Position(node); + switch (edge) { + case AlignEdge.Top: position = position with { Y = bounds.Values.Min(r => r.Y) }; break; + case AlignEdge.Left: position = position with { X = bounds.Values.Min(r => r.X) }; break; + case AlignEdge.Bottom: position = position with { Y = bounds.Values.Max(r => r.Bottom) - b.H }; break; + case AlignEdge.Right: position = position with { X = bounds.Values.Max(r => r.Right) - b.W }; break; + } + layout.SetPosition(node, position); + } + } + + public static void Distribute(GraphLayout layout, IReadOnlyCollection nodes, bool horizontal) { + var placed = nodes.Where(layout.IsPlaced).OrderBy(n => horizontal ? layout.Position(n).X : layout.Position(n).Y).ToList(); + if (placed.Count < 3) return; + double Extent(GraphNode n) => horizontal ? layout.Bounds(n).W : layout.Bounds(n).H; + var first = horizontal ? layout.Bounds(placed[0]).X : layout.Bounds(placed[0]).Y; + var last = horizontal ? layout.Bounds(placed[^1]).Right : layout.Bounds(placed[^1]).Bottom; + var gap = (last - first - placed.Sum(Extent)) / (placed.Count - 1); + var cursor = first; + foreach (var node in placed) { + var p = layout.Position(node); + layout.SetPosition(node, horizontal ? p with { X = cursor } : p with { Y = cursor }); + cursor += Extent(node) + gap; + } + } +} diff --git a/editor/LuaEditor/Layout/AutoLayout.cs b/editor/LuaEditor/Layout/AutoLayout.cs new file mode 100644 index 000000000..c4fd2b146 --- /dev/null +++ b/editor/LuaEditor/Layout/AutoLayout.cs @@ -0,0 +1,148 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using editor.LuaEditor.Graph; + +namespace editor.LuaEditor.Layout; + +public sealed class AutoLayout { + public const double ColumnGap = 64; + public const double StepGap = 90; + public const double RowGap = 46; + + public const double MaxRowWidth = 1e9; + + public const double ExecClearance = DefaultMeasure.HeaderHeight + DefaultMeasure.RowHeight + 12; + + private readonly INodeMeasure m_measure; + private readonly GraphKeys m_keys; + private readonly Dictionary m_result = []; + + public AutoLayout(INodeMeasure measure, GraphKeys keys) { + m_measure = measure; + m_keys = keys; + } + + public Dictionary Region(RegionInfo region) { + m_result.Clear(); + var x = 0.0; + if (region.Header is FunctionDecl decl) { + var size = m_measure.Measure(decl); + var data = DataColumns(decl, 0, 0, out var dataBottom, out var dataLeft, 0); + Put(decl, new Vec(dataLeft, 0)); + x = dataLeft + size.W + StepGap; + _ = data; + _ = dataBottom; + } else if (region.Entry is not null) { + x = PlaceEntry(region, x); + } + Block(region.Body, x, 0, x + MaxRowWidth, out _, out _); + + var minX = m_result.Count == 0 ? 0 : m_result.Values.Min(v => v.X); + var minY = m_result.Count == 0 ? 0 : m_result.Values.Min(v => v.Y); + return m_result.ToDictionary(p => p.Key, p => new Vec(p.Value.X - minX, p.Value.Y - minY)); + } + + public Size SizeOf(Dictionary placed) { + var w = 0.0; + var h = 0.0; + foreach (var (node, p) in placed) { + var s = m_measure.Measure(node); + w = Math.Max(w, p.X + s.W); + h = Math.Max(h, p.Y + s.H); + } + return new Size(w, h); + } + + private double PlaceEntry(RegionInfo region, double x) { + var entry = region.Entry!; + Put(entry, new Vec(x, 0)); + return x + m_measure.Measure(entry).W + StepGap; + } + + private void Put(GraphNode node, Vec position) => m_result[node] = position; + + private void Block(Block block, double x, double y, double limit, out double right, out double bottom) { + right = x; + bottom = y; + var cursor = x; + var rowY = y; + var inRow = 0; + foreach (var statement in block.Statements) { + if (statement is FunctionDecl) continue; + var size = m_measure.Measure(statement); + DataColumns(statement, cursor, rowY, out var dataBottom, out var statementX); + if (inRow > 0 && statementX + size.W > limit) { + cursor = x; + rowY = bottom + RowGap * 2; + inRow = 0; + DataColumns(statement, cursor, rowY, out dataBottom, out statementX); + } + Put(statement, new Vec(statementX, rowY)); + + var rowBottom = Math.Max(rowY + size.H, dataBottom); + var rowRight = statementX + size.W; + var childY = rowY; +var first = true; + foreach (var child in statement.ChildBlocks) { + if (!first) childY += RowGap; + first = false; + Block(child, statementX + size.W + StepGap, childY, limit, out var childRight, out var childBottom); + // empty branches still need room for a flow wire + childBottom = Math.Max(childBottom, childY + DefaultMeasure.RowHeight); + rowRight = Math.Max(rowRight, childRight); + childY = childBottom; + rowBottom = Math.Max(rowBottom, childBottom); + } + right = Math.Max(right, rowRight); + bottom = Math.Max(bottom, rowBottom); + if (statement.ChildBlocks.Any() && NodeShape.HasContinuation(statement)) { + // branch order keeps the flow wires from crossing + cursor = statementX + size.W + StepGap; + rowY = rowBottom + RowGap; + } else { + cursor = rowRight + StepGap; + } + inRow++; + } + } + + private List<(GraphNode Node, int Depth)> DataColumns(Statement statement, double left, double top, out double bottom, out double statementX, double clearance = ExecClearance) { + var nodes = new List<(GraphNode Node, int Depth, double Y)>(); + var cursorY = top + clearance; + var seen = new HashSet(); + foreach (var pin in statement.Inputs) cursorY = Collect(pin, 1, cursorY, nodes, seen); + bottom = Math.Max(cursorY - RowGap, top); + + var maxDepth = nodes.Count == 0 ? 0 : nodes.Max(n => n.Depth); + var columnWidth = new double[maxDepth + 2]; + foreach (var (node, depth, _) in nodes) columnWidth[depth] = Math.Max(columnWidth[depth], m_measure.Measure(node).W); + + var columnX = new double[maxDepth + 2]; + var x = left; + for (var d = maxDepth; d >= 1; d--) { + columnX[d] = x; + x += columnWidth[d] + ColumnGap; + } + statementX = x; + foreach (var (node, depth, y) in nodes) Put(node, new Vec(columnX[depth] + columnWidth[depth] - m_measure.Measure(node).W, y)); + return nodes.Select(n => (n.Node, n.Depth)).ToList(); + } + + private double Collect(InputPin pin, int depth, double top, List<(GraphNode Node, int Depth, double Y)> nodes, HashSet seen) { + if (pin.Source?.Owner is not ExprNode expr || !seen.Add(expr) || m_keys.KeyOf(expr) is null) return top; + if (InlineRules.IsMerged(expr)) { + foreach (var input in expr.Inputs) top = Collect(input, depth, top, nodes, seen); + return top; + } + var size = m_measure.Measure(expr); + var index = nodes.Count; + nodes.Add((expr, depth, top)); + var next = top; + if (expr is not FunctionNode) + foreach (var input in expr.Inputs) next = Collect(input, depth + 1, next, nodes, seen); + var used = Math.Max(next, top + size.H + RowGap); + nodes[index] = (expr, depth, top); + return used; + } +} diff --git a/editor/LuaEditor/Layout/Geometry.cs b/editor/LuaEditor/Layout/Geometry.cs new file mode 100644 index 000000000..71cac7c2a --- /dev/null +++ b/editor/LuaEditor/Layout/Geometry.cs @@ -0,0 +1,92 @@ +using System; +using System.Linq; +using editor.LuaEditor.Graph; + +namespace editor.LuaEditor.Layout; + +public readonly record struct Vec(double X, double Y) { + public static Vec operator +(Vec a, Vec b) => new(a.X + b.X, a.Y + b.Y); + public static Vec operator -(Vec a, Vec b) => new(a.X - b.X, a.Y - b.Y); +} + +public readonly record struct Size(double W, double H); + +public readonly record struct Rect(double X, double Y, double W, double H) { + public double Right => X + W; + public double Bottom => Y + H; + public Vec TopLeft => new(X, Y); + + public bool Intersects(Rect o) => X < o.Right && o.X < Right && Y < o.Bottom && o.Y < Bottom; + + public Rect Inflate(double d) => new(X - d, Y - d, W + 2 * d, H + 2 * d); + + public Rect Offset(Vec v) => new(X + v.X, Y + v.Y, W, H); + + public static Rect Union(Rect a, Rect b) { + var x = Math.Min(a.X, b.X); + var y = Math.Min(a.Y, b.Y); + return new Rect(x, y, Math.Max(a.Right, b.Right) - x, Math.Max(a.Bottom, b.Bottom) - y); + } +} + +public interface INodeMeasure { + Size Measure(GraphNode node); + + double PinY(GraphNode node, int index, bool output); +} + +public sealed class DefaultMeasure : INodeMeasure { + public const double HeaderHeight = 28; + public const double RowHeight = 22; + public const double MinWidth = 120; + + public const double ConstantBoxWidth = 64; + + public static double ConstantWidth(InputPin pin) { + var choice = InlineRules.EnumValueOf(pin); + var text = choice ?? pin.Constant?.Raw ?? "nil"; + return Math.Clamp(text.Length * 7 + (choice is not null ? 28 : 20), ConstantBoxWidth, 240); + } + + private const double LabelChar = 6.6; + + private const double TitleChar = 7.6; + + public static (double Left, double Right) Rails(GraphNode node) { + var slots = NodeShape.SlotsOf(node); + double Left(Slot s) => s.Label.Length * LabelChar + 24 + (s.Kind == SlotKind.DataIn && s.In is { } pin && (pin.Source is null || InlineRules.IsMergedName(pin.Source.Owner)) ? ConstantWidth(pin) + 8 : 0); + var left = slots.Where(s => s.IsLeft).Select(Left).DefaultIfEmpty(0).Max(); + var right = slots.Where(s => !s.IsLeft).Select(s => s.Label.Length * LabelChar + 24).DefaultIfEmpty(0).Max(); + if (node.IsExpanded && NodeShape.CalleeOf(node) is not null) return (Math.Max(left, 96), Math.Max(right, 96)); + return (left, right); + } + + public Func? RegionSize { get; set; } + + public static Vec FrameInset(GraphNode host) => new(Rails(host).Left + FramePadX, HeaderHeight + FramePadY); + + public const double FramePadX = 44; + + public const double FramePadY = 40; + + public Size Measure(GraphNode node) { + if (InlineRules.IsGetterNode(node)) return new Size(NodeShape.TitleOf(node).Length * 7 + 36, GetterHeight); + var (left, right) = Rails(node); + var title = NodeShape.TitleOf(node).Length * TitleChar + 44; + var width = Math.Max(MinWidth, Math.Max(title, left + right + 12)); + if (node is CommentStatement) width = Math.Max(MinWidth, NodeShape.TitleOf(node).Length * 6.8 + 28); + var height = HeaderHeight + RowHeight * NodeShape.Rows(node) + 8; + if (NodeShape.ExpansionOf(node) is { } frame) { + var (innerW, innerH) = (frame.InnerWidth, frame.InnerHeight); + if (RegionSize?.Invoke(frame.Callee) is { } size) (innerW, innerH) = (Math.Max(size.W, 200), Math.Max(size.H, 110)); + width = left + innerW + right + 2 * FramePadX; + height = HeaderHeight + Math.Max(RowHeight * NodeShape.Rows(node) + 8, innerH + 2 * FramePadY) + 1; + return new Size(width, height); + } + return new Size(Math.Min(width, 760), height); + } + + public const double GetterHeight = 22; + + public double PinY(GraphNode node, int row, bool output) => InlineRules.IsGetterNode(node) ? GetterHeight / 2 : HeaderHeight + RowHeight * row + RowHeight / 2; +} diff --git a/editor/LuaEditor/Layout/GraphKeys.cs b/editor/LuaEditor/Layout/GraphKeys.cs new file mode 100644 index 000000000..9cbbb5e36 --- /dev/null +++ b/editor/LuaEditor/Layout/GraphKeys.cs @@ -0,0 +1,190 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using editor.LuaEditor.Graph; + +namespace editor.LuaEditor.Layout; + +public sealed class RegionInfo { + internal RegionInfo(string key, GraphNode? header, Block body, GraphNode? entry) { + Key = key; + Header = header; + Body = body; + Entry = entry; + } + + public string Key { get; } + + public GraphNode? Header { get; } + + public GraphNode? Entry { get; } + public Block Body { get; } + public string Name => Header is FunctionDecl d ? d.Name : Key; + public bool IsModule => Header is null; +} + +public sealed class GraphKeys { + public const string ModuleKey = ""; + + private readonly Dictionary m_keys = []; + private readonly Dictionary m_nodes = []; + private readonly Dictionary m_regionOf = []; + private readonly List m_regions = []; + private readonly HashSet m_claimed = []; + private readonly List<(GraphNode Node, string Key)> m_ordered = []; + + public IReadOnlyList Regions => m_regions; + + public static GraphKeys Compute(LuaGraph graph) { + var keys = new GraphKeys(); + var module = new RegionInfo(ModuleKey, null, graph.Module, null); + keys.m_regions.Add(module); + keys.WalkBlock(graph.Module, "", module, true); + return keys; + } + + public string? KeyOf(GraphNode node) => m_keys.GetValueOrDefault(node); + + public GraphNode? NodeOf(string key) => m_nodes.GetValueOrDefault(key); + + public RegionInfo? RegionOf(GraphNode node) => m_regionOf.GetValueOrDefault(node); + + public IEnumerable> All => m_keys; + + public IReadOnlyList<(GraphNode Node, string Key)> Ordered => m_ordered; + + public static IEnumerable Flatten(Block block) { + foreach (var s in block.Statements) { + if (s is SequenceStatement sequence) { + foreach (var branch in sequence.Branches) + foreach (var inner in Flatten(branch)) + yield return inner; + } else { + yield return s; + } + } + } + + public static string Fingerprint(Statement s) => s switch { + CallStatement c => "call:" + CallName(c.CallNode), + LocalDecl l => "local:" + string.Join(",", l.Names.Select(n => n.Name)), + AssignStatement a => "assign:" + string.Join(",", a.Targets.Select(t => t.Name ?? "[]")), + IfStatement => "if", + WhileStatement => "while", + RepeatStatement => "repeat", + NumericFor n => "for:" + n.Var.Name, + GenericFor g => "forin:" + string.Join(",", g.Vars.Select(v => v.Name)), + DoStatement => "do", + FunctionDecl d => "fn:" + string.Join(d.IsMethod ? ":" : ".", d.Path), + ReturnStatement => "return", + BreakStatement => "break", + GotoStatement g => "goto:" + g.Label, + LabelStatement l => "label:" + l.Name, + CastStatement c => "cast:" + c.Variable, + CommentStatement c => "comment:" + (c.Lines.Count > 0 ? c.Lines[0].Trim() : ""), + SequenceStatement => "sequence", + RawStatement r => "raw:" + (r.Text.Length > 24 ? r.Text[..24] : r.Text), + _ => s.GetType().Name + }; + + private static string CallName(CallNode? call) { + if (call is null) return "?"; + if (call.Style == CallStyle.Method) return Describe(call.Target.Source?.Owner) + ":" + call.Method; + return Describe(call.Target.Source?.Owner); + } + + private static string Describe(GraphNode? node) => node switch { + GlobalGet g => g.Name, + VariableGet v => v.Binding.Name, + MemberGet m => Describe(m.Object.Source?.Owner) + "." + m.Name, + CallNode c => CallName(c) + "()", + null => "", + _ => node.Outputs.Count > 0 && node.Outputs[0].Binding is { } b ? b.Name : node.GetType().Name + }; + + public static string RoleOf(Statement owner, Block block) { + if (owner is IfStatement i) { + var index = i.Clauses.FindIndex(c => c.Body == block); + if (index == 0) return "then"; + if (index > 0) return "elseif" + (index + 1); + return "else"; + } + return "body"; + } + + private void WalkBlock(Block block, string prefix, RegionInfo region, bool module) { + var n = 0; + foreach (var s in block.Statements) { + if (s.IsFloating) continue; + if (s is SequenceStatement sequence) { + var firstIndex = n + 1; + WalkSequence(sequence, prefix, region, module, ref n); + Add(sequence, "~" + prefix + firstIndex, region); + continue; + } + n++; + WalkStatement(s, prefix + n, region, module); + } + } + + private void WalkSequence(SequenceStatement sequence, string prefix, RegionInfo region, bool module, ref int n) { + foreach (var branch in sequence.Branches) { + foreach (var s in branch.Statements) { + if (s is SequenceStatement inner) { + var firstIndex = n + 1; + WalkSequence(inner, prefix, region, module, ref n); + Add(inner, "~" + prefix + firstIndex, region); + continue; + } + n++; + WalkStatement(s, prefix + n, region, module); + } + } + } + + private void WalkStatement(Statement s, string key, RegionInfo region, bool module) { + if (s is FunctionDecl decl) { + var regionKey = !module ? key : decl.IsLocal ? "local " + decl.Name : string.Join(decl.IsMethod ? ":" : ".", decl.Path); + if (m_nodes.ContainsKey(regionKey) || regionKey == ModuleKey) regionKey = key; + var own = new RegionInfo(regionKey, decl, decl.Entry.Body, decl.Entry); + m_regions.Add(own); + Add(decl, regionKey, own); + Add(decl.Entry, regionKey + "!entry", own); + ExpressionKeys(decl, regionKey, own); + WalkBlock(decl.Entry.Body, regionKey + "/", own, false); + return; + } + + Add(s, key, region); + ExpressionKeys(s, key, region); + foreach (var child in s.ChildBlocks) WalkBlock(child, key + "/" + RoleOf(s, child) + "/", region, false); + } + + private void ExpressionKeys(Statement s, string key, RegionInfo region) { + var closures = 0; + for (var i = 0; i < s.Inputs.Count; i++) Expression(s.Inputs[i], key + "#" + i, key, region, ref closures); + } + + private void Expression(InputPin pin, string path, string statementKey, RegionInfo region, ref int closures) { + if (pin.Source?.Owner is not ExprNode e || !m_claimed.Add(e)) return; + Add(e, path, region); + if (e is FunctionNode f) { + closures++; + var regionKey = statementKey + "/fn" + closures; + var own = new RegionInfo(regionKey, f, f.Entry.Body, f.Entry); + m_regions.Add(own); + Add(f.Entry, regionKey + "!entry", own); + WalkBlock(f.Entry.Body, regionKey + "/", own, false); + return; + } + for (var i = 0; i < e.Inputs.Count; i++) Expression(e.Inputs[i], path + "." + i, statementKey, region, ref closures); + } + + private void Add(GraphNode node, string key, RegionInfo region) { + if (m_nodes.ContainsKey(key)) key += "'" + m_nodes.Count; + m_keys[node] = key; + m_ordered.Add((node, key)); + m_nodes[key] = node; + m_regionOf[node] = region; + } +} diff --git a/editor/LuaEditor/Layout/GraphLayout.cs b/editor/LuaEditor/Layout/GraphLayout.cs new file mode 100644 index 000000000..76d02df59 --- /dev/null +++ b/editor/LuaEditor/Layout/GraphLayout.cs @@ -0,0 +1,231 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using editor.LuaEditor.Graph; + +namespace editor.LuaEditor.Layout; + +public sealed class LayoutGroup { + public string Title { get; set; } = ""; + public string Color { get; set; } = "#4a7a5c"; + + public Rect Rect { get; set; } + + public List Members { get; } = []; +} + +public sealed class GraphLayout { + private Dictionary> m_nodesOfRegion = []; + + public GraphLayout(LuaGraph graph, INodeMeasure measure) { + Graph = graph; + Measure = measure; + Keys = GraphKeys.Compute(graph); + IndexRegions(); + if (measure is DefaultMeasure sized) sized.RegionSize = CalleeSize; + } + + private readonly HashSet m_measuring = []; + + private Size? CalleeSize(FunctionDecl callee) { + var region = Keys.Regions.FirstOrDefault(r => r.Header == callee); + if (region is null || !m_measuring.Add(callee)) return null; + try { + if (LocalBoundsOf(region) is not { } bounds) return null; + var corner = FrameCorner(region.Body, bounds); + return new Size(bounds.Right - corner.X, bounds.Bottom - corner.Y); + } finally { + m_measuring.Remove(callee); + } + } + + public LuaGraph Graph { get; } + public INodeMeasure Measure { get; set; } + public GraphKeys Keys { get; private set; } + + public Dictionary Local { get; } = []; + + public Dictionary Origins { get; } = []; + + public HashSet PinnedRegions { get; } = []; + public HashSet CollapsedRegions { get; } = []; + public HashSet PinnedNodes { get; } = []; + public HashSet CollapsedNodes { get; } = []; + public List Groups { get; } = []; + + public Dictionary> Reroutes { get; } = []; + + public Dictionary CallableWireHosts { get; } = []; + + public Dictionary ProxyOffsets { get; } = []; + + public Dictionary> ExecReroutes { get; } = []; + + public HashSet Loose { get; } = []; + + public void Refresh() { + Keys = GraphKeys.Compute(Graph); + IndexRegions(); + foreach (var dead in Local.Keys.Where(n => Keys.KeyOf(n) is null && !Loose.Contains(n)).ToList()) Local.Remove(dead); + Loose.RemoveWhere(n => !Graph.Nodes.Contains(n)); + foreach (var group in Groups) group.Members.RemoveAll(m => Keys.KeyOf(m) is null); + Groups.RemoveAll(g => g.Members.Count == 0); + PinnedNodes.RemoveWhere(n => Keys.KeyOf(n) is null); + foreach (var body in Embedded.Where(e => (!Loose.Contains(e.Value) && Keys.KeyOf(e.Value) is null) || !e.Value.IsExpanded || NodeShape.LocalCalleeOf(e.Value)?.Entry.Body != e.Key || HostBody(e.Value) == e.Key).Select(e => e.Key).ToList()) Embedded.Remove(body); + foreach (var host in Keys.Ordered.Select(k => k.Node).Concat(Loose).Where(node => node.IsExpanded && !Embedded.ContainsValue(node)).Distinct().ToList()) { + var region = NodeShape.LocalCalleeOf(host) is { } callee ? Keys.Regions.FirstOrDefault(r => r.Header == callee) : null; + if (region is not null && !Embedded.ContainsKey(region.Body) && HostBody(host) != region.Body) Embedded[region.Body] = host; + else host.IsExpanded = false; + } + foreach (var dead in Reroutes.Keys.Where(p => p.Source is null || Keys.KeyOf(InlineRules.Drawn(p.Owner)) is null).ToList()) Reroutes.Remove(dead); + foreach (var dead in CallableWireHosts.Where(pair => Keys.KeyOf(pair.Key.Owner) is null || Keys.KeyOf(pair.Value) is null || CallableSlot(pair.Key, pair.Value) is null).Select(pair => pair.Key).ToList()) + CallableWireHosts.Remove(dead); + foreach (var dead in ProxyOffsets.Keys.Where(p => p.Source is null || Keys.KeyOf(InlineRules.Drawn(p.Owner)) is null).ToList()) ProxyOffsets.Remove(dead); + foreach (var dead in ExecReroutes.Keys.Where(s => Keys.KeyOf(s) is null).ToList()) ExecReroutes.Remove(dead); + CollapsedNodes.RemoveWhere(n => Keys.KeyOf(n) is null); + var live = Keys.Regions.Select(r => r.Body).ToHashSet(); + foreach (var dead in Origins.Keys.Where(b => !live.Contains(b)).ToList()) Origins.Remove(dead); + foreach (var dead in FrameCorners.Keys.Where(b => !live.Contains(b)).ToList()) FrameCorners.Remove(dead); + PinnedRegions.RemoveWhere(b => !live.Contains(b)); + CollapsedRegions.RemoveWhere(b => !live.Contains(b)); + } + + private void IndexRegions() { + m_nodesOfRegion = Keys.Regions.ToDictionary(r => r, _ => new List()); + foreach (var (node, _) in Keys.All) + if (Keys.RegionOf(node) is { } region) + m_nodesOfRegion[region].Add(node); + } + + public IReadOnlyList NodesOf(RegionInfo region) => m_nodesOfRegion.TryGetValue(region, out var list) ? list : []; + + public bool IsPlaced(GraphNode node) => Local.ContainsKey(node); + + public Dictionary Embedded { get; } = []; + public Dictionary FrameCorners { get; } = []; + + private Vec FrameCorner(Block body, Rect bounds) => FrameCorners.TryGetValue(body, out var corner) + ? new Vec(Math.Min(corner.X, bounds.X), Math.Min(corner.Y, bounds.Y)) : bounds.TopLeft; + + public Vec ConstrainFrameMove(GraphNode node, Vec delta) { + if (Keys.RegionOf(node) is not { } region || !Embedded.ContainsKey(region.Body) || IsHidden(node) || + LocalBoundsOf(region) is not { } bounds) return delta; + var corner = FrameCorner(region.Body, bounds); + var at = Local[node]; + return new Vec(Math.Max(delta.X, corner.X - at.X), Math.Max(delta.Y, corner.Y - at.Y)); + } + + public void AnchorFrame(GraphNode node) { + if (Keys.RegionOf(node) is { } region && Embedded.ContainsKey(region.Body) && LocalBoundsOf(region) is { } bounds) + FrameCorners[region.Body] = FrameCorner(region.Body, bounds); + } + + // unwired statements still need a scope for name lookup + public Block? HostBody(GraphNode host) { + if (Keys.RegionOf(host) is { } region) return region.Body; + for (var block = (host as Statement ?? host.OwnerStatement)?.Parent; block is not null; block = (block.Owner as Statement)?.Parent) + if (block == Graph.Module || block.Owner is FunctionEntry) return block; + return null; + } + + public Slot? CallableSlot(InputPin target) => CallableWireHosts.TryGetValue(target, out var host) ? CallableSlot(target, host) : null; + + private static Slot? CallableSlot(InputPin target, GraphNode host) { + if (target.Source is not { } source) return null; + return NodeShape.SlotsOf(host).FirstOrDefault(slot => slot is { IsCallableReference: true, Out: { } callable } && + (source == callable || NodeShape.BindingOf(source) is { } binding && binding == NodeShape.BindingOf(callable) || + source.Owner is MemberGet a && callable.Owner is MemberGet b && a.Name == b.Name && + NodeShape.BindingOf(a.Object.Source) is { } receiver && receiver == NodeShape.BindingOf(b.Object.Source))); + } + + public Vec OriginOf(RegionInfo region) { + if (Embedded.TryGetValue(region.Body, out var host) && Local.ContainsKey(host) && LocalBoundsOf(region) is { } inside) { + var inset = DefaultMeasure.FrameInset(host); + return Position(host) + inset - FrameCorner(region.Body, inside); + } + return Origins.GetValueOrDefault(region.Body); + } + + public Rect? LocalBoundsOf(RegionInfo region) { + Rect? total = null; + foreach (var node in NodesOf(region)) { + if (!Local.ContainsKey(node) || InlineRules.IsMerged(node) || IsHidden(node)) continue; + var b = BoundsLocal(node); + total = total is null ? b : Rect.Union(total.Value, b); + } + return total; + } + + public Vec Position(GraphNode node) { + if (Loose.Contains(node)) return Local.GetValueOrDefault(node); + var local = Local.GetValueOrDefault(node); + return Keys.RegionOf(node) is { } region ? OriginOf(region) + local : local; + } + + public void SetPosition(GraphNode node, Vec canvas) { + var origin = Keys.RegionOf(node) is { } region ? OriginOf(region) : default; + Local[node] = canvas - origin; + } + + public Rect BoundsLocal(GraphNode node) { + var p = Local.GetValueOrDefault(node); + var s = Measure.Measure(node); + return new Rect(p.X, p.Y, s.W, s.H); + } + + public Rect Bounds(GraphNode node) { + var p = Position(node); + var s = Measure.Measure(node); + return new Rect(p.X, p.Y, s.W, s.H); + } + + public Rect? RegionBounds(RegionInfo region) { + Rect? total = null; + foreach (var node in NodesOf(region)) { + if (!Local.ContainsKey(node) || InlineRules.IsMerged(node) || IsHidden(node)) continue; + var b = Bounds(node); + total = total is null ? b : Rect.Union(total.Value, b); + } + return total; + } + + public void MoveRegion(RegionInfo region, Vec delta) { + Origins[region.Body] = OriginOf(region) + delta; + foreach (var group in GroupsOf(region)) group.Rect = group.Rect.Offset(delta); + } + + public IEnumerable GroupsOf(RegionInfo region) => + Groups.Where(g => g.Members.FirstOrDefault(m => Keys.KeyOf(m) is not null) is { } member && Keys.RegionOf(member) == region); + + public Rect? RegionExtent(RegionInfo region) { + if (RegionBounds(region) is not { } bounds) return null; + foreach (var group in GroupsOf(region)) bounds = Rect.Union(bounds, group.Rect); + return bounds; + } + + public void PlaceRegion(RegionInfo region, Vec topLeft) { + if (RegionExtent(region) is not { } bounds) return; + MoveRegion(region, topLeft - bounds.TopLeft); + } + + public bool IsHidden(GraphNode node) { + if (Keys.RegionOf(node) is not { } region || !Embedded.ContainsKey(region.Body)) return false; + if (node == region.Header || node == region.Entry) return true; + return node is ReturnStatement ret && NodeShape.TrailingReturn(region.Body) == ret; + } + + public bool IsInsideFrameOf(GraphNode node, GraphNode host) { + for (var body = HostBody(node); body is not null && Embedded.TryGetValue(body, out var outer); body = HostBody(outer)) + if (outer == host) return true; + return false; + } + + public IEnumerable<(GraphNode A, GraphNode B)> Overlaps() { + + var placed = Local.Keys.Where(n => Keys.KeyOf(n) is not null && !InlineRules.IsMerged(n) && !IsHidden(n)).ToList(); + var rects = placed.Select(Bounds).ToList(); + for (var i = 0; i < placed.Count; i++) + for (var j = i + 1; j < placed.Count; j++) + if (rects[i].Intersects(rects[j]) && !IsInsideFrameOf(placed[i], placed[j]) && !IsInsideFrameOf(placed[j], placed[i])) yield return (placed[i], placed[j]); + } +} diff --git a/editor/LuaEditor/Layout/InlineRules.cs b/editor/LuaEditor/Layout/InlineRules.cs new file mode 100644 index 000000000..90f4248b3 --- /dev/null +++ b/editor/LuaEditor/Layout/InlineRules.cs @@ -0,0 +1,109 @@ +using System.Collections.Generic; +using System.Linq; +using editor.LuaEditor.Graph; + +namespace editor.LuaEditor.Layout; + +public static class InlineRules { + public static GraphNode? HostOf(GraphNode node) { + if (node is FunctionEntry { Owner: FunctionDecl declaration }) return declaration; + if (node is MemberGet enumMember && Sole(enumMember.Result) is { } enumPin && EnumValueOf(enumPin) is not null) return enumPin.Owner; + if (node is CallNode call && Sole(call.Result) is { } used) { + if (used.Owner is CallStatement statement && statement.Call == used) return statement; + if (used.Owner is LocalDecl { Values: [var initializer] } local && initializer == used && + call.Style == CallStyle.Function && (NodeShape.BindingOf(call.Target.Source)?.Declarer is FunctionDecl { IsLocal: true } || call.Target.Source?.Owner is MemberGet)) return local; + } + if (IsStaticName(node) && Sole(((ExprNode)node).Result) is { } pin) { + if (pin.Owner is MemberGet member && member.Object == pin) return member; + if (pin.Owner is CallNode caller && caller.Target == pin && caller.Style == CallStyle.Function) return caller; + } + return null; + } + + public static string? EnumValueOf(InputPin pin) { + if (pin.Source?.Owner is MemberGet member && member.Object.Source?.Owner is GlobalGet table && Sole(member.Result) == pin + && pin.Owner.Graph.Universe.Enums.Any(e => e.TableName == table.Name)) return member.Name; + return null; + } + + public static string? InlineValueOf(InputPin pin) => EnumValueOf(pin); + + private static InputPin? Sole(OutputPin output) + => output.Consumers.Count == 1 ? output.Consumers[0] : null; + + private static bool IsStaticName(GraphNode node) => + node is GlobalGet || node is MemberGet { Object.Source.Owner: { } inner } member && IsStaticName(inner) && Sole(((ExprNode)inner).Result) == member.Object; + + public static bool IsMerged(GraphNode node) => HostOf(node) is not null; + + public static bool IsMergedName(GraphNode node) => node is not FunctionEntry && IsMerged(node); + + public static bool IsGetterNode(GraphNode node) => !IsMerged(node) && (node is VariableGet || node is MemberGet); + + public static bool IsImplicitObject(InputPin pin) { + if (pin.Source?.Binding is not { } binding) return false; + var inObjectPosition = pin.Owner switch { + CallNode c => c.Style == CallStyle.Method && c.Target == pin, + AssignStatement a => a.Targets.Any(t => t.Object == pin), + _ => false + }; + return inObjectPosition && (binding.Kind == BindingKind.Self || IsScriptTable(binding)); + } + + private static bool IsScriptTable(Binding binding) { + if (binding.Declarer is not LocalDecl declaration || declaration.Parent != declaration.Graph.Module) return false; + var last = declaration.Graph.Module.Statements.LastOrDefault(s => s is not (CommentStatement or CastStatement)); + return last is ReturnStatement { Values.Count: 1 } ret && ret.Values[0].Source?.Binding == binding; + } + + public static string? ImplicitObjectName(InputPin pin) => IsImplicitObject(pin) ? pin.Source!.Binding!.Name : null; + + public static GraphNode Drawn(GraphNode node) { + var current = node; + for (var guard = 0; guard < 64 && HostOf(current) is { } host; guard++) current = host; + return current; + } + + public static IReadOnlyList VisibleInputs(GraphNode node) { + switch (node) { + case Statement when NodeShape.CallOf(node) is { } call && IsMerged(call): + return VisibleInputs(call); + case CallNode call: + return call.Inputs.Where(p => !(p == call.Target && (IsImplicitObject(p) || p.Source is { Binding.Kind: BindingKind.LocalFunction } || p.Source?.Owner is { } target && IsMergedName(target)))).ToList(); + case MemberGet member when IsImplicitObject(member.Object) || member.Object.Source?.Owner is { } inner && IsMergedName(inner): + return []; + case TableNode table: + return table.Inputs.Where(p => !table.Fields.Any(f => f.Key == p && p.Source is null)).ToList(); + case AssignStatement assign when assign.Targets.Any(t => t.Object is { } o && IsImplicitObject(o)): + return assign.Inputs.Where(p => !IsImplicitObject(p)).ToList(); + default: + return node.Inputs; + } + } + + public static int RowOf(InputPin pin) { + var host = Drawn(pin.Owner); + var visible = VisibleInputs(host); + for (var i = 0; i < visible.Count; i++) + if (visible[i] == pin) return i; + return -1; + } + + public static string? Title(GraphNode node) { + switch (node) { + case Statement when NodeShape.CallOf(node) is { } call && IsMerged(call): + return Title(call); + case CallNode call: + if (call.Style == CallStyle.Method) return (ImplicitObjectName(call.Target) ?? "") + ":" + call.Method; + if (NodeShape.BindingOf(call.Target.Source) is { Kind: BindingKind.LocalFunction } local) return local.Name; + if (call.Target.Source?.Owner is MemberGet memberTarget) return Title(memberTarget); + return call.Target.Source?.Owner is { } target && IsMergedName(target) ? Title(target) : call.Method ?? "call"; + case GlobalGet global: + return global.Name; + case MemberGet member: + if (ImplicitObjectName(member.Object) is { } owner) return owner + "." + member.Name; + return member.Object.Source?.Owner is { } inner && IsMergedName(inner) ? Title(inner) + "." + member.Name : member.Name; + } + return null; + } +} diff --git a/editor/LuaEditor/Layout/LayoutEngine.cs b/editor/LuaEditor/Layout/LayoutEngine.cs new file mode 100644 index 000000000..b93b83378 --- /dev/null +++ b/editor/LuaEditor/Layout/LayoutEngine.cs @@ -0,0 +1,246 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using editor.LuaEditor.Graph; + +namespace editor.LuaEditor.Layout; + +public static class LayoutEngine { + public static GraphLayout Create(LuaGraph graph, INodeMeasure? measure = null) { + var layout = new GraphLayout(graph, measure ?? new DefaultMeasure()); + PlaceUnplaced(layout); + PackRegions(layout); + return layout; + } + + public static void PlaceUnplaced(GraphLayout layout) { + var auto = new AutoLayout(layout.Measure, layout.Keys); + foreach (var region in layout.Keys.Regions) { + var nodes = layout.NodesOf(region); + if (nodes.All(n => layout.IsPlaced(n) || InlineRules.IsMerged(n))) continue; + var ideal = auto.Region(region); + if (!nodes.Any(n => layout.IsPlaced(n) && !InlineRules.IsMerged(n))) { + foreach (var (node, p) in ideal) layout.Local[node] = p; + continue; + } + + var anchor = nodes.First(n => layout.IsPlaced(n) && !InlineRules.IsMerged(n)); + var shift = ideal.TryGetValue(anchor, out var idealAnchor) ? layout.Local[anchor] - idealAnchor : default; + new Filler(layout, region, ideal, shift).Run(); + } + FollowHosts(layout); + } + + public static void FollowHosts(GraphLayout layout) { + foreach (var (node, _) in layout.Keys.Ordered) { + if (!InlineRules.IsMerged(node)) continue; + if (layout.Local.TryGetValue(InlineRules.Drawn(node), out var host)) layout.Local[node] = host; + } + } + + public static bool Separate(GraphLayout layout, IEnumerable placed, bool includeInputs = true) { + var group = new HashSet(); + foreach (var node in placed.Select(InlineRules.Drawn)) { + if (!layout.IsPlaced(node)) continue; + group.Add(node); + if (includeInputs && layout.Keys.KeyOf(node) is { } key && node is Statement) + foreach (var (other, otherKey) in layout.Keys.Ordered) + if (otherKey.StartsWith(key + "#", StringComparison.Ordinal) && !InlineRules.IsMerged(other) && layout.IsPlaced(other)) group.Add(other); + } + if (group.Count == 0) return false; + // a frame must not collide with its own contents + var others = layout.Local.Keys.Where(n => !group.Contains(n) && !InlineRules.IsMerged(n) && !layout.IsHidden(n) && + (layout.Loose.Contains(n) || layout.Keys.KeyOf(n) is not null) && + !group.Any(g => layout.IsInsideFrameOf(g, n) || layout.IsInsideFrameOf(n, g) || + NodeShape.ExpansionOf(n) is not null && Contains(layout.Bounds(n), layout.Bounds(g)))).ToList(); + var waiting = layout.Loose.OfType().Where(n => n.IsFloating && !group.Contains(n) && + group.Any(g => layout.IsInsideFrameOf(n, g))).ToList(); + var moved = false; + for (var guard = 0; guard < 400; guard++) { + var rects = group.Select(layout.Bounds).Select(r => r.Inflate(4)).ToList(); + var hit = others.Select(layout.Bounds).Where(b => rects.Any(r => r.Intersects(b))).Select(b => (Rect?)b).FirstOrDefault(); + if (hit is null) break; + var dy = hit.Value.Bottom + 8 - rects.Min(r => r.Y) - 4; + foreach (var node in group) layout.Local[node] += new Vec(0, dy); + foreach (var node in waiting) layout.Local[node] += new Vec(0, dy); + moved = true; + } + FollowHosts(layout); + return moved; + } + + private static bool Contains(Rect outer, Rect inner) => inner.X >= outer.X && inner.X <= outer.Right && inner.Y >= outer.Y + DefaultMeasure.HeaderHeight && inner.Y <= outer.Bottom; + + public static void PlaceNewRegions(GraphLayout layout) { + var fresh = layout.Keys.Regions.Where(r => !layout.Embedded.ContainsKey(r.Body) && !layout.Origins.ContainsKey(r.Body) && layout.RegionExtent(r) is not null).ToList(); + if (fresh.Count == 0) return; + var others = layout.Keys.Regions.Where(r => !fresh.Contains(r) && !layout.Embedded.ContainsKey(r.Body) && layout.RegionExtent(r) is not null).Select(r => layout.RegionExtent(r)!.Value).ToList(); + var x = others.Count == 0 ? 0 : others.Min(r => r.X); + var y = others.Count == 0 ? 0 : others.Max(r => r.Bottom) + 80; + foreach (var region in fresh) { + layout.PlaceRegion(region, new Vec(x, y)); + y = layout.RegionExtent(region)!.Value.Bottom + 80; + } + } + + public static void PackRegions(GraphLayout layout) { + var regions = layout.Keys.Regions.Where(r => !layout.Embedded.ContainsKey(r.Body) && layout.RegionExtent(r) is not null).ToList(); + var free = regions.Where(r => !layout.PinnedRegions.Contains(r.Body)).ToList(); + var module = free.Where(r => r.IsModule); + var rest = free.Where(r => !r.IsModule).Select((r, i) => (r, i)) + .OrderBy(t => RegionPacker.LifecycleRank(t.r.Header is FunctionDecl d ? d.Name : "")).ThenBy(t => t.i).Select(t => t.r); + var ordered = module.Concat(rest).ToList(); + + var obstacles = regions.Where(r => layout.PinnedRegions.Contains(r.Body)).Select(r => layout.RegionExtent(r)!.Value).ToList(); + var sizes = ordered.Select(r => { + var b = layout.RegionExtent(r)!.Value; + return layout.CollapsedRegions.Contains(r.Body) ? new Size(Math.Min(b.W, 260), DefaultMeasure.HeaderHeight + 8) : new Size(b.W, b.H); + }).ToList(); + var positions = RegionPacker.Pack(sizes, obstacles); + for (var i = 0; i < ordered.Count; i++) layout.PlaceRegion(ordered[i], positions[i]); + } + + private sealed class Filler { + private readonly GraphLayout m_layout; + private readonly RegionInfo m_region; + private readonly Dictionary m_ideal; + private readonly Vec m_shift; + private readonly GraphKeys m_keys; + + public Filler(GraphLayout layout, RegionInfo region, Dictionary ideal, Vec shift) { + m_layout = layout; + m_region = region; + m_ideal = ideal; + m_shift = shift; + m_keys = layout.Keys; + } + + private bool IsPlaced(GraphNode node) => m_layout.Local.ContainsKey(node); + + private Vec At(GraphNode node) => m_layout.Local[node]; + + private Size SizeOf(GraphNode node) => m_layout.Measure.Measure(node); + + private Rect Box(GraphNode node) { + var p = At(node); + var s = SizeOf(node); + return new Rect(p.X, p.Y, s.W, s.H); + } + + public void Run() { + foreach (var node in new[] { m_region.Header, m_region.Entry }) { + if (node is null || IsPlaced(node) || InlineRules.IsMerged(node) || m_keys.RegionOf(node) != m_region) continue; + PlaceGroup(node, [], m_ideal.GetValueOrDefault(node) + m_shift); + } + Block(m_region.Body, StartOf(m_region.Body)); + } + + private Vec StartOf(Block block) { + var first = block.Statements.FirstOrDefault(IsPlaced); + if (first is not null) return At(first); + if (block.Owner is FunctionEntry entry && InlineRules.Drawn(entry) is var header && IsPlaced(header)) return At(header) + new Vec(SizeOf(header).W + AutoLayout.StepGap, 0); + if (block.Owner is { } owner && IsPlaced(owner)) return At(owner) + new Vec(SizeOf(owner).W + AutoLayout.StepGap, 0); + var min = m_ideal.Count == 0 ? default : new Vec(m_ideal.Values.Min(v => v.X), m_ideal.Values.Min(v => v.Y)); + return min + m_shift; + } + + private void Block(Block block, Vec start) { + var cursor = start; + foreach (var statement in block.Statements) { + if (statement is FunctionDecl) continue; + if (IsPlaced(statement)) { + FillData(statement); + } else { + var data = DataOf(statement); + var dataWidth = data.Count == 0 ? 0 : m_ideal[statement].X - data.Min(n => m_ideal[n].X); + var target = new Vec(cursor.X + dataWidth, cursor.Y); + var below = PlacedBelow(statement); + if (below.Count > 0) target = new Vec(below.Min(n => At(n).X) - SizeOf(statement).W - AutoLayout.StepGap, below.Min(n => At(n).Y)); + PlaceGroup(statement, data, target); + } + + var position = At(statement); + var childY = position.Y; + var childX = position.X + SizeOf(statement).W + AutoLayout.StepGap; + foreach (var child in statement.ChildBlocks) { + Block(child, new Vec(childX, childY)); + var bottom = BottomOf(child); + childY = Math.Max(childY, double.IsNegativeInfinity(bottom) ? childY : bottom) + AutoLayout.RowGap; + } + cursor = new Vec(RightOf(statement) + AutoLayout.StepGap, position.Y); + } + } + + private List PlacedBelow(Statement statement) { + var list = new List(); + foreach (var child in statement.ChildBlocks) + foreach (var inner in child.Statements) { + if (IsPlaced(inner)) list.Add(inner); + else list.AddRange(PlacedBelow(inner)); + } + return list; + } + + private List DataOf(Statement statement) { + var list = new List(); + var seen = new HashSet(); + void Visit(InputPin pin) { + if (pin.Source?.Owner is not ExprNode e || !seen.Add(e) || m_keys.RegionOf(e) != m_region) return; + if (!InlineRules.IsMerged(e) && !IsPlaced(e)) list.Add(e); + if (e is FunctionNode) return; + foreach (var input in e.Inputs) Visit(input); + } + foreach (var pin in statement.Inputs) Visit(pin); + return list; + } + + private void FillData(Statement statement) { + var missing = DataOf(statement); + if (missing.Count == 0) return; + var offset = At(statement) - (m_ideal.GetValueOrDefault(statement) + m_shift); + foreach (var node in missing) PlaceGroup(node, [], m_ideal.GetValueOrDefault(node) + m_shift + offset); + } + + private void PlaceGroup(GraphNode main, List others, Vec target) { + var mainIdeal = m_ideal.GetValueOrDefault(main); + var positions = new List<(GraphNode Node, Vec Pos)> { (main, target) }; + foreach (var node in others) positions.Add((node, target + (m_ideal[node] - mainIdeal))); + var members = positions.Select(p => p.Node).ToHashSet(); + + for (var guard = 0; guard < 10_000; guard++) { + var group = positions.Select(p => new Rect(p.Pos.X, p.Pos.Y, SizeOf(p.Node).W, SizeOf(p.Node).H).Inflate(6)).ToList(); + var hit = Collider(group, members); + if (hit is null) break; + var dy = hit.Value.Bottom - group.Min(g => g.Y) + 4; + positions = positions.Select(p => (p.Node, p.Pos + new Vec(0, dy))).ToList(); + } + foreach (var (node, pos) in positions) m_layout.Local[node] = pos; + } + + private Rect? Collider(List group, HashSet except) { + foreach (var node in m_layout.NodesOf(m_region)) { + if (except.Contains(node) || !IsPlaced(node) || InlineRules.IsMerged(node)) continue; + var box = Box(node); + if (group.Any(g => g.Intersects(box))) return box; + } + return null; + } + + private double RightOf(Statement statement) { + var right = Box(statement).Right; + foreach (var child in statement.ChildBlocks) + foreach (var inner in child.Statements.Where(IsPlaced)) + right = Math.Max(right, RightOf(inner)); + return right; + } + + private double BottomOf(Block block) { + var bottom = double.NegativeInfinity; + foreach (var statement in block.Statements.Where(IsPlaced)) { + bottom = Math.Max(bottom, Box(statement).Bottom); + foreach (var child in statement.ChildBlocks) bottom = Math.Max(bottom, BottomOf(child)); + } + return bottom; + } + } +} diff --git a/editor/LuaEditor/Layout/LayoutMeta.cs b/editor/LuaEditor/Layout/LayoutMeta.cs new file mode 100644 index 000000000..33b501a07 --- /dev/null +++ b/editor/LuaEditor/Layout/LayoutMeta.cs @@ -0,0 +1,259 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using Tomlyn; +using Tomlyn.Model; + +namespace editor.LuaEditor.Layout; + +public sealed record NodeMeta(string Key, string Fingerprint, double X, double Y, bool Pinned, bool Collapsed); + +public sealed record RegionMeta(string Function, double X, double Y, bool Pinned, bool Collapsed, Vec? FrameCorner = null); + +public sealed record GroupMeta(string Title, string Color, string Region, double X, double Y, double W, double H, IReadOnlyList Members); + +public sealed record SequenceMeta(string Key, IReadOnlyList Outputs, IReadOnlyList Counts); + +public sealed record CallableWireMeta(string Target, int Input, string Host); + +public sealed record SharedWireMeta(string Source, int Output, string Target, int Input); + +public sealed record RerouteMeta(string Key, int Row, IReadOnlyList Points); + +public sealed record LooseMeta(string Expression, double X, double Y, string Region = "", string Flavor = "", bool Expanded = false); + +public sealed record FlavorMeta(string Key, string Flavor); + +public sealed class GraphMeta { + public const int CurrentVersion = 1; + + public List Nodes { get; } = []; + public List Regions { get; } = []; + public List Groups { get; } = []; + public List Sequences { get; } = []; + public List Reroutes { get; } = []; + public List CallableWires { get; } = []; + public List SharedWires { get; } = []; + public List Loose { get; } = []; + + public List Floating { get; } = []; + + public List Flavors { get; } = []; + + public List Expanded { get; } = []; + + public static GraphMeta? Read(string metaText) { + try { + var root = TomlSerializer.Deserialize(metaText); + if (root is null || !root.TryGetValue("graph", out var g) || g is not TomlTable graph) return null; + if (Int(graph, "version", 0) != CurrentVersion) return null; + + var meta = new GraphMeta(); + foreach (var t in Tables(graph, "nodes")) { + var pos = Numbers(t, "pos"); + meta.Nodes.Add(new NodeMeta(Str(t, "key"), Str(t, "fp"), pos[0], pos[1], Bool(t, "pinned"), Bool(t, "collapsed"))); + } + foreach (var t in Tables(graph, "regions")) { + var pos = Numbers(t, "pos"); + var corner = t.ContainsKey("frame_corner") ? Numbers(t, "frame_corner") : null; + meta.Regions.Add(new RegionMeta(Str(t, "function"), pos[0], pos[1], Bool(t, "pinned"), Bool(t, "collapsed"), + corner is null ? null : new Vec(corner[0], corner[1]))); + } + foreach (var t in Tables(graph, "groups")) { + var rect = Numbers(t, "rect", 4); + meta.Groups.Add(new GroupMeta(Str(t, "title"), Str(t, "color"), Str(t, "region"), rect[0], rect[1], rect[2], rect[3], Strings(t, "members"))); + } + foreach (var t in Tables(graph, "sequences")) + meta.Sequences.Add(new SequenceMeta(Str(t, "key"), Strings(t, "outputs"), Numbers(t, "counts", -1).Select(d => (int)d).ToList())); + foreach (var t in Tables(graph, "reroutes")) + meta.Reroutes.Add(new RerouteMeta(Str(t, "key"), Int(t, "row", 0), Numbers(t, "points", -1))); + foreach (var t in Tables(graph, "floating")) + meta.Floating.Add(new LooseMeta(Str(t, "expr"), Numbers(t, "pos")[0], Numbers(t, "pos")[1], Str(t, "region"), Expanded: Bool(t, "expanded"))); + foreach (var t in Tables(graph, "callable_wires")) + meta.CallableWires.Add(new CallableWireMeta(Str(t, "target"), Int(t, "input", -1), Str(t, "host"))); + foreach (var t in Tables(graph, "shared_wires")) + meta.SharedWires.Add(new SharedWireMeta(Str(t, "source"), Int(t, "output", -1), Str(t, "target"), Int(t, "input", -1))); + meta.Expanded.AddRange(Strings(graph, "expanded")); + foreach (var t in Tables(graph, "flavors")) + meta.Flavors.Add(new FlavorMeta(Str(t, "key"), Str(t, "kind"))); + foreach (var t in Tables(graph, "loose")) + meta.Loose.Add(new LooseMeta(Str(t, "expr"), Numbers(t, "pos")[0], Numbers(t, "pos")[1], "", Str(t, "kind"))); + return meta; + } catch (Exception e) when (e is TomlException or InvalidCastException or KeyNotFoundException or ArgumentException or IndexOutOfRangeException or FormatException) { + return null; + } + } + + public string? Write(string metaText) { + TomlTable root; + try { + root = string.IsNullOrWhiteSpace(metaText) ? new TomlTable() : TomlSerializer.Deserialize(metaText) ?? new TomlTable(); + } catch (TomlException) { + return null; + } + + var graph = new TomlTable { ["version"] = (long)CurrentVersion }; + var nodes = new TomlTableArray(); + foreach (var n in Nodes) { + var t = new TomlTable { ["key"] = n.Key }; + if (n.Fingerprint.Length > 0) t["fp"] = n.Fingerprint; + t["pos"] = Pair(n.X, n.Y); + if (n.Pinned) t["pinned"] = true; + if (n.Collapsed) t["collapsed"] = true; + nodes.Add(t); + } + graph["nodes"] = nodes; + + var regions = new TomlTableArray(); + foreach (var r in Regions) { + var t = new TomlTable { ["function"] = r.Function, ["pos"] = Pair(r.X, r.Y) }; + if (r.Pinned) t["pinned"] = true; + if (r.Collapsed) t["collapsed"] = true; + if (r.FrameCorner is { } corner) t["frame_corner"] = Pair(corner.X, corner.Y); + regions.Add(t); + } + graph["regions"] = regions; + + var groups = new TomlTableArray(); + foreach (var gr in Groups) { + var members = new TomlArray(); + foreach (var m in gr.Members) members.Add(m); + var rect = new TomlArray { Round(gr.X), Round(gr.Y), Round(gr.W), Round(gr.H) }; + groups.Add(new TomlTable { ["title"] = gr.Title, ["color"] = gr.Color, ["region"] = gr.Region, ["rect"] = rect, ["members"] = members }); + } + graph["groups"] = groups; + + var sequences = new TomlTableArray(); + foreach (var s in Sequences) { + var outputs = new TomlArray(); + foreach (var o in s.Outputs) outputs.Add(o); + var counts = new TomlArray(); + foreach (var c in s.Counts) counts.Add((long)c); + sequences.Add(new TomlTable { ["key"] = s.Key, ["outputs"] = outputs, ["counts"] = counts }); + } + graph["sequences"] = sequences; + + var reroutes = new TomlTableArray(); + foreach (var r in Reroutes) { + var points = new TomlArray(); + foreach (var p in r.Points) points.Add(Round(p)); + reroutes.Add(new TomlTable { ["key"] = r.Key, ["row"] = (long)r.Row, ["points"] = points }); + } + graph["reroutes"] = reroutes; + if (CallableWires.Count > 0) { + var wires = new TomlTableArray(); + foreach (var wire in CallableWires) + wires.Add(new TomlTable { ["target"] = wire.Target, ["input"] = (long)wire.Input, ["host"] = wire.Host }); + graph["callable_wires"] = wires; + } + if (SharedWires.Count > 0) { + var wires = new TomlTableArray(); + foreach (var wire in SharedWires) + wires.Add(new TomlTable { + ["source"] = wire.Source, ["output"] = (long)wire.Output, + ["target"] = wire.Target, ["input"] = (long)wire.Input + }); + graph["shared_wires"] = wires; + } + + var loose = new TomlTableArray(); + foreach (var l in Loose) { + var lt = new TomlTable { ["expr"] = l.Expression, ["pos"] = Pair(l.X, l.Y) }; + if (l.Flavor.Length > 0) lt["kind"] = l.Flavor; + loose.Add(lt); + } + + var flavors = new TomlTableArray(); + foreach (var f in Flavors) flavors.Add(new TomlTable { ["key"] = f.Key, ["kind"] = f.Flavor }); + graph["flavors"] = flavors; + + var expanded = new TomlArray(); + foreach (var key in Expanded) expanded.Add(key); + graph["expanded"] = expanded; + graph["loose"] = loose; + + var floating = new TomlTableArray(); + foreach (var f in Floating) { + var t = new TomlTable { ["expr"] = f.Expression, ["pos"] = Pair(f.X, f.Y) }; + if (f.Region.Length > 0) t["region"] = f.Region; + if (f.Expanded) t["expanded"] = true; + floating.Add(t); + } + graph["floating"] = floating; + + var section = TomlSerializer.Serialize(new TomlTable { ["graph"] = graph }); + if (Splice(metaText, section) is { } spliced) return spliced; + root["graph"] = graph; + return TomlSerializer.Serialize(root); + } + + private static readonly System.Text.RegularExpressions.Regex s_header = new(@"^\s*\[\[?\s*([A-Za-z0-9_\-\.""]+)\s*\]\]?\s*(#.*)?$", System.Text.RegularExpressions.RegexOptions.Compiled); + + private static string? Splice(string original, string section) { + var eol = original.Contains("\r\n") ? "\r\n" : "\n"; + var lines = original.Split('\n').Select(l => l.TrimEnd('\r')).ToList(); + if (lines.Count > 0 && lines[^1].Length == 0) lines.RemoveAt(lines.Count - 1); + var kept = new List(); + var insertAt = -1; + var inGraph = false; + foreach (var line in lines) { + var header = s_header.Match(line); + if (header.Success) { + var name = header.Groups[1].Value; + inGraph = name == "graph" || name.StartsWith("graph.", StringComparison.Ordinal); + if (inGraph && insertAt < 0) insertAt = kept.Count; + } + if (!inGraph) kept.Add(line); + } + if (insertAt < 0) { + if (kept.Count > 0 && kept[^1].Trim().Length > 0) kept.Add(""); + insertAt = kept.Count; + } + var block = section.Replace("\r\n", "\n").TrimEnd('\n').Split('\n').ToList(); + block.Add(""); + kept.InsertRange(insertAt, block); + while (kept.Count > 0 && kept[^1].Length == 0) kept.RemoveAt(kept.Count - 1); + var result = string.Join(eol, kept) + eol; + try { + var table = TomlSerializer.Deserialize(result); + return table is not null && table.ContainsKey("graph") ? result : null; + } catch (TomlException) { + return null; + } + } + + private static double Round(double d) => Math.Round(d, 1); + + private static TomlArray Pair(double x, double y) => new() { Round(x), Round(y) }; + + private static IEnumerable Tables(TomlTable table, string key) { + if (!table.TryGetValue(key, out var v)) return []; + if (v is TomlTableArray tables) return tables; + if (v is TomlArray array) return array.OfType(); + return []; + } + + private static string Str(TomlTable t, string key) => t.TryGetValue(key, out var v) && v is string s ? s : ""; + + private static bool Bool(TomlTable t, string key) => t.TryGetValue(key, out var v) && v is true; + + private static int Int(TomlTable t, string key, int fallback) => t.TryGetValue(key, out var v) && v is long l ? (int)l : fallback; + + private static List Numbers(TomlTable t, string key, int expected = 2) { + var list = new List(); + if (t.TryGetValue(key, out var v) && v is TomlArray array) + foreach (var item in array) + list.Add(item switch { long l => l, double d => d, _ => throw new FormatException(key) }); + if (expected >= 0 && list.Count != expected) throw new FormatException(key); + return list; + } + + private static List Strings(TomlTable t, string key) { + var list = new List(); + if (t.TryGetValue(key, out var v) && v is TomlArray array) + foreach (var item in array) + if (item is string s) list.Add(s); + return list; + } +} diff --git a/editor/LuaEditor/Layout/LayoutPersistence.cs b/editor/LuaEditor/Layout/LayoutPersistence.cs new file mode 100644 index 000000000..ab5a5d1fb --- /dev/null +++ b/editor/LuaEditor/Layout/LayoutPersistence.cs @@ -0,0 +1,490 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.RegularExpressions; +using editor.LuaEditor.Graph; +using editor.LuaEditor.Types; + +namespace editor.LuaEditor.Layout; + +public static class LayoutPersistence { + public static GraphMeta Capture(GraphLayout layout) { + var keys = layout.Keys; + var meta = new GraphMeta(); + + foreach (var (node, key) in keys.Ordered) { + if (!layout.Local.TryGetValue(node, out var local) || InlineRules.IsMerged(node)) continue; + var pinned = layout.PinnedNodes.Contains(node); + var collapsed = layout.CollapsedNodes.Contains(node); + var hash = key.IndexOf('#'); + if (hash >= 0) { + if (keys.NodeOf(key[..hash]) is { } owner && layout.Local.TryGetValue(owner, out var ownerLocal)) + meta.Nodes.Add(new NodeMeta(key, "", local.X - ownerLocal.X, local.Y - ownerLocal.Y, pinned, collapsed)); + continue; + } + meta.Nodes.Add(new NodeMeta(key, node is Statement s and not SequenceStatement ? GraphKeys.Fingerprint(s) : "", local.X, local.Y, pinned, collapsed)); + } + + foreach (var region in keys.Regions) { + if (layout.RegionBounds(region) is null) continue; + var origin = layout.Origins.GetValueOrDefault(region.Body); + meta.Regions.Add(new RegionMeta(region.Key, origin.X, origin.Y, layout.PinnedRegions.Contains(region.Body), layout.CollapsedRegions.Contains(region.Body), + layout.FrameCorners.TryGetValue(region.Body, out var corner) ? corner : null)); + } + + foreach (var group in layout.Groups) { + var members = group.Members.Select(keys.KeyOf).OfType().ToList(); + if (members.Count == 0) continue; + var region = keys.RegionOf(group.Members.First(m => keys.KeyOf(m) is not null)); + var origin = region is null ? default : layout.OriginOf(region); + meta.Groups.Add(new GroupMeta(group.Title, group.Color, region?.Key ?? "", group.Rect.X - origin.X, group.Rect.Y - origin.Y, group.Rect.W, group.Rect.H, members)); + } + + foreach (var sequence in layout.Graph.AllStatements().OfType()) { + var key = keys.KeyOf(sequence); + if (key is null) continue; + var outputs = new List(); + var counts = new List(); + foreach (var branch in sequence.Branches) { + var flat = GraphKeys.Flatten(branch).ToList(); + outputs.Add(flat.Count == 0 ? "" : keys.KeyOf(flat[0]) ?? ""); + counts.Add(flat.Count); + } + meta.Sequences.Add(new SequenceMeta(key, outputs, counts)); + } + foreach (var (pin, points) in layout.Reroutes) { + var drawn = InlineRules.Drawn(pin.Owner); + if (keys.KeyOf(drawn) is not { } key || NodeShape.SlotOf(pin) is not { } slot || points.Count == 0) continue; + meta.Reroutes.Add(new RerouteMeta(key, slot.Row, points.SelectMany(p => new[] { p.X, p.Y }).ToList())); + } + foreach (var (pin, offset) in layout.ProxyOffsets) { + var drawn = InlineRules.Drawn(pin.Owner); + if (keys.KeyOf(drawn) is not { } key || NodeShape.SlotOf(pin) is not { } slot) continue; + meta.Reroutes.Add(new RerouteMeta(key, ProxyRow + slot.Row, [offset.X, offset.Y])); + } + foreach (var (statement, points) in layout.ExecReroutes) { + if (keys.KeyOf(statement) is not { } key || points.Count == 0) continue; + meta.Reroutes.Add(new RerouteMeta(key, ExecRow, points.SelectMany(q => new[] { q.X, q.Y }).ToList())); + } + foreach (var (pin, host) in layout.CallableWireHosts) + if (keys.KeyOf(pin.Owner) is { } target && keys.KeyOf(host) is { } hostKey && layout.CallableSlot(pin) is not null) + meta.CallableWires.Add(new CallableWireMeta(target, pin.Owner.Inputs.ToList().IndexOf(pin), hostKey)); + foreach (var (node, key) in keys.Ordered) { + if (node is not ExprNode) continue; + foreach (var output in node.Outputs.Where(o => o.Consumers.Count > 1)) + foreach (var pin in output.Consumers) { + if (keys.KeyOf(pin.Owner) is not { } target || keys.RegionOf(node) != keys.RegionOf(pin.Owner)) continue; + var input = pin.Owner.Inputs.ToList().IndexOf(pin); + // the first occurrence already owns the expression key + var separator = pin.Owner is Statement ? "#" : "."; + if (key != target + separator + input) + meta.SharedWires.Add(new SharedWireMeta(key, output.Index, target, input)); + } + } + foreach (var host in layout.Embedded.Values.Distinct()) + if (keys.KeyOf(host) is { } hostKey) meta.Expanded.Add(hostKey); + foreach (var table in layout.Graph.Nodes.OfType()) + if (table.DeclaredFlavor is { } chosen && keys.KeyOf(table) is { } tableKey) meta.Flavors.Add(new FlavorMeta(tableKey, FlavorText(table))); + foreach (var statement in layout.Loose.OfType().Where(x => x.IsFloating && layout.Local.ContainsKey(x))) { + var text = Fragments.Copy([statement]).Trim(); + var owner = statement.Parent?.Owner is FunctionEntry { Owner: FunctionDecl declaration } ? declaration.Name : ""; + if (text.Length > 0) meta.Floating.Add(new LooseMeta(text, layout.Local[statement].X, layout.Local[statement].Y, owner, Expanded: statement.IsExpanded)); + } + foreach (var node in layout.Loose.OfType()) { + if (node.Outputs.Any(o => o.Consumers.Count > 0) || !layout.Local.TryGetValue(node, out var at)) continue; + if (Fragments.CopyExpression(node) is { Length: > 0 } text) meta.Loose.Add(new LooseMeta(text, at.X, at.Y, "", node is TableNode { DeclaredFlavor: not null } looseTable ? FlavorText(looseTable) : "")); + } + return meta; + } + + private const int ExecRow = -1; + + private const int ProxyRow = 1000; + + public static GraphLayout Restore(LuaGraph graph, GraphMeta? meta, INodeMeasure? measure = null) { + var layout = new GraphLayout(graph, measure ?? new DefaultMeasure()); + var matcher = meta is null ? null : new Matcher(layout, meta); + matcher?.ApplyPositions(); + matcher?.RestoreSharedWires(); + matcher?.RestoreExpanded(); + matcher?.RebuildSequences(); + LayoutEngine.PlaceUnplaced(layout); + LayoutEngine.PackRegions(layout); + matcher?.RestoreGroups(); + matcher?.RestoreReroutes(); + matcher?.RestoreFlavors(); + if (meta is not null) { + RestoreLoose(layout, meta); + foreach (var wire in meta.CallableWires) { + if (layout.Keys.NodeOf(wire.Target) is not { } target || layout.Keys.NodeOf(wire.Host) is not { } host || + wire.Input < 0 || wire.Input >= target.Inputs.Count) continue; + var pin = target.Inputs[wire.Input]; + layout.CallableWireHosts[pin] = host; + if (layout.CallableSlot(pin) is null) layout.CallableWireHosts.Remove(pin); + } + } + return layout; + } + + private static void RestoreLoose(GraphLayout layout, GraphMeta meta) { + var added = new List(); + var expanded = new List(); + foreach (var saved in meta.Floating) { + var module = saved.Region.Length > 0 && layout.Graph.Module.Statements.OfType().FirstOrDefault(d => d.Name == saved.Region) is { } function ? function.Entry.Body : layout.Graph.Module; + var count = module.Statements.Count; + var index = count > 0 && module.Statements[^1] is ReturnStatement ? count - 1 : count; + var result = Fragments.Paste(layout.Graph, saved.Expression + "\n", module, index); + if (result.Errors.Count > 0) continue; + foreach (var statement in result.Statements) { + statement.IsFloating = true; + layout.Loose.Add(statement); + layout.Local[statement] = new Vec(saved.X, saved.Y); + added.Add(statement); + if (saved.Expanded) expanded.Add(statement); + } + } + if (added.Count > 0) layout.Refresh(); + + foreach (var saved in meta.Loose) { + var nodes = Fragments.BuildLoose(layout.Graph, saved.Expression); + if (nodes.Count == 0) continue; + if (nodes[0] is TableNode madeAs) ApplyFlavor(madeAs, saved.Flavor); + var depth = new Dictionary { [nodes[0]] = 0 }; + var perColumn = new Dictionary(); + foreach (var node in nodes) { + if (!depth.TryGetValue(node, out var d)) continue; + foreach (var input in node.Inputs) + if (input.Source?.Owner is ExprNode child && nodes.Contains(child) && !depth.ContainsKey(child)) depth[child] = d + 1; + } + foreach (var node in nodes) { + var d = depth.GetValueOrDefault(node, 1); + var row = perColumn.GetValueOrDefault(d); + perColumn[d] = row + 1; + layout.Loose.Add(node); + layout.Local[node] = new Vec(saved.X - d * 260, saved.Y + row * 90); + added.Add(node); + } + } + if (added.Count == 0) return; + layout.Graph.Analyze(); + foreach (var host in expanded) { + if (NodeShape.LocalCalleeOf(host)?.Entry.Body is not { } body || + layout.HostBody(host) is not { } own || own == body || + layout.Embedded.ContainsKey(own) || layout.Embedded.ContainsKey(body) || + layout.Embedded.Values.Any(other => layout.HostBody(other) == body)) continue; + host.IsExpanded = true; + layout.Embedded[body] = host; + layout.CollapsedRegions.Remove(body); + } + layout.Refresh(); + LayoutEngine.Separate(layout, added); + } + + private static string FlavorText(TableNode table) => table.DeclaredFlavor + (table.DeclaredType is { } type ? "|" + TypeFormatter.Format(type) : ""); + + internal static void ApplyFlavor(TableNode table, string text) { + var parts = text.Split('|', 2); + if (Enum.TryParse(parts[0], out var flavor)) table.DeclaredFlavor = flavor; + if (parts.Length == 2) { + try { + table.DeclaredType = TypeExprParser.Parse(parts[1]); + } catch (TypeSyntaxException) { + } + } + } + + private sealed class Matcher { + + private static readonly Regex s_closureEntry = new(@"^(.*)(/fn\d+)$", RegexOptions.Compiled); + + private readonly GraphLayout m_layout; + private readonly GraphMeta m_meta; + private GraphKeys m_keys => m_layout.Keys; + private readonly Dictionary m_saved = []; + private readonly Dictionary> m_children = []; + private readonly Dictionary m_map = []; + private readonly Dictionary m_inverse = []; + private readonly Dictionary m_newToSaved = []; + + public Matcher(GraphLayout layout, GraphMeta meta) { + m_layout = layout; + m_meta = meta; + foreach (var n in meta.Nodes) { + m_saved[n.Key] = n; + if (n.Fingerprint.Length == 0 || n.Key.Contains('#') || n.Key.Contains('!') || n.Key.StartsWith('~')) continue; + var slash = n.Key.LastIndexOf('/'); + var parent = slash < 0 ? "" : n.Key[..slash]; + if (!m_children.TryGetValue(parent, out var list)) m_children[parent] = list = []; + list.Add(n); + } + AlignBlock(layout.Graph.Module, ""); + foreach (var (statement, saved) in m_map) + if (m_keys.KeyOf(statement) is { } newKey) m_newToSaved[newKey] = saved; + } + + private void AlignBlock(Block block, string parent) { + var saved = m_children.GetValueOrDefault(parent) ?? []; + var fresh = GraphKeys.Flatten(block).ToList(); + foreach (var (s, n) in AlignLists(saved.Select(x => x.Fingerprint).ToList(), fresh.Select(GraphKeys.Fingerprint).ToList())) + Matched(fresh[n], saved[s].Key); + } + + private void Matched(Statement statement, string savedKey) { + m_map[statement] = savedKey; + m_inverse[savedKey] = statement; + if (statement is FunctionDecl decl) AlignBlock(decl.Entry.Body, savedKey); + else + foreach (var child in statement.ChildBlocks) + AlignBlock(child, savedKey + "/" + GraphKeys.RoleOf(statement, child)); + + var key = m_keys.KeyOf(statement); + if (key is null) return; + foreach (var region in m_keys.Regions) + if (region.Header is FunctionNode && region.Key.StartsWith(key + "/fn", StringComparison.Ordinal) && region.Key.IndexOf("/fn", key.Length + 1, StringComparison.Ordinal) < 0) + AlignBlock(region.Body, savedKey + region.Key[key.Length..]); + } + + internal static List<(int Saved, int Fresh)> AlignLists(IReadOnlyList saved, IReadOnlyList fresh) { + var anchors = new List<(int, int)>(); + var prefix = 0; + while (prefix < saved.Count && prefix < fresh.Count && saved[prefix] == fresh[prefix]) { + anchors.Add((prefix, prefix)); + prefix++; + } + var endS = saved.Count; + var endF = fresh.Count; + var tail = new List<(int, int)>(); + while (endS > prefix && endF > prefix && saved[endS - 1] == fresh[endF - 1]) { + endS--; + endF--; + tail.Add((endS, endF)); + } + + var rows = endS - prefix; + var cols = endF - prefix; + if (rows > 0 && cols > 0 && (long)rows * cols <= 4_000_000) { + var table = new int[rows + 1, cols + 1]; + for (var i = rows - 1; i >= 0; i--) + for (var j = cols - 1; j >= 0; j--) + table[i, j] = saved[prefix + i] == fresh[prefix + j] ? table[i + 1, j + 1] + 1 : Math.Max(table[i + 1, j], table[i, j + 1]); + int a = 0, b = 0; + while (a < rows && b < cols) { + if (saved[prefix + a] == fresh[prefix + b]) { + anchors.Add((prefix + a, prefix + b)); + a++; + b++; + } else if (table[a + 1, b] >= table[a, b + 1]) { + a++; + } else { + b++; + } + } + } + tail.Reverse(); + anchors.AddRange(tail); + + var result = new List<(int, int)>(); + int prevS = -1, prevF = -1; + foreach (var (s, f) in anchors.Append((saved.Count, fresh.Count))) { + var gap = Math.Min(s - prevS - 1, f - prevF - 1); + for (var k = 1; k <= gap; k++) result.Add((prevS + k, prevF + k)); + if (s < saved.Count) result.Add((s, f)); + prevS = s; + prevF = f; + } + return result; + } + + private string? SavedKeyOf(string key) { + if (key.StartsWith('~')) return null; + string statement; + string suffix; + var hash = key.IndexOf('#'); + if (hash >= 0) { + statement = key[..hash]; + suffix = key[hash..]; + } else if (key.EndsWith("!entry", StringComparison.Ordinal)) { + var body = key[..^"!entry".Length]; + var closure = s_closureEntry.Match(body); + if (closure.Success) { + statement = closure.Groups[1].Value; + suffix = closure.Groups[2].Value + "!entry"; + } else { + statement = body; + suffix = "!entry"; + } + } else { + statement = key; + suffix = ""; + } + return m_newToSaved.TryGetValue(statement, out var saved) ? saved + suffix : null; + } + + public void ApplyPositions() { + var deferred = new List<(GraphNode Node, NodeMeta Meta, string OwnerKey)>(); + foreach (var (node, key) in m_keys.Ordered) { + var savedKey = SavedKeyOf(key); + if (savedKey is null || !m_saved.TryGetValue(savedKey, out var entry)) continue; + var hash = savedKey.IndexOf('#'); + if (hash >= 0) { + deferred.Add((node, entry, key[..key.IndexOf('#')])); + continue; + } + m_layout.Local[node] = new Vec(entry.X, entry.Y); + Flags(node, entry); + } + foreach (var (node, entry, ownerKey) in deferred) { + if (m_keys.NodeOf(ownerKey) is not { } owner || !m_layout.Local.TryGetValue(owner, out var ownerLocal)) continue; + m_layout.Local[node] = ownerLocal + new Vec(entry.X, entry.Y); + Flags(node, entry); + } + + foreach (var region in m_keys.Regions) { + var savedKey = region.IsModule ? GraphKeys.ModuleKey + : region.Header is FunctionDecl decl ? m_map.GetValueOrDefault(decl) + : ClosureRegionKey(region.Key); + if (savedKey is null) continue; + var saved = m_meta.Regions.FirstOrDefault(r => r.Function == savedKey); + if (saved is null) continue; + m_layout.Origins[region.Body] = new Vec(saved.X, saved.Y); + if (saved.FrameCorner is { } corner) m_layout.FrameCorners[region.Body] = corner; + if (saved.Pinned) m_layout.PinnedRegions.Add(region.Body); + if (saved.Collapsed) m_layout.CollapsedRegions.Add(region.Body); + } + } + + private string? ClosureRegionKey(string key) { + var m = s_closureEntry.Match(key); + return m.Success && m_newToSaved.TryGetValue(m.Groups[1].Value, out var saved) ? saved + m.Groups[2].Value : null; + } + + private void Flags(GraphNode node, NodeMeta entry) { + if (entry.Pinned) m_layout.PinnedNodes.Add(node); + if (entry.Collapsed) m_layout.CollapsedNodes.Add(node); + } + + public void RebuildSequences() { + var created = false; + foreach (var saved in m_meta.Sequences) { + if (saved.Outputs.Count == 0 || saved.Outputs.Count != saved.Counts.Count || saved.Outputs.Any(o => o.Length == 0 || !m_inverse.ContainsKey(o))) continue; + var firsts = saved.Outputs.Select(o => m_inverse[o]).ToList(); + var block = firsts[0].Parent; + if (block is null || firsts.Any(f => f.Parent != block)) continue; + var starts = firsts.Select(block.IndexOf).ToList(); + var ok = true; + for (var i = 0; i < starts.Count; i++) { + if (starts[i] < 0 || (i > 0 && starts[i] <= starts[i - 1])) ok = false; + else if (i + 1 < starts.Count && starts[i + 1] - starts[i] != saved.Counts[i]) ok = false; + else if (i + 1 == starts.Count && starts[i] + saved.Counts[i] != block.Statements.Count) ok = false; + } + if (!ok) continue; + + SequenceStatement sequence; + try { + sequence = m_layout.Graph.GroupAsSequence(block, starts); + } catch (ArgumentException) { + continue; + } + created = true; + if (m_saved.TryGetValue(saved.Key, out var entry)) { + m_layout.Local[sequence] = new Vec(entry.X, entry.Y); + Flags(sequence, entry); + } + } + if (created) m_layout.Refresh(); + } + + public void RestoreExpanded() { + foreach (var key in m_meta.Expanded) { + if (Resolve(key) is not { } host || NodeShape.LocalCalleeOf(host) is not { } callee) continue; + if (m_keys.Regions.FirstOrDefault(r => r.Header == callee) is not { } region || m_layout.Embedded.ContainsKey(region.Body) || m_keys.RegionOf(host) == region) continue; + var hostRegion = m_keys.RegionOf(host); + if (hostRegion is not null && m_layout.Embedded.ContainsKey(hostRegion.Body) || + m_layout.Embedded.Values.Any(existing => m_keys.RegionOf(existing) == region)) continue; + m_layout.CollapsedRegions.Remove(region.Body); + host.IsExpanded = true; + m_layout.Embedded[region.Body] = host; + } + } + + public void RestoreFlavors() { + foreach (var saved in m_meta.Flavors) + if (Resolve(saved.Key) is TableNode table) ApplyFlavor(table, saved.Flavor); + } + + public void RestoreSharedWires() { + // folding duplicates changes the paths used to restore wires + var links = new List<(OutputPin Source, InputPin Target)>(); + foreach (var wire in m_meta.SharedWires) { + if (Resolve(wire.Source) is not ExprNode source || Resolve(wire.Target) is not { } target || + wire.Output < 0 || wire.Output >= source.Outputs.Count || wire.Input < 0 || wire.Input >= target.Inputs.Count || + m_keys.RegionOf(source) != m_keys.RegionOf(target)) continue; + links.Add((source.Outputs[wire.Output], target.Inputs[wire.Input])); + } + var changed = false; + foreach (var (source, target) in links) + changed |= m_layout.Graph.TryRestoreSharedValue(source, target); + if (changed) m_layout.Refresh(); + } + + public void RestoreReroutes() { + foreach (var saved in m_meta.Reroutes) { + if (Resolve(saved.Key) is not { } node || saved.Points.Count % 2 != 0) continue; + if (saved.Row >= ProxyRow) { + var feeds = NodeShape.SlotsOf(InlineRules.Drawn(node)).FirstOrDefault(s => s.Kind == SlotKind.DataIn && s.Row == saved.Row - ProxyRow); + if (feeds?.In is { Source: not null } proxied && saved.Points.Count == 2) m_layout.ProxyOffsets[proxied] = new Vec(saved.Points[0], saved.Points[1]); + continue; + } + if (saved.Row == ExecRow) { + if (node is Statement target) m_layout.ExecReroutes[target] = Pairs(saved.Points); + continue; + } + var slot = NodeShape.SlotsOf(InlineRules.Drawn(node)).FirstOrDefault(s => s.Kind == SlotKind.DataIn && s.Row == saved.Row); + if (slot?.In is not { Source: not null } pin) continue; + m_layout.Reroutes[pin] = Pairs(saved.Points); + } + } + + private static List Pairs(IReadOnlyList numbers) { + var list = new List(); + for (var i = 0; i < numbers.Count; i += 2) list.Add(new Vec(numbers[i], numbers[i + 1])); + return list; + } + + public void RestoreGroups() { + foreach (var saved in m_meta.Groups) { + var members = new List(); + foreach (var key in saved.Members) + if (Resolve(key) is { } node && m_layout.Local.ContainsKey(node)) members.Add(node); + if (members.Count == 0) continue; + + var group = new LayoutGroup { Title = saved.Title, Color = saved.Color }; + group.Members.AddRange(members); + if (members.Count == saved.Members.Count) { + var origin = m_keys.RegionOf(members[0]) is { } region ? m_layout.OriginOf(region) : default; + group.Rect = new Rect(saved.X + origin.X, saved.Y + origin.Y, saved.W, saved.H); + } else { + group.Rect = Around(members); + } + m_layout.Groups.Add(group); + } + } + + private Rect Around(IReadOnlyList members) => AroundCore(members.Select(m_layout.Bounds)); + + private static Rect AroundCore(IEnumerable rects) { + var union = rects.Aggregate(Rect.Union); + return new Rect(union.X - 16, union.Y - 36, union.W + 32, union.H + 52); + } + + private GraphNode? Resolve(string savedKey) { + var hash = savedKey.IndexOf('#'); + var statement = hash >= 0 ? savedKey[..hash] : savedKey; + var suffix = hash >= 0 ? savedKey[hash..] : ""; + if (savedKey.StartsWith('~')) return m_layout.Keys.NodeOf(savedKey); + if (!m_inverse.TryGetValue(statement, out var node) || m_layout.Keys.KeyOf(node) is not { } newKey) return null; + return m_layout.Keys.NodeOf(newKey + suffix); + } + + } +} diff --git a/editor/LuaEditor/Layout/NodeShape.cs b/editor/LuaEditor/Layout/NodeShape.cs new file mode 100644 index 000000000..14305aeec --- /dev/null +++ b/editor/LuaEditor/Layout/NodeShape.cs @@ -0,0 +1,208 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using editor.LuaEditor.Graph; +using editor.LuaEditor.Types; + +namespace editor.LuaEditor.Layout; + +public enum SlotKind { ExecIn, ExecOut, DataIn, DataOut } + +public sealed record Slot(SlotKind Kind, int Row, string Label, GraphNode Node, InputPin? In = null, OutputPin? Out = null, Block? Child = null, LuaType? Type = null, bool IsCallableReference = false) { + public bool IsLeft => Kind is SlotKind.ExecIn or SlotKind.DataIn; + public bool IsExec => Kind is SlotKind.ExecIn or SlotKind.ExecOut; +} + +public enum NodeLook { Event, Flow, Call, Variable, Operator, Value, Comment, Raw } + +public static class NodeShape { + public const string ContinuationLabel = "next"; + + public static bool HasExecutionIn(GraphNode node) => node is Statement and not (CommentStatement or FunctionDecl or LabelStatement); + + public static bool HasContinuation(Statement s) => s is not (ReturnStatement or BreakStatement or GotoStatement or CommentStatement or FunctionDecl); + + public static string? TableLabel(InputPin pin) { + if (pin.Owner is not TableNode table || table.Fields.FirstOrDefault(f => f.Value == pin) is not { Kind: TableFieldKind.Keyed, Key: { Source: null } key }) return null; + return "[" + KeyText(key) + "] "; + } + + public static string KeyText(InputPin key) => key.Constant is { Kind: ConstantKind.String, Raw: var raw } && raw.Length >= 2 ? raw[1..^1] : key.Constant?.Raw ?? "key"; + + public static IReadOnlyList SlotsOf(GraphNode node) { + + var slots = new List(); + var left = 0; + var right = 0; + + if (node is Statement statement && HasExecutionIn(node)) slots.Add(new Slot(SlotKind.ExecIn, left++, "", node)); + + foreach (var pin in InlineRules.VisibleInputs(node)) { + if (pin.Owner is Statement && pin.Name == "table" && node is FunctionDecl d && d.Path.Count < 2) continue; + slots.Add(new Slot(SlotKind.DataIn, left++, TableLabel(pin) ?? pin.Name, node, In: pin, Type: pin.Expected)); + } + + if (node is FunctionEntry entry) slots.Add(new Slot(SlotKind.ExecOut, right++, "", node, Child: entry.Body)); + if (node is Statement s) { + var roles = s is FunctionDecl ? [] : s.ChildBlocks.ToList(); + foreach (var block in roles) slots.Add(new Slot(SlotKind.ExecOut, right++, RoleLabel(s, block), node, Child: block)); + if (HasContinuation(s)) slots.Add(new Slot(SlotKind.ExecOut, right++, roles.Count > 0 ? ContinuationLabel : "", node)); + } + + if (node is FunctionDecl declaration) { + slots.Add(new Slot(SlotKind.ExecOut, right++, "", node, Child: declaration.Entry.Body)); + foreach (var output in declaration.Entry.Outputs) + slots.Add(new Slot(SlotKind.DataOut, right++, output.Name, node, Out: output, Type: output.Type)); + } + foreach (var output in node.Outputs) { + if (node is CallStatement || InlineRules.IsMerged(node)) break; + slots.Add(new Slot(SlotKind.DataOut, right++, output.Name, node, Out: output, Type: output.Type)); + } + var call = CallOf(node); + if (node is CallStatement && call is { Style: CallStyle.Function } && + (LocalCalleeOf(node) is not null || call.Target.Source?.Owner is MemberGet)) + foreach (var output in call.Outputs.Take(call.ReturnCount)) + slots.Add(new Slot(SlotKind.DataOut, right++, output.Name, node, Out: output, Type: output.Type)); + if (call is { Style: CallStyle.Function, Target.Source: { } callable } && + (callable.Owner is MemberGet || LocalCalleeOf(node) is not null)) + slots.Add(new Slot(SlotKind.DataOut, right++, "function", node, Out: callable, Type: callable.Type, IsCallableReference: true)); + + if (node.IsExpanded && CalleeOf(node) is { } callee) { + var names = callee.Entry.Params.Select(p => p.Name).ToList(); + var index = 0; + for (var i = 0; i < slots.Count; i++) { + if (slots[i].Kind != SlotKind.DataIn) continue; + if (index < names.Count) slots[i] = slots[i] with { Label = names[index] }; + index++; + } + } + return slots; + + } + + public static int SlotRows(GraphNode node) { + var slots = SlotsOf(node); + return slots.Count == 0 ? 1 : slots.Max(s => s.Row) + 1; + } + + public static int Rows(GraphNode node) => SlotRows(node) + (node is TableNode ? 1 : 0); + + public static (FunctionDecl Callee, double InnerWidth, double InnerHeight)? ExpansionOf(GraphNode node) { + if (!node.IsExpanded || CalleeOf(node) is not { } callee) return null; + var statements = callee.Entry.Body.Statements.Count(s => s is not CommentStatement); + return (callee, 440, Math.Clamp(150 + 22 * Math.Min(statements, 10), 170, 380)); + } + + public static ReturnStatement? TrailingReturn(Block body) => body.Statements.LastOrDefault(s => !s.IsFloating && s is not CommentStatement) as ReturnStatement; + + public static CallNode? CallOf(GraphNode node) => node switch { + CallNode call => call, + CallStatement statement => statement.CallNode, + LocalDecl { Values: [{ Source.Owner: CallNode call }] } local when InlineRules.HostOf(call) == local => call, + _ => null + }; + + public static Binding? BindingOf(OutputPin? pin) => pin?.Binding ?? (pin?.Owner as VariableGet)?.Binding; + + public static FunctionDecl? LocalCalleeOf(GraphNode node) { + var call = CallOf(node); + return call is { Style: CallStyle.Function } && BindingOf(call.Target.Source) is { IsMutable: false, Declarer: FunctionDecl { IsLocal: true } local } + ? local : null; + } + + public static FunctionDecl? CalleeOf(GraphNode node) { + if (LocalCalleeOf(node) is { } local) return local; + var call = CallOf(node); + if (call is null || ScriptInfo.Find(node.Graph) is not { } script) return null; + var member = call.Target.Source?.Owner as MemberGet; + var receiver = call.Style == CallStyle.Method ? call.Target : member?.Object; + if (receiver is null || !script.IsTable(receiver) && BindingOf(receiver.Source)?.Kind != BindingKind.Self) return null; + var name = call.Style == CallStyle.Method ? call.Method : member?.Name; + return script.Methods.FirstOrDefault(d => d.Name == name); + } + + public static IReadOnlyList ExpansionLines(GraphNode node) { + if (!node.IsExpanded || CalleeOf(node) is not { } callee) return []; + var lines = new List { callee.Name + "(" + string.Join(", ", callee.Entry.Params.Select(p => p.Name)) + ")" }; + var statements = callee.Entry.Body.Statements.Where(s => s is not CommentStatement).ToList(); + lines.AddRange(statements.Take(6).Select(s => "• " + TitleOf(s))); + if (statements.Count > 6) lines.Add("… " + (statements.Count - 6) + " more"); + return lines; + } + + public static Slot? SlotOf(InputPin pin) { + var drawn = InlineRules.Drawn(pin.Owner); + return SlotsOf(drawn).FirstOrDefault(s => s.In == pin); + } + + public static Slot? SlotOf(OutputPin pin) { + var drawn = InlineRules.Drawn(pin.Owner); + return SlotsOf(drawn).FirstOrDefault(s => s.Out == pin); + } + + public static string RoleLabel(Statement owner, Block block) { + if (owner is IfStatement i) { + var index = i.Clauses.FindIndex(c => c.Body == block); + return index switch { 0 => "then", > 0 => "elseif", _ => "else" }; + } + if (owner is SequenceStatement q) return "then " + q.Branches.IndexOf(block); + return owner is NumericFor or GenericFor or WhileStatement ? "loop" : "do"; + } + + public static NodeLook LookOf(GraphNode node) => node switch { + FunctionDecl or FunctionEntry or FunctionNode => NodeLook.Event, + CommentStatement => NodeLook.Comment, + RawStatement or RawExpression => NodeLook.Raw, + IfStatement or WhileStatement or RepeatStatement or NumericFor or GenericFor or DoStatement or SequenceStatement + or ReturnStatement or BreakStatement or GotoStatement or LabelStatement => NodeLook.Flow, + LocalDecl local when CallOf(local) is not null => NodeLook.Call, + LocalDecl or AssignStatement or CastStatement or VariableGet => NodeLook.Variable, + BinaryOp or UnaryOp or ParenNode => NodeLook.Operator, + CallStatement or CallNode => NodeLook.Call, + _ => NodeLook.Value + }; + + public static string TitleOf(GraphNode node) { + if (InlineRules.Title(node) is { } call) return call; + return node switch { + FunctionDecl d => (d.IsLocal ? "local function " : d.IsMethod ? "method " : "function ") + d.Name, + FunctionEntry e => "Entry", + LocalDecl l => "local " + string.Join(", ", l.Names.Select(n => n.Name)), + AssignStatement a => "Set " + string.Join(", ", a.Targets.Select(t => (t.Object is { } o && InlineRules.ImplicitObjectName(o) is { } owner ? owner + "." : "") + (t.Name ?? "[ ]"))), + IfStatement => "if", + WhileStatement => "while", + RepeatStatement => "repeat until", + NumericFor f => "for " + f.Var.Name + " =", + GenericFor g => "for " + string.Join(", ", g.Vars.Select(v => v.Name)) + " in", + DoStatement => "do", + ReturnStatement => "return", + BreakStatement => "break", + GotoStatement g => "goto " + g.Label, + LabelStatement l => "::" + l.Name + "::", + CastStatement c => "---@cast " + c.Variable + " " + c.TypeText, + CommentStatement c => string.Join(" ", c.Lines.Select(l => l.TrimStart('-', ' ', '\t'))), + SequenceStatement => "Sequence", + RawStatement r => "Raw: " + r.Text, + BinaryOp b => OperatorName(b.Op), + UnaryOp u => u.Op switch { UnaryKind.Neg => "-", UnaryKind.Not => "not", UnaryKind.Len => "#", _ => "~" }, + ParenNode => "( )", + VariableGet v => v.Binding.Name, + VarargNode => "...", + IndexGet => "[ ]", + MemberGet m => "." + m.Name, +TableNode table => table.Flavor switch { TableFlavor.Array => "Array", TableFlavor.Dictionary => "Dictionary", _ => "Table" }, + FunctionNode f => "function(" + string.Join(", ", f.Entry.Params.Select(p => p.Name)) + ")", + RawExpression r => r.Text, + GlobalGet g => g.Name, + _ => node.GetType().Name + }; + } + + public static string OperatorName(BinaryKind op) => op switch { + BinaryKind.Add => "+", BinaryKind.Sub => "-", BinaryKind.Mul => "*", BinaryKind.Div => "/", BinaryKind.FloorDiv => "//", + BinaryKind.Mod => "%", BinaryKind.Pow => "^", BinaryKind.Concat => "..", BinaryKind.Eq => "==", BinaryKind.Ne => "~=", + BinaryKind.Lt => "<", BinaryKind.Le => "<=", BinaryKind.Gt => ">", BinaryKind.Ge => ">=", BinaryKind.And => "and", + BinaryKind.Or => "or", BinaryKind.BitAnd => "&", BinaryKind.BitOr => "|", BinaryKind.BitXor => "~", BinaryKind.Shl => "<<", + _ => ">>" + }; +} diff --git a/editor/LuaEditor/Layout/RegionPacker.cs b/editor/LuaEditor/Layout/RegionPacker.cs new file mode 100644 index 000000000..0e45dfeef --- /dev/null +++ b/editor/LuaEditor/Layout/RegionPacker.cs @@ -0,0 +1,74 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace editor.LuaEditor.Layout; + +public static class RegionPacker { + public const double Gap = 80; + public const double TargetAspect = 16.0 / 9.0; + + public static List Pack(IReadOnlyList sizes, IReadOnlyList obstacles, double aspect = TargetAspect) { + var widest = sizes.Count == 0 ? 0 : sizes.Max(s => s.W); + var total = sizes.Sum(s => s.W + Gap); + var area = sizes.Sum(s => (s.W + Gap) * (s.H + Gap)); + var candidates = new SortedSet { Math.Max(widest, Math.Sqrt(area * aspect)), widest }; + for (var k = 2; k <= 6; k++) candidates.Add(Math.Max(widest, widest * k + Gap * (k - 1))); + candidates.Add(Math.Max(widest, total)); + + List? best = null; + var bestScore = double.MaxValue; + foreach (var rowWidth in candidates) { + var positions = PackAt(sizes, obstacles, rowWidth); + var right = 0.0; + var bottom = 0.0; + for (var i = 0; i < sizes.Count; i++) { + right = Math.Max(right, positions[i].X + sizes[i].W); + bottom = Math.Max(bottom, positions[i].Y + sizes[i].H); + } + var shape = bottom <= 0 || right <= 0 ? 1 : right / bottom; + var score = Math.Abs(Math.Log(shape / aspect)) + 0.0000001 * right * bottom; + if (score < bestScore) { + bestScore = score; + best = positions; + } + } + return best ?? []; + } + + private static List PackAt(IReadOnlyList sizes, IReadOnlyList obstacles, double rowWidth) { + var result = new List(); + var x = 0.0; + var y = 0.0; + var rowHeight = 0.0; + foreach (var size in sizes) { + while (true) { + if (x > 0 && x + size.W > rowWidth) { + x = 0; + y += rowHeight + Gap; + rowHeight = 0; + } + var candidate = new Rect(x, y, size.W, size.H); + var hit = obstacles.Where(o => o.Inflate(Gap / 2).Intersects(candidate)).Select(o => (Rect?)o).FirstOrDefault(); + if (hit is null) break; + if (x == 0 && hit.Value.Right + Gap + size.W > rowWidth) { + y = hit.Value.Bottom + Gap; + rowHeight = 0; + continue; + } + x = hit.Value.Right + Gap; + } + result.Add(new Vec(x, y)); + x += size.W + Gap; + rowHeight = Math.Max(rowHeight, size.H); + } + return result; + } + + public static int LifecycleRank(string functionName) => functionName switch { + "init" or "awake" or "start" => 0, + "tick" or "update" or "fixedTick" or "lateUpdate" => 1, + "destroy" or "onDestroy" => 2, + _ => 3 + }; +} From a65135d4aa81df6a4d008927b4d6f9e8943dd343 Mon Sep 17 00:00:00 2001 From: Xein Date: Wed, 11 Nov 2026 18:38:55 +0100 Subject: [PATCH 4/8] lua editor ui --- editor/Assets/Types/ScriptAsset.cs | 6 +- .../Components/Elements/CollapseAnimator.cs | 26 + editor/Components/Elements/EnumBox.cs | 128 +- editor/Editors/PaletteView.axaml.cs | 16 +- editor/LuaEditor/Canvas/CanvasTheme.cs | 61 + editor/LuaEditor/Canvas/GraphCanvas.Draw.cs | 932 ++++++++++++++ editor/LuaEditor/Canvas/GraphCanvas.cs | 1071 +++++++++++++++++ editor/LuaEditor/Canvas/VariableDrag.cs | 10 + editor/LuaEditor/Controls/PinShapeIcon.cs | 123 ++ editor/LuaEditor/Controls/TypeEditor.cs | 206 ++++ editor/LuaEditor/Controls/TypePicker.cs | 237 ++++ editor/LuaEditor/LuaEditorWindow.cs | 63 + editor/LuaEditor/LuaGraphEditorView.axaml | 587 +++++++++ editor/LuaEditor/LuaGraphEditorView.axaml.cs | 450 +++++++ .../LuaGraphEditorViewModel.Files.cs | 139 +++ .../LuaGraphEditorViewModel.Signature.cs | 315 +++++ .../LuaEditor/LuaGraphEditorViewModel.Tags.cs | 74 ++ editor/LuaEditor/LuaGraphEditorViewModel.cs | 659 ++++++++++ editor/LuaEditor/SearchRow.cs | 149 +++ editor/LuaEditor/VariableRow.cs | 77 ++ editor/Resources/EnumBox.axaml | 25 +- editor/Workspace/HierarchyConnectorLayer.cs | 8 +- editor/Workspace/HierarchyRowPress.cs | 28 + editor/Workspace/HierarchyView.axaml.cs | 41 +- editor/Workspace/HierarchyViewModel.cs | 2 +- editor/Workspace/MainWindowView.axaml | 4 + editor/Workspace/MainWindowViewModel.cs | 39 + editor/Workspace/ToastZoneFactory.cs | 23 +- 28 files changed, 5430 insertions(+), 69 deletions(-) create mode 100644 editor/Components/Elements/CollapseAnimator.cs create mode 100644 editor/LuaEditor/Canvas/CanvasTheme.cs create mode 100644 editor/LuaEditor/Canvas/GraphCanvas.Draw.cs create mode 100644 editor/LuaEditor/Canvas/GraphCanvas.cs create mode 100644 editor/LuaEditor/Canvas/VariableDrag.cs create mode 100644 editor/LuaEditor/Controls/PinShapeIcon.cs create mode 100644 editor/LuaEditor/Controls/TypeEditor.cs create mode 100644 editor/LuaEditor/Controls/TypePicker.cs create mode 100644 editor/LuaEditor/LuaEditorWindow.cs create mode 100644 editor/LuaEditor/LuaGraphEditorView.axaml create mode 100644 editor/LuaEditor/LuaGraphEditorView.axaml.cs create mode 100644 editor/LuaEditor/LuaGraphEditorViewModel.Files.cs create mode 100644 editor/LuaEditor/LuaGraphEditorViewModel.Signature.cs create mode 100644 editor/LuaEditor/LuaGraphEditorViewModel.Tags.cs create mode 100644 editor/LuaEditor/LuaGraphEditorViewModel.cs create mode 100644 editor/LuaEditor/SearchRow.cs create mode 100644 editor/LuaEditor/VariableRow.cs create mode 100644 editor/Workspace/HierarchyRowPress.cs diff --git a/editor/Assets/Types/ScriptAsset.cs b/editor/Assets/Types/ScriptAsset.cs index ef2b76c90..c9bb73e08 100644 --- a/editor/Assets/Types/ScriptAsset.cs +++ b/editor/Assets/Types/ScriptAsset.cs @@ -14,12 +14,12 @@ public sealed class ScriptAsset : BaseAsset { public override bool CanBeCreated => true; public override string Category => "Logic"; public override bool HasThumbnail => false; - public override bool CanBeEdited => false; - public override string EditorTool => ""; + public override bool CanBeEdited => true; + public override string EditorTool => "LuaEditor"; public override string SchemaPath => ""; public override Task CreateAsync(string path) { - File.WriteAllText(path, "-- Toast Script\n"); + File.WriteAllText(path, "-- Toast Script\nlocal M = {}\n\nreturn M\n"); return Task.CompletedTask; } } diff --git a/editor/Components/Elements/CollapseAnimator.cs b/editor/Components/Elements/CollapseAnimator.cs new file mode 100644 index 000000000..81b2acd7c --- /dev/null +++ b/editor/Components/Elements/CollapseAnimator.cs @@ -0,0 +1,26 @@ +using System; +using System.Diagnostics; +using Avalonia.Threading; + +namespace editor.Components.Elements; + +public static class CollapseAnimator { + public const int DurationMs = 180; + + public static DispatcherTimer Run(double from, double to, Action apply, Action? done = null) { + var clock = Stopwatch.StartNew(); + var timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(8) }; + timer.Tick += (_, _) => { + var t = Math.Min(clock.ElapsedMilliseconds / (double)DurationMs, 1.0); + if (t >= 1) { + timer.Stop(); + apply(to); + done?.Invoke(); + return; + } + apply(from + (to - from) * (1 - Math.Pow(1 - t, 3))); + }; + timer.Start(); + return timer; + } +} diff --git a/editor/Components/Elements/EnumBox.cs b/editor/Components/Elements/EnumBox.cs index 10b914009..fa8fb8c19 100644 --- a/editor/Components/Elements/EnumBox.cs +++ b/editor/Components/Elements/EnumBox.cs @@ -5,6 +5,8 @@ using System; using System.Collections.Generic; +using System.Linq; +using Avalonia.Threading; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Primitives; @@ -27,8 +29,21 @@ public sealed class EnumBox : TemplatedControl { public static readonly DirectProperty IsOpenProperty = AvaloniaProperty.RegisterDirect(nameof(IsOpen), o => o.m_isOpen); + public static readonly StyledProperty?> GroupsProperty = + AvaloniaProperty.Register?>(nameof(Groups)); + + public const int SearchThreshold = 12; + + private sealed record Header(string Text, bool Folded, int Count); + + private readonly HashSet m_folded = []; + private bool m_isOpen; private ItemsControl? m_list; + private TextBox? m_search; + private List m_visible = []; + private int m_highlight = -1; + private Button? m_highlighted; private Popup? m_popup; @@ -42,6 +57,11 @@ public IEnumerable? Options { set => SetValue(OptionsProperty, value); } + public IReadOnlyDictionary? Groups { + get => GetValue(GroupsProperty); + set => SetValue(GroupsProperty, value); + } + public bool IsOpen { get => m_isOpen; private set => SetAndRaise(IsOpenProperty, ref m_isOpen, value); @@ -60,16 +80,25 @@ protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { if (root is not null) root.Tapped += OnRootTapped; if (m_popup is not null) m_popup.Closed += OnPopupClosed; + if (m_search is not null) { + m_search.TextChanged -= OnSearchChanged; + m_search.KeyDown -= OnSearchKey; + } + m_search = e.NameScope.Find("PART_Search"); + if (m_search is not null) { + m_search.TextChanged += OnSearchChanged; + m_search.KeyDown += OnSearchKey; + } if (m_list is not null) { - m_list.ItemTemplate = new FuncDataTemplate((opt, _) => BuildOption(opt)); - m_list.ItemsSource = Options; + m_list.ItemTemplate = new FuncDataTemplate((item, _) => item is Header header ? BuildHeader(header) : BuildOption((string)item)); + Rebuild(); } + } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); - if (change.Property == OptionsProperty && m_list is not null) - m_list.ItemsSource = Options; + if ((change.Property == OptionsProperty || change.Property == GroupsProperty) && m_list is not null) Rebuild(); } private void OnRootTapped(object? sender, TappedEventArgs e) { @@ -85,6 +114,93 @@ private void OnPopupClosed(object? sender, EventArgs e) { private void ToggleOpen() { IsOpen = !IsOpen; if (m_popup is not null) m_popup.IsOpen = IsOpen; + if (!IsOpen) return; + if (m_search is not null) { + m_search.Text = ""; + m_search.IsVisible = (Options?.Count() ?? 0) > SearchThreshold; + } + m_folded.Clear(); + if (Groups is { } groupNames) { + var first = groupNames.Values.FirstOrDefault(); + var current = Value is { } value && groupNames.TryGetValue(value, out var own) ? own : null; + foreach (var name in groupNames.Values.Distinct()) + if (name != first && name != current) m_folded.Add(name); + } + Rebuild(highlightValue: true); + if (m_search is { IsVisible: true }) Dispatcher.UIThread.Post(() => m_search.Focus()); + } + + private void OnSearchChanged(object? sender, TextChangedEventArgs e) => Rebuild(); + + private void OnSearchKey(object? sender, KeyEventArgs e) { + switch (e.Key) { + case Key.Down: + m_highlight = Math.Min(m_highlight + 1, m_visible.Count - 1); + Rebuild(keepHighlight: true); + break; + case Key.Up: + m_highlight = Math.Max(m_highlight - 1, 0); + Rebuild(keepHighlight: true); + break; + case Key.Enter: + if (m_highlight >= 0 && m_highlight < m_visible.Count) Select(m_visible[m_highlight]); + break; + case Key.Escape: + IsOpen = false; + if (m_popup is not null) m_popup.IsOpen = false; + break; + default: + return; + } + e.Handled = true; + } + + private void Rebuild(bool highlightValue = false, bool keepHighlight = false) { + if (m_list is null) return; + var all = Options?.ToList() ?? []; + var query = m_search?.Text?.Trim() ?? ""; + var matching = all.Where(o => query.Length == 0 || o.Contains(query, StringComparison.OrdinalIgnoreCase)).ToList(); + var items = new List(); + if (Groups is { } groups) { + var searching = query.Length > 0; + foreach (var group in matching.GroupBy(o => groups.GetValueOrDefault(o, "Other"))) { + var folded = !searching && m_folded.Contains(group.Key); + items.Add(new Header(group.Key, folded, group.Count())); + if (!folded) items.AddRange(group); + } + m_visible = items.OfType().ToList(); + } else { + m_visible = matching; + items.AddRange(matching); + } + if (!keepHighlight) m_highlight = highlightValue && Value is { } v && m_visible.IndexOf(v) is var at and >= 0 ? at : m_visible.Count > 0 ? 0 : -1; + m_highlighted = null; + m_list.ItemsSource = items; + Dispatcher.UIThread.Post(() => m_highlighted?.BringIntoView(), DispatcherPriority.Loaded); + } + + private Control BuildHeader(Header header) { + var line = new Button { + Content = new TextBlock { + Text = (header.Folded ? "▸ " : "▾ ") + header.Text + " " + header.Count, + FontSize = 13, + FontWeight = FontWeight.Bold, + Foreground = Brush("Text") + }, + HorizontalAlignment = HorizontalAlignment.Stretch, + HorizontalContentAlignment = HorizontalAlignment.Left, + Background = Brush("Bg4"), + BorderThickness = new Thickness(0), + Padding = new Thickness(8, 5), + Margin = new Thickness(0, 4, 0, 0), + CornerRadius = new CornerRadius(4), + Cursor = new Cursor(StandardCursorType.Hand) + }; + line.Click += (_, _) => { + if (!m_folded.Remove(header.Text)) m_folded.Add(header.Text); + Rebuild(keepHighlight: true); + }; + return line; } private void Select(string option) { @@ -95,11 +211,12 @@ private void Select(string option) { private Control BuildOption(string option) { var selected = string.Equals(option, Value, StringComparison.Ordinal); + var highlighted = m_highlight >= 0 && m_highlight < m_visible.Count && m_visible[m_highlight] == option; var btn = new Button { Content = option, HorizontalAlignment = HorizontalAlignment.Stretch, HorizontalContentAlignment = HorizontalAlignment.Left, - Background = selected ? Brush("Red") : Brushes.Transparent, + Background = selected ? Brush("Red") : highlighted ? Brush("Bg4") : Brushes.Transparent, Foreground = Brush(selected ? "Bg1" : "Text"), BorderThickness = new Thickness(0), Padding = new Thickness(8, 6), @@ -108,6 +225,7 @@ private Control BuildOption(string option) { FontSize = 15 }; btn.Click += (_, _) => Select(option); + if (highlighted) m_highlighted = btn; return btn; } diff --git a/editor/Editors/PaletteView.axaml.cs b/editor/Editors/PaletteView.axaml.cs index 4c071addb..a8f72a4f9 100644 --- a/editor/Editors/PaletteView.axaml.cs +++ b/editor/Editors/PaletteView.axaml.cs @@ -93,21 +93,7 @@ private void AnimateWidth(int column, double from, double to, GridLength final) m_timers[column]?.Stop(); var definition = Root.ColumnDefinitions[column]; - var clock = Stopwatch.StartNew(); - var timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(8) }; - m_timers[column] = timer; - timer.Tick += (_, _) => { - var t = Math.Min(clock.ElapsedMilliseconds / (double)AnimationMs, 1.0); - var eased = 1 - Math.Pow(1 - t, 3); - if (t >= 1) { - timer.Stop(); - definition.Width = final; - return; - } - - definition.Width = new GridLength(from + (to - from) * eased); - }; - timer.Start(); + m_timers[column] = Components.Elements.CollapseAnimator.Run(from, to, width => definition.Width = new GridLength(width), () => definition.Width = final); } private void OnLabelTapped(object? sender, TappedEventArgs e) { diff --git a/editor/LuaEditor/Canvas/CanvasTheme.cs b/editor/LuaEditor/Canvas/CanvasTheme.cs new file mode 100644 index 000000000..a1a3b54cb --- /dev/null +++ b/editor/LuaEditor/Canvas/CanvasTheme.cs @@ -0,0 +1,61 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using Avalonia; +using Avalonia.Media; +using editor.LuaEditor.Layout; + +namespace editor.LuaEditor.Canvas; + +public sealed class CanvasTheme { + public static CanvasTheme Default { get; } = new(); + + private readonly Dictionary<(string Text, double Size, uint Color, bool Bold), FormattedText> m_text = []; + + public IBrush Background { get; } = Brush.Parse("#121111"); + public IBrush GridMinor { get; } = Brush.Parse("#181717"); + public IBrush GridMajor { get; } = Brush.Parse("#1f1d1e"); + public IBrush NodeBody { get; } = Brush.Parse("#2b2a2a"); + public IBrush NodeBodyDim { get; } = Brush.Parse("#222121"); + public IBrush Text { get; } = Brush.Parse("#fafafa"); + public IBrush TextMuted { get; } = Brush.Parse("#a0a0a0"); + public IBrush Accent { get; } = Brush.Parse("#ff1659"); + public IBrush Error { get; } = Brush.Parse("#ff1659"); + public IBrush Warning { get; } = Brush.Parse("#ffa300"); + public IBrush Exec { get; } = Brush.Parse(Editing.PinStyle.Exec); + public IBrush ConstantBox { get; } = Brush.Parse("#161515"); + public Pen NodeBorder { get; } = new(Brush.Parse("#383637"), 1); + public Pen SelectedBorder { get; } = new(Brush.Parse("#ff1659"), 2); + public Pen ErrorBorder { get; } = new(Brush.Parse("#ff1659"), 2); + public Pen WarningBorder { get; } = new(Brush.Parse("#ffa300"), 2); + public Pen ExecWire { get; } = new(Brush.Parse("#fafafa"), 2.5, lineCap: PenLineCap.Round); + public Typeface Font { get; } = new("Inter, Segoe UI, sans-serif"); + public Typeface FontBold { get; } = new("Inter, Segoe UI, sans-serif", FontStyle.Normal, FontWeight.SemiBold); + + public IBrush HeaderOf(NodeLook look) => look switch { + NodeLook.Event => Brush.Parse("#ff1659"), + NodeLook.Flow => Brush.Parse("#454343"), + NodeLook.Call => Brush.Parse("#29adff"), + NodeLook.Variable => Brush.Parse("#00d437"), + NodeLook.Operator => Brush.Parse("#ad73ff"), + NodeLook.Value => Brush.Parse("#73ffea"), + NodeLook.Comment => Brush.Parse("#ffec27"), + _ => Brush.Parse("#ffa300") + }; + + public IBrush HeaderTextOf(NodeLook look) => look is NodeLook.Flow or NodeLook.Event ? Text : Brush.Parse("#121111"); + + public static Color ParseColor(string hex) => Color.Parse(hex); + + public Pen WirePen(string color, bool dim = false, double width = 2) => new(new SolidColorBrush(Color.Parse(color), dim ? 0.35 : 0.95), width, lineCap: PenLineCap.Round); + + public FormattedText Format(string text, double size, IBrush brush, bool bold = false) { + var color = brush is ISolidColorBrush solid ? solid.Color.ToUInt32() : 0u; + var key = (text, size, color, bold); + if (m_text.TryGetValue(key, out var cached)) return cached; + if (m_text.Count > 4000) m_text.Clear(); + var formatted = new FormattedText(text, CultureInfo.InvariantCulture, FlowDirection.LeftToRight, bold ? FontBold : Font, size, brush); + m_text[key] = formatted; + return formatted; + } +} diff --git a/editor/LuaEditor/Canvas/GraphCanvas.Draw.cs b/editor/LuaEditor/Canvas/GraphCanvas.Draw.cs new file mode 100644 index 000000000..5e09e2d03 --- /dev/null +++ b/editor/LuaEditor/Canvas/GraphCanvas.Draw.cs @@ -0,0 +1,932 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Avalonia; +using Avalonia.Media; +using editor.LuaEditor.Editing; +using editor.LuaEditor.Graph; +using editor.LuaEditor.Layout; +using editor.LuaEditor.Types; +using Size = Avalonia.Size; + +namespace editor.LuaEditor.Canvas; + +public sealed partial class GraphCanvas { + private const double PinRadius = 5; + private const int ProxyThreshold = 3; + private const double ConstantBoxWidth = DefaultMeasure.ConstantBoxWidth; + + private readonly Dictionary> m_slotCache = []; + private readonly Dictionary m_nodeSeverity = []; + private readonly Dictionary m_pinProblems = []; + + private IReadOnlyList SlotsOf(GraphNode node) { + if (!m_slotCache.TryGetValue(node, out var slots)) { + slots = NodeShape.SlotsOf(node); + if (node is ReturnStatement { IsFloating: true } && Session?.Layout is { } layout && + layout.HostBody(node) is { } body && layout.Embedded.ContainsKey(body)) + slots = [.. slots, new Slot(SlotKind.ExecOut, 0, "", node)]; + m_slotCache[node] = slots; + } + return slots; + } + + private void RefreshCaches() { + m_slotCache.Clear(); + m_nodeSeverity.Clear(); + m_pinProblems.Clear(); + if (Session is null) return; + foreach (var d in Session.Graph.Diagnostics) { + var node = InlineRules.Drawn(d.Node); + if (!m_nodeSeverity.TryGetValue(node, out var current) || d.Severity > current) m_nodeSeverity[node] = d.Severity; + if (d.Pin is not null) m_pinProblems[d.Pin] = d.Message; + } + } + + private IEnumerable CanvasRegions() => Session is { } session + ? session.Layout.Keys.Regions.Where(region => ShowModuleSetup || !region.IsModule) : []; + + private bool IsModuleSetupNode(GraphNode node) => !ShowModuleSetup && Session is { } session && + !node.IsExpanded && !session.Layout.Loose.Contains(node) && session.Layout.Keys.RegionOf(node) is { IsModule: true }; + + private IEnumerable VisibleGroups() => Session is { } session + ? session.Layout.Groups.Where(group => ShowModuleSetup || group.Members.Any(node => !IsModuleSetupNode(node))) : []; + + private IEnumerable VisibleNodes(RegionInfo? only = null) { + if (Session is null) yield break; + var layout = Session.Layout; + foreach (var region in CanvasRegions()) { + if (only is not null && region != only) continue; + if (only is null && layout.CollapsedRegions.Contains(region.Body)) continue; + foreach (var node in layout.NodesOf(region)) { + if (InlineRules.IsMerged(node) || !layout.IsPlaced(node) || layout.IsHidden(node)) continue; + yield return node; + } + } + if (only is not null) yield break; + if (!ShowModuleSetup) + foreach (var host in layout.Embedded.Values.Where(host => !layout.Loose.Contains(host) && layout.Keys.RegionOf(host) is { IsModule: true })) + yield return host; + foreach (var loose in layout.Loose) yield return loose; + } + + private static StreamGeometry RoutedWire(Point from, Point to, GraphNode? fromNode, GraphNode? toNode) => Bezier(from, to); + + private Avalonia.Rect NodeRect(GraphNode node) { + + var b = Session!.Layout.Bounds(node); + return new Avalonia.Rect(b.X, b.Y, b.W, b.H); + } + + private Point SlotPoint(Slot slot) { + var layout = Session!.Layout; + var p = layout.Position(slot.Node); + var size = layout.Measure.Measure(slot.Node); + return new Point(slot.IsLeft ? p.X : p.X + size.W, p.Y + layout.Measure.PinY(slot.Node, slot.Row, !slot.IsLeft)); + } + + private Slot? SlotFor(InputPin pin) { + var drawn = InlineRules.Drawn(pin.Owner); + return SlotsOf(drawn).FirstOrDefault(s => s.In == pin); + } + + private Slot? SlotFor(OutputPin pin) { + var drawn = InlineRules.Drawn(pin.Owner); + return SlotsOf(drawn).FirstOrDefault(s => s.Out == pin); + } + + public override void Render(DrawingContext context) { + base.Render(context); + var theme = CanvasTheme.Default; + var size = Bounds.Size; + context.DrawRectangle(theme.Background, null, new Avalonia.Rect(size)); + using var clip = context.PushClip(new Avalonia.Rect(size)); + DrawGrid(context, theme, size); + if (Session is null) return; + + using (context.PushTransform(Matrix.CreateScale(Zoom, Zoom) * Matrix.CreateTranslation(PanX, PanY))) { + var view = new Avalonia.Rect(-PanX / Zoom, -PanY / Zoom, size.Width / Zoom, size.Height / Zoom); + DrawGroups(context, theme, view); + DrawRegions(context, theme, view); + DrawFrames(context, theme, view); + DrawWires(context, theme, view); + DrawNodes(context, theme, view); + DrawDragPreview(context, theme); + } + DrawBoxSelect(context, theme); + DrawMinimap(context, theme, size); + DrawDocCard(context, theme, size); + } + + private void DrawDocCard(DrawingContext context, CanvasTheme theme, Size size) { + if (m_docNode is not { } node || Session is null) return; + var doc = NodeDoc.Of(node, Session.Catalog); + var keyword = new SolidColorBrush(Color.Parse("#ff77a8")); + var lines = new List { theme.Format(doc.Title, 14, doc.Title.Split(' ', 2)[0] is "if" or "for" or "while" or "repeat" or "do" or "return" or "break" or "local" or "goto" or "not" ? keyword : theme.Text, true) }; + if (doc.Summary.Length > 0) lines.Add(theme.Format(doc.Summary, 12, theme.TextMuted)); + FormattedText Pin(DocPin pin) { + var text = theme.Format(" " + pin.Name + ": " + pin.Type, 12, theme.Text); + text.SetForegroundBrush(theme.TextMuted, 2 + pin.Name.Length, 1); + text.SetForegroundBrush(new SolidColorBrush(Color.Parse(pin.Color)), 4 + pin.Name.Length, pin.Type.Length); + return text; + } + if (doc.Inputs.Count > 0) { + lines.Add(theme.Format("Inputs", 11, theme.TextMuted, true)); + lines.AddRange(doc.Inputs.Select(Pin)); + } + if (doc.Outputs.Count > 0) { + lines.Add(theme.Format("Outputs", 11, theme.TextMuted, true)); + lines.AddRange(doc.Outputs.Select(Pin)); + } + + foreach (var line in lines) line.MaxTextWidth = 360; + var width = lines.Max(l => l.Width) + 20; + var height = lines.Sum(l => l.Height + 3) + 14; + var x = Math.Min(m_docAt.X + 14, Math.Max(4, size.Width - width - 4)); + var y = Math.Min(m_docAt.Y + 18, Math.Max(4, size.Height - height - 4)); + context.DrawRectangle(theme.NodeBody, new Pen(theme.TextMuted, 1), new Avalonia.Rect(x, y, width, height), 6, 6); + var top = y + 8; + foreach (var line in lines) { + context.DrawText(line, new Point(x + 10, top)); + top += line.Height + 3; + } + } + + private void DrawGrid(DrawingContext context, CanvasTheme theme, Size size) { + var step = 32 * Zoom; + if (step < 7) return; + var minor = new Pen(theme.GridMinor, 1); + var major = new Pen(theme.GridMajor, 1); + var startX = PanX % step; + var startY = PanY % step; + for (var x = startX; x < size.Width; x += step) { + var index = (int)Math.Round((x - PanX) / step); + context.DrawLine(index % 5 == 0 ? major : minor, new Point(x, 0), new Point(x, size.Height)); + } + for (var y = startY; y < size.Height; y += step) { + var index = (int)Math.Round((y - PanY) / step); + context.DrawLine(index % 5 == 0 ? major : minor, new Point(0, y), new Point(size.Width, y)); + } + } + + private void DrawGroups(DrawingContext context, CanvasTheme theme, Avalonia.Rect view) { + foreach (var group in VisibleGroups()) { + var r = new Avalonia.Rect(group.Rect.X, group.Rect.Y, group.Rect.W, group.Rect.H); + if (!r.Intersects(view)) continue; + var color = CanvasTheme.ParseColor(group.Color); + var selected = ReferenceEquals(m_selectedGroup, group); + context.DrawRectangle(new SolidColorBrush(color, 0.14), new Pen(new SolidColorBrush(color, selected ? 1 : 0.55), selected ? 2 : 1), r, 6, 6); + context.DrawRectangle(new SolidColorBrush(color, 0.35), null, new Avalonia.Rect(r.X, r.Y, r.Width, 26), 6, 6); + context.DrawText(theme.Format(group.Title, 13, theme.Text, true), new Point(r.X + 10, r.Y + 5)); + } + } + + private void DrawRegions(DrawingContext context, CanvasTheme theme, Avalonia.Rect view) { + var layout = Session!.Layout; + foreach (var region in CanvasRegions()) { + if (layout.Embedded.ContainsKey(region.Body) || layout.RegionBounds(region) is not { } b) continue; + var collapsed = layout.CollapsedRegions.Contains(region.Body); + var name = region.IsModule ? "Script" : region.Header is FunctionDecl d ? d.Name : region.Header is { } closure ? NodeShape.TitleOf(closure) : "function"; + var header = RegionHeaderRect(region, b); + if (!header.Intersects(view) && !(b.X < view.Right && b.Y < view.Bottom && b.X + b.W > view.X && b.Y + b.H > view.Y)) continue; + if (!collapsed) { + var frame = RegionFrame(region, b); +context.DrawRectangle(new SolidColorBrush(Color.Parse("#ffffff"), 0.025), new Pen(new SolidColorBrush(Color.Parse("#ffffff"), 0.07), 1, dashStyle: DashStyle.Dash), frame, 8, 8); + } + var pinned = layout.PinnedRegions.Contains(region.Body); + context.DrawRectangle(new SolidColorBrush(Color.Parse("#ffffff"), 0.09), null, header, 6, 6); + DrawToggleButton(context, theme, header, !collapsed, theme.Text); + context.DrawText(theme.Format(name + (pinned ? " •" : ""), 14, theme.Text, true), new Point(header.X + 36, header.Y + 4)); + } + } + + private Avalonia.Rect RegionFrame(RegionInfo region, Layout.Rect bounds) { + var frame = new Avalonia.Rect(bounds.X - 12, bounds.Y - 30, bounds.W + 24, bounds.H + 42); + var layout = Session!.Layout; + foreach (var group in layout.Groups) { + if (group.Members.FirstOrDefault(m => layout.Keys.KeyOf(m) is not null) is not { } member || layout.Keys.RegionOf(member) != region) continue; + frame = frame.Union(new Avalonia.Rect(group.Rect.X - 12, group.Rect.Y - 30, group.Rect.W + 24, group.Rect.H + 42)); + } + return frame; + } + + private Avalonia.Rect RegionHeaderRect(RegionInfo region, Layout.Rect bounds) { + var name = region.IsModule ? "Script" : region.Header is FunctionDecl d ? d.Name : region.Header is { } closure ? NodeShape.TitleOf(closure) : "function"; + var frame = RegionFrame(region, bounds); + return new Avalonia.Rect(frame.X + 4, frame.Y + 4, Math.Max(140, name.Length * 9 + 60), 26); + } + + private List RerouteOf(InputPin pin) { + var layout = Session!.Layout; + if (!layout.Reroutes.TryGetValue(pin, out var offsets)) return []; + var origin = layout.Position(InlineRules.Drawn(pin.Owner)); + return offsets.Select(o => new Point(origin.X + o.X, origin.Y + o.Y)).ToList(); + } + + private static double Reach(Point a, Point b) => Math.Max(40, Math.Min(260, Math.Abs(b.X - a.X) * 0.55 + Math.Abs(b.Y - a.Y) * 0.1)); + + private List ExecThrough(Statement to) { + var layout = Session!.Layout; + if (!layout.ExecReroutes.TryGetValue(to, out var offsets)) return []; + var origin = layout.Position(to); + return offsets.Select(o => new Point(origin.X + o.X, origin.Y + o.Y)).ToList(); + } + + private static StreamGeometry WireGeometry(Point from, IReadOnlyList through, Point to) { + var geometry = new StreamGeometry(); + using var g = geometry.Open(); + var chain = new List { from }; + chain.AddRange(through); + chain.Add(to); + g.BeginFigure(from, false); + for (var i = 0; i < chain.Count - 1; i++) { + var a = chain[i]; + var b = chain[i + 1]; + var reach = Reach(a, b); + g.CubicBezierTo(new Point(a.X + reach, a.Y), new Point(b.X - reach, b.Y), b); + } + g.EndFigure(false); + return geometry; + } + + private static Point OnBezier(Point a, Point b, double t) { + var reach = Reach(a, b); + var c1 = new Point(a.X + reach, a.Y); + var c2 = new Point(b.X - reach, b.Y); + var u = 1 - t; + return new Point(u * u * u * a.X + 3 * u * u * t * c1.X + 3 * u * t * t * c2.X + t * t * t * b.X, u * u * u * a.Y + 3 * u * u * t * c1.Y + 3 * u * t * t * c2.Y + t * t * t * b.Y); + } + + private (object? Wire, int Index) RerouteAt(Vec world) { + if (Session is null) return (null, -1); + var radius = 8 / Zoom; + bool Near(Point p) => (p.X - world.X) * (p.X - world.X) + (p.Y - world.Y) * (p.Y - world.Y) <= radius * radius; + foreach (var (pin, _) in Session.Layout.Reroutes) { + if (IsModuleSetupNode(InlineRules.Drawn(pin.Owner))) continue; + var points = RerouteOf(pin); + for (var i = 0; i < points.Count; i++) + if (Near(points[i])) return (pin, i); + } + foreach (var (statement, _) in Session.Layout.ExecReroutes) { + if (IsModuleSetupNode(statement)) continue; + var points = ExecThrough(statement); + for (var i = 0; i < points.Count; i++) + if (Near(points[i])) return (statement, i); + } + return (null, -1); + } + + private int WireSegmentAt(Vec world, Point start, IReadOnlyList bends, Point end, double reach) { + var chain = new List { start }; + chain.AddRange(bends); + chain.Add(end); + for (var i = 0; i < chain.Count - 1; i++) { + var previous = chain[i]; + for (var step = 1; step <= 32; step++) { + var point = OnBezier(chain[i], chain[i + 1], step / 32.0); + var edge = point - previous; + var length = edge.X * edge.X + edge.Y * edge.Y; + var along = length == 0 ? 0 : Math.Clamp(((world.X - previous.X) * edge.X + (world.Y - previous.Y) * edge.Y) / length, 0, 1); + var dx = previous.X + along * edge.X - world.X; + var dy = previous.Y + along * edge.Y - world.Y; + if (dx * dx + dy * dy <= reach * reach) return i; + previous = point; + } + } + return -1; + } + + private Point? FrameReturnSource(InputPin pin) { + if (pin.Source is not { } source || (Session!.Layout.CallableSlot(pin) ?? SlotFor(source)) is not { } from) return null; + return IsModuleSetupNode(from.Node) ? null : Session.Layout.IsHidden(from.Node) ? FrameRailPoint(from) : SlotPoint(from); + } + + private (InputPin? Pin, int Segment) WireAt(Vec world) { + if (Session is null) return (null, -1); + var layout = Session.Layout; + var reach = 6 / Zoom; + foreach (var node in VisibleNodes()) { + if (NodeShape.ExpansionOf(node) is { } frame) + foreach (var port in FrameReturns(node, frame.Callee)) + if (port.Input is { } input && FrameReturnSource(input) is { } source && + WireSegmentAt(world, source, RerouteOf(input), port.Point, reach) is >= 0 and var segment) + return (input, segment); + foreach (var slot in SlotsOf(node)) { + if (slot.In is not { Source: { } source } pin || (layout.CallableSlot(pin) ?? SlotFor(source)) is not { } from || from.Node == node) continue; + if (IsModuleSetupNode(from.Node)) continue; + Point? start; + if (layout.IsHidden(from.Node)) start = FrameRailPoint(from); + else { + if (layout.CallableSlot(pin) is null && source.Binding is not null && + (source.Consumers.Count >= ProxyThreshold || layout.Keys.RegionOf(from.Node) != layout.Keys.RegionOf(node))) continue; + start = SlotPoint(from); + } + if (start is { } point && WireSegmentAt(world, point, RerouteOf(pin), SlotPoint(slot), reach) is >= 0 and var segment) + return (pin, segment); + } + } + return (null, -1); + } + + private (Statement? To, int Segment) ExecWireAt(Vec world) { + if (Session is null) return (null, -1); + var reach = 14 / Zoom; + (Statement?, int) hit = (null, -1); + ForEachExecLink(null, (from, to) => { + if (hit.Item1 is not null || !Session.Layout.IsPlaced(to) || Session.Layout.IsHidden(to)) return; + if (SlotsOf(to).FirstOrDefault(s => s.Kind == SlotKind.ExecIn) is not { } target) return; + var segment = WireSegmentAt(world, SlotPoint(from), ExecThrough(to), SlotPoint(target), reach); + if (segment >= 0) hit = (to, segment); + }); + if (hit.Item1 is not null) return hit; + foreach (var host in VisibleNodes()) { + if (NodeShape.ExpansionOf(host) is not { } frame) continue; + foreach (var (key, start, end) in FrameExecWires(host, frame.Callee)) { + var segment = WireSegmentAt(world, start, ExecThrough(key), end, reach); + if (segment >= 0) return (key, segment); + } + } + return hit; + } + + private static StreamGeometry Bezier(Point from, Point to) { + + var geometry = new StreamGeometry(); + using var g = geometry.Open(); + var reach = Math.Max(40, Math.Min(260, Math.Abs(to.X - from.X) * 0.55 + Math.Abs(to.Y - from.Y) * 0.1)); + g.BeginFigure(from, false); + g.CubicBezierTo(new Point(from.X + reach, from.Y), new Point(to.X - reach, to.Y), to); + g.EndFigure(false); + return geometry; + } + + private void DrawWires(DrawingContext context, CanvasTheme theme, Avalonia.Rect view, RegionInfo? only = null) { + var session = Session!; + var layout = session.Layout; + var selected = session.Selection.ToHashSet(); + foreach (var node in VisibleNodes(only)) { + foreach (var slot in SlotsOf(node)) { + if (slot.Kind != SlotKind.DataIn || slot.In?.Source is not { } source) continue; + if ((Session!.Layout.CallableSlot(slot.In) ?? SlotFor(source)) is not { } from || from.Node == node) continue; + if (IsModuleSetupNode(from.Node)) { + if (source.Binding is not null) DrawProxy(context, theme, source, SlotPoint(slot), PinStyle.ColorOf(source.Type), slot.In); + continue; + } + if (layout.IsHidden(from.Node)) { + var rail = FrameRailPoint(from); + var target = SlotPoint(slot); + var tint = PinStyle.ColorOf(source.Type); + if (rail is { } start) DrawRoutedData(context, theme, slot.In, start, target, tint); + else DrawProxy(context, theme, source, target, tint, slot.In); + continue; + } + + if (only is null && layout.Keys.RegionOf(from.Node) is { } fromRegion && layout.CollapsedRegions.Contains(fromRegion.Body)) continue; + var a = SlotPoint(from); + var b = SlotPoint(slot); + if (!new Avalonia.Rect(Math.Min(a.X, b.X), Math.Min(a.Y, b.Y), Math.Abs(a.X - b.X) + 1, Math.Abs(a.Y - b.Y) + 1).Intersects(view)) continue; + var color = PinStyle.ColorOf(source.Type); + var otherRegion = layout.Keys.RegionOf(from.Node) != layout.Keys.RegionOf(node); + if (only is null && layout.CallableSlot(slot.In) is null && source.Binding is not null && (source.Consumers.Count >= ProxyThreshold || otherRegion)) { + DrawProxy(context, theme, source, b, color, slot.In); + continue; + } + var dim = selected.Count > 0 && !selected.Contains(node) && !selected.Contains(from.Node); + var bad = m_pinProblems.ContainsKey(slot.In); + var pen = bad ? new Pen(theme.Error, 2.5, lineCap: PenLineCap.Round) : theme.WirePen(color, dim, slot.In == m_hoverWire ? 3.8 : 2); + var through = RerouteOf(slot.In); + context.DrawGeometry(null, pen, through.Count > 0 ? WireGeometry(a, through, b) : RoutedWire(a, b, from.Node, node)); + foreach (var point in through) context.DrawEllipse(new SolidColorBrush(Color.Parse(color)), new Pen(theme.NodeBody, 1.5), point, 4.5, 4.5); + } + } + DrawExecWires(context, theme, view, only); + } + + private static void DrawPinGlyph(DrawingContext context, Point p, LuaType type, Color color) { + var brush = new SolidColorBrush(color); + var pen = new Pen(brush, 1.8); + var r = PinRadius; + switch (PinStyle.ShapeOf(type)) { + case PinShape.Diamond: + var diamond = new StreamGeometry(); + using (var g = diamond.Open()) { + g.BeginFigure(new Point(p.X, p.Y - r - 1), true); + g.LineTo(new Point(p.X + r + 1, p.Y)); + g.LineTo(new Point(p.X, p.Y + r + 1)); + g.LineTo(new Point(p.X - r - 1, p.Y)); + g.EndFigure(true); + } + context.DrawGeometry(brush, pen, diamond); + break; + case PinShape.Triangle: + var triangle = new StreamGeometry(); + using (var g = triangle.Open()) { + g.BeginFigure(new Point(p.X - r, p.Y - r - 1), true); + g.LineTo(new Point(p.X + r + 2, p.Y)); + g.LineTo(new Point(p.X - r, p.Y + r + 1)); + g.EndFigure(true); + } + context.DrawGeometry(brush, pen, triangle); + break; + case PinShape.Square or PinShape.Stack: + context.DrawRectangle(brush, pen, new Avalonia.Rect(p.X - r, p.Y - r, r * 2, r * 2), 1.5, 1.5); + break; + case PinShape.Pair: + editor.LuaEditor.Controls.PinGlyph.DrawPair(context, p, color, r * 0.65); + break; + default: + context.DrawEllipse(brush, pen, p, r, r); + break; + } + } + + private Avalonia.Rect ProxyRect(InputPin? pin, OutputPin source, Point target) { + var width = CanvasTheme.Default.Format(source.Name, 11, CanvasTheme.Default.Text, true).Width + 14; + var rect = new Avalonia.Rect(target.X - 16 - width, target.Y - 9, width, 18); + return pin is not null && Session!.Layout.ProxyOffsets.TryGetValue(pin, out var offset) ? rect.Translate(new Vector(offset.X, offset.Y)) : rect; + } + + private InputPin? ProxyAt(Vec world) { + if (Session is null) return null; + var layout = Session.Layout; + foreach (var node in VisibleNodes()) { + foreach (var slot in SlotsOf(node)) { + if (slot.Kind != SlotKind.DataIn || slot.In?.Source is not { } source || (Session!.Layout.CallableSlot(slot.In) ?? SlotFor(source)) is not { } from || from.Node == node) continue; + var tagged = layout.CallableSlot(slot.In) is null && (layout.IsHidden(from.Node) ? FrameRailPoint(from) is null : source.Binding is not null && (source.Consumers.Count >= ProxyThreshold || layout.Keys.RegionOf(from.Node) != layout.Keys.RegionOf(node))); + if (tagged && ProxyRect(slot.In, source, SlotPoint(slot)).Inflate(3).Contains(new Point(world.X, world.Y))) return slot.In; + } + } + return null; + } + + private void DrawProxy(DrawingContext context, CanvasTheme theme, OutputPin source, Point target, string color, InputPin? pin = null) { + var text = theme.Format(source.Name, 11, theme.Text, true); + var rect = ProxyRect(pin, source, target); + var c = Color.Parse(color); + var selected = pin is not null && pin == m_selectedProxy; + context.DrawGeometry(null, new Pen(new SolidColorBrush(c, 0.9), 2, lineCap: PenLineCap.Round), Bezier(new Point(rect.Right, rect.Center.Y), target)); + DrawPinGlyph(context, new Point(rect.Right, rect.Center.Y), source.Type, c); + context.DrawRectangle(new SolidColorBrush(c, 0.28), selected ? theme.SelectedBorder : new Pen(new SolidColorBrush(c, 0.9), 1), rect, 9, 9); + + context.DrawText(text, new Point(rect.X + 7, rect.Y + (rect.Height - text.Height) / 2)); + } + + private void DrawExecWires(DrawingContext context, CanvasTheme theme, Avalonia.Rect view, RegionInfo? only = null) => ForEachExecLink(only, (from, to) => DrawExec(context, theme, from, to, view)); + + private void ForEachExecLink(RegionInfo? only, Action link) { + var layout = Session!.Layout; + foreach (var region in CanvasRegions()) { + if (only is not null && region != only) continue; + if (only is null && layout.CollapsedRegions.Contains(region.Body)) continue; + if (region.Entry is not null && !InlineRules.IsMerged(region.Entry) && layout.IsPlaced(region.Entry) && !layout.IsHidden(region.Entry)) { + var slot = SlotsOf(region.Entry).FirstOrDefault(s => s.Kind == SlotKind.ExecOut); + if (slot is not null) LinkBlock(link, slot, region.Body); + } + foreach (var node in layout.NodesOf(region)) { + if (node is not Statement statement || InlineRules.IsMerged(node) || !layout.IsPlaced(node) || layout.IsHidden(node) || statement.Parent is null) continue; + var slots = SlotsOf(statement); + foreach (var slot in slots.Where(s => s.Kind == SlotKind.ExecOut && s.Child is not null)) LinkBlock(link, slot, slot.Child!); + if (!NodeShape.HasContinuation(statement)) continue; + var next = NextInChain(statement); + var continuation = slots.LastOrDefault(s => s.Kind == SlotKind.ExecOut && s.Child is null); + if (next is null || continuation is null) continue; + link(continuation, next); + } + } + } + + private static Statement? NextInChain(Statement statement) { + var block = statement.Parent!; + for (var i = block.IndexOf(statement) + 1; i < block.Statements.Count; i++) + if (NodeShape.HasExecutionIn(block.Statements[i]) && !block.Statements[i].IsFloating) return block.Statements[i]; + return null; + } + + private static void LinkBlock(Action link, Slot from, Block block) { + var first = block.Statements.FirstOrDefault(s => !s.IsFloating && NodeShape.HasExecutionIn(s)); + if (first is not null) link(from, first); + } + + private void DrawExec(DrawingContext context, CanvasTheme theme, Slot from, Statement to, Avalonia.Rect view) { + if (!Session!.Layout.IsPlaced(to) || Session.Layout.IsHidden(to)) return; + var target = SlotsOf(to).FirstOrDefault(s => s.Kind == SlotKind.ExecIn); + if (target is null) return; + var a = SlotPoint(from); + var b = SlotPoint(target); + if (!new Avalonia.Rect(Math.Min(a.X, b.X), Math.Min(a.Y, b.Y), Math.Abs(a.X - b.X) + 1, Math.Abs(a.Y - b.Y) + 1).Intersects(view)) return; + var through = ExecThrough(to); + context.DrawGeometry(null, theme.ExecWire, through.Count > 0 ? WireGeometry(a, through, b) : Bezier(a, b)); + foreach (var point in through) context.DrawEllipse(Brushes.White, new Pen(theme.NodeBody, 1.5), point, 4.5, 4.5); + } + + public static Avalonia.Rect ToggleButtonRect(Avalonia.Rect node) => new(node.X + 6, node.Y + 4, 22, 20); + + private void DrawToggleButton(DrawingContext context, CanvasTheme theme, Avalonia.Rect node, bool open, IBrush ink) { + var button = ToggleButtonRect(node); + context.DrawRectangle(new SolidColorBrush(Color.Parse("#000000"), 0.28), new Pen(new SolidColorBrush(Color.Parse("#ffffff"), 0.55), 1.2), button, 5, 5); + var cx = button.X + button.Width / 2; + var cy = button.Y + button.Height / 2; + var dy = open ? -2.5 : 2.5; + var arrow = new StreamGeometry(); + using (var g = arrow.Open()) { + g.BeginFigure(new Point(cx - 5, cy - dy), false); + g.LineTo(new Point(cx, cy + dy)); + g.LineTo(new Point(cx + 5, cy - dy)); + g.EndFigure(false); + } + context.DrawGeometry(null, new Pen(ink, 2, lineCap: PenLineCap.Round, lineJoin: PenLineJoin.Round), arrow); + } + + private void DrawNodes(DrawingContext context, CanvasTheme theme, Avalonia.Rect view, RegionInfo? only = null) { + var session = Session!; + var selected = session.Selection.ToHashSet(); + var detailed = Zoom >= 0.4; + foreach (var node in VisibleNodes(only)) { + var rect = NodeRect(node); + if (!rect.Intersects(view)) continue; + if (NodeShape.ExpansionOf(node) is not null) continue; + var look = NodeShape.LookOf(node); + if (node is CommentStatement) { + DrawNote(context, theme, node, rect, selected.Contains(node)); + continue; + } + var border = selected.Contains(node) ? theme.SelectedBorder + : m_nodeSeverity.TryGetValue(node, out var severity) ? severity == DiagnosticSeverity.Error ? theme.ErrorBorder : theme.WarningBorder + : theme.NodeBorder; + if (InlineRules.IsGetterNode(node)) { + DrawGetterTag(context, theme, node, rect, border, detailed); + continue; + } + var loose = session.Layout.Loose.Contains(node); + context.DrawRectangle(loose ? theme.NodeBodyDim : theme.NodeBody, border, rect, 7, 7); + + context.DrawRectangle(theme.HeaderOf(look), null, new Avalonia.Rect(rect.X + 1, rect.Y + 1, rect.Width - 2, DefaultMeasure.HeaderHeight - 2), 6, 6); + if (!detailed) continue; + var openable = session.CanOpen(node); + if (openable) DrawToggleButton(context, theme, rect, open: false, theme.HeaderTextOf(look)); + context.DrawText(theme.Format(NodeShape.TitleOf(node), 12.5, theme.HeaderTextOf(look), true), new Point(rect.X + (openable ? 36 : 10), rect.Y + 6)); + foreach (var slot in SlotsOf(node)) DrawSlot(context, theme, slot, rect); + if (node is TableNode table) DrawTableAdd(context, theme, table, rect); + } + } + + public static Avalonia.Rect TableAddRect(Avalonia.Rect node) => new(node.X + 10, node.Bottom - 26, 96, 20); + + public static TableFieldKind TableGrowsBy(TableNode table) => GraphSession.EntryKindOf(table); + + private void DrawTableAdd(DrawingContext context, CanvasTheme theme, TableNode table, Avalonia.Rect rect) { + var button = TableAddRect(rect); + context.DrawRectangle(new SolidColorBrush(Color.Parse("#ffffff"), 0.10), new Pen(new SolidColorBrush(Color.Parse("#ffffff"), 0.35), 1), button, 5, 5); + var text = theme.Format(table.Flavor switch { TableFlavor.Array => "+ item", TableFlavor.Dictionary => "+ entry", _ => "+ field" }, 11, theme.Text, true); + context.DrawText(text, new Point(button.X + 10, button.Y + (button.Height - text.Height) / 2)); + } + + private void DrawGetterTag(DrawingContext context, CanvasTheme theme, GraphNode node, Avalonia.Rect rect, Pen border, bool detailed) { + var slot = SlotsOf(node).FirstOrDefault(s => s.Kind == SlotKind.DataOut); + var type = slot?.Out?.Type ?? LuaType.Any; + var tint = Color.Parse(PinStyle.ColorOf(type)); + var selected = Session!.Selection.Contains(node); + context.DrawRectangle(new SolidColorBrush(tint, 0.28), selected ? theme.SelectedBorder : new Pen(new SolidColorBrush(tint, 0.9), 1), rect, rect.Height / 2, rect.Height / 2); + if (detailed) { + var text = theme.Format(NodeShape.TitleOf(node), 11, theme.Text, true); + context.DrawText(text, new Point(rect.X + 10, rect.Y + (rect.Height - text.Height) / 2)); + } + foreach (var pin in SlotsOf(node)) DrawSlot(context, theme, pin, rect); + } + + private void DrawFrames(DrawingContext context, CanvasTheme theme, Avalonia.Rect view) { + var selected = Session!.Selection.ToHashSet(); + foreach (var node in VisibleNodes()) { + if (NodeShape.ExpansionOf(node) is not { } frame) continue; + var rect = NodeRect(node); + if (rect.Intersects(view)) DrawFrame(context, theme, node, rect, frame.Callee, selected.Contains(node)); + } + } + + private Point? FrameRailPoint(Slot entryOutput) { + var layout = Session!.Layout; + if (entryOutput.Out?.Owner is not FunctionEntry entry || layout.Keys.RegionOf(entry) is not { } region || !layout.Embedded.TryGetValue(region.Body, out var host)) return null; + var index = entry.Params.FindIndex(p => p.Output == entryOutput.Out); + var rows = SlotsOf(host).Where(s => s.Kind == SlotKind.DataIn).ToList(); + if (index < 0 || index >= rows.Count) return null; + var rect = NodeRect(host); + return new Point(rect.X + DefaultMeasure.Rails(host).Left, SlotPoint(rows[index]).Y); + } + + private void DrawFrame(DrawingContext context, CanvasTheme theme, GraphNode node, Avalonia.Rect rect, FunctionDecl callee, bool selected) { + var layout = Session!.Layout; + var look = NodeShape.LookOf(node); + var accent = theme.HeaderOf(look); + var accentColor = accent is ISolidColorBrush solid ? solid.Color : Color.Parse("#29adff"); + var (railLeft, railRight) = DefaultMeasure.Rails(node); + + context.DrawRectangle(new SolidColorBrush(Color.Parse("#1c1b20")), selected ? theme.SelectedBorder : new Pen(new SolidColorBrush(accentColor, 0.75), 2), rect, 8, 8); + context.DrawRectangle(accent, null, new Avalonia.Rect(rect.X + 1, rect.Y + 1, rect.Width - 2, DefaultMeasure.HeaderHeight - 2), 7, 7); + DrawToggleButton(context, theme, rect, open: true, theme.HeaderTextOf(look)); + context.DrawText(theme.Format(callee.Name + "()", 12.5, theme.HeaderTextOf(look), true), new Point(rect.X + 36, rect.Y + 6)); + + var body = new Avalonia.Rect(rect.X + 1, rect.Y + DefaultMeasure.HeaderHeight, rect.Width - 2, rect.Height - DefaultMeasure.HeaderHeight - 1); + var rail = new SolidColorBrush(Color.Parse("#454343")); + context.DrawRectangle(rail, null, new Avalonia.Rect(body.X, body.Y, railLeft, body.Height)); + context.DrawRectangle(rail, null, new Avalonia.Rect(body.Right - railRight, body.Y, railRight, body.Height)); + var floor = new Avalonia.Rect(body.X + railLeft, body.Y, body.Width - railLeft - railRight, body.Height); + context.DrawRectangle(new SolidColorBrush(Color.Parse("#121115")), null, floor); + var line = new Pen(new SolidColorBrush(Color.Parse("#ffffff"), 0.05), 1); + for (var x = floor.X + 32; x < floor.Right; x += 32) context.DrawLine(line, new Point(x, floor.Y), new Point(x, floor.Bottom)); + for (var y = floor.Y + 32; y < floor.Bottom; y += 32) context.DrawLine(line, new Point(floor.X, y), new Point(floor.Right, y)); + + foreach (var slot in SlotsOf(node)) { + DrawSlot(context, theme, slot, rect); + if (slot.IsCallableReference || slot.Kind == SlotKind.DataOut) continue; + var inner = FrameExecPoint(slot); + if (slot.IsExec) DrawArrow(context, theme, inner, connected: true, hot: false); + else { + var type = slot.In?.Source?.Type ?? slot.In?.Expected ?? LuaType.Any; + context.DrawEllipse(new SolidColorBrush(Color.Parse(PinStyle.ColorOf(type))), new Pen(rail, 1.5), inner, 5, 5); + } + } + foreach (var (key, start, end) in FrameExecWires(node, callee)) { + var bends = ExecThrough(key); + context.DrawGeometry(null, theme.ExecWire, WireGeometry(start, bends, end)); + foreach (var point in bends) context.DrawEllipse(Brushes.White, new Pen(theme.NodeBody, 1.5), point, 4.5, 4.5); + } + foreach (var port in FrameReturns(node, callee)) { + var color = new SolidColorBrush(Color.Parse(PinStyle.ColorOf(port.Input?.Source?.Type ?? port.Input?.Expected ?? LuaType.Any))); + context.DrawEllipse(port.Input is null ? rail : color, new Pen(color, 1.5), port.Point, 5, 5); + if (port.Input is { } input) DrawFrameReturn(context, theme, input, port.Point); + else { + var label = theme.Format("return", 11, theme.TextMuted); + context.DrawText(label, new Point(port.Point.X + 9, port.Point.Y - label.Height / 2)); + } + } + } + + private IEnumerable<(Statement Key, Point Start, Point End)> FrameExecWires(GraphNode host, FunctionDecl function) { + var layout = Session!.Layout; + var slots = SlotsOf(host); + var body = function.Entry.Body; + var enter = slots.FirstOrDefault(s => s.Kind == SlotKind.ExecIn); + var exit = slots.FirstOrDefault(s => s.Kind == SlotKind.ExecOut && s.Child is null); + var first = body.Statements.FirstOrDefault(s => !s.IsFloating && NodeShape.HasExecutionIn(s) && !layout.IsHidden(s)); + if (enter is not null && first is not null && layout.IsPlaced(first) && + SlotsOf(first).FirstOrDefault(s => s.Kind == SlotKind.ExecIn) is { } entry) + yield return (first, FrameExecPoint(enter), SlotPoint(entry)); + var last = FrameTail(body); + if (exit is not null && last is not null && layout.IsPlaced(last) && + SlotsOf(last).LastOrDefault(s => s.Kind == SlotKind.ExecOut && s.Child is null) is { } tail) + yield return (function, SlotPoint(tail), FrameExecPoint(exit)); + else if (first is null && enter is not null && exit is not null) + yield return (function, FrameExecPoint(enter), FrameExecPoint(exit)); + } + + private void DrawRoutedData(DrawingContext context, CanvasTheme theme, InputPin pin, Point start, Point end, string color) { + var bends = RerouteOf(pin); + context.DrawGeometry(null, theme.WirePen(color, width: pin == m_hoverWire ? 3.8 : 2), WireGeometry(start, bends, end)); + foreach (var point in bends) + context.DrawEllipse(new SolidColorBrush(Color.Parse(color)), new Pen(theme.NodeBody, 1.5), point, 4.5, 4.5); + } + + private void DrawFrameReturn(DrawingContext context, CanvasTheme theme, InputPin value, Point end) { + if (value.Source is { } source) { + var color = PinStyle.ColorOf(source.Type); + if (FrameReturnSource(value) is { } point) DrawRoutedData(context, theme, value, point, end, color); + else DrawProxy(context, theme, source, end, color, value); + } else if (value.Constant is { } literal) { + var text = theme.Format(literal.Raw, 11, theme.Text); + context.DrawText(text, new Point(end.X - text.Width - 9, end.Y - text.Height / 2)); + } + } + + private void DrawNote(DrawingContext context, CanvasTheme theme, GraphNode node, Avalonia.Rect rect, bool selected) { + context.DrawRectangle(new SolidColorBrush(Color.Parse("#665f10"), 0.4), selected ? theme.SelectedBorder : new Pen(new SolidColorBrush(Color.Parse("#ffec27"), 0.5), 1), new Avalonia.Rect(rect.X, rect.Y, rect.Width, DefaultMeasure.HeaderHeight + 4), 6, 6); + if (Zoom >= 0.4) context.DrawText(theme.Format(NodeShape.TitleOf(node), 12, theme.Text), new Point(rect.X + 10, rect.Y + 7)); + } + + private void DrawSlot(DrawingContext context, CanvasTheme theme, Slot slot, Avalonia.Rect rect) { + var p = SlotPoint(slot); + var hot = m_hoverSlot is { } h && h.Node == slot.Node && h.Row == slot.Row && h.Kind == slot.Kind; + if (slot.IsExec) { + var connected = IsExecConnected(slot); + DrawArrow(context, theme, p, connected, hot); + if (slot.Label.Length > 0) DrawLabel(context, theme, slot, p); + return; + } + + var type = PinTypeOf(slot); + var color = Color.Parse(PinStyle.ColorOf(type)); + var connectedData = (slot.In?.Source is not null && InlineRules.EnumValueOf(slot.In) is null) || (slot.Out is { } o && o.Consumers.Count > 0); + var brush = connectedData ? new SolidColorBrush(color) : null; + var pen = new Pen(new SolidColorBrush(color), hot ? 2.5 : 1.8); + var radius = hot ? PinRadius + 1.5 : PinRadius; + switch (PinStyle.ShapeOf(type)) { + case PinShape.Diamond: + var diamond = new StreamGeometry(); + using (var g = diamond.Open()) { + g.BeginFigure(new Point(p.X, p.Y - radius - 1), true); + g.LineTo(new Point(p.X + radius + 1, p.Y)); + g.LineTo(new Point(p.X, p.Y + radius + 1)); + g.LineTo(new Point(p.X - radius - 1, p.Y)); + g.EndFigure(true); + } + context.DrawGeometry(brush ?? theme.NodeBody, pen, diamond); + break; + case PinShape.Pair: + editor.LuaEditor.Controls.PinGlyph.DrawPair(context, p, color, radius * 0.65, brush is not null); + break; + case PinShape.Hexagon: + var hexagon = new StreamGeometry(); + using (var g = hexagon.Open()) { + var r = radius + 1.5; + g.BeginFigure(new Point(p.X - r, p.Y), true); + g.LineTo(new Point(p.X - r / 2, p.Y - r * 0.87)); + g.LineTo(new Point(p.X + r / 2, p.Y - r * 0.87)); + g.LineTo(new Point(p.X + r, p.Y)); + g.LineTo(new Point(p.X + r / 2, p.Y + r * 0.87)); + g.LineTo(new Point(p.X - r / 2, p.Y + r * 0.87)); + g.EndFigure(true); + } + context.DrawGeometry(brush ?? theme.NodeBody, pen, hexagon); + break; + case PinShape.Triangle: + var triangle = new StreamGeometry(); + using (var g = triangle.Open()) { + g.BeginFigure(new Point(p.X - radius, p.Y - radius - 1), true); + g.LineTo(new Point(p.X + radius + 2, p.Y)); + g.LineTo(new Point(p.X - radius, p.Y + radius + 1)); + g.EndFigure(true); + } + context.DrawGeometry(brush ?? theme.NodeBody, pen, triangle); + break; + case PinShape.Stack: + var back = new Avalonia.Rect(p.X - radius, p.Y - radius, radius * 2, radius * 2); + context.DrawRectangle(brush ?? theme.NodeBody, pen, back, 1.5, 1.5); + var inkPen = new Pen(brush is null ? new SolidColorBrush(color) : theme.NodeBody, 1.1); + context.DrawLine(inkPen, new Point(p.X - radius + 1.5, p.Y), new Point(p.X + radius - 1.5, p.Y)); + context.DrawLine(inkPen, new Point(p.X, p.Y - radius + 1.5), new Point(p.X, p.Y + radius - 1.5)); + break; + case PinShape.Square: + context.DrawRectangle(brush ?? theme.NodeBody, pen, new Avalonia.Rect(p.X - radius, p.Y - radius, radius * 2, radius * 2), 1.5, 1.5); + break; + default: + context.DrawEllipse(brush ?? theme.NodeBody, pen, p, radius, radius); + break; + } + + if (PinStyle.IsOptional(type)) context.DrawEllipse(Brushes.Black, null, p, 2.4, 2.4); + if (!InlineRules.IsGetterNode(slot.Node)) DrawLabel(context, theme, slot, p); +if (slot.In is { } pin && (pin.Source is null || InlineRules.InlineValueOf(pin) is not null)) DrawConstant(context, theme, slot, pin, p); + } + + private static LuaType PinTypeOf(Slot slot) { + if (slot.In?.Source?.Type is { } wired) return wired; + var expected = slot.In?.Expected; + if (expected is not null && expected is not PrimitiveType { Kind: PrimitiveKind.Any or PrimitiveKind.Unknown }) return expected; + if (slot.In?.Constant is { } constant) + return constant.Kind switch { + ConstantKind.Number => LuaType.Number, + ConstantKind.String => LuaType.String, + ConstantKind.Boolean => LuaType.Boolean, + _ => expected ?? LuaType.Any + }; + return expected ?? slot.Out?.Type ?? LuaType.Any; + } + + private Statement? FrameTail(Block body) => body.Statements.LastOrDefault(s => + !s.IsFloating && NodeShape.HasExecutionIn(s) && !Session!.Layout.IsHidden(s)) is { } tail && NodeShape.HasContinuation(tail) ? tail : null; + + private bool IsExecConnected(Slot slot) { + if (slot.Node is Statement { IsFloating: true }) return false; + if (slot.Kind == SlotKind.ExecIn) return slot.Node is Statement { Parent: not null }; + if (slot.Child is { } child) return child.Statements.Any(NodeShape.HasExecutionIn); + return slot.Node is Statement s && (NextInChain(s) is not null || + s.Parent is { } body && Session!.Layout.Embedded.ContainsKey(body) && FrameTail(body) == s); + } + + private static void DrawArrow(DrawingContext context, CanvasTheme theme, Point p, bool connected, bool hot) { + var geometry = new StreamGeometry(); + using (var g = geometry.Open()) { + g.BeginFigure(new Point(p.X - 5, p.Y - 6), true); + g.LineTo(new Point(p.X + 4, p.Y - 6)); + g.LineTo(new Point(p.X + 8, p.Y)); + g.LineTo(new Point(p.X + 4, p.Y + 6)); + g.LineTo(new Point(p.X - 5, p.Y + 6)); + g.EndFigure(true); + } + context.DrawGeometry(connected ? theme.Exec : null, new Pen(theme.Exec, hot ? 2.5 : 1.6), geometry); + } + + private void DrawLabel(DrawingContext context, CanvasTheme theme, Slot slot, Point p) { + if (slot.Label.Length == 0) return; + if (slot.In is { } valuePin && KeyOfRow(valuePin) is { } key) { + var keyText = theme.Format(NodeShape.KeyText(key), 11, key.Constant?.Kind == ConstantKind.String ? new SolidColorBrush(Color.Parse(PinStyle.Text)) : theme.Text); + var keyBox = KeyBoxRect(slot, p); + context.DrawRectangle(theme.ConstantBox, new Pen(m_pinProblems.ContainsKey(key) ? theme.Error : new SolidColorBrush(Color.Parse("#454343")), 1), keyBox, 3, 3); + context.DrawText(keyText, new Point(keyBox.X + 5, keyBox.Y + (keyBox.Height - keyText.Height) / 2)); + return; + } + var text = theme.Format(slot.Label, 11.5, theme.TextMuted); + var x = slot.IsLeft ? p.X + 12 : p.X - 12 - text.Width; + context.DrawText(text, new Point(x, p.Y - text.Height / 2)); + } + + private static InputPin? KeyOfRow(InputPin value) => value.Owner is TableNode table && table.Fields.FirstOrDefault(f => f.Value == value) is { Kind: TableFieldKind.Keyed, Key: { Source: null } key } ? key : null; + + private static Avalonia.Rect KeyBoxRect(Slot slot, Point p) { + var width = CanvasTheme.Default.Format(slot.Label, 11.5, CanvasTheme.Default.TextMuted).Width; + return new Avalonia.Rect(p.X + 10, p.Y - 8, width + 4, 16); + } + + private void DrawConstant(DrawingContext context, CanvasTheme theme, Slot slot, InputPin pin, Point p) { + var label = theme.Format(slot.Label, 11.5, theme.TextMuted); + var box = ConstantRect(slot, p, label.Width); + if (GraphSession.IsBoolean(pin) && pin.Source is null) { + var check = new Avalonia.Rect(box.X, p.Y - 7, 14, 14); + var on = pin.Constant?.Raw == "true"; + context.DrawRectangle(on ? new SolidColorBrush(Color.Parse(PinStyle.Boolean)) : theme.ConstantBox, new Pen(new SolidColorBrush(Color.Parse(PinStyle.Boolean)), 1.2), check, 3, 3); + if (on) context.DrawText(theme.Format("✓", 11, new SolidColorBrush(Color.Parse("#121111")), true), new Point(check.X + 2.5, check.Y - 0.5)); + context.DrawText(theme.Format(on ? "true" : "false", 11, theme.TextMuted), new Point(check.Right + 6, p.Y - 7)); + return; + } + var enumValue = InlineRules.EnumValueOf(pin); + var isList = enumValue is not null || (Session?.ChoicesFor(pin) is not null); + var text = enumValue ?? (pin.Constant is { } literal ? GraphSession.DisplayText(literal) : "nil"); + var room = (int)((DefaultMeasure.ConstantWidth(pin) - (isList ? 20 : 10)) / 6.0); + if (text.Length > room) text = text[..Math.Max(1, room - 1)] + "…"; + var problem = m_pinProblems.ContainsKey(pin); + context.DrawRectangle(theme.ConstantBox, new Pen(problem ? theme.Error : new SolidColorBrush(Color.Parse("#454343")), 1), box, 3, 3); + var value = theme.Format(text, 11, pin.Constant is null ? theme.TextMuted : pin.Constant.Kind == ConstantKind.String ? new SolidColorBrush(Color.Parse(PinStyle.Text)) : theme.Text); + context.DrawText(value, new Point(box.X + 5, box.Y + (box.Height - value.Height) / 2)); + if (isList) context.DrawText(theme.Format("▾", 10, theme.TextMuted), new Point(box.Right - 13, box.Y + 1.5)); + } + + private static Avalonia.Rect ConstantRect(Slot slot, Point p, double labelWidth) => new(p.X + 18 + labelWidth, p.Y - 8, slot.In is { } pin ? DefaultMeasure.ConstantWidth(pin) : ConstantBoxWidth, 16); + + private void DrawDragPreview(DrawingContext context, CanvasTheme theme) { + switch (m_drag) { + case DragMode.Wire when m_wireFromOutput is not null || m_wireFromInput is not null || m_wireFromReturn is not null: { + var anchorSlot = m_wireFromOutput is not null ? SlotFor(m_wireFromOutput) : m_wireFromInput is { } input ? SlotFor(input) : null; + if (anchorSlot is null && m_wireAnchor is null) break; + var anchor = m_wireAnchor ?? SlotPoint(anchorSlot!); + var type = m_wireFromOutput?.Type ?? m_wireFromInput?.Expected ?? LuaType.Any; + var ok = (m_hoverTarget is null && m_hoverRail is null) || m_hoverCompat.Kind != Compat.Blocked; + var pen = ok ? theme.WirePen(PinStyle.ColorOf(type)) : new Pen(theme.Error, 2.5, lineCap: PenLineCap.Round); + var end = m_hoverRail ?? (m_hoverTarget is { } target ? SlotPoint(target) : new Point(m_pointerWorld.X, m_pointerWorld.Y)); + context.DrawGeometry(null, pen, m_wireFromOutput is not null ? Bezier(anchor, end) : Bezier(end, anchor)); + if ((m_hoverTarget is not null || m_hoverRail is not null) && m_hoverCompat.Reason is { } reason) { + var tip = theme.Format(reason, 11.5, m_hoverCompat.Kind == Compat.Blocked ? theme.Error : theme.Warning); + context.DrawRectangle(theme.NodeBody, null, new Avalonia.Rect(end.X + 12, end.Y - 10, tip.Width + 12, tip.Height + 6), 4, 4); + context.DrawText(tip, new Point(end.X + 18, end.Y - 7)); + } + break; + } + case DragMode.Exec when m_execFrom is not null || m_execFromFrameExit is not null: { + var a = m_wireAnchor ?? SlotPoint(m_execFrom!); + var b = m_hoverExecTarget is { } t && SlotsOf(t).FirstOrDefault(s => s.Kind == SlotKind.ExecIn) is { } slot ? SlotPoint(slot) : new Point(m_pointerWorld.X, m_pointerWorld.Y); + if (m_execFromFrameExit is not null) context.DrawGeometry(null, theme.ExecWire, Bezier(b, a)); + else context.DrawGeometry(null, theme.ExecWire, Bezier(a, FrameExitAt(m_pointerWorld)?.Point ?? b)); + break; + } + } + } + + private void DrawBoxSelect(DrawingContext context, CanvasTheme theme) { + if (m_drag != DragMode.Box) return; + var r = new Avalonia.Rect(Math.Min(m_boxStart.X, m_pointerScreen.X), Math.Min(m_boxStart.Y, m_pointerScreen.Y), Math.Abs(m_boxStart.X - m_pointerScreen.X), Math.Abs(m_boxStart.Y - m_pointerScreen.Y)); + context.DrawRectangle(new SolidColorBrush(Color.Parse("#29adff"), 0.12), new Pen(theme.Accent, 1, dashStyle: DashStyle.Dash), r); + } + + private Avalonia.Rect MinimapRect(Size size) => new(size.Width - MinimapWidth - 12, size.Height - MinimapHeight - 12, MinimapWidth, MinimapHeight); + + private const double MinimapWidth = 190; + private const double MinimapHeight = 120; + + private (Avalonia.Rect World, double Scale)? MinimapWorld(Avalonia.Rect map) { + var nodes = VisibleNodes().ToList(); + if (nodes.Count == 0) return null; + var world = nodes.Select(NodeRect).Concat(VisibleGroups().Select(g => new Avalonia.Rect(g.Rect.X, g.Rect.Y, g.Rect.W, g.Rect.H))).Aggregate((a, b) => a.Union(b)).Inflate(40); + var scale = Math.Min(map.Width / world.Width, map.Height / world.Height); + return (world, scale); + } + + private void DrawMinimap(DrawingContext context, CanvasTheme theme, Size size) { + if (!MinimapVisible || Session is null) return; + var map = MinimapRect(size); + context.DrawRectangle(new SolidColorBrush(Color.Parse("#121111"), 0.85), new Pen(new SolidColorBrush(Color.Parse("#454343")), 1), map, 5, 5); + if (MinimapWorld(map) is not { } info) return; + var (world, scale) = info; + Point ToMap(double x, double y) => new(map.X + (x - world.X) * scale + (map.Width - world.Width * scale) / 2, map.Y + (y - world.Y) * scale + (map.Height - world.Height * scale) / 2); + using var clip = context.PushClip(map); + foreach (var group in VisibleGroups()) { + var a = ToMap(group.Rect.X, group.Rect.Y); + var color = Color.Parse(group.Color); + context.DrawRectangle(new SolidColorBrush(color, 0.45), new Pen(new SolidColorBrush(color, 1), 1.5), new Avalonia.Rect(a.X, a.Y, Math.Max(4, group.Rect.W * scale), Math.Max(4, group.Rect.H * scale))); + } + foreach (var node in VisibleNodes()) { + var r = NodeRect(node); + var a = ToMap(r.X, r.Y); + context.DrawRectangle(theme.HeaderOf(NodeShape.LookOf(node)), null, new Avalonia.Rect(a.X, a.Y, Math.Max(2, r.Width * scale), Math.Max(2, r.Height * scale))); + } + var tl = ToMap(-PanX / Zoom, -PanY / Zoom); + context.DrawRectangle(null, new Pen(theme.Accent, 1.2), new Avalonia.Rect(tl.X, tl.Y, size.Width / Zoom * scale, size.Height / Zoom * scale)); + } +} diff --git a/editor/LuaEditor/Canvas/GraphCanvas.cs b/editor/LuaEditor/Canvas/GraphCanvas.cs new file mode 100644 index 000000000..e6b5ecb04 --- /dev/null +++ b/editor/LuaEditor/Canvas/GraphCanvas.cs @@ -0,0 +1,1071 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Avalonia; +using Avalonia.Controls; +using Avalonia.Input; +using Avalonia.Input.Platform; +using Avalonia.Media; +using editor.LuaEditor.Editing; +using editor.LuaEditor.Graph; +using editor.LuaEditor.Layout; +using editor.LuaEditor.Types; +using Size = Avalonia.Size; + +namespace editor.LuaEditor.Canvas; + +public sealed record SearchRequest(Vec World, Point Screen, OutputPin? From, InputPin? Into, InsertPoint? Insert, bool StatementsOnly); + +public sealed record ConstantEditRequest(InputPin Pin, Avalonia.Rect Screen, string Text); + +public sealed record GroupEditRequest(LayoutGroup Group, Avalonia.Rect Screen); + +public enum DragMode { None, Pan, Nodes, Box, Wire, Exec, Group, Minimap, Region, Reroute, GroupResize, Proxy } + +public sealed partial class GraphCanvas : Control { + public static readonly StyledProperty SessionProperty = AvaloniaProperty.Register(nameof(Session)); + + public bool ShowModuleSetup { get; set; } + + private DragMode m_drag; + private Point m_pointerScreen; + private Vec m_pointerWorld; + private Point m_pressScreen; + private Point m_boxStart; + private bool m_moved; + private Slot? m_hoverSlot; + private Slot? m_hoverTarget; + private InputPin? m_hoverWire; + private Point? m_wireAnchor; + private InputPin? m_selectedProxy; + private GraphNode? m_docCandidate; + private GraphNode? m_docNode; + private Point m_docAt; + private Avalonia.Threading.DispatcherTimer? m_docTimer; + + private void TrackDoc(GraphNode? overHeader) { + if (overHeader == m_docCandidate) return; + m_docCandidate = overHeader; + if (m_docNode is not null) { + m_docNode = null; + InvalidateVisual(); + } + m_docTimer?.Stop(); + if (overHeader is null) return; + m_docTimer ??= new Avalonia.Threading.DispatcherTimer { Interval = TimeSpan.FromMilliseconds(450) }; + m_docTimer.Tick -= OnDocTick; + m_docTimer.Tick += OnDocTick; + m_docTimer.Start(); + } + + private void OnDocTick(object? sender, EventArgs e) { + m_docTimer?.Stop(); + if (m_docCandidate is null || m_drag != DragMode.None) return; + m_docNode = m_docCandidate; + m_docAt = m_pointerScreen; + InvalidateVisual(); + } + + private Point? m_hoverRail; + private CompatResult m_hoverCompat = CompatResult.Ok; + private OutputPin? m_wireFromOutput; + private InputPin? m_wireFromInput; + private Slot? m_execFrom; + private FrameReturnPort? m_wireFromReturn; + private FunctionDecl? m_execFromFrameExit; + private Statement? m_hoverExecTarget; + private LayoutGroup? m_selectedGroup; + private int m_resizeEdges; + private Layout.Rect m_resizeStart; + private Vec m_resizePress; + private RegionInfo? m_dragRegion; + private Vec m_lastNodeDragWorld; + private List m_dragNodes = []; + private bool m_fittedOnce; + private bool m_moveAllWires; + private object? m_reroutePin; + private int m_rerouteIndex; + + public GraphCanvas() { + Focusable = true; + ClipToBounds = true; + PointerTouchPadGestureMagnify += OnTouchpadMagnify; + DragDrop.SetAllowDrop(this, true); + AddHandler(DragDrop.DragOverEvent, OnDragOverVariable); + AddHandler(DragDrop.DropEvent, OnDropVariable); + } + + public GraphSession? Session { + get => GetValue(SessionProperty); + set => SetValue(SessionProperty, value); + } + + public double Zoom { get; private set; } = 1; + public double PanX { get; private set; } = 40; + public double PanY { get; private set; } = 60; + public bool MinimapVisible { get; set; } = true; + + public event Action? SearchRequested; + public event Action? ConstantEditRequested; + public event Action? GroupEditRequested; + public event Action? SaveRequested; + public event Action? FindRequested; + public event Action? NodeMenuRequested; + + public event Action>? RenameRequested; + public event Action>? ChoiceMenuRequested; + + static GraphCanvas() { + SessionProperty.Changed.AddClassHandler((canvas, e) => canvas.OnSessionChanged(e.OldValue as GraphSession, e.NewValue as GraphSession)); + AffectsRender(SessionProperty); + } + + private void OnSessionChanged(GraphSession? old, GraphSession? current) { + if (old is not null) old.Changed -= OnGraphChanged; + if (current is not null) current.Changed += OnGraphChanged; + m_fittedOnce = false; + OnGraphChanged(); + } + + private void OnGraphChanged() { + RefreshCaches(); + if (Session is not null && m_selectedGroup is not null && !Session.Layout.Groups.Contains(m_selectedGroup)) m_selectedGroup = null; + InvalidateVisual(); + } + + protected override Size ArrangeOverride(Size finalSize) { + var size = base.ArrangeOverride(finalSize); + if (!m_fittedOnce && Session is not null && size.Width > 50 && size.Height > 50) { + m_fittedOnce = true; + FrameAll(); + } + return size; + } + + private Vec ToWorld(Point screen) => new((screen.X - PanX) / Zoom, (screen.Y - PanY) / Zoom); + + private Point ToScreen(Vec world) => new(world.X * Zoom + PanX, world.Y * Zoom + PanY); + + private void ZoomAt(Point screen, double factor) { + var world = ToWorld(screen); + Zoom = Math.Clamp(Zoom * factor, 0.1, 2.5); + PanX = screen.X - world.X * Zoom; + PanY = screen.Y - world.Y * Zoom; + InvalidateVisual(); + } + + public void FrameAll() { + var nodes = Session is null ? [] : VisibleNodes().ToList(); + if (nodes.Count == 0) return; + Frame(nodes.Select(NodeRect).Aggregate((a, b) => a.Union(b))); + } + + public void FrameNodes(IEnumerable nodes) { + var list = nodes.Where(n => Session!.Layout.IsPlaced(n) && !IsModuleSetupNode(n) && !Session.Layout.IsHidden(n)).Select(NodeRect).ToList(); + if (list.Count > 0) Frame(list.Aggregate((a, b) => a.Union(b))); + } + + private void Frame(Avalonia.Rect world) { + var area = Bounds.Size; + if (area.Width < 10 || area.Height < 10) return; + world = world.Inflate(60); + Zoom = Math.Clamp(Math.Min(area.Width / world.Width, area.Height / world.Height), 0.1, 1.2); + PanX = (area.Width - world.Width * Zoom) / 2 - world.X * Zoom; + PanY = (area.Height - world.Height * Zoom) / 2 - world.Y * Zoom; + InvalidateVisual(); + } + + protected override void OnPointerWheelChanged(PointerWheelEventArgs e) { + base.OnPointerWheelChanged(e); + var p = e.GetPosition(this); + if (e.KeyModifiers.HasFlag(KeyModifiers.Control)) { + ZoomAt(p, Math.Pow(1.0015, e.Delta.Y * 120)); + } else { + PanX += e.Delta.X * 60; + PanY += e.Delta.Y * 60; + InvalidateVisual(); + } + e.Handled = true; + } + + private void OnTouchpadMagnify(object? sender, PointerDeltaEventArgs e) { + var amount = e.Delta.X != 0 ? e.Delta.X : e.Delta.Y; + ZoomAt(e.GetPosition(this), Math.Max(0.1, 1.0 + amount)); + e.Handled = true; + } + + private GraphNode? NodeAt(Vec world) { + if (Session is null) return null; + GraphNode? hit = null; + foreach (var node in VisibleNodes()) { + var r = NodeRect(node); + // nodes inside a frame must stay selectable + if (world.X >= r.X && world.X <= r.Right && world.Y >= r.Y && world.Y <= r.Bottom && (hit is null || r.Width * r.Height <= NodeRect(hit).Width * NodeRect(hit).Height)) hit = node; + } + if (hit is not null && NodeShape.ExpansionOf(hit) is not null) { + var r = NodeRect(hit); + var (railLeft, railRight) = DefaultMeasure.Rails(hit); + if (world.X > r.X + railLeft && world.X < r.Right - railRight && world.Y > r.Y + DefaultMeasure.HeaderHeight) return null; + } + return hit; + } + + private Slot? SlotAt(Vec world) { + if (Session is null) return null; + Slot? best = null; + var bestDistance = (PinRadius + 6) * (PinRadius + 6) / (Zoom < 1 ? Zoom : 1); + foreach (var node in VisibleNodes()) { + var r = NodeRect(node); + if (world.X < r.X - 12 || world.X > r.Right + 12 || world.Y < r.Y || world.Y > r.Bottom) continue; + foreach (var slot in SlotsOf(node)) { + var p = SlotPoint(slot); + var d = (p.X - world.X) * (p.X - world.X) + (p.Y - world.Y) * (p.Y - world.Y); + if (d <= bestDistance) { + best = slot; + bestDistance = d; + } + } + } + return best; + } + + private Slot? ConstantAt(Vec world) { + if (Session is null) return null; + foreach (var node in VisibleNodes()) { + foreach (var slot in SlotsOf(node)) { + if (slot.Kind != SlotKind.DataIn || slot.In is not { } candidate || (candidate.Source is not null && InlineRules.EnumValueOf(candidate) is null)) continue; + var label = CanvasTheme.Default.Format(slot.Label, 11.5, CanvasTheme.Default.TextMuted); + if (ConstantRect(slot, SlotPoint(slot), label.Width).Contains(new Point(world.X, world.Y))) return slot; + } + } + return null; + } + + private const int EdgeLeft = 1, EdgeTop = 2, EdgeRight = 4, EdgeBottom = 8; + + private (LayoutGroup? Group, int Edges) GroupEdgeAt(Vec world) { + if (Session is null) return (null, 0); + var m = 7 / Zoom; + foreach (var g in VisibleGroups().Reverse()) { + var r = g.Rect; + if (world.X < r.X - m || world.X > r.Right + m || world.Y < r.Y - m || world.Y > r.Bottom + m) continue; + var edges = (Math.Abs(world.X - r.X) <= m ? EdgeLeft : 0) | (Math.Abs(world.X - r.Right) <= m ? EdgeRight : 0) + | (Math.Abs(world.Y - r.Y) <= m ? EdgeTop : 0) | (Math.Abs(world.Y - r.Bottom) <= m ? EdgeBottom : 0); + if (edges != 0) return (g, edges); + } + return (null, 0); + } + + private static Cursor ResizeCursor(int edges) => new(edges switch { + EdgeLeft or EdgeRight => StandardCursorType.SizeWestEast, + EdgeTop or EdgeBottom => StandardCursorType.SizeNorthSouth, + EdgeLeft | EdgeTop or EdgeRight | EdgeBottom => StandardCursorType.TopLeftCorner, + _ => StandardCursorType.TopRightCorner + }); + + private (OutputPin? Output, Point Point, Slot? Exec)? FrameDotAt(Vec world) { + if (Session is null) return null; + var radius = 8 / Math.Min(Zoom, 1); + foreach (var node in VisibleNodes()) { + if (NodeShape.ExpansionOf(node) is not { } frame) continue; + var rect = NodeRect(node); + if (world.X < rect.X || world.X > rect.Right || world.Y < rect.Y || world.Y > rect.Bottom) continue; + var (railLeft, railRight) = DefaultMeasure.Rails(node); + var slots = SlotsOf(node); + var parameters = slots.Where(s => s.Kind == SlotKind.DataIn).ToList(); + for (var i = 0; i < parameters.Count && i < frame.Callee.Entry.Params.Count; i++) { + var p = new Point(rect.X + railLeft, SlotPoint(parameters[i]).Y); + if ((p.X - world.X) * (p.X - world.X) + (p.Y - world.Y) * (p.Y - world.Y) <= radius * radius) return (frame.Callee.Entry.Params[i].Output, p, null); + } + if (slots.FirstOrDefault(s => s.Kind == SlotKind.ExecIn) is { } enter && NodeShape.SlotsOf(frame.Callee).FirstOrDefault(s => s.Kind == SlotKind.ExecOut && s.Child is not null) is { } start) { + var p = new Point(rect.X + railLeft, SlotPoint(enter).Y); + if ((p.X - world.X) * (p.X - world.X) + (p.Y - world.Y) * (p.Y - world.Y) <= radius * radius) return (null, p, start); + } + } + return null; + } + + private sealed record FrameReturnPort(FunctionDecl Function, int Index, Point Point, InputPin? Input); + + private IEnumerable FrameReturns(GraphNode host, FunctionDecl function) { + var slots = SlotsOf(host); + var results = slots.Where(s => s.Kind == SlotKind.DataOut && !s.IsCallableReference).ToList(); + var rect = NodeRect(host); + var x = rect.Right - DefaultMeasure.Rails(host).Right; + var ret = NodeShape.TrailingReturn(function.Entry.Body); + if (results.Count == 0) { + var row = slots.Where(s => !s.IsLeft).Select(s => s.Row).DefaultIfEmpty(-1).Max() + 1; + var y = rect.Y + Session!.Layout.Measure.PinY(host, row, true); + yield return new FrameReturnPort(function, 0, new Point(x, y), ret?.Values.FirstOrDefault()); + } + for (var i = 0; i < results.Count; i++) + yield return new FrameReturnPort(function, i, new Point(x, SlotPoint(results[i]).Y), ret?.Values.ElementAtOrDefault(i)); + } + + private bool NearFrameRail(Vec world, Point point) { + var radius = 8 / Math.Min(Zoom, 1); + var dx = point.X - world.X; + var dy = point.Y - world.Y; + return dx * dx + dy * dy <= radius * radius; + } + + private FrameReturnPort? FrameReturnAt(Vec world) => VisibleNodes() + .SelectMany(host => NodeShape.ExpansionOf(host) is { } frame ? FrameReturns(host, frame.Callee) : []) + .FirstOrDefault(port => NearFrameRail(world, port.Point)); + + private Point FrameExecPoint(Slot slot) { + var (left, right) = DefaultMeasure.Rails(slot.Node); + var rect = NodeRect(slot.Node); + return new Point(slot.IsLeft ? rect.X + left : rect.Right - right, SlotPoint(slot).Y); + } + + private (FunctionDecl Function, Point Point)? FrameExitAt(Vec world) { + foreach (var host in VisibleNodes()) { + if (NodeShape.ExpansionOf(host) is not { } frame || + SlotsOf(host).FirstOrDefault(s => s.Kind == SlotKind.ExecOut && s.Child is null) is not { } exit) continue; + var point = FrameExecPoint(exit); + if (NearFrameRail(world, point)) return (frame.Callee, point); + } + return null; + } + + private InsertPoint? ExecInsertAt(Vec world) { + var hit = ExecWireAt(world); + if (hit.To is FunctionDecl function) { + var body = function.Entry.Body; + return new InsertPoint(body, NodeShape.TrailingReturn(body) is { } ret ? body.IndexOf(ret) : body.Statements.Count); + } + if (hit.To is not { Parent: { } block } to) return null; + return new InsertPoint(block, block.IndexOf(to)); + } + + private (TableField Field, Avalonia.Rect Label)? TableRowAt(TableNode table, Vec world) { + var rect = NodeRect(table); + foreach (var slot in SlotsOf(table).Where(s => s.Kind == SlotKind.DataIn && s.In is not null)) { + var p = SlotPoint(slot); + if (Math.Abs(world.Y - p.Y) > DefaultMeasure.RowHeight / 2 || world.X < rect.X || world.X > rect.X + rect.Width * 0.6) continue; + var field = table.Fields.FirstOrDefault(f => f.Value == slot.In || f.Key == slot.In); + if (field is null) continue; + var label = CanvasTheme.Default.Format(slot.Label, 11.5, CanvasTheme.Default.TextMuted); + return (field, new Avalonia.Rect(p.X + 10, p.Y - 10, label.Width + 16, 20)); + } + return null; + } + + private LayoutGroup? GroupHeaderAt(Vec world) + + => VisibleGroups().LastOrDefault(g => world.X >= g.Rect.X && world.X <= g.Rect.Right && world.Y >= g.Rect.Y && world.Y <= g.Rect.Y + 26); + + private RegionInfo? RegionHeaderAt(Vec world) { + if (Session is null) return null; + foreach (var region in CanvasRegions()) { + if (Session.Layout.RegionBounds(region) is not { } b) continue; + if (RegionHeaderRect(region, b).Contains(new Point(world.X, world.Y))) return region; + } + return null; + } + + private Statement? StatementOf(GraphNode node) => node as Statement ?? node.OwnerStatement; + + private void OnDragOverVariable(object? sender, DragEventArgs e) { + e.DragEffects = e.DataTransfer.Contains(VariableDrag.Format) ? DragDropEffects.Copy : DragDropEffects.None; + e.Handled = true; + } + + private void OnDropVariable(object? sender, DragEventArgs e) { + if (Session is null || e.DataTransfer.TryGetValue(VariableDrag.Format) is not { } drag || drag.Session != Session) return; + e.Handled = true; + var shift = e.KeyModifiers.HasFlag(KeyModifiers.Shift); + var set = shift || e.KeyModifiers.HasFlag(KeyModifiers.Alt); + CreateHierarchyNode(drag.Row, set, shift, ToWorld(e.GetPosition(this))); + } + + public void CreateHierarchyNode(VariableRow row, bool set) => + CreateHierarchyNode(row, set, false, ToWorld(new Point(Bounds.Width / 2, Bounds.Height / 2))); + + private void CreateHierarchyNode(VariableRow row, bool set, bool shift, Vec world) { + if (Session is not { } session || !row.CanDrag || row.Variable is not { } variable || variable.Declaration.Graph != session.Graph) return; + var entry = row.Kind == VariableRowKind.Script + ? new NodeEntry(NodeKind.GetSelf, "Script Table", "Variables", "self", Name: "self") + : session.HierarchyEntry(variable, row.Binding, row.Native, set, shift && row.Kind == VariableRowKind.Method); + var into = entry.Kind != NodeKind.SetVariable && SlotAt(world) is { Kind: SlotKind.DataIn, In: { } pin } ? pin : null; + session.Create(entry, world, into: into, insert: ExecInsertAt(world)); + } + + protected override void OnPointerPressed(PointerPressedEventArgs e) { + base.OnPointerPressed(e); + Focus(); + TrackDoc(null); + if (Session is null) return; + var point = e.GetCurrentPoint(this); + m_pointerScreen = m_pressScreen = point.Position; + m_pointerWorld = ToWorld(point.Position); + m_moved = false; + var props = point.Properties; + var ctrl = e.KeyModifiers.HasFlag(KeyModifiers.Control); + var shift = e.KeyModifiers.HasFlag(KeyModifiers.Shift); + var alt = e.KeyModifiers.HasFlag(KeyModifiers.Alt); + + if (props.IsRightButtonPressed && ProxyAt(m_pointerWorld) is { Source: { } tagSource } tagPin) { + e.Pointer.Capture(this); + m_wireFromOutput = tagSource; + m_wireFromInput = null; + m_moveAllWires = false; + Session.Disconnect(tagPin); + m_drag = DragMode.Wire; + return; + } + if (props.IsRightButtonPressed && WireAt(m_pointerWorld) is var (cutWire, _) && cutWire?.Source is { } cutSource) { + e.Pointer.Capture(this); + m_wireFromOutput = cutSource; + m_wireFromInput = null; + m_moveAllWires = false; + Session.Disconnect(cutWire); + m_drag = DragMode.Wire; + return; + } + if (props.IsMiddleButtonPressed || props.IsRightButtonPressed) { + m_drag = DragMode.Pan; + e.Pointer.Capture(this); + return; + } + if (!props.IsLeftButtonPressed) return; + e.Pointer.Capture(this); + + if (MinimapVisible && MinimapRect(Bounds.Size).Contains(point.Position)) { + m_drag = DragMode.Minimap; + MoveViewFromMinimap(point.Position); + return; + } + + var world = m_pointerWorld; + m_selectedProxy = null; + if (FrameReturnAt(world) is { } returned) { + if (alt && returned.Input is { } input) Session.Disconnect(input); + else { + m_wireFromReturn = returned; + m_wireFromInput = returned.Input; + m_wireAnchor = returned.Point; + m_drag = DragMode.Wire; + } + return; + } + if (FrameExitAt(world) is { } exit) { + m_execFromFrameExit = exit.Function; + m_wireAnchor = exit.Point; + m_drag = DragMode.Exec; + return; + } + if (FrameDotAt(world) is { } dot) { + m_wireAnchor = dot.Point; + if (dot.Exec is { } start) { + m_execFrom = start; + m_drag = DragMode.Exec; + return; + } + m_wireFromOutput = dot.Output; + m_wireFromInput = null; + m_moveAllWires = false; + m_drag = DragMode.Wire; + return; + } + if (SlotAt(world) is { } slot) { + BeginSlotDrag(slot, ctrl, alt); + return; + } + if (ProxyAt(world) is { } tag) { + if (alt) { + Session.Disconnect(tag); + m_drag = DragMode.None; + return; + } + m_selectedProxy = tag; + Session.ClearSelection(); + m_selectedGroup = null; + m_drag = DragMode.Proxy; + m_lastNodeDragWorld = world; + InvalidateVisual(); + return; + } + if (alt && WireAt(world) is var (cutPin, _) && cutPin is not null) { + Session.Disconnect(cutPin); + m_drag = DragMode.None; + return; + } + if (RerouteAt(world) is var (reroutePin, rerouteIndex) && reroutePin is not null) { + if (e.ClickCount >= 2) { + Session.RemoveReroute(reroutePin, rerouteIndex); + } else { + m_drag = DragMode.Reroute; + m_reroutePin = reroutePin; + m_rerouteIndex = rerouteIndex; + } + return; + } + if (e.ClickCount >= 2 && WireAt(world) is var (wirePin, segment) && wirePin is not null) { + m_drag = DragMode.None; + Session.AddReroute(wirePin, world, segment); + return; + } + if (e.ClickCount >= 2 && ExecWireAt(world) is var (execTo, execSegment) && execTo is not null) { + m_drag = DragMode.None; + Session.AddReroute(execTo, world, execSegment); + return; + } + if (ConstantAt(world) is { } constantSlot && e.ClickCount >= 1 && NodeAt(world) is not null) { + EditConstant(constantSlot); + m_drag = DragMode.None; + e.Handled = true; + return; + } + if (RegionHeaderAt(world) is { } region) { + if (e.ClickCount >= 2 || ToggleButtonRect(RegionHeaderRect(region, Session.Layout.RegionBounds(region)!.Value)).Contains(new Point(world.X, world.Y))) { + ToggleRegion(region); + m_drag = DragMode.None; + } else { + m_drag = DragMode.Region; + m_dragRegion = region; + m_lastNodeDragWorld = world; + } + return; + } + if (NodeAt(world) is { } node) { + var statement = node; + if (e.ClickCount >= 2 && node is FunctionNode closure) { + JumpToClosure(closure); + m_drag = DragMode.None; + return; + } + if (node is TableNode named && TableRowAt(named, world) is { } row && (row.Field.Kind == TableFieldKind.Keyed && row.Field.Key is { Source: null } || e.ClickCount >= 2 && row.Field.Kind == TableFieldKind.Named)) { + var tableNode = named; + var field = row.Field; + var screenAt = ToScreen(new Vec(row.Label.X, row.Label.Y)); + var box = new Avalonia.Rect(screenAt.X, screenAt.Y, Math.Max(140, row.Label.Width * Zoom), Math.Max(20, row.Label.Height * Zoom)); + if (field.Kind == TableFieldKind.Named) RenameRequested?.Invoke(box, field.Name ?? "", text => Session?.RenameTableField(tableNode, field, text.Trim())); + else if (field.Key is { } key) RenameRequested?.Invoke(box, NodeShape.KeyText(key), text => Session?.SetTableKey(tableNode, field, text)); + m_drag = DragMode.None; + e.Handled = true; + return; + } + if (e.ClickCount >= 2 && (node is MemberGet { Object.Source: not { Binding: { } } } || node is AssignStatement { Targets: [{ Kind: TargetKind.Member }] }) && world.Y <= NodeRect(node).Y + DefaultMeasure.HeaderHeight) { + var access = node; + var current = node is MemberGet member ? member.Name : ((AssignStatement)node).Targets[0].Name ?? ""; + var head = ToScreen(new Vec(NodeRect(node).X, NodeRect(node).Y)); + RenameRequested?.Invoke(new Avalonia.Rect(head.X, head.Y, Math.Max(160, NodeRect(node).Width * Zoom), 24), current, text => Session?.RenameAccess(access, text.Trim())); + m_drag = DragMode.None; + e.Handled = true; + return; + } + if (node is TableNode growing && TableAddRect(NodeRect(node)).Contains(new Point(world.X, world.Y))) { + + Session.AddTableEntry(growing, TableGrowsBy(growing)); + m_drag = DragMode.None; + e.Handled = true; + return; + } + if (Session.CanOpen(node) && NodeRect(node) is var expandRect && ToggleButtonRect(expandRect).Contains(new Point(world.X, world.Y))) { + Session.ToggleExpanded(node); + m_drag = DragMode.None; + return; + } + if (e.ClickCount >= 2 && JumpToCallee(node)) { + m_drag = DragMode.None; + return; + } + if (ctrl || shift) Session.Select([node], additive: true); + else if (!Session.Selection.Contains(node)) Session.Select([node]); + m_selectedGroup = null; + m_drag = DragMode.Nodes; + m_dragNodes = Session.Selection.ToList(); + m_lastNodeDragWorld = world; + _ = statement; + return; + } + if (GroupEdgeAt(world) is var (resizeGroup, resizeEdges) && resizeGroup is not null) { + m_selectedGroup = resizeGroup; + m_resizeEdges = resizeEdges; + m_resizeStart = resizeGroup.Rect; + m_resizePress = world; + m_drag = DragMode.GroupResize; + Session.ClearSelection(); + InvalidateVisual(); + return; + } + if (GroupHeaderAt(world) is { } group) { + + if (e.ClickCount >= 2) { + GroupEditRequested?.Invoke(new GroupEditRequest(group, GroupScreenRect(group))); + m_drag = DragMode.None; + return; + } + m_selectedGroup = group; + m_drag = DragMode.Group; + m_lastNodeDragWorld = world; + Session.ClearSelection(); + InvalidateVisual(); + return; + } + + m_selectedGroup = null; + m_drag = DragMode.Box; + m_boxStart = point.Position; + if (!ctrl && !shift) Session.ClearSelection(); + } + + private GraphNode? m_callableWireHost; + + private static GraphNode? CallableHost(Slot slot) => slot.IsCallableReference ? slot.Node : null; + + private void BeginSlotDrag(Slot slot, bool ctrl, bool alt) { + var session = Session!; + switch (slot.Kind) { + case SlotKind.DataOut: + m_drag = DragMode.Wire; + m_wireFromOutput = slot.Out; + m_wireFromInput = null; + m_callableWireHost = CallableHost(slot); + var isReference = m_callableWireHost is not null; + if (isReference) m_wireAnchor = SlotPoint(slot); + m_moveAllWires = ctrl && !isReference; + break; + case SlotKind.DataIn when slot.In is { } pin: + if (alt) { + session.Disconnect(pin); + m_drag = DragMode.None; + } else if (pin.Source is { } source && ctrl) { + m_wireFromOutput = source; + m_wireFromInput = null; + session.Disconnect(pin); + m_drag = DragMode.Wire; + } else if (pin.Source is { } existing) { + m_wireFromOutput = existing; + m_wireFromInput = null; + if (SlotFor(existing) is { } origin && session.Layout.IsHidden(origin.Node)) m_wireAnchor = FrameRailPoint(origin); + session.Disconnect(pin); + m_drag = DragMode.Wire; + } else { + m_wireFromInput = pin; + m_wireFromOutput = null; + m_drag = DragMode.Wire; + } + break; + case SlotKind.ExecOut: + m_drag = DragMode.Exec; + m_execFrom = slot; + break; + default: + m_drag = DragMode.None; + break; + } + } + + protected override void OnPointerMoved(PointerEventArgs e) { + base.OnPointerMoved(e); + if (Session is null) return; + var p = e.GetPosition(this); + var delta = p - m_pointerScreen; + m_pointerScreen = p; + m_pointerWorld = ToWorld(p); + if ((p - m_pressScreen).X * (p - m_pressScreen).X + (p - m_pressScreen).Y * (p - m_pressScreen).Y > 16) m_moved = true; + var session = Session; + + switch (m_drag) { + case DragMode.Pan: + PanX += delta.X; + PanY += delta.Y; + break; + case DragMode.Minimap: + MoveViewFromMinimap(p); + break; + case DragMode.Nodes when m_moved: + var step = m_pointerWorld - m_lastNodeDragWorld; + session.Move(m_dragNodes, step); + m_lastNodeDragWorld = m_pointerWorld; + break; + case DragMode.Region when m_moved && m_dragRegion is not null: + session.MoveRegion(m_dragRegion, m_pointerWorld - m_lastNodeDragWorld); + m_lastNodeDragWorld = m_pointerWorld; + break; + case DragMode.Group when m_moved && m_selectedGroup is not null: + var d = m_pointerWorld - m_lastNodeDragWorld; + session.Move(m_selectedGroup.Members, d); + m_selectedGroup.Rect = m_selectedGroup.Rect.Offset(d); + m_lastNodeDragWorld = m_pointerWorld; + break; + case DragMode.GroupResize when m_selectedGroup is not null: + var gdx = m_pointerWorld.X - m_resizePress.X; + var gdy = m_pointerWorld.Y - m_resizePress.Y; + double left = m_resizeStart.X, top = m_resizeStart.Y, right = m_resizeStart.Right, bottom = m_resizeStart.Bottom; + if ((m_resizeEdges & EdgeLeft) != 0) left = Math.Min(left + gdx, right - 80); + if ((m_resizeEdges & EdgeRight) != 0) right = Math.Max(right + gdx, left + 80); + if ((m_resizeEdges & EdgeTop) != 0) top = Math.Min(top + gdy, bottom - 60); + if ((m_resizeEdges & EdgeBottom) != 0) bottom = Math.Max(bottom + gdy, top + 60); + m_selectedGroup.Rect = new Layout.Rect(left, top, right - left, bottom - top); + break; + case DragMode.Proxy when m_moved && m_selectedProxy is not null: + session.MoveProxy(m_selectedProxy, m_pointerWorld - m_lastNodeDragWorld); + m_lastNodeDragWorld = m_pointerWorld; + break; + case DragMode.Reroute when m_reroutePin is not null: + + session.MoveReroute(m_reroutePin, m_rerouteIndex, m_pointerWorld); + break; + case DragMode.Wire: + UpdateWireHover(); + break; + case DragMode.Exec: + m_hoverExecTarget = NodeAt(m_pointerWorld) is { } hit ? StatementOf(hit) : null; + if (m_hoverExecTarget is not null && !NodeShape.HasExecutionIn(m_hoverExecTarget)) m_hoverExecTarget = null; + break; + case DragMode.None: + var hover = SlotAt(m_pointerWorld); + if (hover != m_hoverSlot) m_hoverSlot = hover; + TrackDoc(hover is null && NodeAt(m_pointerWorld) is { } headerNode && m_pointerWorld.Y <= NodeRect(headerNode).Y + DefaultMeasure.HeaderHeight && NodeShape.ExpansionOf(headerNode) is null ? headerNode : null); + m_hoverWire = hover is null ? WireAt(m_pointerWorld).Pin : null; + var overToggle = VisibleNodes().Any(n => Session.CanOpen(n) && ToggleButtonRect(NodeRect(n)).Contains(new Point(m_pointerWorld.X, m_pointerWorld.Y))); + var overEdge = hover is null && !overToggle && NodeAt(m_pointerWorld) is null ? GroupEdgeAt(m_pointerWorld).Edges : 0; + Cursor = overEdge != 0 ? ResizeCursor(overEdge) : hover is not null || overToggle || FrameReturnAt(m_pointerWorld) is not null || FrameExitAt(m_pointerWorld) is not null ? new Cursor(StandardCursorType.Hand) : Cursor.Default; + break; + } + InvalidateVisual(); + } + + private void UpdateWireHover() { + m_hoverTarget = null; + m_hoverCompat = CompatResult.Ok; + m_hoverRail = null; + if (m_wireFromOutput is { } railOutput && FrameReturnAt(m_pointerWorld) is { } returned) { + m_hoverRail = returned.Point; + if (returned.Input is { } input) m_hoverCompat = Session!.CanConnect(railOutput, input); + return; + } + if ((m_wireFromReturn is not null || m_wireFromInput is not null) && FrameDotAt(m_pointerWorld) is { Output: not null } parameter) { + m_hoverRail = parameter.Point; + if (m_wireFromInput is { } input) m_hoverCompat = Session!.CanConnect(parameter.Output, input); + return; + } + var slot = SlotAt(m_pointerWorld); + if (slot is null) return; + if (m_wireFromOutput is { } from && slot is { Kind: SlotKind.DataIn, In: { } pin }) { + m_hoverTarget = slot; + m_hoverCompat = Session!.CanConnect(from, pin); + } else if (m_wireFromInput is { } into && slot is { Kind: SlotKind.DataOut, Out: { } output }) { + m_hoverTarget = slot; + m_hoverCompat = Session!.CanConnect(output, into); + } + } + + protected override void OnPointerReleased(PointerReleasedEventArgs e) { + base.OnPointerReleased(e); + var session = Session; + var mode = m_drag; + m_drag = DragMode.None; + e.Pointer.Capture(null); + if (session is null) return; + var p = e.GetPosition(this); + m_pointerWorld = ToWorld(p); + + switch (mode) { + case DragMode.Pan when !m_moved: + if (e.InitialPressMouseButton == MouseButton.Right) + if (NodeAt(m_pointerWorld) is { } hitNode) NodeMenuRequested?.Invoke(hitNode, p); + else SearchRequested?.Invoke(new SearchRequest(m_pointerWorld, p, null, null, ExecInsertAt(m_pointerWorld), false)); + break; + case DragMode.Nodes when m_moved: + session.FinishMove(m_dragNodes); + break; + case DragMode.Group when m_moved && m_selectedGroup is not null: + session.FinishMove(m_selectedGroup.Members); + break; + case DragMode.Region when m_moved: + session.FinishRegionMove(); + break; + case DragMode.Box: + FinishBoxSelect(e.KeyModifiers.HasFlag(KeyModifiers.Control) || e.KeyModifiers.HasFlag(KeyModifiers.Shift)); + break; + case DragMode.Reroute when m_moved: + session.CommitLayout(); + break; + case DragMode.Proxy when m_moved: + session.CommitLayout(); + break; + case DragMode.GroupResize when m_selectedGroup is not null: + if (m_moved) session.FinishResizeGroup(m_selectedGroup); + break; + case DragMode.Wire: + FinishWire(p); + break; + case DragMode.Exec: + FinishExec(p); + break; + } + m_wireFromOutput = null; + m_wireFromInput = null; + m_wireFromReturn = null; + m_execFromFrameExit = null; + m_wireAnchor = null; + m_callableWireHost = null; + m_hoverTarget = null; + m_hoverRail = null; + m_execFrom = null; + m_hoverExecTarget = null; + m_dragRegion = null; + InvalidateVisual(); + } + + private void FinishWire(Point screen) { + var session = Session!; + var world = ToWorld(screen); + var slot = SlotAt(world); + var rail = FrameDotAt(world); + if (m_wireFromOutput is { } from) { + if (FrameReturnAt(world) is { } returned) { + session.ConnectFrameReturn(returned.Function, returned.Index, from, m_callableWireHost); + return; + } + if (m_moveAllWires && slot is { Kind: SlotKind.DataOut, Out: { } target } && target != from) session.MoveWires(from, target); + else if (slot is { Kind: SlotKind.DataIn, In: { } pin }) session.Connect(from, pin, m_callableWireHost); + else if (slot is null) { + if (NodeAt(world) is { } node && NodeAt(world) is not null && SessionPrimary(node) is { } primary) session.Connect(from, primary, m_callableWireHost); + else if (m_moved) SearchRequested?.Invoke(new SearchRequest(world, screen, from, null, null, false)); + } + } else if (m_wireFromReturn is { } returned) { + var output = rail?.Output ?? (slot?.Kind == SlotKind.DataOut ? slot.Out : null); + if (output is not null) session.ConnectFrameReturn(returned.Function, returned.Index, output, slot is null ? null : CallableHost(slot)); + } else if (m_wireFromInput is { } into) { + if (rail?.Output is { } parameter) session.Connect(parameter, into); + else if (slot is { Kind: SlotKind.DataOut, Out: { } output }) session.Connect(output, into, CallableHost(slot)); + else if (slot is null && m_moved) SearchRequested?.Invoke(new SearchRequest(world, screen, null, into, null, false)); + } + } + + private static InputPin? SessionPrimary(GraphNode node) { + if (node is Statement or ExprNode) return GraphSession.PrimaryInput(node); + return null; + } + + private void FinishExec(Point screen) { + var session = Session!; + var world = ToWorld(screen); + if (m_execFromFrameExit is { } frame) { + if (NodeAt(world) is ReturnStatement ret) session.ConnectFrameExit(frame, ret); + return; + } + if (m_execFrom is null) return; + if (FrameExitAt(world) is { } exit && m_execFrom.Node is Statement tail && m_execFrom.Child is null) { + session.ConnectFrameExit(exit.Function, tail); + return; + } + if (m_hoverExecTarget is { } target) { + session.ConnectExec(m_execFrom, target); + } else if (m_moved) { + InsertPoint? point = null; + if (m_execFrom.Child is { } child) point = new InsertPoint(child, 0); + else if (m_execFrom.Node is Statement { Parent: { } block } source) point = new InsertPoint(block, block.IndexOf(source) + 1); + SearchRequested?.Invoke(new SearchRequest(world, screen, null, null, point, true)); + } + } + + private void FinishBoxSelect(bool additive) { + var session = Session!; + if (!m_moved) return; + var a = ToWorld(m_boxStart); + var b = ToWorld(m_pointerScreen); + var box = new Avalonia.Rect(Math.Min(a.X, b.X), Math.Min(a.Y, b.Y), Math.Abs(a.X - b.X), Math.Abs(a.Y - b.Y)); + var hits = VisibleNodes().Where(n => NodeRect(n).Intersects(box)).ToList(); + if (!additive) session.ClearSelection(); + session.Select(hits, additive: true); + } + + private void MoveViewFromMinimap(Point screen) { + var map = MinimapRect(Bounds.Size); + if (MinimapWorld(map) is not { } info) return; + var (world, scale) = info; + var wx = world.X + (screen.X - map.X - (map.Width - world.Width * scale) / 2) / scale; + var wy = world.Y + (screen.Y - map.Y - (map.Height - world.Height * scale) / 2) / scale; + PanX = Bounds.Width / 2 - wx * Zoom; + PanY = Bounds.Height / 2 - wy * Zoom; + InvalidateVisual(); + } + + private void ToggleRegion(RegionInfo region) { + var layout = Session!.Layout; + if (!layout.CollapsedRegions.Remove(region.Body)) layout.CollapsedRegions.Add(region.Body); + Session.CommitLayout(); + } + + private bool JumpToCallee(GraphNode node) => NodeShape.CalleeOf(node) is { } function && ShowFunction(function); + + public bool ShowFunction(FunctionDecl function) { + if (Session is not { Layout: { } layout }) return false; + var region = layout.Keys.Regions.FirstOrDefault(r => r.Header == function); + if (region is null) return false; + layout.CollapsedRegions.Remove(region.Body); + if (layout.Embedded.TryGetValue(region.Body, out var host)) { + if (layout.Keys.RegionOf(host) is { } hostRegion) layout.CollapsedRegions.Remove(hostRegion.Body); + FrameNodes([host]); + } else { + FrameNodes(layout.NodesOf(region)); + } + return true; + } + + private void JumpToClosure(FunctionNode closure) { + var layout = Session!.Layout; + var region = layout.Keys.Regions.FirstOrDefault(r => r.Header == closure); + if (region is null) return; + layout.CollapsedRegions.Remove(region.Body); + FrameNodes(layout.NodesOf(region)); + } + + private void EditConstant(Slot slot) { + var pin = slot.In!; + if (GraphSession.IsBoolean(pin) && pin.Source is null) { + Session!.Toggle(pin); + return; + } + var label = CanvasTheme.Default.Format(slot.Label, 11.5, CanvasTheme.Default.TextMuted); + var world = ConstantRect(slot, SlotPoint(slot), label.Width); + var topLeft = ToScreen(new Vec(world.X, world.Y)); + var screen = new Avalonia.Rect(topLeft.X, topLeft.Y, world.Width * Zoom, world.Height * Zoom); + if (Session!.ChoicesFor(pin) is { } choices) { + ChoiceMenuRequested?.Invoke(pin, screen, choices); + return; + } + ConstantEditRequested?.Invoke(new ConstantEditRequest(pin, screen, pin.Constant is { } current ? GraphSession.DisplayText(current) : "")); + } + + private Avalonia.Rect GroupScreenRect(LayoutGroup group) { + var tl = ToScreen(new Vec(group.Rect.X, group.Rect.Y)); + return new Avalonia.Rect(tl.X, tl.Y, group.Rect.W * Zoom, 26 * Zoom); + } + + protected override void OnKeyDown(KeyEventArgs e) { + base.OnKeyDown(e); + if (Session is null || e.Handled) return; + var key = e.Key.ToString(); + var ctrl = e.KeyModifiers.HasFlag(KeyModifiers.Control); + var shift = e.KeyModifiers.HasFlag(KeyModifiers.Shift); + var alt = e.KeyModifiers.HasFlag(KeyModifiers.Alt); + if (e.Key == Key.Escape) { + m_drag = DragMode.None; + Session.ClearSelection(); + e.Handled = true; + return; + } + if (Shortcuts.Find(key, ctrl, shift, alt) is not { } action) return; + e.Handled = true; + Execute(action); + } + + public void Execute(CanvasAction action) { + var session = Session; + if (session is null) return; + var at = m_pointerWorld; + switch (action) { + case CanvasAction.Branch: Make(NodeCatalog.Of(NodeKind.If), at); break; + case CanvasAction.Sequence: + if (session.Selection.OfType().Count() >= 2) session.GroupSelectionAsSequence(); + else Make(NodeCatalog.Of(NodeKind.Sequence), at); + break; + case CanvasAction.ForEach: Make(NodeCatalog.Of(NodeKind.GenericFor), at); break; + case CanvasAction.MakeTable: Make(NodeCatalog.Of(NodeKind.MakeTable), at); break; + case CanvasAction.Add: Make(NodeCatalog.Operator(BinaryKind.Add), at); break; + case CanvasAction.Subtract: Make(NodeCatalog.Operator(BinaryKind.Sub), at); break; + case CanvasAction.Multiply: Make(NodeCatalog.Operator(BinaryKind.Mul), at); break; + case CanvasAction.Divide: Make(NodeCatalog.Operator(BinaryKind.Div), at); break; + case CanvasAction.Greater: Make(NodeCatalog.Operator(BinaryKind.Gt), at); break; + case CanvasAction.Less: Make(NodeCatalog.Operator(BinaryKind.Lt), at); break; + case CanvasAction.Equal: Make(NodeCatalog.Operator(BinaryKind.Eq), at); break; + case CanvasAction.Not: Make(NodeCatalog.Operator(UnaryKind.Not), at); break; + case CanvasAction.Number: Make(NodeCatalog.Of(NodeKind.Number), at); break; + case CanvasAction.Vec2: Make(NodeCatalog.Vector("vec2"), at); break; + case CanvasAction.Vec3: Make(NodeCatalog.Vector("vec3"), at); break; + case CanvasAction.Quat: Make(NodeCatalog.Vector("quat"), at); break; + case CanvasAction.Search: + SearchRequested?.Invoke(new SearchRequest(at, ToScreen(at), m_wireFromOutput, m_wireFromInput, m_wireFromOutput is null && m_wireFromInput is null ? ExecInsertAt(at) : null, false)); + break; + case CanvasAction.CommentBox: + if (session.AddCommentBox() is { } group) { + m_selectedGroup = group; + GroupEditRequested?.Invoke(new GroupEditRequest(group, GroupScreenRect(group))); + } + break; + case CanvasAction.GroupAsFunction: session.GroupSelectionAsFunction(); break; + case CanvasAction.Straighten: StraightenSelection(); break; + case CanvasAction.AlignTop: session.Align(AlignEdge.Top); break; + case CanvasAction.AlignLeft: session.Align(AlignEdge.Left); break; + case CanvasAction.AlignBottom: session.Align(AlignEdge.Bottom); break; + case CanvasAction.AlignRight: session.Align(AlignEdge.Right); break; + case CanvasAction.Tidy: session.Tidy(null, includePinned: false); break; + case CanvasAction.Duplicate: session.Duplicate(); break; + case CanvasAction.Delete: + if (m_selectedProxy is { } tagToRemove) { + session.Disconnect(tagToRemove); + m_selectedProxy = null; + } else if (m_selectedGroup is not null) { + session.RemoveCommentBox(m_selectedGroup); + m_selectedGroup = null; + } else { + session.Delete(session.Selection.ToList()); + } + break; + case CanvasAction.Copy: _ = CopyAsync(); break; + case CanvasAction.Cut: _ = CutAsync(); break; + case CanvasAction.Paste: _ = PasteAsync(at); break; + case CanvasAction.SelectAll: session.Select(VisibleNodes()); break; + case CanvasAction.Undo: session.Undo(); break; + case CanvasAction.Redo: session.Redo(); break; + case CanvasAction.Save: SaveRequested?.Invoke(); break; + case CanvasAction.Find: FindRequested?.Invoke(); break; + case CanvasAction.Home: + if (session.Selection.Count > 0) FrameNodes(session.Selection); + else FrameAll(); + break; + } + InvalidateVisual(); + } + + private OutputPin? SelectedOutput() => Session!.Selection.Count == 1 ? Session.Selection[0].Outputs.FirstOrDefault() : null; + + private void Make(NodeEntry entry, Vec at) { + var session = Session!; + var from = m_wireFromOutput; + if (from is not null && from.Owner is Statement { Parent: null }) from = null; + session.Create(entry, at, from, m_wireFromInput, ExecInsertAt(at)); + m_drag = DragMode.None; + m_wireFromOutput = null; + m_wireFromInput = null; + } + + private void StraightenSelection() { + var session = Session!; + var selected = session.Selection.ToHashSet(); + var links = new List<(Slot From, Slot To)>(); + ForEachExecLink(null, (from, target) => { + if (selected.Contains(from.Node) && selected.Contains(target) && SlotsOf(target).FirstOrDefault(s => s.Kind == SlotKind.ExecIn) is { } into) + links.Add((from, into)); + }); + foreach (var node in selected) + foreach (var into in SlotsOf(node)) + if (into.In is { Source: { } source } pin && (session.Layout.CallableSlot(pin) ?? SlotFor(source)) is { } from && selected.Contains(from.Node)) + links.Add((from, into)); + session.StraightenSelection(links); + } + + private async System.Threading.Tasks.Task CopyAsync() { + var text = Session!.CopyText(); + if (text.Length > 0 && TopLevel.GetTopLevel(this)?.Clipboard is { } clipboard) await clipboard.SetTextAsync(text); + } + + private async System.Threading.Tasks.Task CutAsync() { + await CopyAsync(); + Session!.Delete(Session.Selection.OfType().ToList()); + } + + private async System.Threading.Tasks.Task PasteAsync(Vec at) { + if (TopLevel.GetTopLevel(this)?.Clipboard is not { } clipboard) return; + var text = await clipboard.TryGetTextAsync(); + if (!string.IsNullOrWhiteSpace(text)) Session!.Paste(text, at); + } +} diff --git a/editor/LuaEditor/Canvas/VariableDrag.cs b/editor/LuaEditor/Canvas/VariableDrag.cs new file mode 100644 index 000000000..c3cd476c4 --- /dev/null +++ b/editor/LuaEditor/Canvas/VariableDrag.cs @@ -0,0 +1,10 @@ +using Avalonia.Input; +using editor.LuaEditor.Editing; + +namespace editor.LuaEditor.Canvas; + +public sealed record HierarchyDrag(GraphSession Session, VariableRow Row); + +public static class VariableDrag { + public static readonly DataFormat Format = DataFormat.CreateInProcessFormat("lua-graph-variable"); +} diff --git a/editor/LuaEditor/Controls/PinShapeIcon.cs b/editor/LuaEditor/Controls/PinShapeIcon.cs new file mode 100644 index 000000000..8c9cffcf8 --- /dev/null +++ b/editor/LuaEditor/Controls/PinShapeIcon.cs @@ -0,0 +1,123 @@ +using System; +using Avalonia; +using Avalonia.Controls; +using Avalonia.Media; +using editor.LuaEditor.Editing; + +namespace editor.LuaEditor.Controls; + +public static class PinGlyph { + public static void Draw(DrawingContext context, Point p, PinShape shape, Color color, double r = 5.5, bool filled = true) { + var brush = new SolidColorBrush(color); + var pen = new Pen(brush, 1.8); + IBrush? fill = filled ? brush : null; + switch (shape) { + case PinShape.Diamond: { + var g = new StreamGeometry(); + using (var c = g.Open()) { + c.BeginFigure(new Point(p.X, p.Y - r - 1), true); + c.LineTo(new Point(p.X + r + 1, p.Y)); + c.LineTo(new Point(p.X, p.Y + r + 1)); + c.LineTo(new Point(p.X - r - 1, p.Y)); + c.EndFigure(true); + } + context.DrawGeometry(fill, pen, g); + break; + } + case PinShape.Triangle: { + var g = new StreamGeometry(); + using (var c = g.Open()) { + c.BeginFigure(new Point(p.X - r, p.Y - r - 1), true); + c.LineTo(new Point(p.X + r + 2, p.Y)); + c.LineTo(new Point(p.X - r, p.Y + r + 1)); + c.EndFigure(true); + } + context.DrawGeometry(fill, pen, g); + break; + } + case PinShape.Hexagon: { + var g = new StreamGeometry(); + var h = r + 1.5; + using (var c = g.Open()) { + c.BeginFigure(new Point(p.X - h, p.Y), true); + c.LineTo(new Point(p.X - h / 2, p.Y - h * 0.87)); + c.LineTo(new Point(p.X + h / 2, p.Y - h * 0.87)); + c.LineTo(new Point(p.X + h, p.Y)); + c.LineTo(new Point(p.X + h / 2, p.Y + h * 0.87)); + c.LineTo(new Point(p.X - h / 2, p.Y + h * 0.87)); + c.EndFigure(true); + } + context.DrawGeometry(fill, pen, g); + break; + } + case PinShape.Square: + context.DrawRectangle(fill, pen, new Rect(p.X - r, p.Y - r, r * 2, r * 2), 1.5, 1.5); + break; + case PinShape.Pair: + DrawPair(context, p, color, r * 0.65, filled); + break; + case PinShape.Stack: { + context.DrawRectangle(fill, pen, new Rect(p.X - r, p.Y - r, r * 2, r * 2), 1.5, 1.5); + var ink = new Pen(filled ? new SolidColorBrush(Color.Parse("#1c1b1b")) : brush, 1.1); + context.DrawLine(ink, new Point(p.X - r + 1.5, p.Y), new Point(p.X + r - 1.5, p.Y)); + context.DrawLine(ink, new Point(p.X, p.Y - r + 1.5), new Point(p.X, p.Y + r - 1.5)); + break; + } + default: + context.DrawEllipse(fill, pen, p, r, r); + break; + } + } + + public static void DrawPair(DrawingContext context, Point p, Color color, double r = 3.6, bool filled = true) { + var brush = new SolidColorBrush(color); + var pen = new Pen(brush, 1.6); + IBrush? fill = filled ? brush : null; + context.DrawLine(pen, new Point(p.X - 4, p.Y), new Point(p.X + 4, p.Y)); + context.DrawEllipse(fill, pen, new Point(p.X - 5.5, p.Y), r, r); + context.DrawRectangle(fill, pen, new Rect(p.X + 2.2, p.Y - r, r * 2, r * 2), 1, 1); + } +} + +public sealed class PinShapeIcon : Control { + public static readonly StyledProperty ShapeProperty = AvaloniaProperty.Register(nameof(Shape)); + public static readonly StyledProperty ColorProperty = AvaloniaProperty.Register(nameof(Color), "#d8d8d8"); + public static readonly StyledProperty IsPairProperty = AvaloniaProperty.Register(nameof(IsPair)); + public static readonly StyledProperty FilledProperty = AvaloniaProperty.Register(nameof(Filled), true); + + static PinShapeIcon() { + AffectsRender(ShapeProperty, ColorProperty, IsPairProperty, FilledProperty); + } + + public PinShapeIcon() { + Width = 18; + Height = 18; + } + + public PinShape Shape { + get => GetValue(ShapeProperty); + set => SetValue(ShapeProperty, value); + } + + public string Color { + get => GetValue(ColorProperty); + set => SetValue(ColorProperty, value); + } + + public bool IsPair { + get => GetValue(IsPairProperty); + set => SetValue(IsPairProperty, value); + } + + public bool Filled { + get => GetValue(FilledProperty); + set => SetValue(FilledProperty, value); + } + + public override void Render(DrawingContext context) { + var center = new Point(Bounds.Width / 2, Bounds.Height / 2); + var color = Avalonia.Media.Color.TryParse(Color, out var parsed) ? parsed : Avalonia.Media.Color.Parse("#d8d8d8"); + if (IsPair) PinGlyph.DrawPair(context, center, color); + else PinGlyph.Draw(context, center, Shape, color, 5, Filled); + } +} diff --git a/editor/LuaEditor/Controls/TypeEditor.cs b/editor/LuaEditor/Controls/TypeEditor.cs new file mode 100644 index 000000000..25ee9383b --- /dev/null +++ b/editor/LuaEditor/Controls/TypeEditor.cs @@ -0,0 +1,206 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Avalonia; +using Avalonia.Controls; +using Avalonia.Layout; +using Avalonia.Media; +using Avalonia.Styling; +using Avalonia.Threading; +using editor.LuaEditor.Editing; +using editor.LuaEditor.Types; + +namespace editor.LuaEditor.Controls; + +public sealed class TypeEditor : UserControl { + public static readonly StyledProperty TypeTextProperty = AvaloniaProperty.Register(nameof(TypeText), "", defaultBindingMode: Avalonia.Data.BindingMode.TwoWay); + public static readonly StyledProperty?> ItemsProperty = AvaloniaProperty.Register?>(nameof(Items)); + + private enum Container { Value, Array, Dictionary, Table } + + private readonly StackPanel m_buttons = new() { Orientation = Orientation.Horizontal, Spacing = 3 }; + private readonly TypePicker m_element = new(); + private readonly TypePicker m_key = new(); + private readonly Control m_keyRow; + private readonly Control m_elementRow; + private readonly TextBlock m_elementLabel = new() { Text = "Value", VerticalAlignment = VerticalAlignment.Center }; + private readonly Dictionary m_containers = []; + private Container m_container = Container.Value; + private bool m_loading; + private bool m_composePending; + + static TypeEditor() { + TypeTextProperty.Changed.AddClassHandler((e, _) => e.Load()); + ItemsProperty.Changed.AddClassHandler((e, _) => { + e.m_element.Items = e.Items; + e.m_key.Items = e.Items; + }); + } + + public TypeEditor() { + // reparenting a picker during a popup click crashes avalonia + foreach (var (container, tip) in new[] { (Container.Value, "Value"), (Container.Array, "Array"), (Container.Dictionary, "Dictionary"), (Container.Table, "Table") }) { + var icon = new PinShapeIcon { Width = 20, Height = 20, IsPair = container == Container.Dictionary }; + var button = new Button { + Content = icon, + Width = 40, + Height = 34, + MinHeight = 0, + Padding = new Thickness(0), + HorizontalContentAlignment = HorizontalAlignment.Center, + VerticalContentAlignment = VerticalAlignment.Center, + CornerRadius = new CornerRadius(6), + BorderThickness = new Thickness(0) + }; + ToolTip.SetTip(button, tip); + var picked = container; + button.Click += (_, _) => { + m_container = picked; + Refresh(); + QueueCompose(); + }; + m_containers[container] = (button, icon); + m_buttons.Children.Add(button); + } + m_element.PropertyChanged += (_, e) => { + if (e.Property == TypePicker.ValueProperty) { + Refresh(); + QueueCompose(); + } + }; + m_key.PropertyChanged += (_, e) => { + if (e.Property == TypePicker.ValueProperty) QueueCompose(); + }; + m_keyRow = Labelled(new TextBlock { Text = "Key", VerticalAlignment = VerticalAlignment.Center }, m_key); + m_elementRow = Labelled(m_elementLabel, m_element); + Content = new StackPanel { Spacing = 6, Children = { m_buttons, m_keyRow, m_elementRow } }; + Load(); + } + + public string TypeText { + get => GetValue(TypeTextProperty); + set => SetValue(TypeTextProperty, value); + } + + public IReadOnlyList? Items { + get => GetValue(ItemsProperty); + set => SetValue(ItemsProperty, value); + } + + private static IBrush? Brush(string key) { + if (Application.Current?.Resources.TryGetResource(key, ThemeVariant.Dark, out var r) == true) return r as IBrush; + return null; + } + + private void Load() { + if (m_loading) return; + m_loading = true; + try { + var text = TypeText.Trim(); + string element = text, key = "string"; + m_container = Container.Value; + if (text.Length > 0) { + try { + switch (TypeExprParser.Parse(text)) { + case ArrayType array: + m_container = Container.Array; + element = TypeFormatter.Format(array.Element); + break; + case TableType table: + m_container = Container.Dictionary; + key = TypeFormatter.Format(table.Key); + element = TypeFormatter.Format(table.Value); + break; + case PrimitiveType { Kind: PrimitiveKind.Table }: + m_container = Container.Table; + element = "table"; + break; + } + } catch (TypeSyntaxException) { + } + } + m_element.Value = element; + m_key.Value = key; + Refresh(); + } finally { + m_loading = false; + } + } + + private (PinShape Shape, string Color) Look(Container container) { + var color = PinStyle.ColorOf(Safe(m_element.Value)); + return container switch { + Container.Array => (PinShape.Stack, color), + Container.Table => (PinShape.Diamond, PinStyle.Table), + Container.Dictionary => (PinShape.Circle, color), + _ => (PinStyle.ShapeOf(Safe(m_element.Value)), color) + }; + } + + private static LuaType Safe(string text) { + try { + return string.IsNullOrWhiteSpace(text) ? LuaType.Any : TypeExprParser.Parse(text); + } catch (TypeSyntaxException) { + return LuaType.Any; + } + } + + private void Refresh() { + foreach (var (container, parts) in m_containers) { + var (shape, color) = Look(container); + var chosen = container == m_container; + parts.Icon.Shape = shape; + parts.Icon.Color = color; + parts.Icon.Filled = chosen; + parts.Button.Background = chosen ? Brush("Bg5") : Brush("Bg1"); + parts.Button.BorderThickness = new Thickness(chosen ? 1.5 : 0); + parts.Button.BorderBrush = chosen ? Brush("TextMuted") : null; + } + m_keyRow.IsVisible = m_container == Container.Dictionary; + m_elementRow.IsVisible = m_container != Container.Table; + m_elementLabel.IsVisible = m_container == Container.Dictionary; + } + + private static Control Labelled(Control label, Control picker) { + var grid = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*") }; + label.Margin = new Thickness(0, 0, 8, 0); + if (label is TextBlock text) text.Foreground = Brush("TextMuted"); + grid.Children.Add(label); + Grid.SetColumn(picker, 1); + grid.Children.Add(picker); + return grid; + } + + private void QueueCompose() { + if (m_loading || m_composePending) return; + m_composePending = true; + Dispatcher.UIThread.Post(() => { + m_composePending = false; + try { + Compose(); + } catch (Exception e) { + System.Diagnostics.Debug.WriteLine("TypeEditor: " + e.Message); + } + }, DispatcherPriority.Background); + } + + private void Compose() { + if (m_loading) return; + var element = m_element.Value.Length == 0 ? "any" : m_element.Value; + var key = m_key.Value.Length == 0 ? "string" : m_key.Value; + var wrapped = element.Contains('|') || element.StartsWith("fun(", StringComparison.Ordinal) ? "(" + element + ")" : element; + var text = m_container switch { + Container.Array => wrapped + "[]", + Container.Dictionary => $"table<{key}, {element}>", + Container.Table => "table", + _ => element + }; + if (text == TypeText) return; + m_loading = true; + try { + SetCurrentValue(TypeTextProperty, text); + } finally { + m_loading = false; + } + } +} diff --git a/editor/LuaEditor/Controls/TypePicker.cs b/editor/LuaEditor/Controls/TypePicker.cs new file mode 100644 index 000000000..41d440250 --- /dev/null +++ b/editor/LuaEditor/Controls/TypePicker.cs @@ -0,0 +1,237 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Avalonia; +using Avalonia.Controls; +using Avalonia.Controls.Primitives; +using Avalonia.Input; +using Avalonia.Layout; +using Avalonia.Media; +using Avalonia.Styling; +using Style = Avalonia.Styling.Style; +using Avalonia.Threading; +using Lucide.Avalonia; +using editor.LuaEditor.Editing; + +namespace editor.LuaEditor.Controls; + +public sealed record PickItem(string Value, string Group, LucideIconKind Icon, string Color, PinShape? Glyph = null); + +public sealed class PickRow { + public string Text { get; init; } = ""; + public string Count { get; init; } = ""; + public bool IsGroup { get; init; } + public bool IsOpen { get; init; } + public int Depth { get; init; } + public string Key { get; init; } = ""; + public PickItem? Item { get; init; } + + public static List Tree(IReadOnlyList items, ISet open, bool everythingOpen) { + var rows = new List(); + foreach (var group in items.GroupBy(i => i.Group)) { + var isOpen = everythingOpen || open.Contains(group.Key); + rows.Add(new PickRow { Text = group.Key, Count = group.Count().ToString(), IsGroup = true, IsOpen = isOpen, Key = group.Key }); + if (isOpen) rows.AddRange(group.Select(i => new PickRow { Text = i.Value, Depth = 1, Item = i, Key = i.Value })); + } + return rows; + } +} + +public sealed class TypePicker : UserControl { + public static readonly StyledProperty ValueProperty = AvaloniaProperty.Register(nameof(Value), "", defaultBindingMode: Avalonia.Data.BindingMode.TwoWay); + public static readonly StyledProperty?> ItemsProperty = AvaloniaProperty.Register?>(nameof(Items)); + + private readonly Button m_button = new(); + private readonly StackPanel m_face = new() { Orientation = Orientation.Horizontal, Spacing = 8 }; + private readonly Popup m_popup = new(); + private readonly TextBox m_search = new() { PlaceholderText = "Search...", MinHeight = 0, Padding = new Thickness(6, 3), FontSize = 13 }; + private readonly ListBox m_list = new(); + private readonly HashSet m_open = []; + + static TypePicker() { + ValueProperty.Changed.AddClassHandler((p, _) => p.ShowFace()); + ItemsProperty.Changed.AddClassHandler((p, _) => p.ShowFace()); + } + + public TypePicker() { + m_button.HorizontalAlignment = HorizontalAlignment.Stretch; + m_button.HorizontalContentAlignment = HorizontalAlignment.Left; + m_button.CornerRadius = new CornerRadius(6); + m_button.Padding = new Thickness(8, 4); + m_button.MinHeight = 34; + m_button.FontSize = 15; + m_button.FontFamily = new FontFamily("FiraCode Nerd Font,Consolas,monospace"); + m_button.VerticalContentAlignment = VerticalAlignment.Center; + m_button.Background = Brush("Bg1"); + m_button.BorderThickness = new Thickness(0); + m_button.Content = m_face; + m_button.Click += (_, _) => Open(); + + m_list.ItemTemplate = new Avalonia.Controls.Templates.FuncDataTemplate((row, _) => Build(row)); + m_list.Background = Brushes.Transparent; + m_list.Padding = new Thickness(0); + m_list.Styles.Add(new Style(x => x.OfType()) { + Setters = { + new Setter(ListBoxItem.PaddingProperty, new Thickness(6, 0)), + new Setter(ListBoxItem.MinHeightProperty, 0d), + new Setter(ListBoxItem.HeightProperty, 22d), + new Setter(ListBoxItem.CornerRadiusProperty, new CornerRadius(4)) + } + }); + m_list.Tapped += (_, _) => Tapped(); + m_search.TextChanged += (_, _) => Fill(); + m_search.KeyDown += OnKey; + + var card = new Border { + Background = Brush("Bg3"), + CornerRadius = new CornerRadius(8), + Padding = new Thickness(8), + BorderBrush = Brush("Bg4"), + BorderThickness = new Thickness(1), + Child = new StackPanel { + Spacing = 6, + Children = { m_search, new ScrollViewer { MaxHeight = 240, HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Disabled, Content = m_list } } + } + }; + m_popup.Child = card; + m_popup.IsLightDismissEnabled = true; + m_popup.Placement = PlacementMode.Bottom; + m_popup.PlacementTarget = m_button; + m_popup.MinWidth = 220; + m_popup.MaxWidth = 300; + + Content = new Panel { Children = { m_button, m_popup } }; + } + + public string Value { + get => GetValue(ValueProperty); + set => SetValue(ValueProperty, value); + } + + public IReadOnlyList? Items { + get => GetValue(ItemsProperty); + set => SetValue(ItemsProperty, value); + } + + private static IBrush? Brush(string key) { + if (Application.Current?.Resources.TryGetResource(key, ThemeVariant.Dark, out var r) == true) return r as IBrush; + return null; + } + + private PickItem? Current => Items?.FirstOrDefault(i => i.Value == Value); + + private static Control IconOf(PickItem? item, string fallbackColor = "TextMuted") { + if (item?.Glyph is { } shape) return new PinShapeIcon { Shape = shape, Color = item.Color.StartsWith('#') ? item.Color : "#d8d8d8", Width = 14, Height = 14 }; + return new LucideIcon { Kind = item?.Icon ?? LucideIconKind.CircleDot, Size = 13, StrokeWidth = 2.5, Foreground = Brush(item?.Color ?? fallbackColor) }; + } + + private void ShowFace() { + m_face.Children.Clear(); + var current = Current; + m_face.Children.Add(IconOf(current)); + m_face.Children.Add(new TextBlock { Text = Value.Length == 0 ? "(none)" : Value, VerticalAlignment = VerticalAlignment.Center, TextTrimming = TextTrimming.CharacterEllipsis }); + m_face.Children.Add(new LucideIcon { Kind = LucideIconKind.ChevronDown, Size = 14, StrokeWidth = 2, Foreground = Brush("TextMuted"), VerticalAlignment = VerticalAlignment.Center }); + } + + private void Open() { + m_open.Clear(); + var first = Items?.FirstOrDefault()?.Group; + if (first is not null) m_open.Add(first); + if (Current is { } current) m_open.Add(current.Group); + m_search.Text = ""; + Fill(Value); + m_popup.IsOpen = true; + Dispatcher.UIThread.Post(() => m_search.Focus()); + } + + private void Fill(string? keep = null) { + var items = Items ?? []; + var query = (m_search.Text ?? "").Trim(); + var shown = query.Length == 0 ? items : items.Where(i => i.Value.Contains(query, StringComparison.OrdinalIgnoreCase)).ToList(); + var rows = PickRow.Tree(shown, m_open, query.Length > 0); + m_list.ItemsSource = rows; + var at = keep is null ? -1 : rows.FindIndex(r => r.Item is not null && r.Key == keep); + m_list.SelectedIndex = at >= 0 ? at : rows.FindIndex(r => r.Item is not null) is var first and >= 0 && query.Length > 0 ? first : 0; + Reveal(); + } + + private Control Build(PickRow? row) { + if (row is null) return new Panel(); + var grid = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,Auto,*,Auto"), Height = 22, Margin = new Thickness(row.Depth * 14, 0, 0, 0) }; + if (row.IsGroup) { + grid.Children.Add(new TextBlock { Text = row.IsOpen ? "▾" : "▸", FontSize = 11, Foreground = Brush("TextMuted"), Margin = new Thickness(0, 0, 6, 0), VerticalAlignment = VerticalAlignment.Center }); + } else { + var icon = IconOf(row.Item); + Grid.SetColumn(icon, 1); + icon.Margin = new Thickness(0, 0, 6, 0); + grid.Children.Add(icon); + } + var text = new TextBlock { Text = row.Text, FontSize = 12, VerticalAlignment = VerticalAlignment.Center, FontWeight = row.IsGroup ? FontWeight.Bold : FontWeight.Normal, TextTrimming = TextTrimming.CharacterEllipsis }; + Grid.SetColumn(text, 2); + grid.Children.Add(text); + if (row.Count.Length > 0) { + var count = new TextBlock { Text = row.Count, Foreground = Brush("TextMuted"), FontSize = 11, VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(8, 0, 4, 0) }; + Grid.SetColumn(count, 3); + grid.Children.Add(count); + } + return grid; + } + + private void Reveal() { + Dispatcher.UIThread.Post(() => { + try { + if (m_list.SelectedItem is { } selected) m_list.ScrollIntoView(selected); + } catch (Exception) { + } + }, DispatcherPriority.Loaded); + } + + private void Tapped() { + if (m_list.SelectedItem is not PickRow row) return; + if (row.IsGroup) Toggle(row); + else Choose(row); + } + + private void Toggle(PickRow row, bool? open = null) { + if ((m_search.Text ?? "").Trim().Length > 0) return; + if (open ?? !m_open.Contains(row.Key)) m_open.Add(row.Key); + else m_open.Remove(row.Key); + Fill(); + var at = (m_list.ItemsSource as List)?.FindIndex(r => r.IsGroup && r.Key == row.Key) ?? -1; + if (at >= 0) m_list.SelectedIndex = at; + } + + private void Choose(PickRow row) { + if (row.Item is null) return; + Value = row.Item.Value; + m_popup.IsOpen = false; + } + + private void OnKey(object? sender, KeyEventArgs e) { + switch (e.Key) { + case Key.Down: + m_list.SelectedIndex = Math.Min(m_list.SelectedIndex + 1, m_list.ItemCount - 1); + Reveal(); + break; + case Key.Up: + m_list.SelectedIndex = Math.Max(m_list.SelectedIndex - 1, 0); + Reveal(); + break; + case Key.Right when m_list.SelectedItem is PickRow { IsGroup: true } closed: + Toggle(closed, true); + break; + case Key.Left when m_list.SelectedItem is PickRow { IsGroup: true } open: + Toggle(open, false); + break; + case Key.Enter: + Tapped(); + break; + case Key.Escape: + m_popup.IsOpen = false; + break; + default: + return; + } + e.Handled = true; + } +} diff --git a/editor/LuaEditor/LuaEditorWindow.cs b/editor/LuaEditor/LuaEditorWindow.cs new file mode 100644 index 000000000..b880752f5 --- /dev/null +++ b/editor/LuaEditor/LuaEditorWindow.cs @@ -0,0 +1,63 @@ +using System; +using System.Threading.Tasks; +using Avalonia; +using Avalonia.Controls; +using Avalonia.Data; +using Avalonia.Media; + +namespace editor.LuaEditor; + +public sealed class LuaEditorWindow : Window { + private static LuaEditorWindow? s_open; + + private readonly LuaGraphEditorViewModel m_vm; + private Action? m_closed; + private bool m_confirmed; + + public static bool IsOpen => s_open is not null; + + public static void ShowFor(LuaGraphEditorViewModel vm, Window? owner, Action? closed = null) { + if (s_open is { } open) { + open.m_closed = closed ?? open.m_closed; + if (open.WindowState == WindowState.Minimized) open.WindowState = WindowState.Normal; + open.Activate(); + return; + } + var window = new LuaEditorWindow(vm) { m_closed = closed }; + s_open = window; + if (owner is not null) window.Show(owner); + else window.Show(); + } + + public static void CloseOpen() => s_open?.Close(); + + private LuaEditorWindow(LuaGraphEditorViewModel vm) { + m_vm = vm; + Width = 1500; + Height = 920; + MinWidth = 960; + MinHeight = 560; + WindowStartupLocation = WindowStartupLocation.CenterOwner; + if (Application.Current?.TryFindResource("Bg2", Application.Current.ActualThemeVariant, out var bg) == true && bg is IBrush brush) Background = brush; + DataContext = vm; + Bind(TitleProperty, new Binding(nameof(LuaGraphEditorViewModel.Title)) { StringFormat = "Lua Graph - {0}" }); + Content = new LuaGraphEditorView { DataContext = vm }; + Closing += OnClosing; + Closed += (_, _) => { + if (ReferenceEquals(s_open, this)) s_open = null; + m_closed?.Invoke(); + }; + } + + private void OnClosing(object? sender, WindowClosingEventArgs e) { + if (m_confirmed || !m_vm.IsDirty) return; + e.Cancel = true; + _ = ConfirmThenClose(); + } + + private async Task ConfirmThenClose() { + if (!await m_vm.ConfirmCloseCurrentAsync()) return; + m_confirmed = true; + Close(); + } +} diff --git a/editor/LuaEditor/LuaGraphEditorView.axaml b/editor/LuaEditor/LuaGraphEditorView.axaml new file mode 100644 index 000000000..d4cc06684 --- /dev/null +++ b/editor/LuaEditor/LuaGraphEditorView.axaml @@ -0,0 +1,587 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/editor/LuaEditor/LuaGraphEditorView.axaml.cs b/editor/LuaEditor/LuaGraphEditorView.axaml.cs new file mode 100644 index 000000000..2e1a3d65d --- /dev/null +++ b/editor/LuaEditor/LuaGraphEditorView.axaml.cs @@ -0,0 +1,450 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Avalonia; +using Avalonia.Controls; +using Avalonia.Input; +using Avalonia.Layout; +using Avalonia.Controls.Primitives; +using Avalonia.Threading; +using editor.Components.Elements; +using Avalonia.Interactivity; +using editor.LuaEditor.Canvas; +using editor.LuaEditor.Editing; +using editor.LuaEditor.Graph; +using editor.LuaEditor.Layout; +using editor.Workspace; + +namespace editor.LuaEditor; + +public partial class LuaGraphEditorView : UserControl { + private SearchRequest? m_search; + private ConstantEditRequest? m_constant; + private GroupEditRequest? m_group; + + public LuaGraphEditorView() { + InitializeComponent(); + GraphView.SearchRequested += OpenSearch; + GraphView.ConstantEditRequested += OpenConstantEditor; + GraphView.GroupEditRequested += OpenGroupEditor; + GraphView.NodeMenuRequested += OpenNodeMenu; + GraphView.ChoiceMenuRequested += OpenChoiceMenu; + GraphView.RenameRequested += (box, text, commit) => OpenTextEditor(box, text, commit); + GraphView.FindRequested += () => OpenSearch(new SearchRequest(default, new Point(80, 60), null, null, null, false)); + GraphView.SaveRequested += () => Vm?.SaveCommand.Execute(null); + + Rows.PointerMoved += OnVariableMoved; + Rows.PointerReleased += OnRowReleased; + SearchBox.TextChanged += (_, _) => FillSearch(); + SearchBox.KeyDown += OnSearchKey; + SearchPanel.GetObservable(IsKeyboardFocusWithinProperty).Subscribe(new Avalonia.Reactive.AnonymousObserver(inside => { + if (!inside && SearchPanel.IsVisible) Dispatcher.UIThread.Post(() => { if (!SearchPanel.IsKeyboardFocusWithin) CloseSearch(refocus: false); }); + })); +SearchList.DoubleTapped += (_, _) => CommitSearch(); + ConstantBox.KeyDown += OnConstantKey; + ConstantBox.LostFocus += (_, _) => CloseConstantEditor(commit: false); + GroupBox.KeyDown += OnGroupKey; + GroupBox.LostFocus += (_, _) => CloseGroupEditor(commit: true); + DataContextChanged += (_, _) => { + WireTree(); + if (Vm is { } vm) vm.FocusRequested += node => GraphView.FrameNodes([node]); + }; + } + + private LuaGraphEditorViewModel? Vm => DataContext as LuaGraphEditorViewModel; + + private const double FoldedDetailsHeight = 46; + private bool m_detailsFolded; + private double m_detailsHeight; + private Avalonia.Threading.DispatcherTimer? m_detailsTimer; + + private void OnInspectorHeaderPressed(object? sender, PointerPressedEventArgs e) { + var rows = LeftPanel.RowDefinitions; + var details = rows[2]; + var script = rows[0]; + m_detailsTimer?.Stop(); + var current = DetailsCard.Bounds.Height; + m_detailsFolded = !m_detailsFolded; + InspectorChevron.Kind = m_detailsFolded ? Lucide.Avalonia.LucideIconKind.ChevronRight : Lucide.Avalonia.LucideIconKind.ChevronDown; + details.MinHeight = 0; + script.Height = new GridLength(1, GridUnitType.Star); + if (m_detailsFolded) { + m_detailsHeight = current; + m_detailsTimer = editor.Components.Elements.CollapseAnimator.Run(current, FoldedDetailsHeight, h => details.Height = new GridLength(h), () => details.Height = new GridLength(FoldedDetailsHeight)); + } else { + var target = Math.Max(m_detailsHeight, 140); + m_detailsTimer = editor.Components.Elements.CollapseAnimator.Run(current, target, h => details.Height = new GridLength(h), () => { + script.Height = new GridLength(3, GridUnitType.Star); + details.Height = new GridLength(2, GridUnitType.Star); + }); + } + e.Handled = true; + } + + private void OpenSearch(SearchRequest request) { + if (Vm?.Session is null) return; + CloseConstantEditor(commit: false); + m_search = request; + SearchPanel.Margin = new Thickness(Math.Clamp(request.Screen.X, 0, Math.Max(0, Bounds.Width - 640)), Math.Clamp(request.Screen.Y, 0, Math.Max(0, Bounds.Height - 480)), 0, 0); + SearchPanel.IsVisible = true; + SearchBox.Text = ""; + m_searchOpen.Clear(); + m_searchOpen.Add("This script"); + if ((request.From is not null || request.Into is not null) && Vm.Session.Search("", request.From?.Type, request.Into?.Expected, request.StatementsOnly).Count <= 40) + foreach (var e in Vm.Session.Search("", request.From?.Type, request.Into?.Expected, request.StatementsOnly)) { + m_searchOpen.Add(SearchRow.GroupOf(e)); + m_searchOpen.Add(SearchRow.GroupOf(e) + "/" + SearchRow.CategoryOf(e)); + } + FillSearch(); + SearchBox.Focus(); + } + + private readonly HashSet m_searchOpen = []; + + private void FillSearch(string? keepKey = null) { + if (m_search is null || Vm?.Session is not { } session) return; + var producing = m_search.From?.Type; + var expecting = m_search.Into?.Expected; + var text = SearchBox.Text ?? ""; + var all = session.Search(text, producing, expecting, m_search.StatementsOnly).ToList(); + var searching = text.Trim().Length > 0; + var rows = SearchRow.Tree(searching ? all.Take(120).ToList() : all, m_searchOpen, searching); + SearchList.ItemsSource = rows; + var at = keepKey is null ? -1 : rows.FindIndex(r => r.Key == keepKey); + SearchList.SelectedIndex = at >= 0 ? at : rows.FindIndex(r => !r.IsGroup) is var first and >= 0 && searching ? first : 0; + } + + private void ToggleSearchGroup(SearchRow group, bool? open = null) { + if (!group.IsGroup || (SearchBox.Text ?? "").Trim().Length > 0) return; + var want = open ?? !m_searchOpen.Contains(group.Key); + if (want) m_searchOpen.Add(group.Key); + else m_searchOpen.Remove(group.Key); + FillSearch(group.Key); + } + + private void OnSearchKey(object? sender, KeyEventArgs e) { + switch (e.Key) { + case Key.Escape: + CloseSearch(); + e.Handled = true; + break; + case Key.Right when SearchList.SelectedItem is SearchRow { IsGroup: true } closed: + ToggleSearchGroup(closed, true); + e.Handled = true; + break; + case Key.Left when SearchList.SelectedItem is SearchRow { IsGroup: true } open: + ToggleSearchGroup(open, false); + e.Handled = true; + break; + case Key.Enter: + CommitSearch(); + e.Handled = true; + break; + case Key.Down: + SearchList.SelectedIndex = Math.Min(SearchList.SelectedIndex + 1, SearchList.ItemCount - 1); + SearchList.ScrollIntoView(SearchList.SelectedItem!); + e.Handled = true; + break; + case Key.Up: + SearchList.SelectedIndex = Math.Max(SearchList.SelectedIndex - 1, 0); + SearchList.ScrollIntoView(SearchList.SelectedItem!); + e.Handled = true; + break; + } + } + + private void CommitSearch() { + if (SearchList.SelectedItem is SearchRow { IsGroup: true } group) { + ToggleSearchGroup(group); + return; + } + if (m_search is { } request && (SearchList.SelectedItem as SearchRow)?.Entry is { } entry && Vm?.Session is { } session) + session.Create(entry, request.World, request.From, request.Into, request.Insert); + CloseSearch(); + } + + private void CloseSearch(bool refocus = true) { + m_search = null; + SearchPanel.IsVisible = false; + if (refocus) GraphView.Focus(); + } + + private void OnAction(object? sender, RoutedEventArgs e) { + if ((sender as Control)?.Tag is string name && Enum.TryParse(name, out var action)) { + GraphView.Execute(action); + GraphView.Focus(); + } + } + + private void OnAlignTop(object? sender, RoutedEventArgs e) => GraphView.Execute(CanvasAction.AlignTop); + + private void OnAlignLeft(object? sender, RoutedEventArgs e) => GraphView.Execute(CanvasAction.AlignLeft); + + private void OnStraighten(object? sender, RoutedEventArgs e) => GraphView.Execute(CanvasAction.Straighten); + + private void OnFrameAll(object? sender, RoutedEventArgs e) => GraphView.FrameAll(); + + private void OnFindClick(object? sender, RoutedEventArgs e) => OpenSearch(new SearchRequest(default, new Point(80, 20), null, null, null, false)); + + private void OpenConstantEditor(ConstantEditRequest request) { + m_constant = request; + var height = Math.Max(request.Screen.Height, 20); + ConstantBox.Margin = new Thickness(request.Screen.X, request.Screen.Y - (height - request.Screen.Height) / 2, 0, 0); + ConstantBox.Width = Math.Max(request.Screen.Width, 40); + ConstantBox.Height = height; + ConstantBox.VerticalContentAlignment = VerticalAlignment.Center; + ConstantBox.Text = request.Text; + ConstantBox.IsVisible = true; + // the opening click would otherwise steal focus back + Dispatcher.UIThread.Post(() => { + ConstantBox.Focus(); + ConstantBox.SelectAll(); + }, DispatcherPriority.Input); + } + + private void OnConstantKey(object? sender, KeyEventArgs e) { + if (e.Key == Key.Enter) CloseConstantEditor(commit: true); + else if (e.Key == Key.Escape) CloseConstantEditor(commit: false); + else return; + e.Handled = true; + } + + private Action? m_textCommit; + + private void OpenTextEditor(Avalonia.Rect screen, string text, Action commit) { + m_textCommit = commit; + m_constant = new ConstantEditRequest(null!, screen, text); + ConstantBox.Margin = new Thickness(screen.X, screen.Y, 0, 0); + ConstantBox.Width = Math.Max(220, screen.Width); + ConstantBox.Text = text; + ConstantBox.IsVisible = true; + ConstantBox.Focus(); + ConstantBox.SelectAll(); + } + + private void OpenChoiceMenu(InputPin pin, Avalonia.Rect screen, IReadOnlyList choices) { + var menu = new ContextMenu(); + foreach (var choice in choices) { + var item = new MenuItem { Header = choice.Label, FontWeight = choice.IsCurrent ? Avalonia.Media.FontWeight.Bold : Avalonia.Media.FontWeight.Normal }; + var apply = choice.Apply; + item.Click += (_, _) => apply(); + menu.Items.Add(item); + } + menu.Placement = PlacementMode.Bottom; + menu.PlacementRect = new PixelRect((int)screen.X, (int)screen.Y, (int)screen.Width, (int)screen.Height).ToRect(1); + menu.Open(GraphView); + } + + private static string FieldText(TableField field) => field.Kind switch { TableFieldKind.Named => "field " + field.Name, TableFieldKind.Keyed => "entry [" + NodeShape.KeyText(field.Key!) + "]", _ => "item " + field.Value.Name }; + + private void OpenNodeMenu(GraphNode node, Point screen) { + if (Vm?.Session is not { } session) return; + if (!session.Selection.Contains(node)) session.Select([node]); + var menu = new ContextMenu(); + var call = NodeShape.CallOf(node); + if (call is not null && session.CanSwitchCallStyle(call)) { + var method = call.Style == CallStyle.Method; + var name = call.Method ?? (call.Target.Source?.Owner as MemberGet)?.Name ?? "fn"; + var item = new MenuItem { Header = method ? $"Write as a.{name}(a)" : $"Write as a:{name}()" }; + item.Click += (_, _) => session.SetCallStyle(call, method ? CallStyle.Function : CallStyle.Method); + menu.Items.Add(item); + } + if (node is TableNode table) { + var kind = GraphSession.EntryKindOf(table); + var add = new MenuItem { Header = kind switch { TableFieldKind.Positional => "Add item", TableFieldKind.Keyed => "Add entry [key] = value", _ => "Add field name = value" } }; + add.Click += (_, _) => session.AddTableEntry(table, kind); + menu.Items.Add(add); + foreach (var entry in table.Fields.Where(f => f.Kind != TableFieldKind.Positional).ToList()) { + var target = entry; + var rename = new MenuItem { Header = entry.Kind == TableFieldKind.Named ? $"Rename field {entry.Name}..." : $"Change key [{NodeShape.KeyText(entry.Key!)}]..." }; + rename.Click += (_, _) => { + var box = new Avalonia.Rect(screen.X, screen.Y, 220, 24); + if (target.Kind == TableFieldKind.Named) OpenTextEditor(box, target.Name ?? "", text => session.RenameTableField(table, target, text.Trim())); + else OpenTextEditor(box, NodeShape.KeyText(target.Key!), text => session.SetTableKey(table, target, text)); + }; + menu.Items.Add(rename); + } + for (var index = table.Fields.Count - 1; index >= 0; index--) { + var at = index; + var removeEntry = new MenuItem { Header = $"Remove {FieldText(table.Fields[at])}" }; + removeEntry.Click += (_, _) => session.RemoveTableEntry(table, at); + menu.Items.Add(removeEntry); + } + menu.Items.Add(new Separator()); + } + if (node is MemberGet { Object.Source: not { Binding: { } } } || node is AssignStatement { Targets: [{ Kind: TargetKind.Member }] }) { + var access = node; + var current = node is MemberGet member ? member.Name : ((AssignStatement)node).Targets[0].Name ?? ""; + var renameAccess = new MenuItem { Header = $"Rename field {current}..." }; + renameAccess.Click += (_, _) => OpenTextEditor(new Avalonia.Rect(screen.X, screen.Y, 220, 24), current, text => session.RenameAccess(access, text.Trim())); + menu.Items.Add(renameAccess); + } + if (call is not null) { + var add = new MenuItem { Header = "Add argument" }; + + add.Click += (_, _) => session.AddCallArgument(call); + menu.Items.Add(add); + if (call.Args.Count > 0) { + var remove = new MenuItem { Header = "Remove last argument" }; + remove.Click += (_, _) => session.RemoveLastCallArgument(call); + menu.Items.Add(remove); + } + } + if (node is Statement statement) { + var current = string.Join(" ", statement.LeadingLines.Where(l => !l.TrimStart().StartsWith("---@", StringComparison.Ordinal)).Select(l => l.TrimStart('-', ' '))); + var edit = new MenuItem { Header = "Edit comment..." }; + edit.Click += (_, _) => OpenTextEditor(new Avalonia.Rect(screen.X, screen.Y, 260, 24), current, text => session.SetComment(statement, text.Length == 0 ? null : text)); + menu.Items.Add(edit); + } + var copy = new MenuItem { Header = "Copy", InputGesture = new KeyGesture(Key.C, KeyModifiers.Control) }; + copy.Click += (_, _) => GraphView.Execute(CanvasAction.Copy); + menu.Items.Add(copy); + var paste = new MenuItem { Header = "Paste", InputGesture = new KeyGesture(Key.V, KeyModifiers.Control) }; + paste.Click += (_, _) => GraphView.Execute(CanvasAction.Paste); + menu.Items.Add(paste); + var group = new MenuItem { Header = "Group into a function", InputGesture = new KeyGesture(Key.G) }; + group.Click += (_, _) => session.GroupSelectionAsFunction(); + menu.Items.Add(group); + var duplicate = new MenuItem { Header = "Duplicate" }; + duplicate.Click += (_, _) => session.Duplicate(); + menu.Items.Add(duplicate); + var delete = new MenuItem { Header = "Delete" }; + delete.Click += (_, _) => session.Delete(session.Selection.ToList()); + menu.Items.Add(delete); + menu.Open(GraphView); + } + + private void CloseConstantEditor(bool commit) { + if (m_constant is not { } request) return; + m_constant = null; + ConstantBox.IsVisible = false; + var textCommit = m_textCommit; + m_textCommit = null; + if (commit && textCommit is not null) textCommit(ConstantBox.Text ?? ""); + else if (commit && Vm?.Session is { } session) session.SetConstant(request.Pin, ConstantBox.Text ?? ""); + GraphView.Focus(); + } + + private void OpenGroupEditor(GroupEditRequest request) { + m_group = request; + GroupBox.Margin = new Thickness(request.Screen.X + 6, request.Screen.Y, 0, 0); + GroupBox.Width = Math.Max(160, request.Screen.Width - 12); + GroupBox.Text = request.Group.Title; + GroupBox.IsVisible = true; + GroupBox.Focus(); + GroupBox.SelectAll(); + } + + private void OnGroupKey(object? sender, KeyEventArgs e) { + if (e.Key == Key.Enter) CloseGroupEditor(commit: true); + else if (e.Key == Key.Escape) CloseGroupEditor(commit: false); + else return; + e.Handled = true; + } + + private void CloseGroupEditor(bool commit) { + if (m_group is not { } request) return; + m_group = null; + GroupBox.IsVisible = false; + if (commit && !string.IsNullOrWhiteSpace(GroupBox.Text)) { + request.Group.Title = GroupBox.Text.Trim(); + Vm?.Session?.CommitLayout(); + } + GraphView.InvalidateVisual(); + GraphView.Focus(); + } + + private LuaGraphEditorViewModel? m_treeVm; + + private void WireTree() { + if (m_treeVm is not null) { + m_treeVm.Variables.CollectionChanged -= OnRowsChanged; + m_treeVm.PropertyChanged -= OnTreeVmChanged; + } + m_treeVm = Vm; + if (m_treeVm is null) return; + m_treeVm.Variables.CollectionChanged += OnRowsChanged; + m_treeVm.PropertyChanged += OnTreeVmChanged; + RefreshConnector(); + } + + private void OnRowsChanged(object? sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) => RefreshConnector(); + + private void OnTreeVmChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e) { + if (e.PropertyName == nameof(LuaGraphEditorViewModel.SelectedVariable)) RefreshConnector(); + } + + private void RefreshConnector() { + if (m_treeVm is not { } vm) return; + Connector.Rows = vm.Variables.ToList(); + Connector.SelectedIndex = vm.SelectedVariable is { } selected ? vm.Variables.IndexOf(selected) : -1; + } + + private readonly HierarchyRowPress m_rowPress = new(); + + private void OnRowPressed(object? sender, PointerPressedEventArgs e) { + if (sender is not Control control || control.DataContext is not VariableRow row || Vm is not { } vm) return; + var properties = e.GetCurrentPoint(control).Properties; + m_rowPress.Clear(); + if (properties.IsRightButtonPressed) { + if (row.Kind is VariableRowKind.Field or VariableRowKind.Tick && row.Variable is not null) + OpenRowMenu(control, row); + return; + } + if (!properties.IsLeftButtonPressed) return; + var wasSelected = ReferenceEquals(vm.SelectedVariable, row); + vm.SelectRow(row); + if (row.Kind == VariableRowKind.Tick) { + if (row.Variable?.Declaration is FunctionDecl tick) GraphView.ShowFunction(tick); + else if (vm.CanEdit && vm.Session is { } session && ScriptInfo.Find(session.Graph) is not null && + session.AddFunction(row.Id["tick/".Length..]) && vm.FindRow(row.Id) is { Variable.Declaration: FunctionDecl created } newRow) { + vm.SelectRow(newRow); + GraphView.ShowFunction(created); + } + return; + } + if (row.Kind == VariableRowKind.Local && e.ClickCount >= 2 && row.Variable?.Declaration is FunctionDecl local) { + GraphView.ShowFunction(local); + return; + } + m_rowPress.Begin(row, e, this, wasSelected); + } + + private void OnRowReleased(object? sender, PointerReleasedEventArgs e) { + if (m_rowPress.TakeClick(e) is not { } click) return; + if (click.Row.Kind == VariableRowKind.Method && click.Row.Variable?.Declaration is FunctionDecl function) + GraphView.ShowFunction(function); + else if (click.WasSelected) Vm?.SetSection(click.Row); + } + + private void OpenRowMenu(Control control, VariableRow row) { + if (Vm is not { CanEdit: true, Session: { } session } vm || row.Variable is not { } variable) return; + vm.SelectRow(row); + var items = new List(); + void Item(string title, Action action) { + var item = new MenuItem { Header = title }; + item.Click += (_, _) => action(); + items.Add(item); + } + if (row.Kind == VariableRowKind.Field && variable.Declaration is AssignStatement field) { + Item("Get", () => GraphView.CreateHierarchyNode(row, set: false)); + Item("Set", () => GraphView.CreateHierarchyNode(row, set: true)); + Item("Rename", () => OpenTextEditor(new Avalonia.Rect(12, 70, 230, 28), variable.Name, name => vm.CommitName(name.Trim()))); + Item("Duplicate", () => session.DuplicateField(field, vm.FreshName(variable.Name + "_copy"))); + } + Item("Delete", () => session.Delete([variable.Declaration])); + var menu = new ContextMenu { ItemsSource = items }; + menu.Open(control); + } + + private async void OnVariableMoved(object? sender, PointerEventArgs e) { + if (m_rowPress.TakeDrag(e, this) is not { Row.CanDrag: true } drag || Vm is not { CanEdit: true, Session: { } session }) return; + var data = new DataTransfer(); + data.Add(DataTransferItem.Create(VariableDrag.Format, new HierarchyDrag(session, drag.Row))); + await DragDrop.DoDragDropAsync(drag.Args, data, DragDropEffects.Copy); + } + + private void OnProblemSelected(object? sender, SelectionChangedEventArgs e) { + if (e.AddedItems.OfType().FirstOrDefault() is { } row) Vm?.FocusProblem(row); + } +} diff --git a/editor/LuaEditor/LuaGraphEditorViewModel.Files.cs b/editor/LuaEditor/LuaGraphEditorViewModel.Files.cs new file mode 100644 index 000000000..91fd35557 --- /dev/null +++ b/editor/LuaEditor/LuaGraphEditorViewModel.Files.cs @@ -0,0 +1,139 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Threading.Tasks; +using Avalonia.Threading; +using editor.Assets; +using editor.Assets.Types; +using editor.Components.Modals; +using editor.LuaEditor.Editing; + +namespace editor.LuaEditor; + +public sealed partial class LuaGraphEditorViewModel { + private GraphDocument? m_document; + private readonly List m_watchers = []; + private readonly DispatcherTimer m_debounce = new() { Interval = TimeSpan.FromMilliseconds(350) }; + private bool m_typesChanged; + private bool m_asking; + + public bool IsDirty => Session?.IsDirty == true; + + public string CurrentPath { get; private set; } = ""; + + public string CurrentUid { get; private set; } = ""; + + public void OpenFile(string uid, string virtualPath, BaseAsset definition, string? contentSourceRealPath = null) { + StopWatching(); + CurrentUid = uid; + CurrentPath = virtualPath; + Title = Path.GetFileName(virtualPath); + var stdlib = Path.Combine(AppContext.BaseDirectory, "Resources", "lua", "stdlib"); + m_document = GraphDocument.Open(ProjectContext.Resolve(virtualPath), ProjectContext.ProjectPath, stdlib); + if (contentSourceRealPath is not null && File.Exists(contentSourceRealPath) && m_document.LoadRecovered(File.ReadAllText(contentSourceRealPath))) Status = "Recovered unsaved changes"; + ApplyDocument(); + var real = ProjectContext.Resolve(virtualPath); + m_lockedByOther = editor.Git.GitService.Current is { IsAvailable: true } git && git.GetLock(real) is { OwnedByMe: false }; + if (File.Exists(real) && File.GetAttributes(real).HasFlag(FileAttributes.ReadOnly)) IsReadOnly = true; + OnPropertyChanged(nameof(CanEdit)); + StartWatching(); + } + + public bool IsAutosaveDirty => IsDirty; + + public string? AutosaveFileName => CurrentUid.Length > 0 ? CurrentUid + ".lua" : null; + + public async Task WriteAutosaveAsync(string virtualPath) { + var text = await Dispatcher.UIThread.InvokeAsync(() => Session?.SaveText()); + if (text is null) return; + var path = ProjectContext.Resolve(virtualPath); + await Task.Run(() => File.WriteAllText(path, text)); + } + + private void ApplyDocument() { + if (m_document?.Session is { } session) Open(session); + else ShowError(m_document?.Error is { } error ? $"{error}. Fix it in a text editor, the graph reloads when the file is saved." : "The script could not be read."); + OnPropertyChanged(nameof(IsDirty)); + } + + public async Task ConfirmCloseCurrentAsync() { + if (!IsDirty) { + Workspace.AutosaveService.Delete(CurrentUid, ".lua"); + return true; + } + if (App.MainWindow is not { } owner) return true; + var result = await new MessageModal(new ModalConfig("Unsaved Changes", $"Save changes to '{Title}'?", ModalButtons.OkNoCancel, OkLabel: "Save")).ShowDialog(owner); + if (result is null) return false; + if (result is true) { + Save(); + return !IsDirty; + } + Workspace.AutosaveService.Delete(CurrentUid, ".lua"); + return true; + } + + private void StartWatching() { + if (m_document is null) return; + m_debounce.Tick -= OnDebounce; + m_debounce.Tick += OnDebounce; + Watch(Path.GetDirectoryName(m_document.LuaPath)!, Path.GetFileName(m_document.LuaPath), types: false); + foreach (var folder in m_document.LibraryFolders()) Watch(folder, "*.d.lua", types: true); + } + + private void Watch(string folder, string filter, bool types) { + try { + var watcher = new FileSystemWatcher(folder, filter) { NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.Size | NotifyFilters.FileName, EnableRaisingEvents = true }; + FileSystemEventHandler handler = (_, _) => Dispatcher.UIThread.Post(() => { + m_typesChanged |= types; + m_debounce.Stop(); + m_debounce.Start(); + }); + watcher.Changed += handler; + watcher.Created += handler; + watcher.Renamed += (_, _) => handler(null, null!); + m_watchers.Add(watcher); + } catch (Exception e) when (e is ArgumentException or IOException) { + Status = "could not watch " + folder; + } + } + + private void StopWatching() { + m_debounce.Stop(); + foreach (var w in m_watchers) w.Dispose(); + m_watchers.Clear(); + } + + private async void OnDebounce(object? sender, EventArgs e) { + m_debounce.Stop(); + if (m_document is null || m_asking) return; + if (m_typesChanged) { + m_typesChanged = false; + m_document.ReloadTypes(); + ApplyDocument(); + } + switch (m_document.CheckDisk()) { + case ExternalChange.Reloaded: + ApplyDocument(); + Status = "Reloaded: the file changed outside the editor"; + break; + case ExternalChange.Broken: + ApplyDocument(); + break; + case ExternalChange.Conflict: + m_asking = true; + try { + var take = App.MainWindow is { } owner + && await new MessageModal(new ModalConfig("File Changed", $"'{Title}' was changed outside the editor and you have unsaved edits.", ModalButtons.OkNoCancel, OkLabel: "Use file on disk")).ShowDialog(owner) is true; + if (take) { + m_document.AcceptDiskVersion(); + ApplyDocument(); + } else { + m_document.KeepMine(); + } + } finally { + m_asking = false; + } + break; + } + } +} diff --git a/editor/LuaEditor/LuaGraphEditorViewModel.Signature.cs b/editor/LuaEditor/LuaGraphEditorViewModel.Signature.cs new file mode 100644 index 000000000..f950428b8 --- /dev/null +++ b/editor/LuaEditor/LuaGraphEditorViewModel.Signature.cs @@ -0,0 +1,315 @@ +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; +using Lucide.Avalonia; +using editor.Assets.Types; +using editor.LuaEditor.Controls; +using editor.LuaEditor.Editing; +using editor.LuaEditor.Graph; +using editor.LuaEditor.Types; + +namespace editor.LuaEditor; + +public sealed partial class ParamRow : ObservableObject { + [ObservableProperty] private string m_name = ""; + [ObservableProperty] private string m_typeText = "any"; + + internal Action? Changed { get; set; } + internal bool Loading { get; set; } + + partial void OnNameChanged(string oldValue, string newValue) { + if (!Loading) Changed?.Invoke(this, oldValue, newValue); + } + + partial void OnTypeTextChanged(string oldValue, string newValue) { + if (!Loading) Changed?.Invoke(this, "", ""); + } +} + +public sealed partial class ReturnRow : ObservableObject { + [ObservableProperty] private string m_typeText = "any"; + + internal Action? Changed { get; set; } + internal bool Loading { get; set; } + + partial void OnTypeTextChanged(string value) { + if (!Loading) Changed?.Invoke(); + } +} + +public sealed partial class LuaGraphEditorViewModel { + [ObservableProperty] private IReadOnlyList m_typeItems = []; + + public ObservableCollection ParamRows { get; } = []; + public ObservableCollection ReturnRows { get; } = []; + + private string m_signatureKey = ""; + + private IReadOnlyList BuildTypeItems() { + var items = new List(); + void Basic(string name, LuaType type) => items.Add(new PickItem(name, "Basic", LucideIconKind.CircleDot, PinStyle.ColorOf(type), PinStyle.ShapeOf(type))); + Basic("number", LuaType.Number); + Basic("integer", LuaType.Integer); + Basic("string", LuaType.String); + Basic("boolean", LuaType.Boolean); + Basic("table", new PrimitiveType(PrimitiveKind.Table)); + Basic("function", new PrimitiveType(PrimitiveKind.Function)); + Basic("nil", LuaType.Nil); + Basic("any", LuaType.Any); + foreach (var name in new[] { "vec2", "vec3", "vec4", "quat", "color" }) + items.Add(new PickItem(name, "Math", LucideIconKind.CircleDot, PinStyle.Vector, PinShape.Circle)); + if (Session is not null) { + foreach (var cls in Session.Universe.Classes.OrderBy(c => c.Name, StringComparer.Ordinal)) { + if (items.Any(i => i.Value == cls.Name)) continue; + var asset = AssetTypeRegistry.ByCppTypeName(cls.Name) ?? AssetTypeRegistry.ByType(cls.Name.Replace("Asset", "").ToLowerInvariant()); + if (cls.Name.Contains("Asset", StringComparison.OrdinalIgnoreCase)) items.Add(new PickItem(cls.Name, "Assets", asset?.Icon ?? LucideIconKind.Image, asset?.ChipColor ?? "Orange")); + else if (cls.Name.Contains("Event", StringComparison.OrdinalIgnoreCase)) items.Add(new PickItem(cls.Name, "Events", LucideIconKind.CirclePlay, "Red")); + else items.Add(new PickItem(cls.Name, "Nodes", LucideIconKind.Box, "Blue")); + } + foreach (var e in Session.Universe.Enums.OrderBy(e => e.Name, StringComparer.Ordinal)) + items.Add(new PickItem(e.Name, "Enums", LucideIconKind.List, "Orange")); + } + return items; + } + + private IReadOnlyList BuildBaseItems() => TypeItems.Where(i => i.Group is not ("Basic" or "Math" or "Enums")).Prepend(new PickItem("(none)", "Base", LucideIconKind.Minus, "TextMuted")).ToList(); + + partial void OnScriptClassChanged(string value) => CommitScriptClass(); + + partial void OnScriptBaseChanged(string value) => CommitScriptClass(); + + private void CommitScriptClass() { + if (m_inspecting || Session is null || !InspectorIsScript) return; + var name = ScriptClass.Trim(); + var parent = ScriptBase is "(none)" or "" ? null : ScriptBase; + if (parent is not null && name.Length == 0) name = char.ToUpperInvariant(InspectorName[0]) + InspectorName[1..] + "Script"; + Session.Apply(g => g.SetScriptClass(name.Length == 0 ? null : name, parent)); + } + + public ObservableCollection TableRows { get; } = []; + + [ObservableProperty] private bool m_inspectorIsTableField; + + private string m_tableKey = ""; + + private void LoadTable(GraphVariable v) { + var table = GraphSession.TableOfField(v); + var declared = v.Type is UnionType u && u.Members.Count(m => m != LuaType.Nil) == 1 ? u.Members.First(m => m != LuaType.Nil) : v.Type; + InspectorIsTableField = v.Kind == VariableKind.Field && declared is not (ArrayType or TableType) && (declared is PrimitiveType { Kind: PrimitiveKind.Table } || table is { Flavor: TableFlavor.Table }); + if (table is null) { + m_tableKey = ""; + TableRows.Clear(); + return; + } + var key = v.Name + "|" + string.Join(",", table.Fields.Select(f => f.Kind + ":" + (f.Name ?? "") + ":" + GraphSession.TableEntryType(f))); + if (key == m_tableKey) return; + m_tableKey = key; + if (TableRows.Count == table.Fields.Count && TableRows.Select((r, i) => r.Field == table.Fields[i]).All(same => same)) { + for (var i = 0; i < table.Fields.Count; i++) { + var row = TableRows[i]; + var field = table.Fields[i]; + row.Loading = true; + row.Name = field.Kind == TableFieldKind.Named ? field.Name ?? "" : field.Kind == TableFieldKind.Keyed ? "[key]" : field.Value.Name; + row.TypeText = GraphSession.TableEntryType(field); + row.Loading = false; + } + return; + } + TableRows.Clear(); + foreach (var field in table.Fields) { + var named = field.Kind == TableFieldKind.Named; + var label = named ? field.Name ?? "" : field.Kind == TableFieldKind.Keyed ? "[key]" : field.Value.Name; + TableRows.Add(new TableEntryRow { Loading = true, Name = label, TypeText = GraphSession.TableEntryType(field), IsNamed = named, Kind = field.Kind.ToString(), Table = table, Field = field, Changed = OnTableEntryChanged }.Ready()); + } + } + + private void ClearTable() { + m_tableKey = ""; + InspectorIsTableField = false; + TableRows.Clear(); + } + + private void OnTableEntryChanged(TableEntryRow row, bool nameChanged) { + if (Session is null || row.Table is not { } table || row.Field is not { } field) return; + var index = table.Fields.ToList().IndexOf(field); + if (index < 0) return; + try { + if (nameChanged) { + if (row.IsNamed) Session.RenameTableField(table, field, row.Name.Trim()); + } else { + Session.SetTableEntryType(table, index, row.TypeText); + } + } catch (TypeSyntaxException e) { + Status = e.Message; + } + } + + [RelayCommand] + private void AddTableField() => AddEntryToSelected(TableFieldKind.Named); + + [RelayCommand] + private void AddTableItem() => AddEntryToSelected(TableFieldKind.Positional); + + private void AddEntryToSelected(TableFieldKind kind) { + if (Session is null || SelectedVariable?.Variable is not { Kind: VariableKind.Field } v || DefaultPin(v) is not { } pin) return; + m_tableKey = ""; + Session.AddFieldEntry(pin, kind); + } + + [RelayCommand] + private void RemoveTableEntryRow(TableEntryRow? row) { + if (Session is null || row?.Table is not { } table || row.Field is not { } field) return; + var index = table.Fields.ToList().IndexOf(field); + m_tableKey = ""; + if (index >= 0) Session.RemoveTableEntry(table, index); + } + + private void Safely(Action edit) { + try { + edit(); + } catch (Exception e) when (e is not OutOfMemoryException) { + Status = e.Message; + } + } + + private FunctionDecl? SelectedFunction + + => SelectedVariable?.Variable?.Declaration as FunctionDecl; + + private void LoadSignature(FunctionDecl function, FunctionType type) { + var parameters = function.Entry.Params.Select(p => (p.Name, Type: type.Params.FirstOrDefault(x => x.Name == p.Name)?.Type ?? LuaType.Any)).ToList(); + var key = function.Name + "|" + string.Join(",", parameters.Select(p => p.Name + ":" + TypeFormatter.Format(p.Type))) + "|" + string.Join(",", type.Returns.Select(TypeFormatter.Format)); + if (key == m_signatureKey) return; + m_signatureKey = key; + // replacing rows during an edit can detach the active picker + if (ParamRows.Count == parameters.Count && ReturnRows.Count == type.Returns.Count) { + for (var i = 0; i < parameters.Count; i++) { + var row = ParamRows[i]; + row.Loading = true; + row.Name = parameters[i].Name; + row.TypeText = TypeFormatter.Format(parameters[i].Type); + row.Loading = false; + } + for (var i = 0; i < type.Returns.Count; i++) { + var row = ReturnRows[i]; + row.Loading = true; + row.TypeText = TypeFormatter.Format(type.Returns[i]); + row.Loading = false; + } + return; + } + ParamRows.Clear(); + foreach (var (name, paramType) in parameters) + ParamRows.Add(new ParamRow { Loading = true, Name = name, TypeText = TypeFormatter.Format(paramType), Changed = OnParamChanged }.Ready()); + ReturnRows.Clear(); + foreach (var returned in type.Returns) + ReturnRows.Add(new ReturnRow { Loading = true, TypeText = TypeFormatter.Format(returned), Changed = OnReturnChanged }.Ready()); + } + + private void ClearSignature() { + m_signatureKey = ""; + ParamRows.Clear(); + ReturnRows.Clear(); + } + + private void OnParamChanged(ParamRow row, string oldName, string newName) { + if (Session is null || SelectedFunction is not { } function) return; + if (oldName.Length > 0 || newName.Length > 0) { + var binding = function.Entry.Params.FirstOrDefault(p => p.Name == oldName); + if (binding is null || newName.Length == 0) return; + Safely(() => Session.Apply(g => g.Rename(binding, newName))); + return; + } + try { + var type = row.TypeText.Trim().Length == 0 ? null : TypeExprParser.Parse(row.TypeText); + Safely(() => Session.Apply(g => g.SetParamType(function, row.Name, type))); + } catch (TypeSyntaxException e) { + Status = e.Message; + } + } + + private void OnReturnChanged() { + if (Session is null || SelectedFunction is not { } function) return; + var types = new List(); + try { + foreach (var row in ReturnRows) types.Add(TypeExprParser.Parse(row.TypeText.Trim().Length == 0 ? "any" : row.TypeText)); + } catch (TypeSyntaxException e) { + Status = e.Message; + return; + } + Safely(() => Session.Apply(g => g.SetReturnTypes(function, types))); + } + + [RelayCommand] + private void AddParameter() { + if (Session is null || SelectedFunction is not { } function) return; + var taken = function.Entry.Params.Select(p => p.Name).ToHashSet(); + var name = "value"; + for (var i = 2; taken.Contains(name); i++) name = "value" + i; + m_signatureKey = ""; + Session.Apply(g => g.AddParam(function, name)); + } + + [RelayCommand] + private void RemoveParameter(ParamRow? row) { + if (Session is null || row is null || SelectedFunction is not { } function) return; + m_signatureKey = ""; + Session.Apply(g => g.RemoveParam(function, row.Name)); + } + + [RelayCommand] + private void AddReturn() { + if (Session is null || SelectedFunction is not { } function) return; + var types = ReturnRows.Select(r => TypeExprParser.Parse(r.TypeText.Trim().Length == 0 ? "any" : r.TypeText)).Append(LuaType.Any).ToList(); + m_signatureKey = ""; + Session.Apply(g => g.SetReturnTypes(function, types)); + } + + [RelayCommand] + private void RemoveReturn(ReturnRow? row) { + if (Session is null || row is null || SelectedFunction is not { } function) return; + var types = ReturnRows.Where(r => r != row).Select(r => TypeExprParser.Parse(r.TypeText.Trim().Length == 0 ? "any" : r.TypeText)).ToList(); + m_signatureKey = ""; + Session.Apply(g => g.SetReturnTypes(function, types)); + } +} + +public sealed partial class TableEntryRow : ObservableObject { + [ObservableProperty] private string m_name = ""; + [ObservableProperty] private string m_typeText = "any"; + + public bool IsNamed { get; init; } + public string Kind { get; init; } = ""; + internal TableNode? Table { get; init; } + internal TableField? Field { get; init; } + internal Action? Changed { get; set; } + internal bool Loading { get; set; } + + partial void OnNameChanged(string value) { + if (!Loading) Changed?.Invoke(this, true); + } + + partial void OnTypeTextChanged(string value) { + if (!Loading) Changed?.Invoke(this, false); + } +} + +internal static class RowExtensions { + public static TableEntryRow Ready(this TableEntryRow row) { + row.Loading = false; + return row; + } + + public static ParamRow Ready(this ParamRow row) { + row.Loading = false; + return row; + } + + public static ReturnRow Ready(this ReturnRow row) { + row.Loading = false; + return row; + } +} diff --git a/editor/LuaEditor/LuaGraphEditorViewModel.Tags.cs b/editor/LuaEditor/LuaGraphEditorViewModel.Tags.cs new file mode 100644 index 000000000..3a11bad15 --- /dev/null +++ b/editor/LuaEditor/LuaGraphEditorViewModel.Tags.cs @@ -0,0 +1,74 @@ +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; +using editor.LuaEditor.Graph; +using editor.LuaEditor.Types; + +namespace editor.LuaEditor; + +public sealed partial class TagRow(LuaGraphEditorViewModel owner, string text) : ObservableObject { + [ObservableProperty] private string m_text = text; + + partial void OnTextChanged(string value) => owner.TagEdited(); +} + +public sealed partial class LuaGraphEditorViewModel { + public ObservableCollection Tags { get; } = []; + + [ObservableProperty] private IReadOnlyList m_typeOptions = []; + + private static LuaType WithoutNil(LuaType type) => type is UnionType u && u.Members.Any(m => m is PrimitiveType { Kind: PrimitiveKind.Nil }) + ? LuaType.Union(u.Members.Where(m => m is not PrimitiveType { Kind: PrimitiveKind.Nil }).ToArray()) + : type; + + private IReadOnlyList TypeOptionsFor(string current) { + var names = TypeNames.ToList(); + if (current.Length > 0 && !names.Contains(current)) names.Insert(0, current); + return names; + } + + private static bool IsManagedTag(string name, bool function) => name == "type" && !function || function && name is "param" or "return"; + + private static string? TagText(string line) => line.StartsWith("---@", StringComparison.Ordinal) ? line[4..].TrimEnd() : null; + + private void LoadTags(GraphVariable v) { + var function = v.Kind == VariableKind.Function; + foreach (var line in v.Declaration.LeadingLines) { + if (TagText(line) is not { } text) continue; + var name = text.Split(' ', 2)[0]; + if (!IsManagedTag(name, function)) Tags.Add(new TagRow(this, text)); + } + } + + internal void TagEdited() { + if (m_inspecting) return; + WriteTags(); + } + + private void WriteTags() { + if (Session is null || SelectedVariable?.Variable is not { } v) return; + var function = v.Kind == VariableKind.Function; + var kept = v.Declaration.LeadingLines + .Where(l => l.StartsWith("---", StringComparison.Ordinal) && (TagText(l) is not { } t || IsManagedTag(t.Split(' ', 2)[0], function))) + .ToList(); + var lines = kept.Concat(Tags.Select(r => r.Text.Trim()).Where(t => t.Length > 0).Select(t => "---@" + t.TrimStart('@'))).ToList(); + Session.Apply(g => g.SetAnnotationLines(v.Declaration, lines)); + } + + [RelayCommand] + private void AddTag() { + if (SelectedVariable?.Variable is null) return; + m_inspecting = true; + Tags.Add(new TagRow(this, "")); + m_inspecting = false; + } + + [RelayCommand] + private void RemoveTag(TagRow row) { + Tags.Remove(row); + WriteTags(); + } +} diff --git a/editor/LuaEditor/LuaGraphEditorViewModel.cs b/editor/LuaEditor/LuaGraphEditorViewModel.cs new file mode 100644 index 000000000..89bc515ca --- /dev/null +++ b/editor/LuaEditor/LuaGraphEditorViewModel.cs @@ -0,0 +1,659 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Threading.Tasks; +using Avalonia.Controls; +using Lucide.Avalonia; +using Loretta.CodeAnalysis.Lua.Syntax; +using Avalonia.Threading; +using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; +using editor.LuaEditor.Canvas; +using editor.LuaEditor.Editing; +using editor.LuaEditor.Graph; +using editor.LuaEditor.Layout; +using editor.LuaEditor.Syntax; +using editor.LuaEditor.Types; +using Dock.Model.Mvvm.Controls; +using editor.Assets; +using editor.Assets.Types; +using editor.Components.Modals; +using editor.Editors; + +namespace editor.LuaEditor; + +public sealed record ProblemRow(string Severity, string Text, GraphNode? Node) { + public uint Level => Severity switch { "Error" => 3u, "Warning" => 2u, _ => 1u }; + public string ShortName => Level switch { 3 => "ERROR", 2 => "WARN", _ => "INFO" }; +} + +public sealed partial class LuaGraphEditorViewModel : Tool, IToastZoneEditor, Workspace.IAutosavable { + [ObservableProperty] private GraphSession? m_session; + [ObservableProperty] private string? m_banner; + [ObservableProperty] private bool m_isReadOnly; + [ObservableProperty] private string m_inspectorTitle = "Nothing selected"; + [ObservableProperty] private string m_inspectorName = ""; + [ObservableProperty] private string m_inspectorType = ""; + [ObservableProperty] private string m_inspectorDoc = ""; + [ObservableProperty] private bool m_inspectorIsVariable; + [ObservableProperty] private bool m_inspectorIsFunction; + [ObservableProperty] private bool m_inspectorIsScript; + [ObservableProperty] private string m_scriptClass = ""; + [ObservableProperty] private string m_scriptBase = ""; + [ObservableProperty] private IReadOnlyList m_scriptBaseItems = []; + [ObservableProperty] private string m_defaultKind = "none"; + [ObservableProperty] private float m_defaultNumber; + [ObservableProperty] private string m_defaultInteger = "0"; + [ObservableProperty] private string m_defaultText = ""; + [ObservableProperty] private bool m_defaultBool; + [ObservableProperty] private bool m_inspectorNullable; + [ObservableProperty] private bool m_inspectorExported; + [ObservableProperty] private bool m_inspectorCanExport; + private bool m_inspecting; + [ObservableProperty] private string m_inspectorParams = ""; + [ObservableProperty] private string m_inspectorReturns = ""; + [ObservableProperty] private string m_status = ""; + [ObservableProperty] private VariableRow? m_selectedVariable; + + public LuaGraphEditorViewModel() { + if (Design.IsDesignMode) LoadDesignData(); + } + + public ObservableCollection Variables { get; } = []; + + private readonly List m_allRows = []; + private readonly HashSet m_collapsedSections = []; + + [ObservableProperty] private string m_filterText = ""; + + partial void OnFilterTextChanged(string value) => ShowRows(); + + public void SetSection(VariableRow row) { + if (!row.HasChildren) return; + row.IsExpanded = !row.IsExpanded; + if (row.IsExpanded) m_collapsedSections.Remove(row.Id); + else m_collapsedSections.Add(row.Id); + ShowRows(); + } + + private void ShowRows() { + var filter = FilterText.Trim(); + var matching = new HashSet(); + if (filter.Length > 0) { + foreach (var row in m_allRows.Where(r => r.Name.Contains(filter, StringComparison.OrdinalIgnoreCase))) + for (var ancestor = row; ancestor is not null; ancestor = ancestor.Parent) matching.Add(ancestor); + } + bool Visible(VariableRow row) => row.Parent is null || row.Parent.IsExpanded && Visible(row.Parent); + Variables.Clear(); + foreach (var row in m_allRows) { + row.IsSelected = row == SelectedVariable; + row.IsFolded = row.HasChildren && !row.IsExpanded && filter.Length == 0; + if (filter.Length > 0 ? matching.Contains(row) : Visible(row)) Variables.Add(row); + } + } + + public ObservableCollection Problems { get; } = []; + + public event Action? FocusRequested; + + public bool CanEdit => Session is not null && !IsReadOnly && !m_lockedByOther; + + private bool m_lockedByOther; + + partial void OnIsReadOnlyChanged(bool value) => OnPropertyChanged(nameof(CanEdit)); + + partial void OnSessionChanged(GraphSession? oldValue, GraphSession? newValue) { + OnPropertyChanged(nameof(CanEdit)); + if (oldValue is not null) { + oldValue.Changed -= Refresh; + oldValue.SelectionChanged -= SelectCanvasMember; + } + SelectedVariable = null; + if (newValue is not null) { + newValue.Changed += Refresh; + newValue.SelectionChanged += SelectCanvasMember; + } + Refresh(); + } + + partial void OnSelectedVariableChanged(VariableRow? value) { + foreach (var row in m_allRows) row.IsSelected = row == value; + Inspect(); + } + + public void ShowError(string message) { + Session = null; + Banner = message; + IsReadOnly = true; + m_allRows.Clear(); + ShowRows(); + Problems.Clear(); + } + + public void Open(GraphSession session) { + Banner = null; + IsReadOnly = false; + Session = session; + } + + public void Refresh() { + RefreshVariables(); + RefreshProblems(); + Inspect(); + Status = Session?.Message ?? ""; + OnPropertyChanged(nameof(IsDirty)); + } + + private object? m_itemsUniverse; + + private void RefreshVariables() { + if (!ReferenceEquals(m_itemsUniverse, Session?.Universe)) { + m_itemsUniverse = Session?.Universe; + TypeItems = BuildTypeItems(); + } + var keep = SelectedVariable; + m_allRows.Clear(); + if (Session is { } session) { + var graph = session.Graph; + var script = ScriptInfo.Find(graph); + var all = graph.Variables; + VariableRow Add(string id, VariableRow? parent, string name, LucideIconKind icon, VariableRowKind kind, + GraphVariable? variable = null, Binding? binding = null, MemberInfo? native = null, Avalonia.Media.Imaging.Bitmap? bitmap = null, string? nodeColor = null) { + var row = new VariableRow(id, parent, name, icon, kind, variable, binding, native, bitmap, nodeColor) { + IsExpanded = !m_collapsedSections.Contains(id) + }; + if (parent is not null) parent.HasChildren = true; + m_allRows.Add(row); + return row; + } + VariableRow Group(string id, VariableRow? parent, string name, LucideIconKind icon, Avalonia.Media.Imaging.Bitmap? bitmap = null, string? nodeColor = null) + => Add(id, parent, name, icon, VariableRowKind.Group, bitmap: bitmap, nodeColor: nodeColor); + var table = script is null ? null : new GraphVariable(script.Table.Name, VariableKind.ModuleLocal, false, + new NamedType(script.ClassName, []), null, script.ClassAnnotations.Doc, script.Declaration); + var scriptRow = Add("script", null, "Script Table", LucideIconKind.CodeXml, VariableRowKind.Script, table, script?.Table); + var fields = Group("fields", scriptRow, "Fields", LucideIconKind.Cuboid); + foreach (var v in Sort(all.Where(v => v.Kind == VariableKind.Field))) + Add("field/" + v.Name, fields, v.Name, LucideIconKind.Cuboid, VariableRowKind.Field, v); + var methods = Group("methods", scriptRow, "Methods", LucideIconKind.Box); + var own = all.Where(v => v.Declaration is FunctionDecl f && script?.Methods.Contains(f) == true).ToList(); + foreach (var v in Sort(own.Where(v => !GraphSession.TickFunctions.Contains(v.Name)))) + Add("method/" + v.Name, methods, v.Name, LucideIconKind.Box, VariableRowKind.Method, v); + var ticks = Group("ticks", null, "Tick functions", LucideIconKind.Metronome); + foreach (var name in GraphSession.TickFunctions) + Add("tick/" + name, ticks, name == "_end" ? "end" : name, LucideIconKind.Metronome, VariableRowKind.Tick, + own.FirstOrDefault(v => v.Name == name)); + + var source = Group("source", null, "Source", LucideIconKind.File); + foreach (var cls in session.SourceClasses()) { + var group = Group("source/" + cls.Name, source, cls.Name, LucideIconKind.Box, + NodeIconCache.Get(editor.Engine.ReflectionDatabase.ResolveIcon(cls.Name)), editor.Engine.ReflectionDatabase.ResolveColor(cls.Name)); + foreach (var member in cls.Members.OrderBy(m => m.Name, StringComparer.OrdinalIgnoreCase).ThenBy(m => m.Name, StringComparer.Ordinal)) { + var function = member.Type is FunctionType; + var v = new GraphVariable(member.Name, function ? VariableKind.Function : VariableKind.Field, true, + member.Type, member.Unit, member.Doc, script!.Declaration); + Add(group.Id + "/" + member.Name, group, member.Name, function ? LucideIconKind.SquareFunction : LucideIconKind.Binary, + VariableRowKind.Native, v, native: new MemberInfo(member, cls.Name)); + } + } + var locals = Group("local", null, "Local", LucideIconKind.Variable); + foreach (var v in Sort(all.Where(v => v.Kind == VariableKind.ModuleLocal || v.Declaration is FunctionDecl { IsLocal: true }))) { + var binding = v.Declaration switch { + LocalDecl d => d.Names.First(n => n.Name == v.Name), + FunctionDecl f => f.FunctionBinding, + _ => null + }; + var index = graph.Module.IndexOf(v.Declaration); + Add($"local/{index}/{binding?.OutputIndex}", locals, v.Name, LocalIcon(v, binding), VariableRowKind.Local, v, binding); + } + } + SelectedVariable = keep is null ? null : m_allRows.FirstOrDefault(r => + keep.Binding is not null && r.Binding == keep.Binding || + keep.Native is null && keep.Binding is null && keep.Variable is { } old && r.Kind == keep.Kind && r.Variable?.Declaration == old.Declaration) + ?? m_allRows.FirstOrDefault(r => r.Id == keep.Id && (r.Kind != VariableRowKind.Local || r.Name == keep.Name)) + ?? m_allRows.LastOrDefault(r => r.Kind == keep.Kind && r.Name == keep.Name); + ShowRows(); + } + + private static IEnumerable Sort(IEnumerable variables) + => variables.OrderBy(v => v.Name, StringComparer.OrdinalIgnoreCase).ThenBy(v => v.Name, StringComparer.Ordinal); + + private static LucideIconKind LocalIcon(GraphVariable variable, Binding? binding) { + if (variable.Declaration is LocalDecl local && binding is not null && + local.Values.ElementAtOrDefault(local.Names.IndexOf(binding))?.Source?.Owner is TableNode table) + return table.Flavor switch { + TableFlavor.Array => LucideIconKind.Brackets, + TableFlavor.Dictionary => LucideIconKind.Book, + _ => LucideIconKind.Table + }; + return WithoutNil(variable.Type) switch { + FunctionType or PrimitiveType { Kind: PrimitiveKind.Function } => LucideIconKind.Code, + ArrayType => LucideIconKind.Brackets, + TableType => LucideIconKind.Book, + PrimitiveType { Kind: PrimitiveKind.Table } => LucideIconKind.Table, + _ => LucideIconKind.Variable + }; + } + + public VariableRow? FindRow(string id) => m_allRows.FirstOrDefault(row => row.Id == id); + + public void SelectRow(VariableRow? row) { + SelectedVariable = row; + if (row is null || Variables.Contains(row)) return; + for (var parent = row.Parent; parent is not null; parent = parent.Parent) { + m_collapsedSections.Remove(parent.Id); + parent.IsExpanded = true; + } + if (FilterText.Length > 0) FilterText = ""; + else ShowRows(); + } + + private void SelectCanvasMember() { + SelectRow(Session?.Selection is [var node] ? RowForNode(node) : null); + } + + private VariableRow? RowForNode(GraphNode node) { + var graph = node.Graph; + var script = ScriptInfo.Find(graph); + VariableRow? BindingRow(Binding? binding) => binding is null ? null : m_allRows.FirstOrDefault(r => r.Binding == binding); + VariableRow? MemberRow(InputPin? receiver, string? name, bool function) { + if (receiver is null || name is null) return null; + var type = receiver.ActualType as NamedType; + if (script is not null && (script.IsTable(receiver) || type?.Name == script.ClassName)) { + var own = m_allRows.FirstOrDefault(r => r.Variable?.Name == name && + (function ? r.Kind is VariableRowKind.Method or VariableRowKind.Tick : r.Kind == VariableRowKind.Field)); + if (own is not null) return own; + type = script.ClassTag?.Bases.OfType().FirstOrDefault(); + } + var member = type is null ? null : graph.Universe.MembersOf(type.Name).FirstOrDefault(m => m.Decl.Name == name); + return member is null ? null : m_allRows.FirstOrDefault(r => r.Native?.DeclaringClass == member.DeclaringClass && r.Name == name); + } + + if (NodeShape.CallOf(node) is { } call) node = call; + if (node is FunctionEntry entry) node = entry.Owner; + var declaration = m_allRows.Where(r => r.Native is null && r.Variable?.Declaration == node).Take(2).ToList(); + if (declaration.Count == 1) return declaration[0]; + return node switch { + VariableGet get => BindingRow(get.Binding), + MemberGet get => MemberRow(get.Object, get.Name, false), + CallNode { Style: CallStyle.Method } c => MemberRow(c.Target, c.Method, true), + CallNode { Target.Source.Owner: MemberGet member } => MemberRow(member.Object, member.Name, true), + CallNode c => BindingRow(NodeShape.BindingOf(c.Target.Source)), + AssignStatement { Targets: [var target] } => target.Binding is { } binding + ? BindingRow(binding) : MemberRow(target.Object, target.Name, false), + _ => null + }; + } + + private void RefreshProblems() { + Problems.Clear(); + if (Session is null) return; + foreach (var d in Session.Graph.Diagnostics) + Problems.Add(new ProblemRow(d.Severity.ToString(), $"{NodeShape.TitleOf(InlineRules.Drawn(d.Node))}: {d.Message}", d.Node)); + foreach (var w in Session.Graph.Warnings) Problems.Add(new ProblemRow("Warning", w, null)); + } + + private void Inspect() { + var before = m_inspecting; + m_inspecting = true; + try { + InspectCore(); + } finally { + m_inspecting = before; + } + } + + private void InspectCore() { + Tags.Clear(); + InspectorIsScript = false; + if (SelectedVariable is { Native: { } native, Variable: { } nativeMember }) { + InspectorIsVariable = false; + InspectorIsFunction = false; + ClearSignature(); + ClearTable(); + InspectorTitle = "C++ " + (nativeMember.Kind == VariableKind.Function ? "function " : "field ") + nativeMember.Name; + InspectorName = native.DeclaringClass + "\n" + nativeMember.Doc.Trim(); + InspectorType = TypeFormatter.Display(nativeMember.Type); + InspectorDoc = ""; + return; + } + if (SelectedVariable?.Variable is { Kind: VariableKind.ModuleLocal } scriptVariable && ScriptInfo.Find(Session!.Graph) is { } script && scriptVariable.Declaration == script.Declaration) { + InspectorIsScript = true; + InspectorIsVariable = false; + InspectorIsFunction = false; + InspectorTitle = "Script " + script.Table.Name; + InspectorName = script.Table.Name; + ScriptClass = script.ClassTag?.Name ?? ""; + ScriptBase = script.ClassTag?.Bases.OfType().FirstOrDefault()?.Name ?? ""; + ScriptBaseItems = BuildBaseItems(); + InspectorDoc = ""; + ClearSignature(); + ClearTable(); + return; + } + if (SelectedVariable?.Variable is { } v) { + InspectorIsVariable = true; + InspectorIsFunction = v.Kind == VariableKind.Function; + LoadDefault(v); + InspectorNullable = v.Type is UnionType u && u.Members.Any(m => m is PrimitiveType { Kind: PrimitiveKind.Nil }); + InspectorCanExport = v.Kind == VariableKind.Field; + InspectorExported = v.Exported; + if (v.Declaration is FunctionDecl declared && v.Type is FunctionType fn) LoadSignature(declared, fn); + else ClearSignature(); + if (v.Kind == VariableKind.Field) LoadTable(v); + else ClearTable(); + InspectorTitle = v.Kind + " " + v.Name; + InspectorName = v.Name; + InspectorType = TypeFormatter.Format(WithoutNil(v.Type)); + TypeOptions = TypeOptionsFor(InspectorType); + LoadTags(v); + InspectorDoc = v.Doc; + return; + } + InspectorIsVariable = false; + InspectorIsFunction = false; + ClearTable(); + ClearSignature(); + InspectorTitle = "Nothing selected"; + InspectorName = InspectorType = InspectorDoc = ""; + } + + [RelayCommand] + private void Undo() => Session?.Undo(); + + [RelayCommand] + private void Redo() => Session?.Redo(); + + [RelayCommand] + private void Tidy() => Session?.Tidy(null); + + [RelayCommand] + private Task Save() { + if (m_document is null) return Task.CompletedTask; + var saved = m_document.Save(out var message); + if (saved) Workspace.AutosaveService.Delete(CurrentUid, ".lua"); + Refresh(); + Status = saved ? "Saved" : message ?? "Save failed"; + OnPropertyChanged(nameof(IsDirty)); + return Task.CompletedTask; + } + + [RelayCommand] + private void AddField() { + var name = FreshName("new_field"); + if (Session?.AddField(name) == true) SelectRow(FindRow("field/" + name)); + } + + [RelayCommand] + private void AddFunction() => Session?.AddFunction(FreshName("new_function")); + + [RelayCommand] + private void AddLocal() { + var name = FreshName("value"); + if (Session?.AddModuleLocal(name) == true) SelectRow(m_allRows.LastOrDefault(r => r.Kind == VariableRowKind.Local && r.Name == name)); + } + + public string FreshName(string stem) { + var taken = Session?.Graph.Variables.Select(v => v.Name).ToHashSet() ?? []; + if (!taken.Contains(stem)) return stem; + for (var i = 2;; i++) + if (!taken.Contains(stem + i)) return stem + i; + } + + public void FocusProblem(ProblemRow row) { + if (row.Node is null || Session is null) return; + var drawn = InlineRules.Drawn(row.Node); + if (!drawn.IsExpanded && !Session.Layout.Loose.Contains(drawn) && + Session.Layout.Keys.RegionOf(drawn) is { IsModule: true }) { + Session.ClearSelection(); + SelectRow(RowForNode(drawn)); + return; + } + Session.Select([row.Node]); + FocusRequested?.Invoke(drawn); + } + + public void CommitName(string name) { + if (InspectorIsScript && Session is not null && SelectedVariable?.Variable is { } renamed && name.Length > 0 && name != renamed.Name) { + Session.Apply(g => g.Rename(((LocalDecl)renamed.Declaration).Names[0], name)); + return; + } + if (Session is null || SelectedVariable?.Variable is not { } v || name == v.Name || name.Length == 0) return; + Session.Apply(g => { + switch (v.Declaration) { + case LocalDecl local: g.Rename(SelectedVariable?.Binding ?? local.Names[0], name); break; + case FunctionDecl f when f.IsLocal: g.Rename(f.FunctionBinding!, name); break; + case AssignStatement: g.RenameMember(v.Name, name); break; + case FunctionDecl f: g.RenameMember(f.Name, name); break; + } + }); + } + + public void CommitType(string typeText) { + if (Session is null || SelectedVariable?.Variable is not { } v || v.Kind == VariableKind.Function) return; + LuaType? type = null; + if (!string.IsNullOrWhiteSpace(typeText)) { + try { + type = TypeExprParser.Parse(typeText); + } catch (TypeSyntaxException e) { + Status = e.Message; + return; + } + } + if (type == LuaType.Function && SelectedVariable?.Binding is { Declarer: LocalDecl } binding && v.Kind == VariableKind.ModuleLocal) { + Session.MakeLocalFunction(binding); + return; + } + if (type is not null && InspectorNullable) type = LuaType.Optional(type); + Safely(() => Session.SetVariableType(v, SelectedVariable?.Binding, type)); + } + + public void CommitDoc(string doc) { + if (Session is null || SelectedVariable?.Variable is not { } v) return; + Session.Apply(g => g.SetDoc(v.Declaration, doc.Length == 0 ? null : doc)); + } + + public const string DesignScript = """ + ---@class Door + local M = {} + + ---@type number + M.open_speed = 2.5 + M.label = "Door" + local closed = true + + ---Opens the door + function M:init() + self.angle = 0 + if closed then + print("closed", self.open_speed) + else + self.angle = self.angle + 1 + end + end + + function M:tick(dt) + for i = 1, 3 do + self.angle = self.angle + dt * self.open_speed * i + end + print(math.floor(self.angle), self.label .. "!") + end + + return M + """; + + private void LoadDesignData() { + var universe = TypeUniverse.Build([]); + var document = LuaDocument.Parse(DesignScript); + if (!LuaGraph.TryBuild(document, universe, out var graph, out _)) return; + Open(GraphSession.Open(graph!, null)); + Title = "Door.lua"; + } +} + +public sealed partial class LuaGraphEditorViewModel { + public void CommitParams(string text) { + if (Session is null || SelectedVariable?.Variable is not { Declaration: FunctionDecl function }) return; + var changes = new List<(string Name, LuaType? Type)>(); + foreach (var part in TypeText.SplitTopLevel(text)) { + var colon = part.IndexOf(':'); + var name = (colon < 0 ? part : part[..colon]).Trim().TrimEnd('?'); + if (!function.Entry.Params.Any(p => p.Name == name)) { + Status = $"{function.Name} has no parameter called {name}"; + return; + } + try { + changes.Add((name, colon < 0 ? null : TypeExprParser.Parse(part[(colon + 1)..].Trim()))); + } catch (TypeSyntaxException e) { + Status = e.Message; + return; + } + } + Session.Apply(g => { + foreach (var (name, type) in changes) g.SetParamType(function, name, type); + }); + } + + public void CommitReturns(string text) { + if (Session is null || SelectedVariable?.Variable is not { Declaration: FunctionDecl function }) return; + var types = new List(); + try { + foreach (var part in TypeText.SplitTopLevel(text)) types.Add(TypeExprParser.Parse(part)); + } catch (TypeSyntaxException e) { + Status = e.Message; + return; + } + Session.Apply(g => g.SetReturnTypes(function, types)); + } +} + +public sealed partial class LuaGraphEditorViewModel { + public IReadOnlyList TypeNames { + get { + var names = new List { "nil", "boolean", "number", "integer", "string", "table", "function", "any" }; + if (Session is not null) { + names.AddRange(Session.Universe.Classes.Select(c => c.Name)); + names.AddRange(Session.Universe.Enums.Select(e => e.Name)); + } + return names.Distinct().Order(StringComparer.Ordinal).ToList(); + } + } + + public IReadOnlyDictionary TypeGroups { + get { + var groups = new Dictionary(); + foreach (var name in new[] { "nil", "boolean", "number", "integer", "string", "table", "function", "any" }) groups[name] = "Basic"; + if (Session is null) return groups; + foreach (var name in new[] { "vec2", "vec3", "vec4", "quat", "color" }) groups[name] = "Math"; + foreach (var cls in Session.Universe.Classes) + groups.TryAdd(cls.Name, cls.Name.Contains("Asset", StringComparison.OrdinalIgnoreCase) ? "Assets" : cls.Name.Contains("Event", StringComparison.OrdinalIgnoreCase) ? "Events" : "Classes"); + foreach (var e in Session.Universe.Enums) groups.TryAdd(e.Name, "Enums"); + return groups; + } + } + + private InputPin? DefaultPin(GraphVariable v) => GraphSession.VariableDefault(v, SelectedVariable?.Binding); + + private void LoadDefault(GraphVariable variable) { + DefaultKind = "none"; + if (variable.Kind == VariableKind.Function) return; + var pin = DefaultPin(variable); + var constant = GraphSession.LiteralDefault(pin); + if (pin?.Source is not null && constant is null) return; + var type = WithoutNil(Session!.Universe.ResolveAliases(variable.Type)); + if (type == LuaType.Any || type == LuaType.Unknown) type = constant?.ValueType ?? LuaType.Nil; + switch (type) { + case PrimitiveType { Kind: PrimitiveKind.Integer }: + DefaultKind = "integer"; + DefaultInteger = constant is { Kind: ConstantKind.Number } && TryDefaultInteger(constant.Raw, out var integer) + ? integer.ToString(CultureInfo.InvariantCulture) : "0"; + break; + case PrimitiveType { Kind: PrimitiveKind.Number }: + DefaultKind = "number"; + DefaultNumber = constant is { Kind: ConstantKind.Number } && + float.TryParse(constant.Raw, NumberStyles.Float, CultureInfo.InvariantCulture, out var number) && float.IsFinite(number) ? number : 0; + break; + case PrimitiveType { Kind: PrimitiveKind.Boolean }: + DefaultKind = "boolean"; + DefaultBool = constant?.Raw == "true"; + break; + case PrimitiveType { Kind: PrimitiveKind.String }: + DefaultKind = "string"; + DefaultText = constant is { Kind: ConstantKind.String } ? ReadDefaultString(pin, constant) : ""; + break; + } + } + + private static string ReadDefaultString(InputPin? pin, LuaConstant constant) { + if (pin?.Origin is LiteralExpressionSyntax original && original.Token.Text == constant.Raw && original.Token.Value is string text) + return text; + var statement = LuaDocument.Parse("return " + constant.Raw).Root.Statements.Statements.FirstOrDefault(); + return statement is ReturnStatementSyntax ret && ret.Expressions.FirstOrDefault() is LiteralExpressionSyntax literal && + literal.Token.Value is string decoded ? decoded : GraphSession.DisplayText(constant); + } + + private static bool TryDefaultInteger(string text, out long value) => text.StartsWith("0x", StringComparison.OrdinalIgnoreCase) + ? long.TryParse(text.AsSpan(2), NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, out value) + : long.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out value); + + private void CommitDefault(LuaConstant value) { + if (m_inspecting || Session is null || SelectedVariable?.Variable is not { } variable) return; + if (GraphSession.LiteralDefault(DefaultPin(variable)) == value) return; + Session.SetVariableDefault(variable, SelectedVariable.Binding, value); + } + + partial void OnDefaultNumberChanged(float value) { + if (float.IsFinite(value)) CommitDefault(LuaConstant.Float(value)); + } + + partial void OnDefaultIntegerChanged(string value) { + if (m_inspecting) return; + if (TryDefaultInteger(value, out var number)) CommitDefault(LuaConstant.Integer(number)); + else Status = "enter a whole number between " + long.MinValue + " and " + long.MaxValue; + } + + partial void OnDefaultBoolChanged(bool value) => CommitDefault(value ? LuaConstant.True : LuaConstant.False); + + partial void OnDefaultTextChanged(string value) => CommitDefault(LuaConstant.String(value)); + + partial void OnInspectorNullableChanged(bool value) { + if (m_inspecting || Session is null || SelectedVariable?.Variable is not { } v || v.Kind == VariableKind.Function) return; + if (v.Declaration is LocalDecl local && SelectedVariable.Binding != local.Names[0]) return; + var members = v.Type is UnionType u ? u.Members.ToList() : [v.Type]; + var hasNil = members.Any(m => m is PrimitiveType { Kind: PrimitiveKind.Nil }); + if (value == hasNil) return; + var next = value ? LuaType.Optional(v.Type) : LuaType.Union(members.Where(m => m is not PrimitiveType { Kind: PrimitiveKind.Nil }).ToArray()); + Session.Apply(g => g.SetDeclaredType(v.Declaration, next)); + } + + partial void OnInspectorExportedChanged(bool value) { + if (m_inspecting || Session is null || SelectedVariable?.Variable is not { Kind: VariableKind.Field } v || v.Exported == value) return; + var name = value ? v.Name.TrimStart('_') : "_" + v.Name; + if (name.Length == 0) return; + Session.Apply(g => g.RenameMember(v.Name, name)); + } +} + +public sealed partial class LuaGraphEditorViewModel { + partial void OnInspectorNameChanged(string value) { + if (!m_inspecting) CommitName(value); + } + + partial void OnInspectorTypeChanged(string value) { + if (!m_inspecting) CommitType(value); + } + + partial void OnInspectorDocChanged(string value) { + if (!m_inspecting) CommitDoc(value); + } + + partial void OnInspectorParamsChanged(string value) { + if (!m_inspecting) CommitParams(value); + } + + partial void OnInspectorReturnsChanged(string value) { + if (!m_inspecting) CommitReturns(value); + } +} diff --git a/editor/LuaEditor/SearchRow.cs b/editor/LuaEditor/SearchRow.cs new file mode 100644 index 000000000..9d7f8bbe6 --- /dev/null +++ b/editor/LuaEditor/SearchRow.cs @@ -0,0 +1,149 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Lucide.Avalonia; +using editor.LuaEditor.Editing; +using editor.LuaEditor.Graph; + +namespace editor.LuaEditor; + +public sealed class SearchRow { + public string Text { get; private init; } = ""; + public bool IsGroup { get; private init; } + public bool IsOpen { get; private init; } + public int Depth { get; private init; } + public string Key { get; private init; } = ""; + public NodeEntry? Entry { get; private init; } + public LucideIconKind Icon { get; private init; } + public string ColorKey { get; private init; } = "Blue"; + + public LucideIconKind Chevron => IsOpen ? LucideIconKind.ChevronDown : LucideIconKind.ChevronRight; + public string Count { get; private init; } = ""; + public Avalonia.Thickness Indent => new(Depth * 20, 0, 0, 0); + public bool ShowIcon => true; + + private static SearchRow Group(string key, string name, int depth, bool open, int count, string? parent = null) { + var (icon, color) = depth == 0 ? PageLook(name) : CategoryLook(parent ?? "", name); + return new SearchRow { Key = key, Text = name, Count = count.ToString(), IsGroup = true, IsOpen = open, Depth = depth, Icon = icon, ColorKey = color }; + } + + private static (LucideIconKind Icon, string Color) CategoryLook(string group, string category) { + switch (group) { + case "Assets": { + var asset = editor.Assets.Types.AssetTypeRegistry.ByCppTypeName(category) ?? editor.Assets.Types.AssetTypeRegistry.ByType(category.Replace("Asset", "").ToLowerInvariant()); + return asset is null ? (LucideIconKind.Image, "Orange") : (asset.Icon, asset.ChipColor); + } + case "Nodes": return (LucideIconKind.Box, "Blue"); + case "Events": return (LucideIconKind.CirclePlay, "Red"); + case "Libraries": return (LucideIconKind.Package, "Cyan"); + default: return (LucideIconKind.Boxes, "Magenta"); + } + } + + private static SearchRow Of(NodeEntry entry, int depth) { + var (icon, color) = Look(entry); + return new SearchRow { Text = entry.Title, Entry = entry, Depth = depth, Icon = icon, ColorKey = color }; + } + + public static (LucideIconKind Icon, string Color) Look(NodeEntry entry) => entry.Kind switch { + NodeKind.GetVariable or NodeKind.GetGlobal or NodeKind.Member or NodeKind.GetSelf => (LucideIconKind.Download, "Blue"), + NodeKind.SetVariable => (LucideIconKind.Pencil, "Orange"), + NodeKind.CallMethod => (LucideIconKind.Package, "Cyan"), + NodeKind.CallGlobal => (LucideIconKind.Braces, "Magenta"), + NodeKind.Lambda => (LucideIconKind.SquareFunction, "Orange"), + NodeKind.If or NodeKind.While or NodeKind.Repeat or NodeKind.NumericFor or NodeKind.GenericFor or NodeKind.Do or NodeKind.Return or NodeKind.Break or NodeKind.Sequence => (LucideIconKind.GitBranch, "Red"), + NodeKind.Local or NodeKind.Cast => (LucideIconKind.Variable, "Green"), + NodeKind.Comment => (LucideIconKind.MessageSquare, "Yellow"), + NodeKind.RawStatement or NodeKind.RawExpression => (LucideIconKind.CodeXml, "Yellow"), + _ => (LucideIconKind.CircleDot, "Green") + }; + + public static string GroupOf(NodeEntry e) { + if (e.Category == "Tables") return "Tables"; + switch (e.Kind) { + case NodeKind.GetSelf or NodeKind.GetVariable or NodeKind.SetVariable: + return "This script"; + case NodeKind.If or NodeKind.While or NodeKind.Repeat or NodeKind.NumericFor or NodeKind.GenericFor or NodeKind.Do or NodeKind.Return or NodeKind.Break or NodeKind.Sequence: + return "Flow"; + case NodeKind.Binary or NodeKind.Unary or NodeKind.VectorConstructor: + return "Math"; + case NodeKind.Lambda: + return "Values"; + case NodeKind.Local or NodeKind.Cast or NodeKind.Number or NodeKind.String or NodeKind.Boolean or NodeKind.Nil: + return "Values"; + case NodeKind.Comment or NodeKind.RawStatement or NodeKind.RawExpression: + return "Comments and raw Lua"; + } + if (e.Owner == GraphSession.ScriptOwner || e.Category.StartsWith("C++ ", StringComparison.Ordinal)) return "This script"; + if (e.Kind is NodeKind.CallGlobal or NodeKind.GetGlobal && e.Owner is null) return "Lua library"; + if (e.Owner is { Length: > 0 } lib && char.IsLower(lib[0])) return "Lua library"; + var owner = e.Owner ?? e.Category; + if (owner.Contains("Asset", StringComparison.OrdinalIgnoreCase)) return "Engine assets"; + if (owner.Contains("Event", StringComparison.OrdinalIgnoreCase)) return "Engine events"; + return "Engine nodes"; + } + + public static string CategoryOf(NodeEntry e) { + var group = GroupOf(e); + switch (group) { + case "This script": + return e.Kind switch { + NodeKind.GetSelf => "Self", + NodeKind.GetVariable or NodeKind.SetVariable when e.Owner == GraphSession.BaseOwner => e.Category, + NodeKind.GetVariable or NodeKind.SetVariable => "Variables", + _ when e.Owner == GraphSession.ScriptOwner => "Functions", + _ => e.Category + }; + case "Math": + return e.Kind == NodeKind.VectorConstructor ? "Vectors" : e.Binary is BinaryKind.Eq or BinaryKind.Ne or BinaryKind.Lt or BinaryKind.Le or BinaryKind.Gt or BinaryKind.Ge ? "Compare" + : e.Binary is BinaryKind.And or BinaryKind.Or || e.Unary == UnaryKind.Not ? "Logic" : "Arithmetic"; + case "Lua library": + return e.Owner ?? (e.Kind == NodeKind.GetGlobal ? "Globals" : "Basic"); + default: + return group == e.Category ? group : e.Owner ?? e.Category; + } + } + + private static (LucideIconKind Icon, string Color) PageLook(string name) => name switch { + "Best matches" => (LucideIconKind.Search, "Yellow"), + "This script" => (LucideIconKind.CodeXml, "Magenta"), + "Flow" => (LucideIconKind.GitBranch, "Red"), + "Tables" => (LucideIconKind.Braces, "Cyan"), + "Math" => (LucideIconKind.Plus, "Orange"), + "Values" => (LucideIconKind.CircleDot, "Green"), + "Lua library" => (LucideIconKind.Package, "Cyan"), + "Engine assets" => (LucideIconKind.Image, "Orange"), + "Engine events" => (LucideIconKind.CirclePlay, "Red"), + "Comments and raw Lua" => (LucideIconKind.MessageSquare, "Yellow"), + _ => (LucideIconKind.Boxes, "Blue") + }; + + private static readonly string[] s_order = ["Best matches", "This script", "Flow", "Tables", "Math", "Values", "Lua library", "Engine nodes", "Engine assets", "Engine events", "Comments and raw Lua"]; + + public static List Tree(IReadOnlyList entries, ISet open, bool everythingOpen) { + var rows = new List(); + if (everythingOpen && entries.Count > 12) { + rows.Add(Group("Best matches", "Best matches", 0, true, Math.Min(10, entries.Count))); + rows.AddRange(entries.Take(10).Select(e => Of(e, 1))); + } + var groups = entries.GroupBy(GroupOf).OrderBy(g => Array.IndexOf(s_order, g.Key) is var at and >= 0 ? at : s_order.Length); + foreach (var group in groups) { + var groupOpen = everythingOpen || open.Contains(group.Key); + rows.Add(Group(group.Key, group.Key, 0, groupOpen, group.Count())); + if (!groupOpen) continue; + var categories = group.GroupBy(CategoryOf).ToList(); + var flat = categories.Count == 1 || group.Count() <= 10; + foreach (var category in categories) { + if (flat) { + rows.AddRange(category.Select(e => Of(e, 1))); + continue; + } + var key = group.Key + "/" + category.Key; + var categoryOpen = everythingOpen || open.Contains(key); + rows.Add(Group(key, category.Key, 1, categoryOpen, category.Count(), group.Key)); + if (categoryOpen) rows.AddRange(category.Select(e => Of(e, 2))); + } + } + return rows; + } +} diff --git a/editor/LuaEditor/VariableRow.cs b/editor/LuaEditor/VariableRow.cs new file mode 100644 index 000000000..79b341671 --- /dev/null +++ b/editor/LuaEditor/VariableRow.cs @@ -0,0 +1,77 @@ +using CommunityToolkit.Mvvm.ComponentModel; +using Avalonia; +using Avalonia.Media; +using Avalonia.Media.Imaging; +using Lucide.Avalonia; +using editor.LuaEditor.Graph; +using editor.LuaEditor.Types; +using editor.Workspace; + +namespace editor.LuaEditor; + +public enum VariableRowKind { Script, Group, Field, Method, Tick, Native, Local } + +public sealed partial class VariableRow(string id, VariableRow? parent, string name, LucideIconKind icon, + VariableRowKind kind, GraphVariable? variable = null, Binding? binding = null, MemberInfo? native = null, + Bitmap? bitmap = null, string? nodeColor = null) : ObservableObject, IHierarchyRow { + [ObservableProperty] private bool m_isSelected; + [ObservableProperty] private bool m_isExpanded = true; + [ObservableProperty] private bool m_isFolded; + public string Id { get; } = id; + public VariableRow? Parent { get; } = parent; + public string Name { get; } = name; + public VariableRowKind Kind { get; } = kind; + public GraphVariable? Variable { get; } = variable; + public Binding? Binding { get; } = binding; + public MemberInfo? Native { get; } = native; + public Bitmap? Bitmap { get; } = bitmap; + public bool UsesLucide => Bitmap is null && Glyph is null; + public bool UsesGlyph => Glyph is not null; + public bool UsesBitmap => Bitmap is not null; + public Geometry? Glyph => Icon switch { + LucideIconKind.Code when Kind == VariableRowKind.Local => s_lambda, + LucideIconKind.Book when Kind == VariableRowKind.Local => s_bookBookmark, + _ => null + }; + + // Lucide Lambda and Book Bookmark paths, from lucide-icons/lucide. + // Copyright (c) 2026 Lucide Icons and Contributors + // Permission to use, copy, modify, and/or distribute this software for any + // purpose with or without fee is hereby granted, provided that the above + // copyright notice and this permission notice appear in all copies. + // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + private static readonly Geometry s_lambda = Geometry.Parse("M11.38 10 5 20 M19 18a2 2 0 0 1 -2 2c-4.87 -.003 -5.052 -16 -10 -16a2 2 0 0 0 -2 2"); + private static readonly Geometry s_bookBookmark = Geometry.Parse("M10 2v7.751a.25 .25 0 0 0 .407 .195l2.28 -1.834a.5 .5 0 0 1 .627 0l2.28 1.834A.25 .25 0 0 0 16 9.751V2 M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H19a1 1 0 0 1 1 1v18a1 1 0 0 1 -1 1H6.5a1 1 0 0 1 0 -5H20"); + public LucideIconKind Icon { get; } = icon; + public int Depth => Parent is null ? 0 : Parent.Depth + 1; + public bool HasChildren { get; internal set; } + public bool CanDrag => Variable is not null && Kind != VariableRowKind.Tick; + public bool IsPlaceholder => Kind == VariableRowKind.Tick && Variable is null; + public FontStyle FontStyle => IsPlaceholder ? FontStyle.Italic : FontStyle.Normal; + public double Opacity => IsPlaceholder ? 0.45 : 1; + public string Detail => Variable is null || Kind == VariableRowKind.Script ? "" : TypeFormatter.Display(Variable.Type); + public string ColorKey => nodeColor ?? Kind switch { + VariableRowKind.Native => Parent?.ColorKey ?? "TextMuted", + VariableRowKind.Field => "Blue", + VariableRowKind.Method => "Magenta", + VariableRowKind.Tick when IsPlaceholder => "TextMuted", + VariableRowKind.Tick => "Orange", + VariableRowKind.Local when Icon == LucideIconKind.Code => "Magenta", + VariableRowKind.Local when Icon == LucideIconKind.Table => "Cyan", + VariableRowKind.Local => "Green", + _ => Id switch { + "fields" => "Blue", + "methods" or "script" => "Magenta", + "ticks" => "Orange", + "local" => "Green", + _ => "TextMuted" + } + }; + public Thickness ContentMargin => new(HierarchyConnectorLayer.LeftPad + Depth * HierarchyConnectorLayer.IndentStep, 0, 0, 0); +} diff --git a/editor/Resources/EnumBox.axaml b/editor/Resources/EnumBox.axaml index c52f33583..09b94854c 100644 --- a/editor/Resources/EnumBox.axaml +++ b/editor/Resources/EnumBox.axaml @@ -61,13 +61,24 @@ Padding="4" BorderBrush="{StaticResource Bg4}" BorderThickness="1"> - - - - - - - + + + + + + + + + + + + diff --git a/editor/Workspace/HierarchyConnectorLayer.cs b/editor/Workspace/HierarchyConnectorLayer.cs index 083c2dc61..501bd13ad 100644 --- a/editor/Workspace/HierarchyConnectorLayer.cs +++ b/editor/Workspace/HierarchyConnectorLayer.cs @@ -6,6 +6,10 @@ namespace editor.Workspace; // You dont even know how much this took -x +public interface IHierarchyRow { + int Depth { get; } +} + public sealed class HierarchyConnectorLayer : Control { public const double RowHeight = 28; public const double IndentStep = 20; @@ -22,10 +26,10 @@ public sealed class HierarchyConnectorLayer : Control { private int m_dropLineDepth; private int m_dropLineIndex = -1; // row boundary to draw the insertion line at; -1 = none - private IReadOnlyList m_rows = []; + private IReadOnlyList m_rows = []; private int m_selectedIndex = -1; - public IReadOnlyList Rows { + public IReadOnlyList Rows { get => m_rows; set { m_rows = value; diff --git a/editor/Workspace/HierarchyRowPress.cs b/editor/Workspace/HierarchyRowPress.cs new file mode 100644 index 000000000..061c5e38f --- /dev/null +++ b/editor/Workspace/HierarchyRowPress.cs @@ -0,0 +1,28 @@ +using Avalonia; +using Avalonia.Input; + +namespace editor.Workspace; + +internal sealed class HierarchyRowPress where TRow : class { + private const double DragThreshold = 4; + private (TRow Row, PointerPressedEventArgs Args, Point Start, bool WasSelected)? m_press; + + public void Begin(TRow row, PointerPressedEventArgs args, Visual relativeTo, bool wasSelected) => + m_press = (row, args, args.GetPosition(relativeTo), wasSelected); + + public (TRow Row, PointerPressedEventArgs Args)? TakeDrag(PointerEventArgs args, Visual relativeTo) { + if (m_press is not { } press || !args.GetCurrentPoint(relativeTo).Properties.IsLeftButtonPressed) return null; + var delta = args.GetPosition(relativeTo) - press.Start; + if (delta.X * delta.X + delta.Y * delta.Y < DragThreshold * DragThreshold) return null; + Clear(); + return (press.Row, press.Args); + } + + public (TRow Row, bool WasSelected)? TakeClick(PointerReleasedEventArgs args) { + var press = m_press; + Clear(); + return args.InitialPressMouseButton == MouseButton.Left && press is { } click ? (click.Row, click.WasSelected) : null; + } + + public void Clear() => m_press = null; +} diff --git a/editor/Workspace/HierarchyView.axaml.cs b/editor/Workspace/HierarchyView.axaml.cs index ed5fb8ede..81be1158e 100644 --- a/editor/Workspace/HierarchyView.axaml.cs +++ b/editor/Workspace/HierarchyView.axaml.cs @@ -19,16 +19,10 @@ namespace editor.Workspace; public partial class HierarchyView : UserControl, IWorkspaceShortcutTarget { - private const double DragThreshold = 4; - private static readonly HashSet s_reservedNames = ["root", "world", "global"]; private HierarchyElement? m_dropTarget; - private PointerPressedEventArgs? m_pressArgs; - - private HierarchyElement? m_pressItem; - private Point m_pressPoint; - private bool m_pressWasSelected; + private readonly HierarchyRowPress m_rowPress = new(); private HierarchyViewModel? m_vm; public HierarchyView() { @@ -99,43 +93,24 @@ private void OnItemPointerPressed(object? sender, PointerPressedEventArgs e) { // remember the press so a small move can promote to a drag, and a click // can fall through to fold/unfold on release - m_pressItem = el; - m_pressArgs = e; - m_pressPoint = e.GetPosition(this); - m_pressWasSelected = ReferenceEquals(el, vm.SelectedNode); - if (!m_pressWasSelected) vm.SelectedNode = el; + var wasSelected = ReferenceEquals(el, vm.SelectedNode); + m_rowPress.Begin(el, e, this, wasSelected); + if (!wasSelected) vm.SelectedNode = el; Focus(); } private async void OnItemPointerMoved(object? sender, PointerEventArgs e) { - if (m_pressItem is null || m_pressArgs is null) return; - if (!e.GetCurrentPoint(this).Properties.IsLeftButtonPressed) return; - - var delta = e.GetPosition(this) - m_pressPoint; - if (delta.X * delta.X + delta.Y * delta.Y < DragThreshold * DragThreshold) return; - - var item = m_pressItem; - var args = m_pressArgs; - ClearPress(); - if (item.IsRoot) return; // the root cannot be reparented + if (m_rowPress.TakeDrag(e, this) is not { } drag || drag.Row.IsRoot) return; // the root cannot be reparented var data = new DataTransfer(); - data.Add(DataTransferItem.Create(NodeDragData.Format, item)); - await DragDrop.DoDragDropAsync(args, data, DragDropEffects.Copy | DragDropEffects.Move); + data.Add(DataTransferItem.Create(NodeDragData.Format, drag.Row)); + await DragDrop.DoDragDropAsync(drag.Args, data, DragDropEffects.Copy | DragDropEffects.Move); SetDropTarget(null); Connector.SetDropLine(-1, 0); } private void OnItemPointerReleased(object? sender, PointerReleasedEventArgs e) { - // a click on the already-selected node toggles fold - if (m_pressItem is { } item && m_pressWasSelected) Vm?.ToggleExpand(item); - ClearPress(); - } - - private void ClearPress() { - m_pressItem = null; - m_pressArgs = null; - m_pressWasSelected = false; + if (m_rowPress.TakeClick(e) is { WasSelected: true } click) Vm?.ToggleExpand(click.Row); } private void OnRenameStarted(HierarchyElement element) { diff --git a/editor/Workspace/HierarchyViewModel.cs b/editor/Workspace/HierarchyViewModel.cs index a3c5ce7d6..57e320f7c 100644 --- a/editor/Workspace/HierarchyViewModel.cs +++ b/editor/Workspace/HierarchyViewModel.cs @@ -20,7 +20,7 @@ namespace editor.Workspace; -public class HierarchyElement : INotifyPropertyChanged { +public class HierarchyElement : INotifyPropertyChanged, IHierarchyRow { private string m_draftName = ""; private bool m_isDropTarget; diff --git a/editor/Workspace/MainWindowView.axaml b/editor/Workspace/MainWindowView.axaml index c8ba582b2..3d2deb9ca 100644 --- a/editor/Workspace/MainWindowView.axaml +++ b/editor/Workspace/MainWindowView.axaml @@ -354,6 +354,10 @@ ToggleType="CheckBox" IsChecked="{Binding PaletteEditorVisible, Mode=TwoWay}" InputGesture="Alt+D7" /> + diff --git a/editor/Workspace/MainWindowViewModel.cs b/editor/Workspace/MainWindowViewModel.cs index a7b56d4f3..d3404df54 100644 --- a/editor/Workspace/MainWindowViewModel.cs +++ b/editor/Workspace/MainWindowViewModel.cs @@ -44,6 +44,7 @@ public partial class MainWindowViewModel : ViewModelBase, IDisposable { private ulong m_activeWorkspaceHandle; private bool m_applyingLayout; [ObservableProperty] private bool m_curveEditorVisible; + [ObservableProperty] private bool m_luaEditorVisible; [ObservableProperty] private bool m_genericEditorVisible; [ObservableProperty] private bool m_hapticsEditorVisible; [ObservableProperty] private bool m_paletteEditorVisible; @@ -128,11 +129,13 @@ public MainWindowViewModel(ToastEngine toast) { if (e.Dockable == m_toastZoneFactory.CurveEditorVm) m_curveEditorVisible = false; if (e.Dockable == m_toastZoneFactory.TableEditorVm) m_tableEditorVisible = false; if (e.Dockable == m_toastZoneFactory.PaletteEditorVm) m_paletteEditorVisible = false; + if (e.Dockable == m_toastZoneFactory.LuaEditorVm) m_luaEditorVisible = false; OnPropertyChanged(nameof(LogsVisible)); OnPropertyChanged(nameof(HapticsEditorVisible)); OnPropertyChanged(nameof(CurveEditorVisible)); OnPropertyChanged(nameof(TableEditorVisible)); + OnPropertyChanged(nameof(LuaEditorVisible)); OnPropertyChanged(nameof(PaletteEditorVisible)); }; @@ -212,6 +215,7 @@ private IEnumerable EnumerateAutosavables() { if (m_toastZoneFactory.HapticsEditorVm is { } haptics) yield return haptics; if (m_toastZoneFactory.TableEditorVm is { } table) yield return table; if (m_toastZoneFactory.PaletteEditorVm is { } palette) yield return palette; + if (m_toastZoneFactory.LuaEditorVm is { } lua) yield return lua; } [RelayCommand] @@ -376,6 +380,27 @@ partial void OnCurveEditorVisibleChanged(bool value) { ToggleToastTool("Curve", value); } + partial void OnLuaEditorVisibleChanged(bool value) { + if (m_applyingLayout) return; + if (value && m_toastZoneFactory.LuaEditorVm is { } vm) ShowLuaWindow(vm); + else if (!value) LuaEditor.LuaEditorWindow.CloseOpen(); + } + + private void ShowLuaWindow(LuaEditor.LuaGraphEditorViewModel vm) { + // old layouts may still contain a docked lua editor + m_toastZoneFactory.EvictLuaTool(); + LuaEditor.LuaEditorWindow.ShowFor(vm, App.MainWindow, () => { + if (m_luaEditorVisible) { + m_luaEditorVisible = false; + OnPropertyChanged(nameof(LuaEditorVisible)); + } + }); + if (!m_luaEditorVisible) { + m_luaEditorVisible = true; + OnPropertyChanged(nameof(LuaEditorVisible)); + } + } + partial void OnShowDebugWindowsChanged(bool value) { ToastEngine.SetShowDebugWindows(value); } @@ -441,6 +466,13 @@ private async void OnEditorOpenRequested(AssetFile file) { TableEditorVisible = true; } + break; + case "LuaEditor": + if (m_toastZoneFactory.LuaEditorVm is { } luaVm) { + _ = OpenToastEditorAsync(luaVm, uid, virtualPath, def, recoverPath); + ShowLuaWindow(luaVm); + } + break; case "PaletteEditor": if (m_toastZoneFactory.PaletteEditorVm is { } paletteVm) { @@ -636,6 +668,7 @@ private List CollectDirtyTools() { if (m_toastZoneFactory.HapticsEditorVm is { IsDirty: true }) dirty.Add("Haptics"); if (m_toastZoneFactory.TableEditorVm is { IsDirty: true }) dirty.Add("Table"); if (m_toastZoneFactory.PaletteEditorVm is { IsDirty: true }) dirty.Add("Palette"); + if (m_toastZoneFactory.LuaEditorVm is { IsDirty: true }) dirty.Add("Lua"); return dirty; } @@ -673,6 +706,8 @@ void AddEditor(string kind, bool dirty, string path, string uid, IAsyncRelayComm if (m_toastZoneFactory.PaletteEditorVm is { } palette) AddEditor("Palette", palette.IsDirty, palette.CurrentPath, palette.CurrentUid, palette.SaveCommand, () => palette.IsDirty); + if (m_toastZoneFactory.LuaEditorVm is { } luaGraph) + AddEditor("Lua", luaGraph.IsDirty, luaGraph.CurrentPath, luaGraph.CurrentUid, luaGraph.SaveCommand, () => luaGraph.IsDirty); return items; } @@ -708,11 +743,13 @@ private void RestoreTool(string id) { case "Haptics": HapticsEditorVisible = true; break; case "Table": TableEditorVisible = true; break; case "Palette": PaletteEditorVisible = true; break; + case "Lua": LuaEditorVisible = true; break; } } #pragma warning disable MVVMTK0034 private void SyncVisibilityFromDocks() { + m_toastZoneFactory.EvictLuaTool(); m_hierarchyVisible = m_dockFactory.IsToolVisible("Hierarchy"); m_historyVisible = m_dockFactory.IsToolVisible("History"); m_locksVisible = m_dockFactory.IsToolVisible("Locks"); @@ -725,6 +762,7 @@ private void SyncVisibilityFromDocks() { m_curveEditorVisible = m_toastZoneFactory.IsToolVisible("Curve"); m_tableEditorVisible = m_toastZoneFactory.IsToolVisible("Table"); m_paletteEditorVisible = m_toastZoneFactory.IsToolVisible("Palette"); + m_luaEditorVisible = LuaEditor.LuaEditorWindow.IsOpen; OnPropertyChanged(nameof(HierarchyVisible)); OnPropertyChanged(nameof(HistoryVisible)); @@ -737,6 +775,7 @@ private void SyncVisibilityFromDocks() { OnPropertyChanged(nameof(HapticsEditorVisible)); OnPropertyChanged(nameof(CurveEditorVisible)); OnPropertyChanged(nameof(TableEditorVisible)); + OnPropertyChanged(nameof(LuaEditorVisible)); OnPropertyChanged(nameof(PaletteEditorVisible)); } #pragma warning restore MVVMTK0034 diff --git a/editor/Workspace/ToastZoneFactory.cs b/editor/Workspace/ToastZoneFactory.cs index aa77fdf57..dc654532f 100644 --- a/editor/Workspace/ToastZoneFactory.cs +++ b/editor/Workspace/ToastZoneFactory.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; @@ -16,6 +16,7 @@ public class ToastZoneFactory : Factory { private bool m_curveClosePending; private bool m_hapticsClosePending; private bool m_paletteClosePending; + private bool m_luaClosePending; private IRootDock? m_rootDock; private bool m_tableClosePending; private IToolDock? m_toolDock; @@ -25,6 +26,7 @@ public class ToastZoneFactory : Factory { public HapticsViewModel? HapticsEditorVm { get; private set; } public TableViewModel? TableEditorVm { get; private set; } public PaletteViewModel? PaletteEditorVm { get; private set; } + public LuaEditor.LuaGraphEditorViewModel? LuaEditorVm { get; private set; } public AssetBrowserViewModel? AssetBrowserVm { get; private set; } public override IRootDock CreateLayout() { @@ -41,6 +43,8 @@ public override IRootDock CreateLayout() { { Id = "Table", Title = "Table Editor", CanPin = false, CanFloat = false }; var paletteEditor = new PaletteViewModel { Id = "Palette", Title = "Palette Editor", CanPin = false, CanFloat = false }; + var luaEditor = new LuaEditor.LuaGraphEditorViewModel + { Id = "Lua", Title = "Lua Graph", CanPin = false, CanFloat = false }; AssetBrowserVm = assetBrowser; LogsVm = logs; @@ -48,6 +52,7 @@ public override IRootDock CreateLayout() { CurveEditorVm = curveEditor; TableEditorVm = tableEditor; PaletteEditorVm = paletteEditor; + LuaEditorVm = luaEditor; m_toolDock = new ToolDock { AllowedDropOperations = DockOperationMask.Fill | DockOperationMask.Left | DockOperationMask.Right, @@ -110,6 +115,10 @@ private void HideTool(Tool tool) { }; } + public void EvictLuaTool() { + if (LuaEditorVm is { } lua && LayoutSerializer.ContainsVisible(m_rootDock, lua)) HideTool(lua); + } + public bool IsToolVisible(string id) { return ToolById(id) is { } tool && LayoutSerializer.ContainsVisible(m_rootDock, tool); } @@ -145,6 +154,7 @@ public bool IsToolVisible(string id) { yield return CurveEditorVm; yield return TableEditorVm; yield return PaletteEditorVm; + yield return LuaEditorVm; } private static IToolDock? FindBottomDock(IRootDock root) { @@ -187,14 +197,16 @@ public override void InitLayout(IDockable layout) { ["Haptics"] = () => layout, ["Curve"] = () => layout, ["Table"] = () => layout, - ["Palette"] = () => layout + ["Palette"] = () => layout, + ["Lua"] = () => layout }; DockableLocator = new Dictionary> { ["Root"] = () => m_rootDock, ["Haptics"] = () => HapticsEditorVm, ["Curve"] = () => CurveEditorVm, ["Table"] = () => TableEditorVm, - ["Palette"] = () => PaletteEditorVm + ["Palette"] = () => PaletteEditorVm, + ["Lua"] = () => LuaEditorVm }; HostWindowLocator = new Dictionary> { [nameof(IDockWindow)] = () => new EditorHostWindow() @@ -226,6 +238,11 @@ public override void CloseDockable(IDockable dockable) { return; } + if (dockable == LuaEditorVm && LuaEditorVm!.IsDirty && !m_luaClosePending) { + _ = GatedClose(LuaEditorVm, LuaEditorVm, v => m_luaClosePending = v); + return; + } + base.CloseDockable(dockable); } From 85fa7bbad2801566b7664b0a68695c20cd3a50d1 Mon Sep 17 00:00:00 2001 From: Xein Date: Wed, 11 Nov 2026 18:38:55 +0100 Subject: [PATCH 5/8] compact lua ui --- editor/LuaEditor/LuaGraphEditorView.axaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/editor/LuaEditor/LuaGraphEditorView.axaml b/editor/LuaEditor/LuaGraphEditorView.axaml index 73d173cc6..a85f16888 100644 --- a/editor/LuaEditor/LuaGraphEditorView.axaml +++ b/editor/LuaEditor/LuaGraphEditorView.axaml @@ -411,7 +411,7 @@ - + -