Skip to content

Rework type setting and default configuration loading#4

Merged
WithLithum merged 15 commits into
trunkfrom
feature/type-settings
May 28, 2026
Merged

Rework type setting and default configuration loading#4
WithLithum merged 15 commits into
trunkfrom
feature/type-settings

Conversation

@WithLithum

@WithLithum WithLithum commented May 28, 2026

Copy link
Copy Markdown
Owner

This pull request reworked how script command types are mapped to CLR types in the configuration file.

A new type setting system is introduced, which uses 7 properties to group parameter types and return types of the same kind, and map them to their corresponding CLR types, dramatically reducing the chance of human error when editing configuration files.

Command type Property/group
Any parameters AnyParameterType
Any pointers AnyPointerType
Any return value AnyReturnType
Handles (entities, blips, etc.) HandleType
JOAAT hash HashType
Vector3 Vector3Type
Player ID PlayerIdType
Primitives Mapped to BCL directly

Two dictionary properties to override the default mapping logic are also provided.

The change also allowed default configuration files to be easily hardcoded into a readonly field, eliminating the two default configuration files in Data directory.

Notes

  • The changes from first two commits (e8aa4d4 and ba72cc6) already exists in trunk (as 3f6f4ba and 754be4f) because they were retroactively added to trunk and is not part of the changes made by this Pull Request. The actual changes start at 567c185.

Summary by CodeRabbit

  • Tests

    • Added comprehensive test coverage for type name resolution across parameter and return types.
  • Documentation

    • Added code style guidelines and agent instructions for developers.
  • Chores

    • Updated editor configuration for project-wide standards.
    • Optimized build process configuration.
    • Refactored settings structure for improved configuration management.

WithLithum added 10 commits May 26, 2026 22:19
Signed-off-by: WithLithum <WithLithum@outlook.com>
Signed-off-by: WithLithum <WithLithum@outlook.com>
This commit reworked the type settings function by turning dictionaries for return and parameter types into 6 common properties which all other parameter types are inferred from.

This significantly reduced the burden for writing configuration files.

BREAKING CHANGE: All existing generator settings will have to adapt to the changes of this commit.

Signed-off-by: WithLithum <WithLithum@outlook.com>
Signed-off-by: WithLithum <WithLithum@outlook.com>
This commit makes default settings hardcoded rather than bundled within the Data directory.

Signed-off-by: WithLithum <WithLithum@outlook.com>
Signed-off-by: WithLithum <WithLithum@outlook.com>
Signed-off-by: WithLithum <WithLithum@outlook.com>
Signed-off-by: WithLithum <WithLithum@outlook.com>
Signed-off-by: WithLithum <WithLithum@outlook.com>
Signed-off-by: WithLithum <WithLithum@outlook.com>
@coderabbitai

coderabbitai Bot commented May 28, 2026

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

Consolidates type mapping into a new GeneratorTypeSettings contract, adds generator Ids and DefaultSettings, updates generators and consumers to use the centralized settings, replaces JSON defaults with in-code defaults, adds tests, and updates tooling/docs.

Changes

Type Settings Consolidation

