From 56e6ed1705539208c475ba12166d0f5e1dfb1fa7 Mon Sep 17 00:00:00 2001 From: Xein Date: Sun, 8 Nov 2026 12:30:52 +0100 Subject: [PATCH 1/4] Reflection generator --- .gitattributes | 3 - .github/workflows/ci-build-windows.yml | 9 - .github/workflows/ci-linux-dev.yml | 4 - .github/workflows/ci-linux-main.yml | 16 +- .gitignore | 2 - CMakePresets.json | 74 +- README.md | 1 - cmake/codegen.cmake | 41 +- cmake/install_cargo_output.cmake | 37 - docs/reflection.md | 2 +- docs/scripting.md | 2 +- engine/CMakeLists.txt | 7 +- flake.nix | 3 - toast-engine.slnx | 7 +- tools/CMakeLists.txt | 10 +- .../Analysis/FieldLayout.cs | 57 ++ .../Analysis/InheritanceOrder.cs | 55 ++ tools/reflection_generator/CMakeLists.txt | 28 +- tools/reflection_generator/Cargo.toml | 13 - .../GeneratorException.cs | 3 + .../reflection_generator/Model/Attributes.cs | 34 + tools/reflection_generator/Model/EventType.cs | 16 + tools/reflection_generator/Model/FieldKind.cs | 33 + tools/reflection_generator/Model/NodeType.cs | 42 + tools/reflection_generator/Options.cs | 61 ++ .../reflection_generator/Output/CppOutput.cs | 24 + tools/reflection_generator/Output/CppText.cs | 20 + tools/reflection_generator/Output/CppViews.cs | 175 ++++ tools/reflection_generator/Output/Database.cs | 145 ++++ .../reflection_generator/Output/LuaOutput.cs | 36 + .../reflection_generator/Output/OutputFile.cs | 21 + .../reflection_generator/Output/Templates.cs | 58 ++ .../Templates/events.d.lua.scriban} | 16 +- .../Templates/node.generated.hpp.scriban | 171 ++++ .../Templates/node.type_info.cpp.scriban | 21 + .../Output/Templates/node_info_fields.scriban | 10 + .../Templates/reflect.generated.cpp.scriban | 46 ++ .../Templates/types.d.lua.scriban} | 18 +- .../Parsing/AttributeReader.cs | 34 + .../Parsing/EventParser.cs | 135 +++ .../Parsing/ExportMacros.cs | 10 + .../Parsing/HeaderFinder.cs | 33 + .../Parsing/NodeParser.cs | 163 ++++ .../Parsing/ParameterReader.cs | 38 + tools/reflection_generator/Parsing/Syntax.cs | 47 ++ .../Parsing/TemplateArgs.cs | 36 + tools/reflection_generator/Pipeline.cs | 112 +++ tools/reflection_generator/Program.cs | 24 + tools/reflection_generator/README.md | 80 +- .../reflection_generator/Rules/FieldKinds.cs | 38 + tools/reflection_generator/Rules/LuaTypes.cs | 130 +++ .../Rules/TickFunctions.cs | 26 + .../reflection_generator/Rules/Validation.cs | 34 + tools/reflection_generator/Strings.cs | 27 + tools/reflection_generator/build.rs | 37 - .../reflection_generator.csproj | 43 + tools/reflection_generator/src/generator.rs | 165 ---- tools/reflection_generator/src/lib.rs | 153 ---- tools/reflection_generator/src/lua_stubs.rs | 284 ------- tools/reflection_generator/src/main.rs | 214 ----- tools/reflection_generator/src/node.rs | 321 -------- tools/reflection_generator/src/parser.rs | 768 ------------------ .../templates/node.generated.hpp.jinja2 | 170 ---- .../templates/node.type_info.cpp.jinja2 | 30 - .../templates/reflect.generated.cpp.jinja2 | 43 - tools/reflection_generator/tests/common.rs | 122 --- .../tests/debug_parser.rs | 35 - .../reflection_generator/tests/debug_tree.rs | 31 - .../reflection_generator/tests/events_test.rs | 68 -- .../tests/expected_outputs/01_simple.json | 107 --- .../tests/expected_outputs/02_inherited.json | 106 --- .../tests/expected_outputs/03_no_fields.json | 37 - .../tests/expected_outputs/04_no_ticks.json | 66 -- .../expected_outputs/05_complex_groups.json | 261 ------ .../tests/expected_outputs/06_all_types.json | 210 ----- .../tests/expected_outputs/07_attributes.json | 113 --- .../expected_outputs/08_multi_class.json | 100 --- .../expected_outputs/09_export_macros.json | 50 -- .../10_inheritance_chain.json | 53 -- .../11_deeply_nested_groups.json | 360 -------- .../expected_outputs/12_sparse_groups.json | 215 ----- .../expected_outputs/13_subgroup_only.json | 170 ---- .../14_mixed_subgroup_fields.json | 219 ----- .../expected_outputs/15_snake_case_names.json | 187 ----- .../16_all_tick_functions.json | 47 -- .../expected_outputs/17_global_namespace.json | 52 -- .../expected_outputs/18_nested_namespace.json | 50 -- .../19_field_with_all_attributes.json | 66 -- .../20_vector_of_different_types.json | 98 --- .../21_field_with_defaults.json | 114 --- .../expected_outputs/22_pointer_types.json | 50 -- .../23_qualified_type_names.json | 98 --- .../24_many_global_fields.json | 354 -------- .../25_m_prefix_stripping.json | 90 -- .../26_unsigned_integer_types.json | 114 --- .../27_signed_integer_types.json | 114 --- .../expected_outputs/28_empty_group.json | 66 -- .../29_duplicate_field_names.json | 94 --- .../30_const_volatile_fields.json | 82 -- .../31_reflected_functions.json | 123 --- .../tests/fixtures/01_simple.hpp | 11 - .../tests/fixtures/02_inherited.hpp | 11 - .../tests/fixtures/03_no_fields.hpp | 9 - .../tests/fixtures/04_no_ticks.hpp | 9 - .../tests/fixtures/05_complex_groups.hpp | 12 - .../tests/fixtures/06_all_types.hpp | 16 - .../tests/fixtures/07_attributes.hpp | 7 - .../tests/fixtures/08_multi_class.hpp | 15 - .../tests/fixtures/09_export_macros.hpp | 8 - .../tests/fixtures/10_inheritance_chain.hpp | 8 - .../fixtures/11_deeply_nested_groups.hpp | 15 - .../tests/fixtures/12_sparse_groups.hpp | 13 - .../tests/fixtures/13_subgroup_only.hpp | 9 - .../fixtures/14_mixed_subgroup_fields.hpp | 11 - .../tests/fixtures/15_snake_case_names.hpp | 9 - .../tests/fixtures/16_all_tick_functions.hpp | 19 - .../tests/fixtures/17_global_namespace.hpp | 7 - .../tests/fixtures/18_nested_namespace.hpp | 8 - .../fixtures/19_field_with_all_attributes.hpp | 6 - .../fixtures/20_vector_of_different_types.hpp | 9 - .../tests/fixtures/21_field_with_defaults.hpp | 10 - .../tests/fixtures/22_pointer_types.hpp | 8 - .../fixtures/23_qualified_type_names.hpp | 11 - .../tests/fixtures/24_many_global_fields.hpp | 25 - .../tests/fixtures/25_m_prefix_stripping.hpp | 8 - .../fixtures/26_unsigned_integer_types.hpp | 10 - .../fixtures/27_signed_integer_types.hpp | 10 - .../tests/fixtures/28_empty_group.hpp | 7 - .../fixtures/29_duplicate_field_names.hpp | 7 - .../fixtures/30_const_volatile_fields.hpp | 8 - .../tests/fixtures/31_reflected_functions.hpp | 31 - .../tests/integration_test.rs | 644 --------------- .../tests/lua_stubs_test.rs | 88 -- 133 files changed, 2109 insertions(+), 7608 deletions(-) delete mode 100644 cmake/install_cargo_output.cmake create mode 100644 tools/reflection_generator/Analysis/FieldLayout.cs create mode 100644 tools/reflection_generator/Analysis/InheritanceOrder.cs delete mode 100644 tools/reflection_generator/Cargo.toml create mode 100644 tools/reflection_generator/GeneratorException.cs create mode 100644 tools/reflection_generator/Model/Attributes.cs create mode 100644 tools/reflection_generator/Model/EventType.cs create mode 100644 tools/reflection_generator/Model/FieldKind.cs create mode 100644 tools/reflection_generator/Model/NodeType.cs create mode 100644 tools/reflection_generator/Options.cs create mode 100644 tools/reflection_generator/Output/CppOutput.cs create mode 100644 tools/reflection_generator/Output/CppText.cs create mode 100644 tools/reflection_generator/Output/CppViews.cs create mode 100644 tools/reflection_generator/Output/Database.cs create mode 100644 tools/reflection_generator/Output/LuaOutput.cs create mode 100644 tools/reflection_generator/Output/OutputFile.cs create mode 100644 tools/reflection_generator/Output/Templates.cs rename tools/reflection_generator/{templates/events.d.lua.jinja2 => Output/Templates/events.d.lua.scriban} (90%) create mode 100644 tools/reflection_generator/Output/Templates/node.generated.hpp.scriban create mode 100644 tools/reflection_generator/Output/Templates/node.type_info.cpp.scriban create mode 100644 tools/reflection_generator/Output/Templates/node_info_fields.scriban create mode 100644 tools/reflection_generator/Output/Templates/reflect.generated.cpp.scriban rename tools/reflection_generator/{templates/types.d.lua.jinja2 => Output/Templates/types.d.lua.scriban} (63%) create mode 100644 tools/reflection_generator/Parsing/AttributeReader.cs create mode 100644 tools/reflection_generator/Parsing/EventParser.cs create mode 100644 tools/reflection_generator/Parsing/ExportMacros.cs create mode 100644 tools/reflection_generator/Parsing/HeaderFinder.cs create mode 100644 tools/reflection_generator/Parsing/NodeParser.cs create mode 100644 tools/reflection_generator/Parsing/ParameterReader.cs create mode 100644 tools/reflection_generator/Parsing/Syntax.cs create mode 100644 tools/reflection_generator/Parsing/TemplateArgs.cs create mode 100644 tools/reflection_generator/Pipeline.cs create mode 100644 tools/reflection_generator/Program.cs create mode 100644 tools/reflection_generator/Rules/FieldKinds.cs create mode 100644 tools/reflection_generator/Rules/LuaTypes.cs create mode 100644 tools/reflection_generator/Rules/TickFunctions.cs create mode 100644 tools/reflection_generator/Rules/Validation.cs create mode 100644 tools/reflection_generator/Strings.cs delete mode 100644 tools/reflection_generator/build.rs create mode 100644 tools/reflection_generator/reflection_generator.csproj delete mode 100644 tools/reflection_generator/src/generator.rs delete mode 100644 tools/reflection_generator/src/lib.rs delete mode 100644 tools/reflection_generator/src/lua_stubs.rs delete mode 100644 tools/reflection_generator/src/main.rs delete mode 100644 tools/reflection_generator/src/node.rs delete mode 100644 tools/reflection_generator/src/parser.rs delete mode 100644 tools/reflection_generator/templates/node.generated.hpp.jinja2 delete mode 100644 tools/reflection_generator/templates/node.type_info.cpp.jinja2 delete mode 100644 tools/reflection_generator/templates/reflect.generated.cpp.jinja2 delete mode 100644 tools/reflection_generator/tests/common.rs delete mode 100644 tools/reflection_generator/tests/debug_parser.rs delete mode 100644 tools/reflection_generator/tests/debug_tree.rs delete mode 100644 tools/reflection_generator/tests/events_test.rs delete mode 100644 tools/reflection_generator/tests/expected_outputs/01_simple.json delete mode 100644 tools/reflection_generator/tests/expected_outputs/02_inherited.json delete mode 100644 tools/reflection_generator/tests/expected_outputs/03_no_fields.json delete mode 100644 tools/reflection_generator/tests/expected_outputs/04_no_ticks.json delete mode 100644 tools/reflection_generator/tests/expected_outputs/05_complex_groups.json delete mode 100644 tools/reflection_generator/tests/expected_outputs/06_all_types.json delete mode 100644 tools/reflection_generator/tests/expected_outputs/07_attributes.json delete mode 100644 tools/reflection_generator/tests/expected_outputs/08_multi_class.json delete mode 100644 tools/reflection_generator/tests/expected_outputs/09_export_macros.json delete mode 100644 tools/reflection_generator/tests/expected_outputs/10_inheritance_chain.json delete mode 100644 tools/reflection_generator/tests/expected_outputs/11_deeply_nested_groups.json delete mode 100644 tools/reflection_generator/tests/expected_outputs/12_sparse_groups.json delete mode 100644 tools/reflection_generator/tests/expected_outputs/13_subgroup_only.json delete mode 100644 tools/reflection_generator/tests/expected_outputs/14_mixed_subgroup_fields.json delete mode 100644 tools/reflection_generator/tests/expected_outputs/15_snake_case_names.json delete mode 100644 tools/reflection_generator/tests/expected_outputs/16_all_tick_functions.json delete mode 100644 tools/reflection_generator/tests/expected_outputs/17_global_namespace.json delete mode 100644 tools/reflection_generator/tests/expected_outputs/18_nested_namespace.json delete mode 100644 tools/reflection_generator/tests/expected_outputs/19_field_with_all_attributes.json delete mode 100644 tools/reflection_generator/tests/expected_outputs/20_vector_of_different_types.json delete mode 100644 tools/reflection_generator/tests/expected_outputs/21_field_with_defaults.json delete mode 100644 tools/reflection_generator/tests/expected_outputs/22_pointer_types.json delete mode 100644 tools/reflection_generator/tests/expected_outputs/23_qualified_type_names.json delete mode 100644 tools/reflection_generator/tests/expected_outputs/24_many_global_fields.json delete mode 100644 tools/reflection_generator/tests/expected_outputs/25_m_prefix_stripping.json delete mode 100644 tools/reflection_generator/tests/expected_outputs/26_unsigned_integer_types.json delete mode 100644 tools/reflection_generator/tests/expected_outputs/27_signed_integer_types.json delete mode 100644 tools/reflection_generator/tests/expected_outputs/28_empty_group.json delete mode 100644 tools/reflection_generator/tests/expected_outputs/29_duplicate_field_names.json delete mode 100644 tools/reflection_generator/tests/expected_outputs/30_const_volatile_fields.json delete mode 100644 tools/reflection_generator/tests/expected_outputs/31_reflected_functions.json delete mode 100644 tools/reflection_generator/tests/fixtures/01_simple.hpp delete mode 100644 tools/reflection_generator/tests/fixtures/02_inherited.hpp delete mode 100644 tools/reflection_generator/tests/fixtures/03_no_fields.hpp delete mode 100644 tools/reflection_generator/tests/fixtures/04_no_ticks.hpp delete mode 100644 tools/reflection_generator/tests/fixtures/05_complex_groups.hpp delete mode 100644 tools/reflection_generator/tests/fixtures/06_all_types.hpp delete mode 100644 tools/reflection_generator/tests/fixtures/07_attributes.hpp delete mode 100644 tools/reflection_generator/tests/fixtures/08_multi_class.hpp delete mode 100644 tools/reflection_generator/tests/fixtures/09_export_macros.hpp delete mode 100644 tools/reflection_generator/tests/fixtures/10_inheritance_chain.hpp delete mode 100644 tools/reflection_generator/tests/fixtures/11_deeply_nested_groups.hpp delete mode 100644 tools/reflection_generator/tests/fixtures/12_sparse_groups.hpp delete mode 100644 tools/reflection_generator/tests/fixtures/13_subgroup_only.hpp delete mode 100644 tools/reflection_generator/tests/fixtures/14_mixed_subgroup_fields.hpp delete mode 100644 tools/reflection_generator/tests/fixtures/15_snake_case_names.hpp delete mode 100644 tools/reflection_generator/tests/fixtures/16_all_tick_functions.hpp delete mode 100644 tools/reflection_generator/tests/fixtures/17_global_namespace.hpp delete mode 100644 tools/reflection_generator/tests/fixtures/18_nested_namespace.hpp delete mode 100644 tools/reflection_generator/tests/fixtures/19_field_with_all_attributes.hpp delete mode 100644 tools/reflection_generator/tests/fixtures/20_vector_of_different_types.hpp delete mode 100644 tools/reflection_generator/tests/fixtures/21_field_with_defaults.hpp delete mode 100644 tools/reflection_generator/tests/fixtures/22_pointer_types.hpp delete mode 100644 tools/reflection_generator/tests/fixtures/23_qualified_type_names.hpp delete mode 100644 tools/reflection_generator/tests/fixtures/24_many_global_fields.hpp delete mode 100644 tools/reflection_generator/tests/fixtures/25_m_prefix_stripping.hpp delete mode 100644 tools/reflection_generator/tests/fixtures/26_unsigned_integer_types.hpp delete mode 100644 tools/reflection_generator/tests/fixtures/27_signed_integer_types.hpp delete mode 100644 tools/reflection_generator/tests/fixtures/28_empty_group.hpp delete mode 100644 tools/reflection_generator/tests/fixtures/29_duplicate_field_names.hpp delete mode 100644 tools/reflection_generator/tests/fixtures/30_const_volatile_fields.hpp delete mode 100644 tools/reflection_generator/tests/fixtures/31_reflected_functions.hpp delete mode 100644 tools/reflection_generator/tests/integration_test.rs delete mode 100644 tools/reflection_generator/tests/lua_stubs_test.rs diff --git a/.gitattributes b/.gitattributes index 03ea6e75b..6bde1cc57 100644 --- a/.gitattributes +++ b/.gitattributes @@ -13,9 +13,6 @@ *.cs linguist-detectable=true linguist-language=C# *.axaml linguist-detectable=true linguist-language=C# -# Rust -*.rs linguist-detectable=true linguist-language=Rust - # Lua *.lua linguist-detectable=true linguist-language=Lua *.d.lua linguist-detectable=true linguist-language=Lua diff --git a/.github/workflows/ci-build-windows.yml b/.github/workflows/ci-build-windows.yml index a00f75925..dd1ff7a10 100644 --- a/.github/workflows/ci-build-windows.yml +++ b/.github/workflows/ci-build-windows.yml @@ -41,9 +41,6 @@ jobs: with: dotnet-version: "10.0.x" - - name: Setup Rust - uses: dtolnay/rust-toolchain@stable - - name: Setup MSVC uses: ilammy/msvc-dev-cmd@v1 @@ -81,9 +78,6 @@ jobs: with: dotnet-version: "10.0.x" - - name: Setup Rust - uses: dtolnay/rust-toolchain@stable - - name: Setup MSVC uses: ilammy/msvc-dev-cmd@v1 @@ -125,9 +119,6 @@ jobs: with: dotnet-version: "10.0.x" - - name: Setup Rust - uses: dtolnay/rust-toolchain@stable - - name: Setup MSVC uses: ilammy/msvc-dev-cmd@v1 diff --git a/.github/workflows/ci-linux-dev.yml b/.github/workflows/ci-linux-dev.yml index 057ed08a5..275c96804 100644 --- a/.github/workflows/ci-linux-dev.yml +++ b/.github/workflows/ci-linux-dev.yml @@ -36,8 +36,6 @@ jobs: env: TRACY_NO_INVARIANT_CHECK: "1" run: nix develop --command bash -c " - rustup toolchain install stable --no-self-update && - rustup default stable && cmake -B build -G Ninja -DCMAKE_C_COMPILER=gcc -DCMAKE_CXX_COMPILER=g++ @@ -68,8 +66,6 @@ jobs: - name: Configure and run clang-tidy run: nix develop --command bash -c " - rustup toolchain install stable --no-self-update && - rustup default stable && cmake -B build -G Ninja -DCMAKE_C_COMPILER=gcc -DCMAKE_CXX_COMPILER=g++ diff --git a/.github/workflows/ci-linux-main.yml b/.github/workflows/ci-linux-main.yml index 8eae0a8ee..879a9fd60 100644 --- a/.github/workflows/ci-linux-main.yml +++ b/.github/workflows/ci-linux-main.yml @@ -56,8 +56,6 @@ jobs: env: TRACY_NO_INVARIANT_CHECK: "1" run: nix develop --command bash -c " - rustup toolchain install stable --no-self-update && - rustup default stable && cmake -B build -G Ninja -DCMAKE_C_COMPILER=${{ matrix.c_compiler }} -DCMAKE_CXX_COMPILER=${{ matrix.cxx_compiler }} @@ -89,8 +87,6 @@ jobs: - name: Configure and run clang-tidy run: nix develop --command bash -c " - rustup toolchain install stable --no-self-update && - rustup default stable && cmake -B build -G Ninja -DCMAKE_C_COMPILER=gcc -DCMAKE_CXX_COMPILER=g++ @@ -102,12 +98,12 @@ jobs: bash ./tools/ci/clang_tidy.sh build " - cargo-reflection-generator: - name: Cargo reflection_generator (${{ matrix.build_type }}) + dotnet-reflection-generator: + name: Dotnet reflection_generator (${{ matrix.build_type }}) runs-on: [self-hosted, Linux, X64] strategy: matrix: - build_type: [debug, release] + build_type: [Debug, Release] fail-fast: false steps: - name: Checkout PR branch @@ -121,10 +117,8 @@ jobs: - name: Install Nix uses: cachix/install-nix-action@v31.10.6 - - name: Cargo build - env: - RELEASE_FLAG: ${{ matrix.build_type == 'release' && '--release' || '' }} - run: nix develop --command bash -c "rustup toolchain install stable --no-self-update && rustup default stable && cargo build --manifest-path tools/reflection_generator/Cargo.toml $RELEASE_FLAG" + - name: Dotnet build and test + run: nix develop --command bash -c 'dotnet build tools/reflection_generator/reflection_generator.csproj --configuration ${{ matrix.build_type }} && dotnet test tools/reflection_generator/tests/ReflectionGenerator.Tests --configuration ${{ matrix.build_type }}' dotnet-editor: name: Dotnet editor (${{ matrix.build_type }}) diff --git a/.gitignore b/.gitignore index 7942c6b9c..89abb3898 100644 --- a/.gitignore +++ b/.gitignore @@ -31,12 +31,10 @@ CMakeUserPresets.json **.sln vsxmake**/ vs**/ -Cargo.lock *.user # exclusions !/tests/** !/toast/src/** -!/tools/reflection_generator/build.rs **/imgui.ini diff --git a/CMakePresets.json b/CMakePresets.json index f5ee7a4ce..02baaa2ef 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -17,6 +17,10 @@ "name": "windows", "hidden": true, "inherits": "vcpkg", + "cacheVariables": { + "CMAKE_C_COMPILER": "cl", + "CMAKE_CXX_COMPILER": "cl" + }, "condition": { "type": "equals", "lhs": "${hostSystemName}", @@ -36,74 +40,34 @@ { "name": "win-debug", "displayName": "Debug", - "description": "Visual Studio, MSVC, Debug", + "description": "Ninja, MSVC, Debug", "inherits": "windows", - "generator": "Visual Studio 18 2026", + "generator": "Ninja", "binaryDir": "${sourceDir}/build/Debug", "cacheVariables": { - "CMAKE_CONFIGURATION_TYPES": "Debug" + "CMAKE_BUILD_TYPE": "Debug" } }, { "name": "win-release", "displayName": "Release", - "description": "Visual Studio, MSVC, Release", + "description": "Ninja, MSVC, Release", "inherits": "windows", - "generator": "Visual Studio 18 2026", + "generator": "Ninja", "binaryDir": "${sourceDir}/build/Release", "cacheVariables": { - "CMAKE_CONFIGURATION_TYPES": "Release" + "CMAKE_BUILD_TYPE": "Release" } }, { "name": "win-relwithdebinfo", "displayName": "RelWithDebInfo", - "description": "Visual Studio, MSVC, Release with debug information", - "inherits": "windows", - "generator": "Visual Studio 18 2026", - "binaryDir": "${sourceDir}/build/RelWithDebInfo", - "cacheVariables": { - "CMAKE_CONFIGURATION_TYPES": "RelWithDebInfo" - } - }, - { - "name": "win-ninja", - "displayName": "Ninja", - "description": "Ninja, MSVC, Debug", + "description": "Ninja, MSVC, Release with debug information", "inherits": "windows", "generator": "Ninja", - "binaryDir": "${sourceDir}/build/Debug", - "cacheVariables": { - "CMAKE_BUILD_TYPE": "Debug", - "CMAKE_C_COMPILER": "cl", - "CMAKE_CXX_COMPILER": "cl" - } - }, - { - "name": "winja-rwd", - "displayName": "Ninja", - "description": "Ninja, MSVC, Debug", - "inherits": "windows", - "generator": "Ninja", - "binaryDir": "${sourceDir}/build/ReleaseWithDebInfo", - "cacheVariables": { - "CMAKE_BUILD_TYPE": "RelWithDebInfo", - "CMAKE_C_COMPILER": "cl", - "CMAKE_CXX_COMPILER": "cl" - } - }, - { - "name": "win-ninja-gcc", - "displayName": "Ninja (gcc)", - "description": "Ninja, GCC, Debug", - "inherits": "windows", - "generator": "Ninja", - "binaryDir": "${sourceDir}/build/Mingw", + "binaryDir": "${sourceDir}/build/RelWithDebInfo", "cacheVariables": { - "CMAKE_BUILD_TYPE": "Debug", - "CMAKE_C_COMPILER": "gcc", - "CMAKE_CXX_COMPILER": "g++", - "VCPKG_TARGET_TRIPLET": "x64-mingw-dynamic" + "CMAKE_BUILD_TYPE": "RelWithDebInfo" } }, { @@ -199,18 +163,6 @@ "configurePreset": "win-relwithdebinfo", "configuration": "RelWithDebInfo" }, - { - "name": "win-ninja", - "displayName": "Ninja", - "inherits": "windows-build", - "configurePreset": "win-ninja" - }, - { - "name": "win-ninja-gcc", - "displayName": "Ninja (gcc)", - "inherits": "windows-build", - "configurePreset": "win-ninja-gcc" - }, { "name": "linux-debug", "displayName": "Debug", diff --git a/README.md b/README.md index db9c02cba..9c3353aff 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,6 @@ Credits: ### Prerequisites - CMake >=3.24 - A C++23 compiler (VS18 and GCC15 tested) -- Rustc and Cargo - C# .NET10 toolchain - VCPKG with `VCPKG_ROOT` set up in PATH diff --git a/cmake/codegen.cmake b/cmake/codegen.cmake index 2974f70f6..92df0f5dd 100644 --- a/cmake/codegen.cmake +++ b/cmake/codegen.cmake @@ -48,39 +48,28 @@ macro(run_codegen) set(_cfg "Debug") endif() if(_cfg STREQUAL "Release" OR _cfg STREQUAL "RelWithDebInfo" OR _cfg STREQUAL "MinSizeRel") - set(_profile_dir "release") - set(_profile_flag "release") + set(_dotnet_config "Release") else() - set(_profile_dir "debug") - set(_profile_flag "dev") + set(_dotnet_config "Debug") endif() - set(_refgen_cargo_dir "${OUTPUT_ROOT}/${_cfg}/cargo") + set(_refgen_dir "${OUTPUT_ROOT}/${_cfg}/reflection_generator") - find_program(CARGO cargo REQUIRED) + find_program(DOTNET dotnet REQUIRED) execute_process( - COMMAND ${CARGO} build --profile "${_profile_flag}" --target-dir "${_refgen_cargo_dir}" - WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}/tools/reflection_generator" - RESULT_VARIABLE _cargo_result - ERROR_VARIABLE _cargo_error + COMMAND ${DOTNET} build "${CMAKE_SOURCE_DIR}/tools/reflection_generator/reflection_generator.csproj" + --configuration ${_dotnet_config} --output "${_refgen_dir}" --nologo + RESULT_VARIABLE _dotnet_result + OUTPUT_VARIABLE _dotnet_output + ERROR_VARIABLE _dotnet_error ) - if(NOT _cargo_result EQUAL 0) - message(FATAL_ERROR "Failed to build reflection_generator:\n${_cargo_error}") + if(NOT _dotnet_result EQUAL 0) + # msbuild reports compile errors on stdout + message(FATAL_ERROR "Failed to build reflection_generator:\n${_dotnet_output}\n${_dotnet_error}") endif() - set(_bin "reflection_generator${CMAKE_EXECUTABLE_SUFFIX}") - set(_direct "${_refgen_cargo_dir}/${_profile_dir}/${_bin}") - if(EXISTS "${_direct}") - set(REFLECTION_GENERATOR "${_direct}") - else() - file(GLOB _cands "${_refgen_cargo_dir}/*/${_profile_dir}/${_bin}") - if(NOT _cands) - message(FATAL_ERROR - "reflection_generator binary not found.\n" - "Searched:\n" - " ${_refgen_cargo_dir}/${_profile_dir}/${_bin}\n" - " ${_refgen_cargo_dir}/*/${_profile_dir}/${_bin}") - endif() - list(GET _cands 0 REFLECTION_GENERATOR) + set(REFLECTION_GENERATOR "${_refgen_dir}/reflection_generator${CMAKE_EXECUTABLE_SUFFIX}") + if(NOT EXISTS "${REFLECTION_GENERATOR}") + message(FATAL_ERROR "reflection_generator binary not found at ${REFLECTION_GENERATOR}") endif() message(STATUS "Using reflection_generator: ${REFLECTION_GENERATOR}") diff --git a/cmake/install_cargo_output.cmake b/cmake/install_cargo_output.cmake deleted file mode 100644 index d0aa6cc0a..000000000 --- a/cmake/install_cargo_output.cmake +++ /dev/null @@ -1,37 +0,0 @@ -if(NOT BINARY_NAMES) - message(FATAL_ERROR "install_cargo_output: BINARY_NAMES is empty") -endif() - -# cargo uses // when a target triple is configured -list(GET BINARY_NAMES 0 _first) -set(_probe "${_first}${EXE_SUFFIX}") - -if(EXISTS "${CARGO_TARGET_DIR}/${PROFILE_NAME}/${_probe}") - set(_src_dir "${CARGO_TARGET_DIR}/${PROFILE_NAME}") -else() - file(GLOB _candidates "${CARGO_TARGET_DIR}/*/${PROFILE_NAME}/${_probe}") - if(NOT _candidates) - message(FATAL_ERROR - "cargo output not found for '${_probe}'\n" - "Searched:\n" - " ${CARGO_TARGET_DIR}/${PROFILE_NAME}/\n" - " ${CARGO_TARGET_DIR}/*/${PROFILE_NAME}/") - endif() - list(GET _candidates 0 _found) - cmake_path(GET _found PARENT_PATH _src_dir) -endif() - -file(MAKE_DIRECTORY "${DEST_DIR}") - -foreach(_name IN LISTS BINARY_NAMES) - set(_binary "${_name}${EXE_SUFFIX}") - if(NOT EXISTS "${_src_dir}/${_binary}") - message(FATAL_ERROR "cargo output not found: ${_src_dir}/${_binary}") - endif() - # file(COPY) compares timestamps so unchanged binaries are not rewritten - file(COPY "${_src_dir}/${_binary}" DESTINATION "${DEST_DIR}") -endforeach() - -if(EXISTS "${_src_dir}/templates") - file(COPY "${_src_dir}/templates" DESTINATION "${DEST_DIR}") -endif() diff --git a/docs/reflection.md b/docs/reflection.md index dab840319..480396ac6 100644 --- a/docs/reflection.md +++ b/docs/reflection.md @@ -155,7 +155,7 @@ A completely `constexpr` templated struct called `Reflect` would hold all ref fields, functions and attributes on a given class, with getters and setters and a bunch of other functions like RTTI, Factory functions, destructors, etc. to avoid the use of vtables on the `Node` classes while maintaining inheritance and polymorphism. A generator -coded mainly in rust (`tools/reflection_generator`) would then parse all header files that +coded in C# (`tools/reflection_generator`) would then parse all header files that contain a `[[ToastNode]]` attribute and generate an Abstract Syntax Tree with Tree-sitter. Then, it would generate C++ files that would get compiled with the project and would fill out all the information required by the `Reflect` class. diff --git a/docs/scripting.md b/docs/scripting.md index ca0f2ce9e..1a3b5b082 100644 --- a/docs/scripting.md +++ b/docs/scripting.md @@ -196,7 +196,7 @@ a bitmask at load, so a node whose script only defines `init` costs nothing per `tests/scripting` covers schema extraction (types, groups, ordering, collisions), scheduling of Lua-only tick functions, hot-reload value preservation, and error -reporting. The reflection generator's stub emission is covered by its own cargo tests. +reporting. The reflection generator's stub emission is covered by its own dotnet tests. ## Expansion diff --git a/engine/CMakeLists.txt b/engine/CMakeLists.txt index 6b336d73c..45c91f210 100644 --- a/engine/CMakeLists.txt +++ b/engine/CMakeLists.txt @@ -66,8 +66,11 @@ add_library(toast_engine SHARED ${SOURCE}) file(GLOB_RECURSE TOAST_REFLECTED_HEADERS CONFIGURE_DEPENDS "src/toast/*.hpp" "src/toast/*.h") file(GLOB_RECURSE TOAST_REFLECTION_GENERATOR_SOURCES CONFIGURE_DEPENDS - "${CMAKE_SOURCE_DIR}/tools/reflection_generator/src/*.rs" - "${CMAKE_SOURCE_DIR}/tools/reflection_generator/templates/*") + "${CMAKE_SOURCE_DIR}/tools/reflection_generator/*.cs" + "${CMAKE_SOURCE_DIR}/tools/reflection_generator/*.scriban" + "${CMAKE_SOURCE_DIR}/tools/reflection_generator/*.csproj") +# obj holds generated .cs files that change on every build and would force a regeneration each time +list(FILTER TOAST_REFLECTION_GENERATOR_SOURCES EXCLUDE REGEX "/(obj|bin|tests)/") add_custom_command( OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/reflection.stamp" COMMAND "${OUTPUT_ROOT}/$/reflection_generator/reflection_generator${CMAKE_EXECUTABLE_SUFFIX}" diff --git a/flake.nix b/flake.nix index 3284a7681..3a934ac5b 100644 --- a/flake.nix +++ b/flake.nix @@ -99,15 +99,12 @@ ccache ninja valgrind - rustc - cargo protobuf grpc pkg-config vcpkg dotnet-sdk clang-tools - rust-analyzer buf roslyn-ls gdb diff --git a/toast-engine.slnx b/toast-engine.slnx index cf101e7bd..74ee65183 100644 --- a/toast-engine.slnx +++ b/toast-engine.slnx @@ -1,5 +1,6 @@ - - - + + + + diff --git a/tools/CMakeLists.txt b/tools/CMakeLists.txt index 94f7b3baa..153261819 100644 --- a/tools/CMakeLists.txt +++ b/tools/CMakeLists.txt @@ -32,18 +32,18 @@ add_custom_target(kenzo ALL add_dependencies(reflection_generator packer) if (BUILD_TESTING) - find_program(CARGO cargo) - if (CARGO) + find_program(DOTNET dotnet) + if (DOTNET) add_test( NAME refgen_unit_tests - COMMAND ${CARGO} test --manifest-path "${CMAKE_CURRENT_SOURCE_DIR}/reflection_generator/Cargo.toml" + 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;rust" + LABELS "reflection_generator;dotnet" TIMEOUT 300 ) else() - message(WARNING "cargo not found; skipping reflection_generator unit tests") + message(WARNING "dotnet not found; skipping reflection_generator unit tests") endif() endif() diff --git a/tools/reflection_generator/Analysis/FieldLayout.cs b/tools/reflection_generator/Analysis/FieldLayout.cs new file mode 100644 index 000000000..d077edd61 --- /dev/null +++ b/tools/reflection_generator/Analysis/FieldLayout.cs @@ -0,0 +1,57 @@ +using ReflectionGenerator.Model; + +namespace ReflectionGenerator.Analysis; + +internal sealed record FieldSubgroup(string Name, IReadOnlyList Fields); + +internal sealed record FieldGroup(string Name, IReadOnlyList Fields, IReadOnlyList Subgroups); + +// the inspector shows loose fields first then each Group with its Subgroups +internal sealed record FieldLayout(IReadOnlyList GlobalFields, IReadOnlyList Groups) +{ + // generated indices and lua stubs both follow this order + public IEnumerable InOrder => GlobalFields.Concat(Groups.SelectMany(g => g.Fields.Concat(g.Subgroups.SelectMany(s => s.Fields)))); + + public static FieldLayout From(IEnumerable fields) + { + var global = new List(); + var groups = new SortedDictionary(StringComparer.Ordinal); + + foreach (var field in fields) { + var group = field.Attributes.FirstArg("Group"); + if (group is null) { + global.Add(field); + continue; + } + + if (!groups.TryGetValue(group, out var builder)) { + groups[group] = builder = new GroupBuilder(); + } + builder.Add(field, field.Attributes.FirstArg("Subgroup")); + } + + return new FieldLayout(global, groups.Select(g => g.Value.Build(g.Key)).ToList()); + } + + private sealed class GroupBuilder + { + private readonly List m_fields = []; + private readonly SortedDictionary> m_subgroups = new(StringComparer.Ordinal); + + public void Add(Field field, string? subgroup) + { + if (subgroup is null) { + m_fields.Add(field); + return; + } + + if (!m_subgroups.TryGetValue(subgroup, out var list)) { + m_subgroups[subgroup] = list = []; + } + list.Add(field); + } + + public FieldGroup Build(string name) => + new(name, m_fields, m_subgroups.Select(s => new FieldSubgroup(s.Key, s.Value)).ToList()); + } +} diff --git a/tools/reflection_generator/Analysis/InheritanceOrder.cs b/tools/reflection_generator/Analysis/InheritanceOrder.cs new file mode 100644 index 000000000..d86f2f8a1 --- /dev/null +++ b/tools/reflection_generator/Analysis/InheritanceOrder.cs @@ -0,0 +1,55 @@ +using ReflectionGenerator.Model; + +namespace ReflectionGenerator.Analysis; + +internal static class InheritanceOrder +{ + // a generated header includes its parent's header so parents have to come first + public static IReadOnlyList Sort(IReadOnlyList nodes) + { + var indexByName = new Dictionary(); + for (var i = 0; i < nodes.Count; i++) { + indexByName[nodes[i].QualifiedName] = i; + } + + var parents = nodes.Select(n => ParentIndex(n, indexByName)).ToList(); + var placed = new bool[nodes.Count]; + var order = new List(); + + for (var start = 0; start < nodes.Count; start++) { + // climb to an ancestor that is already placed or to the start of a cycle then emit top down + var chain = new List(); + for (int? current = start; current is { } i && !placed[i] && !chain.Contains(i); current = parents[i]) { + chain.Add(i); + } + + chain.Reverse(); + foreach (var i in chain) { + placed[i] = true; + order.Add(i); + } + } + + return order.Select(i => nodes[i]).ToList(); + } + + // looks the parent up from the innermost namespace outwards like c++ does + private static int? ParentIndex(NodeType node, Dictionary indexByName) + { + if (node.Parent is null) return null; + + var written = Strings.Qualify(node.Parent.Namespace, node.Parent.Name); + if (written.StartsWith("::", StringComparison.Ordinal)) { + return indexByName.TryGetValue(written[2..], out var global) ? global : null; + } + + var scope = node.Namespace; + while (true) { + if (indexByName.TryGetValue(Strings.Qualify(scope, written), out var index)) return index; + if (scope is null) return null; + + var cut = scope.LastIndexOf("::", StringComparison.Ordinal); + scope = cut < 0 ? null : scope[..cut]; + } + } +} diff --git a/tools/reflection_generator/CMakeLists.txt b/tools/reflection_generator/CMakeLists.txt index f1568082d..083a8d428 100644 --- a/tools/reflection_generator/CMakeLists.txt +++ b/tools/reflection_generator/CMakeLists.txt @@ -1,25 +1,17 @@ project(reflection_generator NONE) -set(CARGO_PROJECT_DIR "${CMAKE_CURRENT_SOURCE_DIR}") -set(CARGO_TARGET_DIR "${OUTPUT_ROOT}/$/cargo") -set(CARGO_PROFILE_NAME "$,$,$>,release,debug>") -set(CARGO_PROFILE_FLAG "$,$,$>,release,dev>") +set(DOTNET_CONFIG "$,$,$>,Release,Debug>") -find_program(CARGO_EXECUTABLE cargo REQUIRED) -message(STATUS "Found cargo: ${CARGO_EXECUTABLE}") -message(STATUS "Build configuration: ${CARGO_PROFILE_NAME}") -message(STATUS "Cargo target directory: ${CARGO_TARGET_DIR}") +find_program(DOTNET_EXECUTABLE dotnet REQUIRED) +message(STATUS "Found dotnet: ${DOTNET_EXECUTABLE}") add_custom_target(reflection_generator ALL - COMMAND ${CARGO_EXECUTABLE} build --profile "${CARGO_PROFILE_FLAG}" --target-dir "${CARGO_TARGET_DIR}" - COMMAND ${CMAKE_COMMAND} - -DCARGO_TARGET_DIR=${CARGO_TARGET_DIR} - -DPROFILE_NAME=${CARGO_PROFILE_NAME} - "-DBINARY_NAMES=reflection_generator" - -DEXE_SUFFIX=${CMAKE_EXECUTABLE_SUFFIX} - -DDEST_DIR=${OUTPUT_ROOT}/$/reflection_generator - -P ${CMAKE_SOURCE_DIR}/cmake/install_cargo_output.cmake - WORKING_DIRECTORY ${CARGO_PROJECT_DIR} - COMMENT "[cargo] Building reflection_generator (${CARGO_PROFILE_NAME})..." + COMMAND ${DOTNET_EXECUTABLE} build + "${CMAKE_CURRENT_SOURCE_DIR}/reflection_generator.csproj" + --configuration ${DOTNET_CONFIG} + --output "${OUTPUT_ROOT}/$/reflection_generator" + --nologo + WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} + COMMENT "[dotnet] Building reflection_generator (${DOTNET_CONFIG})..." VERBATIM ) diff --git a/tools/reflection_generator/Cargo.toml b/tools/reflection_generator/Cargo.toml deleted file mode 100644 index a2d2bcf89..000000000 --- a/tools/reflection_generator/Cargo.toml +++ /dev/null @@ -1,13 +0,0 @@ -[package] -name = "reflection_generator" -version = "0.1.0" -edition = "2024" - -[dependencies] -minijinja = "2.20.0" -tree-sitter = "0.26.9" -tree-sitter-cpp = "0.23.4" -serde = { version = "1.0", features = ["derive"] } -serde_json = "1.0.150" -clap = { version = "4", features = ["derive"] } -walkdir = "2" diff --git a/tools/reflection_generator/GeneratorException.cs b/tools/reflection_generator/GeneratorException.cs new file mode 100644 index 000000000..58e50f79f --- /dev/null +++ b/tools/reflection_generator/GeneratorException.cs @@ -0,0 +1,3 @@ +namespace ReflectionGenerator; + +internal sealed class GeneratorException(string message) : Exception(message); diff --git a/tools/reflection_generator/Model/Attributes.cs b/tools/reflection_generator/Model/Attributes.cs new file mode 100644 index 000000000..4882525d0 --- /dev/null +++ b/tools/reflection_generator/Model/Attributes.cs @@ -0,0 +1,34 @@ +using System.Collections; + +namespace ReflectionGenerator.Model; + +internal sealed record CppAttribute(string Name, IReadOnlyList Args); + +internal sealed class AttributeList(IEnumerable items) : IEnumerable +{ + private readonly List m_items = items.ToList(); + + public static AttributeList Empty => new([]); + + public bool Has(string name) => m_items.Any(a => a.Name == name); + + public string? FirstArg(string name) => m_items.FirstOrDefault(a => a.Name == name)?.Args.FirstOrDefault(); + + public AttributeList Without(string name) => new(m_items.Where(a => a.Name != name)); + + public AttributeList WithMarker(string name) => Has(name) ? this : new(m_items.Append(new CppAttribute(name, []))); + + // generated code and json both want attributes sorted by name with the last repeat winning + public SortedDictionary ByName() + { + var result = new SortedDictionary(StringComparer.Ordinal); + foreach (var attribute in m_items) { + result[attribute.Name] = attribute.Args.ToArray(); + } + return result; + } + + public IEnumerator GetEnumerator() => m_items.GetEnumerator(); + + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); +} diff --git a/tools/reflection_generator/Model/EventType.cs b/tools/reflection_generator/Model/EventType.cs new file mode 100644 index 000000000..02a337dd2 --- /dev/null +++ b/tools/reflection_generator/Model/EventType.cs @@ -0,0 +1,16 @@ +namespace ReflectionGenerator.Model; + +internal sealed record EventField(string Name, string TypeName, string? LuaType, bool Readable); + +internal sealed record EventType( + string Name, + string? Namespace, + IReadOnlyList Fields, + string SourceFile, + bool ConstructorCompatible, + bool Supported, + bool Sendable, + string? SkipReason) +{ + public string QualifiedName => Strings.Qualify(Namespace, Name); +} diff --git a/tools/reflection_generator/Model/FieldKind.cs b/tools/reflection_generator/Model/FieldKind.cs new file mode 100644 index 000000000..58c15b2c5 --- /dev/null +++ b/tools/reflection_generator/Model/FieldKind.cs @@ -0,0 +1,33 @@ +namespace ReflectionGenerator.Model; + +internal enum FieldKind +{ + Bool, + Int, + Float, + String, + Double, + Uid, + Vec2, + Vec3, + Vec4, + Quaternion, +} + +internal static class FieldKindNames +{ + // these are the FieldType enumerators in reflect_node.hpp and the field_type values the editor reads + public static string Name(this FieldKind kind) => kind switch { + FieldKind.Bool => "bool_t", + FieldKind.Int => "int_t", + FieldKind.Float => "float_t", + FieldKind.String => "string_t", + FieldKind.Double => "double_t", + FieldKind.Uid => "uid_t", + FieldKind.Vec2 => "vec2_t", + FieldKind.Vec3 => "vec3_t", + FieldKind.Vec4 => "vec4_t", + FieldKind.Quaternion => "quaternion_t", + _ => throw new ArgumentOutOfRangeException(nameof(kind)), + }; +} diff --git a/tools/reflection_generator/Model/NodeType.cs b/tools/reflection_generator/Model/NodeType.cs new file mode 100644 index 000000000..c0404f608 --- /dev/null +++ b/tools/reflection_generator/Model/NodeType.cs @@ -0,0 +1,42 @@ +namespace ReflectionGenerator.Model; + +internal sealed record ParentRef(string Name, string? Namespace); + +internal sealed record Parameter(string Name, string Type, string? Default); + +internal sealed record Field( + string Name, + string TypeName, + FieldKind Kind, + bool IsArray, + AttributeList Attributes, + string? Default); + +internal sealed record Method( + string Name, + string ReturnType, + IReadOnlyList Parameters, + bool IsConst, + AttributeList Attributes); + +internal sealed record Signal( + string Name, + string TypeName, + IReadOnlyList Arguments, + AttributeList Attributes); + +internal sealed record NodeType( + string Name, + string? Namespace, + ParentRef? Parent, + AttributeList Attributes, + IReadOnlyList TickFunctions, + IReadOnlyList Methods, + IReadOnlyList Fields, + IReadOnlyList Signals, + string SourceFile) +{ + public string QualifiedName => Strings.Qualify(Namespace, Name); + + public bool IsInterface => Attributes.Has("Interface"); +} diff --git a/tools/reflection_generator/Options.cs b/tools/reflection_generator/Options.cs new file mode 100644 index 000000000..81452c5de --- /dev/null +++ b/tools/reflection_generator/Options.cs @@ -0,0 +1,61 @@ +namespace ReflectionGenerator; + +internal sealed class Options +{ + public const string Usage = """ + usage: reflection_generator --database --output --input ... [options] + + --database json metadata output + --output where generated c++ is written + --input folder searched for headers, repeatable + --include-root headers are included relative to this folder + --register-fn registration function name, default registerEngineTypes + --split-typeinfo emit type_info into one cpp per node + --attribute attribute added to every node, repeatable + --lua-stubs lua types for the reflected nodes + --event-lua-stubs lua types for the events + """; + + public string Database { get; private set; } = ""; + public string Output { get; private set; } = ""; + public List Inputs { get; } = []; + public string? IncludeRoot { get; private set; } + public string RegisterFn { get; private set; } = "registerEngineTypes"; + public bool SplitTypeInfo { get; private set; } + public List Attributes { get; } = []; + public string? LuaStubs { get; private set; } + public string? EventLuaStubs { get; private set; } + + public static Options Parse(IReadOnlyList args) + { + var options = new Options(); + for (var i = 0; i < args.Count; i++) { + var (flag, inlineValue) = SplitFlag(args[i]); + + string Value() => inlineValue ?? (++i < args.Count ? args[i] : throw new GeneratorException($"{flag} needs a value")); + + switch (flag) { + case "--database": options.Database = Value(); break; + case "--output": options.Output = Value(); break; + case "--input": options.Inputs.Add(Value()); break; + case "--include-root": options.IncludeRoot = Value(); break; + case "--register-fn": options.RegisterFn = Value(); break; + case "--split-typeinfo": options.SplitTypeInfo = true; break; + case "--attribute": options.Attributes.Add(Value()); break; + case "--lua-stubs": options.LuaStubs = Value(); break; + case "--event-lua-stubs": options.EventLuaStubs = Value(); break; + default: throw new GeneratorException($"unknown argument '{args[i]}'\n{Usage}"); + } + } + + if (options.Database.Length == 0) throw new GeneratorException($"--database is required\n{Usage}"); + if (options.Output.Length == 0) throw new GeneratorException($"--output is required\n{Usage}"); + return options; + } + + private static (string Flag, string? Value) SplitFlag(string arg) + { + var eq = arg.IndexOf('='); + return arg.StartsWith("--", StringComparison.Ordinal) && eq > 0 ? (arg[..eq], arg[(eq + 1)..]) : (arg, null); + } +} diff --git a/tools/reflection_generator/Output/CppOutput.cs b/tools/reflection_generator/Output/CppOutput.cs new file mode 100644 index 000000000..cff494702 --- /dev/null +++ b/tools/reflection_generator/Output/CppOutput.cs @@ -0,0 +1,24 @@ +using ReflectionGenerator.Model; + +namespace ReflectionGenerator.Output; + +internal sealed class CppOutput(Templates templates, string outputDir, string registerFn, bool splitTypeInfo) +{ + public void Write(IEnumerable nodes, IEnumerable events) + { + var views = nodes.Select(n => NodeView.From(n, splitTypeInfo)).ToList(); + + foreach (var node in views) { + Emit($"{node.Slug}.generated.hpp", templates.Render("node.generated.hpp.scriban", "node", node)); + if (splitTypeInfo) { + Emit($"{node.Slug}.type_info.cpp", templates.Render("node.type_info.cpp.scriban", "node", node)); + } + } + + var eventViews = events.Where(e => e.Supported).Select(EventView.From).ToList(); + var registry = new RegistryView(views, eventViews, registerFn, splitTypeInfo); + Emit("reflect.generated.cpp", templates.Render("reflect.generated.cpp.scriban", "registry", registry)); + } + + private void Emit(string fileName, string content) => OutputFile.WriteIfChanged(Path.Combine(outputDir, fileName), content); +} diff --git a/tools/reflection_generator/Output/CppText.cs b/tools/reflection_generator/Output/CppText.cs new file mode 100644 index 000000000..076d6b46d --- /dev/null +++ b/tools/reflection_generator/Output/CppText.cs @@ -0,0 +1,20 @@ +using ReflectionGenerator.Model; + +namespace ReflectionGenerator.Output; + +internal static class CppText +{ + public static string Attributes(AttributeList attributes) + { + var entries = attributes.ByName().Select(a => "{\"" + a.Key + "\", {" + string.Join(", ", a.Value.Select(v => "\"" + v + "\"")) + "}}"); + return "{{" + string.Join(", ", entries) + "}}"; + } + + public static string TypeIds(IEnumerable types) => + "{{" + string.Join(", ", types.Select(t => $"&typeid(std::decay_t<{t}>)")) + "}}"; + + public static string DefaultValue(string? value) => + value is null ? "std::nullopt" : $"std::optional{{\"{Escape(value)}\"}}"; + + private static string Escape(string text) => text.Replace("\\", "\\\\").Replace("\"", "\\\""); +} diff --git a/tools/reflection_generator/Output/CppViews.cs b/tools/reflection_generator/Output/CppViews.cs new file mode 100644 index 000000000..0a6ccc276 --- /dev/null +++ b/tools/reflection_generator/Output/CppViews.cs @@ -0,0 +1,175 @@ +using ReflectionGenerator.Analysis; +using ReflectionGenerator.Model; +using ReflectionGenerator.Rules; + +namespace ReflectionGenerator.Output; + +// templates only lay text out so every decision is made here + +internal sealed record FieldView(int Index, string Name, string TypeName, string Kind, bool IsArray, string Accessor, string AttributesInit) +{ + public static FieldView From(Field field, int index) + { + var isAsset = field.TypeName.Contains("Handle<"); + var isEnum = field.Attributes.Has("Enum") && !field.IsArray; + var accessor = (isAsset, isEnum, field.IsArray) switch { + (true, _, true) => "AssetArrayFieldAccess", + (true, _, false) => "AssetFieldAccess", + (false, true, _) => "EnumFieldAccess", + _ => "FieldAccess", + }; + return new FieldView(index, field.Name, field.TypeName, field.Kind.Name(), field.IsArray, accessor, CppText.Attributes(field.Attributes)); + } +} + +internal sealed record SubgroupView(string Name, string Slug, IReadOnlyList Fields); + +internal sealed record GroupView(string Name, string Slug, IReadOnlyList Fields, IReadOnlyList Subgroups); + +internal sealed record TickFunctionView(string Flag, string Method); + +internal sealed record SignalView(string Name, string TypeName, string TypeIdsInit, string AttributesInit); + +internal sealed record ParameterView(int Index, string Name, string Type, string ArgName, string DefaultInit, string DynamicValue) +{ + public static ParameterView From(Parameter parameter, int index) + { + var cast = DynamicCast(parameter.Type, index); + var value = parameter.Default is null + ? cast + : $"((args.size() > {index} && args[{index}].has_value()) ? static_cast>({cast}) : static_cast>({parameter.Default}))"; + return new ParameterView(index, parameter.Name, parameter.Type, $"a{index}", CppText.DefaultValue(parameter.Default), value); + } + + // arguments arrive from lua as std::any so every parameter kind needs its own way back to a c++ value + private static string DynamicCast(string type, int index) + { + if (type.Contains("Box<")) { + var node = type.Replace("toast::Box<", "").Replace("Box<", "").Replace("const ", "").Replace("&", "").Replace(">", "").Trim(); + return $"std::any_cast>(args[{index}]).as<{node}>()"; + } + if (type.Contains("Handle<")) { + return $"assets::load::asset_type>(std::any_cast(args[{index}]))"; + } + return $"std::any_cast>(args[{index}])"; + } +} + +internal sealed record MethodView( + string Name, + string ReturnType, + bool ReturnsVoid, + string PointerType, + string InvokerParameters, + string ArgumentNames, + string DynamicArguments, + string AttributesInit, + IReadOnlyList Parameters) +{ + public static MethodView From(Method method, string qualifiedClassName) + { + var parameters = method.Parameters.Select(ParameterView.From).ToList(); + var types = string.Join(", ", parameters.Select(p => p.Type)); + var constSuffix = method.IsConst ? " const" : ""; + + return new MethodView( + method.Name, + method.ReturnType, + method.ReturnType == "void", + $"{method.ReturnType} ({qualifiedClassName}::*)({types}){constSuffix}", + string.Concat(parameters.Select(p => $", std::decay_t<{p.Type}> {p.ArgName}")), + string.Join(", ", parameters.Select(p => p.ArgName)), + string.Join(", ", parameters.Select(p => p.DynamicValue)), + CppText.Attributes(method.Attributes), + parameters); + } +} + +internal sealed record NodeView( + string Name, + string Slug, + string QualifiedName, + string? ParentQualifiedName, + string? ParentSlug, + string SourceFile, + bool IsInterface, + bool HasAssetHandle, + bool SplitTypeInfo, + IReadOnlyList AllFields, + IReadOnlyList GlobalFields, + IReadOnlyList Groups, + IReadOnlyList TickFunctions, + string TickList, + IReadOnlyList Methods, + IReadOnlyList Signals) +{ + public static NodeView From(NodeType node, bool splitTypeInfo) + { + var qualified = node.QualifiedName; + var allFields = new List(); + + FieldView Add(Field field) + { + var view = FieldView.From(field, allFields.Count); + allFields.Add(view); + return view; + } + + // the order fields are added in is the index they get in the generated array + var layout = FieldLayout.From(node.Fields); + var global = layout.GlobalFields.Select(Add).ToList(); + var groups = layout.Groups.Select(group => new GroupView( + group.Name, + GroupSlug(group.Name), + group.Fields.Select(Add).ToList(), + group.Subgroups.Select(sub => new SubgroupView(sub.Name, GroupSlug(sub.Name), sub.Fields.Select(Add).ToList())).ToList() + )).ToList(); + + var tickFunctions = Rules.TickFunctions.All + .Where(t => node.TickFunctions.Contains(t.Method)) + .Select(t => new TickFunctionView(t.Flag, t.Method)) + .ToList(); + + var hasAssetHandle = node.Fields.Any(f => f.TypeName.Contains("Handle<")) + || node.Methods.Any(m => m.Parameters.Any(p => p.Type.Contains("Handle<"))); + + return new NodeView( + node.Name, + node.Name.ToLowerInvariant(), + qualified, + node.Parent is { } parent ? Strings.Qualify(parent.Namespace, parent.Name) : null, + node.Parent?.Name.ToLowerInvariant(), + node.SourceFile, + node.IsInterface, + hasAssetHandle, + splitTypeInfo, + allFields, + global, + groups, + tickFunctions, + tickFunctions.Count == 0 ? "TickFunctionList::none" : string.Join(" | ", tickFunctions.Select(t => $"TickFunctionList::{t.Flag}")), + node.Methods.Select(m => MethodView.From(m, qualified)).ToList(), + node.Signals.Select(s => new SignalView( + s.Name, + s.TypeName, + CppText.TypeIds(s.Arguments), + CppText.Attributes(s.Attributes))).ToList()); + } + + // group names become part of c++ identifiers + private static string GroupSlug(string name) => name.ToLowerInvariant().Replace(' ', '_'); +} + +internal sealed record EventFieldView(string Name, string TypeName); + +internal sealed record EventView(string Name, string QualifiedName, string SourceFile, bool Sendable, IReadOnlyList Fields) +{ + public static EventView From(EventType e) => new( + e.Name, + e.QualifiedName, + e.SourceFile, + e.Sendable, + e.Fields.Select(f => new EventFieldView(f.Name, f.TypeName)).ToList()); +} + +internal sealed record RegistryView(IReadOnlyList Nodes, IReadOnlyList Events, string RegisterFn, bool SplitTypeInfo); diff --git a/tools/reflection_generator/Output/Database.cs b/tools/reflection_generator/Output/Database.cs new file mode 100644 index 000000000..f5ad6b5d6 --- /dev/null +++ b/tools/reflection_generator/Output/Database.cs @@ -0,0 +1,145 @@ +using System.Text.Encodings.Web; +using System.Text.Json; +using System.Text.Json.Serialization; +using ReflectionGenerator.Analysis; +using ReflectionGenerator.Model; +using ReflectionGenerator.Rules; + +namespace ReflectionGenerator.Output; + +// keys must stay in step with editor/Engine/ReflectionDatabase.cs +internal static class Database +{ + private static readonly JsonSerializerOptions JsonOptions = new() { + WriteIndented = true, + PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower, + Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping, + }; + + public static string Serialize(IEnumerable nodes, IEnumerable events) => + ToJson(new DatabaseDto(nodes.Select(NodeDto.From).ToList(), events.Select(EventDto.From).ToList())); + + public static string SerializeNodes(IEnumerable nodes) => + ToJson(nodes.Select(NodeDto.From).ToList()); + + private static string ToJson(object value) => JsonSerializer.Serialize(value, JsonOptions).Replace("\r\n", "\n"); + + private sealed record DatabaseDto(List Nodes, List Events); + + private sealed record ParentDto(string Name, string? Namespace); + + private sealed record AttributeDto(string Name, List Args); + + private sealed record ParameterDto(string Name, string Type, string? Default); + + private sealed record FieldDto( + string Name, + [property: JsonPropertyName("typename")] string TypeName, + string FieldType, + bool IsArray, + SortedDictionary Attributes, + string? Default) + { + public static FieldDto From(Field f) => + new(f.Name, f.TypeName, f.Kind.Name(), f.IsArray, f.Attributes.ByName(), f.Default); + } + + private sealed record MethodDto( + string Name, + string ReturnType, + List Parameters, + SortedDictionary Attributes, + bool IsConst) + { + public static MethodDto From(Method m) => new( + m.Name, + m.ReturnType, + m.Parameters.Select(p => new ParameterDto(p.Name, p.Type, p.Default)).ToList(), + m.Attributes.ByName(), + m.IsConst); + } + + private sealed record SignalDto( + string Name, + [property: JsonPropertyName("typename")] string TypeName, + List Arguments, + List AttrsList, + SortedDictionary Attributes) + { + public static SignalDto From(Signal s) => new( + s.Name, + s.TypeName, + s.Arguments.ToList(), + s.Attributes.Select(a => new AttributeDto(a.Name, a.Args.ToList())).ToList(), + s.Attributes.ByName()); + } + + private sealed record SubgroupDto(string Name, List Fields); + + private sealed record GroupDto(string Name, List Subgroups, List Fields); + + private sealed record NodeDto( + string Name, + string? Namespace, + ParentDto? Parent, + SortedDictionary Attributes, + List Functions, + List Methods, + List Fields, + List Signals, + string SourceFile, + List Groups, + List GlobalFields, + Dictionary TickFunctions, + bool IsInterface) + { + public static NodeDto From(NodeType node) + { + var layout = FieldLayout.From(node.Fields); + return new NodeDto( + node.Name, + node.Namespace, + node.Parent is { } p ? new ParentDto(p.Name, p.Namespace) : null, + node.Attributes.ByName(), + node.TickFunctions.ToList(), + node.Methods.Select(MethodDto.From).ToList(), + node.Fields.Select(FieldDto.From).ToList(), + node.Signals.Select(SignalDto.From).ToList(), + node.SourceFile, + layout.Groups.Select(g => new GroupDto( + g.Name, + g.Subgroups.Select(s => new SubgroupDto(s.Name, s.Fields.Select(FieldDto.From).ToList())).ToList(), + g.Fields.Select(FieldDto.From).ToList())).ToList(), + layout.GlobalFields.Select(FieldDto.From).ToList(), + Rules.TickFunctions.All.ToDictionary(t => t.Flag, t => node.TickFunctions.Contains(t.Method)), + node.IsInterface); + } + } + + private sealed record EventFieldDto( + string Name, + [property: JsonPropertyName("typename")] string TypeName, + string? LuaType, + bool Readable); + + private sealed record EventDto( + string Name, + string? Namespace, + List Fields, + string SourceFile, + bool ConstructorCompatible, + bool Supported, + bool Sendable, + string? SkipReason) + { + public static EventDto From(EventType e) => new( + e.Name, + e.Namespace, + e.Fields.Select(f => new EventFieldDto(f.Name, f.TypeName, f.LuaType, f.Readable)).ToList(), + e.SourceFile, + e.ConstructorCompatible, + e.Supported, + e.Sendable, + e.SkipReason); + } +} diff --git a/tools/reflection_generator/Output/LuaOutput.cs b/tools/reflection_generator/Output/LuaOutput.cs new file mode 100644 index 000000000..8c03bd354 --- /dev/null +++ b/tools/reflection_generator/Output/LuaOutput.cs @@ -0,0 +1,36 @@ +using ReflectionGenerator.Analysis; +using ReflectionGenerator.Model; +using ReflectionGenerator.Rules; + +namespace ReflectionGenerator.Output; + +internal sealed record LuaMember(string Name, string LuaType); + +internal sealed record LuaNodeView(string Name, string Inheritance, IReadOnlyList Fields, IReadOnlyList Methods, IReadOnlyList Signals); + +internal sealed record LuaEventView(string Name, bool Sendable, IReadOnlyList Fields); + +internal static class LuaOutput +{ + public static string NodeStubs(Templates templates, IEnumerable nodes) => + templates.Render("types.d.lua.scriban", "nodes", nodes.Select(NodeStub).ToList()); + + public static string EventStubs(Templates templates, IEnumerable events) => + templates.Render("events.d.lua.scriban", "events", events.Where(e => e.Supported).Select(EventStub).ToList()); + + private static LuaNodeView NodeStub(NodeType node) => new( + node.Name, + node.Parent is { } parent ? $" : {parent.Name.Bare()}" : "", + // hidden fields are not in the inspector and would shadow builtins like uid() and name() + FieldLayout.From(node.Fields).InOrder + .Where(f => !f.Attributes.Has("Hidden")) + .Select(f => new LuaMember(f.Name.WithoutPrefix("m_"), LuaTypes.ForField(f))) + .ToList(), + node.Methods.Select(m => new LuaMember(m.Name, LuaTypes.ForMethod(node.Name, m))).ToList(), + node.Signals.Select(s => new LuaMember(s.Name, LuaTypes.ForSignal(s))).ToList()); + + private static LuaEventView EventStub(EventType e) => new( + e.Name, + e.Sendable, + e.Fields.Select(f => new LuaMember(f.Name, f.LuaType ?? "any")).ToList()); +} diff --git a/tools/reflection_generator/Output/OutputFile.cs b/tools/reflection_generator/Output/OutputFile.cs new file mode 100644 index 000000000..16950723a --- /dev/null +++ b/tools/reflection_generator/Output/OutputFile.cs @@ -0,0 +1,21 @@ +using System.Text; + +namespace ReflectionGenerator.Output; + +internal static class OutputFile +{ + // identical content keeps its timestamp so nothing downstream rebuilds + public static void WriteIfChanged(string path, string content) + { + var bytes = new UTF8Encoding(false).GetBytes(content); + try { + if (File.Exists(path) && File.ReadAllBytes(path).AsSpan().SequenceEqual(bytes)) return; + + var directory = Path.GetDirectoryName(Path.GetFullPath(path)); + if (directory is not null) Directory.CreateDirectory(directory); + File.WriteAllBytes(path, bytes); + } catch (Exception e) when (e is IOException or UnauthorizedAccessException) { + throw new GeneratorException($"cannot write '{path}': {e.Message}"); + } + } +} diff --git a/tools/reflection_generator/Output/Templates.cs b/tools/reflection_generator/Output/Templates.cs new file mode 100644 index 000000000..faab3c61f --- /dev/null +++ b/tools/reflection_generator/Output/Templates.cs @@ -0,0 +1,58 @@ +using System.Reflection; +using Scriban; +using Scriban.Parsing; +using Scriban.Runtime; +using Scriban.Syntax; + +namespace ReflectionGenerator.Output; + +internal sealed class Templates +{ + private readonly Dictionary m_parsed = []; + + public string Render(string file, string variable, object model) + { + var context = new TemplateContext { + TemplateLoader = new EmbeddedLoader(), + // a typo in a template must fail loudly instead of rendering nothing + StrictVariables = true, + EnableRelaxedMemberAccess = false, + }; + context.PushGlobal(new ScriptObject { [variable] = model }); + + try { + return Parse(file).Render(context).Replace("\r\n", "\n"); + } catch (ScriptRuntimeException e) { + throw new GeneratorException($"template {file}: {e.Message}"); + } + } + + private Template Parse(string file) + { + if (m_parsed.TryGetValue(file, out var cached)) return cached; + + var template = Template.Parse(EmbeddedLoader.Read(file), file); + if (template.HasErrors) { + throw new GeneratorException($"template {file}: {string.Join("; ", template.Messages)}"); + } + return m_parsed[file] = template; + } + + private sealed class EmbeddedLoader : ITemplateLoader + { + public static string Read(string name) + { + using var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(name) + ?? throw new GeneratorException($"template '{name}' is not embedded"); + using var reader = new StreamReader(stream); + return reader.ReadToEnd().Replace("\r\n", "\n"); + } + + public string GetPath(TemplateContext context, SourceSpan callerSpan, string templateName) => templateName; + + public string Load(TemplateContext context, SourceSpan callerSpan, string templatePath) => Read(templatePath); + + public ValueTask LoadAsync(TemplateContext context, SourceSpan callerSpan, string templatePath) => + new((string?)Read(templatePath)); + } +} diff --git a/tools/reflection_generator/templates/events.d.lua.jinja2 b/tools/reflection_generator/Output/Templates/events.d.lua.scriban similarity index 90% rename from tools/reflection_generator/templates/events.d.lua.jinja2 rename to tools/reflection_generator/Output/Templates/events.d.lua.scriban index 54d6127ca..144081318 100644 --- a/tools/reflection_generator/templates/events.d.lua.jinja2 +++ b/tools/reflection_generator/Output/Templates/events.d.lua.scriban @@ -47,18 +47,18 @@ function event.send(descriptor, payload) end ---@field contacts ContactPoint[] ---@class EventsTable -{% for event in events %} +{{ for event in events ~}} ---@field {{ event.name }} EventDescriptor<{{ event.name }}> -{% endfor %} +{{ end ~}} Events = {} -{% for event in events %} -{% if not event.sendable %} +{{ for event in events ~}} +{{ if !event.sendable ~}} ---Receive only: can only be sent on c++ -{% endif %} +{{ end ~}} ---@class {{ event.name }} -{% for field in event.fields %} +{{ for field in event.fields ~}} ---@field {{ field.name }} {{ field.lua_type }} -{% endfor %} +{{ end ~}} -{% endfor %} +{{ end ~}} diff --git a/tools/reflection_generator/Output/Templates/node.generated.hpp.scriban b/tools/reflection_generator/Output/Templates/node.generated.hpp.scriban new file mode 100644 index 000000000..35cad5754 --- /dev/null +++ b/tools/reflection_generator/Output/Templates/node.generated.hpp.scriban @@ -0,0 +1,171 @@ +// ============================================================ +// AUTO-GENERATED FILE - DO NOT MODIFY DIRECTLY +// Changes will not persist +// ============================================================ + +#pragma once +#include +#include +#include +#include +{{ if node.has_asset_handle ~}} +#include +{{ end ~}} +{{ if node.parent_slug != null ~}} +#include "{{ node.parent_slug }}.generated.hpp" +{{ end ~}} +#include <{{ node.source_file }}> + +namespace toast { +namespace _detail { + +{{ for field in node.all_fields ~}} + struct {{ node.slug }}_{{ field.name }}_tag { using type = {{ field.type_name }} {{ node.qualified_name }}::*; }; + template struct Robber<{{ node.slug }}_{{ field.name }}_tag, &{{ node.qualified_name }}::{{ field.name }}>; +{{ end ~}} +{{ for tick in node.tick_functions ~}} + + struct {{ node.slug }}_{{ tick.flag }}_tag { using type = void ({{ node.qualified_name }}::*)(); }; + template struct Robber<{{ node.slug }}_{{ tick.flag }}_tag, &{{ node.qualified_name }}::{{ tick.method }}>; + + inline void {{ node.slug }}_{{ tick.flag }}(void* obj) { (static_cast<{{ node.qualified_name }}*>(obj)->*Accessor<{{ node.slug }}_{{ tick.flag }}_tag>::member)(); } +{{ end ~}} +{{ for method in node.methods ~}} + + struct {{ node.slug }}_method_{{ method.name }}_tag { using type = {{ method.pointer_type }}; }; + template struct Robber<{{ node.slug }}_method_{{ method.name }}_tag, static_cast<{{ method.pointer_type }}>(&{{ node.qualified_name }}::{{ method.name }})>; + + inline auto {{ node.slug }}_method_{{ method.name }}(void* obj{{ method.invoker_parameters }}) { + return (static_cast<{{ node.qualified_name }}*>(obj)->*Accessor<{{ node.slug }}_method_{{ method.name }}_tag>::member)({{ method.argument_names }}); + } + + inline std::any {{ node.slug }}_method_{{ method.name }}_dyn(void* obj, std::span args) { + auto* self = static_cast<{{ node.qualified_name }}*>(obj); +{{ if method.returns_void ~}} + (self->*Accessor<{{ node.slug }}_method_{{ method.name }}_tag>::member)({{ method.dynamic_arguments }}); + return std::any{}; +{{ else ~}} + return std::any{ (self->*Accessor<{{ node.slug }}_method_{{ method.name }}_tag>::member)({{ method.dynamic_arguments }}) }; +{{ end ~}} + } +{{ end ~}} +{{ if !node.is_interface ~}} + + inline {{ node.qualified_name }}* {{ node.slug }}_construct() { return new {{ node.qualified_name }}(); } + inline void {{ node.slug }}_delete({{ node.qualified_name }}* obj) { delete obj; } +{{ end ~}} +} + +template<> +struct Reflect<{{ node.qualified_name }}> { + static constexpr std::string_view name = "{{ node.qualified_name }}"; + + inline static const std::array _all_field_info = { { +{{ for field in node.all_fields ~}} + { + .name = "{{ field.name }}", + .type = "{{ field.type_name }}", + .value_type = FieldType::{{ field.kind }}, + .attributes = {{ field.attributes_init }}, + .is_array = {{ field.is_array }}, + .get = &{{ field.accessor }}<{{ node.qualified_name }}, {{ field.type_name }}, _detail::{{ node.slug }}_{{ field.name }}_tag>::get, + .set = &{{ field.accessor }}<{{ node.qualified_name }}, {{ field.type_name }}, _detail::{{ node.slug }}_{{ field.name }}_tag>::set, + }, +{{ end ~}} + } }; + + inline static const std::array signal_info = { { +{{ for signal in node.signals ~}} + { + .name = "{{ signal.name }}", + .type = "{{ signal.type_name }}", + .args = {{ signal.type_ids_init }}, + .attributes = {{ signal.attributes_init }}, + .get = {{ signal.type_name }}::get<{{ node.qualified_name }}, &{{ node.qualified_name }}::{{ signal.name }}>, + .connect = {{ signal.type_name }}::connect<{{ node.qualified_name }}, &{{ node.qualified_name }}::{{ signal.name }}>, + .disconnect = {{ signal.type_name }}::disconnect<{{ node.qualified_name }}, &{{ node.qualified_name }}::{{ signal.name }}>, + .clear = {{ signal.type_name }}::clear<{{ node.qualified_name }}, &{{ node.qualified_name }}::{{ signal.name }}>, + .fire = {{ signal.type_name }}::fire<{{ node.qualified_name }}, &{{ node.qualified_name }}::{{ signal.name }}>, + }, +{{ end ~}} + } }; + + inline static const std::array field_info = { { +{{ for field in node.global_fields ~}} + &_all_field_info[{{ field.index }}], +{{ end ~}} + } }; +{{ for group in node.groups ~}} + + inline static const std::array {{ group.slug }}_group_fields = { { +{{ for field in group.fields ~}} + &_all_field_info[{{ field.index }}], +{{ end ~}} + } }; +{{ for sub in group.subgroups ~}} + inline static const std::array {{ group.slug }}_{{ sub.slug }}_subgroup_fields = { { +{{ for field in sub.fields ~}} + &_all_field_info[{{ field.index }}], +{{ end ~}} + } }; + inline static const SubgroupInfo {{ group.slug }}_{{ sub.slug }}_subgroup = { + .name = "{{ sub.name }}", .fields = {{ group.slug }}_{{ sub.slug }}_subgroup_fields, + }; +{{ end ~}} + inline static const std::array {{ group.slug }}_subgroups = { { +{{ for sub in group.subgroups ~}} + {{ group.slug }}_{{ sub.slug }}_subgroup, +{{ end ~}} + } }; + inline static const GroupInfo {{ group.slug }}_group = { + .name = "{{ group.name }}", + .fields = {{ group.slug }}_group_fields, + .subgroups = {{ group.slug }}_subgroups, + }; +{{ end ~}} + + inline static const std::array group_info = { { +{{ for group in node.groups ~}} + {{ group.slug }}_group, +{{ end ~}} + } }; +{{ for method in node.methods ~}} + + inline static const std::array {{ method.name }}_param_info = { { +{{ for parameter in method.parameters ~}} + { .name = "{{ parameter.name }}", .type = "{{ parameter.type }}", .default_value = {{ parameter.default_init }}, .type_id = &typeid(std::decay_t<{{ parameter.type }}>) }, +{{ end ~}} + } }; +{{ end ~}} + + inline static const std::array _method_info = { { +{{ for method in node.methods ~}} + { + .name = "{{ method.name }}", + .return_type = "{{ method.return_type }}", + .return_type_id = &typeid(std::decay_t<{{ method.return_type }}>), + .parameters = {{ method.name }}_param_info, + .attributes = {{ method.attributes_init }}, + .invoke = reinterpret_cast(&_detail::{{ node.slug }}_method_{{ method.name }}), + .invoke_dynamic = reinterpret_cast(&_detail::{{ node.slug }}_method_{{ method.name }}_dyn), + }, +{{ end ~}} + } }; + + static constexpr TickFunctions tick_functions = { + .list = {{ node.tick_list }}, +{{ for tick in node.tick_functions ~}} + .{{ tick.flag }} = &_detail::{{ node.slug }}_{{ tick.flag }}, +{{ end ~}} + }; + +{{ if node.split_type_info ~}} + TOAST_API static const toast::NodeInfo type_info; +{{ else ~}} + inline static const toast::NodeInfo type_info = { +{{ include 'node_info_fields.scriban' ~}} + }; +{{ end ~}} +}; + +} // namespace toast diff --git a/tools/reflection_generator/Output/Templates/node.type_info.cpp.scriban b/tools/reflection_generator/Output/Templates/node.type_info.cpp.scriban new file mode 100644 index 000000000..88107620c --- /dev/null +++ b/tools/reflection_generator/Output/Templates/node.type_info.cpp.scriban @@ -0,0 +1,21 @@ +// ============================================================ +// AUTO-GENERATED FILE - DO NOT MODIFY DIRECTLY +// Changes will not persist +// ============================================================ + +// clang-format off +#include "{{ node.slug }}.generated.hpp" +// clang-format on + +namespace toast { + +TOAST_API const toast::NodeInfo Reflect<{{ node.qualified_name }}>::type_info = { +{{ include 'node_info_fields.scriban' ~}} +}; + +template<> +TOAST_API auto NodeTypeInfo<{{ node.qualified_name }}>::get() noexcept -> const NodeInfo* { + return &Reflect<{{ node.qualified_name }}>::type_info; +} + +} // namespace toast diff --git a/tools/reflection_generator/Output/Templates/node_info_fields.scriban b/tools/reflection_generator/Output/Templates/node_info_fields.scriban new file mode 100644 index 000000000..6bcc474e5 --- /dev/null +++ b/tools/reflection_generator/Output/Templates/node_info_fields.scriban @@ -0,0 +1,10 @@ + .type = name, + .base_type = {{ if node.parent_qualified_name != null }}&Reflect<{{ node.parent_qualified_name }}>::type_info{{ else }}nullptr{{ end }}, + .signals = signal_info, + .all_fields = _all_field_info, + .fields = field_info, + .groups = group_info, + .methods = _method_info, + .functions = tick_functions, + .construct = {{ if node.is_interface }}nullptr{{ else }}reinterpret_cast(&_detail::{{ node.slug }}_construct){{ end }}, + .destroy = {{ if node.is_interface }}nullptr{{ else }}reinterpret_cast(&_detail::{{ node.slug }}_delete){{ end }}, diff --git a/tools/reflection_generator/Output/Templates/reflect.generated.cpp.scriban b/tools/reflection_generator/Output/Templates/reflect.generated.cpp.scriban new file mode 100644 index 000000000..8b615c82f --- /dev/null +++ b/tools/reflection_generator/Output/Templates/reflect.generated.cpp.scriban @@ -0,0 +1,46 @@ +// ============================================================ +// AUTO-GENERATED FILE - DO NOT MODIFY DIRECTLY +// Changes will not persist +// ============================================================ + +// clang-format off +{{ for node in registry.nodes ~}} +#include "{{ node.slug }}.generated.hpp" +{{ end ~}} +{{ for event in registry.events ~}} +#include <{{ event.source_file }}> +{{ end ~}} +#include +#include +#include +#include +#include +// clang-format on + +namespace toast { +template +auto nodeTypeInfo() noexcept -> const NodeInfo* { + return &Reflect::type_info; +} +{{ for node in registry.nodes ~}} +template {{ if registry.split_type_info }}TOAST_API {{ end }}auto nodeTypeInfo<{{ node.qualified_name }}>() noexcept -> const NodeInfo*; +{{ end ~}} + +void {{ registry.register_fn }}() { + static const std::array all_types = { { +{{ for node in registry.nodes ~}} + &Reflect<{{ node.qualified_name }}>::type_info, +{{ end ~}} + } }; + for (const auto* info : all_types) { + NodeRegistry::registerNode(info); + } +{{ for event in registry.events ~}} + scripting::registerLuaEvent<{{ event.qualified_name }}, {{ event.sendable }}>("{{ event.name }}"{{ for field in event.fields }}, + scripting::luaEventField<{{ event.qualified_name }}>("{{ field.name }}", "{{ field.type_name }}", + [](const {{ event.qualified_name }}& e) -> const auto& { return e.{{ field.name }}; }, + [](auto& e, auto&& v) { e.{{ field.name }} = std::forward(v); }){{ end }}); +{{ end ~}} + TOAST_INFO("Reflection", "Registered {} types ({{ registry.register_fn }})", all_types.size()); +} +} // namespace toast diff --git a/tools/reflection_generator/templates/types.d.lua.jinja2 b/tools/reflection_generator/Output/Templates/types.d.lua.scriban similarity index 63% rename from tools/reflection_generator/templates/types.d.lua.jinja2 rename to tools/reflection_generator/Output/Templates/types.d.lua.scriban index 0d313b7a3..0225d9742 100644 --- a/tools/reflection_generator/templates/types.d.lua.jinja2 +++ b/tools/reflection_generator/Output/Templates/types.d.lua.scriban @@ -3,19 +3,19 @@ -- Changes will not persist -- ============================================================ -{% for node in nodes %} +{{ for node in nodes ~}} ---@class {{ node.name }}{{ node.inheritance }} -{% for field in node.fields %} +{{ for field in node.fields ~}} ---@field {{ field.name }} {{ field.lua_type }} -{% endfor %} -{% for method in node.methods %} ----@field {{ method.name }} {{ method.signature }} -{% endfor %} -{% for signal in node.signals %} +{{ end ~}} +{{ for method in node.methods ~}} +---@field {{ method.name }} {{ method.lua_type }} +{{ end ~}} +{{ for signal in node.signals ~}} ---@field {{ signal.name }} {{ signal.lua_type }} -{% endfor %} +{{ end ~}} ---@type TypeMarker {{ node.name }} = nil -{% endfor %} +{{ end ~}} diff --git a/tools/reflection_generator/Parsing/AttributeReader.cs b/tools/reflection_generator/Parsing/AttributeReader.cs new file mode 100644 index 000000000..173a603ac --- /dev/null +++ b/tools/reflection_generator/Parsing/AttributeReader.cs @@ -0,0 +1,34 @@ +using ReflectionGenerator.Model; +using TreeSitter; + +namespace ReflectionGenerator.Parsing; + +internal static class AttributeReader +{ + public static AttributeList Read(Node declaration) + { + var attributes = new List(); + + foreach (var list in declaration.ChildrenOfKind("attribute_declaration")) { + foreach (var attribute in list.ChildrenOfKind("attribute")) { + var name = attribute.Field("name"); + if (name is null) continue; + + var args = name.NextNamedSibling is { } argumentList + ? argumentList.Children.Where(a => a.IsNamed).Select(a => Unquote(a.Str())).ToList() + : []; + attributes.Add(new CppAttribute(name.Str(), args)); + } + } + + return new AttributeList(attributes); + } + + // string literal nodes come with their quotes + private static string Unquote(string argument) + { + var text = argument.Trim(); + var quoted = text.Length >= 2 && text[0] == text[^1] && text[0] is '"' or '\''; + return quoted ? text[1..^1] : text; + } +} diff --git a/tools/reflection_generator/Parsing/EventParser.cs b/tools/reflection_generator/Parsing/EventParser.cs new file mode 100644 index 000000000..1388b9ead --- /dev/null +++ b/tools/reflection_generator/Parsing/EventParser.cs @@ -0,0 +1,135 @@ +using ReflectionGenerator.Model; +using ReflectionGenerator.Rules; +using TreeSitter; + +namespace ReflectionGenerator.Parsing; + +internal static class EventParser +{ + public static IReadOnlyList Parse(string source, string sourceFile) + { + using var tree = Syntax.Parse(source); + var root = tree.RootNode; + var enumNames = EnumNames(root); + + var events = new List(); + foreach (var node in root.Descendants().Where(n => n.Type is "class_specifier" or "struct_specifier")) { + var name = node.Field("name")?.Str(); + if (name is null || !InheritsEvent(node, name)) continue; + + var fields = ReadFields(node, enumNames); + var constructorCompatible = ConstructorMatches(node, name, fields); + var unsupported = fields.FirstOrDefault(f => f.LuaType is null); + var skipReason = unsupported is null ? null : $"field '{unsupported.Name}' has unsupported type '{unsupported.TypeName}'"; + + events.Add(new EventType( + name, + node.EnclosingNamespace(), + fields, + sourceFile, + constructorCompatible, + Supported: skipReason is null, + Sendable: skipReason is null && constructorCompatible && fields.All(f => f.Readable), + skipReason)); + } + return events; + } + + // matches Event and ns::Event but not Event + private static bool InheritsEvent(Node node, string name) + { + var needle = $"Event<{name}>"; + string[] accessWords = ["public", "protected", "private", "virtual"]; + + foreach (var clause in node.ChildrenOfKind("base_class_clause")) { + var bases = clause.Str().TrimStart().TrimStart(':').Split(','); + foreach (var baseClass in bases) { + var words = baseClass.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries).Where(w => !accessWords.Contains(w)); + var compact = string.Concat(words); + if (compact == needle || compact.EndsWith("::" + needle, StringComparison.Ordinal)) return true; + } + } + return false; + } + + private static List EnumNames(Node root) => root.DescendantsOfKind("enum_specifier") + .Where(e => e.Field("name") is { Type: "type_identifier" } && e.Field("body") is not null) + .Select(e => e.Field("name")!.Str()) + .ToList(); + + private static IReadOnlyList ReadFields(Node node, IReadOnlyCollection enumNames) + { + var body = node.Field("body"); + if (body is null) return []; + + var fields = new List(); + var isPublic = node.Type == "struct_specifier"; + + foreach (var member in body.NamedChildren) { + if (member.Type == "access_specifier") { + isPublic = member.Str().TrimStart().StartsWith("public", StringComparison.Ordinal); + continue; + } + if (!isPublic || member.Type != "field_declaration") continue; + + var type = member.Field("type"); + if (type is null || type.Type is "struct_specifier" or "class_specifier" or "enum_specifier") continue; + + var typeName = type.Str().Trim(); + if (typeName.Contains("Event<")) continue; + + foreach (var identifier in FieldIdentifiers(member)) { + var declared = typeName + IndirectionSuffix(identifier, member); + var lua = LuaTypes.ForEventField(declared, enumNames); + fields.Add(new EventField(identifier.Str(), declared, lua?.Lua, lua?.Readable ?? false)); + } + } + return fields; + } + + // int *a, &b declares different types from one type node + private static string IndirectionSuffix(Node identifier, Node declaration) + { + var suffix = ""; + for (var parent = identifier.Parent; parent is not null && parent.Id != declaration.Id; parent = parent.Parent) { + if (parent.Type == "pointer_declarator") suffix += "*"; + if (parent.Type == "reference_declarator") suffix += "&"; + } + return suffix; + } + + private static IEnumerable FieldIdentifiers(Node node) + { + if (node.Type == "field_identifier") { + yield return node; + yield break; + } + foreach (var child in node.NamedChildren) { + foreach (var identifier in FieldIdentifiers(child)) { + yield return identifier; + } + } + } + + // the lua side builds the event by calling this constructor with every field in order + private static bool ConstructorMatches(Node node, string name, IReadOnlyList fields) + { + if (fields.Count == 0) return true; + + var hasConstructor = false; + foreach (var declarator in node.DescendantsOfKind("function_declarator")) { + if (declarator.Field("declarator")?.Str().Trim() != name) continue; + + hasConstructor = true; + var parameters = ParameterReader.Read(declarator); + if (parameters.Count == 0) return true; + if (parameters.Count == fields.Count && parameters.Zip(fields).All(p => Normalized(p.First.Type) == Normalized(p.Second.TypeName))) { + return true; + } + } + return !hasConstructor; + } + + private static string Normalized(string type) => + type.Replace("const", "").Replace("&", "").WithoutWhitespace(); +} diff --git a/tools/reflection_generator/Parsing/ExportMacros.cs b/tools/reflection_generator/Parsing/ExportMacros.cs new file mode 100644 index 000000000..86dcbbba9 --- /dev/null +++ b/tools/reflection_generator/Parsing/ExportMacros.cs @@ -0,0 +1,10 @@ +namespace ReflectionGenerator.Parsing; + +internal static class ExportMacros +{ + // tree-sitter reads TOAST_API and declspec as identifiers and then loses the field that follows + public static string Strip(string source) => source + .Replace("TOAST_API ", "") + .Replace("__declspec(dllexport) ", "") + .Replace("__declspec(dllimport) ", ""); +} diff --git a/tools/reflection_generator/Parsing/HeaderFinder.cs b/tools/reflection_generator/Parsing/HeaderFinder.cs new file mode 100644 index 000000000..63afc1d13 --- /dev/null +++ b/tools/reflection_generator/Parsing/HeaderFinder.cs @@ -0,0 +1,33 @@ +namespace ReflectionGenerator.Parsing; + +internal static class HeaderFinder +{ + public static IReadOnlyList Find(IEnumerable inputDirs) + { + var found = new List(); + foreach (var dir in inputDirs) { + // sorted so the generated files do not shuffle between machines + var headers = Directory.EnumerateFiles(dir, "*.hpp", SearchOption.AllDirectories) + .Where(path => path.EndsWith(".hpp", StringComparison.Ordinal)) + .Order(StringComparer.Ordinal); + + foreach (var path in headers) { + if (ReadOrNull(path) is { } content && (content.Contains("ToastNode") || content.Contains("Event<"))) { + found.Add(path); + } + } + } + return found; + } + + private static string? ReadOrNull(string path) + { + try { + return File.ReadAllText(path); + } catch (IOException) { + return null; + } catch (UnauthorizedAccessException) { + return null; + } + } +} diff --git a/tools/reflection_generator/Parsing/NodeParser.cs b/tools/reflection_generator/Parsing/NodeParser.cs new file mode 100644 index 000000000..e88ca5bb0 --- /dev/null +++ b/tools/reflection_generator/Parsing/NodeParser.cs @@ -0,0 +1,163 @@ +using ReflectionGenerator.Model; +using ReflectionGenerator.Rules; +using TreeSitter; + +namespace ReflectionGenerator.Parsing; + +internal static class NodeParser +{ + public static IReadOnlyList Parse(string source, string sourceFile) + { + using var tree = Syntax.Parse(source); + return tree.RootNode.DescendantsOfKind("class_specifier") + .Select(cls => ReadClass(cls, sourceFile)) + .OfType() + .ToList(); + } + + private static NodeType? ReadClass(Node cls, string sourceFile) + { + var name = cls.Field("name")?.Str(); + if (name is null) return null; + + var attributes = AttributeReader.Read(cls); + if (!attributes.Has("ToastNode")) return null; + + return new NodeType( + name, + cls.EnclosingNamespace(), + ReadParent(cls), + attributes.Without("ToastNode"), + ReadTickFunctions(cls), + ReadMethods(cls), + ReadFields(cls), + ReadSignals(cls), + sourceFile); + } + + private static ParentRef? ReadParent(Node cls) + { + foreach (var clause in cls.ChildrenOfKind("base_class_clause")) { + foreach (var inner in clause.Children) { + if (inner.Type == "type_identifier") return new ParentRef(inner.Str(), null); + if (inner.Type != "qualified_identifier") continue; + + var full = inner.Str(); + var cut = full.LastIndexOf("::", StringComparison.Ordinal); + return cut < 0 ? new ParentRef(full, null) : new ParentRef(full[(cut + 2)..], full[..cut]); + } + } + return null; + } + + private static IReadOnlyList ReadTickFunctions(Node cls) + { + var found = new List(); + foreach (var identifier in cls.DescendantsOfKind("field_identifier")) { + var name = identifier.Str(); + if (identifier.Parent?.Type == "function_declarator" && TickFunctions.IsTickFunction(name) && !found.Contains(name)) { + found.Add(name); + } + } + return found; + } + + private static IReadOnlyList ReadFields(Node cls) + { + var fields = new List(); + foreach (var (declaration, identifier) in MemberDeclarations(cls)) { + var attributes = AttributeReader.Read(declaration); + if (!attributes.Has("Reflect")) continue; + + var typeName = TypeText(declaration); + if (typeName.Contains("Signal<")) continue; + + fields.Add(new Field( + identifier.Str(), + typeName, + FieldKinds.Infer(typeName), + typeName.Contains("vector<"), + attributes.Without("Reflect"), + declaration.Field("default_value")?.Str().Trim())); + } + return fields; + } + + private static IReadOnlyList ReadSignals(Node cls) + { + var signals = new List(); + foreach (var (declaration, identifier) in MemberDeclarations(cls)) { + var typeName = TypeText(declaration); + if (!typeName.Contains("Signal<")) continue; + + signals.Add(new Signal(identifier.Str(), typeName, TemplateArgs.Split(typeName), AttributeReader.Read(declaration))); + } + return signals; + } + + // nested struct definitions own their fields so they are skipped + private static IEnumerable<(Node Declaration, Node Identifier)> MemberDeclarations(Node cls) + { + foreach (var identifier in cls.DescendantsOfKind("field_identifier")) { + var declaration = identifier.Parent; + if (declaration?.Type != "field_declaration") continue; + if (declaration.Field("type")?.Type == "struct_specifier") continue; + yield return (declaration, identifier); + } + } + + private static string TypeText(Node declaration) => declaration.Field("type")?.Str().Trim() ?? ""; + + private static IReadOnlyList ReadMethods(Node cls) + { + var methods = new List(); + foreach (var declarator in cls.DescendantsOfKind("function_declarator")) { + var name = declarator.Field("declarator"); + if (name?.Type != "field_identifier") continue; + + var declaration = EnclosingDeclaration(declarator); + if (declaration is null) continue; + + var attributes = AttributeReader.Read(declaration); + if (!attributes.Has("Reflect")) continue; + if (methods.Any(m => m.Name == name.Str())) continue; + + methods.Add(new Method( + name.Str(), + ReturnType(declaration, declarator), + ParameterReader.Read(declarator), + IsConst(declarator), + attributes.Without("Reflect"))); + } + return methods; + } + + private static Node? EnclosingDeclaration(Node declarator) + { + for (var parent = declarator.Parent; parent is not null; parent = parent.Parent) { + if (parent.Type is "field_declaration" or "function_definition" or "declaration") return parent; + } + return null; + } + + private static string ReturnType(Node declaration, Node declarator) + { + var type = declaration.Field("type")?.Str().Trim() ?? ""; + + if (type == "auto") { + var trailing = declarator.ChildrenOfKind("trailing_return_type").FirstOrDefault()?.NamedChildren.FirstOrDefault(); + if (trailing is not null) return trailing.Str().Trim(); + } + + // pointers and references live on the declarator and not on the type + var suffix = ""; + for (var current = declaration.Field("declarator"); current is not null && current.Id != declarator.Id; current = current.Field("declarator")) { + if (current.Type == "pointer_declarator") suffix += "*"; + if (current.Type == "reference_declarator") suffix += "&"; + } + return type + suffix; + } + + private static bool IsConst(Node declarator) => + declarator.ChildrenOfKind("type_qualifier").Any(q => q.Str().Trim() == "const"); +} diff --git a/tools/reflection_generator/Parsing/ParameterReader.cs b/tools/reflection_generator/Parsing/ParameterReader.cs new file mode 100644 index 000000000..5153eba4d --- /dev/null +++ b/tools/reflection_generator/Parsing/ParameterReader.cs @@ -0,0 +1,38 @@ +using ReflectionGenerator.Model; +using TreeSitter; + +namespace ReflectionGenerator.Parsing; + +internal static class ParameterReader +{ + public static IReadOnlyList Read(Node functionDeclarator) + { + var list = functionDeclarator.Field("parameters"); + if (list is null) return []; + + var parameters = new List(); + foreach (var node in list.Children) { + if (node.Type is not ("parameter_declaration" or "optional_parameter_declaration")) continue; + + var defaultValue = node.Field("default_value"); + var name = node.Field("declarator") is { } declarator ? FirstIdentifier(declarator) : null; + + parameters.Add(name is not null + ? new Parameter(name.Str(), node.Slice(node.StartIndex, name.StartIndex).Trim(), defaultValue?.Str().Trim()) + : new Parameter("", UnnamedType(node, defaultValue), defaultValue?.Str().Trim())); + } + return parameters; + } + + private static string UnnamedType(Node parameter, Node? defaultValue) + { + var end = defaultValue?.StartIndex ?? parameter.EndIndex; + return parameter.Slice(parameter.StartIndex, end).Trim().TrimEnd('=').Trim(); + } + + private static Node? FirstIdentifier(Node node) + { + if (node.Type == "identifier") return node; + return node.Children.Select(FirstIdentifier).FirstOrDefault(found => found is not null); + } +} diff --git a/tools/reflection_generator/Parsing/Syntax.cs b/tools/reflection_generator/Parsing/Syntax.cs new file mode 100644 index 000000000..260a19d5c --- /dev/null +++ b/tools/reflection_generator/Parsing/Syntax.cs @@ -0,0 +1,47 @@ +using TreeSitter; + +namespace ReflectionGenerator.Parsing; + +// the only file that knows how tree-sitter is shaped +internal static class Syntax +{ + private static readonly Language Cpp = new("cpp"); + + public static Tree Parse(string source) + { + using var parser = new Parser(Cpp); + return parser.Parse(source) ?? throw new GeneratorException("tree-sitter could not parse the source"); + } + + public static string Str(this Node node) => node.Text ?? ""; + + public static Node? Field(this Node node, string name) => node.GetChildForField(name); + + public static IEnumerable Descendants(this Node node) + { + foreach (var child in node.Children) { + yield return child; + foreach (var inner in child.Descendants()) { + yield return inner; + } + } + } + + public static IEnumerable DescendantsOfKind(this Node node, string kind) => + node.Descendants().Where(n => n.Type == kind); + + public static IEnumerable ChildrenOfKind(this Node node, string kind) => + node.Children.Where(n => n.Type == kind); + + public static string Slice(this Node node, int start, int end) => node.Tree.Source[start..end]; + + public static string? EnclosingNamespace(this Node node) + { + for (var parent = node.Parent; parent is not null; parent = parent.Parent) { + if (parent.Type == "namespace_definition" && parent.Field("name") is { } name) { + return name.Str(); + } + } + return null; + } +} diff --git a/tools/reflection_generator/Parsing/TemplateArgs.cs b/tools/reflection_generator/Parsing/TemplateArgs.cs new file mode 100644 index 000000000..8a182b565 --- /dev/null +++ b/tools/reflection_generator/Parsing/TemplateArgs.cs @@ -0,0 +1,36 @@ +using System.Text; + +namespace ReflectionGenerator.Parsing; + +internal static class TemplateArgs +{ + // "Signal>" gives ["int", "Foo"] + public static IReadOnlyList Split(string typeName) + { + var start = typeName.IndexOf('<'); + var end = typeName.LastIndexOf('>'); + if (start < 0 || end < 0 || start >= end) return []; + + var args = new List(); + var current = new StringBuilder(); + var depth = 0; + + void Flush() + { + var text = current.ToString().Trim(); + if (text.Length > 0) args.Add(text); + current.Clear(); + } + + foreach (var c in typeName[(start + 1)..end]) { + switch (c) { + case '<': depth++; current.Append(c); break; + case '>': depth--; current.Append(c); break; + case ',' when depth == 0: Flush(); break; + default: current.Append(c); break; + } + } + Flush(); + return args; + } +} diff --git a/tools/reflection_generator/Pipeline.cs b/tools/reflection_generator/Pipeline.cs new file mode 100644 index 000000000..d9ee85d43 --- /dev/null +++ b/tools/reflection_generator/Pipeline.cs @@ -0,0 +1,112 @@ +using ReflectionGenerator.Analysis; +using ReflectionGenerator.Model; +using ReflectionGenerator.Output; +using ReflectionGenerator.Parsing; +using ReflectionGenerator.Rules; + +namespace ReflectionGenerator; + +internal sealed class Pipeline(Options options) +{ + public void Run() + { + CheckDirectories(); + + var headers = HeaderFinder.Find(options.Inputs); + if (headers.Count == 0) { + Warn("no [[ToastNode]] headers found in the given --input directories"); + } + + var (nodes, events) = ParseHeaders(headers); + WriteOrWarn(options.Database, Database.Serialize(nodes, events)); + + var ordered = InheritanceOrder.Sort(nodes); + var templates = new Templates(); + + new CppOutput(templates, options.Output, options.RegisterFn, options.SplitTypeInfo).Write(ordered, events); + + if (options.LuaStubs is { } luaStubs) { + WriteOrWarn(luaStubs, LuaOutput.NodeStubs(templates, ordered)); + } + if (options.EventLuaStubs is { } eventLuaStubs) { + WriteOrWarn(eventLuaStubs, LuaOutput.EventStubs(templates, events)); + } + + Console.WriteLine($"refgen: generated {ordered.Count} type(s) -> '{options.Output}' (fn: {options.RegisterFn})"); + } + + private void CheckDirectories() + { + foreach (var input in options.Inputs.Where(input => !Directory.Exists(input))) { + throw new GeneratorException($"--input '{input}' is not a directory"); + } + if (!Directory.Exists(options.Output)) { + throw new GeneratorException($"--output '{options.Output}' is not a directory"); + } + } + + private (List Nodes, List Events) ParseHeaders(IEnumerable headers) + { + var nodes = new List(); + var events = new List(); + + foreach (var header in headers) { + string source; + try { + source = File.ReadAllText(header); + } catch (Exception e) when (e is IOException or UnauthorizedAccessException) { + Console.Error.WriteLine($"error reading '{header}': {e.Message}"); + continue; + } + + var text = ExportMacros.Strip(source); + var includePath = IncludePath(header); + + foreach (var node in NodeParser.Parse(text, includePath)) { + Validation.Check(node); + nodes.Add(node with { Attributes = options.Attributes.Aggregate(node.Attributes, (list, name) => list.WithMarker(name)) }); + } + events.AddRange(EventParser.Parse(text, includePath)); + } + + return (nodes, DistinctEvents(events)); + } + + // the same event can be seen from several headers + private static List DistinctEvents(IEnumerable events) + { + var distinct = events + .OrderBy(e => e.QualifiedName, StringComparer.Ordinal) + .GroupBy(e => e.QualifiedName) + .Select(group => group.First()) + .ToList(); + + var skipped = distinct.Count(e => !e.Supported); + if (skipped > 0) { + Warn($"skipped {skipped} Lua events"); + } + return distinct; + } + + // the include has to be relative to the include root to work from anywhere + private string IncludePath(string file) + { + if (options.IncludeRoot is { } root) { + var relative = Path.GetRelativePath(root, file); + var outside = relative == ".." || relative.StartsWith(".." + Path.DirectorySeparatorChar, StringComparison.Ordinal); + if (!outside && !Path.IsPathRooted(relative)) return relative.Replace('\\', '/'); + } + return Path.GetFileName(file); + } + + private static void WriteOrWarn(string path, string content) + { + try { + OutputFile.WriteIfChanged(path, content); + } catch (GeneratorException e) { + Warn(e.Message); + } + } + + private static void Warn(string message) => Console.Error.WriteLine($"warning: {message}"); +} diff --git a/tools/reflection_generator/Program.cs b/tools/reflection_generator/Program.cs new file mode 100644 index 000000000..56c8f72bc --- /dev/null +++ b/tools/reflection_generator/Program.cs @@ -0,0 +1,24 @@ +using System.Text; + +namespace ReflectionGenerator; + +internal static class Program +{ + private static int Main(string[] args) + { + Console.OutputEncoding = new UTF8Encoding(false); + + if (args.Contains("--help") || args.Contains("-h")) { + Console.WriteLine(Options.Usage); + return 0; + } + + try { + new Pipeline(Options.Parse(args)).Run(); + return 0; + } catch (GeneratorException e) { + Console.Error.WriteLine($"error: {e.Message}"); + return 1; + } + } +} diff --git a/tools/reflection_generator/README.md b/tools/reflection_generator/README.md index 8453d95bd..a95e964ef 100644 --- a/tools/reflection_generator/README.md +++ b/tools/reflection_generator/README.md @@ -1,10 +1,80 @@ +# reflection_generator + +Reads the C++ headers, finds `[[ToastNode]]` classes and `Event` structs and writes everything the engine and the editor need to know about them. + ```bash -./refgen.exe --database ${CACHED_DIR} --output "engine/generated" --input "folder/to/search/1" +reflection_generator --database cache/game_reflect.json --output lib/generated --input lib/src ``` -`--database` is the path where the json metadata will be saved +| flag | | +| --- | --- | +| `--database ` | json metadata the editor reads | +| `--output ` | generated c++, has to exist | +| `--input ` | folder searched for `.hpp` files, repeat it for more folders | +| `--include-root ` | generated includes are written relative to this folder | +| `--register-fn ` | name of the registration function, default `registerEngineTypes` | +| `--split-typeinfo` | one `.type_info.cpp` per node instead of inline, keeps rebuilds small | +| `--attribute ` | attribute added to every node, repeat it for more | +| `--lua-stubs ` | lua types for the nodes | +| `--event-lua-stubs ` | lua types for the events | + +## What comes out + +- `.generated.hpp` one per node +- `.type_info.cpp` one per node, only with `--split-typeinfo` +- `reflect.generated.cpp` registers every node and event +- the json database and the two lua files + +Files whose content did not change are left alone so nothing rebuilds for no reason. + +## How it is laid out + +The run goes top to bottom in `Pipeline.cs`: find headers, parse, validate, order, write. + +| folder | what lives there | +| --- | --- | +| `Parsing` | tree-sitter in, plain records out. `Syntax.cs` is the only file that talks to tree-sitter | +| `Model` | the records the rest of the tool passes around | +| `Rules` | the decisions people tend to change, start here | +| `Analysis` | field groups and the order nodes are emitted in | +| `Output` | views, templates and writers | + +Templates never compute anything. A view in `Output/CppViews.cs` or `Output/LuaOutput.cs` holds every value a template prints, and a template that asks for something that does not exist fails the build. + +## Recipes + +**add a lifecycle function** +Add a line to `Rules/TickFunctions.cs`. Keep it in step with `TickFunctionList` in `reflect.hpp`. -`--output` is the path where the generated files will be stored +**add a field type** +Add the enum value in `Model/FieldKind.cs`, its name in the same file, then a case in `Rules/FieldKinds.cs`. Add the lua type in `Rules/LuaTypes.cs`. + +**change how a c++ type shows up in lua** +`Rules/LuaTypes.cs`. There is one function for fields, one for parameters and returns, one for events. + +**add a rule that rejects a header** +`Rules/Validation.cs`, throw a `GeneratorException`. + +**change the generated c++** +Edit the template in `Output/Templates`. If it needs a new value add it to the view first. The `NodeInfo` initializer is shared by the header and the cpp in `node_info_fields.scriban`. + +**add an output file** +Add a template and a view, render it from a writer in `Output` and call the writer from `Pipeline.cs`. + +**add a command line flag** +`Options.cs`. + +## Things to know + +- Control lines in templates end with `~}}` so the newline after them is dropped. +- 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 +``` -`--input` is the path where the ToastNodes are stored, the program will search for all -the `.hpp` files containing `[[ToastNode]]` +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/FieldKinds.cs b/tools/reflection_generator/Rules/FieldKinds.cs new file mode 100644 index 000000000..595840e6f --- /dev/null +++ b/tools/reflection_generator/Rules/FieldKinds.cs @@ -0,0 +1,38 @@ +using ReflectionGenerator.Model; +using ReflectionGenerator.Parsing; + +namespace ReflectionGenerator.Rules; + +internal static class FieldKinds +{ + public static FieldKind Infer(string typeName) + { + var trimmed = typeName.Trim(); + + // classify a vector by its element or save throws bad_any_cast on std::vector + var element = trimmed.Contains("vector<") + ? TemplateArgs.Split(trimmed).FirstOrDefault() ?? "" + : trimmed; + + var bare = element.Trim().TrimStartText("toast::").TrimStartText("std::").TrimStartText("glm::"); + + if (element.Contains("Handle<")) return FieldKind.Uid; + if (bare.StartsWith("Box<", StringComparison.Ordinal)) return FieldKind.Uid; + + return bare switch { + "bool" => FieldKind.Bool, + "int" or "int8_t" or "int16_t" or "int32_t" or "int64_t" + or "uint8_t" or "uint16_t" or "uint32_t" or "uint64_t" => FieldKind.Int, + "float" => FieldKind.Float, + "string" => FieldKind.String, + "double" => FieldKind.Double, + "UID" => FieldKind.Uid, + "vec2" => FieldKind.Vec2, + "vec3" => FieldKind.Vec3, + "vec4" => FieldKind.Vec4, + "quat" or "quaternion" => FieldKind.Quaternion, + // unknown types compile but the inspector widget will be wrong + _ => FieldKind.Int, + }; + } +} diff --git a/tools/reflection_generator/Rules/LuaTypes.cs b/tools/reflection_generator/Rules/LuaTypes.cs new file mode 100644 index 000000000..eb7cf11d8 --- /dev/null +++ b/tools/reflection_generator/Rules/LuaTypes.cs @@ -0,0 +1,130 @@ +using ReflectionGenerator.Model; + +namespace ReflectionGenerator.Rules; + +// every c++ to lua type decision lives here with one function per place a type shows up +internal static class LuaTypes +{ + public static string ForField(Field field) + { + var color = field.Attributes.Has("Color"); + var type = field.Kind switch { + FieldKind.Bool => "boolean", + FieldKind.Int => "integer", + FieldKind.Float or FieldKind.Double => "number", + FieldKind.String => "string", + FieldKind.Vec2 => "vec2", + FieldKind.Vec3 => color ? "color3" : "vec3", + FieldKind.Vec4 => color ? "color4" : "vec4", + FieldKind.Quaternion => "quat", + FieldKind.Uid => ForHandleOrBox(field.TypeName), + _ => "any", + }; + return field.IsArray ? type + "[]" : type; + } + + private static string ForHandleOrBox(string typeName) + { + var inner = typeName.TrimStartText("std::vector<").TrimEnd('>'); + if (inner.StartsWith("Box<", StringComparison.Ordinal)) { + return inner["Box<".Length..].TrimEnd('>').Bare(); + } + return inner.Contains("Handle<") ? "Asset" : "any"; + } + + // parameters, return values and signal arguments + public static string ForCppType(string cpp) + { + var type = cpp.Trim(); + + if (Unwrap(type, "std::optional<") is { } optional) return ForCppType(optional) + "|nil"; + if (Unwrap(type, "std::vector<") is { } vector) return ForCppType(vector) + "[]"; + + // the longer names go first because the match is a substring one + string[] knownNames = ["input::ActionEvent", "input::Action", "input::Bind", "input::KeyCode", "input::Device", + "input::ValueType", "input::ModifierKey", "input::InputKind", "voxel::WriteMode"]; + string[] luaNames = ["InputActionEvent", "InputAction", "InputBind", "InputKeyCode", "InputDeviceValue", + "InputValueTypeValue", "InputModifierValue", "InputKindValue", "VoxelWriteValue"]; + for (var i = 0; i < knownNames.Length; i++) { + if (type.Contains(knownNames[i])) return luaNames[i]; + } + + if (type.Contains("Box<")) { + var inner = type.Split("Box<").ElementAtOrDefault(1) ?? "Node"; + return inner.TrimEnd('>', '&', ' ').Bare(); + } + if (type.Contains("Handle<")) return "Asset"; + if (type.Contains("physics::RayHit")) return "RayHit"; + if (type.Contains("bool")) return "boolean"; + if (type.Contains("float") || type.Contains("double")) return "number"; + if (type.Contains("string")) return "string"; + if (type.Contains("vec4")) return "vec4"; + if (type.Contains("vec3")) return "vec3"; + if (type.Contains("vec2")) return "vec2"; + if (type.Contains("quat")) return "quat"; + if (type == "void") return "nil"; + if (type.Contains("int") || type.Contains("long") || type.Contains("short") || type == "char") return "integer"; + return "any"; + } + + private static string? Unwrap(string type, string prefix) => + type.StartsWith(prefix, StringComparison.Ordinal) && type.EndsWith('>') ? type[prefix.Length..^1] : null; + + public static string ForMethod(string className, Method method) + { + var parameters = new List { $"self: {className}" }; + foreach (var parameter in method.Parameters) { + var optional = parameter.Default is null ? "" : "?"; + parameters.Add($"{parameter.Name}{optional}: {ForCppType(parameter.Type)}"); + } + + var returns = ForCppType(method.ReturnType); + var signature = $"fun({string.Join(", ", parameters)})"; + return returns == "nil" ? signature : $"{signature}: {returns}"; + } + + // the lua side only has Signal0 to Signal4 + public static string ForSignal(Signal signal) + { + var arguments = signal.Arguments.Select(ForCppType).ToList(); + return arguments.Count is >= 1 and <= 4 + ? $"Signal{arguments.Count}<{string.Join(", ", arguments)}>" + : "Signal0"; + } + + // null means lua cannot see the type and readable false means lua cannot send it + public static (string Lua, bool Readable)? ForEventField(string cpp, IReadOnlyCollection enumNames) + { + var bare = cpp.WithoutWhitespace().TrimStartText("const").TrimStartText("std::").TrimStartText("glm::"); + + if (Unwrap(bare, "vector<") is { } element) { + 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); + } + if (enumNames.Contains(bare.Bare())) return ("integer", true); + + return bare switch { + "toast::Box" or "Box" or "toast::Box" or "Box" + or "toast::Node*" or "Node*" => ("Node", true), + "bool" => ("boolean", true), + "float" or "double" => ("number", true), + "char" or "short" or "int" or "long" or "longlong" or "unsigned" or "unsignedint" + or "unsignedlong" or "unsignedlonglong" or "int8_t" or "int16_t" or "int32_t" or "int64_t" + or "uint8_t" or "uint16_t" or "uint32_t" or "uint64_t" or "size_t" => ("integer", true), + "string" => ("string", true), + "vec2" or "ivec2" => ("vec2", true), + "vec3" or "ivec3" => ("vec3", true), + "vec4" or "ivec4" => ("vec4", true), + "quat" or "quaternion" => ("quat", true), + "toast::UID" or "UID" => ("UID", true), + "input::Device" => ("InputDeviceValue", true), + "input::ActionEvent" => ("InputActionEvent", true), + "input::Action&" or "input::Action" => ("InputAction", false), + "ContactEventData" or "event::ContactEventData" => ("ContactEventData", false), + "physics::BroadPhasePair" or "BroadPhasePair" => ("BroadPhasePair", false), + _ => null, + }; + } +} diff --git a/tools/reflection_generator/Rules/TickFunctions.cs b/tools/reflection_generator/Rules/TickFunctions.cs new file mode 100644 index 000000000..be2393ca2 --- /dev/null +++ b/tools/reflection_generator/Rules/TickFunctions.cs @@ -0,0 +1,26 @@ +namespace ReflectionGenerator.Rules; + +internal sealed record TickFunction(string Method, string Flag); + +internal static class TickFunctions +{ + // keep in step with TickFunctionList in reflect.hpp and this order is the generated order + public static readonly IReadOnlyList All = [ + new("load", "load"), + new("save", "save"), + new("editorTick", "editor_tick"), + new("init", "init"), + new("destroy", "destroy"), + new("begin", "begin"), + new("end", "end"), + new("onEnable", "on_enable"), + new("onDisable", "on_disable"), + new("earlyTick", "early_tick"), + new("tick", "tick"), + new("physicsTick", "physics_tick"), + new("postPhysics", "post_physics"), + new("lateTick", "late_tick"), + ]; + + public static bool IsTickFunction(string method) => All.Any(t => t.Method == method); +} diff --git a/tools/reflection_generator/Rules/Validation.cs b/tools/reflection_generator/Rules/Validation.cs new file mode 100644 index 000000000..5dc486f71 --- /dev/null +++ b/tools/reflection_generator/Rules/Validation.cs @@ -0,0 +1,34 @@ +using ReflectionGenerator.Model; + +namespace ReflectionGenerator.Rules; + +internal static class Validation +{ + private static readonly string[] ReservedFieldNames = [ + "m_uid", + "m_name", + "m_local_enabled", + "m_parent", + "m_source_prefab", + ]; + + public static void Check(NodeType node) + { + var name = node.QualifiedName; + + // the base node is the one class allowed to own the reserved members + if (name == "toast::Node") return; + + foreach (var field in node.Fields) { + if (ReservedFieldNames.Contains(field.Name)) { + throw new GeneratorException( + $"{name}: reflected field '{field.Name}' uses a reserved engine member name (only toast::Node may)"); + } + + var group = field.Attributes.FirstArg("Group"); + if (group is not null && group.StartsWith('~')) { + throw new GeneratorException($"{name}: group name '{group}' may not start with '~' (reserved)"); + } + } + } +} diff --git a/tools/reflection_generator/Strings.cs b/tools/reflection_generator/Strings.cs new file mode 100644 index 000000000..3e6011919 --- /dev/null +++ b/tools/reflection_generator/Strings.cs @@ -0,0 +1,27 @@ +namespace ReflectionGenerator; + +internal static class Strings +{ + public static string Qualify(string? scope, string name) => scope is null ? name : $"{scope}::{name}"; + + // last segment of a qualified name + public static string Bare(this string name) + { + var cut = name.LastIndexOf("::", StringComparison.Ordinal); + return cut < 0 ? name : name[(cut + 2)..]; + } + + public static string WithoutPrefix(this string text, string prefix) => + text.StartsWith(prefix, StringComparison.Ordinal) ? text[prefix.Length..] : text; + + // strips the prefix as many times as it repeats + public static string TrimStartText(this string text, string prefix) + { + while (text.StartsWith(prefix, StringComparison.Ordinal)) { + text = text[prefix.Length..]; + } + return text; + } + + public static string WithoutWhitespace(this string text) => string.Concat(text.Where(c => !char.IsWhiteSpace(c))); +} diff --git a/tools/reflection_generator/build.rs b/tools/reflection_generator/build.rs deleted file mode 100644 index c852c8324..000000000 --- a/tools/reflection_generator/build.rs +++ /dev/null @@ -1,37 +0,0 @@ -use std::fs; -use std::path::Path; - -fn main() { - // Get the output directory where the binary will be placed - let out_dir = std::env::var("OUT_DIR").expect("OUT_DIR not set"); - let target_dir = Path::new(&out_dir) - .parent() - .and_then(|p| p.parent()) - .and_then(|p| p.parent()) - .expect("Could not find target directory"); - - // Create templates directory next to the binary - let template_dest = target_dir.join("templates"); - fs::create_dir_all(&template_dest).expect("Failed to create templates directory"); - - // Copy templates from source to binary directory - let template_src = Path::new("templates"); - if template_src.is_dir() { - for entry in fs::read_dir(template_src).expect("Failed to read templates directory") { - if let Ok(entry) = entry { - let path = entry.path(); - if path.is_file() { - if let Some(file_name) = path.file_name() { - let dest_path = template_dest.join(file_name); - fs::copy(&path, &dest_path) - .expect(&format!("Failed to copy template {:?}", path)); - println!("Copied template: {:?}", dest_path); - } - } - } - } - } - - // Tell cargo to re-run this script if templates change - println!("cargo:rerun-if-changed=templates/"); -} diff --git a/tools/reflection_generator/reflection_generator.csproj b/tools/reflection_generator/reflection_generator.csproj new file mode 100644 index 000000000..4f9262752 --- /dev/null +++ b/tools/reflection_generator/reflection_generator.csproj @@ -0,0 +1,43 @@ + + + + Exe + net8.0 + reflection_generator + ReflectionGenerator + enable + enable + true + + Major + en + nullptr Studios + + + + + + + + + + + + + + + + + + + + $(PkgTreeSitter_DotNet)/runtimes/$(NETCoreSdkRuntimeIdentifier)/native + + + + + + + + + diff --git a/tools/reflection_generator/src/generator.rs b/tools/reflection_generator/src/generator.rs deleted file mode 100644 index 7b708f4d2..000000000 --- a/tools/reflection_generator/src/generator.rs +++ /dev/null @@ -1,165 +0,0 @@ -//! Converts parsed Class structs into NodeInfo data and emits C++ files via Jinja2 templates - -use crate::*; -use minijinja::Environment; -use std::collections::HashMap; -use std::fs; -use std::path::Path; - -/// Leaves the mtime alone when content is identical so dependents do not rebuild -pub fn write_if_changed(path: &Path, content: impl AsRef<[u8]>) -> std::io::Result<()> { - let content = content.as_ref(); - if fs::read(path).is_ok_and(|existing| existing == content) { - return Ok(()); - } - fs::write(path, content) -} - -pub fn generate_files(nodes: &[NodeInfo], output: &Path, register_fn: &str, split_typeinfo: bool) { - generate_files_with_events(nodes, &[], output, register_fn, split_typeinfo); -} - -pub fn generate_files_with_events(nodes: &[NodeInfo], events: &[EventInfo], output: &Path, register_fn: &str, split_typeinfo: bool) { - // Templates live next to the executable: /templates/ - let exe_dir = std::env::current_exe() - .expect("cannot locate executable") - .parent() - .expect("exe has no parent dir") - .to_path_buf(); - let template_dir = exe_dir.join("templates"); - - let mut env = Environment::new(); - env.set_loader(minijinja::path_loader(&template_dir)); - - // Per-class .generated.hpp - let node_tmpl = env - .get_template("node.generated.hpp.jinja2") - .unwrap_or_else(|e| panic!("cannot load node.generated.hpp.jinja2: {e}")); - - let type_info_tmpl = if split_typeinfo { - Some( - env.get_template("node.type_info.cpp.jinja2") - .unwrap_or_else(|e| panic!("cannot load node.type_info.cpp.jinja2: {e}")), - ) - } else { - None - }; - - for node in nodes { - let mut ctx = build_template_context(node); - if split_typeinfo && let json_t::Object(map) = &mut ctx { - map.insert("split_typeinfo".to_string(), json_t::Bool(true)); - } - let sn = ctx["snake_name"].as_str().unwrap(); - - let out = output.join(format!("{sn}.generated.hpp")); - let text = node_tmpl - .render(&ctx) - .unwrap_or_else(|e| panic!("template error for {}: {e}", node.class.name)); - write_if_changed(&out, text).unwrap_or_else(|e| panic!("cannot write {}: {e}", out.display())); - - if let Some(tmpl) = &type_info_tmpl { - let cpp_out = output.join(format!("{sn}.type_info.cpp")); - let cpp_text = tmpl.render(&ctx).unwrap_or_else(|e| { - panic!( - "template error for type_info.cpp ({}): {e}", - node.class.name - ) - }); - write_if_changed(&cpp_out, cpp_text) - .unwrap_or_else(|e| panic!("cannot write {}: {e}", cpp_out.display())); - } - } - - // reflect.generated.cpp - let cpp_tmpl = env - .get_template("reflect.generated.cpp.jinja2") - .unwrap_or_else(|e| panic!("cannot load reflect.generated.cpp.jinja2: {e}")); - - let mut all_ctx: Vec = nodes.iter().map(build_template_context).collect(); - if split_typeinfo { - for ctx in &mut all_ctx { - if let json_t::Object(map) = ctx { - map.insert("split_typeinfo".to_string(), json_t::Bool(true)); - } - } - } - let event_ctx: Vec = events.iter().filter(|e| e.supported).map(|e| json!({ - "name": e.name, - "qualified_name": e.qualified_name(), - "source_file": e.source_file, - "sendable": e.sendable, - "fields": e.fields, - })).collect(); - let cpp_ctx = serde_json::json!({ - "nodes": all_ctx, - "events": event_ctx, - "register_fn": register_fn, - "split_typeinfo": split_typeinfo, - }); - - let out = output.join("reflect.generated.cpp"); - let text = cpp_tmpl - .render(&cpp_ctx) - .unwrap_or_else(|e| panic!("template error for reflect.generated.cpp: {e}")); - write_if_changed(&out, text).unwrap_or_else(|e| panic!("cannot write {}: {e}", out.display())); -} - -fn qualify(namespace: Option<&str>, name: &str) -> String { - match namespace { - Some(ns) => format!("{ns}::{name}"), - None => name.to_string(), - } -} - -fn resolve_parent(node: &NodeInfo, known: &HashMap) -> Option { - let parent = node.class.parent.as_ref()?; - let written = qualify(parent.namespace.as_deref(), &parent.name); - if let Some(global) = written.strip_prefix("::") { - return known.get(global).copied(); - } - let mut scope = node.class.namespace.as_deref(); - loop { - let candidate = match scope { - Some(ns) => format!("{ns}::{written}"), - None => written.clone(), - }; - if let Some(&idx) = known.get(&candidate) { - return Some(idx); - } - scope = match scope { - Some(ns) => ns.rfind("::").map(|pos| &ns[..pos]), - None => return None, - }; - } -} - -pub fn topological_sort(nodes: Vec) -> Vec { - let known: HashMap = nodes - .iter() - .enumerate() - .map(|(i, n)| (qualify(n.class.namespace.as_deref(), &n.class.name), i)) - .collect(); - let parents: Vec> = nodes.iter().map(|n| resolve_parent(n, &known)).collect(); - - let mut placed = vec![false; nodes.len()]; - let mut order = Vec::with_capacity(nodes.len()); - for start in 0..nodes.len() { - let mut chain = Vec::new(); - let mut current = Some(start); - while let Some(i) = current { - if placed[i] || chain.contains(&i) { - break; - } - chain.push(i); - current = parents[i]; - } - for &i in chain.iter().rev() { - placed[i] = true; - order.push(i); - } - } - - let mut slots: Vec> = nodes.into_iter().map(Some).collect(); - order.into_iter().map(|i| slots[i].take().expect("node placed twice")).collect() -} diff --git a/tools/reflection_generator/src/lib.rs b/tools/reflection_generator/src/lib.rs deleted file mode 100644 index 52b577a47..000000000 --- a/tools/reflection_generator/src/lib.rs +++ /dev/null @@ -1,153 +0,0 @@ -//! Re-exports for the integration test crate - -mod generator; -mod lua_stubs; -mod node; -mod parser; - -pub use generator::*; -pub use lua_stubs::*; -pub use node::*; -pub use parser::*; -use serde::Serialize; -use serde_json::to_value; -pub use serde_json::{Value as json_t, json}; - -#[derive(Serialize, Clone)] -pub enum FieldType { - #[serde(rename = "bool_t")] - Bool, - #[serde(rename = "int_t")] - Int, - #[serde(rename = "float_t")] - Float, - #[serde(rename = "string_t")] - String, - #[serde(rename = "double_t")] - Double, - #[serde(rename = "uid_t")] - Uid, - #[serde(rename = "vec2_t")] - Vec2, - #[serde(rename = "vec3_t")] - Vec3, - #[serde(rename = "vec4_t")] - Vec4, - #[serde(rename = "quaternion_t")] - Quaternion, -} - -#[derive(Serialize, Clone)] -pub struct Attribute { - pub name: String, - pub args: Vec, -} - -#[derive(Serialize, Clone)] -pub struct Parent { - pub name: String, - pub namespace: Option, -} - -#[derive(Serialize, Clone)] -pub struct Field { - pub name: String, - pub typename: String, - pub field_type: FieldType, - pub is_array: bool, - #[serde(skip)] - pub attributes: Vec, - #[serde(rename = "attributes")] - pub attrib_json: json_t, - pub default: Option, -} - -#[derive(Serialize, Clone)] -pub struct Signal { - pub name: String, - pub typename: String, - pub arguments: Vec, - pub attrs_list: Vec, - #[serde(rename = "attributes")] - pub attrib_json: json_t, -} - -#[derive(Serialize, Clone)] -pub struct Parameter { - pub name: String, - #[serde(rename = "type")] - pub type_name: String, - pub default: Option, -} - -#[derive(Serialize, Clone)] -pub struct Function { - pub name: String, - pub return_type: String, - pub parameters: Vec, - #[serde(skip)] - pub attributes: Vec, - #[serde(rename = "attributes")] - pub attrib_json: json_t, - pub is_const: bool, -} - -#[derive(Serialize, Clone)] -pub struct Class { - pub name: String, - pub namespace: Option, - pub parent: Option, - #[serde(skip)] - pub attributes: Vec, - #[serde(rename = "attributes")] - pub attrib_json: json_t, - pub functions: Vec, - pub methods: Vec, - pub fields: Vec, - pub signals: Vec, - pub source_file: String, -} - -#[derive(Serialize, Clone)] -pub struct EventInfo { - pub name: String, - pub namespace: Option, - pub fields: Vec, - pub source_file: String, - pub constructor_compatible: bool, - pub supported: bool, - pub sendable: bool, - pub skip_reason: Option, -} - -#[derive(Serialize, Clone)] -pub struct EventField { - pub name: String, - pub typename: String, - pub lua_type: Option, - pub readable: bool, -} - -impl EventInfo { - pub fn qualified_name(&self) -> String { - self.namespace - .as_ref() - .map_or_else(|| self.name.clone(), |ns| format!("{ns}::{}", self.name)) - } -} - -// tree-sitter sees TOAST_API and __declspec attributes as identifiers that break field parsing -pub fn strip_export_macros(source: &str) -> String { - source - .replace("TOAST_API ", "") - .replace("__declspec(dllexport) ", "") - .replace("__declspec(dllimport) ", "") -} - -pub fn generate_json(nodes: &[NodeInfo]) -> json_t { - to_value(nodes).unwrap_or(json_t::Array(vec![])) -} - -pub fn generate_database(nodes: &[NodeInfo], events: &[EventInfo]) -> json_t { - json!({ "nodes": nodes, "events": events }) -} diff --git a/tools/reflection_generator/src/lua_stubs.rs b/tools/reflection_generator/src/lua_stubs.rs deleted file mode 100644 index 95d7c3f60..000000000 --- a/tools/reflection_generator/src/lua_stubs.rs +++ /dev/null @@ -1,284 +0,0 @@ -use crate::node::NodeInfo; -use crate::{EventInfo, Field, FieldType, Function, Signal, json}; -use minijinja::Environment; - -/// Strips namespaces -fn bare(name: &str) -> &str { - name.rsplit("::").next().unwrap_or(name) -} - -/// Strips the m_ member prefix -fn lua_field_name(name: &str) -> &str { - name.strip_prefix("m_").unwrap_or(name) -} - -fn has_color_attr(field: &Field) -> bool { - field.attributes.iter().any(|a| a.name == "Color") -} - -/// Lua type of a reflected field -fn field_lua_type(field: &Field) -> String { - let base = match field.field_type { - FieldType::Bool => "boolean".to_string(), - FieldType::Int => "integer".to_string(), - FieldType::Float | FieldType::Double => "number".to_string(), - FieldType::String => "string".to_string(), - FieldType::Vec2 => "vec2".to_string(), - FieldType::Vec3 => if has_color_attr(field) { - "color3" - } else { - "vec3" - } - .to_string(), - FieldType::Vec4 => if has_color_attr(field) { - "color4" - } else { - "vec4" - } - .to_string(), - FieldType::Quaternion => "quat".to_string(), - FieldType::Uid => uid_lua_type(&field.typename), - }; - if field.is_array { - format!("{base}[]") - } else { - base - } -} - -/// Lua type of a Box and Handle field -fn uid_lua_type(typename: &str) -> String { - let inner = typename - .trim_start_matches("std::vector<") - .trim_end_matches('>'); - if let Some(node_type) = inner.strip_prefix("Box<") { - return bare(node_type.trim_end_matches('>')).to_string(); - } - if inner.contains("Handle<") { - return "Asset".to_string(); - } - "any".to_string() -} - -/// Lua type of a method parameter or return -fn cpp_lua_type(cpp: &str) -> String { - let t = cpp.trim(); - if let Some(inner) = t - .strip_prefix("std::optional<") - .and_then(|type_name| type_name.strip_suffix('>')) - { - return format!("{}|nil", cpp_lua_type(inner)); - } - if let Some(inner) = t - .strip_prefix("std::vector<") - .and_then(|type_name| type_name.strip_suffix('>')) - { - return format!("{}[]", cpp_lua_type(inner)); - } - if t.contains("input::ActionEvent") { - return "InputActionEvent".to_string(); - } - if t.contains("input::Action") { - return "InputAction".to_string(); - } - if t.contains("input::Bind") { - return "InputBind".to_string(); - } - if t.contains("input::KeyCode") { - return "InputKeyCode".to_string(); - } - if t.contains("input::Device") { - return "InputDeviceValue".to_string(); - } - if t.contains("input::ValueType") { - return "InputValueTypeValue".to_string(); - } - if t.contains("input::ModifierKey") { - return "InputModifierValue".to_string(); - } - if t.contains("input::InputKind") { - return "InputKindValue".to_string(); - } - if t.contains("voxel::WriteMode") { - return "VoxelWriteValue".to_string(); - } - if t.contains("Box<") { - let inner = t.split("Box<").nth(1).unwrap_or("Node"); - return bare(inner.trim_end_matches(['>', '&', ' '])).to_string(); - } - if t.contains("Handle<") { - return "Asset".to_string(); - } - if t.contains("physics::RayHit") { - return "RayHit".to_string(); - } - if t.contains("bool") { - return "boolean".to_string(); - } - if t.contains("float") || t.contains("double") { - return "number".to_string(); - } - if t.contains("string") { - return "string".to_string(); - } - if t.contains("vec4") { - return "vec4".to_string(); - } - if t.contains("vec3") { - return "vec3".to_string(); - } - if t.contains("vec2") { - return "vec2".to_string(); - } - if t.contains("quat") { - return "quat".to_string(); - } - if t == "void" { - return "nil".to_string(); - } - if t.contains("int") || t.contains("long") || t.contains("short") || t == "char" { - return "integer".to_string(); - } - "any".to_string() -} - -fn method_signature(class_name: &str, method: &Function) -> String { - let mut params = format!("self: {class_name}"); - for p in &method.parameters { - let optional = if p.default.is_some() { "?" } else { "" }; - params.push_str(&format!( - ", {}{optional}: {}", - p.name, - cpp_lua_type(&p.type_name) - )); - } - let ret = cpp_lua_type(&method.return_type); - if ret == "nil" { - format!("fun({params})") - } else { - format!("fun({params}): {ret}") - } -} - -fn signal_lua_type(signal: &Signal) -> String { - let args: Vec = signal - .arguments - .iter() - .map(|arg| cpp_lua_type(arg)) - .collect(); - match args.len() { - 0 => "Signal0".to_string(), - 1..=4 => format!("Signal{}<{}>", args.len(), args.join(", ")), - _ => "Signal0".to_string(), - } -} - -fn field_context(field: &Field) -> Option { - // Hidden fields don't appear in the inspector and shadow builtins like uid()/name() - if field.attributes.iter().any(|a| a.name == "Hidden") { - return None; - } - Some(json!({ - "name": lua_field_name(&field.name), - "lua_type": field_lua_type(field), - })) -} - -fn render_template(name: &str, source: &'static str, context: &serde_json::Value) -> String { - let mut env = Environment::new(); - env.set_trim_blocks(true); - env.set_lstrip_blocks(true); - env.add_template(name, source) - .unwrap_or_else(|e| panic!("cannot load {name}: {e}")); - env.get_template(name) - .unwrap_or_else(|e| panic!("cannot get {name}: {e}")) - .render(context) - .unwrap_or_else(|e| panic!("template error for {name}: {e}")) -} - -/// Renders the full types.d.lua contents for the reflected node set -pub fn generate_lua_stubs(nodes: &[NodeInfo]) -> String { - let node_contexts: Vec<_> = nodes - .iter() - .map(|node| { - let fields: Vec<_> = node - .global_fields - .iter() - .chain(node.groups.iter().flat_map(|group| { - group - .fields - .iter() - .chain(group.subgroups.iter().flat_map(|subgroup| &subgroup.fields)) - })) - .filter_map(field_context) - .collect(); - let methods: Vec<_> = node - .class - .methods - .iter() - .map(|method| { - json!({ - "name": method.name, - "signature": method_signature(&node.class.name, method), - }) - }) - .collect(); - let signals: Vec<_> = node - .class - .signals - .iter() - .map(|signal| { - json!({ - "name": signal.name, - "lua_type": signal_lua_type(signal), - }) - }) - .collect(); - json!({ - "name": node.class.name, - "inheritance": node.class.parent.as_ref() - .map(|parent| format!(" : {}", bare(&parent.name))) - .unwrap_or_default(), - "fields": fields, - "methods": methods, - "signals": signals, - }) - }) - .collect(); - - render_template( - "types.d.lua.jinja2", - include_str!("../templates/types.d.lua.jinja2"), - &json!({ "nodes": node_contexts }), - ) -} - -pub fn generate_event_lua_stubs(events: &[EventInfo]) -> String { - let event_contexts: Vec<_> = events - .iter() - .filter(|event| event.supported) - .map(|event| { - let fields: Vec<_> = event - .fields - .iter() - .map(|field| { - json!({ - "name": field.name, - "lua_type": field.lua_type.as_deref().unwrap_or("any"), - }) - }) - .collect(); - json!({ - "name": event.name, - "sendable": event.sendable, - "fields": fields, - }) - }) - .collect(); - - render_template( - "events.d.lua.jinja2", - include_str!("../templates/events.d.lua.jinja2"), - &json!({ "events": event_contexts }), - ) -} diff --git a/tools/reflection_generator/src/main.rs b/tools/reflection_generator/src/main.rs deleted file mode 100644 index 3834c2fb6..000000000 --- a/tools/reflection_generator/src/main.rs +++ /dev/null @@ -1,214 +0,0 @@ -//! CLI driver; walks input dirs for `[[ToastNode]]` headers, parses with tree-sitter, -//! validates against reserved names, emits one `.generated.hpp` per class and one -//! `reflect.generated.cpp` registration file - -use reflection_generator::*; - -use clap::Parser; -use std::fs; -use std::path::{Path, PathBuf}; -use walkdir::WalkDir; - -#[derive(Parser)] -#[command(name = "refgen", about = "Toast reflection code generator")] -struct Cli { - /// Path to the JSON metadata output file - #[arg(long)] - database: PathBuf, - - /// Directory where generated files are written - #[arg(long)] - output: PathBuf, - - /// Directory to search for headers - #[arg(long = "input")] - inputs: Vec, - - /// Root directory used to compute #include paths - #[arg(long)] - include_root: Option, - - /// Name of the registration function to emit - #[arg(long, default_value = "registerEngineTypes")] - register_fn: std::string::String, - - #[arg(long)] - split_typeinfo: bool, - #[arg(long = "attribute")] - attributes: Vec, - - /// Path of the lua LSP to emit (types.d.lua) - #[arg(long)] - lua_stubs: Option, - - /// Path of the lua Events definitions (events.d.lua) - #[arg(long)] - event_lua_stubs: Option, -} - -fn main() { - let cli = Cli::parse(); - - // Validate paths - for input in &cli.inputs { - if !input.is_dir() { - eprintln!("error: --input '{}' is not a directory", input.display()); - std::process::exit(1); - } - } - if !cli.output.is_dir() { - eprintln!( - "error: --output '{}' is not a directory", - cli.output.display() - ); - std::process::exit(1); - } - - // Discover headers - let header_files = find_headers(&cli.inputs); - if header_files.is_empty() { - eprintln!("warning: no [[ToastNode]] headers found in the given --input directories"); - } - - // Parse each file - let mut all_nodes: Vec = Vec::new(); - let mut all_events: Vec = Vec::new(); - - for file_path in &header_files { - let include_path = compute_include_path(file_path, cli.include_root.as_deref()); - - let source = match fs::read_to_string(file_path) { - Ok(s) => s, - Err(e) => { - eprintln!("error reading '{}': {e}", file_path.display()); - continue; - } - }; - - let preprocessed = strip_export_macros(&source); - let classes = parse(&preprocessed, &include_path); - all_events.extend(parse_events(&preprocessed, &include_path)); - - for class in &classes { - if let Err(msg) = validate_class(class) { - eprintln!("error: {msg}"); - std::process::exit(1); - } - let mut node = build_node(class); - inject_attributes(&mut node, &cli.attributes); - all_nodes.push(node); - } - } - - // Write JSON database - if let Some(parent) = cli.database.parent() - && !parent.as_os_str().is_empty() - { - fs::create_dir_all(parent) - .unwrap_or_else(|e| eprintln!("warning: cannot create database directory: {e}")); - } - all_events.sort_by_key(EventInfo::qualified_name); - all_events.dedup_by_key(|e| e.qualified_name()); - let skipped = all_events.iter().filter(|e| !e.supported).count(); - if skipped > 0 { - // was too noisy otherwise - eprintln!("warning: skipped {skipped} Lua events"); - } - let json = serde_json::to_string_pretty(&generate_database(&all_nodes, &all_events)) - .expect("JSON serialisation failed"); - fs::write(&cli.database, json).unwrap_or_else(|e| { - eprintln!( - "warning: cannot write database '{}': {e}", - cli.database.display() - ) - }); - - // Generate files, sorted so base classes are included before derived classes - let all_nodes = topological_sort(all_nodes); - generate_files_with_events( - &all_nodes, - &all_events, - &cli.output, - &cli.register_fn, - cli.split_typeinfo, - ); - - if let Some(stub_path) = &cli.lua_stubs { - if let Some(parent) = stub_path.parent() - && !parent.as_os_str().is_empty() - { - fs::create_dir_all(parent) - .unwrap_or_else(|e| eprintln!("warning: cannot create lua stub directory: {e}")); - } - fs::write(stub_path, generate_lua_stubs(&all_nodes)).unwrap_or_else(|e| { - eprintln!( - "warning: cannot write lua stubs '{}': {e}", - stub_path.display() - ) - }); - } - - if let Some(stub_path) = &cli.event_lua_stubs { - if let Some(parent) = stub_path.parent() && !parent.as_os_str().is_empty() { - fs::create_dir_all(parent).unwrap_or_else(|e| eprintln!("warning: cannot create event lua stub directory: {e}")); - } - fs::write(stub_path, generate_event_lua_stubs(&all_events)).unwrap_or_else(|e| eprintln!("warning: cannot write event lua stubs '{}': {e}", stub_path.display())); - } - - println!( - "refgen: generated {} type(s) → '{}' (fn: {})", - all_nodes.len(), - cli.output.display(), - cli.register_fn - ); -} - -/// Inject extra attributes -fn inject_attributes(node: &mut NodeInfo, attributes: &[std::string::String]) { - if attributes.is_empty() { - return; - } - if !node.class.attrib_json.is_object() { - node.class.attrib_json = serde_json::Value::Object(serde_json::Map::new()); - } - let map = node - .class - .attrib_json - .as_object_mut() - .expect("attributes is an object"); - for name in attributes { - map.entry(name.clone()) - .or_insert_with(|| serde_json::json!([])); - } -} - -/// Walk all input dirs and return headers containing useful information -fn find_headers(inputs: &[PathBuf]) -> Vec { - let mut result = Vec::new(); - for dir in inputs { - for entry in WalkDir::new(dir).into_iter().filter_map(|e| e.ok()) { - let path = entry.path().to_path_buf(); - if path.extension().and_then(|e| e.to_str()) != Some("hpp") { - continue; - } - if let Ok(content) = fs::read_to_string(&path) - && (content.contains("ToastNode") || content.contains("Event<")) - { - result.push(path); - } - } - } - result -} - -// strips --include-root prefix and normalizes to forward slashes so the path can be used in a #include directive -fn compute_include_path(file: &Path, include_root: Option<&Path>) -> std::string::String { - if let Some(root) = include_root - && let Ok(rel) = file.strip_prefix(root) - { - return rel.to_string_lossy().replace('\\', "/"); - } - file.file_name() - .map(|n| n.to_string_lossy().into_owned()) - .unwrap_or_default() -} diff --git a/tools/reflection_generator/src/node.rs b/tools/reflection_generator/src/node.rs deleted file mode 100644 index 0a94baefd..000000000 --- a/tools/reflection_generator/src/node.rs +++ /dev/null @@ -1,321 +0,0 @@ -use crate::*; - -use std::collections::BTreeMap; - -#[derive(Serialize)] -pub struct NodeInfo { - #[serde(flatten)] - pub class: Class, - pub groups: Vec, - pub global_fields: Vec, - pub tick_functions: TickFunctions, - pub is_interface: bool, -} - -#[derive(Serialize)] -pub struct TickFunctions { - pub editor_tick: bool, - pub init: bool, - pub begin: bool, - pub early_tick: bool, - pub tick: bool, - pub physics_tick: bool, - pub post_physics: bool, - pub late_tick: bool, - pub end: bool, - pub destroy: bool, - pub on_enable: bool, - pub on_disable: bool, - pub load: bool, - pub save: bool, -} - -#[derive(Serialize)] -pub struct GroupInfo { - pub name: String, - pub subgroups: Vec, - pub fields: Vec, -} - -#[derive(Serialize)] -pub struct SubgroupInfo { - pub name: String, - pub fields: Vec, -} - -const RESERVED_FIELD_NAMES: &[&str] = &[ - "m_uid", - "m_name", - "m_local_enabled", - "m_parent", - "m_source_prefab", -]; - -// TODO: smth with these -fn to_snake(s: &str) -> std::string::String { - s.to_lowercase().replace(' ', "_") -} -fn cpp_escape(s: &str) -> std::string::String { - s.replace('\\', "\\\\").replace('"', "\\\"") -} - -pub fn build_node(class: &Class) -> NodeInfo { - let is_interface = class.attributes.iter().any(|a| a.name == "Interface"); - let (global_fields, groups) = build_field_groups(&class.fields); - - NodeInfo { - class: class.clone(), - groups, - global_fields, - tick_functions: build_tick_functions(class), - is_interface, - } -} - -pub fn build_template_context(node: &NodeInfo) -> json_t { - // --- 1. Basic Info & Namespaces --- - let snake_name = node.class.name.to_lowercase(); - let qualified_name = node - .class - .namespace - .as_ref() - .map_or(node.class.name.clone(), |ns| { - format!("{ns}::{}", node.class.name) - }); - let parent_qualified_name = node.class.parent.as_ref().map(|p| { - p.namespace - .as_ref() - .map_or(p.name.clone(), |ns| format!("{ns}::{}", p.name)) - }); - let parent_snake_name = node.class.parent.as_ref().map(|p| p.name.to_lowercase()); - - // --- 2. Field Flattening & Asset Tracking --- - let mut all_fields_flat = Vec::new(); - let mut has_asset_handle = false; - // This inline closure updates the flat list, checks for assets, and returns the index - let mut process_field = |f: &Field| -> usize { - let idx = all_fields_flat.len(); - if f.typename.contains("Handle<") { - has_asset_handle = true; - } - - let attrs_list: Vec = match &f.attrib_json { - json_t::Object(map) => map - .iter() - .map(|(k, v)| json!({ "name": k, "args": v })) - .collect(), - _ => vec![], - }; - - all_fields_flat.push(json!({ - "index": idx, - "name": f.name, - "member_name": f.name, - "typename": f.typename, - "field_type": serde_json::to_value(&f.field_type).unwrap(), - "is_array": f.is_array, - "is_asset_handle": f.typename.contains("Handle<"), - "is_enum": f.attributes.iter().any(|a| a.name == "Enum") && !f.is_array, - "attributes": f.attrib_json, - "attrs_list": attrs_list, - "default": f.default, - })); - idx - }; - - // --- 3. Process Fields (Global, Groups, Subgroups) --- - let global_field_indices: Vec = - node.global_fields.iter().map(&mut process_field).collect(); - - let augmented_groups: Vec = node.groups.iter().map(|g| { - json!({ - "name": g.name, - "snake_name": to_snake(&g.name), - "field_indices": g.fields.iter().map(&mut process_field).collect::>(), - "subgroups": g.subgroups.iter().map(|sg| { - json!({ - "name": sg.name, - "snake_name": to_snake(&sg.name), - "field_indices": sg.fields.iter().map(&mut process_field).collect::>(), - }) - }).collect::>(), - }) - }).collect(); - // --- 4. Active Tick Functions --- - let tf = &node.tick_functions; - let active_tick_fns: Vec = [ - (tf.load, "load", "load"), - (tf.save, "save", "save"), - (tf.editor_tick, "editor_tick", "editorTick"), - (tf.init, "init", "init"), - (tf.destroy, "destroy", "destroy"), - (tf.begin, "begin", "begin"), - (tf.end, "end", "end"), - (tf.on_enable, "on_enable", "onEnable"), - (tf.on_disable, "on_disable", "onDisable"), - (tf.early_tick, "early_tick", "earlyTick"), - (tf.tick, "tick", "tick"), - (tf.physics_tick, "physics_tick", "physicsTick"), - (tf.post_physics, "post_physics", "postPhysics"), - (tf.late_tick, "late_tick", "lateTick"), - ] - .into_iter() - .filter(|(is_active, _, _)| *is_active) - .map(|(_, flag, method)| json!({ "flag": flag, "method": method })) - .collect(); - - // --- 5. Reflected Methods --- - let methods_ctx: Vec = node - .class - .methods - .iter() - .map(|m| { - let attrs_list: Vec = match &m.attrib_json { - json_t::Object(map) => map - .iter() - .map(|(k, v)| json!({ "name": k, "args": v })) - .collect(), - _ => vec![], - }; - json!({ - "name": m.name, - "return_type": m.return_type, - "is_const": m.is_const, - "attrs_list": attrs_list, - "parameters": m.parameters.iter().enumerate().map(|(i, p)| { - json!({ - "index": i, - "arg_name": format!("a{i}"), - "name": p.name, - "type": p.type_name, - "default": p.default, - "default_escaped": p.default.as_deref().map(cpp_escape), - }) - }).collect::>(), - }) - }) - .collect(); - - if node.class.methods.iter().any(|method| { - method - .parameters - .iter() - .any(|parameter| parameter.type_name.contains("Handle<")) - }) { - has_asset_handle = true; - } - - // --- 6. Final Payload Assembly --- - json!({ - "name": node.class.name, - "namespace": node.class.namespace, - "snake_name": snake_name, - "qualified_name": qualified_name, - "parent_qualified_name": parent_qualified_name, - "parent_snake_name": parent_snake_name, - "source_file": node.class.source_file, - "attributes": node.class.attrib_json, - "all_fields_flat": all_fields_flat, - "global_field_indices": global_field_indices, - "groups": augmented_groups, - "active_tick_fns": active_tick_fns, - "methods": methods_ctx, - "has_asset_handle": has_asset_handle, - "is_interface": node.is_interface, - "signals": node.class.signals, - }) -} - -pub fn validate_class(class: &Class) -> std::result::Result<(), String> { - // Fully qualified name - let q = class.qualified_name(); - - // Exclude Base Class - if q == "toast::Node" { - return Ok(()); - } - - for f in &class.fields { - // Reject reserved field names - if RESERVED_FIELD_NAMES.contains(&f.name.as_str()) { - #[rustfmt::skip] - let msg = format!("{q}: reflected field '{}' uses a reserved engine member name (only toast::Node may)", f.name); - return Err(msg); - } - // Reject internal group syntax (~) - if let Some(g) = f.attributes.get_arg("Group").filter(|g| g.starts_with('~')) { - #[rustfmt::skip] - let msg = format!("{q}: group name '{g}' may not start with '~' (reserved)"); - return Err(msg); - } - } - - Ok(()) -} - -fn build_tick_functions(class: &Class) -> TickFunctions { - let fns = &class.functions; - TickFunctions { - editor_tick: fns.contains(&"editorTick".to_string()), - init: fns.contains(&"init".to_string()), - begin: fns.contains(&"begin".to_string()), - early_tick: fns.contains(&"earlyTick".to_string()), - tick: fns.contains(&"tick".to_string()), - physics_tick: fns.contains(&"physicsTick".to_string()), - post_physics: fns.contains(&"postPhysics".to_string()), - late_tick: fns.contains(&"lateTick".to_string()), - end: fns.contains(&"end".to_string()), - destroy: fns.contains(&"destroy".to_string()), - on_enable: fns.contains(&"onEnable".to_string()), - on_disable: fns.contains(&"onDisable".to_string()), - load: fns.contains(&"load".to_string()), - save: fns.contains(&"save".to_string()), - } -} - -fn build_field_groups(fields: &[Field]) -> (Vec, Vec) { - #[derive(Default)] - struct GroupBucket { - fields: Vec, - subgroups: BTreeMap>, - } - let mut global_fields = Vec::new(); - let mut group_map: BTreeMap = BTreeMap::new(); - for field in fields { - let group = field.attributes.get_arg("Group").cloned(); - let subgroup = field.attributes.get_arg("Subgroup").cloned(); - let fi = field.clone(); - - if let Some(g) = group { - let bucket = group_map.entry(g).or_default(); - match subgroup { - Some(sg) => bucket.subgroups.entry(sg).or_default().push(fi), - None => bucket.fields.push(fi), - } - } else { - global_fields.push(fi); - } - } - - let groups = group_map - .into_iter() - .map(|(name, bucket)| { - let subgroups = bucket - .subgroups - .into_iter() - .map(|(sg_name, sg_fields)| SubgroupInfo { - name: sg_name, - fields: sg_fields, - }) - .collect(); - - GroupInfo { - name, - fields: bucket.fields, - subgroups, - } - }) - .collect(); - - (global_fields, groups) -} diff --git a/tools/reflection_generator/src/parser.rs b/tools/reflection_generator/src/parser.rs deleted file mode 100644 index 9643fd4ac..000000000 --- a/tools/reflection_generator/src/parser.rs +++ /dev/null @@ -1,768 +0,0 @@ -//! Uses tree-sitter-cpp to extract `[[ToastNode]]` classes, `[[Reflect]]` fields, -//! and tick-function declarations from C++ header files - -use tree_sitter::{Parser, Query, QueryCursor, StreamingIterator}; - -use crate::*; - -impl Class { - pub fn qualified_name(&self) -> String { - if let Some(ns) = &self.namespace { - format!("{ns}::{}", self.name) - } else { - self.name.clone() - } - } -} - -pub trait AttributeExt { - fn get_arg(&self, name: &str) -> Option<&String>; -} - -impl AttributeExt for [Attribute] { - fn get_arg(&self, name: &str) -> Option<&String> { - self.iter() - .find(|a| a.name == name) - .and_then(|a| a.args.first()) - } -} -////////////////////////////////////////////////////////////////// -pub fn parse(source: &str, file_path: &str) -> Vec { - let mut parser = Parser::new(); - parser - .set_language(&tree_sitter_cpp::LANGUAGE.into()) - .expect("Language error"); - - let tree = parser.parse(source, None).unwrap(); - let query = Query::new( - &tree_sitter_cpp::LANGUAGE.into(), - "(class_specifier) @class", - ) - .unwrap(); - - let mut cursor = QueryCursor::new(); - let mut captures = cursor.captures(&query, tree.root_node(), source.as_bytes()); - - let mut classes = Vec::new(); - while let Some((m, idx)) = captures.next() { - let node = m.captures[*idx].node; - if let Some(class) = get_class(node, source, file_path) { - classes.push(class); - } - } - classes -} - -pub fn parse_events(source: &str, file_path: &str) -> Vec { - let mut parser = Parser::new(); - parser.set_language(&tree_sitter_cpp::LANGUAGE.into()).expect("Language error"); - let tree = parser.parse(source, None).unwrap(); - let query = Query::new(&tree_sitter_cpp::LANGUAGE.into(), "[(class_specifier) (struct_specifier)] @class").unwrap(); - let enums = collect_enum_names(tree.root_node(), source); - let mut cursor = QueryCursor::new(); - let mut captures = cursor.captures(&query, tree.root_node(), source.as_bytes()); - let mut result = Vec::new(); - - while let Some((m, idx)) = captures.next() { - let node = m.captures[*idx].node; - let Some(name_node) = node.child_by_field_name("name") else { continue }; - let name = source[name_node.byte_range()].to_string(); - if !is_event_base(node, source, &name) { continue; } - - let fields = get_event_fields(node, source, &enums); - let constructor_compatible = event_constructor_compatible(node, source, &name, &fields); - let unsupported = fields.iter().find(|f| f.lua_type.is_none()); - let skip_reason = unsupported.map(|field| format!("field '{}' has unsupported type '{}'", field.name, field.typename)); - let sendable = skip_reason.is_none() && constructor_compatible && fields.iter().all(|f| f.readable); - - result.push(EventInfo { - name, - namespace: get_namespace(node, source), - fields, - source_file: file_path.to_string(), - constructor_compatible, - supported: skip_reason.is_none(), - sendable, - skip_reason, - }); - } - result -} - -fn is_event_base(node: tree_sitter::Node, source: &str, name: &str) -> bool { - for child in node.children(&mut node.walk()) { - if child.kind() != "base_class_clause" { continue; } - let clause = source[child.byte_range()].trim_start().trim_start_matches(':'); - let needle = format!("Event<{name}>"); - let exact = clause.split(',').any(|base| { - let compact: String = base - .split_whitespace() - .filter(|word| !matches!(*word, "public" | "protected" | "private" | "virtual")) - .collect(); - compact == needle || compact.ends_with(&format!("::{needle}")) - }); - if exact { - return true; - } - } - false -} - -fn collect_enum_names(root: tree_sitter::Node, source: &str) -> Vec { - let query = Query::new(&tree_sitter_cpp::LANGUAGE.into(), "(enum_specifier name: (type_identifier) @name body: (_))").unwrap(); - let mut cursor = QueryCursor::new(); - let mut captures = cursor.captures(&query, root, source.as_bytes()); - let mut names = Vec::new(); - while let Some((m, idx)) = captures.next() { - names.push(source[m.captures[*idx].node.byte_range()].to_string()); - } - names -} - -fn lua_event_type(type_name: &str, enums: &[String]) -> Option<(String, bool)> { - let t: String = type_name.chars().filter(|c| !c.is_whitespace()).collect(); - let bare = t.trim_start_matches("const").trim_start_matches("std::").trim_start_matches("glm::"); - if let Some(inner) = bare.strip_prefix("vector<").and_then(|s| s.strip_suffix('>')) { - return lua_event_type(inner, enums).map(|(lua, readable)| (format!("{lua}[]"), readable)); - } - if bare.starts_with("assets::Handle<") || bare.starts_with("Handle<") { - return Some(("Asset".into(), true)); - } - let unqualified = bare.rsplit("::").next().unwrap_or(bare); - if enums.iter().any(|e| e == unqualified) { - return Some(("integer".into(), true)); - } - let readable = |lua: &str| Some((lua.to_string(), true)); - let push_only = |lua: &str| Some((lua.to_string(), false)); - match bare { - "toast::Box" | "Box" | "toast::Box" | "Box" | "toast::Node*" | "Node*" => readable("Node"), - "bool" => readable("boolean"), - "float" | "double" => readable("number"), - "char" | "short" | "int" | "long" | "longlong" | "unsigned" | "unsignedint" | - "unsignedlong" | "unsignedlonglong" | "int8_t" | "int16_t" | "int32_t" | "int64_t" | - "uint8_t" | "uint16_t" | "uint32_t" | "uint64_t" | "size_t" => readable("integer"), - "string" => readable("string"), - "vec2" | "ivec2" => readable("vec2"), - "vec3" | "ivec3" => readable("vec3"), - "vec4" | "ivec4" => readable("vec4"), - "quat" | "quaternion" => readable("quat"), - "toast::UID" | "UID" => readable("UID"), - "input::Device" => readable("InputDeviceValue"), - "input::ActionEvent" => readable("InputActionEvent"), - "input::Action&" | "input::Action" => push_only("InputAction"), - "ContactEventData" | "event::ContactEventData" => push_only("ContactEventData"), - "physics::BroadPhasePair" | "BroadPhasePair" => push_only("BroadPhasePair"), - _ => None, - } -} - -fn get_event_fields(node: tree_sitter::Node, source: &str, enums: &[String]) -> Vec { - let Some(body) = node.child_by_field_name("body") else { return Vec::new() }; - let default_public = node.kind() == "struct_specifier"; - let mut public = default_public; - let mut fields = Vec::new(); - for child in body.named_children(&mut body.walk()) { - if child.kind() == "access_specifier" { - public = source[child.byte_range()].trim_start().starts_with("public"); - continue; - } - if !public || child.kind() != "field_declaration" { continue; } - let Some(ty) = child.child_by_field_name("type") else { continue }; - if matches!(ty.kind(), "struct_specifier" | "class_specifier" | "enum_specifier") { continue; } - let type_name = source[ty.byte_range()].trim().to_string(); - if type_name.contains("Event<") { continue; } - let mut identifiers = Vec::new(); - collect_field_identifiers(child, &mut identifiers); - for decl in identifiers { - let mut declared_type = type_name.clone(); - let mut current = decl.parent(); - while let Some(parent) = current { - if parent.id() == child.id() { break; } - if parent.kind() == "pointer_declarator" { declared_type.push('*'); } - if parent.kind() == "reference_declarator" { declared_type.push('&'); } - current = parent.parent(); - } - let mapped = lua_event_type(&declared_type, enums); - fields.push(EventField { - name: source[decl.byte_range()].to_string(), - typename: declared_type.clone(), - readable: mapped.as_ref().is_some_and(|(_, readable)| *readable), - lua_type: mapped.map(|(lua, _)| lua), - }); - } - } - fields -} - -fn collect_field_identifiers<'a>(node: tree_sitter::Node<'a>, result: &mut Vec>) { - if node.kind() == "field_identifier" { - result.push(node); - return; - } - for child in node.named_children(&mut node.walk()) { - collect_field_identifiers(child, result); - } -} - -fn normalized_type(t: &str) -> String { - t.replace("const", "").replace('&', "").replace("&&", "").chars().filter(|c| !c.is_whitespace()).collect() -} - -fn event_constructor_compatible(node: tree_sitter::Node, source: &str, name: &str, fields: &[EventField]) -> bool { - if fields.is_empty() { return true; } - let query = Query::new(&tree_sitter_cpp::LANGUAGE.into(), "(function_declarator) @fn").unwrap(); - let mut cursor = QueryCursor::new(); - let mut captures = cursor.captures(&query, node, source.as_bytes()); - let mut has_constructor = false; - while let Some((m, _)) = captures.next() { - let decl = m.captures[0].node; - let Some(name_node) = decl.child_by_field_name("declarator") else { continue }; - if source[name_node.byte_range()].trim() != name { continue; } - has_constructor = true; - let params = get_parameters(decl, source); - if params.is_empty() { - return true; - } - if params.len() == fields.len() && params.iter().zip(fields).all(|(p, f)| normalized_type(&p.type_name) == normalized_type(&f.typename)) { - return true; - } - } - !has_constructor -} - -fn get_class(node: tree_sitter::Node, source: &str, file_path: &str) -> Option { - let name = node - .child_by_field_name("name") - .map(|n| source[n.byte_range()].to_string())?; - - let all_attrs = get_attributes(node, source); - if !all_attrs.iter().any(|a| a.name == "ToastNode") { - return None; - } - let attributes: Vec = all_attrs - .into_iter() - .filter(|a| a.name != "ToastNode") - .collect(); - - Some(Class { - name, - namespace: get_namespace(node, source), - parent: get_parent(node, source), - attributes: attributes.clone(), - attrib_json: attrs_to_json(&attributes), - functions: get_functions(node, source), - methods: get_methods(node, source), - fields: get_fields(node, source), - signals: get_signals(node, source), - source_file: file_path.to_string(), - }) -} - -fn get_namespace(node: tree_sitter::Node, source: &str) -> Option { - let mut current = node.parent(); - while let Some(p) = current { - if p.kind() == "namespace_definition" - && let Some(name_node) = p.child_by_field_name("name") - { - return Some(source[name_node.byte_range()].to_string()); - } - current = p.parent(); - } - None -} - -fn get_parent(node: tree_sitter::Node, source: &str) -> Option { - for child in node.children(&mut node.walk()) { - if child.kind() != "base_class_clause" { - continue; - } - for inner in child.children(&mut child.walk()) { - match inner.kind() { - "qualified_identifier" => { - let full = &source[inner.byte_range()]; - return if let Some(pos) = full.rfind("::") { - Some(Parent { - name: full[pos + 2..].to_string(), - namespace: Some(full[..pos].to_string()), - }) - } else { - Some(Parent { - name: full.to_string(), - namespace: None, - }) - }; - } - "type_identifier" => { - return Some(Parent { - name: source[inner.byte_range()].to_string(), - namespace: None, - }); - } - _ => {} - } - } - } - None -} - -fn get_functions(node: tree_sitter::Node, source: &str) -> Vec { - // must match TickFunctionList in reflect.hpp; add new lifecycle methods here too - const TICK_FUNCTIONS: &[&str] = &[ - "editorTick", - "init", - "begin", - "earlyTick", - "tick", - "physicsTick", - "postPhysics", - "lateTick", - "end", - "destroy", - "onEnable", - "onDisable", - "load", - "save", - ]; - - let query = Query::new( - &tree_sitter_cpp::LANGUAGE.into(), - "(field_identifier) @field", - ) - .unwrap(); - let mut cursor = QueryCursor::new(); - let mut captures = cursor.captures(&query, node, source.as_bytes()); - - let mut functions = Vec::new(); - while let Some((m, _)) = captures.next() { - let field_node = m.captures[0].node; - if let Some(parent) = field_node.parent() - && parent.kind() == "function_declarator" - && parent.parent().is_some() - { - let name = source[field_node.byte_range()].to_string(); - if TICK_FUNCTIONS.contains(&name.as_str()) && !functions.contains(&name) { - functions.push(name); - } - } - } - functions -} - -fn get_methods(node: tree_sitter::Node, source: &str) -> Vec { - let query = Query::new( - &tree_sitter_cpp::LANGUAGE.into(), - "(function_declarator) @fn", - ) - .unwrap(); - let mut cursor = QueryCursor::new(); - let mut captures = cursor.captures(&query, node, source.as_bytes()); - - let mut methods = Vec::new(); - while let Some((m, _)) = captures.next() { - let func_decl = m.captures[0].node; - - let Some(name_node) = func_decl.child_by_field_name("declarator") else { - continue; - }; - if name_node.kind() != "field_identifier" { - continue; - } - - let Some(decl) = enclosing_declaration(func_decl) else { - continue; - }; - let all_attrs = get_attributes(decl, source); - if !all_attrs.iter().any(|a| a.name == "Reflect") { - continue; - } - let attributes: Vec = all_attrs - .into_iter() - .filter(|a| a.name != "Reflect") - .collect(); - - let name = source[name_node.byte_range()].to_string(); - if methods.iter().any(|f: &Function| f.name == name) { - continue; - } - - methods.push(Function { - name, - return_type: get_return_type(decl, func_decl, source), - parameters: get_parameters(func_decl, source), - is_const: is_const_method(func_decl, source), - attributes: attributes.clone(), - attrib_json: attrs_to_json(&attributes), - }); - } - methods -} - -fn enclosing_declaration(func_decl: tree_sitter::Node) -> Option { - let mut current = func_decl.parent(); - while let Some(p) = current { - match p.kind() { - "field_declaration" | "function_definition" | "declaration" => return Some(p), - _ => current = p.parent(), - } - } - None -} - -fn get_return_type(decl: tree_sitter::Node, func_decl: tree_sitter::Node, source: &str) -> String { - let base = decl - .child_by_field_name("type") - .map(|t| source[t.byte_range()].trim().to_string()) - .unwrap_or_default(); - - if base == "auto" { - for child in func_decl.children(&mut func_decl.walk()) { - if child.kind() == "trailing_return_type" { - if let Some(return_type) = child.named_child(0) { - return source[return_type.byte_range()].trim().to_string(); - } - } - } - } - - let mut suffix = String::new(); - let mut current = decl.child_by_field_name("declarator"); - while let Some(node) = current { - if node.id() == func_decl.id() { - break; - } - match node.kind() { - "pointer_declarator" => suffix.push('*'), - "reference_declarator" => suffix.push('&'), - _ => {} - } - current = node.child_by_field_name("declarator"); - } - - format!("{base}{suffix}") -} - -fn is_const_method(func_decl: tree_sitter::Node, source: &str) -> bool { - for child in func_decl.children(&mut func_decl.walk()) { - if child.kind() == "type_qualifier" && source[child.byte_range()].trim() == "const" { - return true; - } - } - false -} - -fn get_parameters(func_decl: tree_sitter::Node, source: &str) -> Vec { - let Some(params) = func_decl.child_by_field_name("parameters") else { - return Vec::new(); - }; - - let mut result = Vec::new(); - for param in params.children(&mut params.walk()) { - if param.kind() != "parameter_declaration" - && param.kind() != "optional_parameter_declaration" - { - continue; - } - - let default = param - .child_by_field_name("default_value") - .map(|d| source[d.byte_range()].trim().to_string()); - - let name_node = param - .child_by_field_name("declarator") - .and_then(find_identifier); - - let (name, type_name) = if let Some(n) = name_node { - let ty = source[param.start_byte()..n.start_byte()] - .trim() - .to_string(); - (source[n.byte_range()].to_string(), ty) - } else { - // Unnamed parameter: take the type text up to the default value, if any - let end = param - .child_by_field_name("default_value") - .map(|d| d.start_byte()) - .unwrap_or_else(|| param.end_byte()); - let ty = source[param.start_byte()..end] - .trim() - .trim_end_matches('=') - .trim() - .to_string(); - (String::new(), ty) - }; - - result.push(Parameter { - name, - type_name, - default, - }); - } - result -} - -// Finds the first identifier node in a declarator subtree -fn find_identifier(node: tree_sitter::Node) -> Option { - if node.kind() == "identifier" { - return Some(node); - } - for child in node.children(&mut node.walk()) { - if let Some(found) = find_identifier(child) { - return Some(found); - } - } - None -} - -fn get_fields(node: tree_sitter::Node, source: &str) -> Vec { - let query = Query::new( - &tree_sitter_cpp::LANGUAGE.into(), - "(field_identifier) @field", - ) - .unwrap(); - let mut cursor = QueryCursor::new(); - let mut captures = cursor.captures(&query, node, source.as_bytes()); - - let mut fields = Vec::new(); - while let Some((m, _)) = captures.next() { - let field_node = m.captures[0].node; - let Some(parent) = field_node.parent() else { - continue; - }; - if parent.kind() != "field_declaration" { - continue; - } - - // Skip nested struct definitions - if let Some(ty) = parent.child_by_field_name("type") - && ty.kind() == "struct_specifier" - { - continue; - } - - let all_attrs = get_attributes(parent, source); - if !all_attrs.iter().any(|a| a.name == "Reflect") { - continue; - } - let attributes: Vec = all_attrs - .into_iter() - .filter(|a| a.name != "Reflect") - .collect(); - - let type_name = parent - .child_by_field_name("type") - .map(|t| source[t.byte_range()].trim().to_string()) - .unwrap_or_default(); - - let default = parent - .child_by_field_name("default_value") - .map(|d| source[d.byte_range()].trim().to_string()); - - if type_name.contains("Signal<") { - continue; - } - fields.push(Field { - name: source[field_node.byte_range()].to_string(), - typename: type_name.clone(), - field_type: infer_field_type(&type_name), - is_array: type_name.contains("vector<"), - attributes: attributes.clone(), - attrib_json: attrs_to_json(&attributes), - default, - }); - } - fields -} - -fn get_signals(node: tree_sitter::Node, source: &str) -> Vec { - let query = Query::new( - &tree_sitter_cpp::LANGUAGE.into(), - "(field_identifier) @field", - ) - .unwrap(); - let mut cursor = QueryCursor::new(); - let mut captures = cursor.captures(&query, node, source.as_bytes()); - - let mut signals = Vec::new(); - while let Some((m, _)) = captures.next() { - let field_node = m.captures[0].node; - let Some(parent) = field_node.parent() else { - continue; - }; - if parent.kind() != "field_declaration" { - continue; - } - - // Skip nested struct definitions - if let Some(ty) = parent.child_by_field_name("type") - && ty.kind() == "struct_specifier" - { - continue; - } - - let all_attrs = get_attributes(parent, source); - let attributes: Vec = all_attrs.into_iter().collect(); - - let type_name = parent - .child_by_field_name("type") - .map(|t| source[t.byte_range()].trim().to_string()) - .unwrap_or_default(); - - if !type_name.contains("Signal<") { - continue; - } - let template_args = parse_template_args(&type_name); - signals.push(Signal { - name: source[field_node.byte_range()].to_string(), - typename: type_name.clone(), - arguments: template_args, - attrs_list: attributes.clone(), - attrib_json: attrs_to_json(&attributes), - }); - } - signals -} - -fn get_attributes(node: tree_sitter::Node, source: &str) -> Vec { - // two-level walk: attribute_declaration wraps one or more attribute nodes - let mut attributes = Vec::new(); - - for list in node.children(&mut node.walk()) { - if list.kind() != "attribute_declaration" { - continue; - } - for attr_node in list.children(&mut list.walk()) { - if attr_node.kind() != "attribute" { - continue; - } - let Some(name_node) = attr_node.child_by_field_name("name") else { - continue; - }; - let name = source[name_node.byte_range()].to_string(); - - let mut args = Vec::new(); - if let Some(arg_list) = name_node.next_named_sibling() { - for arg in arg_list.children(&mut arg_list.walk()) { - if !arg.is_named() { - continue; - } - args.push(clean_argument(&source[arg.byte_range()])); - } - } - - attributes.push(Attribute { name, args }); - } - } - attributes -} - -// tree-sitter includes surrounding double-quotes in string literal nodes; strip them -fn clean_argument(arg: &str) -> String { - let trimmed = arg.trim(); - if (trimmed.starts_with('"') && trimmed.ends_with('"')) - || (trimmed.starts_with('\'') && trimmed.ends_with('\'')) - { - trimmed[1..trimmed.len() - 1].to_string() - } else { - trimmed.to_string() - } -} - -pub fn attrs_to_json(attrs: &[Attribute]) -> json_t { - let map: serde_json::Map = attrs - .iter() - .map(|a| (a.name.clone(), serde_json::json!(a.args))) - .collect(); - json_t::Object(map) -} - -fn infer_field_type(type_name: &str) -> FieldType { - let trimmed = type_name.trim(); - - // std::vector is classified by its element type T; the is_array flag records the vector-ness. - // Without this, "std::vector" falls through to the Int fallback and the serializer - // any_casts it to std::vector, throwing std::bad_any_cast at save time. - let element = if trimmed.contains("vector<") { - parse_template_args(trimmed) - .into_iter() - .next() - .unwrap_or_default() - } else { - trimmed.to_string() - }; - - let base = element - .trim() - .trim_start_matches("toast::") - .trim_start_matches("std::") - .trim_start_matches("glm::"); - - if element.contains("Handle<") { - return FieldType::Uid; - } - if base.starts_with("Box<") { - return FieldType::Uid; - } - - match base { - "bool" => FieldType::Bool, - "int" | "int8_t" | "int16_t" | "int32_t" | "int64_t" | "uint8_t" | "uint16_t" - | "uint32_t" | "uint64_t" => FieldType::Int, - "float" => FieldType::Float, - "string" => FieldType::String, - "double" => FieldType::Double, - "UID" => FieldType::Uid, - "vec2" => FieldType::Vec2, - "vec3" => FieldType::Vec3, - "vec4" => FieldType::Vec4, - "quat" | "quaternion" => FieldType::Quaternion, - _ => FieldType::Int, // unknown types silently become Int; accessor compiles but the inspector widget will be wrong - } -} - -fn parse_template_args(type_name: &str) -> Vec { - // Find the opening '<' and trailing '>' - let Some(start) = type_name.find('<') else { - return Vec::new(); - }; - let Some(end) = type_name.rfind('>') else { - return Vec::new(); - }; - - if start >= end { - return Vec::new(); - } - - let inner = &type_name[start + 1..end]; - let mut args = Vec::new(); - let mut current = String::new(); - let mut depth = 0; - - for c in inner.chars() { - match c { - '<' => { - depth += 1; - current.push(c); - } - '>' => { - depth -= 1; - current.push(c); - } - ',' if depth == 0 => { - let trimmed = current.trim(); - if !trimmed.is_empty() { - args.push(trimmed.to_string()); - } - current.clear(); - } - _ => { - current.push(c); - } - } - } - - let trimmed = current.trim(); - if !trimmed.is_empty() { - args.push(trimmed.to_string()); - } - - args -} diff --git a/tools/reflection_generator/templates/node.generated.hpp.jinja2 b/tools/reflection_generator/templates/node.generated.hpp.jinja2 deleted file mode 100644 index 37f04db47..000000000 --- a/tools/reflection_generator/templates/node.generated.hpp.jinja2 +++ /dev/null @@ -1,170 +0,0 @@ -// ============================================================ -// AUTO-GENERATED FILE - DO NOT MODIFY DIRECTLY -// Changes will not persist -// ============================================================ - -#pragma once -#include -#include -#include -#include -{% if has_asset_handle %}#include -{% endif %} -{% if parent_snake_name %}#include "{{ parent_snake_name }}.generated.hpp" -{% endif %} -#include <{{ source_file }}> -{% macro dyn_cast(p, i) %}{% if "Box<" in p.type %}std::any_cast>(args[{{ i }}]).as<{{ p.type | replace("toast::Box<", "") | replace("Box<", "") | replace("const ", "") | replace("&", "") | replace(">", "") | trim }}>(){% elif "Handle<" in p.type %}assets::load::asset_type>(std::any_cast(args[{{ i }}])){% else %}std::any_cast>(args[{{ i }}]){% endif %}{% endmacro %} -{% macro dyn_arg(p, i) %}{% if p.default is none %}{{ dyn_cast(p, i) }}{% else %}((args.size() > {{ i }} && args[{{ i }}].has_value()) ? static_cast>({{ dyn_cast(p, i) }}) : static_cast>({{ p.default }})){% endif %}{% endmacro %} - -namespace toast { -namespace _detail { - -{% for f in all_fields_flat %} - struct {{ snake_name }}_{{ f.name }}_tag { typedef {{ f.typename }} {{ qualified_name }}::*type; }; - template struct Robber<{{ snake_name }}_{{ f.name }}_tag, &{{ qualified_name }}::{{ f.member_name }}>; -{% endfor %} - -{% for fn in active_tick_fns %} - struct {{ snake_name }}_{{ fn.flag }}_tag { typedef void ({{ qualified_name }}::*type)(); }; - template struct Robber<{{ snake_name }}_{{ fn.flag }}_tag, &{{ qualified_name }}::{{ fn.method }}>; - - inline void {{ snake_name }}_{{ fn.flag }}(void* obj) { (static_cast<{{ qualified_name }}*>(obj)->*Accessor<{{ snake_name }}_{{ fn.flag }}_tag>::member)(); } -{% endfor %} -{% for m in methods %} - struct {{ snake_name }}_method_{{ m.name }}_tag { typedef {{ m.return_type }} ({{ qualified_name }}::*type)({% for p in m.parameters %}{{ p.type }}{% if not loop.last %}, {% endif %}{% endfor %}){% if m.is_const %} const{% endif %}; }; - template struct Robber<{{ snake_name }}_method_{{ m.name }}_tag, static_cast<{{ m.return_type }} ({{ qualified_name }}::*)({% for p in m.parameters %}{{ p.type }}{% if not loop.last %}, {% endif %}{% endfor %}){% if m.is_const %} const{% endif %}>(&{{ qualified_name }}::{{ m.name }})>; - - inline auto {{ snake_name }}_method_{{ m.name }}(void* obj{% for p in m.parameters %}, std::decay_t<{{ p.type }}> {{ p.arg_name }}{% endfor %}) { - return (static_cast<{{ qualified_name }}*>(obj)->*Accessor<{{ snake_name }}_method_{{ m.name }}_tag>::member)({% for p in m.parameters %}{{ p.arg_name }}{% if not loop.last %}, {% endif %}{% endfor %}); - } - - inline std::any {{ snake_name }}_method_{{ m.name }}_dyn(void* obj, std::span args) { - auto* self = static_cast<{{ qualified_name }}*>(obj); -{% if m.return_type == "void" %} - (self->*Accessor<{{ snake_name }}_method_{{ m.name }}_tag>::member)({% for p in m.parameters %}{{ dyn_arg(p, loop.index0) }}{% if not loop.last %}, {% endif %}{% endfor %}); - return std::any{}; -{% else %} - return std::any{ (self->*Accessor<{{ snake_name }}_method_{{ m.name }}_tag>::member)({% for p in m.parameters %}{{ dyn_arg(p, loop.index0) }}{% if not loop.last %}, {% endif %}{% endfor %}) }; -{% endif %} - } -{% endfor %} -{% if not is_interface %} - inline {{ qualified_name }}* {{ snake_name }}_construct() { return new {{ qualified_name }}(); } - inline void {{ snake_name }}_delete({{ qualified_name }}* obj) { delete obj; } -{% endif %} -} - -template<> -struct Reflect<{{ qualified_name }}> { - static constexpr std::string_view name = "{{ qualified_name }}"; - - inline static const std::array _all_field_info = {{ '{{' }} -{% for f in all_fields_flat %} - { - .name = "{{ f.name }}", - .type = "{{ f.typename }}", - .value_type = FieldType::{{ f.field_type }}, - .attributes = {{ '{{' }}{% for a in f.attrs_list %}{"{{ a.name }}", {{ '{' }}{% for v in a.args %}"{{ v }}"{% if not loop.last %}, {% endif %}{% endfor %}{{ '}' }}}{% if not loop.last %}, {% endif %}{% endfor %}{{ '}}' }}, - .is_array = {{ f.is_array | lower }}, - .get = &{% if f.is_asset_handle and f.is_array %}AssetArrayFieldAccess{% elif f.is_asset_handle %}AssetFieldAccess{% elif f.is_enum %}EnumFieldAccess{% else %}FieldAccess{% endif %}<{{ qualified_name }}, {{ f.typename }}, _detail::{{ snake_name }}_{{ f.name }}_tag>::get, - .set = &{% if f.is_asset_handle and f.is_array %}AssetArrayFieldAccess{% elif f.is_asset_handle %}AssetFieldAccess{% elif f.is_enum %}EnumFieldAccess{% else %}FieldAccess{% endif %}<{{ qualified_name }}, {{ f.typename }}, _detail::{{ snake_name }}_{{ f.name }}_tag>::set, - }{% if not loop.last %},{% endif %} - -{% endfor %} - {{ '}}' }}; - - inline static const std::array signal_info = {{ '{{' }} -{% for s in signals %} - { - .name = "{{ s.name }}", - .type = "{{ s.typename }}", - .args = {{ '{{' }}{% for a in s.arguments %}&typeid(std::decay_t<{{ a }}>){% if not loop.last %}, {% endif %}{% endfor %}{{ '}}' }}, - .attributes = {{ '{{' }}{% for a in s.attrs_list %}{"{{ a.name }}", {{ '{' }}{% for v in a.args %}"{{ v }}"{% if not loop.last %}, {% endif %}{% endfor %}{{ '}' }}}{% if not loop.last %}, {% endif %}{% endfor %}{{ '}}' }}, - .get = {{ s.typename }}::get<{{ qualified_name }},&{{ qualified_name }}::{{ s.name }}>, - .connect = {{ s.typename }}::connect<{{ qualified_name }},&{{ qualified_name }}::{{ s.name }}>, - .disconnect = {{ s.typename }}::disconnect<{{ qualified_name }},&{{ qualified_name }}::{{ s.name }}>, - .clear = {{ s.typename }}::clear<{{ qualified_name }},&{{ qualified_name }}::{{ s.name }}>, - .fire = {{ s.typename }}::fire<{{ qualified_name }},&{{ qualified_name }}::{{ s.name }}>, - }{% if not loop.last %},{% endif %} - -{% endfor %} - {{ '}}' }}; - - - inline static const std::array field_info = {{ '{{' }} -{% for idx in global_field_indices %} - &_all_field_info[{{ idx }}], -{% endfor %} - {{ '}}' }}; -{% for g in groups %} - - inline static const std::array {{ g.snake_name }}_group_fields = {{ '{{' }} - {% for idx in g.field_indices %}&_all_field_info[{{ idx }}], {% endfor %} - {{ '}}' }}; -{% for sg in g.subgroups %} - inline static const std::array {{ g.snake_name }}_{{ sg.snake_name }}_subgroup_fields = {{ '{{' }} - {% for idx in sg.field_indices %}&_all_field_info[{{ idx }}], {% endfor %} - {{ '}}' }}; - inline static const SubgroupInfo {{ g.snake_name }}_{{ sg.snake_name }}_subgroup = { - .name = "{{ sg.name }}", .fields = {{ g.snake_name }}_{{ sg.snake_name }}_subgroup_fields, - }; -{% endfor %} - inline static const std::array {{ g.snake_name }}_subgroups = {{ '{{' }} - {% for sg in g.subgroups %}{{ g.snake_name }}_{{ sg.snake_name }}_subgroup, {% endfor %} - {{ '}}' }}; - inline static const GroupInfo {{ g.snake_name }}_group = { - .name = "{{ g.name }}", - .fields = {{ g.snake_name }}_group_fields, - .subgroups = {{ g.snake_name }}_subgroups, - }; -{% endfor %} - - inline static const std::array group_info = {{ '{{' }} - {% for g in groups %}{{ g.snake_name }}_group, {% endfor %} - {{ '}}' }}; -{% for m in methods %} - inline static const std::array {{ m.name }}_param_info = {{ '{{' }} - {% for p in m.parameters %}{ .name = "{{ p.name }}", .type = "{{ p.type }}", .default_value = {% if p.default_escaped is none %}std::nullopt{% else %}std::optional{"{{ p.default_escaped }}"}{% endif %}, .type_id = &typeid(std::decay_t<{{ p.type }}>) }, {% endfor %} - {{ '}}' }}; -{% endfor %} - - inline static const std::array _method_info = {{ '{{' }} - {% for m in methods %} - { - .name = "{{ m.name }}", - .return_type = "{{ m.return_type }}", - .return_type_id = &typeid(std::decay_t<{{ m.return_type }}>), - .parameters = {{ m.name }}_param_info, - .attributes = {{ '{{' }}{% for a in m.attrs_list %}{"{{ a.name }}", {{ '{' }}{% for v in a.args %}"{{ v }}"{% if not loop.last %}, {% endif %}{% endfor %}{{ '}' }}}{% if not loop.last %}, {% endif %}{% endfor %}{{ '}}' }}, - .invoke = reinterpret_cast(&_detail::{{ snake_name }}_method_{{ m.name }}), - .invoke_dynamic = reinterpret_cast(&_detail::{{ snake_name }}_method_{{ m.name }}_dyn), - }, - {% endfor %} - {{ '}}' }}; - - static constexpr TickFunctions tick_functions = { - .list = {% if active_tick_fns %}{% for fn in active_tick_fns %}TickFunctionList::{{ fn.flag }}{% if not loop.last %} | {% endif %}{% endfor %}{% else %}TickFunctionList::none{% endif %}, -{% for fn in active_tick_fns %} - .{{ fn.flag }} = &_detail::{{ snake_name }}_{{ fn.flag }}, -{% endfor %} - }; - -{% if split_typeinfo %} - TOAST_API static const toast::NodeInfo type_info; -{% else %} - inline static const toast::NodeInfo type_info = { - .type = name, - .base_type = {% if parent_qualified_name %}&Reflect<{{ parent_qualified_name }}>::type_info{% else %}nullptr{% endif %}, - .signals = signal_info, - .all_fields = _all_field_info, - .fields = field_info, - .groups = group_info, - .methods = _method_info, - .functions = tick_functions, - .construct = {% if is_interface %}nullptr{% else %}reinterpret_cast(&_detail::{{ snake_name }}_construct){% endif %}, - .destroy = {% if is_interface %}nullptr{% else %}reinterpret_cast(&_detail::{{ snake_name }}_delete){% endif %}, - }; -{% endif %} -}; - -} // namespace toast diff --git a/tools/reflection_generator/templates/node.type_info.cpp.jinja2 b/tools/reflection_generator/templates/node.type_info.cpp.jinja2 deleted file mode 100644 index 83dd3ff38..000000000 --- a/tools/reflection_generator/templates/node.type_info.cpp.jinja2 +++ /dev/null @@ -1,30 +0,0 @@ -// ============================================================ -// AUTO-GENERATED FILE - DO NOT MODIFY DIRECTLY -// Changes will not persist -// ============================================================ - -// clang-format off -#include "{{ snake_name }}.generated.hpp" -// clang-format on - -namespace toast { - -TOAST_API const toast::NodeInfo Reflect<{{ qualified_name }}>::type_info = { - .type = name, - .base_type = {% if parent_qualified_name %}&Reflect<{{ parent_qualified_name }}>::type_info{% else %}nullptr{% endif %}, - .signals = signal_info, - .all_fields = _all_field_info, - .fields = field_info, - .groups = group_info, - .methods = _method_info, - .functions = tick_functions, - .construct = {% if is_interface %}nullptr{% else %}reinterpret_cast(&_detail::{{ snake_name }}_construct){% endif %}, - .destroy = {% if is_interface %}nullptr{% else %}reinterpret_cast(&_detail::{{ snake_name }}_delete){% endif %}, -}; - -template<> -TOAST_API auto NodeTypeInfo<{{ qualified_name }}>::get() noexcept -> const NodeInfo* { - return &Reflect<{{ qualified_name }}>::type_info; -} - -} // namespace toast diff --git a/tools/reflection_generator/templates/reflect.generated.cpp.jinja2 b/tools/reflection_generator/templates/reflect.generated.cpp.jinja2 deleted file mode 100644 index 9862f8fcd..000000000 --- a/tools/reflection_generator/templates/reflect.generated.cpp.jinja2 +++ /dev/null @@ -1,43 +0,0 @@ -// ============================================================ -// AUTO-GENERATED FILE - DO NOT MODIFY DIRECTLY -// Changes will not persist -// ============================================================ - -// clang-format off -{% for node in nodes %} -#include "{{ node.snake_name }}.generated.hpp" -{% endfor %} -{% for event in events %} -#include <{{ event.source_file }}> -{% endfor %} -#include -#include -#include -#include -#include -// clang-format on - -namespace toast { -template -auto nodeTypeInfo() noexcept -> const NodeInfo* { - return &Reflect::type_info; -} -{% for node in nodes %} -template {% if split_typeinfo %}TOAST_API {% endif %}auto nodeTypeInfo<{{ node.qualified_name }}>() noexcept -> const NodeInfo*; -{% endfor %} - -void {{ register_fn }}() { - static const std::array all_types = {{ '{{' }} -{% for node in nodes %} - &Reflect<{{ node.qualified_name }}>::type_info, -{% endfor %} - {{ '}}' }}; - for (const auto* info : all_types) { - NodeRegistry::registerNode(info); - } - {% for event in events %} - scripting::registerLuaEvent<{{ event.qualified_name }}, {{ "true" if event.sendable else "false" }}>("{{ event.name }}"{% for field in event.fields %}, scripting::luaEventField<{{ event.qualified_name }}>("{{ field.name }}", "{{ field.typename }}", [](const {{ event.qualified_name }}& e) -> const auto& { return e.{{ field.name }}; }, [](auto& e, auto&& v) { e.{{ field.name }} = std::forward(v); }){% endfor %}); - {% endfor %} - TOAST_INFO("Reflection", "Registered {} types ({{ register_fn }})", all_types.size()); -} -} // namespace toast diff --git a/tools/reflection_generator/tests/common.rs b/tools/reflection_generator/tests/common.rs deleted file mode 100644 index a847f6339..000000000 --- a/tools/reflection_generator/tests/common.rs +++ /dev/null @@ -1,122 +0,0 @@ -use serde_json::{Value as JsonValue, json}; -use std::fmt; - -/// Deep JSON comparison with path tracking for better error messages -pub struct JsonComparator; - -#[derive(Debug)] -pub struct JsonDiff { - pub path: String, - pub reason: String, -} - -impl fmt::Display for JsonDiff { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{}: {}", self.path, self.reason) - } -} - -impl JsonComparator { - /// Compare two JSON values and return detailed differences - pub fn compare(actual: &JsonValue, expected: &JsonValue, path: &str) -> Result<(), JsonDiff> { - match (actual, expected) { - (JsonValue::Null, JsonValue::Null) => Ok(()), - (JsonValue::Bool(a), JsonValue::Bool(e)) if a == e => Ok(()), - (JsonValue::Bool(a), JsonValue::Bool(e)) => Err(JsonDiff { - path: path.to_string(), - reason: format!("bool mismatch: {} != {}", a, e), - }), - (JsonValue::Number(a), JsonValue::Number(e)) if a == e => Ok(()), - (JsonValue::Number(a), JsonValue::Number(e)) => Err(JsonDiff { - path: path.to_string(), - reason: format!("number mismatch: {} != {}", a, e), - }), - (JsonValue::String(a), JsonValue::String(e)) if a == e => Ok(()), - (JsonValue::String(a), JsonValue::String(e)) => Err(JsonDiff { - path: path.to_string(), - reason: format!("string mismatch: '{}' != '{}'", a, e), - }), - (JsonValue::Array(a), JsonValue::Array(e)) => { - if a.len() != e.len() { - return Err(JsonDiff { - path: path.to_string(), - reason: format!("array length mismatch: {} != {}", a.len(), e.len()), - }); - } - for (i, (av, ev)) in a.iter().zip(e.iter()).enumerate() { - Self::compare(av, ev, &format!("{}[{}]", path, i))?; - } - Ok(()) - } - (JsonValue::Object(a), JsonValue::Object(e)) => { - // Check all expected keys exist and match - for key in e.keys() { - let av = a.get(key).ok_or_else(|| JsonDiff { - path: format!("{}.{}", path, key), - reason: "missing key in actual".to_string(), - })?; - let ev = &e[key]; - Self::compare(av, ev, &format!("{}.{}", path, key))?; - } - // Check no extra keys in actual - for key in a.keys() { - if !e.contains_key(key) { - return Err(JsonDiff { - path: format!("{}.{}", path, key), - reason: "unexpected extra key in actual".to_string(), - }); - } - } - Ok(()) - } - _ => Err(JsonDiff { - path: path.to_string(), - reason: format!( - "type mismatch: {} vs {}", - json_type_str(actual), - json_type_str(expected) - ), - }), - } - } -} - -fn json_type_str(v: &JsonValue) -> &'static str { - match v { - JsonValue::Null => "null", - JsonValue::Bool(_) => "bool", - JsonValue::Number(_) => "number", - JsonValue::String(_) => "string", - JsonValue::Array(_) => "array", - JsonValue::Object(_) => "object", - } -} - -#[allow(dead_code)] -pub fn minimal_node_json(name: &str, namespace: Option<&str>) -> JsonValue { - json!({ - "name": name, - "namespace": namespace, - "parent": null, - "source_file": "test.hpp", - "attributes": {}, - "functions": { - "editor_tick": false, - "init": false, - "begin": false, - "early_tick": false, - "tick": false, - "physics_tick": false, - "post_physics": false, - "late_tick": false, - "end": false, - "destroy": false, - "on_enable": false, - "on_disable": false, - "load": false, - "save": false, - }, - "global_fields": [], - "groups": [] - }) -} diff --git a/tools/reflection_generator/tests/debug_parser.rs b/tools/reflection_generator/tests/debug_parser.rs deleted file mode 100644 index 75efe4e66..000000000 --- a/tools/reflection_generator/tests/debug_parser.rs +++ /dev/null @@ -1,35 +0,0 @@ -use reflection_generator::parse; - -#[test] -fn debug_parse_simple() { - let source = r#" -namespace toast { -class [[ToastNode]] SimpleNode { -public: - [[Reflect, Group("Transform")]] int m_x = 0; - [[Reflect]] std::string m_name; - - void tick() {} -}; -} -"#; - - let classes = parse(source, "debug_parser.hpp"); - eprintln!("Found {} classes", classes.len()); - for class in &classes { - eprintln!("Class: {}", class.name); - eprintln!(" Namespace: {:?}", class.namespace); - eprintln!( - " Attributes: {} ({:?})", - class.attributes.len(), - class.attributes.iter().map(|a| &a.name).collect::>() - ); - eprintln!(" Fields: {}", class.fields.len()); - for field in &class.fields { - eprintln!(" - {}: {}", field.name, field.typename); - } - eprintln!(" Functions: {:?}", class.functions); - } - - assert!(!classes.is_empty(), "Parser should find at least one class"); -} diff --git a/tools/reflection_generator/tests/debug_tree.rs b/tools/reflection_generator/tests/debug_tree.rs deleted file mode 100644 index 52c342ddd..000000000 --- a/tools/reflection_generator/tests/debug_tree.rs +++ /dev/null @@ -1,31 +0,0 @@ -use tree_sitter::Parser; - -#[test] -fn debug_tree_simple() { - let source = r#"class [[ToastNode]] SimpleNode { -public: - int m_x; -};"#; - - let mut parser = Parser::new(); - parser - .set_language(&tree_sitter_cpp::LANGUAGE.into()) - .expect("Language error"); - let tree = parser.parse(source, None).unwrap(); - - print_tree(&tree.root_node(), source, 0); -} - -fn print_tree(node: &tree_sitter::Node, source: &str, indent: usize) { - let kind = node.kind(); - let text = if node.child_count() == 0 { - format!(" \"{}\"", &source[node.byte_range()]) - } else { - String::new() - }; - eprintln!("{}{}{}", " ".repeat(indent * 2), kind, text); - - for child in node.children(&mut node.walk()) { - print_tree(&child, source, indent + 1); - } -} diff --git a/tools/reflection_generator/tests/events_test.rs b/tools/reflection_generator/tests/events_test.rs deleted file mode 100644 index b7ec20bf5..000000000 --- a/tools/reflection_generator/tests/events_test.rs +++ /dev/null @@ -1,68 +0,0 @@ -use reflection_generator::{generate_event_lua_stubs, parse_events}; - -#[test] -fn discovers_both_event_base_spellings_and_public_fields() { - let source = r#" -namespace event { -struct Resize : Event { - int width, height; - Resize(int width, int height) : width(width), height(height) {} -}; -struct Scale : event::Event { - float value; - explicit Scale(float value) : value(value) {} -private: - int hidden; -}; -} -"#; - let events = parse_events(source, "events.hpp"); - assert_eq!(events.len(), 2); - assert_eq!(events[0].fields.len(), 2); - assert_eq!(events[0].fields[0].lua_type.as_deref(), Some("integer")); - assert_eq!(events[1].fields.len(), 1); - assert!(events.iter().all(|e| e.constructor_compatible && e.supported)); - let stubs = generate_event_lua_stubs(&events); - assert!(stubs.contains("---@field Resize EventDescriptor")); - assert!(stubs.contains("---@field width integer")); -} - -#[test] -fn reports_unsupported_fields_and_incompatible_constructors() { - let source = r#" -struct Unsupported : Event { - Widget value; - Unsupported(Widget value) : value(value) {} -}; -struct WrongCtor : Event { - int value; - explicit WrongCtor(float other) : value(0) {} -}; -"#; - let events = parse_events(source, "events.hpp"); - assert_eq!(events.len(), 2); - assert!(events[0].skip_reason.as_deref().unwrap().contains("unsupported type")); - assert!(events[1].supported && !events[1].sendable); -} - -#[test] -fn accepts_aggregate_events_with_node_and_enum_fields() { - let source = r#" -enum class DamageType : uint8_t { physical, bullet }; -struct DamageEvent : public event::Event { - toast::Box target; - toast::Box attacker; - float amount = 0.0f; - DamageType type = DamageType::physical; -}; -struct Defaulted : Event { - int value; - Defaulted() : value(0) {} -}; -"#; - let events = parse_events(source, "damage_event.hpp"); - assert_eq!(events.len(), 2); - assert!(events.iter().all(|e| e.supported), "{:?}", events.iter().map(|e| &e.skip_reason).collect::>()); - let types: Vec<_> = events[0].fields.iter().map(|f| f.lua_type.as_deref().unwrap()).collect(); - assert_eq!(types, ["Node", "Node", "number", "integer"]); -} diff --git a/tools/reflection_generator/tests/expected_outputs/01_simple.json b/tools/reflection_generator/tests/expected_outputs/01_simple.json deleted file mode 100644 index 9bda10ea4..000000000 --- a/tools/reflection_generator/tests/expected_outputs/01_simple.json +++ /dev/null @@ -1,107 +0,0 @@ -[ - { - "attributes": {}, - "fields": [ - { - "attributes": { - "Group": [ - "Transform" - ] - }, - "default": "0", - "field_type": "int_t", - "is_array": false, - "name": "m_x", - "typename": "int" - }, - { - "attributes": { - "Group": [ - "Transform" - ] - }, - "default": "0", - "field_type": "int_t", - "is_array": false, - "name": "m_y", - "typename": "int" - }, - { - "attributes": {}, - "default": null, - "field_type": "string_t", - "is_array": false, - "name": "m_name", - "typename": "std::string" - } - ], - "functions": [ - "tick" - ], - "global_fields": [ - { - "attributes": {}, - "default": null, - "field_type": "string_t", - "is_array": false, - "name": "m_name", - "typename": "std::string" - } - ], - "groups": [ - { - "fields": [ - { - "attributes": { - "Group": [ - "Transform" - ] - }, - "default": "0", - "field_type": "int_t", - "is_array": false, - "name": "m_x", - "typename": "int" - }, - { - "attributes": { - "Group": [ - "Transform" - ] - }, - "default": "0", - "field_type": "int_t", - "is_array": false, - "name": "m_y", - "typename": "int" - } - ], - "name": "Transform", - "subgroups": [] - } - ], - "is_interface": false, - "methods": [], - "name": "SimpleNode", - "namespace": "toast", - "parent": null, - "signals": [], - "source_file": "01_simple.hpp", - "tick_functions": { - "begin": false, - "destroy": false, - "early_tick": false, - "end": false, - "init": false, - "late_tick": false, - "load": false, - "on_disable": false, - "on_enable": false, - "physics_tick": false, - "post_physics": false, - "editor_tick": false, - "save": false, - "tick": true - } - } -] \ No newline at end of file diff --git a/tools/reflection_generator/tests/expected_outputs/02_inherited.json b/tools/reflection_generator/tests/expected_outputs/02_inherited.json deleted file mode 100644 index 1a8df35d5..000000000 --- a/tools/reflection_generator/tests/expected_outputs/02_inherited.json +++ /dev/null @@ -1,106 +0,0 @@ -[ - { - "attributes": {}, - "fields": [ - { - "attributes": { - "Group": [ - "Stats" - ] - }, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_health", - "typename": "int" - }, - { - "attributes": { - "Group": [ - "Stats" - ], - "Subgroup": [ - "Damage" - ] - }, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_armor", - "typename": "int" - } - ], - "functions": [ - "init", - "tick" - ], - "global_fields": [], - "groups": [ - { - "fields": [ - { - "attributes": { - "Group": [ - "Stats" - ] - }, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_health", - "typename": "int" - } - ], - "name": "Stats", - "subgroups": [ - { - "fields": [ - { - "attributes": { - "Group": [ - "Stats" - ], - "Subgroup": [ - "Damage" - ] - }, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_armor", - "typename": "int" - } - ], - "name": "Damage" - } - ] - } - ], - "is_interface": false, - "methods": [], - "name": "Player", - "namespace": "game", - "parent": { - "name": "Node", - "namespace": "toast" - }, - "signals": [], - "source_file": "02_inherited.hpp", - "tick_functions": { - "begin": false, - "destroy": false, - "early_tick": false, - "end": false, - "init": true, - "late_tick": false, - "load": false, - "on_disable": false, - "on_enable": false, - "physics_tick": false, - "post_physics": false, - "editor_tick": false, - "save": false, - "tick": true - } - } -] diff --git a/tools/reflection_generator/tests/expected_outputs/03_no_fields.json b/tools/reflection_generator/tests/expected_outputs/03_no_fields.json deleted file mode 100644 index 0f90e5b43..000000000 --- a/tools/reflection_generator/tests/expected_outputs/03_no_fields.json +++ /dev/null @@ -1,37 +0,0 @@ -[ - { - "attributes": {}, - "fields": [], - "functions": [ - "editorTick", - "tick", - "lateTick", - "destroy" - ], - "global_fields": [], - "groups": [], - "is_interface": false, - "methods": [], - "name": "TickOnlyNode", - "namespace": null, - "parent": null, - "signals": [], - "source_file": "03_no_fields.hpp", - "tick_functions": { - "begin": false, - "destroy": true, - "early_tick": false, - "end": false, - "init": false, - "late_tick": true, - "load": false, - "on_disable": false, - "on_enable": false, - "editor_tick": true, - "physics_tick": false, - "post_physics": false, - "save": false, - "tick": true - } - } -] \ No newline at end of file diff --git a/tools/reflection_generator/tests/expected_outputs/04_no_ticks.json b/tools/reflection_generator/tests/expected_outputs/04_no_ticks.json deleted file mode 100644 index fadcda82d..000000000 --- a/tools/reflection_generator/tests/expected_outputs/04_no_ticks.json +++ /dev/null @@ -1,66 +0,0 @@ -[ - { - "attributes": {}, - "fields": [ - { - "attributes": {}, - "default": null, - "field_type": "float_t", - "is_array": false, - "name": "m_value", - "typename": "float" - }, - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": true, - "name": "m_items", - "typename": "std::vector" - } - ], - "functions": [], - "global_fields": [ - { - "attributes": {}, - "default": null, - "field_type": "float_t", - "is_array": false, - "name": "m_value", - "typename": "float" - }, - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": true, - "name": "m_items", - "typename": "std::vector" - } - ], - "groups": [], - "is_interface": false, - "methods": [], - "name": "DataNode", - "namespace": "data", - "parent": null, - "signals": [], - "source_file": "04_no_ticks.hpp", - "tick_functions": { - "begin": false, - "destroy": false, - "early_tick": false, - "end": false, - "init": false, - "late_tick": false, - "load": false, - "on_disable": false, - "on_enable": false, - "physics_tick": false, - "post_physics": false, - "editor_tick": false, - "save": false, - "tick": false - } - } -] \ No newline at end of file diff --git a/tools/reflection_generator/tests/expected_outputs/05_complex_groups.json b/tools/reflection_generator/tests/expected_outputs/05_complex_groups.json deleted file mode 100644 index 189b05ef6..000000000 --- a/tools/reflection_generator/tests/expected_outputs/05_complex_groups.json +++ /dev/null @@ -1,261 +0,0 @@ -[ - { - "attributes": {}, - "fields": [ - { - "attributes": { - "Group": [ - "Physics" - ] - }, - "default": null, - "field_type": "float_t", - "is_array": false, - "name": "m_mass", - "typename": "float" - }, - { - "attributes": { - "Group": [ - "Physics" - ], - "Subgroup": [ - "Velocity" - ] - }, - "default": null, - "field_type": "float_t", - "is_array": false, - "name": "m_vx", - "typename": "float" - }, - { - "attributes": { - "Group": [ - "Physics" - ], - "Subgroup": [ - "Velocity" - ] - }, - "default": null, - "field_type": "float_t", - "is_array": false, - "name": "m_vy", - "typename": "float" - }, - { - "attributes": { - "Group": [ - "Physics" - ], - "Subgroup": [ - "Acceleration" - ] - }, - "default": null, - "field_type": "float_t", - "is_array": false, - "name": "m_ax", - "typename": "float" - }, - { - "attributes": { - "Group": [ - "Physics" - ], - "Subgroup": [ - "Acceleration" - ] - }, - "default": null, - "field_type": "float_t", - "is_array": false, - "name": "m_ay", - "typename": "float" - }, - { - "attributes": { - "Group": [ - "Rendering" - ] - }, - "default": null, - "field_type": "string_t", - "is_array": false, - "name": "m_shader", - "typename": "std::string" - }, - { - "attributes": { - "Group": [ - "Rendering" - ], - "Subgroup": [ - "Transform" - ] - }, - "default": null, - "field_type": "float_t", - "is_array": false, - "name": "m_scale", - "typename": "float" - } - ], - "functions": [], - "global_fields": [], - "groups": [ - { - "fields": [ - { - "attributes": { - "Group": [ - "Physics" - ] - }, - "default": null, - "field_type": "float_t", - "is_array": false, - "name": "m_mass", - "typename": "float" - } - ], - "name": "Physics", - "subgroups": [ - { - "fields": [ - { - "attributes": { - "Group": [ - "Physics" - ], - "Subgroup": [ - "Acceleration" - ] - }, - "default": null, - "field_type": "float_t", - "is_array": false, - "name": "m_ax", - "typename": "float" - }, - { - "attributes": { - "Group": [ - "Physics" - ], - "Subgroup": [ - "Acceleration" - ] - }, - "default": null, - "field_type": "float_t", - "is_array": false, - "name": "m_ay", - "typename": "float" - } - ], - "name": "Acceleration" - }, - { - "fields": [ - { - "attributes": { - "Group": [ - "Physics" - ], - "Subgroup": [ - "Velocity" - ] - }, - "default": null, - "field_type": "float_t", - "is_array": false, - "name": "m_vx", - "typename": "float" - }, - { - "attributes": { - "Group": [ - "Physics" - ], - "Subgroup": [ - "Velocity" - ] - }, - "default": null, - "field_type": "float_t", - "is_array": false, - "name": "m_vy", - "typename": "float" - } - ], - "name": "Velocity" - } - ] - }, - { - "fields": [ - { - "attributes": { - "Group": [ - "Rendering" - ] - }, - "default": null, - "field_type": "string_t", - "is_array": false, - "name": "m_shader", - "typename": "std::string" - } - ], - "name": "Rendering", - "subgroups": [ - { - "fields": [ - { - "attributes": { - "Group": [ - "Rendering" - ], - "Subgroup": [ - "Transform" - ] - }, - "default": null, - "field_type": "float_t", - "is_array": false, - "name": "m_scale", - "typename": "float" - } - ], - "name": "Transform" - } - ] - } - ], - "is_interface": false, - "methods": [], - "name": "ComplexNode", - "namespace": null, - "parent": null, - "signals": [], - "source_file": "05_complex_groups.hpp", - "tick_functions": { - "begin": false, - "destroy": false, - "early_tick": false, - "end": false, - "init": false, - "late_tick": false, - "load": false, - "on_disable": false, - "on_enable": false, - "physics_tick": false, - "post_physics": false, - "editor_tick": false, - "save": false, - "tick": false - } - } -] \ No newline at end of file diff --git a/tools/reflection_generator/tests/expected_outputs/06_all_types.json b/tools/reflection_generator/tests/expected_outputs/06_all_types.json deleted file mode 100644 index 6489e68a2..000000000 --- a/tools/reflection_generator/tests/expected_outputs/06_all_types.json +++ /dev/null @@ -1,210 +0,0 @@ -[ - { - "attributes": {}, - "fields": [ - { - "attributes": {}, - "default": null, - "field_type": "bool_t", - "is_array": false, - "name": "m_bool_val", - "typename": "bool" - }, - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_int_val", - "typename": "int" - }, - { - "attributes": {}, - "default": null, - "field_type": "float_t", - "is_array": false, - "name": "m_float_val", - "typename": "float" - }, - { - "attributes": {}, - "default": null, - "field_type": "double_t", - "is_array": false, - "name": "m_double_val", - "typename": "double" - }, - { - "attributes": {}, - "default": null, - "field_type": "string_t", - "is_array": false, - "name": "m_string_val", - "typename": "std::string" - }, - { - "attributes": {}, - "default": null, - "field_type": "vec2_t", - "is_array": false, - "name": "m_vec2_val", - "typename": "glm::vec2" - }, - { - "attributes": {}, - "default": null, - "field_type": "vec3_t", - "is_array": false, - "name": "m_vec3_val", - "typename": "glm::vec3" - }, - { - "attributes": {}, - "default": null, - "field_type": "vec4_t", - "is_array": false, - "name": "m_vec4_val", - "typename": "glm::vec4" - }, - { - "attributes": {}, - "default": null, - "field_type": "quaternion_t", - "is_array": false, - "name": "m_quat_val", - "typename": "glm::quat" - }, - { - "attributes": {}, - "default": null, - "field_type": "uid_t", - "is_array": false, - "name": "m_uid_val", - "typename": "UID" - }, - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": true, - "name": "m_int_array", - "typename": "std::vector" - } - ], - "functions": [], - "global_fields": [ - { - "attributes": {}, - "default": null, - "field_type": "bool_t", - "is_array": false, - "name": "m_bool_val", - "typename": "bool" - }, - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_int_val", - "typename": "int" - }, - { - "attributes": {}, - "default": null, - "field_type": "float_t", - "is_array": false, - "name": "m_float_val", - "typename": "float" - }, - { - "attributes": {}, - "default": null, - "field_type": "double_t", - "is_array": false, - "name": "m_double_val", - "typename": "double" - }, - { - "attributes": {}, - "default": null, - "field_type": "string_t", - "is_array": false, - "name": "m_string_val", - "typename": "std::string" - }, - { - "attributes": {}, - "default": null, - "field_type": "vec2_t", - "is_array": false, - "name": "m_vec2_val", - "typename": "glm::vec2" - }, - { - "attributes": {}, - "default": null, - "field_type": "vec3_t", - "is_array": false, - "name": "m_vec3_val", - "typename": "glm::vec3" - }, - { - "attributes": {}, - "default": null, - "field_type": "vec4_t", - "is_array": false, - "name": "m_vec4_val", - "typename": "glm::vec4" - }, - { - "attributes": {}, - "default": null, - "field_type": "quaternion_t", - "is_array": false, - "name": "m_quat_val", - "typename": "glm::quat" - }, - { - "attributes": {}, - "default": null, - "field_type": "uid_t", - "is_array": false, - "name": "m_uid_val", - "typename": "UID" - }, - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": true, - "name": "m_int_array", - "typename": "std::vector" - } - ], - "groups": [], - "is_interface": false, - "methods": [], - "name": "AllTypesNode", - "namespace": null, - "parent": null, - "signals": [], - "source_file": "06_all_types.hpp", - "tick_functions": { - "begin": false, - "destroy": false, - "early_tick": false, - "end": false, - "init": false, - "late_tick": false, - "load": false, - "on_disable": false, - "on_enable": false, - "physics_tick": false, - "post_physics": false, - "editor_tick": false, - "save": false, - "tick": false - } - } -] \ No newline at end of file diff --git a/tools/reflection_generator/tests/expected_outputs/07_attributes.json b/tools/reflection_generator/tests/expected_outputs/07_attributes.json deleted file mode 100644 index 3a7595b77..000000000 --- a/tools/reflection_generator/tests/expected_outputs/07_attributes.json +++ /dev/null @@ -1,113 +0,0 @@ -[ - { - "attributes": {}, - "fields": [ - { - "attributes": { - "Custom": [ - "editor", - "fancy" - ], - "Name": [ - "Display Name" - ] - }, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_value", - "typename": "int" - }, - { - "attributes": { - "Custom": [ - "range", - "0", - "100" - ], - "Group": [ - "Settings" - ], - "Name": [ - "Speed" - ] - }, - "default": null, - "field_type": "float_t", - "is_array": false, - "name": "m_speed", - "typename": "float" - } - ], - "functions": [], - "global_fields": [ - { - "attributes": { - "Custom": [ - "editor", - "fancy" - ], - "Name": [ - "Display Name" - ] - }, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_value", - "typename": "int" - } - ], - "groups": [ - { - "fields": [ - { - "attributes": { - "Custom": [ - "range", - "0", - "100" - ], - "Group": [ - "Settings" - ], - "Name": [ - "Speed" - ] - }, - "default": null, - "field_type": "float_t", - "is_array": false, - "name": "m_speed", - "typename": "float" - } - ], - "name": "Settings", - "subgroups": [] - } - ], - "is_interface": false, - "methods": [], - "name": "AttributeNode", - "namespace": null, - "parent": null, - "signals": [], - "source_file": "07_attributes.hpp", - "tick_functions": { - "begin": false, - "destroy": false, - "early_tick": false, - "end": false, - "init": false, - "late_tick": false, - "load": false, - "on_disable": false, - "on_enable": false, - "physics_tick": false, - "post_physics": false, - "editor_tick": false, - "save": false, - "tick": false - } - } -] \ No newline at end of file diff --git a/tools/reflection_generator/tests/expected_outputs/08_multi_class.json b/tools/reflection_generator/tests/expected_outputs/08_multi_class.json deleted file mode 100644 index c747ac566..000000000 --- a/tools/reflection_generator/tests/expected_outputs/08_multi_class.json +++ /dev/null @@ -1,100 +0,0 @@ -[ - { - "attributes": {}, - "fields": [ - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_value", - "typename": "int" - } - ], - "functions": [ - "tick" - ], - "global_fields": [ - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_value", - "typename": "int" - } - ], - "groups": [], - "is_interface": false, - "methods": [], - "name": "FirstNode", - "namespace": "test", - "parent": null, - "signals": [], - "source_file": "08_multi_class.hpp", - "tick_functions": { - "begin": false, - "destroy": false, - "early_tick": false, - "end": false, - "init": false, - "late_tick": false, - "load": false, - "on_disable": false, - "on_enable": false, - "physics_tick": false, - "post_physics": false, - "editor_tick": false, - "save": false, - "tick": true - } - }, - { - "attributes": {}, - "fields": [ - { - "attributes": {}, - "default": null, - "field_type": "string_t", - "is_array": false, - "name": "m_name", - "typename": "std::string" - } - ], - "functions": [], - "global_fields": [ - { - "attributes": {}, - "default": null, - "field_type": "string_t", - "is_array": false, - "name": "m_name", - "typename": "std::string" - } - ], - "groups": [], - "is_interface": false, - "methods": [], - "name": "SecondNode", - "namespace": "test", - "parent": null, - "signals": [], - "source_file": "08_multi_class.hpp", - "tick_functions": { - "begin": false, - "destroy": false, - "early_tick": false, - "end": false, - "init": false, - "late_tick": false, - "load": false, - "on_disable": false, - "on_enable": false, - "physics_tick": false, - "post_physics": false, - "editor_tick": false, - "save": false, - "tick": false - } - } -] \ No newline at end of file diff --git a/tools/reflection_generator/tests/expected_outputs/09_export_macros.json b/tools/reflection_generator/tests/expected_outputs/09_export_macros.json deleted file mode 100644 index 1d511f8f5..000000000 --- a/tools/reflection_generator/tests/expected_outputs/09_export_macros.json +++ /dev/null @@ -1,50 +0,0 @@ -[ - { - "attributes": {}, - "fields": [ - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_value", - "typename": "int" - } - ], - "functions": [], - "global_fields": [ - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_value", - "typename": "int" - } - ], - "groups": [], - "is_interface": false, - "methods": [], - "name": "ExportedNode", - "namespace": "toast", - "parent": null, - "signals": [], - "source_file": "09_export_macros.hpp", - "tick_functions": { - "begin": false, - "destroy": false, - "early_tick": false, - "end": false, - "init": false, - "late_tick": false, - "load": false, - "on_disable": false, - "on_enable": false, - "physics_tick": false, - "post_physics": false, - "editor_tick": false, - "save": false, - "tick": false - } - } -] \ No newline at end of file diff --git a/tools/reflection_generator/tests/expected_outputs/10_inheritance_chain.json b/tools/reflection_generator/tests/expected_outputs/10_inheritance_chain.json deleted file mode 100644 index 6a2dd7864..000000000 --- a/tools/reflection_generator/tests/expected_outputs/10_inheritance_chain.json +++ /dev/null @@ -1,53 +0,0 @@ -[ - { - "attributes": {}, - "fields": [ - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_extra", - "typename": "int" - } - ], - "functions": [], - "global_fields": [ - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_extra", - "typename": "int" - } - ], - "groups": [], - "is_interface": false, - "methods": [], - "name": "GrandchildNode", - "namespace": "game", - "parent": { - "name": "ParentNode", - "namespace": "game" - }, - "signals": [], - "source_file": "10_inheritance_chain.hpp", - "tick_functions": { - "begin": false, - "destroy": false, - "early_tick": false, - "end": false, - "init": false, - "late_tick": false, - "load": false, - "on_disable": false, - "on_enable": false, - "physics_tick": false, - "post_physics": false, - "editor_tick": false, - "save": false, - "tick": false - } - } -] diff --git a/tools/reflection_generator/tests/expected_outputs/11_deeply_nested_groups.json b/tools/reflection_generator/tests/expected_outputs/11_deeply_nested_groups.json deleted file mode 100644 index f5dc242c8..000000000 --- a/tools/reflection_generator/tests/expected_outputs/11_deeply_nested_groups.json +++ /dev/null @@ -1,360 +0,0 @@ -[ - { - "attributes": {}, - "fields": [ - { - "attributes": { - "Group": [ - "Physics" - ], - "Subgroup": [ - "Collider" - ] - }, - "default": null, - "field_type": "float_t", - "is_array": false, - "name": "m_c1", - "typename": "float" - }, - { - "attributes": { - "Group": [ - "Physics" - ], - "Subgroup": [ - "Collider" - ] - }, - "default": null, - "field_type": "float_t", - "is_array": false, - "name": "m_c2", - "typename": "float" - }, - { - "attributes": { - "Group": [ - "Physics" - ], - "Subgroup": [ - "Collider" - ] - }, - "default": null, - "field_type": "float_t", - "is_array": false, - "name": "m_c3", - "typename": "float" - }, - { - "attributes": { - "Group": [ - "Physics" - ], - "Subgroup": [ - "Dynamics" - ] - }, - "default": null, - "field_type": "float_t", - "is_array": false, - "name": "m_d1", - "typename": "float" - }, - { - "attributes": { - "Group": [ - "Physics" - ], - "Subgroup": [ - "Dynamics" - ] - }, - "default": null, - "field_type": "float_t", - "is_array": false, - "name": "m_d2", - "typename": "float" - }, - { - "attributes": { - "Group": [ - "Physics" - ], - "Subgroup": [ - "Constraints" - ] - }, - "default": null, - "field_type": "float_t", - "is_array": false, - "name": "m_k1", - "typename": "float" - }, - { - "attributes": { - "Group": [ - "Physics" - ], - "Subgroup": [ - "Constraints" - ] - }, - "default": null, - "field_type": "float_t", - "is_array": false, - "name": "m_k2", - "typename": "float" - }, - { - "attributes": { - "Group": [ - "Physics" - ], - "Subgroup": [ - "Constraints" - ] - }, - "default": null, - "field_type": "float_t", - "is_array": false, - "name": "m_k3", - "typename": "float" - }, - { - "attributes": { - "Group": [ - "Physics" - ], - "Subgroup": [ - "Constraints" - ] - }, - "default": null, - "field_type": "float_t", - "is_array": false, - "name": "m_k4", - "typename": "float" - }, - { - "attributes": { - "Group": [ - "Physics" - ], - "Subgroup": [ - "Debug" - ] - }, - "default": null, - "field_type": "bool_t", - "is_array": false, - "name": "m_debug", - "typename": "bool" - } - ], - "functions": [], - "global_fields": [], - "groups": [ - { - "fields": [], - "name": "Physics", - "subgroups": [ - { - "fields": [ - { - "attributes": { - "Group": [ - "Physics" - ], - "Subgroup": [ - "Collider" - ] - }, - "default": null, - "field_type": "float_t", - "is_array": false, - "name": "m_c1", - "typename": "float" - }, - { - "attributes": { - "Group": [ - "Physics" - ], - "Subgroup": [ - "Collider" - ] - }, - "default": null, - "field_type": "float_t", - "is_array": false, - "name": "m_c2", - "typename": "float" - }, - { - "attributes": { - "Group": [ - "Physics" - ], - "Subgroup": [ - "Collider" - ] - }, - "default": null, - "field_type": "float_t", - "is_array": false, - "name": "m_c3", - "typename": "float" - } - ], - "name": "Collider" - }, - { - "fields": [ - { - "attributes": { - "Group": [ - "Physics" - ], - "Subgroup": [ - "Constraints" - ] - }, - "default": null, - "field_type": "float_t", - "is_array": false, - "name": "m_k1", - "typename": "float" - }, - { - "attributes": { - "Group": [ - "Physics" - ], - "Subgroup": [ - "Constraints" - ] - }, - "default": null, - "field_type": "float_t", - "is_array": false, - "name": "m_k2", - "typename": "float" - }, - { - "attributes": { - "Group": [ - "Physics" - ], - "Subgroup": [ - "Constraints" - ] - }, - "default": null, - "field_type": "float_t", - "is_array": false, - "name": "m_k3", - "typename": "float" - }, - { - "attributes": { - "Group": [ - "Physics" - ], - "Subgroup": [ - "Constraints" - ] - }, - "default": null, - "field_type": "float_t", - "is_array": false, - "name": "m_k4", - "typename": "float" - } - ], - "name": "Constraints" - }, - { - "fields": [ - { - "attributes": { - "Group": [ - "Physics" - ], - "Subgroup": [ - "Debug" - ] - }, - "default": null, - "field_type": "bool_t", - "is_array": false, - "name": "m_debug", - "typename": "bool" - } - ], - "name": "Debug" - }, - { - "fields": [ - { - "attributes": { - "Group": [ - "Physics" - ], - "Subgroup": [ - "Dynamics" - ] - }, - "default": null, - "field_type": "float_t", - "is_array": false, - "name": "m_d1", - "typename": "float" - }, - { - "attributes": { - "Group": [ - "Physics" - ], - "Subgroup": [ - "Dynamics" - ] - }, - "default": null, - "field_type": "float_t", - "is_array": false, - "name": "m_d2", - "typename": "float" - } - ], - "name": "Dynamics" - } - ] - } - ], - "is_interface": false, - "methods": [], - "name": "DeeplyNestedNode", - "namespace": null, - "parent": null, - "signals": [], - "source_file": "11_deeply_nested_groups.hpp", - "tick_functions": { - "begin": false, - "destroy": false, - "early_tick": false, - "end": false, - "init": false, - "late_tick": false, - "load": false, - "on_disable": false, - "on_enable": false, - "physics_tick": false, - "post_physics": false, - "editor_tick": false, - "save": false, - "tick": false - } - } -] \ No newline at end of file diff --git a/tools/reflection_generator/tests/expected_outputs/12_sparse_groups.json b/tools/reflection_generator/tests/expected_outputs/12_sparse_groups.json deleted file mode 100644 index 997f30fd8..000000000 --- a/tools/reflection_generator/tests/expected_outputs/12_sparse_groups.json +++ /dev/null @@ -1,215 +0,0 @@ -[ - { - "attributes": {}, - "fields": [ - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_global1", - "typename": "int" - }, - { - "attributes": { - "Group": [ - "A" - ] - }, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_a1", - "typename": "int" - }, - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_global2", - "typename": "int" - }, - { - "attributes": { - "Group": [ - "B" - ] - }, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_b1", - "typename": "int" - }, - { - "attributes": { - "Group": [ - "A" - ] - }, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_a2", - "typename": "int" - }, - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_global3", - "typename": "int" - }, - { - "attributes": { - "Group": [ - "B" - ] - }, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_b2", - "typename": "int" - }, - { - "attributes": { - "Group": [ - "A" - ] - }, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_a3", - "typename": "int" - } - ], - "functions": [], - "global_fields": [ - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_global1", - "typename": "int" - }, - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_global2", - "typename": "int" - }, - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_global3", - "typename": "int" - } - ], - "groups": [ - { - "fields": [ - { - "attributes": { - "Group": [ - "A" - ] - }, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_a1", - "typename": "int" - }, - { - "attributes": { - "Group": [ - "A" - ] - }, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_a2", - "typename": "int" - }, - { - "attributes": { - "Group": [ - "A" - ] - }, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_a3", - "typename": "int" - } - ], - "name": "A", - "subgroups": [] - }, - { - "fields": [ - { - "attributes": { - "Group": [ - "B" - ] - }, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_b1", - "typename": "int" - }, - { - "attributes": { - "Group": [ - "B" - ] - }, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_b2", - "typename": "int" - } - ], - "name": "B", - "subgroups": [] - } - ], - "is_interface": false, - "methods": [], - "name": "SparseGroupNode", - "namespace": null, - "parent": null, - "signals": [], - "source_file": "12_sparse_groups.hpp", - "tick_functions": { - "begin": false, - "destroy": false, - "early_tick": false, - "end": false, - "init": false, - "late_tick": false, - "load": false, - "on_disable": false, - "on_enable": false, - "physics_tick": false, - "post_physics": false, - "editor_tick": false, - "save": false, - "tick": false - } - } -] \ No newline at end of file diff --git a/tools/reflection_generator/tests/expected_outputs/13_subgroup_only.json b/tools/reflection_generator/tests/expected_outputs/13_subgroup_only.json deleted file mode 100644 index ef59a061c..000000000 --- a/tools/reflection_generator/tests/expected_outputs/13_subgroup_only.json +++ /dev/null @@ -1,170 +0,0 @@ -[ - { - "attributes": {}, - "fields": [ - { - "attributes": { - "Group": [ - "Settings" - ], - "Subgroup": [ - "Audio" - ] - }, - "default": null, - "field_type": "float_t", - "is_array": false, - "name": "m_volume", - "typename": "float" - }, - { - "attributes": { - "Group": [ - "Settings" - ], - "Subgroup": [ - "Audio" - ] - }, - "default": null, - "field_type": "float_t", - "is_array": false, - "name": "m_pitch", - "typename": "float" - }, - { - "attributes": { - "Group": [ - "Settings" - ], - "Subgroup": [ - "Video" - ] - }, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_width", - "typename": "int" - }, - { - "attributes": { - "Group": [ - "Settings" - ], - "Subgroup": [ - "Video" - ] - }, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_height", - "typename": "int" - } - ], - "functions": [], - "global_fields": [], - "groups": [ - { - "fields": [], - "name": "Settings", - "subgroups": [ - { - "fields": [ - { - "attributes": { - "Group": [ - "Settings" - ], - "Subgroup": [ - "Audio" - ] - }, - "default": null, - "field_type": "float_t", - "is_array": false, - "name": "m_volume", - "typename": "float" - }, - { - "attributes": { - "Group": [ - "Settings" - ], - "Subgroup": [ - "Audio" - ] - }, - "default": null, - "field_type": "float_t", - "is_array": false, - "name": "m_pitch", - "typename": "float" - } - ], - "name": "Audio" - }, - { - "fields": [ - { - "attributes": { - "Group": [ - "Settings" - ], - "Subgroup": [ - "Video" - ] - }, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_width", - "typename": "int" - }, - { - "attributes": { - "Group": [ - "Settings" - ], - "Subgroup": [ - "Video" - ] - }, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_height", - "typename": "int" - } - ], - "name": "Video" - } - ] - } - ], - "is_interface": false, - "methods": [], - "name": "SubgroupOnlyNode", - "namespace": null, - "parent": null, - "signals": [], - "source_file": "13_subgroup_only.hpp", - "tick_functions": { - "begin": false, - "destroy": false, - "early_tick": false, - "end": false, - "init": false, - "late_tick": false, - "load": false, - "on_disable": false, - "on_enable": false, - "physics_tick": false, - "post_physics": false, - "editor_tick": false, - "save": false, - "tick": false - } - } -] \ No newline at end of file diff --git a/tools/reflection_generator/tests/expected_outputs/14_mixed_subgroup_fields.json b/tools/reflection_generator/tests/expected_outputs/14_mixed_subgroup_fields.json deleted file mode 100644 index 21a56c4aa..000000000 --- a/tools/reflection_generator/tests/expected_outputs/14_mixed_subgroup_fields.json +++ /dev/null @@ -1,219 +0,0 @@ -[ - { - "attributes": {}, - "fields": [ - { - "attributes": { - "Group": [ - "Data" - ] - }, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_version", - "typename": "int" - }, - { - "attributes": { - "Group": [ - "Data" - ] - }, - "default": null, - "field_type": "string_t", - "is_array": false, - "name": "m_title", - "typename": "std::string" - }, - { - "attributes": { - "Group": [ - "Data" - ], - "Subgroup": [ - "Content" - ] - }, - "default": null, - "field_type": "string_t", - "is_array": false, - "name": "m_body", - "typename": "std::string" - }, - { - "attributes": { - "Group": [ - "Data" - ], - "Subgroup": [ - "Content" - ] - }, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_checksum", - "typename": "int" - }, - { - "attributes": { - "Group": [ - "Data" - ], - "Subgroup": [ - "Metadata" - ] - }, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_created", - "typename": "int" - }, - { - "attributes": { - "Group": [ - "Data" - ], - "Subgroup": [ - "Metadata" - ] - }, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_modified", - "typename": "int" - } - ], - "functions": [], - "global_fields": [], - "groups": [ - { - "fields": [ - { - "attributes": { - "Group": [ - "Data" - ] - }, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_version", - "typename": "int" - }, - { - "attributes": { - "Group": [ - "Data" - ] - }, - "default": null, - "field_type": "string_t", - "is_array": false, - "name": "m_title", - "typename": "std::string" - } - ], - "name": "Data", - "subgroups": [ - { - "fields": [ - { - "attributes": { - "Group": [ - "Data" - ], - "Subgroup": [ - "Content" - ] - }, - "default": null, - "field_type": "string_t", - "is_array": false, - "name": "m_body", - "typename": "std::string" - }, - { - "attributes": { - "Group": [ - "Data" - ], - "Subgroup": [ - "Content" - ] - }, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_checksum", - "typename": "int" - } - ], - "name": "Content" - }, - { - "fields": [ - { - "attributes": { - "Group": [ - "Data" - ], - "Subgroup": [ - "Metadata" - ] - }, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_created", - "typename": "int" - }, - { - "attributes": { - "Group": [ - "Data" - ], - "Subgroup": [ - "Metadata" - ] - }, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_modified", - "typename": "int" - } - ], - "name": "Metadata" - } - ] - } - ], - "is_interface": false, - "methods": [], - "name": "MixedSubgroupNode", - "namespace": null, - "parent": null, - "signals": [], - "source_file": "14_mixed_subgroup_fields.hpp", - "tick_functions": { - "begin": false, - "destroy": false, - "early_tick": false, - "end": false, - "init": false, - "late_tick": false, - "load": false, - "on_disable": false, - "on_enable": false, - "physics_tick": false, - "post_physics": false, - "editor_tick": false, - "save": false, - "tick": false - } - } -] \ No newline at end of file diff --git a/tools/reflection_generator/tests/expected_outputs/15_snake_case_names.json b/tools/reflection_generator/tests/expected_outputs/15_snake_case_names.json deleted file mode 100644 index ce48bcf92..000000000 --- a/tools/reflection_generator/tests/expected_outputs/15_snake_case_names.json +++ /dev/null @@ -1,187 +0,0 @@ -[ - { - "attributes": {}, - "fields": [ - { - "attributes": { - "Group": [ - "Physics Settings" - ], - "Subgroup": [ - "Rigid Body" - ] - }, - "default": null, - "field_type": "float_t", - "is_array": false, - "name": "m_mass", - "typename": "float" - }, - { - "attributes": { - "Group": [ - "Physics Settings" - ], - "Subgroup": [ - "Rigid Body" - ] - }, - "default": null, - "field_type": "float_t", - "is_array": false, - "name": "m_friction", - "typename": "float" - }, - { - "attributes": { - "Group": [ - "UI Components" - ], - "Subgroup": [ - "Button State" - ] - }, - "default": null, - "field_type": "bool_t", - "is_array": false, - "name": "m_focused", - "typename": "bool" - }, - { - "attributes": { - "Group": [ - "AI_Behavior" - ], - "Subgroup": [ - "Pathfinding_Weights" - ] - }, - "default": null, - "field_type": "float_t", - "is_array": false, - "name": "m_dist_weight", - "typename": "float" - } - ], - "functions": [], - "global_fields": [], - "groups": [ - { - "fields": [], - "name": "AI_Behavior", - "subgroups": [ - { - "fields": [ - { - "attributes": { - "Group": [ - "AI_Behavior" - ], - "Subgroup": [ - "Pathfinding_Weights" - ] - }, - "default": null, - "field_type": "float_t", - "is_array": false, - "name": "m_dist_weight", - "typename": "float" - } - ], - "name": "Pathfinding_Weights" - } - ] - }, - { - "fields": [], - "name": "Physics Settings", - "subgroups": [ - { - "fields": [ - { - "attributes": { - "Group": [ - "Physics Settings" - ], - "Subgroup": [ - "Rigid Body" - ] - }, - "default": null, - "field_type": "float_t", - "is_array": false, - "name": "m_mass", - "typename": "float" - }, - { - "attributes": { - "Group": [ - "Physics Settings" - ], - "Subgroup": [ - "Rigid Body" - ] - }, - "default": null, - "field_type": "float_t", - "is_array": false, - "name": "m_friction", - "typename": "float" - } - ], - "name": "Rigid Body" - } - ] - }, - { - "fields": [], - "name": "UI Components", - "subgroups": [ - { - "fields": [ - { - "attributes": { - "Group": [ - "UI Components" - ], - "Subgroup": [ - "Button State" - ] - }, - "default": null, - "field_type": "bool_t", - "is_array": false, - "name": "m_focused", - "typename": "bool" - } - ], - "name": "Button State" - } - ] - } - ], - "is_interface": false, - "methods": [], - "name": "SnakeCaseNode", - "namespace": null, - "parent": null, - "signals": [], - "source_file": "15_snake_case_names.hpp", - "tick_functions": { - "begin": false, - "destroy": false, - "early_tick": false, - "end": false, - "init": false, - "late_tick": false, - "load": false, - "on_disable": false, - "on_enable": false, - "physics_tick": false, - "post_physics": false, - "editor_tick": false, - "save": false, - "tick": false - } - } -] \ No newline at end of file diff --git a/tools/reflection_generator/tests/expected_outputs/16_all_tick_functions.json b/tools/reflection_generator/tests/expected_outputs/16_all_tick_functions.json deleted file mode 100644 index f5cb5f879..000000000 --- a/tools/reflection_generator/tests/expected_outputs/16_all_tick_functions.json +++ /dev/null @@ -1,47 +0,0 @@ -[ - { - "attributes": {}, - "fields": [], - "functions": [ - "editorTick", - "init", - "begin", - "earlyTick", - "tick", - "physicsTick", - "postPhysics", - "lateTick", - "end", - "destroy", - "onEnable", - "onDisable", - "load", - "save" - ], - "global_fields": [], - "groups": [], - "is_interface": false, - "methods": [], - "name": "AllTicksNode", - "namespace": null, - "parent": null, - "signals": [], - "source_file": "16_all_tick_functions.hpp", - "tick_functions": { - "begin": true, - "destroy": true, - "early_tick": true, - "end": true, - "init": true, - "late_tick": true, - "load": true, - "on_disable": true, - "on_enable": true, - "editor_tick": true, - "physics_tick": true, - "post_physics": true, - "save": true, - "tick": true - } - } -] \ No newline at end of file diff --git a/tools/reflection_generator/tests/expected_outputs/17_global_namespace.json b/tools/reflection_generator/tests/expected_outputs/17_global_namespace.json deleted file mode 100644 index 5e90b3d3e..000000000 --- a/tools/reflection_generator/tests/expected_outputs/17_global_namespace.json +++ /dev/null @@ -1,52 +0,0 @@ -[ - { - "attributes": {}, - "fields": [ - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_value", - "typename": "int" - } - ], - "functions": [ - "tick" - ], - "global_fields": [ - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_value", - "typename": "int" - } - ], - "groups": [], - "is_interface": false, - "methods": [], - "name": "GlobalNamespaceNode", - "namespace": null, - "parent": null, - "signals": [], - "source_file": "17_global_namespace.hpp", - "tick_functions": { - "begin": false, - "destroy": false, - "early_tick": false, - "end": false, - "init": false, - "late_tick": false, - "load": false, - "on_disable": false, - "on_enable": false, - "physics_tick": false, - "post_physics": false, - "editor_tick": false, - "save": false, - "tick": true - } - } -] \ No newline at end of file diff --git a/tools/reflection_generator/tests/expected_outputs/18_nested_namespace.json b/tools/reflection_generator/tests/expected_outputs/18_nested_namespace.json deleted file mode 100644 index 80b0d5c9d..000000000 --- a/tools/reflection_generator/tests/expected_outputs/18_nested_namespace.json +++ /dev/null @@ -1,50 +0,0 @@ -[ - { - "attributes": {}, - "fields": [ - { - "attributes": {}, - "default": null, - "field_type": "float_t", - "is_array": false, - "name": "m_x", - "typename": "float" - } - ], - "functions": [], - "global_fields": [ - { - "attributes": {}, - "default": null, - "field_type": "float_t", - "is_array": false, - "name": "m_x", - "typename": "float" - } - ], - "groups": [], - "is_interface": false, - "methods": [], - "name": "DeepNode", - "namespace": "foo::bar::baz", - "parent": null, - "signals": [], - "source_file": "18_nested_namespace.hpp", - "tick_functions": { - "begin": false, - "destroy": false, - "early_tick": false, - "end": false, - "init": false, - "late_tick": false, - "load": false, - "on_disable": false, - "on_enable": false, - "physics_tick": false, - "post_physics": false, - "editor_tick": false, - "save": false, - "tick": false - } - } -] \ No newline at end of file diff --git a/tools/reflection_generator/tests/expected_outputs/19_field_with_all_attributes.json b/tools/reflection_generator/tests/expected_outputs/19_field_with_all_attributes.json deleted file mode 100644 index d8fce6990..000000000 --- a/tools/reflection_generator/tests/expected_outputs/19_field_with_all_attributes.json +++ /dev/null @@ -1,66 +0,0 @@ -[ - { - "attributes": {}, - "fields": [ - { - "attributes": { - "Custom": [ - "color", - "red" - ], - "Name": [ - "Player Health" - ] - }, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_health", - "typename": "int" - } - ], - "functions": [], - "global_fields": [ - { - "attributes": { - "Custom": [ - "color", - "red" - ], - "Name": [ - "Player Health" - ] - }, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_health", - "typename": "int" - } - ], - "groups": [], - "is_interface": false, - "methods": [], - "name": "AttributeRichNode", - "namespace": null, - "parent": null, - "signals": [], - "source_file": "19_field_with_all_attributes.hpp", - "tick_functions": { - "begin": false, - "destroy": false, - "early_tick": false, - "end": false, - "init": false, - "late_tick": false, - "load": false, - "on_disable": false, - "on_enable": false, - "physics_tick": false, - "post_physics": false, - "editor_tick": false, - "save": false, - "tick": false - } - } -] \ No newline at end of file diff --git a/tools/reflection_generator/tests/expected_outputs/20_vector_of_different_types.json b/tools/reflection_generator/tests/expected_outputs/20_vector_of_different_types.json deleted file mode 100644 index 3c63cf0d9..000000000 --- a/tools/reflection_generator/tests/expected_outputs/20_vector_of_different_types.json +++ /dev/null @@ -1,98 +0,0 @@ -[ - { - "attributes": {}, - "fields": [ - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": true, - "name": "m_ints", - "typename": "std::vector" - }, - { - "attributes": {}, - "default": null, - "field_type": "float_t", - "is_array": true, - "name": "m_floats", - "typename": "std::vector" - }, - { - "attributes": {}, - "default": null, - "field_type": "string_t", - "is_array": true, - "name": "m_strings", - "typename": "std::vector" - }, - { - "attributes": {}, - "default": null, - "field_type": "vec3_t", - "is_array": true, - "name": "m_vectors", - "typename": "std::vector" - } - ], - "functions": [], - "global_fields": [ - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": true, - "name": "m_ints", - "typename": "std::vector" - }, - { - "attributes": {}, - "default": null, - "field_type": "float_t", - "is_array": true, - "name": "m_floats", - "typename": "std::vector" - }, - { - "attributes": {}, - "default": null, - "field_type": "string_t", - "is_array": true, - "name": "m_strings", - "typename": "std::vector" - }, - { - "attributes": {}, - "default": null, - "field_type": "vec3_t", - "is_array": true, - "name": "m_vectors", - "typename": "std::vector" - } - ], - "groups": [], - "is_interface": false, - "methods": [], - "name": "VectorTypesNode", - "namespace": null, - "parent": null, - "signals": [], - "source_file": "20_vector_of_different_types.hpp", - "tick_functions": { - "begin": false, - "destroy": false, - "early_tick": false, - "end": false, - "init": false, - "late_tick": false, - "load": false, - "on_disable": false, - "on_enable": false, - "physics_tick": false, - "post_physics": false, - "editor_tick": false, - "save": false, - "tick": false - } - } -] diff --git a/tools/reflection_generator/tests/expected_outputs/21_field_with_defaults.json b/tools/reflection_generator/tests/expected_outputs/21_field_with_defaults.json deleted file mode 100644 index 726148a1b..000000000 --- a/tools/reflection_generator/tests/expected_outputs/21_field_with_defaults.json +++ /dev/null @@ -1,114 +0,0 @@ -[ - { - "attributes": {}, - "fields": [ - { - "attributes": {}, - "default": "42", - "field_type": "int_t", - "is_array": false, - "name": "m_int", - "typename": "int" - }, - { - "attributes": {}, - "default": "3.14f", - "field_type": "float_t", - "is_array": false, - "name": "m_float", - "typename": "float" - }, - { - "attributes": {}, - "default": "\"hello\"", - "field_type": "string_t", - "is_array": false, - "name": "m_str", - "typename": "std::string" - }, - { - "attributes": {}, - "default": "true", - "field_type": "bool_t", - "is_array": false, - "name": "m_flag", - "typename": "bool" - }, - { - "attributes": {}, - "default": "glm::vec3(1, 2, 3)", - "field_type": "vec3_t", - "is_array": false, - "name": "m_vec", - "typename": "glm::vec3" - } - ], - "functions": [], - "global_fields": [ - { - "attributes": {}, - "default": "42", - "field_type": "int_t", - "is_array": false, - "name": "m_int", - "typename": "int" - }, - { - "attributes": {}, - "default": "3.14f", - "field_type": "float_t", - "is_array": false, - "name": "m_float", - "typename": "float" - }, - { - "attributes": {}, - "default": "\"hello\"", - "field_type": "string_t", - "is_array": false, - "name": "m_str", - "typename": "std::string" - }, - { - "attributes": {}, - "default": "true", - "field_type": "bool_t", - "is_array": false, - "name": "m_flag", - "typename": "bool" - }, - { - "attributes": {}, - "default": "glm::vec3(1, 2, 3)", - "field_type": "vec3_t", - "is_array": false, - "name": "m_vec", - "typename": "glm::vec3" - } - ], - "groups": [], - "is_interface": false, - "methods": [], - "name": "DefaultsNode", - "namespace": null, - "parent": null, - "signals": [], - "source_file": "21_field_with_defaults.hpp", - "tick_functions": { - "begin": false, - "destroy": false, - "early_tick": false, - "end": false, - "init": false, - "late_tick": false, - "load": false, - "on_disable": false, - "on_enable": false, - "physics_tick": false, - "post_physics": false, - "editor_tick": false, - "save": false, - "tick": false - } - } -] \ No newline at end of file diff --git a/tools/reflection_generator/tests/expected_outputs/22_pointer_types.json b/tools/reflection_generator/tests/expected_outputs/22_pointer_types.json deleted file mode 100644 index 4ef079529..000000000 --- a/tools/reflection_generator/tests/expected_outputs/22_pointer_types.json +++ /dev/null @@ -1,50 +0,0 @@ -[ - { - "attributes": {}, - "fields": [ - { - "attributes": {}, - "default": null, - "field_type": "uid_t", - "is_array": false, - "name": "m_texture", - "typename": "Box" - } - ], - "functions": [], - "global_fields": [ - { - "attributes": {}, - "default": null, - "field_type": "uid_t", - "is_array": false, - "name": "m_texture", - "typename": "Box" - } - ], - "groups": [], - "is_interface": false, - "methods": [], - "name": "PointerNode", - "namespace": null, - "parent": null, - "signals": [], - "source_file": "22_pointer_types.hpp", - "tick_functions": { - "begin": false, - "destroy": false, - "early_tick": false, - "end": false, - "init": false, - "late_tick": false, - "load": false, - "on_disable": false, - "on_enable": false, - "physics_tick": false, - "post_physics": false, - "editor_tick": false, - "save": false, - "tick": false - } - } -] \ No newline at end of file diff --git a/tools/reflection_generator/tests/expected_outputs/23_qualified_type_names.json b/tools/reflection_generator/tests/expected_outputs/23_qualified_type_names.json deleted file mode 100644 index a472aaf4c..000000000 --- a/tools/reflection_generator/tests/expected_outputs/23_qualified_type_names.json +++ /dev/null @@ -1,98 +0,0 @@ -[ - { - "attributes": {}, - "fields": [ - { - "attributes": {}, - "default": null, - "field_type": "string_t", - "is_array": false, - "name": "m_str", - "typename": "std::string" - }, - { - "attributes": {}, - "default": null, - "field_type": "vec3_t", - "is_array": false, - "name": "m_pos", - "typename": "glm::vec3" - }, - { - "attributes": {}, - "default": null, - "field_type": "uid_t", - "is_array": false, - "name": "m_id", - "typename": "toast::UID" - }, - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_global", - "typename": "::global::Type" - } - ], - "functions": [], - "global_fields": [ - { - "attributes": {}, - "default": null, - "field_type": "string_t", - "is_array": false, - "name": "m_str", - "typename": "std::string" - }, - { - "attributes": {}, - "default": null, - "field_type": "vec3_t", - "is_array": false, - "name": "m_pos", - "typename": "glm::vec3" - }, - { - "attributes": {}, - "default": null, - "field_type": "uid_t", - "is_array": false, - "name": "m_id", - "typename": "toast::UID" - }, - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_global", - "typename": "::global::Type" - } - ], - "groups": [], - "is_interface": false, - "methods": [], - "name": "QualifiedNode", - "namespace": "game", - "parent": null, - "signals": [], - "source_file": "23_qualified_type_names.hpp", - "tick_functions": { - "begin": false, - "destroy": false, - "early_tick": false, - "end": false, - "init": false, - "late_tick": false, - "load": false, - "on_disable": false, - "on_enable": false, - "physics_tick": false, - "post_physics": false, - "editor_tick": false, - "save": false, - "tick": false - } - } -] \ No newline at end of file diff --git a/tools/reflection_generator/tests/expected_outputs/24_many_global_fields.json b/tools/reflection_generator/tests/expected_outputs/24_many_global_fields.json deleted file mode 100644 index 8bdcdf140..000000000 --- a/tools/reflection_generator/tests/expected_outputs/24_many_global_fields.json +++ /dev/null @@ -1,354 +0,0 @@ -[ - { - "attributes": {}, - "fields": [ - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_f1", - "typename": "int" - }, - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_f2", - "typename": "int" - }, - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_f3", - "typename": "int" - }, - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_f4", - "typename": "int" - }, - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_f5", - "typename": "int" - }, - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_f6", - "typename": "int" - }, - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_f7", - "typename": "int" - }, - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_f8", - "typename": "int" - }, - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_f9", - "typename": "int" - }, - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_f10", - "typename": "int" - }, - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_f11", - "typename": "int" - }, - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_f12", - "typename": "int" - }, - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_f13", - "typename": "int" - }, - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_f14", - "typename": "int" - }, - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_f15", - "typename": "int" - }, - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_f16", - "typename": "int" - }, - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_f17", - "typename": "int" - }, - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_f18", - "typename": "int" - }, - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_f19", - "typename": "int" - }, - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_f20", - "typename": "int" - } - ], - "functions": [], - "global_fields": [ - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_f1", - "typename": "int" - }, - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_f2", - "typename": "int" - }, - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_f3", - "typename": "int" - }, - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_f4", - "typename": "int" - }, - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_f5", - "typename": "int" - }, - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_f6", - "typename": "int" - }, - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_f7", - "typename": "int" - }, - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_f8", - "typename": "int" - }, - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_f9", - "typename": "int" - }, - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_f10", - "typename": "int" - }, - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_f11", - "typename": "int" - }, - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_f12", - "typename": "int" - }, - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_f13", - "typename": "int" - }, - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_f14", - "typename": "int" - }, - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_f15", - "typename": "int" - }, - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_f16", - "typename": "int" - }, - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_f17", - "typename": "int" - }, - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_f18", - "typename": "int" - }, - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_f19", - "typename": "int" - }, - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_f20", - "typename": "int" - } - ], - "groups": [], - "is_interface": false, - "methods": [], - "name": "ManyGlobalsNode", - "namespace": null, - "parent": null, - "signals": [], - "source_file": "24_many_global_fields.hpp", - "tick_functions": { - "begin": false, - "destroy": false, - "early_tick": false, - "end": false, - "init": false, - "late_tick": false, - "load": false, - "on_disable": false, - "on_enable": false, - "physics_tick": false, - "post_physics": false, - "editor_tick": false, - "save": false, - "tick": false - } - } -] \ No newline at end of file diff --git a/tools/reflection_generator/tests/expected_outputs/25_m_prefix_stripping.json b/tools/reflection_generator/tests/expected_outputs/25_m_prefix_stripping.json deleted file mode 100644 index 3a1888e7d..000000000 --- a/tools/reflection_generator/tests/expected_outputs/25_m_prefix_stripping.json +++ /dev/null @@ -1,90 +0,0 @@ -[ - { - "attributes": {}, - "fields": [ - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_value", - "typename": "int" - }, - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "raw_value", - "typename": "int" - }, - { - "attributes": { - "Name": [ - "Custom" - ] - }, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_hidden", - "typename": "int" - } - ], - "functions": [], - "global_fields": [ - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_value", - "typename": "int" - }, - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "raw_value", - "typename": "int" - }, - { - "attributes": { - "Name": [ - "Custom" - ] - }, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_hidden", - "typename": "int" - } - ], - "groups": [], - "is_interface": false, - "methods": [], - "name": "PrefixNode", - "namespace": null, - "parent": null, - "signals": [], - "source_file": "25_m_prefix_stripping.hpp", - "tick_functions": { - "begin": false, - "destroy": false, - "early_tick": false, - "end": false, - "init": false, - "late_tick": false, - "load": false, - "on_disable": false, - "on_enable": false, - "physics_tick": false, - "post_physics": false, - "editor_tick": false, - "save": false, - "tick": false - } - } -] \ No newline at end of file diff --git a/tools/reflection_generator/tests/expected_outputs/26_unsigned_integer_types.json b/tools/reflection_generator/tests/expected_outputs/26_unsigned_integer_types.json deleted file mode 100644 index 8b469dc4b..000000000 --- a/tools/reflection_generator/tests/expected_outputs/26_unsigned_integer_types.json +++ /dev/null @@ -1,114 +0,0 @@ -[ - { - "attributes": {}, - "fields": [ - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_u8", - "typename": "uint8_t" - }, - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_u16", - "typename": "uint16_t" - }, - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_u32", - "typename": "uint32_t" - }, - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_u64", - "typename": "uint64_t" - }, - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_uint", - "typename": "unsigned int" - } - ], - "functions": [], - "global_fields": [ - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_u8", - "typename": "uint8_t" - }, - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_u16", - "typename": "uint16_t" - }, - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_u32", - "typename": "uint32_t" - }, - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_u64", - "typename": "uint64_t" - }, - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_uint", - "typename": "unsigned int" - } - ], - "groups": [], - "is_interface": false, - "methods": [], - "name": "UnsignedNode", - "namespace": null, - "parent": null, - "signals": [], - "source_file": "26_unsigned_integer_types.hpp", - "tick_functions": { - "begin": false, - "destroy": false, - "early_tick": false, - "end": false, - "init": false, - "late_tick": false, - "load": false, - "on_disable": false, - "on_enable": false, - "physics_tick": false, - "post_physics": false, - "editor_tick": false, - "save": false, - "tick": false - } - } -] \ No newline at end of file diff --git a/tools/reflection_generator/tests/expected_outputs/27_signed_integer_types.json b/tools/reflection_generator/tests/expected_outputs/27_signed_integer_types.json deleted file mode 100644 index d981a1605..000000000 --- a/tools/reflection_generator/tests/expected_outputs/27_signed_integer_types.json +++ /dev/null @@ -1,114 +0,0 @@ -[ - { - "attributes": {}, - "fields": [ - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_s8", - "typename": "int8_t" - }, - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_s16", - "typename": "int16_t" - }, - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_s32", - "typename": "int32_t" - }, - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_s64", - "typename": "int64_t" - }, - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_sint", - "typename": "signed int" - } - ], - "functions": [], - "global_fields": [ - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_s8", - "typename": "int8_t" - }, - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_s16", - "typename": "int16_t" - }, - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_s32", - "typename": "int32_t" - }, - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_s64", - "typename": "int64_t" - }, - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_sint", - "typename": "signed int" - } - ], - "groups": [], - "is_interface": false, - "methods": [], - "name": "SignedNode", - "namespace": null, - "parent": null, - "signals": [], - "source_file": "27_signed_integer_types.hpp", - "tick_functions": { - "begin": false, - "destroy": false, - "early_tick": false, - "end": false, - "init": false, - "late_tick": false, - "load": false, - "on_disable": false, - "on_enable": false, - "physics_tick": false, - "post_physics": false, - "editor_tick": false, - "save": false, - "tick": false - } - } -] \ No newline at end of file diff --git a/tools/reflection_generator/tests/expected_outputs/28_empty_group.json b/tools/reflection_generator/tests/expected_outputs/28_empty_group.json deleted file mode 100644 index 2e687a94c..000000000 --- a/tools/reflection_generator/tests/expected_outputs/28_empty_group.json +++ /dev/null @@ -1,66 +0,0 @@ -[ - { - "attributes": {}, - "fields": [ - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_value", - "typename": "int" - }, - { - "attributes": {}, - "default": null, - "field_type": "float_t", - "is_array": false, - "name": "m_another", - "typename": "float" - } - ], - "functions": [], - "global_fields": [ - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_value", - "typename": "int" - }, - { - "attributes": {}, - "default": null, - "field_type": "float_t", - "is_array": false, - "name": "m_another", - "typename": "float" - } - ], - "groups": [], - "is_interface": false, - "methods": [], - "name": "EdgeCaseNode", - "namespace": null, - "parent": null, - "signals": [], - "source_file": "28_empty_group.hpp", - "tick_functions": { - "begin": false, - "destroy": false, - "early_tick": false, - "end": false, - "init": false, - "late_tick": false, - "load": false, - "on_disable": false, - "on_enable": false, - "physics_tick": false, - "post_physics": false, - "editor_tick": false, - "save": false, - "tick": false - } - } -] \ No newline at end of file diff --git a/tools/reflection_generator/tests/expected_outputs/29_duplicate_field_names.json b/tools/reflection_generator/tests/expected_outputs/29_duplicate_field_names.json deleted file mode 100644 index 91dc6b417..000000000 --- a/tools/reflection_generator/tests/expected_outputs/29_duplicate_field_names.json +++ /dev/null @@ -1,94 +0,0 @@ -[ - { - "attributes": {}, - "fields": [ - { - "attributes": { - "Group": [ - "A" - ] - }, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_value", - "typename": "int" - }, - { - "attributes": { - "Group": [ - "B" - ] - }, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_value", - "typename": "int" - } - ], - "functions": [], - "global_fields": [], - "groups": [ - { - "fields": [ - { - "attributes": { - "Group": [ - "A" - ] - }, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_value", - "typename": "int" - } - ], - "name": "A", - "subgroups": [] - }, - { - "fields": [ - { - "attributes": { - "Group": [ - "B" - ] - }, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_value", - "typename": "int" - } - ], - "name": "B", - "subgroups": [] - } - ], - "is_interface": false, - "methods": [], - "name": "DuplicateFieldNode", - "namespace": null, - "parent": null, - "signals": [], - "source_file": "29_duplicate_field_names.hpp", - "tick_functions": { - "begin": false, - "destroy": false, - "early_tick": false, - "end": false, - "init": false, - "late_tick": false, - "load": false, - "on_disable": false, - "on_enable": false, - "physics_tick": false, - "post_physics": false, - "editor_tick": false, - "save": false, - "tick": false - } - } -] \ No newline at end of file diff --git a/tools/reflection_generator/tests/expected_outputs/30_const_volatile_fields.json b/tools/reflection_generator/tests/expected_outputs/30_const_volatile_fields.json deleted file mode 100644 index e52f3474d..000000000 --- a/tools/reflection_generator/tests/expected_outputs/30_const_volatile_fields.json +++ /dev/null @@ -1,82 +0,0 @@ -[ - { - "attributes": {}, - "fields": [ - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_const_val", - "typename": "int" - }, - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_volatile_val", - "typename": "int" - }, - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_both", - "typename": "int" - } - ], - "functions": [], - "global_fields": [ - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_const_val", - "typename": "int" - }, - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_volatile_val", - "typename": "int" - }, - { - "attributes": {}, - "default": null, - "field_type": "int_t", - "is_array": false, - "name": "m_both", - "typename": "int" - } - ], - "groups": [], - "is_interface": false, - "methods": [], - "name": "QualifiersNode", - "namespace": null, - "parent": null, - "signals": [], - "source_file": "30_const_volatile_fields.hpp", - "tick_functions": { - "begin": false, - "destroy": false, - "early_tick": false, - "end": false, - "init": false, - "late_tick": false, - "load": false, - "on_disable": false, - "on_enable": false, - "physics_tick": false, - "post_physics": false, - "editor_tick": false, - "save": false, - "tick": false - } - } -] \ No newline at end of file diff --git a/tools/reflection_generator/tests/expected_outputs/31_reflected_functions.json b/tools/reflection_generator/tests/expected_outputs/31_reflected_functions.json deleted file mode 100644 index c2ebebd49..000000000 --- a/tools/reflection_generator/tests/expected_outputs/31_reflected_functions.json +++ /dev/null @@ -1,123 +0,0 @@ -[ - { - "attributes": {}, - "fields": [ - { - "attributes": { - "Group": [ - "Stats" - ] - }, - "default": "100", - "field_type": "int_t", - "is_array": false, - "name": "m_health", - "typename": "int" - } - ], - "functions": [ - "tick" - ], - "global_fields": [], - "groups": [ - { - "fields": [ - { - "attributes": { - "Group": [ - "Stats" - ] - }, - "default": "100", - "field_type": "int_t", - "is_array": false, - "name": "m_health", - "typename": "int" - } - ], - "name": "Stats", - "subgroups": [] - } - ], - "is_interface": false, - "methods": [ - { - "attributes": {}, - "is_const": false, - "name": "takeDamage", - "parameters": [ - { - "default": null, - "name": "amount", - "type": "int" - }, - { - "default": "false", - "name": "crit", - "type": "bool" - } - ], - "return_type": "int" - }, - { - "attributes": {}, - "is_const": false, - "name": "teleport", - "parameters": [ - { - "default": null, - "name": "destination", - "type": "glm::vec3" - } - ], - "return_type": "void" - }, - { - "attributes": {}, - "is_const": false, - "name": "simulate", - "parameters": [ - { - "default": null, - "name": "plan", - "type": "const AttackPlan&" - }, - { - "default": "1.0f", - "name": "scale", - "type": "float" - } - ], - "return_type": "DamageReport" - }, - { - "attributes": {}, - "is_const": true, - "name": "isAlive", - "parameters": [], - "return_type": "bool" - } - ], - "name": "FunctionNode", - "namespace": "toast", - "parent": null, - "signals": [], - "source_file": "31_reflected_functions.hpp", - "tick_functions": { - "begin": false, - "destroy": false, - "early_tick": false, - "end": false, - "init": false, - "late_tick": false, - "load": false, - "on_disable": false, - "on_enable": false, - "physics_tick": false, - "post_physics": false, - "editor_tick": false, - "save": false, - "tick": true - } - } -] \ No newline at end of file diff --git a/tools/reflection_generator/tests/fixtures/01_simple.hpp b/tools/reflection_generator/tests/fixtures/01_simple.hpp deleted file mode 100644 index 4929ff7c7..000000000 --- a/tools/reflection_generator/tests/fixtures/01_simple.hpp +++ /dev/null @@ -1,11 +0,0 @@ -// Simple class: no inheritance, global namespace, basic group -namespace toast { -class [[ToastNode]] SimpleNode { -public: - [[Reflect, Group("Transform")]] int m_x = 0; - [[Reflect, Group("Transform")]] int m_y = 0; - [[Reflect]] std::string m_name; - - void tick() {} -}; -} diff --git a/tools/reflection_generator/tests/fixtures/02_inherited.hpp b/tools/reflection_generator/tests/fixtures/02_inherited.hpp deleted file mode 100644 index 7e03d7504..000000000 --- a/tools/reflection_generator/tests/fixtures/02_inherited.hpp +++ /dev/null @@ -1,11 +0,0 @@ -// Class with parent (single inheritance) -namespace game { -class [[ToastNode]] Player : public toast::Node { -public: - [[Reflect, Group("Stats")]] int m_health; - [[Reflect, Group("Stats"), Subgroup("Damage")]] int m_armor; - - void init() {} - void tick() {} -}; -} diff --git a/tools/reflection_generator/tests/fixtures/03_no_fields.hpp b/tools/reflection_generator/tests/fixtures/03_no_fields.hpp deleted file mode 100644 index b4c689a97..000000000 --- a/tools/reflection_generator/tests/fixtures/03_no_fields.hpp +++ /dev/null @@ -1,9 +0,0 @@ -// Class with no fields, only tick functions - -class [[ToastNode]] TickOnlyNode { -public: - void editorTick() {} - void tick() {} - void lateTick() {} - void destroy() {} -}; diff --git a/tools/reflection_generator/tests/fixtures/04_no_ticks.hpp b/tools/reflection_generator/tests/fixtures/04_no_ticks.hpp deleted file mode 100644 index 9a9c9bc3d..000000000 --- a/tools/reflection_generator/tests/fixtures/04_no_ticks.hpp +++ /dev/null @@ -1,9 +0,0 @@ -// Class with fields, no tick functions -namespace data { - -class [[ToastNode]] DataNode { -public: - [[Reflect]] float m_value; - [[Reflect]] std::vector m_items; -}; -} diff --git a/tools/reflection_generator/tests/fixtures/05_complex_groups.hpp b/tools/reflection_generator/tests/fixtures/05_complex_groups.hpp deleted file mode 100644 index e8c50e9bf..000000000 --- a/tools/reflection_generator/tests/fixtures/05_complex_groups.hpp +++ /dev/null @@ -1,12 +0,0 @@ -// Multiple groups with multiple subgroups - -class [[ToastNode]] ComplexNode { -public: - [[Reflect, Group("Physics")]] float m_mass; - [[Reflect, Group("Physics"), Subgroup("Velocity")]] float m_vx; - [[Reflect, Group("Physics"), Subgroup("Velocity")]] float m_vy; - [[Reflect, Group("Physics"), Subgroup("Acceleration")]] float m_ax; - [[Reflect, Group("Physics"), Subgroup("Acceleration")]] float m_ay; - [[Reflect, Group("Rendering")]] std::string m_shader; - [[Reflect, Group("Rendering"), Subgroup("Transform")]] float m_scale; -}; diff --git a/tools/reflection_generator/tests/fixtures/06_all_types.hpp b/tools/reflection_generator/tests/fixtures/06_all_types.hpp deleted file mode 100644 index 8e8161b54..000000000 --- a/tools/reflection_generator/tests/fixtures/06_all_types.hpp +++ /dev/null @@ -1,16 +0,0 @@ -// All supported field types - -class [[ToastNode]] AllTypesNode { -public: - [[Reflect]] bool m_bool_val; - [[Reflect]] int m_int_val; - [[Reflect]] float m_float_val; - [[Reflect]] double m_double_val; - [[Reflect]] std::string m_string_val; - [[Reflect]] glm::vec2 m_vec2_val; - [[Reflect]] glm::vec3 m_vec3_val; - [[Reflect]] glm::vec4 m_vec4_val; - [[Reflect]] glm::quat m_quat_val; - [[Reflect]] UID m_uid_val; - [[Reflect]] std::vector m_int_array; -}; diff --git a/tools/reflection_generator/tests/fixtures/07_attributes.hpp b/tools/reflection_generator/tests/fixtures/07_attributes.hpp deleted file mode 100644 index dbcb2d71a..000000000 --- a/tools/reflection_generator/tests/fixtures/07_attributes.hpp +++ /dev/null @@ -1,7 +0,0 @@ -// Field with Name and custom attributes - -class [[ToastNode]] AttributeNode { -public: - [[Reflect, Name("Display Name"), Custom("editor", "fancy")]] int m_value; - [[Reflect, Group("Settings"), Name("Speed"), Custom("range", "0", "100")]] float m_speed; -}; diff --git a/tools/reflection_generator/tests/fixtures/08_multi_class.hpp b/tools/reflection_generator/tests/fixtures/08_multi_class.hpp deleted file mode 100644 index 69eae601d..000000000 --- a/tools/reflection_generator/tests/fixtures/08_multi_class.hpp +++ /dev/null @@ -1,15 +0,0 @@ -// Multiple classes in one file -namespace test { - -class [[ToastNode]] FirstNode { -public: - [[Reflect]] int m_value; - void tick() {} -}; - - -class [[ToastNode]] SecondNode { -public: - [[Reflect]] std::string m_name; -}; -} diff --git a/tools/reflection_generator/tests/fixtures/09_export_macros.hpp b/tools/reflection_generator/tests/fixtures/09_export_macros.hpp deleted file mode 100644 index 76347c99c..000000000 --- a/tools/reflection_generator/tests/fixtures/09_export_macros.hpp +++ /dev/null @@ -1,8 +0,0 @@ -// Class with export macros (stripped during parsing) -namespace toast { - -class [[ToastNode]] TOAST_API ExportedNode { -public: - [[Reflect]] int m_value; -}; -} diff --git a/tools/reflection_generator/tests/fixtures/10_inheritance_chain.hpp b/tools/reflection_generator/tests/fixtures/10_inheritance_chain.hpp deleted file mode 100644 index 2a11f1890..000000000 --- a/tools/reflection_generator/tests/fixtures/10_inheritance_chain.hpp +++ /dev/null @@ -1,8 +0,0 @@ -// Multi-level inheritance with namespaced parent -namespace game { - -class [[ToastNode]] GrandchildNode : public game::ParentNode { -public: - [[Reflect]] int m_extra; -}; -} diff --git a/tools/reflection_generator/tests/fixtures/11_deeply_nested_groups.hpp b/tools/reflection_generator/tests/fixtures/11_deeply_nested_groups.hpp deleted file mode 100644 index f66abf42f..000000000 --- a/tools/reflection_generator/tests/fixtures/11_deeply_nested_groups.hpp +++ /dev/null @@ -1,15 +0,0 @@ -// Many subgroups in same group - -class [[ToastNode]] DeeplyNestedNode { -public: - [[Reflect, Group("Physics"), Subgroup("Collider")]] float m_c1; - [[Reflect, Group("Physics"), Subgroup("Collider")]] float m_c2; - [[Reflect, Group("Physics"), Subgroup("Collider")]] float m_c3; - [[Reflect, Group("Physics"), Subgroup("Dynamics")]] float m_d1; - [[Reflect, Group("Physics"), Subgroup("Dynamics")]] float m_d2; - [[Reflect, Group("Physics"), Subgroup("Constraints")]] float m_k1; - [[Reflect, Group("Physics"), Subgroup("Constraints")]] float m_k2; - [[Reflect, Group("Physics"), Subgroup("Constraints")]] float m_k3; - [[Reflect, Group("Physics"), Subgroup("Constraints")]] float m_k4; - [[Reflect, Group("Physics"), Subgroup("Debug")]] bool m_debug; -}; diff --git a/tools/reflection_generator/tests/fixtures/12_sparse_groups.hpp b/tools/reflection_generator/tests/fixtures/12_sparse_groups.hpp deleted file mode 100644 index 74e239d86..000000000 --- a/tools/reflection_generator/tests/fixtures/12_sparse_groups.hpp +++ /dev/null @@ -1,13 +0,0 @@ -// Interleaved groups and globals - -class [[ToastNode]] SparseGroupNode { -public: - [[Reflect]] int m_global1; - [[Reflect, Group("A")]] int m_a1; - [[Reflect]] int m_global2; - [[Reflect, Group("B")]] int m_b1; - [[Reflect, Group("A")]] int m_a2; - [[Reflect]] int m_global3; - [[Reflect, Group("B")]] int m_b2; - [[Reflect, Group("A")]] int m_a3; -}; diff --git a/tools/reflection_generator/tests/fixtures/13_subgroup_only.hpp b/tools/reflection_generator/tests/fixtures/13_subgroup_only.hpp deleted file mode 100644 index 5d0747d73..000000000 --- a/tools/reflection_generator/tests/fixtures/13_subgroup_only.hpp +++ /dev/null @@ -1,9 +0,0 @@ -// Fields ONLY in subgroups, no direct group fields - -class [[ToastNode]] SubgroupOnlyNode { -public: - [[Reflect, Group("Settings"), Subgroup("Audio")]] float m_volume; - [[Reflect, Group("Settings"), Subgroup("Audio")]] float m_pitch; - [[Reflect, Group("Settings"), Subgroup("Video")]] int m_width; - [[Reflect, Group("Settings"), Subgroup("Video")]] int m_height; -}; diff --git a/tools/reflection_generator/tests/fixtures/14_mixed_subgroup_fields.hpp b/tools/reflection_generator/tests/fixtures/14_mixed_subgroup_fields.hpp deleted file mode 100644 index c9204e484..000000000 --- a/tools/reflection_generator/tests/fixtures/14_mixed_subgroup_fields.hpp +++ /dev/null @@ -1,11 +0,0 @@ -// Group with both direct and subgroup fields - -class [[ToastNode]] MixedSubgroupNode { -public: - [[Reflect, Group("Data")]] int m_version; - [[Reflect, Group("Data")]] std::string m_title; - [[Reflect, Group("Data"), Subgroup("Content")]] std::string m_body; - [[Reflect, Group("Data"), Subgroup("Content")]] int m_checksum; - [[Reflect, Group("Data"), Subgroup("Metadata")]] int m_created; - [[Reflect, Group("Data"), Subgroup("Metadata")]] int m_modified; -}; diff --git a/tools/reflection_generator/tests/fixtures/15_snake_case_names.hpp b/tools/reflection_generator/tests/fixtures/15_snake_case_names.hpp deleted file mode 100644 index 030c5799b..000000000 --- a/tools/reflection_generator/tests/fixtures/15_snake_case_names.hpp +++ /dev/null @@ -1,9 +0,0 @@ -// Group/subgroup names with mixed case, spaces, underscores - -class [[ToastNode]] SnakeCaseNode { -public: - [[Reflect, Group("Physics Settings"), Subgroup("Rigid Body")]] float m_mass; - [[Reflect, Group("Physics Settings"), Subgroup("Rigid Body")]] float m_friction; - [[Reflect, Group("UI Components"), Subgroup("Button State")]] bool m_focused; - [[Reflect, Group("AI_Behavior"), Subgroup("Pathfinding_Weights")]] float m_dist_weight; -}; diff --git a/tools/reflection_generator/tests/fixtures/16_all_tick_functions.hpp b/tools/reflection_generator/tests/fixtures/16_all_tick_functions.hpp deleted file mode 100644 index 0513d8558..000000000 --- a/tools/reflection_generator/tests/fixtures/16_all_tick_functions.hpp +++ /dev/null @@ -1,19 +0,0 @@ -// Class with ALL 14 tick functions - -class [[ToastNode]] AllTicksNode { -public: - void editorTick() {} - void init() {} - void begin() {} - void earlyTick() {} - void tick() {} - void physicsTick() {} - void postPhysics() {} - void lateTick() {} - void end() {} - void destroy() {} - void onEnable() {} - void onDisable() {} - void load() {} - void save() {} -}; diff --git a/tools/reflection_generator/tests/fixtures/17_global_namespace.hpp b/tools/reflection_generator/tests/fixtures/17_global_namespace.hpp deleted file mode 100644 index 77e0b8b7e..000000000 --- a/tools/reflection_generator/tests/fixtures/17_global_namespace.hpp +++ /dev/null @@ -1,7 +0,0 @@ -// Class with NO namespace (global scope) - -class [[ToastNode]] GlobalNamespaceNode { -public: - [[Reflect]] int m_value; - void tick() {} -}; diff --git a/tools/reflection_generator/tests/fixtures/18_nested_namespace.hpp b/tools/reflection_generator/tests/fixtures/18_nested_namespace.hpp deleted file mode 100644 index faa9e50c6..000000000 --- a/tools/reflection_generator/tests/fixtures/18_nested_namespace.hpp +++ /dev/null @@ -1,8 +0,0 @@ -// Class in deeply nested namespace -namespace foo::bar::baz { - -class [[ToastNode]] DeepNode { -public: - [[Reflect]] float m_x; -}; -} diff --git a/tools/reflection_generator/tests/fixtures/19_field_with_all_attributes.hpp b/tools/reflection_generator/tests/fixtures/19_field_with_all_attributes.hpp deleted file mode 100644 index ca246c8f9..000000000 --- a/tools/reflection_generator/tests/fixtures/19_field_with_all_attributes.hpp +++ /dev/null @@ -1,6 +0,0 @@ -// Single field with multiple attributes - -class [[ToastNode]] AttributeRichNode { -public: - [[Reflect, Name("Player Health"), Custom("editor", "slider"), Custom("range", "0", "100"), Custom("color", "red")]] int m_health; -}; diff --git a/tools/reflection_generator/tests/fixtures/20_vector_of_different_types.hpp b/tools/reflection_generator/tests/fixtures/20_vector_of_different_types.hpp deleted file mode 100644 index 3a7787637..000000000 --- a/tools/reflection_generator/tests/fixtures/20_vector_of_different_types.hpp +++ /dev/null @@ -1,9 +0,0 @@ -// Vector fields with various element types - -class [[ToastNode]] VectorTypesNode { -public: - [[Reflect]] std::vector m_ints; - [[Reflect]] std::vector m_floats; - [[Reflect]] std::vector m_strings; - [[Reflect]] std::vector m_vectors; -}; diff --git a/tools/reflection_generator/tests/fixtures/21_field_with_defaults.hpp b/tools/reflection_generator/tests/fixtures/21_field_with_defaults.hpp deleted file mode 100644 index afdeee2f8..000000000 --- a/tools/reflection_generator/tests/fixtures/21_field_with_defaults.hpp +++ /dev/null @@ -1,10 +0,0 @@ -// Fields with various default values - -class [[ToastNode]] DefaultsNode { -public: - [[Reflect]] int m_int = 42; - [[Reflect]] float m_float = 3.14f; - [[Reflect]] std::string m_str = "hello"; - [[Reflect]] bool m_flag = true; - [[Reflect]] glm::vec3 m_vec = glm::vec3(1, 2, 3); -}; diff --git a/tools/reflection_generator/tests/fixtures/22_pointer_types.hpp b/tools/reflection_generator/tests/fixtures/22_pointer_types.hpp deleted file mode 100644 index eb40ff464..000000000 --- a/tools/reflection_generator/tests/fixtures/22_pointer_types.hpp +++ /dev/null @@ -1,8 +0,0 @@ -// Pointer and reference types - -class [[ToastNode]] PointerNode { -public: - [[Reflect]] int* m_ptr; - [[Reflect]] int& m_ref; - [[Reflect]] Box m_texture; -}; diff --git a/tools/reflection_generator/tests/fixtures/23_qualified_type_names.hpp b/tools/reflection_generator/tests/fixtures/23_qualified_type_names.hpp deleted file mode 100644 index ac3143efd..000000000 --- a/tools/reflection_generator/tests/fixtures/23_qualified_type_names.hpp +++ /dev/null @@ -1,11 +0,0 @@ -// Fields with fully qualified type names -namespace game { - -class [[ToastNode]] QualifiedNode { -public: - [[Reflect]] std::string m_str; - [[Reflect]] glm::vec3 m_pos; - [[Reflect]] toast::UID m_id; - [[Reflect]] ::global::Type m_global; -}; -} diff --git a/tools/reflection_generator/tests/fixtures/24_many_global_fields.hpp b/tools/reflection_generator/tests/fixtures/24_many_global_fields.hpp deleted file mode 100644 index 066b78a1c..000000000 --- a/tools/reflection_generator/tests/fixtures/24_many_global_fields.hpp +++ /dev/null @@ -1,25 +0,0 @@ -// Lots of ungrouped fields - -class [[ToastNode]] ManyGlobalsNode { -public: - [[Reflect]] int m_f1; - [[Reflect]] int m_f2; - [[Reflect]] int m_f3; - [[Reflect]] int m_f4; - [[Reflect]] int m_f5; - [[Reflect]] int m_f6; - [[Reflect]] int m_f7; - [[Reflect]] int m_f8; - [[Reflect]] int m_f9; - [[Reflect]] int m_f10; - [[Reflect]] int m_f11; - [[Reflect]] int m_f12; - [[Reflect]] int m_f13; - [[Reflect]] int m_f14; - [[Reflect]] int m_f15; - [[Reflect]] int m_f16; - [[Reflect]] int m_f17; - [[Reflect]] int m_f18; - [[Reflect]] int m_f19; - [[Reflect]] int m_f20; -}; diff --git a/tools/reflection_generator/tests/fixtures/25_m_prefix_stripping.hpp b/tools/reflection_generator/tests/fixtures/25_m_prefix_stripping.hpp deleted file mode 100644 index 8359b6566..000000000 --- a/tools/reflection_generator/tests/fixtures/25_m_prefix_stripping.hpp +++ /dev/null @@ -1,8 +0,0 @@ -// Test m_ prefix stripping for display names - -class [[ToastNode]] PrefixNode { -public: - [[Reflect]] int m_value; - [[Reflect]] int raw_value; - [[Reflect, Name("Custom")]] int m_hidden; -}; diff --git a/tools/reflection_generator/tests/fixtures/26_unsigned_integer_types.hpp b/tools/reflection_generator/tests/fixtures/26_unsigned_integer_types.hpp deleted file mode 100644 index 37bfd2f70..000000000 --- a/tools/reflection_generator/tests/fixtures/26_unsigned_integer_types.hpp +++ /dev/null @@ -1,10 +0,0 @@ -// Various unsigned int types - -class [[ToastNode]] UnsignedNode { -public: - [[Reflect]] uint8_t m_u8; - [[Reflect]] uint16_t m_u16; - [[Reflect]] uint32_t m_u32; - [[Reflect]] uint64_t m_u64; - [[Reflect]] unsigned int m_uint; -}; diff --git a/tools/reflection_generator/tests/fixtures/27_signed_integer_types.hpp b/tools/reflection_generator/tests/fixtures/27_signed_integer_types.hpp deleted file mode 100644 index 9fdf13492..000000000 --- a/tools/reflection_generator/tests/fixtures/27_signed_integer_types.hpp +++ /dev/null @@ -1,10 +0,0 @@ -// Various signed int types - -class [[ToastNode]] SignedNode { -public: - [[Reflect]] int8_t m_s8; - [[Reflect]] int16_t m_s16; - [[Reflect]] int32_t m_s32; - [[Reflect]] int64_t m_s64; - [[Reflect]] signed int m_sint; -}; diff --git a/tools/reflection_generator/tests/fixtures/28_empty_group.hpp b/tools/reflection_generator/tests/fixtures/28_empty_group.hpp deleted file mode 100644 index c0eaa4ff3..000000000 --- a/tools/reflection_generator/tests/fixtures/28_empty_group.hpp +++ /dev/null @@ -1,7 +0,0 @@ -// Edge case: only global fields, no groups - -class [[ToastNode]] EdgeCaseNode { -public: - [[Reflect]] int m_value; - [[Reflect]] float m_another; -}; diff --git a/tools/reflection_generator/tests/fixtures/29_duplicate_field_names.hpp b/tools/reflection_generator/tests/fixtures/29_duplicate_field_names.hpp deleted file mode 100644 index 2dd730e58..000000000 --- a/tools/reflection_generator/tests/fixtures/29_duplicate_field_names.hpp +++ /dev/null @@ -1,7 +0,0 @@ -// Fields with same name in different groups - -class [[ToastNode]] DuplicateFieldNode { -public: - [[Reflect, Group("A")]] int m_value; - [[Reflect, Group("B")]] int m_value; -}; diff --git a/tools/reflection_generator/tests/fixtures/30_const_volatile_fields.hpp b/tools/reflection_generator/tests/fixtures/30_const_volatile_fields.hpp deleted file mode 100644 index 3e75f3308..000000000 --- a/tools/reflection_generator/tests/fixtures/30_const_volatile_fields.hpp +++ /dev/null @@ -1,8 +0,0 @@ -// const/volatile qualifiers on fields - -class [[ToastNode]] QualifiersNode { -public: - [[Reflect]] const int m_const_val; - [[Reflect]] volatile int m_volatile_val; - [[Reflect]] const volatile int m_both; -}; diff --git a/tools/reflection_generator/tests/fixtures/31_reflected_functions.hpp b/tools/reflection_generator/tests/fixtures/31_reflected_functions.hpp deleted file mode 100644 index d7668cd3a..000000000 --- a/tools/reflection_generator/tests/fixtures/31_reflected_functions.hpp +++ /dev/null @@ -1,31 +0,0 @@ -// Reflected member functions: parameters, default values, custom struct args, and void returns. -// Only [[Reflect]]-marked functions are reflected; plain members and tick functions are not. -namespace toast { - -struct AttackPlan { - int strikes; -}; - -struct DamageReport { - int total; - bool lethal; -}; - -class [[ToastNode]] FunctionNode { -public: - [[Reflect, Group("Stats")]] int m_health = 100; - - [[Reflect]] int takeDamage(int amount, bool crit = false) { return m_health; } - - [[Reflect]] void teleport(glm::vec3 destination) {} - - [[Reflect]] DamageReport simulate(const AttackPlan& plan, float scale = 1.0f) { return {}; } - - [[Reflect]] bool isAlive() const { return m_health > 0; } - - // Not reflected: no annotation - void internalHelper() {} - - void tick() {} -}; -} diff --git a/tools/reflection_generator/tests/integration_test.rs b/tools/reflection_generator/tests/integration_test.rs deleted file mode 100644 index 4bdcca0b6..000000000 --- a/tools/reflection_generator/tests/integration_test.rs +++ /dev/null @@ -1,644 +0,0 @@ -mod common; - -use common::JsonComparator; -use minijinja::Environment; -use reflection_generator::{ - build_node, build_template_context, generate_files, generate_json, parse, strip_export_macros, -}; -use serde_json::Value as JsonValue; -use std::fs; -use std::path::Path; - -#[test] -fn test_all_fixtures() { - let manifest_dir = env!("CARGO_MANIFEST_DIR"); - let fixtures_dir = format!("{}/tests/fixtures", manifest_dir); - let expected_dir = format!("{}/tests/expected_outputs", manifest_dir); - let output_dir = format!("{}/target/test_outputs", manifest_dir); - - // Ensure output directory exists - fs::create_dir_all(&output_dir).expect("Failed to create output directory"); - - // List all fixtures - let entries = fs::read_dir(&fixtures_dir) - .unwrap_or_else(|_| panic!("Cannot read fixtures directory: {}", fixtures_dir)); - - let mut fixture_paths: Vec<_> = entries - .filter_map(|e| { - let entry = e.ok()?; - let path = entry.path(); - if path.extension().map_or(false, |ext| ext == "hpp") { - Some(path) - } else { - None - } - }) - .collect(); - - fixture_paths.sort(); - - println!("Found {} fixtures", fixture_paths.len()); - - for fixture_path in fixture_paths { - let fixture_name = fixture_path - .file_stem() - .unwrap() - .to_string_lossy() - .to_string(); - - println!("\n=== Testing fixture: {} ===", fixture_name); - test_single_fixture(&fixture_path, &fixture_name, &output_dir, &expected_dir); - } -} - -fn test_single_fixture( - fixture_path: &Path, - fixture_name: &str, - output_dir: impl AsRef, - expected_dir: impl AsRef, -) { - let output_dir = output_dir.as_ref(); - let expected_dir = expected_dir.as_ref(); - let fixture_path = if fixture_path.is_absolute() { - fixture_path.to_path_buf() - } else { - let manifest_dir = env!("CARGO_MANIFEST_DIR"); - std::path::PathBuf::from(manifest_dir).join(fixture_path) - }; - // 1. Read fixture - let source = fs::read_to_string(&fixture_path) - .unwrap_or_else(|e| panic!("Cannot read fixture {}: {}", fixture_path.display(), e)); - - // 2. Preprocess and parse - let filename = fixture_path - .file_name() - .unwrap() - .to_string_lossy() - .to_string(); - let preprocessed = strip_export_macros(&source); - let classes = parse(&preprocessed, &filename); - - if classes.is_empty() { - println!(" WARNING: No classes found in fixture"); - return; - } - - println!(" Found {} class(es)", classes.len()); - - // 3. Build nodes - let nodes: Vec<_> = classes.iter().map(build_node).collect(); - - // 4. Generate JSON - let actual_json = generate_json(&nodes); - - println!(" Generated JSON for {} nodes", nodes.len()); - - // 5. Check for expected JSON - let expected_path = format!("{}/{}.json", expected_dir, fixture_name); - if Path::new(&expected_path).exists() { - println!(" Comparing against expected JSON..."); - let expected_json: JsonValue = serde_json::from_str( - &fs::read_to_string(&expected_path) - .unwrap_or_else(|_| panic!("Cannot read expected JSON: {}", expected_path)), - ) - .expect("Invalid JSON in expected output"); - - // Deep compare - match JsonComparator::compare(&actual_json, &expected_json, "root") { - Ok(_) => println!(" ✓ JSON matches expected output"), - Err(diff) => { - eprintln!(" ✗ JSON mismatch: {}", diff); - eprintln!( - "\n Expected:\n{}", - serde_json::to_string_pretty(&expected_json).unwrap() - ); - eprintln!( - "\n Actual:\n{}", - serde_json::to_string_pretty(&actual_json).unwrap() - ); - panic!("JSON assertion failed for {}", fixture_name); - } - } - } else { - println!(" No expected JSON found at: {}", expected_path); - println!(" Writing actual JSON for review..."); - let json_str = - serde_json::to_string_pretty(&actual_json).expect("Failed to serialize JSON"); - fs::write(&expected_path, json_str) - .unwrap_or_else(|e| eprintln!("Failed to write expected JSON: {}", e)); - println!(" Wrote: {}", expected_path); - } - - // 6. Generate files for manual inspection - println!(" Generating .hpp files for manual inspection..."); - - // Create a temporary template directory in the output dir for the generator to find - let manifest_dir = env!("CARGO_MANIFEST_DIR"); - let template_src = format!("{}/templates", manifest_dir); - let template_dest = format!("{}/templates", output_dir); - - if Path::new(&template_src).exists() { - // Copy templates to output dir so generator can find them - let _ = fs::create_dir_all(&template_dest); - for entry in - fs::read_dir(&template_src).unwrap_or_else(|_| panic!("Cannot read template dir")) - { - if let Ok(entry) = entry { - let path = entry.path(); - if path.is_file() { - if let Some(filename) = path.file_name() { - let dest_file = format!("{}/{}", template_dest, filename.to_string_lossy()); - let _ = fs::copy(&path, &dest_file); - } - } - } - } - - match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - generate_files(&nodes, Path::new(output_dir), "testRegisterTypes", false); - })) { - Ok(_) => println!(" ✓ Generated .hpp files in: {}", output_dir), - Err(_) => println!(" ⚠ Skipped .hpp generation"), - } - } else { - println!(" ⚠ Template directory not found"); - } -} - -#[test] -fn test_fixture_simple() { - let manifest_dir = env!("CARGO_MANIFEST_DIR"); - let fixture_path = format!("{}/tests/fixtures/01_simple.hpp", manifest_dir); - let output_dir = format!("{}/target/test_outputs", manifest_dir); - let expected_dir = format!("{}/tests/expected_outputs", manifest_dir); - test_single_fixture( - Path::new(&fixture_path), - "01_simple", - &output_dir, - &expected_dir, - ); -} - -#[test] -fn test_fixture_inherited() { - let fixture_path = Path::new("tests/fixtures/02_inherited.hpp"); - if fixture_path.exists() { - test_single_fixture( - fixture_path, - "02_inherited", - "target/test_outputs", - "tests/expected_outputs", - ); - } -} - -#[test] -fn test_fixture_no_fields() { - let fixture_path = Path::new("tests/fixtures/03_no_fields.hpp"); - if fixture_path.exists() { - test_single_fixture( - fixture_path, - "03_no_fields", - "target/test_outputs", - "tests/expected_outputs", - ); - } -} - -#[test] -fn test_fixture_no_ticks() { - let fixture_path = Path::new("tests/fixtures/04_no_ticks.hpp"); - if fixture_path.exists() { - test_single_fixture( - fixture_path, - "04_no_ticks", - "target/test_outputs", - "tests/expected_outputs", - ); - } -} - -#[test] -fn test_fixture_complex_groups() { - let fixture_path = Path::new("tests/fixtures/05_complex_groups.hpp"); - if fixture_path.exists() { - test_single_fixture( - fixture_path, - "05_complex_groups", - "target/test_outputs", - "tests/expected_outputs", - ); - } -} - -#[test] -fn test_fixture_all_types() { - let fixture_path = Path::new("tests/fixtures/06_all_types.hpp"); - if fixture_path.exists() { - test_single_fixture( - fixture_path, - "06_all_types", - "target/test_outputs", - "tests/expected_outputs", - ); - } -} - -#[test] -fn test_fixture_attributes() { - let fixture_path = Path::new("tests/fixtures/07_attributes.hpp"); - if fixture_path.exists() { - test_single_fixture( - fixture_path, - "07_attributes", - "target/test_outputs", - "tests/expected_outputs", - ); - } -} - -#[test] -fn test_fixture_multi_class() { - let fixture_path = Path::new("tests/fixtures/08_multi_class.hpp"); - if fixture_path.exists() { - test_single_fixture( - fixture_path, - "08_multi_class", - "target/test_outputs", - "tests/expected_outputs", - ); - } -} - -#[test] -fn test_fixture_export_macros() { - let fixture_path = Path::new("tests/fixtures/09_export_macros.hpp"); - if fixture_path.exists() { - test_single_fixture( - fixture_path, - "09_export_macros", - "target/test_outputs", - "tests/expected_outputs", - ); - } -} - -#[test] -fn test_fixture_inheritance_chain() { - let fixture_path = Path::new("tests/fixtures/10_inheritance_chain.hpp"); - if fixture_path.exists() { - test_single_fixture( - fixture_path, - "10_inheritance_chain", - "target/test_outputs", - "tests/expected_outputs", - ); - } -} - -#[test] -fn test_fixture_deeply_nested_groups() { - let fixture_path = Path::new("tests/fixtures/11_deeply_nested_groups.hpp"); - if fixture_path.exists() { - test_single_fixture( - fixture_path, - "11_deeply_nested_groups", - "target/test_outputs", - "tests/expected_outputs", - ); - } -} - -#[test] -fn test_fixture_sparse_groups() { - let fixture_path = Path::new("tests/fixtures/12_sparse_groups.hpp"); - if fixture_path.exists() { - test_single_fixture( - fixture_path, - "12_sparse_groups", - "target/test_outputs", - "tests/expected_outputs", - ); - } -} - -#[test] -fn test_fixture_subgroup_only() { - let fixture_path = Path::new("tests/fixtures/13_subgroup_only.hpp"); - if fixture_path.exists() { - test_single_fixture( - fixture_path, - "13_subgroup_only", - "target/test_outputs", - "tests/expected_outputs", - ); - } -} - -#[test] -fn test_fixture_mixed_subgroup_fields() { - let fixture_path = Path::new("tests/fixtures/14_mixed_subgroup_fields.hpp"); - if fixture_path.exists() { - test_single_fixture( - fixture_path, - "14_mixed_subgroup_fields", - "target/test_outputs", - "tests/expected_outputs", - ); - } -} - -#[test] -fn test_fixture_snake_case_names() { - let fixture_path = Path::new("tests/fixtures/15_snake_case_names.hpp"); - if fixture_path.exists() { - test_single_fixture( - fixture_path, - "15_snake_case_names", - "target/test_outputs", - "tests/expected_outputs", - ); - } -} - -#[test] -fn test_fixture_all_tick_functions() { - let fixture_path = Path::new("tests/fixtures/16_all_tick_functions.hpp"); - if fixture_path.exists() { - test_single_fixture( - fixture_path, - "16_all_tick_functions", - "target/test_outputs", - "tests/expected_outputs", - ); - } -} - -#[test] -fn test_fixture_global_namespace() { - let fixture_path = Path::new("tests/fixtures/17_global_namespace.hpp"); - if fixture_path.exists() { - test_single_fixture( - fixture_path, - "17_global_namespace", - "target/test_outputs", - "tests/expected_outputs", - ); - } -} - -#[test] -fn test_fixture_nested_namespace() { - let fixture_path = Path::new("tests/fixtures/18_nested_namespace.hpp"); - if fixture_path.exists() { - test_single_fixture( - fixture_path, - "18_nested_namespace", - "target/test_outputs", - "tests/expected_outputs", - ); - } -} - -#[test] -fn test_fixture_field_with_all_attributes() { - let fixture_path = Path::new("tests/fixtures/19_field_with_all_attributes.hpp"); - if fixture_path.exists() { - test_single_fixture( - fixture_path, - "19_field_with_all_attributes", - "target/test_outputs", - "tests/expected_outputs", - ); - } -} - -#[test] -fn test_fixture_vector_of_different_types() { - let fixture_path = Path::new("tests/fixtures/20_vector_of_different_types.hpp"); - if fixture_path.exists() { - test_single_fixture( - fixture_path, - "20_vector_of_different_types", - "target/test_outputs", - "tests/expected_outputs", - ); - } -} - -#[test] -fn test_fixture_field_with_defaults() { - let fixture_path = Path::new("tests/fixtures/21_field_with_defaults.hpp"); - if fixture_path.exists() { - test_single_fixture( - fixture_path, - "21_field_with_defaults", - "target/test_outputs", - "tests/expected_outputs", - ); - } -} - -#[test] -fn test_fixture_pointer_types() { - let fixture_path = Path::new("tests/fixtures/22_pointer_types.hpp"); - if fixture_path.exists() { - test_single_fixture( - fixture_path, - "22_pointer_types", - "target/test_outputs", - "tests/expected_outputs", - ); - } -} - -#[test] -fn test_fixture_qualified_type_names() { - let fixture_path = Path::new("tests/fixtures/23_qualified_type_names.hpp"); - if fixture_path.exists() { - test_single_fixture( - fixture_path, - "23_qualified_type_names", - "target/test_outputs", - "tests/expected_outputs", - ); - } -} - -#[test] -fn test_fixture_many_global_fields() { - let fixture_path = Path::new("tests/fixtures/24_many_global_fields.hpp"); - if fixture_path.exists() { - test_single_fixture( - fixture_path, - "24_many_global_fields", - "target/test_outputs", - "tests/expected_outputs", - ); - } -} - -#[test] -fn test_fixture_m_prefix_stripping() { - let fixture_path = Path::new("tests/fixtures/25_m_prefix_stripping.hpp"); - if fixture_path.exists() { - test_single_fixture( - fixture_path, - "25_m_prefix_stripping", - "target/test_outputs", - "tests/expected_outputs", - ); - } -} - -#[test] -fn test_fixture_unsigned_integer_types() { - let fixture_path = Path::new("tests/fixtures/26_unsigned_integer_types.hpp"); - if fixture_path.exists() { - test_single_fixture( - fixture_path, - "26_unsigned_integer_types", - "target/test_outputs", - "tests/expected_outputs", - ); - } -} - -#[test] -fn test_fixture_signed_integer_types() { - let fixture_path = Path::new("tests/fixtures/27_signed_integer_types.hpp"); - if fixture_path.exists() { - test_single_fixture( - fixture_path, - "27_signed_integer_types", - "target/test_outputs", - "tests/expected_outputs", - ); - } -} - -#[test] -fn test_fixture_empty_group() { - let fixture_path = Path::new("tests/fixtures/28_empty_group.hpp"); - if fixture_path.exists() { - test_single_fixture( - fixture_path, - "28_empty_group", - "target/test_outputs", - "tests/expected_outputs", - ); - } -} - -#[test] -fn test_fixture_duplicate_field_names() { - let fixture_path = Path::new("tests/fixtures/29_duplicate_field_names.hpp"); - if fixture_path.exists() { - test_single_fixture( - fixture_path, - "29_duplicate_field_names", - "target/test_outputs", - "tests/expected_outputs", - ); - } -} - -#[test] -fn test_fixture_const_volatile_fields() { - let fixture_path = Path::new("tests/fixtures/30_const_volatile_fields.hpp"); - if fixture_path.exists() { - test_single_fixture( - fixture_path, - "30_const_volatile_fields", - "target/test_outputs", - "tests/expected_outputs", - ); - } -} - -#[test] -fn test_fixture_reflected_functions() { - let fixture_path = Path::new("tests/fixtures/31_reflected_functions.hpp"); - if fixture_path.exists() { - test_single_fixture( - fixture_path, - "31_reflected_functions", - "target/test_outputs", - "tests/expected_outputs", - ); - } -} - -#[test] -fn test_unqualified_box_parameter_generates_valid_dynamic_cast() { - let source = r#" - namespace toast { - class [[ToastNode]] BoxParameterNode { - public: - [[Reflect]] void setCamera(Box camera); - }; - } - "#; - - let classes = parse(source, "box_parameter_node.hpp"); - let context = build_template_context(&build_node(&classes[0])); - let mut environment = Environment::new(); - environment - .add_template( - "node", - include_str!("../templates/node.generated.hpp.jinja2"), - ) - .expect("template should parse"); - let generated = environment - .get_template("node") - .expect("template should exist") - .render(context) - .expect("template should render"); - - assert!(generated.contains(".as()")); - assert!(!generated.contains(".as()")); -} - -#[test] -fn test_inspector_attributes_generate_runtime_metadata_and_enum_access() { - let source = r#" - namespace toast { - enum class InspectorMode : int { automatic = 0, manual = 10 }; - - class [[ToastNode]] InspectorNode { - public: - [[Reflect, Enum("Automatic=0", "Manual=10")]] InspectorMode mode = InspectorMode::automatic; - [[Reflect, Button]] void resetCamera(); - [[Reflect, Button("Run Now")]] void run(); - [[Reflect, Button]] bool invalidButton() const; - }; - } - "#; - - let classes = parse(source, "inspector_node.hpp"); - let node = build_node(&classes[0]); - let json = generate_json(std::slice::from_ref(&node)); - assert_eq!(json[0]["fields"][0]["attributes"]["Enum"][0], "Automatic=0"); - assert_eq!( - json[0]["methods"][0]["attributes"]["Button"], - serde_json::json!([]) - ); - assert_eq!(json[0]["methods"][1]["attributes"]["Button"][0], "Run Now"); - - let context = build_template_context(&node); - let mut environment = Environment::new(); - environment - .add_template( - "node", - include_str!("../templates/node.generated.hpp.jinja2"), - ) - .expect("template should parse"); - let generated = environment - .get_template("node") - .expect("template should exist") - .render(context) - .expect("template should render"); - - assert!(generated.contains("EnumFieldAccess> m_frames; - [[Reflect]] Box m_target; - - [[Reflect]] float takeDamage(float amount, bool crit = false) { return 0.0f; } - [[Reflect]] void onInput(const input::Action& action, input::ActionEvent event) {} - [[Reflect]] std::optional raycast(glm::vec3 pos, glm::vec3 dir) {} - [[Reflect]] std::vector raycasts(glm::vec3 pos, glm::vec3 dir) {} - - signals::Signal<> ready; - signals::Signal hit; - - void tick() {} -}; -} -"#; - let classes = parse(source, "stub_node.hpp"); - assert_eq!(classes.len(), 1); - let nodes: Vec<_> = classes.iter().map(build_node).collect(); - let stubs = generate_lua_stubs(&nodes); - - assert!( - stubs.contains("---@class StubNode"), - "class missing:\n{stubs}" - ); - assert!( - stubs.contains("---@field health integer"), - "m_ prefix should be stripped:\n{stubs}" - ); - assert!( - stubs.contains("---@field tint color3"), - "[[Color]] vec3 should be color3:\n{stubs}" - ); - assert!( - !stubs.contains("secret"), - "[[Hidden]] fields should be skipped:\n{stubs}" - ); - assert!( - stubs.contains("---@field frames Asset[]"), - "asset arrays should be Asset[]:\n{stubs}" - ); - assert!( - stubs.contains("---@field target Node3D"), - "Box should use the bare node type:\n{stubs}" - ); - assert!( - stubs.contains( - "---@field takeDamage fun(self: StubNode, amount: number, crit?: boolean): number" - ), - "method signature wrong:\n{stubs}" - ); - assert!( - stubs.contains( - "---@field onInput fun(self: StubNode, action: InputAction, event: InputActionEvent)" - ), - "input callback signature wrong:\n{stubs}" - ); - assert!( - stubs.contains("---@field raycast fun(self: StubNode, pos: vec3, dir: vec3): RayHit|nil"), - "optional custom return should be typed:\n{stubs}" - ); - assert!( - stubs.contains("---@field raycasts fun(self: StubNode, pos: vec3, dir: vec3): RayHit[]"), - "vector custom return should be typed:\n{stubs}" - ); - assert!( - stubs.contains("---@field ready Signal0"), - "zero-argument signal missing:\n{stubs}" - ); - assert!( - stubs.contains("---@field hit Signal2"), - "typed signal missing:\n{stubs}" - ); - assert!( - stubs.contains("StubNode = nil"), - "type marker global missing:\n{stubs}" - ); -} From 4af4af1c66d758208bc095803a40f935ea48e15e Mon Sep 17 00:00:00 2001 From: Xein Date: Fri, 13 Nov 2026 13:47:54 +0100 Subject: [PATCH 2/4] cmake cleanup and dario enum thing --- CMakeLists.txt | 3 + cmake/codegen.cmake | 4 +- cmake/runtime_dlls.cmake | 9 +++ editor/CMakeLists.txt | 26 ++++--- editor/Components/Modals/LoaderViewModel.cs | 41 +++++----- editor/Components/Modals/TerminalReader.cs | 76 +++++++++++++++++++ editor/Resources/EnumBox.axaml | 18 +++-- editor/Workspace/MainWindowViewModel.cs | 17 +---- tests/CMakeLists.txt | 1 + tools/asset_packer/CMakeLists.txt | 3 +- tools/asset_packer/pack/CMakeLists.txt | 2 +- tools/crash_reporter/CMakeLists.txt | 11 ++- tools/dummy_game/CMakeLists.txt | 1 + tools/log_server/CMakeLists.txt | 6 +- tools/player/CMakeLists.txt | 11 ++- tools/reflection_generator/BarColumn.cs | 28 +++++++ tools/reflection_generator/CMakeLists.txt | 11 ++- tools/reflection_generator/Pipeline.cs | 68 +++++++++++------ .../reflection_generator.csproj | 1 + tools/shader_registers/CMakeLists.txt | 1 + 20 files changed, 244 insertions(+), 94 deletions(-) create mode 100644 cmake/runtime_dlls.cmake create mode 100644 editor/Components/Modals/TerminalReader.cs create mode 100644 tools/reflection_generator/BarColumn.cs diff --git a/CMakeLists.txt b/CMakeLists.txt index a58e14e93..30abfc326 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,6 +1,9 @@ cmake_minimum_required(VERSION 3.28) +set(VCPKG_APPLOCAL_DEPS OFF) project(engine) +include(cmake/runtime_dlls.cmake) + include(CTest) set(CMAKE_CXX_STANDARD 23) diff --git a/cmake/codegen.cmake b/cmake/codegen.cmake index 92df0f5dd..f24e63ee5 100644 --- a/cmake/codegen.cmake +++ b/cmake/codegen.cmake @@ -56,8 +56,8 @@ macro(run_codegen) find_program(DOTNET dotnet REQUIRED) execute_process( - COMMAND ${DOTNET} build "${CMAKE_SOURCE_DIR}/tools/reflection_generator/reflection_generator.csproj" - --configuration ${_dotnet_config} --output "${_refgen_dir}" --nologo + COMMAND ${DOTNET} msbuild -restore "${CMAKE_SOURCE_DIR}/tools/reflection_generator/reflection_generator.csproj" + -property:Configuration=${_dotnet_config} "-property:OutputPath=${_refgen_dir}/" -property:_CommandLineDefinedOutputPath=true -nologo -verbosity:quiet -consoleloggerparameters:NoSummary RESULT_VARIABLE _dotnet_result OUTPUT_VARIABLE _dotnet_output ERROR_VARIABLE _dotnet_error diff --git a/cmake/runtime_dlls.cmake b/cmake/runtime_dlls.cmake new file mode 100644 index 000000000..76f0df606 --- /dev/null +++ b/cmake/runtime_dlls.cmake @@ -0,0 +1,9 @@ +function(toast_copy_runtime_dlls target) + if (WIN32) + add_custom_command(TARGET ${target} POST_BUILD + COMMAND ${CMAKE_COMMAND} -E copy_if_different $ $ + COMMAND_EXPAND_LISTS + VERBATIM + ) + endif () +endfunction() diff --git a/editor/CMakeLists.txt b/editor/CMakeLists.txt index bd0f5949f..d60188efb 100644 --- a/editor/CMakeLists.txt +++ b/editor/CMakeLists.txt @@ -28,24 +28,30 @@ if(CMAKE_GENERATOR MATCHES "Visual Studio") endforeach() add_custom_command(TARGET editor PRE_BUILD - COMMAND ${DOTNET_EXECUTABLE} build + COMMAND ${DOTNET_EXECUTABLE} msbuild -restore "${CSHARP_PROJECT}" - --configuration ${DOTNET_CONFIG} - --property:Platform=AnyCPU - --output "${OUTPUT_ROOT}/$/editor" - --nologo + -property:Configuration=${DOTNET_CONFIG} + -property:Platform=AnyCPU + "-property:OutputPath=${OUTPUT_ROOT}/$/editor/" + -property:_CommandLineDefinedOutputPath=true + -nologo + -verbosity:quiet + -consoleloggerparameters:NoSummary WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} COMMENT "[dotnet] Building ${CSHARP_ASSEMBLY_NAME} (${DOTNET_CONFIG})..." VERBATIM ) else() add_custom_target(editor ALL - COMMAND ${DOTNET_EXECUTABLE} build + COMMAND ${DOTNET_EXECUTABLE} msbuild -restore "${CSHARP_PROJECT}" - --configuration ${DOTNET_CONFIG} - --property:Platform=AnyCPU - --output "${OUTPUT_ROOT}/$/editor" - --nologo + -property:Configuration=${DOTNET_CONFIG} + -property:Platform=AnyCPU + "-property:OutputPath=${OUTPUT_ROOT}/$/editor/" + -property:_CommandLineDefinedOutputPath=true + -nologo + -verbosity:quiet + -consoleloggerparameters:NoSummary WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} COMMENT "[dotnet] Building ${CSHARP_ASSEMBLY_NAME} (${DOTNET_CONFIG})..." VERBATIM diff --git a/editor/Components/Modals/LoaderViewModel.cs b/editor/Components/Modals/LoaderViewModel.cs index 466816945..996772d0b 100644 --- a/editor/Components/Modals/LoaderViewModel.cs +++ b/editor/Components/Modals/LoaderViewModel.cs @@ -13,6 +13,7 @@ namespace editor.Components.Modals; public partial class LoaderViewModel : ViewModelBase { private readonly List m_tasks; + private bool m_hasLiveLine; [ObservableProperty] private bool m_isRunning; [ObservableProperty] private double m_progress; @@ -92,8 +93,6 @@ private Task RunProcessAsync(string exe, string args) { FileName = exe, Arguments = args, WorkingDirectory = ProjectContext.IsInitialized ? ProjectContext.ProjectPath : "", - RedirectStandardOutput = true, - RedirectStandardError = true, UseShellExecute = false, CreateNoWindow = true }; @@ -101,23 +100,12 @@ private Task RunProcessAsync(string exe, string args) { var stderr = new StringBuilder(); var lastOut = ""; - proc.OutputDataReceived += (_, e) => { - if (e.Data is null) return; - if (!string.IsNullOrWhiteSpace(e.Data)) lastOut = e.Data; - AppendLine(e.Data); - }; - proc.ErrorDataReceived += (_, e) => { - if (e.Data is null) return; - stderr.AppendLine(e.Data); - AppendLine(e.Data); - }; - - proc.Start(); - proc.BeginOutputReadLine(); - proc.BeginErrorReadLine(); - proc.WaitForExit(); + var exitCode = TerminalReader.Run(proc, line => { + if (line.Length > 0 && line[0] != TerminalReader.LivePrefix && !string.IsNullOrWhiteSpace(line)) lastOut = line; + AppendLine(line); + }, line => stderr.AppendLine(line)); - if (proc.ExitCode is 0) { + if (exitCode is 0) { AppendLine("exit code: 0 (success)"); return; } @@ -127,7 +115,7 @@ private Task RunProcessAsync(string exe, string args) { if (!string.IsNullOrWhiteSpace(lastOut)) detail.AppendLine(lastOut); var err = stderr.ToString().TrimEnd(); if (err.Length > 0) detail.AppendLine(err); - detail.Append($"(exited with code {proc.ExitCode})"); + detail.Append($"(exited with code {exitCode})"); throw new Exception(detail.ToString()); }); @@ -135,8 +123,17 @@ private Task RunProcessAsync(string exe, string args) { // posts to the UI thread because this is called from background tasks and process callbacks private void AppendLine(string text) { - Log.Trace(text); - if (Dispatcher.UIThread.CheckAccess()) ConsoleLines.Add(text); - else Dispatcher.UIThread.Post(() => ConsoleLines.Add(text)); + var live = text.Length > 0 && text[0] == TerminalReader.LivePrefix; + if (live) text = text[1..]; + else Log.Trace(text); + + void Add() { + if (m_hasLiveLine) ConsoleLines[^1] = text; + else ConsoleLines.Add(text); + m_hasLiveLine = live; + } + + if (Dispatcher.UIThread.CheckAccess()) Add(); + else Dispatcher.UIThread.Post(Add); } } diff --git a/editor/Components/Modals/TerminalReader.cs b/editor/Components/Modals/TerminalReader.cs new file mode 100644 index 000000000..d2847406e --- /dev/null +++ b/editor/Components/Modals/TerminalReader.cs @@ -0,0 +1,76 @@ +using System; +using System.Diagnostics; +using System.IO; +using System.Text; +using System.Threading.Tasks; + +namespace editor.Components.Modals; + +public static class TerminalReader { + public const char LivePrefix = '\r'; + + public static void Pump(StreamReader reader, Action log) { + var line = new StringBuilder(); + var overwrite = false; + var buffer = new char[1024]; + var escape = Escape.None; + int read; + + while ((read = reader.Read(buffer, 0, buffer.Length)) > 0) { + for (var i = 0; i < read; i++) { + var c = buffer[i]; + + switch (escape) { + case Escape.Start: + escape = c switch { '[' => Escape.Csi, ']' => Escape.Osc, _ => Escape.None }; + continue; + case Escape.Csi: + if (c is >= '@' and <= '~') escape = Escape.None; + continue; + case Escape.Osc: + if (c is '\a') escape = Escape.None; + continue; + } + + switch (c) { + case '\x1b': escape = Escape.Start; break; + case '\r': overwrite = true; break; + case '\n': + log(line.ToString()); + line.Clear(); + overwrite = false; + break; + default: + if (overwrite) { + line.Clear(); + overwrite = false; + } + line.Append(c); + break; + } + } + + if (line.Length > 0) log(LivePrefix + line.ToString()); + } + + if (line.Length > 0) log(line.ToString()); + } + + // runs the process to the end sending its output through log + public static int Run(Process proc, Action log, Action? onStderr = null) { + proc.StartInfo.RedirectStandardOutput = true; + proc.StartInfo.RedirectStandardError = true; + proc.Start(); + + var err = Task.Run(() => Pump(proc.StandardError, l => { + log(l); + if (onStderr is not null && l.Length > 0 && l[0] != LivePrefix) onStderr(l); + })); + Pump(proc.StandardOutput, log); + err.Wait(); + proc.WaitForExit(); + return proc.ExitCode; + } + + private enum Escape { None, Start, Csi, Osc } +} diff --git a/editor/Resources/EnumBox.axaml b/editor/Resources/EnumBox.axaml index c52f33583..ed7cb530c 100644 --- a/editor/Resources/EnumBox.axaml +++ b/editor/Resources/EnumBox.axaml @@ -61,13 +61,17 @@ Padding="4" BorderBrush="{StaticResource Bg4}" BorderThickness="1"> - - - - - - - + + + + + + + + + diff --git a/editor/Workspace/MainWindowViewModel.cs b/editor/Workspace/MainWindowViewModel.cs index a89caf1c9..a5d0aff2a 100644 --- a/editor/Workspace/MainWindowViewModel.cs +++ b/editor/Workspace/MainWindowViewModel.cs @@ -1249,23 +1249,12 @@ await Task.Run(() => { FileName = packerBin, Arguments = $"\"{stageDir}\" \"{pakOut}\"", WorkingDirectory = ProjectContext.ProjectPath, - RedirectStandardOutput = true, - RedirectStandardError = true, UseShellExecute = false, CreateNoWindow = true }; - proc.OutputDataReceived += (_, e) => { - if (e.Data is not null) log(e.Data); - }; - proc.ErrorDataReceived += (_, e) => { - if (e.Data is not null) log(e.Data); - }; - proc.Start(); - proc.BeginOutputReadLine(); - proc.BeginErrorReadLine(); - proc.WaitForExit(); - if (proc.ExitCode != 0) - throw new Exception($"packer exited with code {proc.ExitCode} for {dbName}"); + var exitCode = TerminalReader.Run(proc, log); + if (exitCode != 0) + throw new Exception($"packer exited with code {exitCode} for {dbName}"); }); } diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index d6bcc91ac..a3174982d 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -9,6 +9,7 @@ if (BUILD_TESTING) add_executable(toast_tests ${TEST_SOURCES} "${CMAKE_CURRENT_SOURCE_DIR}/test_runner.cpp") target_include_directories(toast_tests BEFORE PRIVATE ${CMAKE_SOURCE_DIR}/engine/src) target_include_directories(toast_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}) + toast_copy_runtime_dlls(toast_tests) # HACK DARIO SHOULD FUCKING HAVE SOME INCLUDES ON THE SOURCE FILES RATHER THAN THE HEADERS target_include_directories(toast_tests PRIVATE ${CMAKE_SOURCE_DIR}/engine) target_include_directories(toast_tests PRIVATE ${CMAKE_SOURCE_DIR}/engine/external/inc) diff --git a/tools/asset_packer/CMakeLists.txt b/tools/asset_packer/CMakeLists.txt index d9d058882..0e5c8c020 100644 --- a/tools/asset_packer/CMakeLists.txt +++ b/tools/asset_packer/CMakeLists.txt @@ -8,10 +8,11 @@ foreach (tool IN LISTS PACKER_TOOLS) add_executable(${tool} src/${tool}.cpp) target_link_libraries(${tool} PRIVATE toast_pack indicators::indicators) target_include_directories(${tool} PRIVATE src) + toast_copy_runtime_dlls(${tool}) if (MSVC) target_compile_definitions(${tool} PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN _CRT_SECURE_NO_WARNINGS) - target_compile_options(${tool} PRIVATE /W4 /utf-8) + target_compile_options(${tool} PRIVATE /W4 /utf-8 /EHsc) else () target_compile_options(${tool} PRIVATE -Wall -Wextra) endif () diff --git a/tools/asset_packer/pack/CMakeLists.txt b/tools/asset_packer/pack/CMakeLists.txt index 3df35be1a..be878c3c1 100644 --- a/tools/asset_packer/pack/CMakeLists.txt +++ b/tools/asset_packer/pack/CMakeLists.txt @@ -8,7 +8,7 @@ target_include_directories(toast_pack PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/includ target_link_libraries(toast_pack PUBLIC LZ4::lz4) if (MSVC) - target_compile_options(toast_pack PRIVATE /W4 /utf-8) + target_compile_options(toast_pack PRIVATE /W4 /utf-8 /EHsc) else () target_compile_options(toast_pack PRIVATE -Wall -Wextra) endif () diff --git a/tools/crash_reporter/CMakeLists.txt b/tools/crash_reporter/CMakeLists.txt index 7c2d85f97..eeccf3189 100644 --- a/tools/crash_reporter/CMakeLists.txt +++ b/tools/crash_reporter/CMakeLists.txt @@ -9,11 +9,14 @@ find_program(DOTNET_EXECUTABLE dotnet REQUIRED) # The crash handler looks for it next to out//toast_engine add_custom_target(crash_reporter ALL - COMMAND ${DOTNET_EXECUTABLE} build + COMMAND ${DOTNET_EXECUTABLE} msbuild -restore "${CSHARP_PROJECT}" - --configuration ${DOTNET_CONFIG} - --output "${OUTPUT_ROOT}/$/crash_reporter" - --nologo + -property:Configuration=${DOTNET_CONFIG} + "-property:OutputPath=${OUTPUT_ROOT}/$/crash_reporter/" + -property:_CommandLineDefinedOutputPath=true + -nologo + -verbosity:quiet + -consoleloggerparameters:NoSummary WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} COMMENT "[dotnet] Building ${CSHARP_ASSEMBLY_NAME} (${DOTNET_CONFIG})..." VERBATIM diff --git a/tools/dummy_game/CMakeLists.txt b/tools/dummy_game/CMakeLists.txt index ffb6ae721..846aa0534 100644 --- a/tools/dummy_game/CMakeLists.txt +++ b/tools/dummy_game/CMakeLists.txt @@ -3,6 +3,7 @@ project(dummy_game CXX) add_library(dummy_game SHARED game.cpp) target_link_libraries(dummy_game PUBLIC toast_engine) target_compile_definitions(dummy_game PRIVATE GAME_EXPORT) +toast_copy_runtime_dlls(dummy_game) foreach(config IN ITEMS Debug Release RelWithDebInfo MinSizeRel) string(TOUPPER "${config}" config_upper) diff --git a/tools/log_server/CMakeLists.txt b/tools/log_server/CMakeLists.txt index 5c613005a..361ef2fcc 100644 --- a/tools/log_server/CMakeLists.txt +++ b/tools/log_server/CMakeLists.txt @@ -34,11 +34,12 @@ add_executable(log_server ${LOG_SERVER_SOURCES} ${LOG_SERVER_PROTO_SOURCES}) target_include_directories(log_server PRIVATE src "${LOG_SERVER_GENERATED_DIR}") target_link_libraries(log_server PRIVATE protobuf::libprotobuf asio::asio Threads::Threads CURL::libcurl ZLIB::ZLIB nlohmann_json::nlohmann_json) target_compile_definitions(log_server PRIVATE ASIO_STANDALONE ASIO_NO_DEPRECATED) +toast_copy_runtime_dlls(log_server) if (MSVC) target_compile_definitions(log_server PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN NOGDI _CRT_SECURE_NO_WARNINGS) target_link_options(log_server PRIVATE /SUBSYSTEM:WINDOWS /ENTRY:mainCRTStartup) - set_source_files_properties(${LOG_SERVER_SOURCES} PROPERTIES COMPILE_OPTIONS "/W4;/utf-8") + set_source_files_properties(${LOG_SERVER_SOURCES} PROPERTIES COMPILE_OPTIONS "/W4;/utf-8;/EHsc") else () set_source_files_properties(${LOG_SERVER_SOURCES} PROPERTIES COMPILE_OPTIONS "-Wall;-Wextra") endif () @@ -52,9 +53,10 @@ add_executable(log_server_checks EXCLUDE_FROM_ALL checks/checks.cpp ${LOG_SERVER target_include_directories(log_server_checks PRIVATE src "${LOG_SERVER_GENERATED_DIR}") target_link_libraries(log_server_checks PRIVATE protobuf::libprotobuf asio::asio Threads::Threads CURL::libcurl ZLIB::ZLIB nlohmann_json::nlohmann_json) target_compile_definitions(log_server_checks PRIVATE ASIO_STANDALONE ASIO_NO_DEPRECATED) +toast_copy_runtime_dlls(log_server_checks) if (MSVC) target_compile_definitions(log_server_checks PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN NOGDI _CRT_SECURE_NO_WARNINGS) - set_source_files_properties(checks/checks.cpp PROPERTIES COMPILE_OPTIONS "/W4;/utf-8") + set_source_files_properties(checks/checks.cpp PROPERTIES COMPILE_OPTIONS "/W4;/utf-8;/EHsc") else () set_source_files_properties(checks/checks.cpp PROPERTIES COMPILE_OPTIONS "-Wall;-Wextra") endif () diff --git a/tools/player/CMakeLists.txt b/tools/player/CMakeLists.txt index 6071ed222..ae3f7da0c 100644 --- a/tools/player/CMakeLists.txt +++ b/tools/player/CMakeLists.txt @@ -11,11 +11,14 @@ message(STATUS "Build configuration: ${DOTNET_CONFIG}") message(STATUS "Output directory: ${OUTPUT_ROOT}/$") add_custom_target(player ALL - COMMAND ${DOTNET_EXECUTABLE} build + COMMAND ${DOTNET_EXECUTABLE} msbuild -restore "${CSHARP_PROJECT}" - --configuration ${DOTNET_CONFIG} - --output "${OUTPUT_ROOT}/$/player" - --nologo + -property:Configuration=${DOTNET_CONFIG} + "-property:OutputPath=${OUTPUT_ROOT}/$/player/" + -property:_CommandLineDefinedOutputPath=true + -nologo + -verbosity:quiet + -consoleloggerparameters:NoSummary COMMAND ${CMAKE_COMMAND} -DSRC_DIR=$ -DDST_DIR=${OUTPUT_ROOT}/$/player diff --git a/tools/reflection_generator/BarColumn.cs b/tools/reflection_generator/BarColumn.cs new file mode 100644 index 000000000..124b050e9 --- /dev/null +++ b/tools/reflection_generator/BarColumn.cs @@ -0,0 +1,28 @@ +using Spectre.Console; +using Spectre.Console.Rendering; + +namespace ReflectionGenerator; + +// [=====>----] 3/10 path +internal sealed class BarColumn : ProgressColumn +{ + public override IRenderable Render(RenderOptions options, ProgressTask task, TimeSpan deltaTime) + { + var done = (int)task.Value; + var total = (int)task.MaxValue; + var counter = $" {done}/{total} "; + + var cols = Math.Max(options.ConsoleSize.Width, 20) - 1; + var barWidth = Math.Min(40, Math.Max(cols - 2 - counter.Length, 0)); + var filled = total == 0 ? 0 : barWidth * done / total; + + var bar = new string('=', filled).PadRight(barWidth, '-'); + if (filled > 0 && done < total) bar = bar.Remove(filled - 1, 1).Insert(filled - 1, ">"); + + var room = Math.Max(cols - 2 - barWidth - counter.Length, 0); + var message = task.Description; + if (message.Length > room) message = message[^room..]; + + return new Markup($"[[[cyan]{bar}[/]]]{counter}{Markup.Escape(message)}"); + } +} diff --git a/tools/reflection_generator/CMakeLists.txt b/tools/reflection_generator/CMakeLists.txt index 083a8d428..e804c761f 100644 --- a/tools/reflection_generator/CMakeLists.txt +++ b/tools/reflection_generator/CMakeLists.txt @@ -6,11 +6,14 @@ find_program(DOTNET_EXECUTABLE dotnet REQUIRED) message(STATUS "Found dotnet: ${DOTNET_EXECUTABLE}") add_custom_target(reflection_generator ALL - COMMAND ${DOTNET_EXECUTABLE} build + COMMAND ${DOTNET_EXECUTABLE} msbuild -restore "${CMAKE_CURRENT_SOURCE_DIR}/reflection_generator.csproj" - --configuration ${DOTNET_CONFIG} - --output "${OUTPUT_ROOT}/$/reflection_generator" - --nologo + -property:Configuration=${DOTNET_CONFIG} + "-property:OutputPath=${OUTPUT_ROOT}/$/reflection_generator/" + -property:_CommandLineDefinedOutputPath=true + -nologo + -verbosity:quiet + -consoleloggerparameters:NoSummary WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} COMMENT "[dotnet] Building reflection_generator (${DOTNET_CONFIG})..." VERBATIM diff --git a/tools/reflection_generator/Pipeline.cs b/tools/reflection_generator/Pipeline.cs index d9ee85d43..361fa8019 100644 --- a/tools/reflection_generator/Pipeline.cs +++ b/tools/reflection_generator/Pipeline.cs @@ -3,6 +3,7 @@ using ReflectionGenerator.Output; using ReflectionGenerator.Parsing; using ReflectionGenerator.Rules; +using Spectre.Console; namespace ReflectionGenerator; @@ -17,24 +18,47 @@ public void Run() Warn("no [[ToastNode]] headers found in the given --input directories"); } - var (nodes, events) = ParseHeaders(headers); - WriteOrWarn(options.Database, Database.Serialize(nodes, events)); + IReadOnlyList ordered = []; - var ordered = InheritanceOrder.Sort(nodes); - var templates = new Templates(); - - new CppOutput(templates, options.Output, options.RegisterFn, options.SplitTypeInfo).Write(ordered, events); - - if (options.LuaStubs is { } luaStubs) { - WriteOrWarn(luaStubs, LuaOutput.NodeStubs(templates, ordered)); - } - if (options.EventLuaStubs is { } eventLuaStubs) { - WriteOrWarn(eventLuaStubs, LuaOutput.EventStubs(templates, events)); + try { + AnsiConsole.Progress() + .AutoClear(true) + .Columns(new BarColumn()) + .Start(ctx => { + var task = ctx.AddTask("starting", maxValue: headers.Count + 3); + void Step(string what) { + task.Description = what; + task.Increment(1); + } + + var (nodes, events) = ParseHeaders(headers, Step); + + Step("database"); + WriteOrWarn(options.Database, Database.Serialize(nodes, events)); + + ordered = InheritanceOrder.Sort(nodes); + var templates = new Templates(); + + Step("cpp"); + new CppOutput(templates, options.Output, options.RegisterFn, options.SplitTypeInfo).Write(ordered, events); + + Step("lua stubs"); + if (options.LuaStubs is { } luaStubs) { + WriteOrWarn(luaStubs, LuaOutput.NodeStubs(templates, ordered)); + } + if (options.EventLuaStubs is { } eventLuaStubs) { + WriteOrWarn(eventLuaStubs, LuaOutput.EventStubs(templates, events)); + } + }); + } finally { + foreach (var message in m_messages) Console.Error.WriteLine(message); } - Console.WriteLine($"refgen: generated {ordered.Count} type(s) -> '{options.Output}' (fn: {options.RegisterFn})"); + if (!Console.IsOutputRedirected) Console.WriteLine($"refgen: generated {ordered.Count} type(s) -> '{options.Output}' (fn: {options.RegisterFn})"); } + private readonly List m_messages = []; + private void CheckDirectories() { foreach (var input in options.Inputs.Where(input => !Directory.Exists(input))) { @@ -45,22 +69,24 @@ private void CheckDirectories() } } - private (List Nodes, List Events) ParseHeaders(IEnumerable headers) + private (List Nodes, List Events) ParseHeaders(IEnumerable headers, Action step) { var nodes = new List(); var events = new List(); foreach (var header in headers) { + var includePath = IncludePath(header); + step(includePath); + string source; try { source = File.ReadAllText(header); } catch (Exception e) when (e is IOException or UnauthorizedAccessException) { - Console.Error.WriteLine($"error reading '{header}': {e.Message}"); + m_messages.Add($"error reading '{header}': {e.Message}"); continue; } var text = ExportMacros.Strip(source); - var includePath = IncludePath(header); foreach (var node in NodeParser.Parse(text, includePath)) { Validation.Check(node); @@ -73,7 +99,7 @@ private void CheckDirectories() } // the same event can be seen from several headers - private static List DistinctEvents(IEnumerable events) + private List DistinctEvents(IEnumerable events) { var distinct = events .OrderBy(e => e.QualifiedName, StringComparer.Ordinal) @@ -81,10 +107,6 @@ private static List DistinctEvents(IEnumerable events) .Select(group => group.First()) .ToList(); - var skipped = distinct.Count(e => !e.Supported); - if (skipped > 0) { - Warn($"skipped {skipped} Lua events"); - } return distinct; } @@ -99,7 +121,7 @@ private string IncludePath(string file) return Path.GetFileName(file); } - private static void WriteOrWarn(string path, string content) + private void WriteOrWarn(string path, string content) { try { OutputFile.WriteIfChanged(path, content); @@ -108,5 +130,5 @@ private static void WriteOrWarn(string path, string content) } } - private static void Warn(string message) => Console.Error.WriteLine($"warning: {message}"); + private void Warn(string message) => m_messages.Add($"warning: {message}"); } diff --git a/tools/reflection_generator/reflection_generator.csproj b/tools/reflection_generator/reflection_generator.csproj index 4f9262752..6d58532e7 100644 --- a/tools/reflection_generator/reflection_generator.csproj +++ b/tools/reflection_generator/reflection_generator.csproj @@ -21,6 +21,7 @@ + diff --git a/tools/shader_registers/CMakeLists.txt b/tools/shader_registers/CMakeLists.txt index fbafe7c93..426764654 100644 --- a/tools/shader_registers/CMakeLists.txt +++ b/tools/shader_registers/CMakeLists.txt @@ -15,6 +15,7 @@ add_executable(shader_registers EXCLUDE_FROM_ALL shader_registers.cpp "${SPIRV_R target_include_directories(shader_registers PRIVATE "${SPIRV_REFLECT_DIR}") target_link_libraries(shader_registers PRIVATE Vulkan::Vulkan) target_compile_features(shader_registers PRIVATE cxx_std_20) +toast_copy_runtime_dlls(shader_registers) foreach (config IN ITEMS Debug Release RelWithDebInfo MinSizeRel) string(TOUPPER "${config}" config_upper) From 25980b8df11b4c2b4005b802abbd587ce7c4b429 Mon Sep 17 00:00:00 2001 From: Xein Date: Fri, 13 Nov 2026 14:05:20 +0100 Subject: [PATCH 3/4] update readme bc we needed it --- README.md | 23 ++++------------------- 1 file changed, 4 insertions(+), 19 deletions(-) diff --git a/README.md b/README.md index 9c3353aff..9fab916ad 100644 --- a/README.md +++ b/README.md @@ -15,19 +15,19 @@ Credits: ### Prerequisites - CMake >=3.24 - A C++23 compiler (VS18 and GCC15 tested) -- C# .NET10 toolchain +- C# .NET8 toolchain - VCPKG with `VCPKG_ROOT` set up in PATH ### Generation Powershell ```pwsh -cmake -B build/Debug -G "Visual Studio 18 2026" -DCMAKE_TOOLCHAIN_FILE="$env:VCPKG_ROOT/scripts/buildsystems/vcpkg.cmake" +cmake --template win-relwithdebinfo ``` Linux ```bash -cmake -B build/Debug -G "Visual Studio 18 2026" -DCMAKE_TOOLCHAIN_FILE="$VCPKG_ROOT/scripts/buildsystems/vcpkg.cmake" +cmake --template linux-relwithdebinfo ``` Or using the Nix flake @@ -39,11 +39,7 @@ cmake-gen ### Build ```bash -cmake --build ./build/Debug -``` - -```bash -dotnet run --project editor +cmake --build --template win-relwithdebinfo --target editor ``` Or using the Nix flake @@ -56,14 +52,3 @@ cmake-build ```bash ctest --test-dir build/Debug -C Debug ``` - -## Other tooling - -To properly install `kenzo` on release and be properly accessible through your entire -computer run the following command: - -```bash -cargo install --git https://github.com/nullptr-studios/toast-engine.git --branch main kenzo -``` - -It's even faster than running the Release version you make through Cargo! From cbfb17fcf56ccce33ed49544a30a66d6ff239938 Mon Sep 17 00:00:00 2001 From: Xein Date: Sat, 14 Nov 2026 12:30:45 +0100 Subject: [PATCH 4/4] tests fixes --- cmake/runtime_dlls.cmake | 9 ++++++++- tools/CMakeLists.txt | 16 ---------------- 2 files changed, 8 insertions(+), 17 deletions(-) diff --git a/cmake/runtime_dlls.cmake b/cmake/runtime_dlls.cmake index 76f0df606..7ad6ba7d6 100644 --- a/cmake/runtime_dlls.cmake +++ b/cmake/runtime_dlls.cmake @@ -1,7 +1,14 @@ function(toast_copy_runtime_dlls target) if (WIN32) + set(_vcpkg_prefix "${VCPKG_INSTALLED_DIR}/${VCPKG_TARGET_TRIPLET}") + file(GLOB _vcpkg_dlls_debug CONFIGURE_DEPENDS "${_vcpkg_prefix}/debug/bin/*.dll") + file(GLOB _vcpkg_dlls_release CONFIGURE_DEPENDS "${_vcpkg_prefix}/bin/*.dll") add_custom_command(TARGET ${target} POST_BUILD - COMMAND ${CMAKE_COMMAND} -E copy_if_different $ $ + COMMAND ${CMAKE_COMMAND} -E copy_if_different + $ + "$<$:${_vcpkg_dlls_debug}>" + "$<$>:${_vcpkg_dlls_release}>" + $ COMMAND_EXPAND_LISTS VERBATIM ) diff --git a/tools/CMakeLists.txt b/tools/CMakeLists.txt index 153261819..34b0b18d6 100644 --- a/tools/CMakeLists.txt +++ b/tools/CMakeLists.txt @@ -31,19 +31,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()