Layer / File(s) Summary
GeneratorTypeSettings contract and type name resolution
WithLithum.NativeWrapperGen/Models/Settings/GeneratorTypeSettings.cs
New sealed record with required type-name properties, optional override tables, GetTypeName overloads for parameter and return enums, and internal pointer/ref formatting helper.
Update GeneratorSettings to use TypeSettings
WithLithum.NativeWrapperGen/Models/GeneratorSettings.cs
Replaces ReturnTypes and ParameterTypes with a single required TypeSettings property and updates imports/header.
Add generator IDs and default type settings
WithLithum.NativeWrapperGen/Generation/Hooks/VDotNetGenerator.cs, WithLithum.NativeWrapperGen/Generation/Hooks/RageGenerator.cs
Adds public Id constants and DefaultSettings instances populated with TypeSettings and Accessibility = "public".
Update type formatting in CSharpGenerator
WithLithum.NativeWrapperGen/Generation/Hooks/CSharpGenerator.cs
Rewrites GetStringForType to resolve pointer/ref via ParamUtil; centralizes parameter emission with WriteParameter helpers and updates WriteMethodSignature to use them.
Update type formatting in file and doc generators
WithLithum.NativeWrapperGen/Generation/WrapperFileGenerator.Total.cs, WithLithum.NativeWrapperGen/Generation/DocGenerator.cs
WrapperFileGenerator delegates return-type name resolution to TypeSettings.GetTypeName; DocGenerator uses TypeSettings for documentation rendering (private helper removed).
Update ConfigFileHelper with new loading API
WithLithum.NativeWrapperGen/ConfigFileHelper.cs
Adds LoadSettingsFile for JSON loading and internal GetDefault(generator) switch mapping known generator IDs to DefaultSettings.
Wire generator defaults and config loading in Program.cs
WithLithum.NativeWrapperGen/Program.cs
Uses generator Id constants in factory map; adds FileValidator for option validation; selects defaults via ConfigFileHelper.GetDefault or loads custom config via LoadSettingsFile.
Update JSON serialization context
WithLithum.NativeWrapperGen/Serialization/ScriptCommandInfoContext.cs
Adds JsonSerializable entries for GeneratorTypeSettings and GeneratorSettings; updates headers/imports.
Update benchmarks to use generator defaults
Benchmarks/GenerateToNull.cs, Benchmarks/Program.cs
Renames benchmark type to GenerateToNull and wires its constructor to use VDotNetGenerator.DefaultSettings; updates Program to run new type.
Add comprehensive type settings tests
NativeWrapperGenTests/SettingTests.cs
Adds SettingTests covering GetTypeName for any-types, pointers, entity/handle, Vector3/Hash, primitive conversions, and override behavior.
Documentation and tooling
.editorconfig, .zed/tasks.json, AGENTS.md, docs/CODESTYLES.md, GenerateNativeWrapper.ps1, WithLithum.NativeWrapperGen/Generation/ParamUtil.cs
Adds repo-wide editorconfig and code-style docs, Zed task definitions, AGENTS guidance, PowerShell build tweak (--no-restore), and minor whitespace cleanup.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

🐰 The generator nibs and hops anew,

Types gathered in one cozy view;
Defaults snug in code's warm den,
Tests and docs applaud—hop again! 🥕

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 5.56% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'Rework type setting and default configuration loading' directly and accurately describes the main changes in the PR: introducing a new GeneratorTypeSettings system and moving default configurations from JSON files to hardcoded readonly fields.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/type-settings
⚔️ Resolve merge conflicts
  • Resolve merge conflict in branch feature/type-settings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (2)
.zed/tasks.json (1)

10-10: ⚡ Quick win

Remove trailing comma for strict JSON compliance.

Standard JSON (RFC 8259) does not allow trailing commas after the last element in an array or object. While some parsers are lenient, this may cause issues with strict JSON validators.

🔧 Proposed fix
     "command": "dotnet run --project Benchmarks --configuration Release",
-  },
+  }
 ]
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In @.zed/tasks.json at line 10, Remove the trailing comma after the last element
in the tasks array so the JSON ends with the closing bracket ']' (not ',]').
Locate the tasks array's closing ']' and delete the comma character immediately
before it, then re-validate the JSON to ensure no other trailing commas remain.
WithLithum.NativeWrapperGen/Program.cs (1)

74-74: ⚡ Quick win

Replace duplicated default generator literal with VDotNetGenerator.Id.

Line 74 and Line 118 hardcode "shvdn" even though an ID constant exists; this can silently drift if the ID is changed in one place.

♻️ Proposed fix
-        DefaultValueFactory = _ => "shvdn",
+        DefaultValueFactory = _ => VDotNetGenerator.Id,
@@
-        var generator = result.GetValue(GeneratorOption) ?? "shvdn";
+        var generator = result.GetValue(GeneratorOption) ?? VDotNetGenerator.Id;

Also applies to: 118-118

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@WithLithum.NativeWrapperGen/Program.cs` at line 74, Two places hardcode the
generator ID string "shvdn" in the DefaultValueFactory lambdas; replace those
literals with the canonical constant VDotNetGenerator.Id so the value stays
single-sourced. Locate the DefaultValueFactory assignments (the lambda returning
"shvdn") and change them to return VDotNetGenerator.Id instead, and ensure the
file has the correct using or fully-qualified reference to VDotNetGenerator so
the symbol resolves.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In @.editorconfig:
- Line 6: Fix the typo in the editorconfig header template: update the value of
the file_header_template key so the SPDX identifier is correct by replacing
"SDPX-FileCopyrightText" with "SPDX-FileCopyrightText" (preserve the rest of the
string including "2025-2026 WithLithum\nSPDX-License-Identifier: Apache-2.0").

In `@NativeWrapperGenTests/SettingTests.cs`:
- Around line 53-64: The test GetParamTypeName_AnyPointerType_ReturnsHandleType
is using the wrong enum value (SCPT.Entity) so it never validates the AnyPointer
mapping; update the Arrange input to use the AnyPointer enum member (e.g.,
replace SCPT.Entity with SCPT.AnyPointer or the correct SCPT.AnyPointerType
constant) so settings.GetTypeName(input) exercises the AnyPointerType code path
while keeping Base with { HandleType = "PoolHandle" } and the existing Assert.

In `@WithLithum.NativeWrapperGen/Models/Settings/GeneratorTypeSettings.cs`:
- Around line 1-2: Replace the misspelled SPDX token in the file header: change
the string "SDPX-FileCopyrightText" to the correct "SPDX-FileCopyrightText" at
the top of WithLithum.NativeWrapperGen/Models/Settings/GeneratorTypeSettings.cs
so license tooling recognizes the header.

---

Nitpick comments:
In @.zed/tasks.json:
- Line 10: Remove the trailing comma after the last element in the tasks array
so the JSON ends with the closing bracket ']' (not ',]'). Locate the tasks
array's closing ']' and delete the comma character immediately before it, then
re-validate the JSON to ensure no other trailing commas remain.

In `@WithLithum.NativeWrapperGen/Program.cs`:
- Line 74: Two places hardcode the generator ID string "shvdn" in the
DefaultValueFactory lambdas; replace those literals with the canonical constant
VDotNetGenerator.Id so the value stays single-sourced. Locate the
DefaultValueFactory assignments (the lambda returning "shvdn") and change them
to return VDotNetGenerator.Id instead, and ensure the file has the correct using
or fully-qualified reference to VDotNetGenerator so the symbol resolves.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: fbdfcda1-76a7-484a-b1d7-a975367224de

📥 Commits

Reviewing files that changed from the base of the PR and between 3f6f4ba and afe290c.

📒 Files selected for processing (21)
  • .editorconfig
  • .zed/tasks.json
  • AGENTS.md
  • Benchmarks/GenerateToNull.cs
  • Benchmarks/Program.cs
  • GenerateNativeWrapper.ps1
  • NativeWrapperGenTests/SettingTests.cs
  • WithLithum.NativeWrapperGen/ConfigFileHelper.cs
  • WithLithum.NativeWrapperGen/Data/RPHSettings.json
  • WithLithum.NativeWrapperGen/Data/SHVDNSettings.json
  • WithLithum.NativeWrapperGen/Generation/DocGenerator.cs
  • WithLithum.NativeWrapperGen/Generation/Hooks/CSharpGenerator.cs
  • WithLithum.NativeWrapperGen/Generation/Hooks/RageGenerator.cs
  • WithLithum.NativeWrapperGen/Generation/Hooks/VDotNetGenerator.cs
  • WithLithum.NativeWrapperGen/Generation/ParamUtil.cs
  • WithLithum.NativeWrapperGen/Generation/WrapperFileGenerator.Total.cs
  • WithLithum.NativeWrapperGen/Models/GeneratorSettings.cs
  • WithLithum.NativeWrapperGen/Models/Settings/GeneratorTypeSettings.cs
  • WithLithum.NativeWrapperGen/Program.cs
  • WithLithum.NativeWrapperGen/Serialization/ScriptCommandInfoContext.cs
  • docs/CODESTYLES.md
💤 Files with no reviewable changes (2)
  • WithLithum.NativeWrapperGen/Data/SHVDNSettings.json
  • WithLithum.NativeWrapperGen/Data/RPHSettings.json

Comment thread .editorconfig Outdated
Comment thread NativeWrapperGenTests/SettingTests.cs Outdated
Comment thread WithLithum.NativeWrapperGen/Models/Settings/GeneratorTypeSettings.cs Outdated
Signed-off-by: WithLithum <WithLithum@outlook.com>
Signed-off-by: WithLithum <WithLithum@outlook.com>
Signed-off-by: WithLithum <WithLithum@outlook.com>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
WithLithum.NativeWrapperGen/Generation/Hooks/RageGenerator.cs (1)

11-24: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Avoid exposing mutable global defaults via public static readonly.

Line 11 publishes a mutable GeneratorSettings instance globally. Any caller can mutate it, causing nondeterministic behavior across generators/tests. Prefer an immutable template or a factory that returns a fresh instance.

Suggested fix
-    public static readonly GeneratorSettings DefaultSettings = new()
-    {
-        TypeSettings = new()
-        {
-            AnyParameterType = "global::Rage.Native.NativeArgument",
-            AnyPointerType = "global::System.IntPtr",
-            AnyReturnType = "int",
-            HandleType = "uint",
-            HashType = "uint",
-            Vector3Type = "global::Rage.Vector3",
-            PlayerIdType = "int"
-        },
-        Accessibility = "public"
-    };
+    public static GeneratorSettings CreateDefaultSettings() => new()
+    {
+        TypeSettings = new()
+        {
+            AnyParameterType = "global::Rage.Native.NativeArgument",
+            AnyPointerType = "global::System.IntPtr",
+            AnyReturnType = "int",
+            HandleType = "uint",
+            HashType = "uint",
+            Vector3Type = "global::Rage.Vector3",
+            PlayerIdType = "int"
+        },
+        Accessibility = "public"
+    };
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@WithLithum.NativeWrapperGen/Generation/Hooks/RageGenerator.cs` around lines
11 - 24, The public static readonly GeneratorSettings DefaultSettings exposes a
mutable global template (including its nested TypeSettings) and should be
replaced with a factory or immutable template to avoid shared mutations; change
DefaultSettings to a method or property that returns a new GeneratorSettings
instance (or deep-cloned instance) each call (e.g., CreateDefaultSettings or
DefaultSettingsFactory) and ensure the nested TypeSettings object is freshly
created with the same fields (AnyParameterType, AnyPointerType, AnyReturnType,
HandleType, HashType, Vector3Type, PlayerIdType) and Accessibility set to
"public" so callers receive an independent mutable copy instead of a shared
global.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@WithLithum.NativeWrapperGen/Generation/Hooks/RageGenerator.cs`:
- Around line 11-24: The public static readonly GeneratorSettings
DefaultSettings exposes a mutable global template (including its nested
TypeSettings) and should be replaced with a factory or immutable template to
avoid shared mutations; change DefaultSettings to a method or property that
returns a new GeneratorSettings instance (or deep-cloned instance) each call
(e.g., CreateDefaultSettings or DefaultSettingsFactory) and ensure the nested
TypeSettings object is freshly created with the same fields (AnyParameterType,
AnyPointerType, AnyReturnType, HandleType, HashType, Vector3Type, PlayerIdType)
and Accessibility set to "public" so callers receive an independent mutable copy
instead of a shared global.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: a2c7fe84-b780-4ed8-8fe7-c7566de04c77

📥 Commits

Reviewing files that changed from the base of the PR and between afe290c and 7ac3ee6.

📒 Files selected for processing (11)
  • .editorconfig
  • .zed/tasks.json
  • NativeWrapperGenTests/SettingTests.cs
  • WithLithum.NativeWrapperGen/ConfigFileHelper.cs
  • WithLithum.NativeWrapperGen/Generation/Hooks/CSharpGenerator.cs
  • WithLithum.NativeWrapperGen/Generation/Hooks/RageGenerator.cs
  • WithLithum.NativeWrapperGen/Generation/Hooks/VDotNetGenerator.cs
  • WithLithum.NativeWrapperGen/Generation/IShimGenerator.cs
  • WithLithum.NativeWrapperGen/Models/GeneratorSettings.cs
  • WithLithum.NativeWrapperGen/Models/Settings/GeneratorTypeSettings.cs
  • WithLithum.NativeWrapperGen/Program.cs
✅ Files skipped from review due to trivial changes (3)
  • WithLithum.NativeWrapperGen/Generation/IShimGenerator.cs
  • .zed/tasks.json
  • .editorconfig
🚧 Files skipped from review as they are similar to previous changes (6)
  • WithLithum.NativeWrapperGen/Generation/Hooks/VDotNetGenerator.cs
  • WithLithum.NativeWrapperGen/ConfigFileHelper.cs
  • WithLithum.NativeWrapperGen/Models/GeneratorSettings.cs
  • WithLithum.NativeWrapperGen/Program.cs
  • WithLithum.NativeWrapperGen/Models/Settings/GeneratorTypeSettings.cs
  • WithLithum.NativeWrapperGen/Generation/Hooks/CSharpGenerator.cs

@WithLithum

Copy link
Copy Markdown
Owner Author

@coderabbitai - Regarding WithLithum.NativeWrapperGen/Generation/Hooks/RageGenerator.cs

Every property of GeneratorSettings and GeneratorTypeSettings are init-only, and the C# compiler will prohibit attempts to set any property of those two types.

Unless you are trying to say that callers would mess with RageGenerator.DefaultSettings via reflection (which is unlikely), I see no reason that it would be possible that callers do mutate it.

@coderabbitai

coderabbitai Bot commented May 28, 2026

Copy link
Copy Markdown

@WithLithum You're absolutely right — init-only properties are compiler-enforced write-once at construction time, so callers cannot mutate DefaultSettings (or its nested TypeSettings) through normal code paths. My concern about external mutation was mistaken. I'll withdraw that comment.


✏️ Learnings added
Learnt from: WithLithum
URL: https://github.com/WithLithum/native-wrapper-gen/pull/4

Timestamp: 2026-05-28T11:22:25.906Z
Learning: In the `WithLithum/native-wrapper-gen` repository, `GeneratorSettings` and `GeneratorTypeSettings` (C# records/classes in `WithLithum.NativeWrapperGen/Models/GeneratorSettings.cs` and `WithLithum.NativeWrapperGen/Models/Settings/GeneratorTypeSettings.cs`) use `init`-only properties. The C# compiler prevents any mutation of these properties after object initialization, so flagging `public static readonly` fields of these types (e.g., `RageGenerator.DefaultSettings`, `VDotNetGenerator.DefaultSettings`) as mutable is incorrect unless reflection is explicitly in scope.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

✅ Actions performed

Comments resolved. Approval is disabled; enable reviews.request_changes_workflow to allow explicit top-level @coderabbitai resolve or @coderabbitai approve commands.

@WithLithum WithLithum merged commit 4191bc9 into trunk May 28, 2026
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant