You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@fory.apache.org by ch...@apache.org on 2026/07/27 09:25:30 UTC
(fory) branch main updated: feat(csharp): support external type serialization (#3889)
This is an automated email from the ASF dual-hosted git repository.
chaokunyang pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/fory.git
The following commit(s) were added to refs/heads/main by this push:
new c5bc54fd1 feat(csharp): support external type serialization (#3889)
c5bc54fd1 is described below
commit c5bc54fd1aa70f2e392f7d323351cf2aae9f366b
Author: Shawn Yang <sh...@gmail.com>
AuthorDate: Mon Jul 27 17:25:27 2026 +0800
feat(csharp): support external type serialization (#3889)
## Why?
## What does this PR do?
## Related issues
## AI Contribution Checklist
- [ ] Substantial AI assistance was used in this PR: `yes` / `no`
- [ ] If `yes`, I included a completed [AI Contribution
Checklist](https://github.com/apache/fory/blob/main/AI_POLICY.md#9-contributor-checklist-for-ai-assisted-prs)
in this PR description and the required `AI Usage Disclosure`.
- [ ] If `yes`, my PR description includes the required `ai_review`
summary and screenshot evidence or equivalent persisted links of the
final clean AI review results from both fresh reviewers described in
`AI_POLICY.md`, the Fory-guided reviewer and the independent general
reviewer, on the current PR diff or current HEAD after the latest code
changes.
## Does this PR introduce any user-facing change?
- [ ] Does this PR introduce any public API change?
- [ ] Does this PR introduce any binary protocol compatibility change?
## Benchmark
---
.agents/languages/csharp.md | 43 +
.gitignore | 2 +
benchmarks/csharp/Directory.Build.props | 7 +
benchmarks/csharp/ExternalEquivalenceBenchmark.cs | 597 ++++++++
benchmarks/csharp/ExternalEquivalenceModels.cs | 221 +++
benchmarks/csharp/ExternalEquivalenceProgram.cs | 231 +++
benchmarks/csharp/Fory.CSharpBenchmark.csproj | 4 +
.../Fory.ExternalBenchmarkTypes/ExternalModels.cs | 34 +
.../Fory.ExternalBenchmarkTypes.csproj | 8 +
...rk.csproj => Fory.ExternalTypeBenchmark.csproj} | 7 +-
benchmarks/csharp/README.md | 81 +
benchmarks/csharp/external_equivalence_report.py | 497 ++++++
benchmarks/csharp/run.sh | 124 +-
csharp/Fory.sln | 7 +
csharp/README.md | 27 +-
.../Fory.Generator/AnalyzerReleases.Unshipped.md | 7 +
csharp/src/Fory.Generator/ForyModelGenerator.cs | 1597 +++++++++++++++++---
csharp/src/Fory/Attributes.cs | 21 +-
csharp/src/Fory/Fory.cs | 6 +-
csharp/src/Fory/Serializer.cs | 3 +-
csharp/src/Fory/ThreadSafeFory.cs | 6 +-
csharp/src/Fory/TypeInfo.cs | 27 +-
csharp/src/Fory/TypeResolver.cs | 51 +-
csharp/tests/Fory.ExternalTypes/ExternalModels.cs | 174 +++
.../Fory.ExternalTypes.csproj} | 6 -
.../Fory.Tests/ExternalTypeSerializationTests.cs | 496 ++++++
csharp/tests/Fory.Tests/ExternalTypeSerializers.cs | 260 ++++
csharp/tests/Fory.Tests/Fory.Tests.csproj | 1 +
csharp/tests/Fory.Tests/ForyGeneratorTests.cs | 723 ++++++++-
csharp/tests/Fory.Tests/GraphMemoryBudgetTests.cs | 46 +
.../Fory.XlangPeer/ExternalTypeSerializers.cs | 56 +
csharp/tests/Fory.XlangPeer/Fory.XlangPeer.csproj | 1 +
csharp/tests/Fory.XlangPeer/Program.cs | 82 +
docs/guide/csharp/basic-serialization.md | 3 +-
docs/guide/csharp/external-types.md | 211 +++
docs/guide/csharp/index.md | 11 +-
...custom-serializers.md => manual-serializers.md} | 14 +-
docs/guide/csharp/references.md | 5 +
docs/guide/csharp/schema-evolution.md | 6 +
docs/guide/csharp/schema-metadata.md | 15 +
docs/guide/csharp/supported-types.md | 7 +-
docs/guide/csharp/type-registration.md | 9 +-
docs/guide/csharp/xlang-serialization.md | 6 +
docs/specification/xlang_implementation_guide.md | 90 ++
docs/specification/xlang_type_mapping.md | 6 +
.../org/apache/fory/xlang/CSharpXlangTest.java | 124 ++
46 files changed, 5700 insertions(+), 260 deletions(-)
diff --git a/.agents/languages/csharp.md b/.agents/languages/csharp.md
index 5357ac7ce..07969c975 100644
--- a/.agents/languages/csharp.md
+++ b/.agents/languages/csharp.md
@@ -11,6 +11,49 @@ Load this file when changing `csharp/` or C# xlang behavior.
- Use `dotnet format` to keep C# code style consistent.
- Generated C# gRPC service companions are compiler-owned files that depend on application-provided gRPC packages, not `csharp/src/Fory`. Keep gRPC package references out of the Fory runtime package.
- C# generated schema modules are source-file owners. Service companions must use that module's `ThreadSafeFory` and must not introduce namespace-owned aliases or duplicate serializer registration paths.
+- C# external-type serialization is target-keyed. A local
+ `ForyStruct(Target = typeof(...))` abstract serializer declaration owns only
+ compile-time schema metadata; an empty static
+ `ForyEnum(Target = typeof(...))` declaration selects the canonical target
+ enum serializer. Generated code, `Serializer<T>`, `TypeInfo`, registration,
+ roots, fields, dynamic values, references, graph memory, and carrier children
+ use the actual target type. Never instantiate, register, reflect over, or
+ reference-publish the declaration.
+- Keep one generator model/emitter and one resolver registration path for
+ ordinary and external C# targets. Registration uses only the
+ `Register<Target>` and `Register<Target, TSerializer>` APIs. Do not add
+ external registration, field/root serializer selectors, provider objects,
+ callbacks, runtime schema trees, carrier-provider types, per-element
+ external dispatch, or declaration-to-target conversion objects.
+- Every generated struct uses
+ `RegisterGeneratedStruct<Target, TSerializer>(Evolving)` so generator-owned
+ schema evolution reaches target `TypeInfo` directly. Generated enum and
+ union factories use `RegisterGenerated<Target, TSerializer>()`. Do not
+ recover structural metadata through target reflection, hide structural
+ registration behind a boolean overload of the non-structural method, or add
+ a second metadata owner. Reject duplicate generated owners by target at
+ compile time and deterministically on the cold cross-assembly
+ factory-registration path. Last-writer-wins generated factories are
+ forbidden; explicit manual serializer replacement uses normal resolver
+ semantics.
+- External structural serializers use direct target construction and member
+ access under the mutable parameterless-construction contract.
+ Immutable, constructor-only, factory-only, readonly, init-only, renamed,
+ converted, or inaccessible targets use a manual serializer. Derive
+ allocation, reference publication, default value, and graph-memory behavior
+ from the target class/struct kind, never the declaration kind.
+- External children compose through the concrete carrier serializers already
+ owned by `TypeResolver`: nullable structs, one-dimensional arrays, List,
+ LinkedList, Queue, Stack, HashSet, SortedSet, ImmutableHashSet, Dictionary,
+ SortedDictionary, SortedList, ConcurrentDictionary, and
+ NullableKeyDictionary. Do not add or claim unsupported collection-interface,
+ tuple, fixed-array, multidimensional-array, memory, or reference-wrapper
+ carriers.
+- External and equivalent ordinary generated hot bodies must have the same
+ work and allocation shape apart from target/member metadata tokens. External
+ target selection is compile-time only. Keep duplicate-target and validation
+ errors on no-inline cold entrances, but do not mark successful serializer
+ dispatch cold.
- Compatible scalar, list-array, and binary/uint8-array adaptations are immediate-field-only. Recursive matched-field comparison for collection elements, array elements, map keys, and map values must require exact nullability, ref tracking, generic arity, and type shape except documented user-type family normalization.
- Root deserialization graph memory budget state belongs to `ReadContext`. C# public roots are
memory-backed today, but the graph budget uses the same fixed default for every root shape.
diff --git a/.gitignore b/.gitignore
index b93f7801d..365b6a33d 100644
--- a/.gitignore
+++ b/.gitignore
@@ -130,6 +130,8 @@ csharp/src/Fory/bin/
csharp/src/Fory/obj/
csharp/tests/Fory.Tests/bin/
csharp/tests/Fory.Tests/obj/
+csharp/tests/Fory.ExternalTypes/bin/
+csharp/tests/Fory.ExternalTypes/obj/
csharp/tests/Fory.XlangPeer/bin/
csharp/tests/Fory.XlangPeer/obj/
csharp/artifacts/
diff --git a/benchmarks/csharp/Directory.Build.props b/benchmarks/csharp/Directory.Build.props
new file mode 100644
index 000000000..a712b40f0
--- /dev/null
+++ b/benchmarks/csharp/Directory.Build.props
@@ -0,0 +1,7 @@
+<Project>
+ <PropertyGroup Condition="'$(MSBuildProjectName)' == 'Fory.CSharpBenchmark' Or '$(MSBuildProjectName)' == 'Fory.ExternalTypeBenchmark'">
+ <BaseIntermediateOutputPath>obj/$(MSBuildProjectName)/</BaseIntermediateOutputPath>
+ <BaseOutputPath>bin/$(MSBuildProjectName)/</BaseOutputPath>
+ <DefaultItemExcludes>$(DefaultItemExcludes);obj/**;bin/**</DefaultItemExcludes>
+ </PropertyGroup>
+</Project>
diff --git a/benchmarks/csharp/ExternalEquivalenceBenchmark.cs b/benchmarks/csharp/ExternalEquivalenceBenchmark.cs
new file mode 100644
index 000000000..c835b5a1e
--- /dev/null
+++ b/benchmarks/csharp/ExternalEquivalenceBenchmark.cs
@@ -0,0 +1,597 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+using System.Diagnostics;
+using System.Globalization;
+using System.Runtime.InteropServices;
+using System.Text.Json;
+using ExternalPoint = Apache.Fory.Benchmarks.CSharp.ExternalTypes.Point;
+using ExternalUser = Apache.Fory.Benchmarks.CSharp.ExternalTypes.User;
+using ForyRuntime = Apache.Fory.Fory;
+
+namespace Apache.Fory.Benchmarks.CSharp;
+
+internal sealed record EquivalenceCase(
+ string DataType,
+ string Operation,
+ int SerializedSize,
+ string SerializedFrameBase64,
+ Action Action);
+
+internal sealed record EquivalenceMeasurement(
+ double OperationsPerSecond,
+ double AverageNanoseconds,
+ long Iterations,
+ double ElapsedSeconds);
+
+internal sealed record EquivalenceSideResult(
+ string DataType,
+ string Operation,
+ int SerializedSize,
+ string SerializedFrameBase64,
+ EquivalenceMeasurement Measurement,
+ double? AllocatedBytesPerOperation);
+
+internal sealed record EquivalenceSideOutput(
+ string GeneratedAtUtc,
+ string RuntimeVersion,
+ string OsDescription,
+ string OsArchitecture,
+ string ProcessArchitecture,
+ int ProcessorCount,
+ double WarmupSeconds,
+ double DurationSeconds,
+ int AllocationIterations,
+ string Implementation,
+ List<EquivalenceSideResult> Results);
+
+internal static class ExternalEquivalenceBenchmark
+{
+ private const uint UserTypeId = 101;
+ private const uint PointTypeId = 102;
+ private const uint UserHolderTypeId = 103;
+ private const uint ListHolderTypeId = 104;
+ private const uint MapHolderTypeId = 105;
+ private const int BatchSize = 256;
+
+ public static int Run(
+ ExternalBenchmarkOptions options,
+ JsonSerializerOptions jsonOptions)
+ {
+ string implementation = ImplementationName(options.Implementation);
+ List<EquivalenceCase> cases = BuildCases(
+ options,
+ options.Implementation);
+ if (cases.Count == 0)
+ {
+ throw new ArgumentException("no external-equivalence benchmark cases selected");
+ }
+
+ Console.WriteLine("=== Fory C# External-Type Equivalence Benchmark ===");
+ Console.WriteLine($"Implementation: {implementation}");
+ Console.WriteLine($"Cases: {cases.Count}");
+ Console.WriteLine(
+ $"Warmup: {options.WarmupSeconds.ToString("F2", CultureInfo.InvariantCulture)}s");
+ Console.WriteLine(
+ $"Duration: {options.DurationSeconds.ToString("F2", CultureInfo.InvariantCulture)}s");
+ Console.WriteLine($"Allocation iterations: {options.AllocationIterations}");
+ Console.WriteLine();
+
+ List<EquivalenceSideResult> results = new(cases.Count);
+ foreach (EquivalenceCase benchmarkCase in cases)
+ {
+ Console.WriteLine(
+ $"Running {implementation}/{benchmarkCase.DataType}/{benchmarkCase.Operation}...");
+ results.Add(RunCase(benchmarkCase, options));
+ }
+
+ EquivalenceSideOutput output = new(
+ GeneratedAtUtc: DateTime.UtcNow.ToString("O", CultureInfo.InvariantCulture),
+ RuntimeVersion: Environment.Version.ToString(),
+ OsDescription: RuntimeInformation.OSDescription,
+ OsArchitecture: RuntimeInformation.OSArchitecture.ToString(),
+ ProcessArchitecture: RuntimeInformation.ProcessArchitecture.ToString(),
+ ProcessorCount: Environment.ProcessorCount,
+ WarmupSeconds: options.WarmupSeconds,
+ DurationSeconds: options.DurationSeconds,
+ AllocationIterations: options.AllocationIterations,
+ Implementation: implementation,
+ Results: results);
+
+ string outputPath = Path.GetFullPath(options.OutputPath);
+ string? parent = Path.GetDirectoryName(outputPath);
+ if (!string.IsNullOrEmpty(parent))
+ {
+ Directory.CreateDirectory(parent);
+ }
+
+ File.WriteAllText(outputPath, JsonSerializer.Serialize(output, jsonOptions));
+
+ PrintSummary(implementation, results);
+ Console.WriteLine();
+ Console.WriteLine($"Results written to {outputPath}");
+ return 0;
+ }
+
+ private static EquivalenceSideResult RunCase(
+ EquivalenceCase benchmarkCase,
+ ExternalBenchmarkOptions options)
+ {
+ RunForDuration(benchmarkCase.Action, options.WarmupSeconds);
+
+ CollectGarbage();
+ EquivalenceMeasurement measurement = MeasureTime(
+ benchmarkCase.Action,
+ options.DurationSeconds);
+
+ double? bytesPerOperation = null;
+ if (options.AllocationIterations > 0)
+ {
+ CollectGarbage();
+ long allocatedBytes = MeasureAllocation(
+ benchmarkCase.Action,
+ options.AllocationIterations);
+ bytesPerOperation =
+ (double)allocatedBytes / options.AllocationIterations;
+ }
+
+ return new EquivalenceSideResult(
+ benchmarkCase.DataType,
+ benchmarkCase.Operation,
+ benchmarkCase.SerializedSize,
+ benchmarkCase.SerializedFrameBase64,
+ measurement,
+ bytesPerOperation);
+ }
+
+ private static EquivalenceMeasurement MeasureTime(Action action, double durationSeconds)
+ {
+ long iterations = 0;
+ Stopwatch stopwatch = Stopwatch.StartNew();
+ while (stopwatch.Elapsed.TotalSeconds < durationSeconds)
+ {
+ for (int i = 0; i < BatchSize; i++)
+ {
+ action();
+ }
+
+ iterations += BatchSize;
+ }
+
+ double elapsed = stopwatch.Elapsed.TotalSeconds;
+ return new EquivalenceMeasurement(
+ iterations / elapsed,
+ elapsed * 1_000_000_000.0 / iterations,
+ iterations,
+ elapsed);
+ }
+
+ private static long MeasureAllocation(Action action, int iterations)
+ {
+ long before = GC.GetAllocatedBytesForCurrentThread();
+ for (int i = 0; i < iterations; i++)
+ {
+ action();
+ }
+
+ return GC.GetAllocatedBytesForCurrentThread() - before;
+ }
+
+ private static void RunForDuration(Action action, double durationSeconds)
+ {
+ Stopwatch stopwatch = Stopwatch.StartNew();
+ while (stopwatch.Elapsed.TotalSeconds < durationSeconds)
+ {
+ action();
+ }
+ }
+
+ private static void CollectGarbage()
+ {
+ GC.Collect();
+ GC.WaitForPendingFinalizers();
+ GC.Collect();
+ }
+
+ private static List<EquivalenceCase> BuildCases(
+ ExternalBenchmarkOptions options,
+ ExternalImplementation implementation)
+ {
+ return implementation switch
+ {
+ ExternalImplementation.Ordinary => BuildOrdinaryCases(options),
+ ExternalImplementation.External => BuildExternalCases(options),
+ _ => throw new ArgumentException(
+ "external-equivalence requires one selected implementation"),
+ };
+ }
+
+ private static List<EquivalenceCase> BuildOrdinaryCases(
+ ExternalBenchmarkOptions options)
+ {
+ ForyRuntime writer = BuildFory();
+ ForyRuntime reader = BuildFory();
+ RegisterOrdinary(writer);
+ RegisterOrdinary(reader);
+
+ List<EquivalenceCase> cases = [];
+ AddCase(
+ "class-root",
+ EquivalenceData.CreateOrdinaryUser(),
+ writer,
+ reader,
+ OrdinaryUsersEqual,
+ options,
+ cases);
+ AddCase(
+ "struct-root",
+ EquivalenceData.CreateOrdinaryPoint(),
+ writer,
+ reader,
+ (expected, decoded) =>
+ expected.X == decoded.X && expected.Y == decoded.Y,
+ options,
+ cases);
+ AddCase(
+ "holder-field",
+ new OrdinaryUserHolder
+ {
+ Value = EquivalenceData.CreateOrdinaryUser(),
+ },
+ writer,
+ reader,
+ (expected, decoded) =>
+ OrdinaryUsersEqual(expected.Value, decoded.Value),
+ options,
+ cases);
+
+ List<OrdinaryUser> list = EquivalenceData.CreateOrdinaryList();
+ AddCase(
+ "list-field",
+ new OrdinaryListHolder
+ {
+ Values = list,
+ },
+ writer,
+ reader,
+ (expected, decoded) =>
+ OrdinaryListsEqual(expected.Values, decoded.Values),
+ options,
+ cases);
+ AddCase(
+ "list-root",
+ list,
+ writer,
+ reader,
+ OrdinaryListsEqual,
+ options,
+ cases);
+
+ Dictionary<string, OrdinaryUser> map = EquivalenceData.CreateOrdinaryMap();
+ AddCase(
+ "map-field",
+ new OrdinaryMapHolder
+ {
+ Values = map,
+ },
+ writer,
+ reader,
+ (expected, decoded) =>
+ OrdinaryMapsEqual(expected.Values, decoded.Values),
+ options,
+ cases);
+ AddCase(
+ "map-root",
+ map,
+ writer,
+ reader,
+ OrdinaryMapsEqual,
+ options,
+ cases);
+ return cases;
+ }
+
+ private static List<EquivalenceCase> BuildExternalCases(
+ ExternalBenchmarkOptions options)
+ {
+ ForyRuntime writer = BuildFory();
+ ForyRuntime reader = BuildFory();
+ RegisterTargetTypes(writer);
+ RegisterTargetTypes(reader);
+
+ List<EquivalenceCase> cases = [];
+ AddCase(
+ "class-root",
+ EquivalenceData.CreateExternalUser(),
+ writer,
+ reader,
+ ExternalUsersEqual,
+ options,
+ cases);
+ AddCase(
+ "struct-root",
+ EquivalenceData.CreateExternalPoint(),
+ writer,
+ reader,
+ (expected, decoded) =>
+ expected.X == decoded.X && expected.Y == decoded.Y,
+ options,
+ cases);
+ AddCase(
+ "holder-field",
+ new ExternalUserHolder
+ {
+ Value = EquivalenceData.CreateExternalUser(),
+ },
+ writer,
+ reader,
+ (expected, decoded) =>
+ ExternalUsersEqual(expected.Value, decoded.Value),
+ options,
+ cases);
+
+ List<ExternalUser> list = EquivalenceData.CreateExternalList();
+ AddCase(
+ "list-field",
+ new ExternalListHolder
+ {
+ Values = list,
+ },
+ writer,
+ reader,
+ (expected, decoded) =>
+ ExternalListsEqual(expected.Values, decoded.Values),
+ options,
+ cases);
+ AddCase(
+ "list-root",
+ list,
+ writer,
+ reader,
+ ExternalListsEqual,
+ options,
+ cases);
+
+ Dictionary<string, ExternalUser> map = EquivalenceData.CreateExternalMap();
+ AddCase(
+ "map-field",
+ new ExternalMapHolder
+ {
+ Values = map,
+ },
+ writer,
+ reader,
+ (expected, decoded) =>
+ ExternalMapsEqual(expected.Values, decoded.Values),
+ options,
+ cases);
+ AddCase(
+ "map-root",
+ map,
+ writer,
+ reader,
+ ExternalMapsEqual,
+ options,
+ cases);
+ return cases;
+ }
+
+ private static ForyRuntime BuildFory()
+ {
+ return ForyRuntime.Builder().Compatible(true).Build();
+ }
+
+ private static void RegisterOrdinary(ForyRuntime fory)
+ {
+ fory.Register<OrdinaryUser>(UserTypeId);
+ fory.Register<OrdinaryPoint>(PointTypeId);
+ fory.Register<OrdinaryUserHolder>(UserHolderTypeId);
+ fory.Register<OrdinaryListHolder>(ListHolderTypeId);
+ fory.Register<OrdinaryMapHolder>(MapHolderTypeId);
+ }
+
+ private static void RegisterTargetTypes(ForyRuntime fory)
+ {
+ fory.Register<ExternalUser>(UserTypeId);
+ fory.Register<ExternalPoint>(PointTypeId);
+ fory.Register<ExternalUserHolder>(UserHolderTypeId);
+ fory.Register<ExternalListHolder>(ListHolderTypeId);
+ fory.Register<ExternalMapHolder>(MapHolderTypeId);
+ }
+
+ private static void AddCase<T>(
+ string dataType,
+ T value,
+ ForyRuntime writer,
+ ForyRuntime reader,
+ Func<T, T, bool> valuesEqual,
+ ExternalBenchmarkOptions options,
+ List<EquivalenceCase> cases)
+ {
+ if (!options.IsDataEnabled(dataType))
+ {
+ return;
+ }
+
+ byte[] payload = writer.Serialize(value);
+ T decoded = reader.Deserialize<T>(payload);
+ if (!valuesEqual(value, decoded))
+ {
+ throw new InvalidOperationException(
+ $"decoded value differs for {dataType}");
+ }
+
+ string frameBase64 = Convert.ToBase64String(payload);
+ Action serialize = () =>
+ {
+ EquivalenceSink<byte[]>.Value = writer.Serialize(value);
+ };
+ Action deserialize = () =>
+ {
+ EquivalenceSink<T>.Value = reader.Deserialize<T>(payload);
+ };
+
+ cases.Add(new EquivalenceCase(
+ dataType,
+ "serialize",
+ payload.Length,
+ frameBase64,
+ serialize));
+ cases.Add(new EquivalenceCase(
+ dataType,
+ "deserialize",
+ payload.Length,
+ frameBase64,
+ deserialize));
+ }
+
+ private static bool OrdinaryUsersEqual(
+ OrdinaryUser expected,
+ OrdinaryUser decoded)
+ {
+ return expected.Id == decoded.Id
+ && expected.Score == decoded.Score
+ && expected.Name == decoded.Name;
+ }
+
+ private static bool ExternalUsersEqual(
+ ExternalUser expected,
+ ExternalUser decoded)
+ {
+ return expected.Id == decoded.Id
+ && expected.Score == decoded.Score
+ && expected.Name == decoded.Name;
+ }
+
+ private static bool OrdinaryListsEqual(
+ IReadOnlyList<OrdinaryUser> expected,
+ IReadOnlyList<OrdinaryUser> decoded)
+ {
+ if (expected.Count != decoded.Count)
+ {
+ return false;
+ }
+
+ for (int i = 0; i < expected.Count; i++)
+ {
+ if (!OrdinaryUsersEqual(expected[i], decoded[i]))
+ {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ private static bool ExternalListsEqual(
+ IReadOnlyList<ExternalUser> expected,
+ IReadOnlyList<ExternalUser> decoded)
+ {
+ if (expected.Count != decoded.Count)
+ {
+ return false;
+ }
+
+ for (int i = 0; i < expected.Count; i++)
+ {
+ if (!ExternalUsersEqual(expected[i], decoded[i]))
+ {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ private static bool OrdinaryMapsEqual(
+ IReadOnlyDictionary<string, OrdinaryUser> expected,
+ IReadOnlyDictionary<string, OrdinaryUser> decoded)
+ {
+ if (expected.Count != decoded.Count)
+ {
+ return false;
+ }
+
+ foreach ((string key, OrdinaryUser expectedUser) in expected)
+ {
+ if (!decoded.TryGetValue(key, out OrdinaryUser? decodedUser)
+ || !OrdinaryUsersEqual(expectedUser, decodedUser))
+ {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ private static bool ExternalMapsEqual(
+ IReadOnlyDictionary<string, ExternalUser> expected,
+ IReadOnlyDictionary<string, ExternalUser> decoded)
+ {
+ if (expected.Count != decoded.Count)
+ {
+ return false;
+ }
+
+ foreach ((string key, ExternalUser expectedUser) in expected)
+ {
+ if (!decoded.TryGetValue(key, out ExternalUser? decodedUser)
+ || !ExternalUsersEqual(expectedUser, decodedUser))
+ {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ private static string ImplementationName(ExternalImplementation implementation)
+ {
+ return implementation switch
+ {
+ ExternalImplementation.Ordinary => "ordinary",
+ ExternalImplementation.External => "external",
+ _ => throw new ArgumentException(
+ "external-equivalence requires one selected implementation"),
+ };
+ }
+
+ private static void PrintSummary(
+ string implementation,
+ List<EquivalenceSideResult> results)
+ {
+ Console.WriteLine();
+ Console.WriteLine(
+ $"=== External-Type {implementation} Summary ===");
+ foreach (EquivalenceSideResult result in results)
+ {
+ Console.WriteLine(
+ $"{result.DataType}/{result.Operation}: "
+ + $"{result.Measurement.AverageNanoseconds:N1} ns/op");
+ if (result.AllocatedBytesPerOperation.HasValue)
+ {
+ Console.WriteLine(
+ $" allocated={result.AllocatedBytesPerOperation:N2} B/op");
+ }
+ }
+ }
+
+ private static class EquivalenceSink<T>
+ {
+ public static T Value = default!;
+ }
+}
diff --git a/benchmarks/csharp/ExternalEquivalenceModels.cs b/benchmarks/csharp/ExternalEquivalenceModels.cs
new file mode 100644
index 000000000..81e468e1a
--- /dev/null
+++ b/benchmarks/csharp/ExternalEquivalenceModels.cs
@@ -0,0 +1,221 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+using Apache.Fory;
+using ExternalPoint = Apache.Fory.Benchmarks.CSharp.ExternalTypes.Point;
+using ExternalUser = Apache.Fory.Benchmarks.CSharp.ExternalTypes.User;
+
+namespace Apache.Fory.Benchmarks.CSharp;
+
+[ForyStruct]
+internal sealed class OrdinaryUser
+{
+ [ForyField(1)]
+ public int Id { get; set; }
+
+ [ForyField(2)]
+ public long Score { get; set; }
+
+ [ForyField(3)]
+ public string Name { get; set; } = string.Empty;
+}
+
+[ForyStruct(Target = typeof(ExternalUser))]
+internal abstract class UserSerializer
+{
+ [ForyField(1)]
+ public abstract int Id { get; }
+
+ [ForyField(2)]
+ public abstract long Score { get; }
+
+ [ForyField(3)]
+ public abstract string Name { get; }
+}
+
+[ForyStruct]
+internal struct OrdinaryPoint
+{
+ [ForyField(1)]
+ public int X { get; set; }
+
+ [ForyField(2)]
+ public long Y { get; set; }
+}
+
+[ForyStruct(Target = typeof(ExternalPoint))]
+internal abstract class PointSerializer
+{
+ [ForyField(1)]
+ public abstract int X { get; }
+
+ [ForyField(2)]
+ public abstract long Y { get; }
+}
+
+[ForyStruct]
+internal sealed class OrdinaryUserHolder
+{
+ [ForyField(1)]
+ public OrdinaryUser Value { get; set; } = new();
+}
+
+[ForyStruct]
+internal sealed class ExternalUserHolder
+{
+ [ForyField(1)]
+ public ExternalUser Value { get; set; } = new();
+}
+
+[ForyStruct]
+internal sealed class OrdinaryListHolder
+{
+ [ForyField(1)]
+ public List<OrdinaryUser> Values { get; set; } = [];
+}
+
+[ForyStruct]
+internal sealed class ExternalListHolder
+{
+ [ForyField(1)]
+ public List<ExternalUser> Values { get; set; } = [];
+}
+
+[ForyStruct]
+internal sealed class OrdinaryMapHolder
+{
+ [ForyField(1)]
+ public Dictionary<string, OrdinaryUser> Values { get; set; } = [];
+}
+
+[ForyStruct]
+internal sealed class ExternalMapHolder
+{
+ [ForyField(1)]
+ public Dictionary<string, ExternalUser> Values { get; set; } = [];
+}
+
+internal static class EquivalenceData
+{
+ private const int ElementCount = 8;
+
+ public static OrdinaryUser CreateOrdinaryUser()
+ {
+ return new OrdinaryUser
+ {
+ Id = 7,
+ Score = 123_456_789,
+ Name = "external-type-benchmark",
+ };
+ }
+
+ public static ExternalUser CreateExternalUser()
+ {
+ return new ExternalUser
+ {
+ Id = 7,
+ Score = 123_456_789,
+ Name = "external-type-benchmark",
+ };
+ }
+
+ public static OrdinaryPoint CreateOrdinaryPoint()
+ {
+ return new OrdinaryPoint
+ {
+ X = 17,
+ Y = 987_654_321,
+ };
+ }
+
+ public static ExternalPoint CreateExternalPoint()
+ {
+ return new ExternalPoint
+ {
+ X = 17,
+ Y = 987_654_321,
+ };
+ }
+
+ public static List<OrdinaryUser> CreateOrdinaryList()
+ {
+ List<OrdinaryUser> values = new(ElementCount);
+ for (int i = 0; i < ElementCount; i++)
+ {
+ values.Add(new OrdinaryUser
+ {
+ Id = i,
+ Score = 100_000L + i,
+ Name = $"user-{i}",
+ });
+ }
+
+ return values;
+ }
+
+ public static List<ExternalUser> CreateExternalList()
+ {
+ List<ExternalUser> values = new(ElementCount);
+ for (int i = 0; i < ElementCount; i++)
+ {
+ values.Add(new ExternalUser
+ {
+ Id = i,
+ Score = 100_000L + i,
+ Name = $"user-{i}",
+ });
+ }
+
+ return values;
+ }
+
+ public static Dictionary<string, OrdinaryUser> CreateOrdinaryMap()
+ {
+ Dictionary<string, OrdinaryUser> values = new(ElementCount, StringComparer.Ordinal);
+ for (int i = 0; i < ElementCount; i++)
+ {
+ values.Add(
+ $"key-{i}",
+ new OrdinaryUser
+ {
+ Id = i,
+ Score = 100_000L + i,
+ Name = $"user-{i}",
+ });
+ }
+
+ return values;
+ }
+
+ public static Dictionary<string, ExternalUser> CreateExternalMap()
+ {
+ Dictionary<string, ExternalUser> values = new(ElementCount, StringComparer.Ordinal);
+ for (int i = 0; i < ElementCount; i++)
+ {
+ values.Add(
+ $"key-{i}",
+ new ExternalUser
+ {
+ Id = i,
+ Score = 100_000L + i,
+ Name = $"user-{i}",
+ });
+ }
+
+ return values;
+ }
+}
diff --git a/benchmarks/csharp/ExternalEquivalenceProgram.cs b/benchmarks/csharp/ExternalEquivalenceProgram.cs
new file mode 100644
index 000000000..3933395fc
--- /dev/null
+++ b/benchmarks/csharp/ExternalEquivalenceProgram.cs
@@ -0,0 +1,231 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+using System.Globalization;
+using System.Text.Json;
+
+namespace Apache.Fory.Benchmarks.CSharp;
+
+internal enum ExternalImplementation
+{
+ None,
+ Ordinary,
+ External,
+}
+
+internal sealed class ExternalBenchmarkOptions
+{
+ public HashSet<string> DataFilter { get; init; } = [];
+
+ public double WarmupSeconds { get; init; } = 1.0;
+
+ public double DurationSeconds { get; init; } = 3.0;
+
+ public string OutputPath { get; init; } = "external_equivalence_results.json";
+
+ public ExternalImplementation Implementation { get; init; }
+
+ public int AllocationIterations { get; init; }
+
+ public bool ShowHelp { get; init; }
+
+ public static ExternalBenchmarkOptions Parse(string[] args)
+ {
+ HashSet<string> dataFilter = new(StringComparer.OrdinalIgnoreCase);
+ double warmupSeconds = 1.0;
+ double durationSeconds = 3.0;
+ string outputPath = "external_equivalence_results.json";
+ ExternalImplementation implementation = ExternalImplementation.None;
+ int allocationIterations = 0;
+ bool showHelp = false;
+
+ for (int i = 0; i < args.Length; i++)
+ {
+ switch (args[i])
+ {
+ case "--help":
+ case "-h":
+ showHelp = true;
+ break;
+ case "--data":
+ RequireValue(args, i);
+ dataFilter.Add(args[++i]);
+ break;
+ case "--warmup":
+ RequireValue(args, i);
+ warmupSeconds = ParsePositiveDouble(args[++i], "warmup");
+ break;
+ case "--duration":
+ RequireValue(args, i);
+ durationSeconds = ParsePositiveDouble(args[++i], "duration");
+ break;
+ case "--output":
+ RequireValue(args, i);
+ outputPath = args[++i];
+ break;
+ case "--external-implementation":
+ RequireValue(args, i);
+ if (implementation != ExternalImplementation.None)
+ {
+ throw new ArgumentException(
+ "--external-implementation may be specified only once");
+ }
+
+ implementation = ParseImplementation(args[++i]);
+ break;
+ case "--allocation-iterations":
+ RequireValue(args, i);
+ allocationIterations = ParsePositiveInt(
+ args[++i],
+ "allocation-iterations");
+ break;
+ default:
+ throw new ArgumentException($"unknown option: {args[i]}");
+ }
+ }
+
+ if (!showHelp && implementation == ExternalImplementation.None)
+ {
+ throw new ArgumentException(
+ "--external-implementation ordinary|external is required");
+ }
+
+ return new ExternalBenchmarkOptions
+ {
+ DataFilter = dataFilter,
+ WarmupSeconds = warmupSeconds,
+ DurationSeconds = durationSeconds,
+ OutputPath = outputPath,
+ Implementation = implementation,
+ AllocationIterations = allocationIterations,
+ ShowHelp = showHelp,
+ };
+ }
+
+ public bool IsDataEnabled(string dataType)
+ {
+ return DataFilter.Count == 0 || DataFilter.Contains(dataType);
+ }
+
+ private static void RequireValue(string[] args, int index)
+ {
+ if (index + 1 >= args.Length)
+ {
+ throw new ArgumentException($"missing value for option {args[index]}");
+ }
+ }
+
+ private static double ParsePositiveDouble(string text, string name)
+ {
+ if (!double.TryParse(
+ text,
+ NumberStyles.Float,
+ CultureInfo.InvariantCulture,
+ out double value)
+ || value <= 0)
+ {
+ throw new ArgumentException($"{name} must be a positive number, got '{text}'");
+ }
+
+ return value;
+ }
+
+ private static int ParsePositiveInt(string text, string name)
+ {
+ if (!int.TryParse(
+ text,
+ NumberStyles.None,
+ CultureInfo.InvariantCulture,
+ out int value)
+ || value <= 0)
+ {
+ throw new ArgumentException($"{name} must be a positive integer, got '{text}'");
+ }
+
+ return value;
+ }
+
+ private static ExternalImplementation ParseImplementation(string text)
+ {
+ if (string.Equals(text, "ordinary", StringComparison.OrdinalIgnoreCase))
+ {
+ return ExternalImplementation.Ordinary;
+ }
+
+ if (string.Equals(text, "external", StringComparison.OrdinalIgnoreCase))
+ {
+ return ExternalImplementation.External;
+ }
+
+ throw new ArgumentException(
+ $"external-implementation must be ordinary or external, got '{text}'");
+ }
+}
+
+internal static class ExternalEquivalenceProgram
+{
+ private static readonly JsonSerializerOptions JsonOptions = new()
+ {
+ WriteIndented = true,
+ };
+
+ private static int Main(string[] args)
+ {
+ ExternalBenchmarkOptions options;
+ try
+ {
+ options = ExternalBenchmarkOptions.Parse(args);
+ }
+ catch (Exception ex)
+ {
+ Console.Error.WriteLine($"error: {ex.Message}");
+ PrintUsage();
+ return 1;
+ }
+
+ if (options.ShowHelp)
+ {
+ PrintUsage();
+ return 0;
+ }
+
+ try
+ {
+ return ExternalEquivalenceBenchmark.Run(options, JsonOptions);
+ }
+ catch (Exception ex)
+ {
+ Console.Error.WriteLine($"failed to run external-equivalence benchmarks: {ex}");
+ return 1;
+ }
+ }
+
+ private static void PrintUsage()
+ {
+ Console.WriteLine("Usage: dotnet run -c Release -- [OPTIONS]");
+ Console.WriteLine();
+ Console.WriteLine("Options:");
+ Console.WriteLine(
+ " --data <class-root|struct-root|holder-field|list-field|list-root|map-field|map-root>");
+ Console.WriteLine(" --warmup <seconds>");
+ Console.WriteLine(" --duration <seconds>");
+ Console.WriteLine(" --output <path>");
+ Console.WriteLine(" --external-implementation <ordinary|external>");
+ Console.WriteLine(" --allocation-iterations <count>");
+ Console.WriteLine(" --help");
+ }
+}
diff --git a/benchmarks/csharp/Fory.CSharpBenchmark.csproj b/benchmarks/csharp/Fory.CSharpBenchmark.csproj
index 7cc9ebc23..588e23b51 100644
--- a/benchmarks/csharp/Fory.CSharpBenchmark.csproj
+++ b/benchmarks/csharp/Fory.CSharpBenchmark.csproj
@@ -12,6 +12,10 @@
<PackageReference Include="protobuf-net" Version="3.2.56" />
</ItemGroup>
+ <ItemGroup>
+ <Compile Remove="ExternalEquivalenceBenchmark.cs;ExternalEquivalenceModels.cs;ExternalEquivalenceProgram.cs;Fory.ExternalBenchmarkTypes/**/*.cs" />
+ </ItemGroup>
+
<ItemGroup>
<ProjectReference Include="../../csharp/src/Fory/Fory.csproj" />
<ProjectReference Include="../../csharp/src/Fory.Generator/Fory.Generator.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
diff --git a/benchmarks/csharp/Fory.ExternalBenchmarkTypes/ExternalModels.cs b/benchmarks/csharp/Fory.ExternalBenchmarkTypes/ExternalModels.cs
new file mode 100644
index 000000000..b9790bbd4
--- /dev/null
+++ b/benchmarks/csharp/Fory.ExternalBenchmarkTypes/ExternalModels.cs
@@ -0,0 +1,34 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+namespace Apache.Fory.Benchmarks.CSharp.ExternalTypes;
+
+public sealed class User
+{
+ public int Id { get; set; }
+
+ public long Score { get; set; }
+
+ public string Name { get; set; } = string.Empty;
+}
+
+public struct Point
+{
+ public int X { get; set; }
+
+ public long Y { get; set; }
+}
diff --git a/benchmarks/csharp/Fory.ExternalBenchmarkTypes/Fory.ExternalBenchmarkTypes.csproj b/benchmarks/csharp/Fory.ExternalBenchmarkTypes/Fory.ExternalBenchmarkTypes.csproj
new file mode 100644
index 000000000..f4e536060
--- /dev/null
+++ b/benchmarks/csharp/Fory.ExternalBenchmarkTypes/Fory.ExternalBenchmarkTypes.csproj
@@ -0,0 +1,8 @@
+<Project Sdk="Microsoft.NET.Sdk">
+ <PropertyGroup>
+ <TargetFramework>net8.0</TargetFramework>
+ <LangVersion>12.0</LangVersion>
+ <ImplicitUsings>enable</ImplicitUsings>
+ <Nullable>enable</Nullable>
+ </PropertyGroup>
+</Project>
diff --git a/benchmarks/csharp/Fory.CSharpBenchmark.csproj b/benchmarks/csharp/Fory.ExternalTypeBenchmark.csproj
similarity index 62%
copy from benchmarks/csharp/Fory.CSharpBenchmark.csproj
copy to benchmarks/csharp/Fory.ExternalTypeBenchmark.csproj
index 7cc9ebc23..11d76006e 100644
--- a/benchmarks/csharp/Fory.CSharpBenchmark.csproj
+++ b/benchmarks/csharp/Fory.ExternalTypeBenchmark.csproj
@@ -5,14 +5,17 @@
<LangVersion>12.0</LangVersion>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
+ <EnableDefaultCompileItems>false</EnableDefaultCompileItems>
</PropertyGroup>
<ItemGroup>
- <PackageReference Include="MessagePack" Version="2.5.301" />
- <PackageReference Include="protobuf-net" Version="3.2.56" />
+ <Compile Include="ExternalEquivalenceBenchmark.cs" />
+ <Compile Include="ExternalEquivalenceModels.cs" />
+ <Compile Include="ExternalEquivalenceProgram.cs" />
</ItemGroup>
<ItemGroup>
+ <ProjectReference Include="./Fory.ExternalBenchmarkTypes/Fory.ExternalBenchmarkTypes.csproj" />
<ProjectReference Include="../../csharp/src/Fory/Fory.csproj" />
<ProjectReference Include="../../csharp/src/Fory.Generator/Fory.Generator.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
</ItemGroup>
diff --git a/benchmarks/csharp/README.md b/benchmarks/csharp/README.md
index bd080aa78..63f17b5b9 100644
--- a/benchmarks/csharp/README.md
+++ b/benchmarks/csharp/README.md
@@ -36,6 +36,8 @@ Options:
--serializer <fory|protobuf|msgpack>
--duration <seconds>
--warmup <seconds>
+ --external-equivalence
+ --allocation-iterations <count>
```
Examples:
@@ -51,6 +53,85 @@ Examples:
./run.sh --duration 10 --warmup 2
```
+## External-Type Equivalence
+
+The opt-in external-type mode compares generated serializers for ordinary
+benchmark models with external structural serializers for equivalent models
+from a Fory-free project:
+
+```bash
+./run.sh --external-equivalence --duration 10 --warmup 3
+```
+
+It covers direct class and struct roots, a direct holder field, list and map
+fields, and list and map roots. Each ordinary/external pair uses the same Fory
+configuration, numeric registration IDs, field schemas, values, and native
+carrier serializers.
+
+`Fory.CSharpBenchmark.csproj` owns only the existing Fory, protobuf-net, and
+MessagePack benchmarks. `Fory.ExternalTypeBenchmark.csproj` is a parallel
+package that owns the external-type models and measurements. Building or
+running the ordinary benchmark therefore does not compile external-type models
+or their generated serializer instantiations.
+
+The runner builds the external-type benchmark once. For each selected lane, it
+launches two balanced adjacent pairs in fixed order: ordinary then external,
+followed by external then ordinary. Each of the four workers runs in a fresh
+process and constructs, registers, validates, warms, times, and optionally
+measures allocations for only its selected implementation. Keeping the
+implementations in separate processes prevents shared reference-generic
+Dynamic PGO profiles from biasing the second implementation while retaining
+normal .NET tiering.
+
+Use `--data` to select one of these lanes:
+
+- `class-root`
+- `struct-root`
+- `holder-field`
+- `list-field`
+- `list-root`
+- `map-field`
+- `map-root`
+
+Add a fixed allocation pass with:
+
+```bash
+./run.sh --external-equivalence --allocation-iterations 100000
+```
+
+Registration, serializer resolution, payload creation, delegates, metadata
+caches, and timed warmup for the selected implementation are completed before
+allocation counters start. Allocation results use
+`GC.GetAllocatedBytesForCurrentThread()` and report bytes per operation.
+
+Results are written to
+`build/external_equivalence_results.json`. Per-process results, including a
+Base64 proof frame, are written under `build/external_equivalence_sides/` with
+the lane, one-based sample index, and implementation in each filename. After
+every worker finishes, the merger rejects missing, duplicate, reordered, or
+reused samples, incompatible runtime metadata, serialized size or byte
+differences, and allocation differences. It reports the median ordinary and
+external throughput and latency from the two samples per implementation. The
+combined JSON records the sample count and fixed pair orders. This opt-in mode
+does not invoke the default Python report generator or update the published
+36-case report.
+
+The benchmark executable requires exactly one implementation for direct worker
+use:
+
+```bash
+dotnet run -c Release --no-build \
+ --project ./Fory.ExternalTypeBenchmark.csproj -- \
+ --external-implementation ordinary \
+ --data class-root \
+ --duration 10 \
+ --warmup 3 \
+ --output build/external_equivalence_sides/class-root-direct-ordinary.json
+```
+
+Use `ordinary` or `external`. `run.sh` owns the paired process ordering and
+normally supplies this selector.
+
## Schema Mismatch Mode
Set `FORY_BENCH_SCHEMA_MISMATCH=1` to run the Fory-only compatible-read
diff --git a/benchmarks/csharp/external_equivalence_report.py b/benchmarks/csharp/external_equivalence_report.py
new file mode 100755
index 000000000..95a9944d4
--- /dev/null
+++ b/benchmarks/csharp/external_equivalence_report.py
@@ -0,0 +1,497 @@
+#!/usr/bin/env python3
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+import argparse
+import base64
+import binascii
+import json
+import math
+import sys
+from datetime import datetime, timezone
+from pathlib import Path
+from statistics import median
+
+LANES = (
+ "class-root",
+ "struct-root",
+ "holder-field",
+ "list-field",
+ "list-root",
+ "map-field",
+ "map-root",
+)
+OPERATIONS = ("serialize", "deserialize")
+IMPLEMENTATIONS = ("ordinary", "external")
+SAMPLE_ORDERS = (
+ ("ordinary", "external"),
+ ("external", "ordinary"),
+)
+TEXT_METADATA = (
+ "RuntimeVersion",
+ "OsDescription",
+ "OsArchitecture",
+ "ProcessArchitecture",
+)
+METADATA_FIELDS = TEXT_METADATA + (
+ "ProcessorCount",
+ "WarmupSeconds",
+ "DurationSeconds",
+ "AllocationIterations",
+)
+
+
+def parse_args(argv=None):
+ parser = argparse.ArgumentParser(
+ description="Merge isolated C# external-equivalence benchmark results."
+ )
+ parser.add_argument(
+ "--lane",
+ action="append",
+ choices=LANES,
+ help="Expected lane; repeat as needed. Defaults to all lanes.",
+ )
+ parser.add_argument(
+ "--sample",
+ action="append",
+ nargs=5,
+ required=True,
+ metavar=("LANE", "INDEX", "ORDER", "FIRST_INPUT", "SECOND_INPUT"),
+ help=(
+ "Balanced sample metadata and worker JSON paths; repeat for each lane "
+ "and sample."
+ ),
+ )
+ parser.add_argument("--output", required=True, help="Combined JSON output path.")
+ return parser.parse_args(argv)
+
+
+def require_object(value, owner: str) -> dict:
+ if not isinstance(value, dict):
+ raise TypeError(f"{owner} must be a JSON object")
+ return value
+
+
+def require_string(value, owner: str) -> str:
+ if not isinstance(value, str) or not value:
+ raise ValueError(f"{owner} must be a non-empty string")
+ return value
+
+
+def require_int(value, owner: str, minimum: int) -> int:
+ if isinstance(value, bool) or not isinstance(value, int) or value < minimum:
+ raise ValueError(
+ f"{owner} must be an integer greater than or equal to {minimum}"
+ )
+ return value
+
+
+def require_number(value, owner: str, positive: bool):
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
+ raise TypeError(f"{owner} must be a number")
+ number = float(value)
+ if not math.isfinite(number) or (number <= 0 if positive else number < 0):
+ qualifier = "positive" if positive else "non-negative"
+ raise ValueError(f"{owner} must be a finite {qualifier} number")
+ return value
+
+
+def validate_metadata(document: dict, path: Path) -> dict:
+ owner = str(path)
+ require_string(document.get("GeneratedAtUtc"), f"{owner}.GeneratedAtUtc")
+ for field in TEXT_METADATA:
+ require_string(document.get(field), f"{owner}.{field}")
+ require_int(document.get("ProcessorCount"), f"{owner}.ProcessorCount", 1)
+ require_number(document.get("WarmupSeconds"), f"{owner}.WarmupSeconds", True)
+ require_number(document.get("DurationSeconds"), f"{owner}.DurationSeconds", True)
+ require_int(
+ document.get("AllocationIterations"),
+ f"{owner}.AllocationIterations",
+ 0,
+ )
+ return {field: document[field] for field in METADATA_FIELDS}
+
+
+def validate_measurement(value, owner: str) -> dict:
+ measurement = require_object(value, owner)
+ for field in ("OperationsPerSecond", "AverageNanoseconds", "ElapsedSeconds"):
+ require_number(measurement.get(field), f"{owner}.{field}", True)
+ require_int(measurement.get("Iterations"), f"{owner}.Iterations", 1)
+ return measurement
+
+
+def decode_frame(value, owner: str, serialized_size: int) -> bytes:
+ encoded = require_string(value, owner)
+ try:
+ frame = base64.b64decode(encoded, validate=True)
+ except (binascii.Error, ValueError) as error:
+ raise ValueError(f"{owner} is not valid Base64: {error}") from error
+ if base64.b64encode(frame).decode("ascii") != encoded:
+ raise ValueError(f"{owner} is not canonical Base64")
+ if len(frame) != serialized_size:
+ raise ValueError(
+ f"{owner} decodes to {len(frame)} bytes, expected {serialized_size}"
+ )
+ return frame
+
+
+def sample_order_name(order) -> str:
+ return "-".join(order)
+
+
+def parse_sample_specs(raw_samples, expected_lanes):
+ expected_lane_set = set(expected_lanes)
+ expected_specs = {
+ (lane, index): order
+ for lane in expected_lanes
+ for index, order in enumerate(SAMPLE_ORDERS, start=1)
+ }
+ specs = {}
+ input_owners = {}
+
+ for raw_sample in raw_samples:
+ lane, raw_index, order_name, first_input, second_input = raw_sample
+ if lane not in expected_lane_set:
+ raise ValueError(f"sample lane is not expected: {lane!r}")
+ try:
+ sample_index = int(raw_index)
+ except ValueError as error:
+ raise ValueError(
+ f"sample index must be an integer: {raw_index!r}"
+ ) from error
+ if raw_index != str(sample_index):
+ raise ValueError(
+ f"sample index must use canonical decimal form: {raw_index!r}"
+ )
+
+ key = (lane, sample_index)
+ expected_order = expected_specs.get(key)
+ if expected_order is None:
+ raise ValueError(f"unexpected sample index for {lane}: {sample_index}")
+ if key in specs:
+ raise ValueError(f"duplicate sample for {lane}/{sample_index}")
+
+ expected_order_name = sample_order_name(expected_order)
+ if order_name != expected_order_name:
+ raise ValueError(
+ f"sample {lane}/{sample_index} order must be "
+ f"{expected_order_name}, got {order_name}"
+ )
+
+ paths = (
+ Path(
+ require_string(first_input, f"sample {lane}/{sample_index} first input")
+ ),
+ Path(
+ require_string(
+ second_input,
+ f"sample {lane}/{sample_index} second input",
+ )
+ ),
+ )
+ for path in paths:
+ normalized = path.resolve()
+ if normalized in input_owners:
+ raise ValueError(
+ f"worker input {path} is reused by {input_owners[normalized]} "
+ f"and {lane}/{sample_index}"
+ )
+ input_owners[normalized] = f"{lane}/{sample_index}"
+
+ specs[key] = {
+ "Order": expected_order,
+ "Paths": paths,
+ }
+
+ missing = set(expected_specs) - set(specs)
+ if missing:
+ raise ValueError(
+ "missing samples: "
+ + ", ".join(f"{lane}/{index}" for lane, index in sorted(missing))
+ )
+ return specs
+
+
+def load_worker(path: Path, expected_lane: str, expected_implementation: str):
+ with path.open("r", encoding="utf-8") as source:
+ document = require_object(json.load(source), str(path))
+
+ metadata = validate_metadata(document, path)
+ implementation = require_string(
+ document.get("Implementation"), f"{path}.Implementation"
+ )
+ if implementation != expected_implementation:
+ raise ValueError(
+ f"{path}.Implementation must be {expected_implementation}, "
+ f"got {implementation}"
+ )
+
+ raw_results = document.get("Results")
+ if not isinstance(raw_results, list) or len(raw_results) != len(OPERATIONS):
+ raise ValueError(f"{path}.Results must contain exactly two operations")
+
+ results = {}
+ for index, raw_result in enumerate(raw_results):
+ owner = f"{path}.Results[{index}]"
+ result = require_object(raw_result, owner)
+ lane = result.get("DataType")
+ if lane != expected_lane:
+ raise ValueError(f"{owner}.DataType must be {expected_lane}, got {lane!r}")
+ operation = result.get("Operation")
+ if operation not in OPERATIONS:
+ raise ValueError(f"{owner}.Operation must be serialize or deserialize")
+ if operation in results:
+ raise ValueError(
+ f"duplicate result for {expected_lane}/{operation} in {path}"
+ )
+
+ serialized_size = require_int(
+ result.get("SerializedSize"), f"{owner}.SerializedSize", 0
+ )
+ frame = decode_frame(
+ result.get("SerializedFrameBase64"),
+ f"{owner}.SerializedFrameBase64",
+ serialized_size,
+ )
+ measurement = validate_measurement(
+ result.get("Measurement"), f"{owner}.Measurement"
+ )
+ allocated = result.get("AllocatedBytesPerOperation")
+ if metadata["AllocationIterations"] == 0:
+ if allocated is not None:
+ raise ValueError(
+ f"{owner}.AllocatedBytesPerOperation must be null when "
+ "allocation measurement is disabled"
+ )
+ elif allocated is None:
+ raise ValueError(
+ f"{owner}.AllocatedBytesPerOperation is required when "
+ "allocation measurement is enabled"
+ )
+ else:
+ require_number(
+ allocated,
+ f"{owner}.AllocatedBytesPerOperation",
+ False,
+ )
+
+ results[operation] = {
+ "SerializedSize": serialized_size,
+ "Frame": frame,
+ "Measurement": measurement,
+ "AllocatedBytesPerOperation": allocated,
+ }
+
+ missing_operations = set(OPERATIONS) - set(results)
+ if missing_operations:
+ raise ValueError(
+ f"{path} is missing operations: {', '.join(sorted(missing_operations))}"
+ )
+ if (
+ results["serialize"]["SerializedSize"]
+ != results["deserialize"]["SerializedSize"]
+ or results["serialize"]["Frame"] != results["deserialize"]["Frame"]
+ ):
+ raise ValueError(
+ f"serialized frame differs between operations for "
+ f"{expected_implementation}/{expected_lane} in {path}"
+ )
+ return metadata, results
+
+
+def load_samples(specs, expected_lanes):
+ metadata = None
+ results = {}
+
+ for lane in expected_lanes:
+ for sample_index, expected_order in enumerate(SAMPLE_ORDERS, start=1):
+ spec = specs[(lane, sample_index)]
+ if spec["Order"] != expected_order:
+ raise ValueError(
+ f"internal sample order mismatch for {lane}/{sample_index}"
+ )
+ for implementation, path in zip(expected_order, spec["Paths"]):
+ current_metadata, worker_results = load_worker(
+ path,
+ lane,
+ implementation,
+ )
+ if metadata is None:
+ metadata = current_metadata
+ elif current_metadata != metadata:
+ differences = [
+ field
+ for field in METADATA_FIELDS
+ if current_metadata[field] != metadata[field]
+ ]
+ raise ValueError(
+ f"{path} has incompatible metadata fields: "
+ f"{', '.join(differences)}"
+ )
+
+ for operation, result in worker_results.items():
+ results[(implementation, lane, sample_index, operation)] = result
+
+ if metadata is None:
+ raise ValueError("no benchmark samples were loaded")
+ return metadata, results
+
+
+def median_summary(samples) -> dict:
+ return {
+ "OperationsPerSecond": median(
+ sample["Measurement"]["OperationsPerSecond"] for sample in samples
+ ),
+ "AverageNanoseconds": median(
+ sample["Measurement"]["AverageNanoseconds"] for sample in samples
+ ),
+ }
+
+
+def merge_results(metadata: dict, results: dict, expected_lanes) -> dict:
+ expected_keys = {
+ (implementation, lane, sample_index, operation)
+ for implementation in IMPLEMENTATIONS
+ for lane in expected_lanes
+ for sample_index in range(1, len(SAMPLE_ORDERS) + 1)
+ for operation in OPERATIONS
+ }
+ missing = expected_keys - set(results)
+ if missing:
+ raise ValueError(
+ "missing results: "
+ + ", ".join(
+ f"{implementation}/{lane}/{sample_index}/{operation}"
+ for implementation, lane, sample_index, operation in sorted(missing)
+ )
+ )
+ unexpected = set(results) - expected_keys
+ if unexpected:
+ raise ValueError(
+ "unexpected results: "
+ + ", ".join(
+ f"{implementation}/{lane}/{sample_index}/{operation}"
+ for implementation, lane, sample_index, operation in sorted(unexpected)
+ )
+ )
+
+ combined_results = []
+ for lane in expected_lanes:
+ baseline = results[("ordinary", lane, 1, "serialize")]
+ lane_samples = [
+ results[(implementation, lane, sample_index, operation)]
+ for implementation in IMPLEMENTATIONS
+ for sample_index in range(1, len(SAMPLE_ORDERS) + 1)
+ for operation in OPERATIONS
+ ]
+ for sample in lane_samples:
+ if (
+ sample["SerializedSize"] != baseline["SerializedSize"]
+ or sample["Frame"] != baseline["Frame"]
+ ):
+ raise ValueError(f"serialized frame differs between samples for {lane}")
+
+ for operation in OPERATIONS:
+ ordinary_samples = [
+ results[("ordinary", lane, sample_index, operation)]
+ for sample_index in range(1, len(SAMPLE_ORDERS) + 1)
+ ]
+ external_samples = [
+ results[("external", lane, sample_index, operation)]
+ for sample_index in range(1, len(SAMPLE_ORDERS) + 1)
+ ]
+ operation_samples = ordinary_samples + external_samples
+ allocations = {
+ sample["AllocatedBytesPerOperation"] for sample in operation_samples
+ }
+ if len(allocations) != 1:
+ raise ValueError(
+ f"allocation mismatch between samples for {lane}/{operation}"
+ )
+
+ allocated_bytes = operation_samples[0]["AllocatedBytesPerOperation"]
+ ordinary_median = median_summary(ordinary_samples)
+ external_median = median_summary(external_samples)
+ slowdown = (
+ external_median["AverageNanoseconds"]
+ / ordinary_median["AverageNanoseconds"]
+ - 1.0
+ ) * 100.0
+ allocation_enabled = metadata["AllocationIterations"] > 0
+ combined_results.append(
+ {
+ "DataType": lane,
+ "Operation": operation,
+ "SerializedSize": baseline["SerializedSize"],
+ "OrdinaryMedian": ordinary_median,
+ "ExternalMedian": external_median,
+ "SlowdownPercent": slowdown,
+ "OrdinaryAllocatedBytesPerOperation": allocated_bytes,
+ "ExternalAllocatedBytesPerOperation": allocated_bytes,
+ "AllocationEqual": True if allocation_enabled else None,
+ }
+ )
+
+ return {
+ "GeneratedAtUtc": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"),
+ **metadata,
+ "SamplesPerImplementation": len(SAMPLE_ORDERS),
+ "SampleOrders": [sample_order_name(order) for order in SAMPLE_ORDERS],
+ "Results": combined_results,
+ }
+
+
+def print_summary(output: dict) -> None:
+ print("=== External-Type Equivalence Median Summary ===")
+ for result in output["Results"]:
+ allocation = ""
+ if result["AllocationEqual"] is not None:
+ allocation = (
+ f", allocated={result['OrdinaryAllocatedBytesPerOperation']:.2f} B/op"
+ )
+ print(
+ f"{result['DataType']}/{result['Operation']}: "
+ f"ordinary={result['OrdinaryMedian']['AverageNanoseconds']:.1f} ns/op, "
+ f"external={result['ExternalMedian']['AverageNanoseconds']:.1f} ns/op, "
+ f"slowdown={result['SlowdownPercent']:+.2f}%{allocation}"
+ )
+
+
+def main(argv=None) -> int:
+ args = parse_args(argv)
+ lanes = args.lane if args.lane is not None else list(LANES)
+ if len(lanes) != len(set(lanes)):
+ raise ValueError("--lane may specify each lane only once")
+
+ specs = parse_sample_specs(args.sample, lanes)
+ metadata, results = load_samples(specs, lanes)
+ output = merge_results(metadata, results, lanes)
+ output_path = Path(args.output)
+ output_path.parent.mkdir(parents=True, exist_ok=True)
+ with output_path.open("w", encoding="utf-8") as destination:
+ json.dump(output, destination, indent=2)
+ destination.write("\n")
+ print_summary(output)
+ return 0
+
+
+if __name__ == "__main__":
+ try:
+ sys.exit(main())
+ except (OSError, TypeError, ValueError, json.JSONDecodeError) as error:
+ print(f"error: {error}", file=sys.stderr)
+ sys.exit(1)
diff --git a/benchmarks/csharp/run.sh b/benchmarks/csharp/run.sh
index 2f8065d72..4c3f47fc2 100755
--- a/benchmarks/csharp/run.sh
+++ b/benchmarks/csharp/run.sh
@@ -34,6 +34,8 @@ DURATION="3"
WARMUP="1"
OUTPUT_DIR=""
COPY_DOCS=true
+EXTERNAL_EQUIVALENCE=false
+ALLOCATION_ITERATIONS=""
usage() {
cat <<USAGE
@@ -50,6 +52,8 @@ Options:
--warmup <seconds> Warmup duration per benchmark (default: 1)
--output-dir <dir> Base directory for benchmark outputs
--no-copy-docs Skip copying report/plots into docs/benchmarks/csharp
+ --external-equivalence Run ordinary/external Fory equivalence cases
+ --allocation-iterations <n> Measure allocations for each equivalence case
--help Show this help
USAGE
exit 0
@@ -81,6 +85,14 @@ while [[ $# -gt 0 ]]; do
COPY_DOCS=false
shift
;;
+ --external-equivalence)
+ EXTERNAL_EQUIVALENCE=true
+ shift
+ ;;
+ --allocation-iterations)
+ ALLOCATION_ITERATIONS="$2"
+ shift 2
+ ;;
--help|-h)
usage
;;
@@ -91,7 +103,33 @@ while [[ $# -gt 0 ]]; do
esac
done
-if [[ "${FORY_BENCH_SCHEMA_MISMATCH:-0}" == "1" && "$SERIALIZER" != "fory" ]]; then
+if [[ "$EXTERNAL_EQUIVALENCE" == true && -n "$SERIALIZER" ]]; then
+ echo -e "${RED}--external-equivalence does not accept --serializer.${NC}"
+ exit 1
+fi
+
+if [[ "$EXTERNAL_EQUIVALENCE" == false && -n "$ALLOCATION_ITERATIONS" ]]; then
+ echo -e "${RED}--allocation-iterations requires --external-equivalence.${NC}"
+ exit 1
+fi
+
+if [[ "$EXTERNAL_EQUIVALENCE" == true && "${FORY_BENCH_SCHEMA_MISMATCH:-0}" == "1" ]]; then
+ echo -e "${RED}--external-equivalence does not support schema-mismatch mode.${NC}"
+ exit 1
+fi
+
+if [[ "$EXTERNAL_EQUIVALENCE" == true && -n "$DATA" ]]; then
+ case "$DATA" in
+ class-root|struct-root|holder-field|list-field|list-root|map-field|map-root)
+ ;;
+ *)
+ echo -e "${RED}Unknown external-equivalence data lane: $DATA${NC}"
+ exit 1
+ ;;
+ esac
+fi
+
+if [[ "$EXTERNAL_EQUIVALENCE" == false && "${FORY_BENCH_SCHEMA_MISMATCH:-0}" == "1" && "$SERIALIZER" != "fory" ]]; then
echo -e "${RED}FORY_BENCH_SCHEMA_MISMATCH=1 supports only Fory benchmarks; rerun with --serializer fory.${NC}"
exit 1
fi
@@ -104,9 +142,88 @@ else
REPORT_DIR="report"
fi
+echo -e "${GREEN}=== Fory C# Benchmark ===${NC}"
+echo ""
+
+if [[ "$EXTERNAL_EQUIVALENCE" == true ]]; then
+ mkdir -p "$BUILD_DIR"
+ RESULT_JSON="$BUILD_DIR/external_equivalence_results.json"
+ SIDE_DIR="$BUILD_DIR/external_equivalence_sides"
+ mkdir -p "$SIDE_DIR"
+
+ if [[ -n "$DATA" ]]; then
+ EXTERNAL_LANES=("$DATA")
+ else
+ EXTERNAL_LANES=(
+ class-root
+ struct-root
+ holder-field
+ list-field
+ list-root
+ map-field
+ map-root
+ )
+ fi
+
+ echo -e "${YELLOW}[1/4] Restoring dependencies...${NC}"
+ dotnet restore ./Fory.ExternalTypeBenchmark.csproj >/dev/null
+
+ echo -e "${YELLOW}[2/4] Building benchmark once...${NC}"
+ dotnet build -c Release --no-restore ./Fory.ExternalTypeBenchmark.csproj
+
+ echo -e "${YELLOW}[3/4] Running isolated adjacent pairs...${NC}"
+ MERGE_ARGS=(--output "$RESULT_JSON")
+ for LANE in "${EXTERNAL_LANES[@]}"; do
+ MERGE_ARGS+=(--lane "$LANE")
+ WORKER_ARGS=(
+ --data "$LANE"
+ --duration "$DURATION"
+ --warmup "$WARMUP"
+ )
+ if [[ -n "$ALLOCATION_ITERATIONS" ]]; then
+ WORKER_ARGS+=(--allocation-iterations "$ALLOCATION_ITERATIONS")
+ fi
+
+ for SAMPLE_INDEX in 1 2; do
+ if [[ "$SAMPLE_INDEX" == 1 ]]; then
+ PAIR_ORDER=(ordinary external)
+ else
+ PAIR_ORDER=(external ordinary)
+ fi
+
+ SIDE_INPUTS=()
+ for IMPLEMENTATION in "${PAIR_ORDER[@]}"; do
+ SIDE_JSON="$SIDE_DIR/${LANE}-sample-${SAMPLE_INDEX}-${IMPLEMENTATION}.json"
+ SIDE_INPUTS+=("$SIDE_JSON")
+ echo "Running $LANE sample $SAMPLE_INDEX ${PAIR_ORDER[*]}: $IMPLEMENTATION worker..."
+ dotnet run -c Release --no-build \
+ --project ./Fory.ExternalTypeBenchmark.csproj -- \
+ "${WORKER_ARGS[@]}" \
+ --external-implementation "$IMPLEMENTATION" \
+ --output "$SIDE_JSON"
+ done
+
+ MERGE_ARGS+=(
+ --sample
+ "$LANE"
+ "$SAMPLE_INDEX"
+ "${PAIR_ORDER[0]}-${PAIR_ORDER[1]}"
+ "${SIDE_INPUTS[0]}"
+ "${SIDE_INPUTS[1]}"
+ )
+ done
+ done
+
+ echo -e "${YELLOW}[4/4] Validating and merging results...${NC}"
+ python3 external_equivalence_report.py "${MERGE_ARGS[@]}"
+ echo ""
+ echo -e "${GREEN}=== All done! ===${NC}"
+ echo "Results written to: $RESULT_JSON"
+ exit 0
+fi
+
mkdir -p "$BUILD_DIR" "$REPORT_DIR"
RESULT_JSON="$BUILD_DIR/benchmark_results.json"
-
RUN_ARGS=(
--output "$RESULT_JSON"
--duration "$DURATION"
@@ -121,9 +238,6 @@ if [[ -n "$SERIALIZER" ]]; then
RUN_ARGS+=(--serializer "$SERIALIZER")
fi
-echo -e "${GREEN}=== Fory C# Benchmark ===${NC}"
-echo ""
-
echo -e "${YELLOW}[1/3] Restoring dependencies...${NC}"
dotnet restore ./Fory.CSharpBenchmark.csproj >/dev/null
diff --git a/csharp/Fory.sln b/csharp/Fory.sln
index b2f9edf7b..63a848cb3 100644
--- a/csharp/Fory.sln
+++ b/csharp/Fory.sln
@@ -15,6 +15,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Fory.Tests", "tests\Fory.Te
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Fory.XlangPeer", "tests\Fory.XlangPeer\Fory.XlangPeer.csproj", "{8E1D5E47-AF72-46FF-B60F-B1C6210654A4}"
EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Fory.ExternalTypes", "tests\Fory.ExternalTypes\Fory.ExternalTypes.csproj", "{EE9DC5A3-3509-4D84-94F2-7B9FAF718989}"
+EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -40,11 +42,16 @@ Global
{8E1D5E47-AF72-46FF-B60F-B1C6210654A4}.Debug|Any CPU.Build.0 = Debug|Any CPU
{8E1D5E47-AF72-46FF-B60F-B1C6210654A4}.Release|Any CPU.ActiveCfg = Release|Any CPU
{8E1D5E47-AF72-46FF-B60F-B1C6210654A4}.Release|Any CPU.Build.0 = Release|Any CPU
+ {EE9DC5A3-3509-4D84-94F2-7B9FAF718989}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {EE9DC5A3-3509-4D84-94F2-7B9FAF718989}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {EE9DC5A3-3509-4D84-94F2-7B9FAF718989}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {EE9DC5A3-3509-4D84-94F2-7B9FAF718989}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{309709EA-773D-449D-AE12-D1C2B9518793} = {C3FE93C6-2294-475C-88DD-BE1FFFADC4D6}
{4DBAD732-2820-4B15-B655-19384F100997} = {C3FE93C6-2294-475C-88DD-BE1FFFADC4D6}
{65701195-E254-4D93-9CD0-F587FDFCE769} = {02DC4D41-0522-42EA-B643-471F4BB0747E}
{8E1D5E47-AF72-46FF-B60F-B1C6210654A4} = {02DC4D41-0522-42EA-B643-471F4BB0747E}
+ {EE9DC5A3-3509-4D84-94F2-7B9FAF718989} = {02DC4D41-0522-42EA-B643-471F4BB0747E}
EndGlobalSection
EndGlobal
diff --git a/csharp/README.md b/csharp/README.md
index 3b8e0dfc0..a505ea727 100644
--- a/csharp/README.md
+++ b/csharp/README.md
@@ -183,9 +183,32 @@ Parallel.For(0, 128, i =>
});
```
-### 6. Custom Serializers
+### 6. External Types
-Provide custom encoding logic with `Serializer<T>`.
+Generate serializers for mutable third-party classes, structs, and enums with a
+local serializer declaration:
+
+```csharp
+[ForyStruct(Target = typeof(ThirdParty.User))]
+internal abstract class UserSerializer
+{
+ [ForyField(1)]
+ public abstract string Name { get; }
+}
+
+Fory fory = Fory.Builder().Build();
+fory.Register<ThirdParty.User>(300);
+
+byte[] payload = fory.Serialize(user);
+ThirdParty.User decoded = fory.Deserialize<ThirdParty.User>(payload);
+```
+
+The target is the runtime and registration type. See the
+[external-types guide](https://fory.apache.org/docs/guide/csharp/external-types/).
+
+### 7. Manual Serializers
+
+Provide specialized encoding logic with `Serializer<T>`.
```csharp
public sealed class PointSerializer : Serializer<Point>
diff --git a/csharp/src/Fory.Generator/AnalyzerReleases.Unshipped.md b/csharp/src/Fory.Generator/AnalyzerReleases.Unshipped.md
index b7b6eff1f..9f5047f7b 100644
--- a/csharp/src/Fory.Generator/AnalyzerReleases.Unshipped.md
+++ b/csharp/src/Fory.Generator/AnalyzerReleases.Unshipped.md
@@ -9,3 +9,10 @@ FORY004 | Fory | Error | Invalid Fory field id
FORY005 | Fory | Error | Invalid Fory union type
FORY006 | Fory | Error | Invalid Fory union case
FORY007 | Fory | Error | Duplicate Fory union case id
+FORY008 | Fory | Error | Invalid external serializer declaration
+FORY009 | Fory | Error | Invalid external serializer target
+FORY010 | Fory | Error | Duplicate generated serializer target
+FORY011 | Fory | Error | Invalid external serializer member
+FORY012 | Fory | Error | External serializer member type mismatch
+FORY013 | Fory | Error | Unsupported extern alias
+FORY014 | Fory | Error | Enum value is outside the supported range
diff --git a/csharp/src/Fory.Generator/ForyModelGenerator.cs b/csharp/src/Fory.Generator/ForyModelGenerator.cs
index 8c11b12b0..76ad404ec 100644
--- a/csharp/src/Fory.Generator/ForyModelGenerator.cs
+++ b/csharp/src/Fory.Generator/ForyModelGenerator.cs
@@ -19,6 +19,7 @@ using System.Collections.Immutable;
using System.Globalization;
using System.Text;
using Microsoft.CodeAnalysis;
+using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
@@ -89,6 +90,62 @@ public sealed class ForyModelGenerator : IIncrementalGenerator
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true);
+ private static readonly DiagnosticDescriptor InvalidExternalDeclaration = new(
+ id: "FORY008",
+ title: "Invalid external serializer declaration",
+ messageFormat: "Serializer declaration '{0}' is invalid: {1}",
+ category: "Fory",
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true);
+
+ private static readonly DiagnosticDescriptor InvalidExternalTarget = new(
+ id: "FORY009",
+ title: "Invalid external serializer target",
+ messageFormat: "External serializer target '{0}' is invalid: {1}",
+ category: "Fory",
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true);
+
+ private static readonly DiagnosticDescriptor DuplicateGeneratedTarget = new(
+ id: "FORY010",
+ title: "Duplicate generated serializer target",
+ messageFormat: "Runtime target '{0}' has multiple generated serializer declarations",
+ category: "Fory",
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true);
+
+ private static readonly DiagnosticDescriptor InvalidExternalMember = new(
+ id: "FORY011",
+ title: "Invalid external serializer member",
+ messageFormat: "Schema member '{0}' cannot bind target '{1}': {2}",
+ category: "Fory",
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true);
+
+ private static readonly DiagnosticDescriptor ExternalMemberTypeMismatch = new(
+ id: "FORY012",
+ title: "External serializer member type mismatch",
+ messageFormat: "Schema member '{0}' type '{1}' does not match target member type '{2}'",
+ category: "Fory",
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true);
+
+ private static readonly DiagnosticDescriptor UnsupportedExternalAlias = new(
+ id: "FORY013",
+ title: "Unsupported extern alias",
+ messageFormat: "Type '{0}' requires an extern alias that generated code cannot preserve",
+ category: "Fory",
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true);
+
+ private static readonly DiagnosticDescriptor EnumValueOutOfRange = new(
+ id: "FORY014",
+ title: "Enum value is outside the supported range",
+ messageFormat: "Enum member '{0}' has a value outside the supported unsigned 32-bit range",
+ category: "Fory",
+ defaultSeverity: DiagnosticSeverity.Error,
+ isEnabledByDefault: true);
+
public void Initialize(IncrementalGeneratorInitializationContext context)
{
IncrementalValuesProvider<TypeModel?> typeModels = context.SyntaxProvider
@@ -119,7 +176,7 @@ public sealed class ForyModelGenerator : IIncrementalGenerator
return;
}
- Dictionary<string, TypeModel> models = new(StringComparer.Ordinal);
+ Dictionary<string, TypeModel> declarations = new(StringComparer.Ordinal);
foreach (TypeModel? maybeModel in maybeModels)
{
if (maybeModel is null)
@@ -127,9 +184,18 @@ public sealed class ForyModelGenerator : IIncrementalGenerator
continue;
}
- if (!maybeModel.Diagnostics.IsDefaultOrEmpty)
+ if (!declarations.ContainsKey(maybeModel.DeclarationName))
+ {
+ declarations.Add(maybeModel.DeclarationName, maybeModel);
+ }
+ }
+
+ List<TypeModel> validModels = [];
+ foreach (TypeModel model in declarations.Values)
+ {
+ if (!model.Diagnostics.IsDefaultOrEmpty)
{
- foreach (Diagnostic diagnostic in maybeModel.Diagnostics)
+ foreach (Diagnostic diagnostic in model.Diagnostics)
{
context.ReportDiagnostic(diagnostic);
}
@@ -137,7 +203,29 @@ public sealed class ForyModelGenerator : IIncrementalGenerator
continue;
}
- models[maybeModel.TypeName] = maybeModel;
+ validModels.Add(model);
+ }
+
+ Dictionary<string, TypeModel> models = new(StringComparer.Ordinal);
+ foreach (IGrouping<string, TypeModel> targetGroup in validModels.GroupBy(
+ model => model.TargetTypeName,
+ StringComparer.Ordinal))
+ {
+ if (targetGroup.Skip(1).Any())
+ {
+ foreach (TypeModel model in targetGroup)
+ {
+ context.ReportDiagnostic(Diagnostic.Create(
+ DuplicateGeneratedTarget,
+ model.DeclarationLocation,
+ model.TargetTypeName));
+ }
+
+ continue;
+ }
+
+ TypeModel targetModel = targetGroup.First();
+ models.Add(targetModel.TargetTypeName, targetModel);
}
if (models.Count == 0)
@@ -182,17 +270,17 @@ public sealed class ForyModelGenerator : IIncrementalGenerator
if (model.Kind == DeclKind.Enum)
{
sb.AppendLine(
- $" global::Apache.Fory.TypeResolver.RegisterGenerated<{model.TypeName}, global::Apache.Fory.EnumSerializer<{model.TypeName}>>();");
+ $" global::Apache.Fory.TypeResolver.RegisterGenerated<{model.TargetTypeName}, global::Apache.Fory.EnumSerializer<{model.TargetTypeName}>>();");
}
else if (model.Kind == DeclKind.Union)
{
sb.AppendLine(
- $" global::Apache.Fory.TypeResolver.RegisterGenerated<{model.TypeName}, {model.SerializerName}>();");
+ $" global::Apache.Fory.TypeResolver.RegisterGenerated<{model.TargetTypeName}, {model.SerializerName}>();");
}
else
{
sb.AppendLine(
- $" global::Apache.Fory.TypeResolver.RegisterGenerated<{model.TypeName}, {model.SerializerName}>();");
+ $" global::Apache.Fory.TypeResolver.RegisterGeneratedStruct<{model.TargetTypeName}, {model.SerializerName}>({BoolLiteral(model.Evolving)});");
}
}
@@ -205,7 +293,7 @@ public sealed class ForyModelGenerator : IIncrementalGenerator
private static void EmitObjectSerializer(StringBuilder sb, TypeModel model)
{
sb.AppendLine(
- $"file sealed class {model.SerializerName} : global::Apache.Fory.Serializer<{model.TypeName}>");
+ $"file sealed class {model.SerializerName} : global::Apache.Fory.Serializer<{model.TargetTypeName}>");
sb.AppendLine("{");
sb.AppendLine(" private static readonly object __ForyTypeMetaCacheLock = new();");
sb.AppendLine(" private static ulong __ForyTypeMetaResolverVersion;");
@@ -335,7 +423,7 @@ public sealed class ForyModelGenerator : IIncrementalGenerator
sb.AppendLine(" }");
sb.AppendLine();
sb.AppendLine(
- $" global::Apache.Fory.TypeInfo typeInfo = typeResolver.GetTypeInfo<{model.TypeName}>();");
+ $" global::Apache.Fory.TypeInfo typeInfo = typeResolver.GetTypeInfo<{model.TargetTypeName}>();");
sb.AppendLine(
" __ForyNoRefTypeMetaHash = typeInfo.GetTypeMetaHeaderHash(false);");
sb.AppendLine(
@@ -413,11 +501,11 @@ public sealed class ForyModelGenerator : IIncrementalGenerator
sb.AppendLine();
if (model.Kind == DeclKind.Class)
{
- sb.AppendLine($" public override {model.TypeName} DefaultValue => null!;");
+ sb.AppendLine($" public override {model.TargetTypeName} DefaultValue => null!;");
}
else
{
- sb.AppendLine($" public override {model.TypeName} DefaultValue => new {model.TypeName}();");
+ sb.AppendLine($" public override {model.TargetTypeName} DefaultValue => new {model.TargetTypeName}();");
}
sb.AppendLine();
@@ -434,7 +522,7 @@ public sealed class ForyModelGenerator : IIncrementalGenerator
sb.AppendLine(" }");
sb.AppendLine();
sb.AppendLine(
- $" public override void WriteData(global::Apache.Fory.WriteContext context, in {model.TypeName} value, bool hasGenerics)");
+ $" public override void WriteData(global::Apache.Fory.WriteContext context, in {model.TargetTypeName} value, bool hasGenerics)");
sb.AppendLine(" {");
sb.AppendLine(" _ = hasGenerics;");
sb.AppendLine(" if (context.Compatible)");
@@ -478,11 +566,11 @@ public sealed class ForyModelGenerator : IIncrementalGenerator
if (model.Kind == DeclKind.Class)
{
sb.AppendLine(
- $" private {model.TypeName} {methodName}(global::Apache.Fory.ReadContext context, bool publishRef, uint refId)");
+ $" private {model.TargetTypeName} {methodName}(global::Apache.Fory.ReadContext context, bool publishRef, uint refId)");
}
else
{
- sb.AppendLine($" private {model.TypeName} {methodName}(global::Apache.Fory.ReadContext context)");
+ sb.AppendLine($" private {model.TargetTypeName} {methodName}(global::Apache.Fory.ReadContext context)");
}
sb.AppendLine(" {");
@@ -498,7 +586,7 @@ public sealed class ForyModelGenerator : IIncrementalGenerator
sb.AppendLine(" // the storage they own.");
}
- sb.AppendLine($" {model.TypeName} valueNoTypeMeta = new {model.TypeName}();");
+ sb.AppendLine($" {model.TargetTypeName} valueNoTypeMeta = new {model.TargetTypeName}();");
EmitRefPublication(sb, model, "valueNoTypeMeta", 2);
foreach (MemberModel member in model.SortedMembers)
@@ -527,7 +615,7 @@ public sealed class ForyModelGenerator : IIncrementalGenerator
string accessibility)
{
sb.AppendLine(" [global::System.Runtime.CompilerServices.MethodImpl(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]");
- sb.AppendLine($" {accessibility} override {model.TypeName} {methodName}(global::Apache.Fory.ReadContext context)");
+ sb.AppendLine($" {accessibility} override {model.TargetTypeName} {methodName}(global::Apache.Fory.ReadContext context)");
sb.AppendLine(" {");
if (model.Kind == DeclKind.Class)
{
@@ -539,13 +627,13 @@ public sealed class ForyModelGenerator : IIncrementalGenerator
sb.AppendLine(" }");
sb.AppendLine();
sb.AppendLine(
- $" private {model.TypeName} ReadReservedRefData(global::Apache.Fory.ReadContext context, uint refId)");
+ $" private {model.TargetTypeName} ReadReservedRefData(global::Apache.Fory.ReadContext context, uint refId)");
sb.AppendLine(" {");
sb.AppendLine($" return {methodName}Core(context, publishRef: true, refId);");
sb.AppendLine(" }");
sb.AppendLine();
sb.AppendLine(
- $" public override {model.TypeName} Read(global::Apache.Fory.ReadContext context, global::Apache.Fory.RefMode refMode, bool readTypeInfo)");
+ $" public override {model.TargetTypeName} Read(global::Apache.Fory.ReadContext context, global::Apache.Fory.RefMode refMode, bool readTypeInfo)");
sb.AppendLine(" {");
sb.AppendLine(" if (refMode != global::Apache.Fory.RefMode.None)");
sb.AppendLine(" {");
@@ -557,7 +645,7 @@ public sealed class ForyModelGenerator : IIncrementalGenerator
sb.AppendLine(" case global::Apache.Fory.RefFlag.Ref:");
sb.AppendLine(" {");
sb.AppendLine(" uint refId = context.RefReader.ReadRefId(context.Reader);");
- sb.AppendLine($" return context.RefReader.GetRef<{model.TypeName}>(refId);");
+ sb.AppendLine($" return context.RefReader.GetRef<{model.TargetTypeName}>(refId);");
sb.AppendLine(" }");
sb.AppendLine(" case global::Apache.Fory.RefFlag.RefValue:");
sb.AppendLine(" {");
@@ -585,14 +673,14 @@ public sealed class ForyModelGenerator : IIncrementalGenerator
sb.AppendLine(" }");
sb.AppendLine();
sb.AppendLine(
- $" private {model.TypeName} {methodName}Core(global::Apache.Fory.ReadContext context, bool publishRef, uint refId)");
+ $" private {model.TargetTypeName} {methodName}Core(global::Apache.Fory.ReadContext context, bool publishRef, uint refId)");
sb.AppendLine(" {");
}
sb.AppendLine(" if (context.Compatible)");
sb.AppendLine(" {");
sb.AppendLine(
- $" global::Apache.Fory.TypeMeta? maybeTypeMeta = context.GetTypeMeta<{model.TypeName}>();");
+ $" global::Apache.Fory.TypeMeta? maybeTypeMeta = context.GetTypeMeta<{model.TargetTypeName}>();");
sb.AppendLine(" if (maybeTypeMeta is null)");
sb.AppendLine(" {");
if (model.Kind == DeclKind.Class)
@@ -619,7 +707,7 @@ public sealed class ForyModelGenerator : IIncrementalGenerator
sb.AppendLine(" // the storage they own.");
}
- sb.AppendLine($" {model.TypeName} value = new {model.TypeName}();");
+ sb.AppendLine($" {model.TargetTypeName} value = new {model.TargetTypeName}();");
EmitRefPublication(sb, model, "value", 3);
sb.AppendLine(" bool __ForyExactTypeMeta = __ForyMatchesCachedTypeMeta(typeMeta, context.TrackRef, context.TypeResolver);");
@@ -738,7 +826,7 @@ public sealed class ForyModelGenerator : IIncrementalGenerator
sb.AppendLine(" // the storage they own.");
}
- sb.AppendLine($" {model.TypeName} valueSchema = new {model.TypeName}();");
+ sb.AppendLine($" {model.TargetTypeName} valueSchema = new {model.TargetTypeName}();");
EmitRefPublication(sb, model, "valueSchema", 2);
foreach (MemberModel member in model.SortedMembers)
@@ -772,9 +860,9 @@ public sealed class ForyModelGenerator : IIncrementalGenerator
private static void EmitUnionSerializer(StringBuilder sb, TypeModel model)
{
sb.AppendLine(
- $"file sealed class {model.SerializerName} : global::Apache.Fory.Serializer<{model.TypeName}>");
+ $"file sealed class {model.SerializerName} : global::Apache.Fory.Serializer<{model.TargetTypeName}>");
sb.AppendLine("{");
- sb.AppendLine($" public override {model.TypeName} DefaultValue => null!;");
+ sb.AppendLine($" public override {model.TargetTypeName} DefaultValue => null!;");
sb.AppendLine();
sb.AppendLine(" private static global::Apache.Fory.RefMode __ForyRefMode(bool nullable, bool trackRef)");
sb.AppendLine(" {");
@@ -795,7 +883,7 @@ public sealed class ForyModelGenerator : IIncrementalGenerator
}
sb.AppendLine(
- $" public override void WriteData(global::Apache.Fory.WriteContext context, in {model.TypeName} value, bool hasGenerics)");
+ $" public override void WriteData(global::Apache.Fory.WriteContext context, in {model.TargetTypeName} value, bool hasGenerics)");
sb.AppendLine(" {");
sb.AppendLine(" _ = hasGenerics;");
sb.AppendLine(" if (value is null)");
@@ -836,7 +924,7 @@ public sealed class ForyModelGenerator : IIncrementalGenerator
sb.AppendLine(" }");
sb.AppendLine(" }");
sb.AppendLine();
- sb.AppendLine($" public override {model.TypeName} ReadData(global::Apache.Fory.ReadContext context)");
+ sb.AppendLine($" public override {model.TargetTypeName} ReadData(global::Apache.Fory.ReadContext context)");
sb.AppendLine(" {");
sb.AppendLine(" uint rawCaseId = context.Reader.ReadVarUInt32();");
sb.AppendLine(" if (rawCaseId > int.MaxValue)");
@@ -854,7 +942,7 @@ public sealed class ForyModelGenerator : IIncrementalGenerator
sb.AppendLine($" case {caseId}:");
sb.AppendLine(" {");
EmitReadUnionCasePayload(sb, unionCase, valueVar, 4);
- sb.AppendLine($" {model.TypeName} __foryUnion = new {unionCase.TypeName}({valueVar});");
+ sb.AppendLine($" {model.TargetTypeName} __foryUnion = new {unionCase.TypeName}({valueVar});");
sb.AppendLine(" return __foryUnion;");
sb.AppendLine(" }");
}
@@ -867,7 +955,7 @@ public sealed class ForyModelGenerator : IIncrementalGenerator
}
else
{
- sb.AppendLine($" {model.TypeName} __foryUnion = new {unknownCase.TypeName}(global::Apache.Fory.UnknownCaseSerializer.ReadPayload(context, caseId));");
+ sb.AppendLine($" {model.TargetTypeName} __foryUnion = new {unknownCase.TypeName}(global::Apache.Fory.UnknownCaseSerializer.ReadPayload(context, caseId));");
sb.AppendLine(" return __foryUnion;");
}
@@ -1955,7 +2043,6 @@ public sealed class ForyModelGenerator : IIncrementalGenerator
member.Name,
member.FieldIdentifier,
member.OriginalIndex,
- member.DeclKind,
member.IsNullableValueType && member.TypeName.EndsWith("?", StringComparison.Ordinal)
? member.TypeName.Substring(0, member.TypeName.Length - 1)
: StripNullableForTypeOf(member.TypeName),
@@ -2112,7 +2199,7 @@ public sealed class ForyModelGenerator : IIncrementalGenerator
private static void EmitWriteMember(StringBuilder sb, MemberModel member, bool compatibleMode)
{
string refModeExpr = BuildWriteRefModeExpression(member);
- string memberAccess = $"value.{member.Name}";
+ string memberAccess = $"value.{EscapeIdentifier(member.Name)}";
string hasGenerics = member.IsCollection ? "true" : "false";
string writeTypeInfo = compatibleMode
? BuildFieldTypeInfoLiteral(member)
@@ -2231,7 +2318,7 @@ public sealed class ForyModelGenerator : IIncrementalGenerator
bool allowDirectRead)
{
string indent = new(' ', indentLevel * 2);
- string assignmentTarget = $"{valueVar}.{member.Name}";
+ string assignmentTarget = $"{valueVar}.{EscapeIdentifier(member.Name)}";
string typeOfTypeName = StripNullableForTypeOf(member.TypeName);
switch (member.DynamicAnyKind)
{
@@ -2833,77 +2920,248 @@ public sealed class ForyModelGenerator : IIncrementalGenerator
private static TypeModel? BuildTypeModel(GeneratorSyntaxContext context, CancellationToken cancellationToken)
{
- _ = cancellationToken;
if (context.SemanticModel.GetDeclaredSymbol(context.Node, cancellationToken) is not INamedTypeSymbol typeSymbol)
{
return null;
}
- ForyAttributeKind attributeKind = GetForyAttributeKind(typeSymbol);
- if (attributeKind == ForyAttributeKind.None)
+ AttributeData? attribute = GetForyAttribute(
+ typeSymbol,
+ out ForyAttributeKind attributeKind,
+ out bool hasConflictingAttributes);
+ if (attribute is null)
{
return null;
}
- string typeName = typeSymbol.ToDisplayString(FullNameFormat);
- if (typeSymbol.TypeParameters.Length > 0)
+ string declarationName = typeSymbol.ToDisplayString(FullNameFormat);
+ string serializerName = "__ForySerializer_" + Sanitize(
+ typeSymbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat));
+ Location? declarationLocation = typeSymbol.Locations.FirstOrDefault(location => location.IsInSource);
+ bool evolving = GetEvolving(attribute);
+ if (hasConflictingAttributes)
+ {
+ return new TypeModel(
+ declarationName,
+ declarationName,
+ serializerName,
+ DeclKind.Unknown,
+ evolving,
+ declarationLocation,
+ ImmutableArray<MemberModel>.Empty,
+ ImmutableArray<MemberModel>.Empty,
+ ImmutableArray.Create(Diagnostic.Create(
+ InvalidExternalDeclaration,
+ declarationLocation,
+ declarationName,
+ "exactly one of ForyStruct, ForyEnum, or ForyUnion is allowed")));
+ }
+
+ Location? targetLocation = GetNamedArgumentLocation(attribute, "Target", cancellationToken) ??
+ declarationLocation;
+ ITypeSymbol? target = null;
+ bool invalidTargetValue = false;
+ foreach (KeyValuePair<string, TypedConstant> namedArgument in attribute.NamedArguments)
+ {
+ if (!string.Equals(namedArgument.Key, "Target", StringComparison.Ordinal))
+ {
+ continue;
+ }
+
+ if (namedArgument.Value.Value is ITypeSymbol targetSymbol)
+ {
+ target = targetSymbol;
+ }
+ else if (!namedArgument.Value.IsNull)
+ {
+ invalidTargetValue = true;
+ }
+
+ break;
+ }
+
+ if (invalidTargetValue)
+ {
+ return new TypeModel(
+ declarationName,
+ declarationName,
+ serializerName,
+ DeclKind.Unknown,
+ evolving,
+ declarationLocation,
+ ImmutableArray<MemberModel>.Empty,
+ ImmutableArray<MemberModel>.Empty,
+ ImmutableArray.Create(Diagnostic.Create(
+ InvalidExternalTarget,
+ targetLocation,
+ "<unknown>",
+ "Target must name one closed CLR type")));
+ }
+
+ if (target is null)
+ {
+ if (attributeKind == ForyAttributeKind.Struct &&
+ typeSymbol.TypeKind == TypeKind.Class &&
+ typeSymbol.IsAbstract)
+ {
+ return new TypeModel(
+ declarationName,
+ declarationName,
+ serializerName,
+ DeclKind.Unknown,
+ evolving,
+ declarationLocation,
+ ImmutableArray<MemberModel>.Empty,
+ ImmutableArray<MemberModel>.Empty,
+ ImmutableArray.Create(Diagnostic.Create(
+ InvalidExternalTarget,
+ targetLocation,
+ "<null>",
+ "an abstract serializer declaration requires a non-null Target")));
+ }
+
+ return BuildOrdinaryTypeModel(
+ context.SemanticModel.Compilation,
+ typeSymbol,
+ attributeKind,
+ declarationName,
+ serializerName,
+ evolving,
+ declarationLocation);
+ }
+
+ return attributeKind switch
+ {
+ ForyAttributeKind.Struct => BuildExternalStructModel(
+ context.SemanticModel.Compilation,
+ typeSymbol,
+ target,
+ declarationName,
+ serializerName,
+ evolving,
+ declarationLocation,
+ targetLocation),
+ ForyAttributeKind.Enum => BuildExternalEnumModel(
+ context.SemanticModel.Compilation,
+ typeSymbol,
+ target,
+ declarationName,
+ serializerName,
+ declarationLocation,
+ targetLocation),
+ _ => new TypeModel(
+ declarationName,
+ declarationName,
+ serializerName,
+ DeclKind.Unknown,
+ evolving,
+ declarationLocation,
+ ImmutableArray<MemberModel>.Empty,
+ ImmutableArray<MemberModel>.Empty,
+ ImmutableArray.Create(Diagnostic.Create(
+ InvalidExternalDeclaration,
+ declarationLocation,
+ declarationName,
+ "Target is supported only by ForyStruct and ForyEnum"))),
+ };
+ }
+
+ private static TypeModel BuildOrdinaryTypeModel(
+ Compilation compilation,
+ INamedTypeSymbol typeSymbol,
+ ForyAttributeKind attributeKind,
+ string declarationName,
+ string serializerName,
+ bool evolving,
+ Location? declarationLocation)
+ {
+ if (HasGenericContext(typeSymbol))
{
return new TypeModel(
- typeName,
- string.Empty,
+ declarationName,
+ declarationName,
+ serializerName,
DeclKind.Unknown,
+ evolving,
+ declarationLocation,
ImmutableArray<MemberModel>.Empty,
ImmutableArray<MemberModel>.Empty,
ImmutableArray.Create(Diagnostic.Create(
GenericTypeNotSupported,
- typeSymbol.Locations.FirstOrDefault(),
- typeName)));
+ declarationLocation,
+ declarationName)));
}
- string serializerName = "__ForySerializer_" + Sanitize(typeSymbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat));
if (attributeKind == ForyAttributeKind.Enum)
{
if (typeSymbol.TypeKind != TypeKind.Enum)
{
- return null;
+ return new TypeModel(
+ declarationName,
+ declarationName,
+ serializerName,
+ DeclKind.Unknown,
+ evolving,
+ declarationLocation,
+ ImmutableArray<MemberModel>.Empty,
+ ImmutableArray<MemberModel>.Empty,
+ ImmutableArray.Create(Diagnostic.Create(
+ InvalidExternalDeclaration,
+ declarationLocation,
+ declarationName,
+ "ForyEnum without Target is valid only on an enum")));
}
+ List<Diagnostic> enumDiagnostics = [];
+ ValidateEnumValues(typeSymbol, declarationLocation, enumDiagnostics);
return new TypeModel(
- typeName,
+ declarationName,
+ declarationName,
serializerName,
DeclKind.Enum,
+ evolving,
+ declarationLocation,
ImmutableArray<MemberModel>.Empty,
ImmutableArray<MemberModel>.Empty,
- ImmutableArray<Diagnostic>.Empty);
+ enumDiagnostics.ToImmutableArray());
}
if (attributeKind == ForyAttributeKind.Union)
{
if (typeSymbol.TypeKind != TypeKind.Class)
- {
- return null;
- }
-
- List<Diagnostic> unionDiagnostics = [];
- ImmutableArray<UnionCaseModel> unionCases = BuildUnionCases(typeSymbol, unionDiagnostics);
- if (unionCases.IsEmpty)
{
return new TypeModel(
- typeName,
+ declarationName,
+ declarationName,
serializerName,
- DeclKind.Union,
+ DeclKind.Unknown,
+ evolving,
+ declarationLocation,
ImmutableArray<MemberModel>.Empty,
ImmutableArray<MemberModel>.Empty,
ImmutableArray.Create(Diagnostic.Create(
InvalidUnionType,
- typeSymbol.Locations.FirstOrDefault(),
- typeName)));
+ declarationLocation,
+ declarationName)));
+ }
+
+ List<Diagnostic> unionDiagnostics = [];
+ ImmutableArray<UnionCaseModel> unionCases = BuildUnionCases(typeSymbol, unionDiagnostics);
+ if (unionCases.IsEmpty)
+ {
+ unionDiagnostics.Add(Diagnostic.Create(
+ InvalidUnionType,
+ declarationLocation,
+ declarationName));
}
return new TypeModel(
- typeName,
+ declarationName,
+ declarationName,
serializerName,
DeclKind.Union,
+ evolving,
+ declarationLocation,
ImmutableArray<MemberModel>.Empty,
ImmutableArray<MemberModel>.Empty,
unionDiagnostics.ToImmutableArray(),
@@ -2916,24 +3174,39 @@ public sealed class ForyModelGenerator : IIncrementalGenerator
TypeKind.Class => DeclKind.Class,
_ => DeclKind.Unknown,
};
-
if (kind == DeclKind.Unknown)
{
- return null;
+ return new TypeModel(
+ declarationName,
+ declarationName,
+ serializerName,
+ kind,
+ evolving,
+ declarationLocation,
+ ImmutableArray<MemberModel>.Empty,
+ ImmutableArray<MemberModel>.Empty,
+ ImmutableArray.Create(Diagnostic.Create(
+ InvalidExternalDeclaration,
+ declarationLocation,
+ declarationName,
+ "ForyStruct without Target is valid only on a class or struct")));
}
- if (kind == DeclKind.Class && !HasAccessibleParameterlessCtor(typeSymbol))
+ if (kind == DeclKind.Class && !HasAccessibleParameterlessCtor(typeSymbol, compilation))
{
return new TypeModel(
- typeName,
+ declarationName,
+ declarationName,
serializerName,
kind,
+ evolving,
+ declarationLocation,
ImmutableArray<MemberModel>.Empty,
ImmutableArray<MemberModel>.Empty,
ImmutableArray.Create(Diagnostic.Create(
MissingCtor,
- typeSymbol.Locations.FirstOrDefault(),
- typeName)));
+ declarationLocation,
+ declarationName)));
}
List<Diagnostic> diagnostics = [];
@@ -2952,7 +3225,7 @@ public sealed class ForyModelGenerator : IIncrementalGenerator
continue;
}
- MemberModel? parsedField = BuildMemberModel(field.Name, field.Type, field, MemberDeclKind.Field, diagnostics);
+ MemberModel? parsedField = BuildMemberModel(field.Name, field.Type, field, diagnostics);
if (parsedField is not null)
{
members.Add(parsedField);
@@ -2983,7 +3256,6 @@ public sealed class ForyModelGenerator : IIncrementalGenerator
property.Name,
property.Type,
property,
- MemberDeclKind.Property,
diagnostics);
if (parsedProperty is not null)
{
@@ -2997,125 +3269,1010 @@ public sealed class ForyModelGenerator : IIncrementalGenerator
.ToImmutableArray();
ImmutableArray<MemberModel> sorted = SortMembers(ordered);
- return new TypeModel(typeName, serializerName, kind, ordered, sorted, diagnostics.ToImmutableArray());
- }
-
- private static ImmutableArray<UnionCaseModel> BuildUnionCases(
- INamedTypeSymbol unionType,
- List<Diagnostic> diagnostics)
+ return new TypeModel(
+ declarationName,
+ declarationName,
+ serializerName,
+ kind,
+ evolving,
+ declarationLocation,
+ ordered,
+ sorted,
+ diagnostics.ToImmutableArray());
+ }
+
+ private static TypeModel BuildExternalStructModel(
+ Compilation compilation,
+ INamedTypeSymbol declaration,
+ ITypeSymbol targetSymbol,
+ string declarationName,
+ string serializerName,
+ bool evolving,
+ Location? declarationLocation,
+ Location? targetLocation)
{
- List<UnionCaseModel> cases = [];
- HashSet<int> caseIds = [];
- foreach (INamedTypeSymbol caseType in unionType.GetTypeMembers())
+ List<Diagnostic> diagnostics = [];
+ bool validDeclaration = ValidateExternalStructDeclaration(
+ declaration,
+ declarationName,
+ declarationLocation,
+ diagnostics);
+ bool validTarget = ValidateExternalStructTarget(
+ compilation,
+ declaration,
+ targetSymbol,
+ targetLocation,
+ diagnostics,
+ out INamedTypeSymbol? target,
+ out DeclKind targetKind);
+ string targetTypeName = targetSymbol.ToDisplayString(FullNameFormat);
+ List<MemberModel> members = [];
+ if (validDeclaration && validTarget)
{
- bool isUnknown = HasForyUnknownCase(caseType);
- if (!TryGetForyCase(caseType, diagnostics, out int caseId, out SchemaTypeModel? schemaType))
+ foreach (IPropertySymbol schemaProperty in declaration.GetMembers().OfType<IPropertySymbol>())
{
- if (isUnknown)
+ if (schemaProperty.IsImplicitlyDeclared)
{
- string unknownCaseTypeName = caseType.ToDisplayString(FullNameFormat);
- if (!SymbolEqualityComparer.Default.Equals(caseType.BaseType, unionType))
- {
- diagnostics.Add(Diagnostic.Create(
- InvalidUnionCase,
- caseType.Locations.FirstOrDefault(),
- unknownCaseTypeName,
- "unknown case type must directly derive from the annotated union root"));
- continue;
- }
-
- if (!string.Equals(caseType.Name, "Unknown", StringComparison.Ordinal) ||
- !HasUnknownCaseValueProperty(caseType))
- {
- diagnostics.Add(Diagnostic.Create(
- InvalidUnionCase,
- caseType.Locations.FirstOrDefault(),
- unknownCaseTypeName,
- "unknown case must be named Unknown and expose Value:UnknownCase"));
- continue;
- }
+ continue;
+ }
- cases.Add(new UnionCaseModel(null, unknownCaseTypeName, isUnknown: true, valueMember: null));
+ if (!TryBindExternalMember(
+ compilation,
+ target!,
+ schemaProperty,
+ targetTypeName,
+ diagnostics))
+ {
+ continue;
}
- continue;
+ int diagnosticCount = diagnostics.Count;
+ MemberModel? member = BuildMemberModel(
+ schemaProperty.Name,
+ schemaProperty.Type,
+ schemaProperty,
+ diagnostics);
+ if (member is not null)
+ {
+ members.Add(member);
+ }
+ else if (diagnostics.Count == diagnosticCount)
+ {
+ diagnostics.Add(Diagnostic.Create(
+ InvalidExternalMember,
+ schemaProperty.Locations.FirstOrDefault(location => location.IsInSource),
+ schemaProperty.Name,
+ targetTypeName,
+ "the schema property type or descriptor is not supported"));
+ }
}
+ }
- if (isUnknown)
- {
- diagnostics.Add(Diagnostic.Create(
- InvalidUnionCase,
- caseType.Locations.FirstOrDefault(),
- caseType.ToDisplayString(FullNameFormat),
- "unknown case must use [ForyUnknownCase] without [ForyCase]"));
- continue;
- }
+ ImmutableArray<MemberModel> ordered = members
+ .OrderBy(member => member.OriginalIndex)
+ .ToImmutableArray();
+ return new TypeModel(
+ declarationName,
+ targetTypeName,
+ serializerName,
+ targetKind,
+ evolving,
+ declarationLocation,
+ ordered,
+ SortMembers(ordered),
+ diagnostics.ToImmutableArray());
+ }
+
+ private static TypeModel BuildExternalEnumModel(
+ Compilation compilation,
+ INamedTypeSymbol declaration,
+ ITypeSymbol targetSymbol,
+ string declarationName,
+ string serializerName,
+ Location? declarationLocation,
+ Location? targetLocation)
+ {
+ List<Diagnostic> diagnostics = [];
+ ValidateExternalEnumDeclaration(
+ declaration,
+ declarationName,
+ declarationLocation,
+ diagnostics);
+ INamedTypeSymbol? target = ValidateExternalEnumTarget(
+ compilation,
+ declaration,
+ targetSymbol,
+ targetLocation,
+ diagnostics);
+ if (target is not null)
+ {
+ ValidateEnumValues(target, targetLocation, diagnostics);
+ }
+
+ return new TypeModel(
+ declarationName,
+ targetSymbol.ToDisplayString(FullNameFormat),
+ serializerName,
+ DeclKind.Enum,
+ true,
+ declarationLocation,
+ ImmutableArray<MemberModel>.Empty,
+ ImmutableArray<MemberModel>.Empty,
+ diagnostics.ToImmutableArray());
+ }
- if (!caseIds.Add(caseId))
- {
- diagnostics.Add(Diagnostic.Create(
- DuplicateUnionCaseId,
- caseType.Locations.FirstOrDefault(),
- caseId,
- unionType.ToDisplayString(FullNameFormat)));
- continue;
- }
+ private static bool ValidateExternalStructDeclaration(
+ INamedTypeSymbol declaration,
+ string declarationName,
+ Location? declarationLocation,
+ List<Diagnostic> diagnostics)
+ {
+ int initialDiagnosticCount = diagnostics.Count;
+ if (declaration.TypeKind != TypeKind.Class ||
+ !declaration.IsAbstract ||
+ declaration.IsStatic ||
+ declaration.IsRecord)
+ {
+ diagnostics.Add(Diagnostic.Create(
+ InvalidExternalDeclaration,
+ declarationLocation,
+ declarationName,
+ "ForyStruct with Target requires a non-record abstract class"));
+ }
- if (!SymbolEqualityComparer.Default.Equals(caseType.BaseType, unionType))
- {
- diagnostics.Add(Diagnostic.Create(
- InvalidUnionCase,
- caseType.Locations.FirstOrDefault(),
- caseType.ToDisplayString(FullNameFormat),
- "case type must directly derive from the annotated union root"));
- continue;
- }
+ if (HasGenericContext(declaration))
+ {
+ diagnostics.Add(Diagnostic.Create(
+ GenericTypeNotSupported,
+ declarationLocation,
+ declarationName));
+ }
- string caseTypeName = caseType.ToDisplayString(FullNameFormat);
- IPropertySymbol? valueProperty = FindProperty(caseType, "Value");
- if (valueProperty is null)
+ if (declaration.BaseType?.SpecialType != SpecialType.System_Object)
+ {
+ diagnostics.Add(Diagnostic.Create(
+ InvalidExternalDeclaration,
+ declarationLocation,
+ declarationName,
+ "the declaration cannot have a base class other than object"));
+ }
+
+ foreach (ISymbol member in declaration.GetMembers())
+ {
+ if (member.IsImplicitlyDeclared ||
+ member is IMethodSymbol { AssociatedSymbol: not null })
{
- diagnostics.Add(Diagnostic.Create(
- InvalidUnionCase,
- caseType.Locations.FirstOrDefault(),
- caseTypeName,
- "known cases must expose a Value property"));
continue;
}
- MemberModel? valueMember = BuildMemberModel(
- valueProperty.Name,
- valueProperty.Type,
- valueProperty,
- MemberDeclKind.Property,
- diagnostics,
- schemaType,
- parseFieldAttribute: false);
- if (valueMember is null)
+ if (member is IPropertySymbol property &&
+ property.IsAbstract &&
+ !property.IsStatic &&
+ !property.IsIndexer &&
+ property.GetMethod is { IsAbstract: true } &&
+ property.SetMethod is null)
{
- diagnostics.Add(Diagnostic.Create(
- InvalidUnionCase,
- valueProperty.Locations.FirstOrDefault(),
- caseTypeName,
- "case Value type is not supported"));
continue;
}
- cases.Add(new UnionCaseModel(caseId, caseTypeName, isUnknown: false, valueMember));
+ diagnostics.Add(Diagnostic.Create(
+ InvalidExternalDeclaration,
+ member.Locations.FirstOrDefault(location => location.IsInSource) ?? declarationLocation,
+ declarationName,
+ $"member '{member.Name}' must be an abstract instance get-only schema property"));
}
- if (cases.Count(c => c.IsUnknown) > 1)
+ return diagnostics.Count == initialDiagnosticCount;
+ }
+
+ private static bool ValidateExternalEnumDeclaration(
+ INamedTypeSymbol declaration,
+ string declarationName,
+ Location? declarationLocation,
+ List<Diagnostic> diagnostics)
+ {
+ int initialDiagnosticCount = diagnostics.Count;
+ if (declaration.TypeKind != TypeKind.Class || !declaration.IsStatic)
{
diagnostics.Add(Diagnostic.Create(
- InvalidUnionCase,
- unionType.Locations.FirstOrDefault(),
- unionType.ToDisplayString(FullNameFormat),
- "union must declare exactly one [ForyUnknownCase] Unknown"));
+ InvalidExternalDeclaration,
+ declarationLocation,
+ declarationName,
+ "ForyEnum with Target requires an empty static class"));
}
- else if (!cases.Any(c => c.IsUnknown))
+
+ if (HasGenericContext(declaration))
{
diagnostics.Add(Diagnostic.Create(
- InvalidUnionCase,
+ GenericTypeNotSupported,
+ declarationLocation,
+ declarationName));
+ }
+
+ foreach (ISymbol member in declaration.GetMembers())
+ {
+ if (member.IsImplicitlyDeclared ||
+ member is IMethodSymbol { AssociatedSymbol: not null })
+ {
+ continue;
+ }
+
+ diagnostics.Add(Diagnostic.Create(
+ InvalidExternalDeclaration,
+ member.Locations.FirstOrDefault(location => location.IsInSource) ?? declarationLocation,
+ declarationName,
+ $"external enum declarations must be empty; found member '{member.Name}'"));
+ }
+
+ return diagnostics.Count == initialDiagnosticCount;
+ }
+
+ private static bool ValidateExternalStructTarget(
+ Compilation compilation,
+ INamedTypeSymbol declaration,
+ ITypeSymbol targetSymbol,
+ Location? targetLocation,
+ List<Diagnostic> diagnostics,
+ out INamedTypeSymbol? target,
+ out DeclKind targetKind)
+ {
+ int initialDiagnosticCount = diagnostics.Count;
+ target = targetSymbol as INamedTypeSymbol;
+ targetKind = DeclKind.Unknown;
+ string targetName = targetSymbol.ToDisplayString(FullNameFormat);
+ if (target is null || target.TypeKind == TypeKind.Error)
+ {
+ diagnostics.Add(Diagnostic.Create(
+ InvalidExternalTarget,
+ targetLocation,
+ targetName,
+ "Target must resolve to one closed class or struct"));
+ return false;
+ }
+
+ if (SymbolEqualityComparer.Default.Equals(declaration, target))
+ {
+ diagnostics.Add(Diagnostic.Create(
+ InvalidExternalTarget,
+ targetLocation,
+ targetName,
+ "the serializer declaration cannot target itself"));
+ }
+
+ if (ContainsOpenType(target))
+ {
+ diagnostics.Add(Diagnostic.Create(
+ InvalidExternalTarget,
+ targetLocation,
+ targetName,
+ "open generic targets are not supported"));
+ }
+
+ targetKind = target.TypeKind switch
+ {
+ TypeKind.Class => DeclKind.Class,
+ TypeKind.Struct => DeclKind.Struct,
+ _ => DeclKind.Unknown,
+ };
+ TypeClassification classification = ClassifyType(target);
+ if (targetKind == DeclKind.Unknown ||
+ target.IsStatic ||
+ target.IsAbstract ||
+ target.IsRefLikeType ||
+ target.IsReadOnly ||
+ classification.IsBuiltIn ||
+ classification.IsCollection ||
+ classification.IsMap ||
+ IsRuntimeOwnedTarget(target) ||
+ IsUnionType(target))
+ {
+ diagnostics.Add(Diagnostic.Create(
+ InvalidExternalTarget,
+ targetLocation,
+ targetName,
+ "Target must be a mutable concrete user class or struct"));
+ }
+
+ if (GetForyAttributeKind(target) == ForyAttributeKind.Struct)
+ {
+ diagnostics.Add(Diagnostic.Create(
+ InvalidExternalTarget,
+ targetLocation,
+ targetName,
+ "the target already owns a direct ForyStruct serializer"));
+ }
+
+ if (!compilation.IsSymbolAccessibleWithin(target, compilation.Assembly))
+ {
+ diagnostics.Add(Diagnostic.Create(
+ InvalidExternalTarget,
+ targetLocation,
+ targetName,
+ "the target is not accessible from generated code"));
+ }
+
+ if (RequiresExternAlias(target, compilation))
+ {
+ diagnostics.Add(Diagnostic.Create(
+ UnsupportedExternalAlias,
+ targetLocation,
+ targetName));
+ }
+
+ IMethodSymbol? constructor = FindAccessibleParameterlessCtor(target, compilation);
+ if (targetKind == DeclKind.Class && constructor is null)
+ {
+ diagnostics.Add(Diagnostic.Create(
+ MissingCtor,
+ targetLocation,
+ targetName));
+ }
+
+ if (HasRequiredMembers(target) && (constructor is null || !SetsRequiredMembers(constructor)))
+ {
+ diagnostics.Add(Diagnostic.Create(
+ InvalidExternalTarget,
+ targetLocation,
+ targetName,
+ "new Target() is illegal because required members are not satisfied by its parameterless constructor"));
+ }
+
+ return diagnostics.Count == initialDiagnosticCount;
+ }
+
+ private static INamedTypeSymbol? ValidateExternalEnumTarget(
+ Compilation compilation,
+ INamedTypeSymbol declaration,
+ ITypeSymbol targetSymbol,
+ Location? targetLocation,
+ List<Diagnostic> diagnostics)
+ {
+ string targetName = targetSymbol.ToDisplayString(FullNameFormat);
+ if (targetSymbol is not INamedTypeSymbol target ||
+ target.TypeKind == TypeKind.Error ||
+ target.TypeKind != TypeKind.Enum)
+ {
+ diagnostics.Add(Diagnostic.Create(
+ InvalidExternalTarget,
+ targetLocation,
+ targetName,
+ "ForyEnum Target must resolve to one closed enum"));
+ return null;
+ }
+
+ if (SymbolEqualityComparer.Default.Equals(declaration, target))
+ {
+ diagnostics.Add(Diagnostic.Create(
+ InvalidExternalTarget,
+ targetLocation,
+ targetName,
+ "the serializer declaration cannot target itself"));
+ }
+
+ if (ContainsOpenType(target))
+ {
+ diagnostics.Add(Diagnostic.Create(
+ InvalidExternalTarget,
+ targetLocation,
+ targetName,
+ "open generic targets are not supported"));
+ }
+
+ if (GetForyAttributeKind(target) == ForyAttributeKind.Enum)
+ {
+ diagnostics.Add(Diagnostic.Create(
+ InvalidExternalTarget,
+ targetLocation,
+ targetName,
+ "the target already owns a direct ForyEnum serializer"));
+ }
+
+ if (!compilation.IsSymbolAccessibleWithin(target, compilation.Assembly))
+ {
+ diagnostics.Add(Diagnostic.Create(
+ InvalidExternalTarget,
+ targetLocation,
+ targetName,
+ "the target is not accessible from generated code"));
+ }
+
+ if (RequiresExternAlias(target, compilation))
+ {
+ diagnostics.Add(Diagnostic.Create(
+ UnsupportedExternalAlias,
+ targetLocation,
+ targetName));
+ }
+
+ return target;
+ }
+
+ private static bool TryBindExternalMember(
+ Compilation compilation,
+ INamedTypeSymbol target,
+ IPropertySymbol schemaProperty,
+ string targetTypeName,
+ List<Diagnostic> diagnostics)
+ {
+ Location? location = schemaProperty.Locations.FirstOrDefault(sourceLocation => sourceLocation.IsInSource);
+ if (schemaProperty.Type.TypeKind is TypeKind.Pointer or TypeKind.FunctionPointer ||
+ schemaProperty.Type.IsRefLikeType)
+ {
+ diagnostics.Add(Diagnostic.Create(
+ InvalidExternalMember,
+ location,
+ schemaProperty.Name,
+ targetTypeName,
+ "the member type cannot be used by Serializer<T>"));
+ return false;
+ }
+
+ if (!TryFindTargetMember(target, schemaProperty.Name, out ISymbol? targetMember, out string reason))
+ {
+ diagnostics.Add(Diagnostic.Create(
+ InvalidExternalMember,
+ location,
+ schemaProperty.Name,
+ targetTypeName,
+ reason));
+ return false;
+ }
+
+ ITypeSymbol targetMemberType;
+ if (targetMember is IFieldSymbol field)
+ {
+ if (field.IsStatic ||
+ field.IsConst ||
+ field.IsReadOnly ||
+ field.IsFixedSizeBuffer ||
+ !compilation.IsSymbolAccessibleWithin(field, compilation.Assembly))
+ {
+ diagnostics.Add(Diagnostic.Create(
+ InvalidExternalMember,
+ location,
+ schemaProperty.Name,
+ targetTypeName,
+ "the target field must be an accessible mutable instance field"));
+ return false;
+ }
+
+ targetMemberType = field.Type;
+ }
+ else if (targetMember is IPropertySymbol property)
+ {
+ if (property.IsStatic ||
+ property.IsIndexer ||
+ property.GetMethod is null ||
+ property.SetMethod is null ||
+ property.SetMethod.IsInitOnly ||
+ !compilation.IsSymbolAccessibleWithin(property.GetMethod, compilation.Assembly) ||
+ !compilation.IsSymbolAccessibleWithin(property.SetMethod, compilation.Assembly))
+ {
+ diagnostics.Add(Diagnostic.Create(
+ InvalidExternalMember,
+ location,
+ schemaProperty.Name,
+ targetTypeName,
+ "the target property must have accessible get and non-init set accessors"));
+ return false;
+ }
+
+ targetMemberType = property.Type;
+ }
+ else
+ {
+ diagnostics.Add(Diagnostic.Create(
+ InvalidExternalMember,
+ location,
+ schemaProperty.Name,
+ targetTypeName,
+ "the matching target symbol is not a field or property"));
+ return false;
+ }
+
+ if (!ExternalMemberTypesMatch(schemaProperty.Type, targetMemberType))
+ {
+ diagnostics.Add(Diagnostic.Create(
+ ExternalMemberTypeMismatch,
+ location,
+ schemaProperty.Name,
+ schemaProperty.Type.ToDisplayString(FullNameFormat),
+ targetMemberType.ToDisplayString(FullNameFormat)));
+ return false;
+ }
+
+ if (RequiresExternAlias(schemaProperty.Type, compilation))
+ {
+ diagnostics.Add(Diagnostic.Create(
+ UnsupportedExternalAlias,
+ location,
+ schemaProperty.Type.ToDisplayString(FullNameFormat)));
+ return false;
+ }
+
+ return true;
+ }
+
+ private static bool TryFindTargetMember(
+ INamedTypeSymbol target,
+ string name,
+ out ISymbol? targetMember,
+ out string reason)
+ {
+ for (INamedTypeSymbol? current = target; current is not null; current = current.BaseType)
+ {
+ ImmutableArray<ISymbol> namedMembers = current.GetMembers(name);
+ if (namedMembers.IsEmpty)
+ {
+ continue;
+ }
+
+ if (namedMembers.Length != 1)
+ {
+ targetMember = null;
+ reason = "the target member name is ambiguous";
+ return false;
+ }
+
+ targetMember = namedMembers[0];
+ reason = string.Empty;
+ return true;
+ }
+
+ targetMember = null;
+ reason = "no target member has the same case-sensitive name";
+ return false;
+ }
+
+ private static bool ExternalMemberTypesMatch(ITypeSymbol declarationType, ITypeSymbol targetType)
+ {
+ if ((declarationType.TypeKind == TypeKind.Dynamic) != (targetType.TypeKind == TypeKind.Dynamic))
+ {
+ return false;
+ }
+
+ if (targetType.NullableAnnotation != NullableAnnotation.None &&
+ declarationType.NullableAnnotation != targetType.NullableAnnotation)
+ {
+ return false;
+ }
+
+ if (declarationType is IArrayTypeSymbol declarationArray &&
+ targetType is IArrayTypeSymbol targetArray)
+ {
+ return declarationArray.Rank == targetArray.Rank &&
+ declarationArray.IsSZArray == targetArray.IsSZArray &&
+ ExternalMemberTypesMatch(declarationArray.ElementType, targetArray.ElementType);
+ }
+
+ if (declarationType is IPointerTypeSymbol declarationPointer &&
+ targetType is IPointerTypeSymbol targetPointer)
+ {
+ return ExternalMemberTypesMatch(declarationPointer.PointedAtType, targetPointer.PointedAtType);
+ }
+
+ if (declarationType is INamedTypeSymbol declarationNamed &&
+ targetType is INamedTypeSymbol targetNamed)
+ {
+ if (!SymbolEqualityComparer.Default.Equals(
+ declarationNamed.OriginalDefinition,
+ targetNamed.OriginalDefinition) ||
+ declarationNamed.TypeArguments.Length != targetNamed.TypeArguments.Length)
+ {
+ return false;
+ }
+
+ if ((declarationNamed.ContainingType is null) != (targetNamed.ContainingType is null) ||
+ declarationNamed.ContainingType is not null &&
+ !ExternalMemberTypesMatch(declarationNamed.ContainingType, targetNamed.ContainingType!))
+ {
+ return false;
+ }
+
+ for (int i = 0; i < declarationNamed.TypeArguments.Length; i++)
+ {
+ if (!ExternalMemberTypesMatch(
+ declarationNamed.TypeArguments[i],
+ targetNamed.TypeArguments[i]))
+ {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ return SymbolEqualityComparer.Default.Equals(declarationType, targetType);
+ }
+
+ private static bool HasGenericContext(INamedTypeSymbol type)
+ {
+ for (INamedTypeSymbol? current = type; current is not null; current = current.ContainingType)
+ {
+ if (current.TypeParameters.Length != 0)
+ {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ private static bool ContainsOpenType(ITypeSymbol type)
+ {
+ if (type.TypeKind == TypeKind.TypeParameter)
+ {
+ return true;
+ }
+
+ if (type is IArrayTypeSymbol array)
+ {
+ return ContainsOpenType(array.ElementType);
+ }
+
+ if (type is IPointerTypeSymbol pointer)
+ {
+ return ContainsOpenType(pointer.PointedAtType);
+ }
+
+ if (type is not INamedTypeSymbol named)
+ {
+ return false;
+ }
+
+ if (named.IsUnboundGenericType ||
+ named.ContainingType is not null && ContainsOpenType(named.ContainingType))
+ {
+ return true;
+ }
+
+ foreach (ITypeSymbol argument in named.TypeArguments)
+ {
+ if (ContainsOpenType(argument))
+ {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ private static bool IsRuntimeOwnedTarget(INamedTypeSymbol type)
+ {
+ if (type.SpecialType == SpecialType.System_Object)
+ {
+ return true;
+ }
+
+ string containingNamespace = type.ContainingNamespace.ToDisplayString();
+ if (string.Equals(containingNamespace, "System", StringComparison.Ordinal))
+ {
+ return type.Name is
+ "ArraySegment" or
+ "Memory" or
+ "Nullable" or
+ "ReadOnlyMemory" or
+ "Tuple" or
+ "ValueTuple";
+ }
+
+ return string.Equals(
+ containingNamespace,
+ "System.Collections.Generic",
+ StringComparison.Ordinal) &&
+ string.Equals(type.Name, "KeyValuePair", StringComparison.Ordinal);
+ }
+
+ private static bool RequiresExternAlias(ITypeSymbol type, Compilation compilation)
+ {
+ if (type is IArrayTypeSymbol array)
+ {
+ return RequiresExternAlias(array.ElementType, compilation);
+ }
+
+ if (type is IPointerTypeSymbol pointer)
+ {
+ return RequiresExternAlias(pointer.PointedAtType, compilation);
+ }
+
+ if (type is not INamedTypeSymbol named)
+ {
+ return false;
+ }
+
+ if (AssemblyRequiresExternAlias(named.ContainingAssembly, compilation))
+ {
+ return true;
+ }
+
+ if (named.ContainingType is not null &&
+ RequiresExternAlias(named.ContainingType, compilation))
+ {
+ return true;
+ }
+
+ foreach (ITypeSymbol argument in named.TypeArguments)
+ {
+ if (RequiresExternAlias(argument, compilation))
+ {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ private static bool AssemblyRequiresExternAlias(IAssemblySymbol assembly, Compilation compilation)
+ {
+ if (SymbolEqualityComparer.Default.Equals(assembly, compilation.Assembly))
+ {
+ return false;
+ }
+
+ bool foundAssembly = false;
+ foreach (MetadataReference reference in compilation.References)
+ {
+ if (!SymbolEqualityComparer.Default.Equals(
+ compilation.GetAssemblyOrModuleSymbol(reference),
+ assembly))
+ {
+ continue;
+ }
+
+ foundAssembly = true;
+ if (reference.Properties.Aliases.IsDefaultOrEmpty)
+ {
+ return false;
+ }
+
+ foreach (string alias in reference.Properties.Aliases)
+ {
+ if (string.Equals(alias, "global", StringComparison.Ordinal))
+ {
+ return false;
+ }
+ }
+ }
+
+ return foundAssembly;
+ }
+
+ private static IMethodSymbol? FindAccessibleParameterlessCtor(
+ INamedTypeSymbol type,
+ Compilation compilation)
+ {
+ foreach (IMethodSymbol constructor in type.InstanceConstructors)
+ {
+ if (constructor.Parameters.Length == 0 &&
+ compilation.IsSymbolAccessibleWithin(constructor, compilation.Assembly))
+ {
+ return constructor;
+ }
+ }
+
+ return null;
+ }
+
+ private static bool HasRequiredMembers(INamedTypeSymbol type)
+ {
+ for (INamedTypeSymbol? current = type; current is not null; current = current.BaseType)
+ {
+ foreach (ISymbol member in current.GetMembers())
+ {
+ if (member is IFieldSymbol { IsRequired: true } or
+ IPropertySymbol { IsRequired: true })
+ {
+ return true;
+ }
+ }
+ }
+
+ return false;
+ }
+
+ private static bool SetsRequiredMembers(IMethodSymbol constructor)
+ {
+ foreach (AttributeData attribute in constructor.GetAttributes())
+ {
+ if (string.Equals(
+ attribute.AttributeClass?.ToDisplayString(),
+ "System.Diagnostics.CodeAnalysis.SetsRequiredMembersAttribute",
+ StringComparison.Ordinal))
+ {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ private static void ValidateEnumValues(
+ INamedTypeSymbol enumType,
+ Location? fallbackLocation,
+ List<Diagnostic> diagnostics)
+ {
+ foreach (IFieldSymbol field in enumType.GetMembers().OfType<IFieldSymbol>())
+ {
+ if (!field.HasConstantValue ||
+ IsSupportedEnumValue(field.ConstantValue))
+ {
+ continue;
+ }
+
+ diagnostics.Add(Diagnostic.Create(
+ EnumValueOutOfRange,
+ field.Locations.FirstOrDefault(location => location.IsInSource) ?? fallbackLocation,
+ $"{enumType.ToDisplayString(FullNameFormat)}.{field.Name}"));
+ }
+ }
+
+ private static bool IsSupportedEnumValue(object? value)
+ {
+ return value switch
+ {
+ byte => true,
+ ushort => true,
+ uint => true,
+ ulong unsignedValue => unsignedValue <= uint.MaxValue,
+ sbyte signedValue => signedValue >= 0,
+ short signedValue => signedValue >= 0,
+ int signedValue => signedValue >= 0,
+ long signedValue => signedValue is >= 0 and <= uint.MaxValue,
+ _ => false,
+ };
+ }
+
+ private static bool GetEvolving(AttributeData attribute)
+ {
+ foreach (KeyValuePair<string, TypedConstant> namedArgument in attribute.NamedArguments)
+ {
+ if (string.Equals(namedArgument.Key, "Evolving", StringComparison.Ordinal) &&
+ namedArgument.Value.Value is bool evolving)
+ {
+ return evolving;
+ }
+ }
+
+ return true;
+ }
+
+ private static Location? GetNamedArgumentLocation(
+ AttributeData attribute,
+ string argumentName,
+ CancellationToken cancellationToken)
+ {
+ if (attribute.ApplicationSyntaxReference?.GetSyntax(cancellationToken) is not AttributeSyntax attributeSyntax)
+ {
+ return null;
+ }
+
+ foreach (AttributeArgumentSyntax argument in attributeSyntax.ArgumentList?.Arguments ??
+ default(SeparatedSyntaxList<AttributeArgumentSyntax>))
+ {
+ if (string.Equals(argument.NameEquals?.Name.Identifier.ValueText, argumentName, StringComparison.Ordinal))
+ {
+ return argument.Expression.GetLocation();
+ }
+ }
+
+ return attributeSyntax.GetLocation();
+ }
+
+ private static ImmutableArray<UnionCaseModel> BuildUnionCases(
+ INamedTypeSymbol unionType,
+ List<Diagnostic> diagnostics)
+ {
+ List<UnionCaseModel> cases = [];
+ HashSet<int> caseIds = [];
+ foreach (INamedTypeSymbol caseType in unionType.GetTypeMembers())
+ {
+ bool isUnknown = HasForyUnknownCase(caseType);
+ if (!TryGetForyCase(caseType, diagnostics, out int caseId, out SchemaTypeModel? schemaType))
+ {
+ if (isUnknown)
+ {
+ string unknownCaseTypeName = caseType.ToDisplayString(FullNameFormat);
+ if (!SymbolEqualityComparer.Default.Equals(caseType.BaseType, unionType))
+ {
+ diagnostics.Add(Diagnostic.Create(
+ InvalidUnionCase,
+ caseType.Locations.FirstOrDefault(),
+ unknownCaseTypeName,
+ "unknown case type must directly derive from the annotated union root"));
+ continue;
+ }
+
+ if (!string.Equals(caseType.Name, "Unknown", StringComparison.Ordinal) ||
+ !HasUnknownCaseValueProperty(caseType))
+ {
+ diagnostics.Add(Diagnostic.Create(
+ InvalidUnionCase,
+ caseType.Locations.FirstOrDefault(),
+ unknownCaseTypeName,
+ "unknown case must be named Unknown and expose Value:UnknownCase"));
+ continue;
+ }
+
+ cases.Add(new UnionCaseModel(null, unknownCaseTypeName, isUnknown: true, valueMember: null));
+ }
+
+ continue;
+ }
+
+ if (isUnknown)
+ {
+ diagnostics.Add(Diagnostic.Create(
+ InvalidUnionCase,
+ caseType.Locations.FirstOrDefault(),
+ caseType.ToDisplayString(FullNameFormat),
+ "unknown case must use [ForyUnknownCase] without [ForyCase]"));
+ continue;
+ }
+
+ if (!caseIds.Add(caseId))
+ {
+ diagnostics.Add(Diagnostic.Create(
+ DuplicateUnionCaseId,
+ caseType.Locations.FirstOrDefault(),
+ caseId,
+ unionType.ToDisplayString(FullNameFormat)));
+ continue;
+ }
+
+ if (!SymbolEqualityComparer.Default.Equals(caseType.BaseType, unionType))
+ {
+ diagnostics.Add(Diagnostic.Create(
+ InvalidUnionCase,
+ caseType.Locations.FirstOrDefault(),
+ caseType.ToDisplayString(FullNameFormat),
+ "case type must directly derive from the annotated union root"));
+ continue;
+ }
+
+ string caseTypeName = caseType.ToDisplayString(FullNameFormat);
+ IPropertySymbol? valueProperty = FindProperty(caseType, "Value");
+ if (valueProperty is null)
+ {
+ diagnostics.Add(Diagnostic.Create(
+ InvalidUnionCase,
+ caseType.Locations.FirstOrDefault(),
+ caseTypeName,
+ "known cases must expose a Value property"));
+ continue;
+ }
+
+ MemberModel? valueMember = BuildMemberModel(
+ valueProperty.Name,
+ valueProperty.Type,
+ valueProperty,
+ diagnostics,
+ schemaType,
+ parseFieldAttribute: false);
+ if (valueMember is null)
+ {
+ diagnostics.Add(Diagnostic.Create(
+ InvalidUnionCase,
+ valueProperty.Locations.FirstOrDefault(),
+ caseTypeName,
+ "case Value type is not supported"));
+ continue;
+ }
+
+ cases.Add(new UnionCaseModel(caseId, caseTypeName, isUnknown: false, valueMember));
+ }
+
+ if (cases.Count(c => c.IsUnknown) > 1)
+ {
+ diagnostics.Add(Diagnostic.Create(
+ InvalidUnionCase,
+ unionType.Locations.FirstOrDefault(),
+ unionType.ToDisplayString(FullNameFormat),
+ "union must declare exactly one [ForyUnknownCase] Unknown"));
+ }
+ else if (!cases.Any(c => c.IsUnknown))
+ {
+ diagnostics.Add(Diagnostic.Create(
+ InvalidUnionCase,
unionType.Locations.FirstOrDefault(),
unionType.ToDisplayString(FullNameFormat),
"union must declare [ForyUnknownCase] Unknown"));
@@ -3244,42 +4401,71 @@ public sealed class ForyModelGenerator : IIncrementalGenerator
StringComparison.Ordinal);
}
- private static ForyAttributeKind GetForyAttributeKind(INamedTypeSymbol typeSymbol)
+ private static AttributeData? GetForyAttribute(
+ INamedTypeSymbol typeSymbol,
+ out ForyAttributeKind attributeKind)
+ {
+ return GetForyAttribute(typeSymbol, out attributeKind, out _);
+ }
+
+ private static AttributeData? GetForyAttribute(
+ INamedTypeSymbol typeSymbol,
+ out ForyAttributeKind attributeKind,
+ out bool hasConflict)
{
+ AttributeData? result = null;
+ attributeKind = ForyAttributeKind.None;
+ hasConflict = false;
foreach (AttributeData attribute in typeSymbol.GetAttributes())
{
string? attrName = attribute.AttributeClass?.ToDisplayString();
+ ForyAttributeKind currentKind;
if (string.Equals(attrName, "Apache.Fory.ForyStructAttribute", StringComparison.Ordinal))
{
- return ForyAttributeKind.Struct;
+ currentKind = ForyAttributeKind.Struct;
}
-
- if (string.Equals(attrName, "Apache.Fory.ForyEnumAttribute", StringComparison.Ordinal))
+ else if (string.Equals(attrName, "Apache.Fory.ForyEnumAttribute", StringComparison.Ordinal))
+ {
+ currentKind = ForyAttributeKind.Enum;
+ }
+ else if (string.Equals(attrName, "Apache.Fory.ForyUnionAttribute", StringComparison.Ordinal))
+ {
+ currentKind = ForyAttributeKind.Union;
+ }
+ else
{
- return ForyAttributeKind.Enum;
+ continue;
}
- if (string.Equals(attrName, "Apache.Fory.ForyUnionAttribute", StringComparison.Ordinal))
+ if (result is not null)
{
- return ForyAttributeKind.Union;
+ hasConflict = true;
+ continue;
}
+
+ result = attribute;
+ attributeKind = currentKind;
}
- return ForyAttributeKind.None;
+ return result;
+ }
+
+ private static ForyAttributeKind GetForyAttributeKind(INamedTypeSymbol typeSymbol)
+ {
+ _ = GetForyAttribute(typeSymbol, out ForyAttributeKind attributeKind);
+ return attributeKind;
}
private static MemberModel? BuildMemberModel(
string name,
ITypeSymbol memberType,
ISymbol memberSymbol,
- MemberDeclKind memberDeclKind,
List<Diagnostic> diagnostics)
{
return BuildMemberModel(
name,
memberType,
memberSymbol,
- memberDeclKind,
diagnostics,
schemaTypeOverride: null,
parseFieldAttribute: true);
@@ -3289,7 +4475,6 @@ public sealed class ForyModelGenerator : IIncrementalGenerator
string name,
ITypeSymbol memberType,
ISymbol memberSymbol,
- MemberDeclKind memberDeclKind,
List<Diagnostic> diagnostics,
SchemaTypeModel? schemaTypeOverride,
bool parseFieldAttribute)
@@ -3297,6 +4482,7 @@ public sealed class ForyModelGenerator : IIncrementalGenerator
(bool isOptional, ITypeSymbol unwrappedType) = UnwrapNullable(memberType);
short? fieldId = null;
SchemaTypeModel? schemaType = schemaTypeOverride;
+ bool invalidSchemaType = false;
if (parseFieldAttribute)
{
foreach (AttributeData attribute in memberSymbol.GetAttributes())
@@ -3333,11 +4519,34 @@ public sealed class ForyModelGenerator : IIncrementalGenerator
if (namedArg.Value.Value is ITypeSymbol schemaSymbol)
{
schemaType = TryParseSchemaType(schemaSymbol);
+ if (schemaType is null)
+ {
+ invalidSchemaType = true;
+ diagnostics.Add(Diagnostic.Create(
+ UnsupportedSchemaType,
+ memberSymbol.Locations.FirstOrDefault(),
+ memberSymbol.Name,
+ memberType.ToDisplayString(FullNameFormat)));
+ }
+ }
+ else if (!namedArg.Value.IsNull)
+ {
+ invalidSchemaType = true;
+ diagnostics.Add(Diagnostic.Create(
+ UnsupportedSchemaType,
+ memberSymbol.Locations.FirstOrDefault(),
+ memberSymbol.Name,
+ memberType.ToDisplayString(FullNameFormat)));
}
}
}
}
+ if (invalidSchemaType)
+ {
+ return null;
+ }
+
DynamicAnyKind dynamicAnyKind = ResolveDynamicAnyKind(unwrappedType);
TypeResolution resolution = ResolveTypeResolution(unwrappedType, schemaType);
if (!resolution.Supported)
@@ -3371,7 +4580,6 @@ public sealed class ForyModelGenerator : IIncrementalGenerator
name,
ToSnakeCase(name),
index,
- memberDeclKind,
typeName,
isOptional,
memberType is INamedTypeSymbol nts &&
@@ -3908,23 +5116,8 @@ public sealed class ForyModelGenerator : IIncrementalGenerator
return accessibility is Accessibility.Public or Accessibility.Internal or Accessibility.ProtectedOrInternal;
}
- private static bool HasAccessibleParameterlessCtor(INamedTypeSymbol type)
- {
- foreach (IMethodSymbol ctor in type.InstanceConstructors)
- {
- if (ctor.Parameters.Length != 0)
- {
- continue;
- }
-
- if (ctor.DeclaredAccessibility is Accessibility.Public or Accessibility.Internal or Accessibility.ProtectedOrInternal)
- {
- return true;
- }
- }
-
- return false;
- }
+ private static bool HasAccessibleParameterlessCtor(INamedTypeSymbol type, Compilation compilation) =>
+ FindAccessibleParameterlessCtor(type, compilation) is not null;
private static SchemaTypeModel? TryParseSchemaType(ITypeSymbol symbol)
{
@@ -4491,6 +5684,14 @@ public sealed class ForyModelGenerator : IIncrementalGenerator
private static string EscapeString(string value) => value.Replace("\\", "\\\\").Replace("\"", "\\\"");
+ private static string EscapeIdentifier(string value)
+ {
+ return SyntaxFacts.GetKeywordKind(value) != SyntaxKind.None
+ || SyntaxFacts.GetContextualKeywordKind(value) != SyntaxKind.None
+ ? "@" + value
+ : value;
+ }
+
private static string ToSnakeCase(string name)
{
if (string.IsNullOrEmpty(name))
@@ -4650,17 +5851,23 @@ public sealed class ForyModelGenerator : IIncrementalGenerator
private sealed class TypeModel
{
public TypeModel(
- string typeName,
+ string declarationName,
+ string targetTypeName,
string serializerName,
DeclKind kind,
+ bool evolving,
+ Location? declarationLocation,
ImmutableArray<MemberModel> members,
ImmutableArray<MemberModel> sortedMembers,
ImmutableArray<Diagnostic> diagnostics,
ImmutableArray<UnionCaseModel> unionCases = default)
{
- TypeName = typeName;
+ DeclarationName = declarationName;
+ TargetTypeName = targetTypeName;
SerializerName = serializerName;
Kind = kind;
+ Evolving = evolving;
+ DeclarationLocation = declarationLocation;
Members = members;
SortedMembers = sortedMembers;
Diagnostics = diagnostics;
@@ -4669,9 +5876,12 @@ public sealed class ForyModelGenerator : IIncrementalGenerator
: unionCases;
}
- public string TypeName { get; }
+ public string DeclarationName { get; }
+ public string TargetTypeName { get; }
public string SerializerName { get; }
public DeclKind Kind { get; }
+ public bool Evolving { get; }
+ public Location? DeclarationLocation { get; }
public ImmutableArray<MemberModel> Members { get; }
public ImmutableArray<MemberModel> SortedMembers { get; }
public ImmutableArray<Diagnostic> Diagnostics { get; }
@@ -4684,7 +5894,6 @@ public sealed class ForyModelGenerator : IIncrementalGenerator
string name,
string fieldIdentifier,
int originalIndex,
- MemberDeclKind declKind,
string typeName,
bool isNullable,
bool isNullableValueType,
@@ -4705,7 +5914,6 @@ public sealed class ForyModelGenerator : IIncrementalGenerator
Name = name;
FieldIdentifier = fieldIdentifier;
OriginalIndex = originalIndex;
- DeclKind = declKind;
TypeName = typeName;
IsNullable = isNullable;
IsNullableValueType = isNullableValueType;
@@ -4727,7 +5935,6 @@ public sealed class ForyModelGenerator : IIncrementalGenerator
public string Name { get; }
public string FieldIdentifier { get; }
public int OriginalIndex { get; }
- public MemberDeclKind DeclKind { get; }
public string TypeName { get; }
public bool IsNullable { get; }
public bool IsNullableValueType { get; }
@@ -4763,12 +5970,6 @@ public sealed class ForyModelGenerator : IIncrementalGenerator
public MemberModel? ValueMember { get; }
}
- private enum MemberDeclKind
- {
- Field,
- Property,
- }
-
private enum DeclKind
{
Unknown,
diff --git a/csharp/src/Fory/Attributes.cs b/csharp/src/Fory/Attributes.cs
index 2cdaa43a8..644721f4a 100644
--- a/csharp/src/Fory/Attributes.cs
+++ b/csharp/src/Fory/Attributes.cs
@@ -18,23 +18,36 @@
namespace Apache.Fory;
/// <summary>
-/// Marks a class or struct as a generated Fory struct type.
+/// Marks a class or struct for generated structural serialization, or declares an
+/// external structural serializer.
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct)]
public sealed class ForyStructAttribute : Attribute
{
/// <summary>
- /// Whether the annotated struct should use schema evolution metadata in compatible mode.
+ /// Gets or sets the external class or struct whose schema is declared by the annotated
+ /// serializer declaration. When null, the annotated class or struct is the serialized target.
+ /// </summary>
+ public Type? Target { get; set; }
+
+ /// <summary>
+ /// Gets or sets whether the generated structural serializer uses schema evolution metadata
+ /// in compatible mode.
/// </summary>
public bool Evolving { get; set; } = true;
}
/// <summary>
-/// Marks an enum as a generated Fory enum type.
+/// Marks an enum as a generated Fory enum type, or declares an external enum serializer.
/// </summary>
-[AttributeUsage(AttributeTargets.Enum)]
+[AttributeUsage(AttributeTargets.Class | AttributeTargets.Enum)]
public sealed class ForyEnumAttribute : Attribute
{
+ /// <summary>
+ /// Gets or sets the external enum handled by the annotated serializer declaration.
+ /// When null, the annotated enum is the serialized target.
+ /// </summary>
+ public Type? Target { get; set; }
}
/// <summary>
diff --git a/csharp/src/Fory/Fory.cs b/csharp/src/Fory/Fory.cs
index 776ffd68e..6c805422b 100644
--- a/csharp/src/Fory/Fory.cs
+++ b/csharp/src/Fory/Fory.cs
@@ -100,7 +100,7 @@ public sealed class Fory
}
/// <summary>
- /// Registers a user type by numeric type identifier with a custom serializer.
+ /// Registers a user type by numeric type identifier with a manual serializer.
/// </summary>
/// <typeparam name="T">Type to register.</typeparam>
/// <typeparam name="TSerializer">Serializer implementation used for <typeparamref name="T"/>.</typeparam>
@@ -115,7 +115,7 @@ public sealed class Fory
}
/// <summary>
- /// Registers a user type by name with a custom serializer.
+ /// Registers a user type by name with a manual serializer.
/// </summary>
/// <typeparam name="T">Type to register.</typeparam>
/// <typeparam name="TSerializer">Serializer implementation used for <typeparamref name="T"/>.</typeparam>
@@ -131,7 +131,7 @@ public sealed class Fory
}
/// <summary>
- /// Registers a user type by namespace and name with a custom serializer.
+ /// Registers a user type by namespace and name with a manual serializer.
/// </summary>
/// <typeparam name="T">Type to register.</typeparam>
/// <typeparam name="TSerializer">Serializer implementation used for <typeparamref name="T"/>.</typeparam>
diff --git a/csharp/src/Fory/Serializer.cs b/csharp/src/Fory/Serializer.cs
index ea3c78c68..89de494de 100644
--- a/csharp/src/Fory/Serializer.cs
+++ b/csharp/src/Fory/Serializer.cs
@@ -18,7 +18,8 @@
namespace Apache.Fory;
/// <summary>
-/// Base class for custom serializers.
+/// Base contract for serializers of <typeparamref name="T"/>. Applications subclass it to
+/// implement a manual serializer.
/// </summary>
/// <typeparam name="T">Runtime value type handled by this serializer.</typeparam>
public abstract class Serializer<T>
diff --git a/csharp/src/Fory/ThreadSafeFory.cs b/csharp/src/Fory/ThreadSafeFory.cs
index 012783d1d..ef256067f 100644
--- a/csharp/src/Fory/ThreadSafeFory.cs
+++ b/csharp/src/Fory/ThreadSafeFory.cs
@@ -81,7 +81,7 @@ public sealed class ThreadSafeFory : IDisposable
}
/// <summary>
- /// Registers a user type by numeric type identifier with a custom serializer for all thread-local runtimes.
+ /// Registers a user type by numeric type identifier with a manual serializer for all thread-local runtimes.
/// </summary>
/// <typeparam name="T">Type to register.</typeparam>
/// <typeparam name="TSerializer">Serializer implementation used for <typeparamref name="T"/>.</typeparam>
@@ -95,7 +95,7 @@ public sealed class ThreadSafeFory : IDisposable
}
/// <summary>
- /// Registers a user type by name with a custom serializer for all thread-local runtimes.
+ /// Registers a user type by name with a manual serializer for all thread-local runtimes.
/// </summary>
/// <typeparam name="T">Type to register.</typeparam>
/// <typeparam name="TSerializer">Serializer implementation used for <typeparamref name="T"/>.</typeparam>
@@ -110,7 +110,7 @@ public sealed class ThreadSafeFory : IDisposable
}
/// <summary>
- /// Registers a user type by namespace and name with a custom serializer for all thread-local runtimes.
+ /// Registers a user type by namespace and name with a manual serializer for all thread-local runtimes.
/// </summary>
/// <typeparam name="T">Type to register.</typeparam>
/// <typeparam name="TSerializer">Serializer implementation used for <typeparamref name="T"/>.</typeparam>
diff --git a/csharp/src/Fory/TypeInfo.cs b/csharp/src/Fory/TypeInfo.cs
index 4eaaf526f..4ff798f5f 100644
--- a/csharp/src/Fory/TypeInfo.cs
+++ b/csharp/src/Fory/TypeInfo.cs
@@ -97,13 +97,24 @@ public sealed class TypeInfo
}
internal static TypeInfo Create<T>(Type type, Serializer<T> serializer)
+ {
+ return Create(type, serializer, evolving: true);
+ }
+
+ internal static TypeInfo Create<T>(
+ Type type,
+ Serializer<T> serializer,
+ bool evolving)
{
Func<bool, IReadOnlyList<TypeMetaFieldInfo>> typeMetaFields =
CreateTypeMetaFieldsProvider(serializer, out bool hasTypeMetaFieldsProvider);
(TypeId? builtInTypeId, UserTypeKind? userTypeKind, bool isDynamicType) = ResolveTypeShape(
type,
hasTypeMetaFieldsProvider);
- bool evolving = ResolveStructEvolving(type, userTypeKind);
+ // Generated structural factories supply schema evolution explicitly;
+ // every other binding uses the canonical true default.
+ bool resolvedEvolving =
+ userTypeKind == Apache.Fory.UserTypeKind.Struct ? evolving : true;
bool isNullableType = !type.IsValueType || Nullable.GetUnderlyingType(type) is not null;
bool isRefType = type != typeof(string) && !type.IsValueType;
long boxedValueBytes = BoxedValueBytes<T>();
@@ -116,7 +127,7 @@ public sealed class TypeInfo
isNullableType,
isRefType,
serializer.DefaultObject,
- evolving,
+ resolvedEvolving,
isRegistered: false,
userTypeId: null,
registerByName: false,
@@ -167,18 +178,6 @@ public sealed class TypeInfo
return EmptyTypeMetaFields;
}
- private static bool ResolveStructEvolving(Type type, UserTypeKind? userTypeKind)
- {
- if (userTypeKind != Apache.Fory.UserTypeKind.Struct)
- {
- return true;
- }
-
- Type structType = Nullable.GetUnderlyingType(type) ?? type;
- ForyStructAttribute? attribute = structType.GetCustomAttribute<ForyStructAttribute>();
- return attribute?.Evolving ?? true;
- }
-
private static void WriteDataObject<T>(Serializer<T> serializer, WriteContext context, object? value, bool hasGenerics)
{
serializer.WriteData(context, CoerceRuntimeValue(serializer, value), hasGenerics);
diff --git a/csharp/src/Fory/TypeResolver.cs b/csharp/src/Fory/TypeResolver.cs
index ed95f067b..0e5d6f243 100644
--- a/csharp/src/Fory/TypeResolver.cs
+++ b/csharp/src/Fory/TypeResolver.cs
@@ -18,6 +18,7 @@
using System.Collections.Concurrent;
using System.Collections.Immutable;
using System.Reflection;
+using System.Runtime.CompilerServices;
using System.Threading;
namespace Apache.Fory;
@@ -112,11 +113,57 @@ public sealed class TypeResolver
private ulong _versionHash;
private bool _finalized;
+ /// <summary>
+ /// Registers a generated enum or union serializer factory for a runtime target type.
+ /// This method is called by source-generated module initializers.
+ /// </summary>
+ /// <typeparam name="T">Runtime target type.</typeparam>
+ /// <typeparam name="TSerializer">Generated serializer type.</typeparam>
+ /// <exception cref="InvalidOperationException">
+ /// Thrown when another generated serializer already owns the target type.
+ /// </exception>
public static void RegisterGenerated<T, TSerializer>()
where TSerializer : Serializer<T>, new()
{
- Type type = typeof(T);
- GeneratedFactories[type] = static _ => TypeInfo.Create(typeof(T), new TSerializer());
+ RegisterGeneratedFactory(
+ typeof(T),
+ static _ => TypeInfo.Create(typeof(T), new TSerializer()));
+ }
+
+ /// <summary>
+ /// Registers a generated structural serializer factory for a runtime target type.
+ /// This method is called by source-generated module initializers.
+ /// </summary>
+ /// <typeparam name="T">Runtime target type.</typeparam>
+ /// <typeparam name="TSerializer">Generated serializer type.</typeparam>
+ /// <param name="evolving">Generated structural schema-evolution setting.</param>
+ /// <exception cref="InvalidOperationException">
+ /// Thrown when another generated serializer already owns the target type.
+ /// </exception>
+ public static void RegisterGeneratedStruct<T, TSerializer>(bool evolving)
+ where TSerializer : Serializer<T>, new()
+ {
+ Func<TypeResolver, TypeInfo> factory = evolving
+ ? static _ => TypeInfo.Create(typeof(T), new TSerializer(), true)
+ : static _ => TypeInfo.Create(typeof(T), new TSerializer(), false);
+ RegisterGeneratedFactory(typeof(T), factory);
+ }
+
+ private static void RegisterGeneratedFactory(
+ Type type,
+ Func<TypeResolver, TypeInfo> factory)
+ {
+ if (!GeneratedFactories.TryAdd(type, factory))
+ {
+ ThrowDuplicateGeneratedSerializer(type);
+ }
+ }
+
+ [MethodImpl(MethodImplOptions.NoInlining)]
+ private static void ThrowDuplicateGeneratedSerializer(Type type)
+ {
+ throw new InvalidOperationException(
+ $"a generated serializer is already registered for target type {type}");
}
private static UInt64Map<Type> CreateTypeMap(params (Type Key, Type Value)[] entries)
diff --git a/csharp/tests/Fory.ExternalTypes/ExternalModels.cs b/csharp/tests/Fory.ExternalTypes/ExternalModels.cs
new file mode 100644
index 000000000..63e6f3977
--- /dev/null
+++ b/csharp/tests/Fory.ExternalTypes/ExternalModels.cs
@@ -0,0 +1,174 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+namespace Fory.ExternalTypes;
+
+public class ExternalUser : IComparable<ExternalUser>, IEquatable<ExternalUser>
+{
+ public int Id { get; set; }
+
+ public string Name { get; set; } = string.Empty;
+
+ public ExternalUser? Friend { get; set; }
+
+ public List<ExternalUser> Links { get; set; } = [];
+
+ public int CompareTo(ExternalUser? other)
+ {
+ return other is null ? 1 : Id.CompareTo(other.Id);
+ }
+
+ public bool Equals(ExternalUser? other)
+ {
+ return other is not null && Id == other.Id && Name == other.Name;
+ }
+
+ public override bool Equals(object? obj)
+ {
+ return obj is ExternalUser other && Equals(other);
+ }
+
+ public override int GetHashCode()
+ {
+ return HashCode.Combine(Id, Name);
+ }
+}
+
+public struct ExternalPoint : IEquatable<ExternalPoint>
+{
+ public int X { get; set; }
+
+ public int Y { get; set; }
+
+ public readonly bool Equals(ExternalPoint other)
+ {
+ return X == other.X && Y == other.Y;
+ }
+
+ public override readonly bool Equals(object? obj)
+ {
+ return obj is ExternalPoint other && Equals(other);
+ }
+
+ public override readonly int GetHashCode()
+ {
+ return HashCode.Combine(X, Y);
+ }
+}
+
+public enum ExternalStatus : uint
+{
+ Unknown = 0,
+ Ready = 1,
+ Done = 2,
+ Complete = Done,
+}
+
+public sealed class ExternalBox<T>
+{
+ public T Value { get; set; } = default!;
+}
+
+public class ExternalBase
+{
+ public string BaseName { get; set; } = string.Empty;
+}
+
+public sealed class ExternalDerived : ExternalBase
+{
+ public int Id { get; set; }
+}
+
+public sealed class ExternalFields
+{
+ public int Count;
+
+ public string Name { get; set; } = string.Empty;
+
+ public int @event { get; set; }
+}
+
+public sealed class ExternalSchemaModel
+{
+ public int FixedValue { get; set; }
+
+ public long TaggedValue { get; set; }
+
+ public int[] ArrayValue { get; set; } = [];
+
+ public List<int> ListValue { get; set; } = [];
+
+ public HashSet<int> SetValue { get; set; } = [];
+
+ public Dictionary<uint, List<ulong?>?> NestedValue { get; set; } = [];
+}
+
+public sealed class ExternalVersionOne
+{
+ public int Id { get; set; }
+
+ public string Name { get; set; } = string.Empty;
+}
+
+public sealed class ExternalVersionTwo
+{
+ public string Name { get; set; } = string.Empty;
+
+ public int Id { get; set; }
+
+ public long Added { get; set; }
+}
+
+public sealed class ExternalVersionRenamed
+{
+ public int Identifier { get; set; }
+
+ public string Name { get; set; } = string.Empty;
+}
+
+public sealed class ExternalEvolutionOff
+{
+ public int Value { get; set; }
+}
+
+public sealed class XlangUser
+{
+ public int Id { get; set; }
+
+ public string Name { get; set; } = string.Empty;
+}
+
+public struct XlangPoint
+{
+ public int X { get; set; }
+
+ public int Y { get; set; }
+}
+
+public enum XlangStatus : uint
+{
+ Unknown = 0,
+ Ready = 1,
+ Done = 2,
+}
+
+public sealed class XlangHolder
+{
+ public List<XlangUser> Users { get; set; } = [];
+
+ public Dictionary<string, XlangUser> UsersByName { get; set; } = [];
+}
diff --git a/csharp/tests/Fory.XlangPeer/Fory.XlangPeer.csproj b/csharp/tests/Fory.ExternalTypes/Fory.ExternalTypes.csproj
similarity index 50%
copy from csharp/tests/Fory.XlangPeer/Fory.XlangPeer.csproj
copy to csharp/tests/Fory.ExternalTypes/Fory.ExternalTypes.csproj
index b5a039459..c578d04a8 100644
--- a/csharp/tests/Fory.XlangPeer/Fory.XlangPeer.csproj
+++ b/csharp/tests/Fory.ExternalTypes/Fory.ExternalTypes.csproj
@@ -1,15 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
- <OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<LangVersion>12.0</LangVersion>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
</PropertyGroup>
-
- <ItemGroup>
- <ProjectReference Include="..\..\src\Fory\Fory.csproj" />
- <ProjectReference Include="..\..\src\Fory.Generator\Fory.Generator.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
- </ItemGroup>
</Project>
diff --git a/csharp/tests/Fory.Tests/ExternalTypeSerializationTests.cs b/csharp/tests/Fory.Tests/ExternalTypeSerializationTests.cs
new file mode 100644
index 000000000..34d7a0c8d
--- /dev/null
+++ b/csharp/tests/Fory.Tests/ExternalTypeSerializationTests.cs
@@ -0,0 +1,496 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+using System.Collections.Concurrent;
+using System.Collections.Immutable;
+using Apache.Fory;
+using Fory.ExternalTypes;
+using ForyRuntime = Apache.Fory.Fory;
+
+namespace Apache.Fory.Tests;
+
+public sealed class ExternalTypeSerializationTests
+{
+ [Theory]
+ [InlineData(true)]
+ [InlineData(false)]
+ public void DirectRootsRoundTrip(bool compatible)
+ {
+ ForyRuntime fory = NewFory(compatible);
+ ExternalUser user = User(1, "alice");
+ ExternalPoint point = new() { X = 3, Y = -5 };
+
+ AssertUser(user, RoundTrip(fory, user));
+ Assert.Equal(point, RoundTrip(fory, point));
+ Assert.Equal(point, RoundTrip<ExternalPoint?>(fory, point));
+ Assert.Null(RoundTrip<ExternalPoint?>(fory, null));
+ Assert.Equal(ExternalStatus.Ready, RoundTrip(fory, ExternalStatus.Ready));
+ Assert.Equal(ExternalStatus.Done, RoundTrip(fory, ExternalStatus.Complete));
+ Assert.Equal((ExternalStatus)99u, RoundTrip(fory, (ExternalStatus)99u));
+
+ ExternalBox<string> box = RoundTrip(
+ fory,
+ new ExternalBox<string> { Value = "closed" });
+ Assert.Equal("closed", box.Value);
+
+ ExternalDerived derived = RoundTrip(
+ fory,
+ new ExternalDerived { Id = 2, BaseName = "base" });
+ Assert.Equal(2, derived.Id);
+ Assert.Equal("base", derived.BaseName);
+
+ ExternalFields fields = RoundTrip(
+ fory,
+ new ExternalFields { Count = 4, Name = "field", @event = 9 });
+ Assert.Equal(4, fields.Count);
+ Assert.Equal("field", fields.Name);
+ Assert.Equal(9, fields.@event);
+ }
+
+ [Fact]
+ public void RegistrationFormsWork()
+ {
+ ExternalUser value = User(2, "forms");
+
+ ForyRuntime numeric = ForyRuntime.Builder().Build();
+ numeric.Register<ExternalUser>(6101);
+ AssertUser(value, RoundTrip(numeric, value));
+
+ ForyRuntime dotted = ForyRuntime.Builder().Build();
+ dotted.Register<ExternalUser>("external.User");
+ AssertUser(value, RoundTrip(dotted, value));
+
+ ForyRuntime split = ForyRuntime.Builder().Build();
+ split.Register<ExternalUser>("external", "User");
+ AssertUser(value, RoundTrip(split, value));
+ }
+
+ [Fact]
+ public void ThreadSafeRootsRoundTrip()
+ {
+ using ThreadSafeFory fory = ForyRuntime.Builder().BuildThreadSafe();
+ fory.Register<ExternalUser>(6101);
+
+ ExternalUser decoded = fory.Deserialize<ExternalUser>(
+ fory.Serialize(User(3, "thread")));
+
+ Assert.Equal(3, decoded.Id);
+ Assert.Equal("thread", decoded.Name);
+ }
+
+ [Theory]
+ [InlineData(true)]
+ [InlineData(false)]
+ public void GeneratedHolderRoundTrip(bool compatible)
+ {
+ ForyRuntime fory = NewFory(compatible, trackRef: true);
+ ExternalUser shared = User(4, "shared");
+ ExternalTargetsHolder value = new()
+ {
+ User = shared,
+ Point = new ExternalPoint { X = 7, Y = 8 },
+ OptionalPoint = new ExternalPoint { X = 9, Y = 10 },
+ Status = ExternalStatus.Done,
+ Users = [shared],
+ UsersByName = new Dictionary<string, ExternalUser>
+ {
+ ["shared"] = shared,
+ },
+ };
+
+ ExternalTargetsHolder decoded = RoundTrip(fory, value);
+
+ Assert.Equal(value.Point, decoded.Point);
+ Assert.Equal(value.OptionalPoint, decoded.OptionalPoint);
+ Assert.Equal(value.Status, decoded.Status);
+ Assert.Same(decoded.User, decoded.Users[0]);
+ Assert.Same(decoded.User, decoded.UsersByName["shared"]);
+ }
+
+ [Fact]
+ public void SchemaDescriptorsRoundTrip()
+ {
+ ForyRuntime fory = NewFory(compatible: true);
+ ExternalSchemaModel value = new()
+ {
+ FixedValue = -7,
+ TaggedValue = long.MaxValue,
+ ArrayValue = [1, 2, 3],
+ ListValue = [4, 5],
+ SetValue = [6, 7],
+ NestedValue = new Dictionary<uint, List<ulong?>?>
+ {
+ [8] = [9, null, ulong.MaxValue],
+ [10] = null,
+ },
+ };
+
+ ExternalSchemaModel decoded = RoundTrip(fory, value);
+
+ Assert.Equal(value.FixedValue, decoded.FixedValue);
+ Assert.Equal(value.TaggedValue, decoded.TaggedValue);
+ Assert.Equal(value.ArrayValue, decoded.ArrayValue);
+ Assert.Equal(value.ListValue, decoded.ListValue);
+ Assert.True(value.SetValue.SetEquals(decoded.SetValue));
+ Assert.Equal(value.NestedValue[8], decoded.NestedValue[8]);
+ Assert.Null(decoded.NestedValue[10]);
+ }
+
+ [Theory]
+ [InlineData(true)]
+ [InlineData(false)]
+ public void EquivalentSchemasMatchBytes(bool compatible)
+ {
+ ForyRuntime external = NewFory(compatible);
+ ForyRuntime ordinary = NewOrdinaryFory(compatible);
+ ExternalUser externalUser = User(5, "wire");
+ OrdinaryUser ordinaryUser = new() { Id = 5, Name = "wire" };
+
+ Assert.Equal(
+ ordinary.Serialize(ordinaryUser),
+ external.Serialize(externalUser));
+ Assert.Equal(
+ ordinary.Serialize(new OrdinaryPoint { X = 1, Y = 2 }),
+ external.Serialize(new ExternalPoint { X = 1, Y = 2 }));
+ Assert.Equal(
+ ordinary.Serialize(OrdinaryStatus.Complete),
+ external.Serialize(ExternalStatus.Complete));
+
+ OrdinaryTargetsHolder ordinaryHolder = new()
+ {
+ User = ordinaryUser,
+ Point = new OrdinaryPoint { X = 1, Y = 2 },
+ OptionalPoint = new OrdinaryPoint { X = 3, Y = 4 },
+ Status = OrdinaryStatus.Done,
+ Users = [ordinaryUser],
+ UsersByName = new Dictionary<string, OrdinaryUser>
+ {
+ ["wire"] = ordinaryUser,
+ },
+ };
+ ExternalTargetsHolder externalHolder = new()
+ {
+ User = externalUser,
+ Point = new ExternalPoint { X = 1, Y = 2 },
+ OptionalPoint = new ExternalPoint { X = 3, Y = 4 },
+ Status = ExternalStatus.Done,
+ Users = [externalUser],
+ UsersByName = new Dictionary<string, ExternalUser>
+ {
+ ["wire"] = externalUser,
+ },
+ };
+ Assert.Equal(
+ ordinary.Serialize(ordinaryHolder),
+ external.Serialize(externalHolder));
+ }
+
+ [Fact]
+ public void CompatibleEvolutionWorks()
+ {
+ ForyRuntime newer = ForyRuntime.Builder().Compatible(true).Build();
+ newer.Register<ExternalVersionTwo>(6201);
+ ForyRuntime older = ForyRuntime.Builder().Compatible(true).Build();
+ older.Register<ExternalVersionOne>(6201);
+
+ ExternalVersionOne removed = older.Deserialize<ExternalVersionOne>(
+ newer.Serialize(new ExternalVersionTwo
+ {
+ Id = 7,
+ Name = "new",
+ Added = 11,
+ }));
+ Assert.Equal(7, removed.Id);
+ Assert.Equal("new", removed.Name);
+
+ ExternalVersionTwo added = newer.Deserialize<ExternalVersionTwo>(
+ older.Serialize(new ExternalVersionOne
+ {
+ Id = 8,
+ Name = "old",
+ }));
+ Assert.Equal(8, added.Id);
+ Assert.Equal("old", added.Name);
+ Assert.Equal(0, added.Added);
+
+ ForyRuntime renamed = ForyRuntime.Builder().Compatible(true).Build();
+ renamed.Register<ExternalVersionRenamed>(6201);
+ ExternalVersionRenamed decoded = renamed.Deserialize<ExternalVersionRenamed>(
+ older.Serialize(new ExternalVersionOne
+ {
+ Id = 9,
+ Name = "renamed",
+ }));
+ Assert.Equal(9, decoded.Identifier);
+ Assert.Equal("renamed", decoded.Name);
+
+ ForyRuntime externalOff = ForyRuntime.Builder().Compatible(true).Build();
+ externalOff.Register<ExternalEvolutionOff>(6202);
+ ForyRuntime ordinaryOff = ForyRuntime.Builder().Compatible(true).Build();
+ ordinaryOff.Register<OrdinaryEvolutionOff>(6202);
+ Assert.False(new TypeResolver().GetTypeInfo<ExternalEvolutionOff>().Evolving);
+ Assert.False(new TypeResolver().GetTypeInfo<OrdinaryEvolutionOff>().Evolving);
+ Assert.Equal(
+ ordinaryOff.Serialize(new OrdinaryEvolutionOff { Value = 12 }),
+ externalOff.Serialize(new ExternalEvolutionOff { Value = 12 }));
+ }
+
+ [Fact]
+ public void TrackedGraphsRoundTrip()
+ {
+ ForyRuntime fory = NewFory(compatible: true, trackRef: true);
+
+ ExternalUser self = User(10, "self");
+ self.Friend = self;
+ ExternalUser selfDecoded = RoundTrip(fory, self);
+ Assert.Same(selfDecoded, selfDecoded.Friend);
+
+ ExternalUser first = User(11, "first");
+ ExternalUser second = User(12, "second");
+ first.Links.Add(second);
+ second.Friend = first;
+ ExternalUser graph = RoundTrip(fory, first);
+ Assert.Same(graph, graph.Links[0].Friend);
+
+ object dynamicSelf = self;
+ ExternalUser dynamicDecoded = Assert.IsType<ExternalUser>(
+ RoundTrip<object>(fory, dynamicSelf));
+ Assert.Same(dynamicDecoded, dynamicDecoded.Friend);
+ }
+
+ [Fact]
+ public void DynamicValuesRoundTrip()
+ {
+ ForyRuntime fory = NewFory(compatible: true);
+ ExternalUser user = User(13, "dynamic");
+
+ AssertUser(
+ user,
+ Assert.IsType<ExternalUser>(RoundTrip<object>(fory, user)));
+
+ ExternalDynamicHolder holder = new() { DynamicValue = user };
+ ExternalDynamicHolder decodedHolder = RoundTrip(fory, holder);
+ AssertUser(user, Assert.IsType<ExternalUser>(decodedHolder.DynamicValue));
+
+ object list = new List<object?> { user };
+ List<object?> decodedList = Assert.IsType<List<object?>>(
+ RoundTrip<object>(fory, list));
+ AssertUser(user, Assert.IsType<ExternalUser>(decodedList[0]));
+
+ object map = new Dictionary<object, object?> { ["user"] = user };
+ Dictionary<object, object?> decodedMap =
+ Assert.IsType<Dictionary<object, object?>>(
+ RoundTrip<object>(fory, map));
+ AssertUser(user, Assert.IsType<ExternalUser>(decodedMap["user"]));
+ }
+
+ [Fact]
+ public void CarrierRootsRoundTrip()
+ {
+ ForyRuntime fory = NewFory(compatible: true);
+ ExternalUser first = User(14, "first");
+ ExternalUser second = User(15, "second");
+
+ Assert.Empty(RoundTrip(fory, Array.Empty<ExternalUser>()));
+ AssertUsers([first, second], RoundTrip(fory, new[] { first, second }));
+
+ Assert.Null(RoundTrip<ExternalPoint?>(fory, null));
+ Assert.Equal(
+ new ExternalPoint { X = 1, Y = 2 },
+ RoundTrip<ExternalPoint?>(
+ fory,
+ new ExternalPoint { X = 1, Y = 2 }));
+
+ Assert.Empty(RoundTrip(fory, new List<ExternalUser>()));
+ AssertUsers([first, second], RoundTrip(fory, new List<ExternalUser> { first, second }));
+ Assert.Empty(RoundTrip(fory, new LinkedList<ExternalUser>()));
+ AssertUsers(
+ [first, second],
+ RoundTrip(fory, new LinkedList<ExternalUser>([first, second])));
+ Assert.Empty(RoundTrip(fory, new Queue<ExternalUser>()));
+ AssertUsers(
+ [first, second],
+ RoundTrip(fory, new Queue<ExternalUser>([first, second])));
+ Assert.Empty(RoundTrip(fory, new Stack<ExternalUser>()));
+ Stack<ExternalUser> stack = new();
+ stack.Push(first);
+ stack.Push(second);
+ AssertUsers(stack, RoundTrip(fory, stack));
+
+ Assert.Empty(RoundTrip(fory, new HashSet<ExternalUser>()));
+ Assert.True(
+ RoundTrip(fory, new HashSet<ExternalUser> { first, second })
+ .SetEquals([first, second]));
+ Assert.Empty(RoundTrip(fory, new SortedSet<ExternalUser>()));
+ AssertUsers(
+ [first, second],
+ RoundTrip(fory, new SortedSet<ExternalUser> { second, first }));
+ Assert.Empty(RoundTrip(fory, ImmutableHashSet<ExternalUser>.Empty));
+ Assert.True(
+ RoundTrip(fory, ImmutableHashSet.Create(first, second))
+ .SetEquals([first, second]));
+
+ Assert.Empty(RoundTrip(fory, new Dictionary<ExternalUser, string>()));
+ Dictionary<ExternalUser, string> dictionary = RoundTrip(
+ fory,
+ new Dictionary<ExternalUser, string> { [first] = "one" });
+ Assert.Equal("one", dictionary[first]);
+
+ Assert.Empty(RoundTrip(fory, new SortedDictionary<ExternalUser, string>()));
+ SortedDictionary<ExternalUser, string> sortedDictionary = RoundTrip(
+ fory,
+ new SortedDictionary<ExternalUser, string> { [first] = "one" });
+ Assert.Equal("one", sortedDictionary[first]);
+
+ Assert.Empty(RoundTrip(fory, new SortedList<ExternalUser, string>()));
+ SortedList<ExternalUser, string> sortedList = RoundTrip(
+ fory,
+ new SortedList<ExternalUser, string> { [first] = "one" });
+ Assert.Equal("one", sortedList[first]);
+
+ Assert.Empty(RoundTrip(fory, new ConcurrentDictionary<string, ExternalUser>()));
+ ConcurrentDictionary<string, ExternalUser> concurrent = RoundTrip(
+ fory,
+ new ConcurrentDictionary<string, ExternalUser>(
+ new Dictionary<string, ExternalUser> { ["one"] = first }));
+ AssertUser(first, concurrent["one"]);
+
+ Assert.Empty(RoundTrip(fory, new NullableKeyDictionary<string, ExternalUser>()));
+ NullableKeyDictionary<string, ExternalUser> nullableKeys = new()
+ {
+ [null!] = first,
+ ["two"] = second,
+ };
+ NullableKeyDictionary<string, ExternalUser> decodedNullableKeys =
+ RoundTrip(fory, nullableKeys);
+ AssertUser(first, decodedNullableKeys[null!]);
+ AssertUser(second, decodedNullableKeys["two"]);
+
+ Dictionary<string, List<ExternalUser[]>> nested = new()
+ {
+ ["users"] = [new[] { first, second }],
+ };
+ Dictionary<string, List<ExternalUser[]>> decodedNested =
+ RoundTrip(fory, nested);
+ AssertUsers([first, second], decodedNested["users"][0]);
+ }
+
+ [Fact]
+ public void ManualSerializerReplacesGenerated()
+ {
+ ExternalFields value = new() { Count = 19, Name = "manual" };
+ ForyRuntime generated = ForyRuntime.Builder().Build();
+ generated.Register<ExternalFields>(6106);
+ byte[] generatedBytes = generated.Serialize(value);
+
+ ForyRuntime manual = ForyRuntime.Builder().Build();
+ manual.Register<ExternalFields, ExternalFieldsManualSerializer>(6106);
+ byte[] manualBytes = manual.Serialize(value);
+ ExternalFields decoded = manual.Deserialize<ExternalFields>(manualBytes);
+
+ Assert.NotEqual(generatedBytes, manualBytes);
+ Assert.Equal(value.Count, decoded.Count);
+ Assert.Equal(value.Name, decoded.Name);
+ Assert.Throws<InvalidDataException>(
+ () => generated.Register<ExternalFields, ExternalFieldsManualSerializer>(6107));
+ }
+
+ [Fact]
+ public void DuplicateFactoryIsRejected()
+ {
+ InvalidOperationException error = Assert.Throws<InvalidOperationException>(
+ () => TypeResolver.RegisterGeneratedStruct<
+ ExternalUser,
+ DuplicateExternalUserSerializer>(true));
+ Assert.Contains(typeof(ExternalUser).ToString(), error.Message, StringComparison.Ordinal);
+
+ ForyRuntime fory = NewFory(compatible: true);
+ ExternalUser decoded = RoundTrip(fory, User(20, "installed"));
+ Assert.Equal("installed", decoded.Name);
+ }
+
+ private static ForyRuntime NewFory(bool compatible, bool trackRef = false)
+ {
+ return ForyRuntime.Builder()
+ .Compatible(compatible)
+ .TrackRef(trackRef)
+ .Build()
+ .Register<ExternalUser>(6101)
+ .Register<ExternalPoint>(6102)
+ .Register<ExternalStatus>(6103)
+ .Register<ExternalBox<string>>(6104)
+ .Register<ExternalDerived>(6105)
+ .Register<ExternalFields>(6106)
+ .Register<ExternalSchemaModel>(6107)
+ .Register<ExternalTargetsHolder>(6108)
+ .Register<ExternalDynamicHolder>(6109);
+ }
+
+ private static ForyRuntime NewOrdinaryFory(bool compatible)
+ {
+ return ForyRuntime.Builder()
+ .Compatible(compatible)
+ .Build()
+ .Register<OrdinaryUser>(6101)
+ .Register<OrdinaryPoint>(6102)
+ .Register<OrdinaryStatus>(6103)
+ .Register<OrdinaryTargetsHolder>(6108);
+ }
+
+ private static ExternalUser User(int id, string name)
+ {
+ return new ExternalUser { Id = id, Name = name };
+ }
+
+ private static T RoundTrip<T>(ForyRuntime fory, T value)
+ {
+ return fory.Deserialize<T>(fory.Serialize(value));
+ }
+
+ private static void AssertUser(ExternalUser expected, ExternalUser actual)
+ {
+ Assert.Equal(expected.Id, actual.Id);
+ Assert.Equal(expected.Name, actual.Name);
+ }
+
+ private static void AssertUsers(
+ IEnumerable<ExternalUser> expected,
+ IEnumerable<ExternalUser> actual)
+ {
+ Assert.Equal(
+ expected.Select(user => (user.Id, user.Name)),
+ actual.Select(user => (user.Id, user.Name)));
+ }
+}
+
+internal sealed class DuplicateExternalUserSerializer : Serializer<ExternalUser>
+{
+ public override ExternalUser DefaultValue => null!;
+
+ public override void WriteData(
+ WriteContext context,
+ in ExternalUser value,
+ bool hasGenerics)
+ {
+ throw new NotSupportedException();
+ }
+
+ public override ExternalUser ReadData(ReadContext context)
+ {
+ throw new NotSupportedException();
+ }
+}
diff --git a/csharp/tests/Fory.Tests/ExternalTypeSerializers.cs b/csharp/tests/Fory.Tests/ExternalTypeSerializers.cs
new file mode 100644
index 000000000..37f1d689b
--- /dev/null
+++ b/csharp/tests/Fory.Tests/ExternalTypeSerializers.cs
@@ -0,0 +1,260 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+using Apache.Fory;
+using Fory.ExternalTypes;
+using S = Apache.Fory.Schema.Types;
+
+namespace Apache.Fory.Tests;
+
+[ForyStruct(Target = typeof(ExternalUser))]
+internal abstract class ExternalUserSerializer
+{
+ [ForyField(1)]
+ public abstract int Id { get; }
+
+ [ForyField(2)]
+ public abstract string Name { get; }
+
+ [ForyField(3)]
+ public abstract ExternalUser? Friend { get; }
+
+ [ForyField(4)]
+ public abstract List<ExternalUser> Links { get; }
+}
+
+[ForyStruct(Target = typeof(ExternalPoint))]
+internal abstract class ExternalPointSerializer
+{
+ [ForyField(1)]
+ public abstract int X { get; }
+
+ [ForyField(2)]
+ public abstract int Y { get; }
+}
+
+[ForyEnum(Target = typeof(ExternalStatus))]
+internal static class ExternalStatusSerializer
+{
+}
+
+[ForyStruct(Target = typeof(ExternalBox<string>))]
+internal abstract class ExternalStringBoxSerializer
+{
+ [ForyField(1)]
+ public abstract string Value { get; }
+}
+
+[ForyStruct(Target = typeof(ExternalDerived))]
+internal abstract class ExternalDerivedSerializer
+{
+ [ForyField(1)]
+ public abstract int Id { get; }
+
+ [ForyField(2)]
+ public abstract string BaseName { get; }
+}
+
+[ForyStruct(Target = typeof(ExternalFields))]
+internal abstract class ExternalFieldsSerializer
+{
+ [ForyField(1)]
+ public abstract int Count { get; }
+
+ [ForyField(2)]
+ public abstract string Name { get; }
+
+ [ForyField(3)]
+ public abstract int @event { get; }
+}
+
+[ForyStruct(Target = typeof(ExternalSchemaModel))]
+internal abstract class ExternalSchemaSerializer
+{
+ [ForyField(1, Type = typeof(S.Fixed<S.Int32>))]
+ public abstract int FixedValue { get; }
+
+ [ForyField(2, Type = typeof(S.Tagged<S.Int64>))]
+ public abstract long TaggedValue { get; }
+
+ [ForyField(3, Type = typeof(S.Array<S.Int32>))]
+ public abstract int[] ArrayValue { get; }
+
+ [ForyField(4, Type = typeof(S.List<S.Int32>))]
+ public abstract List<int> ListValue { get; }
+
+ [ForyField(5, Type = typeof(S.Set<S.Int32>))]
+ public abstract HashSet<int> SetValue { get; }
+
+ [ForyField(6, Type = typeof(S.Map<S.Fixed<S.UInt32>, S.List<S.Tagged<S.UInt64>>>))]
+ public abstract Dictionary<uint, List<ulong?>?> NestedValue { get; }
+}
+
+[ForyStruct(Target = typeof(ExternalVersionOne))]
+internal abstract class ExternalVersionOneSerializer
+{
+ [ForyField(1)]
+ public abstract int Id { get; }
+
+ [ForyField(2)]
+ public abstract string Name { get; }
+}
+
+[ForyStruct(Target = typeof(ExternalVersionTwo))]
+internal abstract class ExternalVersionTwoSerializer
+{
+ [ForyField(2)]
+ public abstract string Name { get; }
+
+ [ForyField(1)]
+ public abstract int Id { get; }
+
+ [ForyField(3)]
+ public abstract long Added { get; }
+}
+
+[ForyStruct(Target = typeof(ExternalVersionRenamed))]
+internal abstract class ExternalVersionRenamedSerializer
+{
+ [ForyField(1)]
+ public abstract int Identifier { get; }
+
+ [ForyField(2)]
+ public abstract string Name { get; }
+}
+
+[ForyStruct(Target = typeof(ExternalEvolutionOff), Evolving = false)]
+internal abstract class ExternalEvolutionOffSerializer
+{
+ [ForyField(1)]
+ public abstract int Value { get; }
+}
+
+[ForyStruct]
+internal sealed class OrdinaryUser
+{
+ [ForyField(1)]
+ public int Id { get; set; }
+
+ [ForyField(2)]
+ public string Name { get; set; } = string.Empty;
+
+ [ForyField(3)]
+ public OrdinaryUser? Friend { get; set; }
+
+ [ForyField(4)]
+ public List<OrdinaryUser> Links { get; set; } = [];
+}
+
+[ForyStruct]
+internal struct OrdinaryPoint
+{
+ [ForyField(1)]
+ public int X { get; set; }
+
+ [ForyField(2)]
+ public int Y { get; set; }
+}
+
+[ForyEnum]
+internal enum OrdinaryStatus : uint
+{
+ Unknown = 0,
+ Ready = 1,
+ Done = 2,
+ Complete = Done,
+}
+
+[ForyStruct]
+internal sealed class ExternalTargetsHolder
+{
+ [ForyField(1)]
+ public ExternalUser User { get; set; } = new();
+
+ [ForyField(2)]
+ public ExternalPoint Point { get; set; }
+
+ [ForyField(3)]
+ public ExternalPoint? OptionalPoint { get; set; }
+
+ [ForyField(4)]
+ public ExternalStatus Status { get; set; }
+
+ [ForyField(5)]
+ public List<ExternalUser> Users { get; set; } = [];
+
+ [ForyField(6)]
+ public Dictionary<string, ExternalUser> UsersByName { get; set; } = [];
+}
+
+[ForyStruct]
+internal sealed class ExternalDynamicHolder
+{
+ [ForyField(1)]
+ public object? DynamicValue { get; set; }
+}
+
+[ForyStruct]
+internal sealed class OrdinaryTargetsHolder
+{
+ [ForyField(1)]
+ public OrdinaryUser User { get; set; } = new();
+
+ [ForyField(2)]
+ public OrdinaryPoint Point { get; set; }
+
+ [ForyField(3)]
+ public OrdinaryPoint? OptionalPoint { get; set; }
+
+ [ForyField(4)]
+ public OrdinaryStatus Status { get; set; }
+
+ [ForyField(5)]
+ public List<OrdinaryUser> Users { get; set; } = [];
+
+ [ForyField(6)]
+ public Dictionary<string, OrdinaryUser> UsersByName { get; set; } = [];
+}
+
+[ForyStruct(Evolving = false)]
+internal sealed class OrdinaryEvolutionOff
+{
+ [ForyField(1)]
+ public int Value { get; set; }
+}
+
+internal sealed class ExternalFieldsManualSerializer : Serializer<ExternalFields>
+{
+ public override ExternalFields DefaultValue => null!;
+
+ public override void WriteData(
+ WriteContext context,
+ in ExternalFields value,
+ bool hasGenerics)
+ {
+ _ = hasGenerics;
+ context.Writer.WriteVarInt32(value.Count + 100);
+ context.TypeResolver.GetSerializer<string>().WriteData(context, value.Name, false);
+ }
+
+ public override ExternalFields ReadData(ReadContext context)
+ {
+ int count = context.Reader.ReadVarInt32() - 100;
+ string name = context.TypeResolver.GetSerializer<string>().ReadData(context);
+ return new ExternalFields { Count = count, Name = name };
+ }
+}
diff --git a/csharp/tests/Fory.Tests/Fory.Tests.csproj b/csharp/tests/Fory.Tests/Fory.Tests.csproj
index bb3130960..c96ff2b67 100644
--- a/csharp/tests/Fory.Tests/Fory.Tests.csproj
+++ b/csharp/tests/Fory.Tests/Fory.Tests.csproj
@@ -23,6 +23,7 @@
</ItemGroup>
<ItemGroup>
+ <ProjectReference Include="..\Fory.ExternalTypes\Fory.ExternalTypes.csproj" />
<ProjectReference Include="..\..\src\Fory\Fory.csproj" />
<ProjectReference Include="..\..\src\Fory.Generator\Fory.Generator.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
<ProjectReference Include="..\..\src\Fory.Generator\Fory.Generator.csproj" ReferenceOutputAssembly="true" />
diff --git a/csharp/tests/Fory.Tests/ForyGeneratorTests.cs b/csharp/tests/Fory.Tests/ForyGeneratorTests.cs
index 053846341..42338b87a 100644
--- a/csharp/tests/Fory.Tests/ForyGeneratorTests.cs
+++ b/csharp/tests/Fory.Tests/ForyGeneratorTests.cs
@@ -19,6 +19,7 @@ using System.Collections.Immutable;
using Apache.Fory.Generator;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
+using Microsoft.CodeAnalysis.Emit;
namespace Apache.Fory.Tests;
@@ -209,6 +210,680 @@ public sealed class ForyGeneratorTests
Assert.True(allocationIndex > checkIndex);
}
+ [Fact]
+ public void ExternalTargetsUseOneEmitter()
+ {
+ const string source = """
+ #nullable enable
+ using System.Collections.Generic;
+ using Apache.Fory;
+ using UserTarget = Fory.ExternalTypes.ExternalUser;
+ using S = Apache.Fory.Schema.Types;
+
+ namespace GeneratedDiagnostics;
+
+ [ForyStruct(Target = typeof(UserTarget))]
+ internal abstract class UserSerializer
+ {
+ [ForyField(1)]
+ public abstract int Id { get; }
+
+ [ForyField(2)]
+ public abstract string Name { get; }
+
+ [ForyField(3)]
+ public abstract UserTarget? Friend { get; }
+
+ [ForyField(4)]
+ public abstract List<UserTarget> Links { get; }
+ }
+
+ [ForyStruct(Target = typeof(Fory.ExternalTypes.ExternalPoint))]
+ internal abstract class PointSerializer
+ {
+ [ForyField(1)]
+ public abstract int X { get; }
+
+ [ForyField(2)]
+ public abstract int Y { get; }
+ }
+
+ [ForyEnum(Target = typeof(Fory.ExternalTypes.ExternalStatus))]
+ internal static class StatusSerializer
+ {
+ }
+
+ [ForyStruct(Target = typeof(Fory.ExternalTypes.ExternalBox<string>))]
+ internal abstract class StringBoxSerializer
+ {
+ [ForyField(1)]
+ public abstract string Value { get; }
+ }
+
+ [ForyStruct(Target = typeof(Fory.ExternalTypes.ExternalDerived))]
+ internal abstract class DerivedSerializer
+ {
+ [ForyField(1)]
+ public abstract int Id { get; }
+
+ [ForyField(2)]
+ public abstract string BaseName { get; }
+ }
+
+ [ForyStruct(Target = typeof(Fory.ExternalTypes.ExternalFields))]
+ internal abstract class FieldsSerializer
+ {
+ [ForyField(1)]
+ public abstract int Count { get; }
+
+ [ForyField(2)]
+ public abstract string Name { get; }
+
+ [ForyField(3)]
+ public abstract int @event { get; }
+ }
+
+ [ForyStruct(Target = typeof(Fory.ExternalTypes.ExternalSchemaModel))]
+ internal abstract class SchemaSerializer
+ {
+ [ForyField(1, Type = typeof(S.Fixed<S.Int32>))]
+ public abstract int FixedValue { get; }
+
+ [ForyField(2, Type = typeof(S.Tagged<S.Int64>))]
+ public abstract long TaggedValue { get; }
+
+ [ForyField(3, Type = typeof(S.Array<S.Int32>))]
+ public abstract int[] ArrayValue { get; }
+
+ [ForyField(4, Type = typeof(S.List<S.Int32>))]
+ public abstract List<int> ListValue { get; }
+
+ [ForyField(5, Type = typeof(S.Set<S.Int32>))]
+ public abstract HashSet<int> SetValue { get; }
+
+ [ForyField(6, Type = typeof(S.Map<S.Fixed<S.UInt32>, S.List<S.Tagged<S.UInt64>>>))]
+ public abstract Dictionary<uint, List<ulong?>?> NestedValue { get; }
+ }
+
+ [ForyStruct(
+ Target = typeof(Fory.ExternalTypes.ExternalEvolutionOff),
+ Evolving = false)]
+ internal abstract class EvolutionOffSerializer
+ {
+ [ForyField(1)]
+ public abstract int Value { get; }
+ }
+
+ [ForyStruct(Target = typeof(Fory.ExternalTypes.ExternalVersionOne))]
+ internal abstract partial class VersionSerializer
+ {
+ [ForyField(1)]
+ public abstract int Id { get; }
+ }
+
+ internal abstract partial class VersionSerializer
+ {
+ [ForyField(2)]
+ public abstract string Name { get; }
+ }
+
+ [ForyStruct]
+ internal sealed class NullablePointHolder
+ {
+ public Fory.ExternalTypes.ExternalPoint? Point { get; set; }
+ }
+
+ [ForyStruct(Evolving = false)]
+ internal sealed class LocalEvolutionOff
+ {
+ public int Value { get; set; }
+ }
+ """;
+
+ string generated = GenerateSource(source);
+ const string userType = "global::Fory.ExternalTypes.ExternalUser";
+
+ Assert.Contains($"Serializer<{userType}>", generated, StringComparison.Ordinal);
+ Assert.Contains($"in {userType} value", generated, StringComparison.Ordinal);
+ Assert.Contains($"public override {userType} ReadData", generated, StringComparison.Ordinal);
+ Assert.Contains($"{userType} value = new {userType}();", generated, StringComparison.Ordinal);
+ Assert.Contains($"GetTypeMeta<{userType}>()", generated, StringComparison.Ordinal);
+ Assert.Contains(
+ generated.Split('\n'),
+ line =>
+ line.Contains(
+ $"RegisterGeneratedStruct<{userType},",
+ StringComparison.Ordinal)
+ && line.TrimEnd().EndsWith(">(true);", StringComparison.Ordinal));
+ Assert.Contains("value.Name", generated, StringComparison.Ordinal);
+ Assert.Contains("value.@event", generated, StringComparison.Ordinal);
+ Assert.Contains(
+ generated.Split('\n'),
+ line =>
+ line.Contains(
+ "RegisterGeneratedStruct<global::Fory.ExternalTypes.ExternalEvolutionOff,",
+ StringComparison.Ordinal)
+ && line.TrimEnd().EndsWith(">(false);", StringComparison.Ordinal));
+ Assert.Contains(
+ generated.Split('\n'),
+ line =>
+ line.Contains(
+ "RegisterGeneratedStruct<global::GeneratedDiagnostics.LocalEvolutionOff,",
+ StringComparison.Ordinal)
+ && line.TrimEnd().EndsWith(">(false);", StringComparison.Ordinal));
+ Assert.Contains(
+ "EnumSerializer<global::Fory.ExternalTypes.ExternalStatus>",
+ generated,
+ StringComparison.Ordinal);
+ }
+
+ public static TheoryData<string, string> ExternalDiagnosticCases => new()
+ {
+ {
+ """
+ using Apache.Fory;
+ namespace GeneratedDiagnostics;
+ public sealed class InvalidTarget { public int Value { get; set; } }
+ [ForyStruct(Target = typeof(InvalidTarget))]
+ internal sealed class InvalidSerializer
+ {
+ public int Value { get; set; }
+ }
+ """,
+ "FORY008"
+ },
+ {
+ """
+ using Apache.Fory;
+ namespace GeneratedDiagnostics;
+ public sealed class InvalidTarget { public int Value { get; set; } }
+ public enum InvalidStatus { Ready }
+ [ForyStruct(Target = typeof(InvalidTarget))]
+ [ForyEnum(Target = typeof(InvalidStatus))]
+ internal abstract class InvalidSerializer
+ {
+ public abstract int Value { get; }
+ }
+ """,
+ "FORY008"
+ },
+ {
+ """
+ using Apache.Fory;
+ namespace GeneratedDiagnostics;
+ public enum InvalidTarget { Ready }
+ [ForyEnum(Target = typeof(InvalidTarget))]
+ internal static class InvalidSerializer
+ {
+ public const int Value = 1;
+ }
+ """,
+ "FORY008"
+ },
+ {
+ """
+ using Apache.Fory;
+ namespace GeneratedDiagnostics;
+ [ForyStruct]
+ internal abstract class InvalidSerializer
+ {
+ public abstract int Value { get; }
+ }
+ """,
+ "FORY009"
+ },
+ {
+ """
+ using Apache.Fory;
+ namespace GeneratedDiagnostics;
+ [ForyStruct(Target = typeof(InvalidSerializer))]
+ internal abstract class InvalidSerializer
+ {
+ public abstract int Value { get; }
+ }
+ """,
+ "FORY009"
+ },
+ {
+ """
+ using Apache.Fory;
+ namespace GeneratedDiagnostics;
+ public sealed class InvalidTarget<T> { public T Value { get; set; } = default!; }
+ [ForyStruct(Target = typeof(InvalidTarget<>))]
+ internal abstract class InvalidSerializer
+ {
+ }
+ """,
+ "FORY009"
+ },
+ {
+ """
+ using Apache.Fory;
+ namespace GeneratedDiagnostics;
+ [ForyStruct(Target = typeof(object))]
+ internal abstract class InvalidSerializer
+ {
+ }
+ """,
+ "FORY009"
+ },
+ {
+ """
+ using Apache.Fory;
+ namespace GeneratedDiagnostics;
+ public enum InvalidTarget { Ready }
+ [ForyStruct(Target = typeof(InvalidTarget))]
+ internal abstract class InvalidSerializer
+ {
+ }
+ """,
+ "FORY009"
+ },
+ {
+ """
+ using Apache.Fory;
+ namespace GeneratedDiagnostics;
+ public static class Owner
+ {
+ private sealed class InvalidTarget { public int Value { get; set; } }
+ }
+ [ForyStruct(Target = typeof(Owner.InvalidTarget))]
+ internal abstract class InvalidSerializer
+ {
+ public abstract int Value { get; }
+ }
+ """,
+ "FORY009"
+ },
+ {
+ """
+ using Apache.Fory;
+ namespace GeneratedDiagnostics;
+ [ForyStruct]
+ public sealed class InvalidTarget { public int Value { get; set; } }
+ [ForyStruct(Target = typeof(InvalidTarget))]
+ internal abstract class InvalidSerializer
+ {
+ public abstract int Value { get; }
+ }
+ """,
+ "FORY009"
+ },
+ {
+ """
+ using Apache.Fory;
+ namespace GeneratedDiagnostics;
+ public sealed class InvalidTarget { public int Value { get; set; } }
+ [ForyStruct(Target = typeof(InvalidTarget))]
+ internal abstract class InvalidSerializer
+ {
+ public abstract int Value { get; }
+ }
+ [ForyStruct(Target = typeof(InvalidTarget))]
+ internal abstract class OtherSerializer
+ {
+ public abstract int Value { get; }
+ }
+ """,
+ "FORY010"
+ },
+ {
+ """
+ using Apache.Fory;
+ namespace GeneratedDiagnostics;
+ public sealed class InvalidTarget
+ {
+ public InvalidTarget(int value) { Value = value; }
+ public int Value { get; set; }
+ }
+ [ForyStruct(Target = typeof(InvalidTarget))]
+ internal abstract class InvalidSerializer
+ {
+ public abstract int Value { get; }
+ }
+ """,
+ "FORY002"
+ },
+ {
+ """
+ using Apache.Fory;
+ namespace GeneratedDiagnostics;
+ public sealed class InvalidTarget
+ {
+ public required int Value { get; set; }
+ }
+ [ForyStruct(Target = typeof(InvalidTarget))]
+ internal abstract class InvalidSerializer
+ {
+ public abstract int Value { get; }
+ }
+ """,
+ "FORY009"
+ },
+ {
+ """
+ using Apache.Fory;
+ namespace GeneratedDiagnostics;
+ public sealed class InvalidTarget
+ {
+ public static int Value { get; set; }
+ }
+ [ForyStruct(Target = typeof(InvalidTarget))]
+ internal abstract class InvalidSerializer
+ {
+ public abstract int Value { get; }
+ }
+ """,
+ "FORY011"
+ },
+ {
+ """
+ using Apache.Fory;
+ namespace GeneratedDiagnostics;
+ public sealed class InvalidTarget
+ {
+ public int Value { get; } = 1;
+ }
+ [ForyStruct(Target = typeof(InvalidTarget))]
+ internal abstract class InvalidSerializer
+ {
+ public abstract int Value { get; }
+ }
+ """,
+ "FORY011"
+ },
+ {
+ """
+ using Apache.Fory;
+ namespace GeneratedDiagnostics;
+ public sealed class InvalidTarget
+ {
+ public int Value { get; init; }
+ }
+ [ForyStruct(Target = typeof(InvalidTarget))]
+ internal abstract class InvalidSerializer
+ {
+ public abstract int Value { get; }
+ }
+ """,
+ "FORY011"
+ },
+ {
+ """
+ using Apache.Fory;
+ namespace GeneratedDiagnostics;
+ public sealed class InvalidTarget
+ {
+ public readonly int Value;
+ }
+ [ForyStruct(Target = typeof(InvalidTarget))]
+ internal abstract class InvalidSerializer
+ {
+ public abstract int Value { get; }
+ }
+ """,
+ "FORY011"
+ },
+ {
+ """
+ using Apache.Fory;
+ namespace GeneratedDiagnostics;
+ public sealed class InvalidTarget { public int Value { get; set; } }
+ [ForyStruct(Target = typeof(InvalidTarget))]
+ internal abstract class InvalidSerializer
+ {
+ public abstract long Value { get; }
+ }
+ """,
+ "FORY012"
+ },
+ {
+ """
+ using Apache.Fory;
+ namespace GeneratedDiagnostics;
+ public sealed class InvalidTarget { public object Value { get; set; } = new(); }
+ [ForyStruct(Target = typeof(InvalidTarget))]
+ internal abstract class InvalidSerializer
+ {
+ public abstract dynamic Value { get; }
+ }
+ """,
+ "FORY012"
+ },
+ {
+ """
+ #nullable enable
+ using System.Collections.Generic;
+ using Apache.Fory;
+ namespace GeneratedDiagnostics;
+ public sealed class InvalidTarget
+ {
+ public List<string?> Values { get; set; } = [];
+ }
+ [ForyStruct(Target = typeof(InvalidTarget))]
+ internal abstract class InvalidSerializer
+ {
+ public abstract List<string> Values { get; }
+ }
+ """,
+ "FORY012"
+ },
+ {
+ """
+ using Apache.Fory;
+ namespace GeneratedDiagnostics;
+ public sealed class InvalidTarget { public int Value { get; set; } }
+ [ForyStruct(Target = typeof(InvalidTarget))]
+ internal abstract class InvalidSerializer
+ {
+ [ForyField(Type = typeof(string))]
+ public abstract int Value { get; }
+ }
+ """,
+ "FORY003"
+ },
+ {
+ """
+ using Apache.Fory;
+ namespace GeneratedDiagnostics;
+ public enum InvalidTarget : long { Invalid = -1 }
+ [ForyEnum(Target = typeof(InvalidTarget))]
+ internal static class InvalidSerializer
+ {
+ }
+ """,
+ "FORY014"
+ },
+ {
+ """
+ using Apache.Fory;
+ namespace GeneratedDiagnostics;
+ public sealed class InvalidTarget { public int Value { get; set; } }
+ public sealed class Outer<T>
+ {
+ [ForyStruct(Target = typeof(InvalidTarget))]
+ internal abstract class InvalidSerializer
+ {
+ public abstract int Value { get; }
+ }
+ }
+ """,
+ "FORY001"
+ },
+ };
+
+ [Theory]
+ [MemberData(nameof(ExternalDiagnosticCases))]
+ public void ExternalDiagnosticsStopEmission(
+ string source,
+ string expectedDiagnostic)
+ {
+ CSharpCompilation compilation = CreateCompilation(source);
+ GeneratorDriver driver = CSharpGeneratorDriver.Create(new ForyModelGenerator());
+ driver = driver.RunGeneratorsAndUpdateCompilation(
+ compilation,
+ out _,
+ out ImmutableArray<Diagnostic> diagnostics);
+
+ IEnumerable<Diagnostic> allDiagnostics =
+ driver.GetRunResult().Diagnostics.Concat(diagnostics);
+ Assert.Contains(allDiagnostics, diagnostic => diagnostic.Id == expectedDiagnostic);
+ string generated = string.Join(
+ "\n",
+ driver.GetRunResult().Results.SelectMany(result => result.GeneratedSources)
+ .Select(sourceResult => sourceResult.SourceText.ToString()));
+ Assert.DoesNotContain(
+ "__ForySerializer_global__GeneratedDiagnostics_InvalidSerializer",
+ generated,
+ StringComparison.Ordinal);
+ }
+
+ [Fact]
+ public void AliasOnlyTargetIsRejected()
+ {
+ const string source = """
+ extern alias thirdparty;
+ using Apache.Fory;
+ namespace GeneratedDiagnostics;
+ [ForyStruct(Target = typeof(thirdparty::Fory.ExternalTypes.ExternalUser))]
+ internal abstract class InvalidSerializer
+ {
+ public abstract int Id { get; }
+ public abstract string Name { get; }
+ public abstract thirdparty::Fory.ExternalTypes.ExternalUser? Friend { get; }
+ public abstract System.Collections.Generic.List<
+ thirdparty::Fory.ExternalTypes.ExternalUser> Links { get; }
+ }
+ """;
+ MetadataReference aliasReference = MetadataReference.CreateFromFile(
+ typeof(global::Fory.ExternalTypes.ExternalUser).Assembly.Location,
+ new MetadataReferenceProperties(
+ aliases: ImmutableArray.Create("thirdparty")));
+ CSharpCompilation compilation = CreateCompilation(
+ source,
+ includeExternalTypes: false,
+ additionalReferences: [aliasReference]);
+ GeneratorDriver driver = CSharpGeneratorDriver.Create(new ForyModelGenerator());
+ driver = driver.RunGeneratorsAndUpdateCompilation(
+ compilation,
+ out _,
+ out ImmutableArray<Diagnostic> diagnostics);
+
+ Assert.Contains(
+ driver.GetRunResult().Diagnostics.Concat(diagnostics),
+ diagnostic => diagnostic.Id == "FORY013");
+ }
+
+ [Fact]
+ public void InternalTargetWithIvtCompiles()
+ {
+ const string targetSource = """
+ using System.Runtime.CompilerServices;
+ [assembly: InternalsVisibleTo("ForyGeneratorDiagnostics")]
+ namespace ThirdParty;
+ internal sealed class InternalTarget
+ {
+ internal int Value { get; set; }
+ }
+ """;
+ MetadataReference targetReference = CreateReference(
+ "ThirdPartyModels",
+ targetSource);
+ const string source = """
+ using Apache.Fory;
+ using ThirdParty;
+ namespace GeneratedDiagnostics;
+ [ForyStruct(Target = typeof(InternalTarget))]
+ internal abstract class InternalTargetSerializer
+ {
+ public abstract int Value { get; }
+ }
+ """;
+
+ CSharpCompilation compilation = CreateCompilation(
+ source,
+ includeExternalTypes: false,
+ additionalReferences: [targetReference]);
+ GeneratorDriver driver = CSharpGeneratorDriver.Create(new ForyModelGenerator());
+ driver.RunGeneratorsAndUpdateCompilation(
+ compilation,
+ out Compilation output,
+ out ImmutableArray<Diagnostic> diagnostics);
+
+ Assert.DoesNotContain(
+ diagnostics.Concat(output.GetDiagnostics()),
+ diagnostic => diagnostic.Severity == DiagnosticSeverity.Error);
+ }
+
+ [Fact]
+ public void ObliviousTargetCompiles()
+ {
+ const string targetSource = """
+ #nullable disable
+ namespace ThirdParty;
+ public sealed class ObliviousTarget
+ {
+ public string Value { get; set; }
+ }
+ """;
+ MetadataReference targetReference = CreateReference(
+ "ObliviousModels",
+ targetSource);
+ const string source = """
+ #nullable enable
+ using Apache.Fory;
+ using ThirdParty;
+ namespace GeneratedDiagnostics;
+ [ForyStruct(Target = typeof(ObliviousTarget))]
+ internal abstract class ObliviousSerializer
+ {
+ public abstract string? Value { get; }
+ }
+ """;
+
+ CSharpCompilation compilation = CreateCompilation(
+ source,
+ includeExternalTypes: false,
+ additionalReferences: [targetReference]);
+ GeneratorDriver driver = CSharpGeneratorDriver.Create(new ForyModelGenerator());
+ driver = driver.RunGeneratorsAndUpdateCompilation(
+ compilation,
+ out Compilation output,
+ out ImmutableArray<Diagnostic> diagnostics);
+
+ Assert.DoesNotContain(
+ diagnostics.Concat(output.GetDiagnostics()),
+ diagnostic => diagnostic.Severity == DiagnosticSeverity.Error);
+ Assert.Contains(
+ driver.GetRunResult().Results.SelectMany(result => result.GeneratedSources)
+ .Select(sourceResult => sourceResult.SourceText.ToString()),
+ generated => generated.Contains("value.Value", StringComparison.Ordinal));
+ }
+
+ [Fact]
+ public void OrdinaryEnumRangeIsValidated()
+ {
+ const string source = """
+ using Apache.Fory;
+ namespace GeneratedDiagnostics;
+ [ForyEnum]
+ public enum InvalidStatus : ulong
+ {
+ TooLarge = 4294967296UL,
+ }
+ """;
+ CSharpCompilation compilation = CreateCompilation(source);
+ GeneratorDriver driver = CSharpGeneratorDriver.Create(new ForyModelGenerator());
+ driver = driver.RunGeneratorsAndUpdateCompilation(
+ compilation,
+ out _,
+ out ImmutableArray<Diagnostic> diagnostics);
+
+ Assert.Contains(
+ driver.GetRunResult().Diagnostics.Concat(diagnostics),
+ diagnostic => diagnostic.Id == "FORY014");
+ }
+
private static string GenerateSource(string source)
{
CSharpCompilation compilation = CreateCompilation(source);
@@ -225,19 +900,55 @@ public sealed class ForyGeneratorTests
.Select(sourceResult => sourceResult.SourceText.ToString()));
}
- private static CSharpCompilation CreateCompilation(string source)
+ private static CSharpCompilation CreateCompilation(
+ string source,
+ bool includeExternalTypes = true,
+ IEnumerable<MetadataReference>? additionalReferences = null)
{
- IEnumerable<MetadataReference> platformReferences =
- ((string)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES")!)
- .Split(Path.PathSeparator)
- .Select(path => MetadataReference.CreateFromFile(path));
MetadataReference foryReference =
MetadataReference.CreateFromFile(typeof(ForyStructAttribute).Assembly.Location);
+ IEnumerable<MetadataReference> references =
+ PlatformReferences().Append(foryReference);
+ if (includeExternalTypes)
+ {
+ references = references.Append(
+ MetadataReference.CreateFromFile(
+ typeof(global::Fory.ExternalTypes.ExternalUser).Assembly.Location));
+ }
+
+ if (additionalReferences is not null)
+ {
+ references = references.Concat(additionalReferences);
+ }
return CSharpCompilation.Create(
"ForyGeneratorDiagnostics",
[CSharpSyntaxTree.ParseText(source, new CSharpParseOptions(LanguageVersion.CSharp12))],
- platformReferences.Append(foryReference),
+ references,
new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
}
+
+ private static MetadataReference CreateReference(
+ string assemblyName,
+ string source)
+ {
+ CSharpCompilation compilation = CSharpCompilation.Create(
+ assemblyName,
+ [CSharpSyntaxTree.ParseText(source, new CSharpParseOptions(LanguageVersion.CSharp12))],
+ PlatformReferences(),
+ new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
+ using MemoryStream stream = new();
+ EmitResult result = compilation.Emit(stream);
+ Assert.True(
+ result.Success,
+ string.Join(Environment.NewLine, result.Diagnostics));
+ return MetadataReference.CreateFromImage(stream.ToArray());
+ }
+
+ private static IEnumerable<MetadataReference> PlatformReferences()
+ {
+ return ((string)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES")!)
+ .Split(Path.PathSeparator)
+ .Select(path => MetadataReference.CreateFromFile(path));
+ }
}
diff --git a/csharp/tests/Fory.Tests/GraphMemoryBudgetTests.cs b/csharp/tests/Fory.Tests/GraphMemoryBudgetTests.cs
index 208735d47..e2bcfd813 100644
--- a/csharp/tests/Fory.Tests/GraphMemoryBudgetTests.cs
+++ b/csharp/tests/Fory.Tests/GraphMemoryBudgetTests.cs
@@ -19,6 +19,7 @@ using System.Buffers;
using System.Collections.Immutable;
using System.Runtime.CompilerServices;
using Apache.Fory;
+using Fory.ExternalTypes;
using ForyRuntime = Apache.Fory.Fory;
using S = Apache.Fory.Schema.Types;
@@ -208,6 +209,51 @@ public sealed class GraphMemoryBudgetTests
Assert.Equal(value.Count, NewFory().Deserialize<List<List<string>>>(Serialize(value)).Count);
}
+ [Fact]
+ public void ExternalStructRootBudget()
+ {
+ ExternalPoint value = new() { X = 1, Y = 2 };
+ ForyRuntime writer = ForyRuntime.Builder().Compatible(false).Build();
+ writer.Register<ExternalPoint>(1013);
+ byte[] bytes = writer.Serialize(value);
+ ForyRuntime reader = ForyRuntime.Builder()
+ .Compatible(false)
+ .MaxGraphMemoryBytes(1)
+ .Build();
+ reader.Register<ExternalPoint>(1013);
+
+ Assert.Equal(value, reader.Deserialize<ExternalPoint>(bytes));
+ }
+
+ [Fact]
+ public void ExternalStructListBudget()
+ {
+ List<ExternalPoint> value =
+ [
+ new ExternalPoint { X = 1, Y = 2 },
+ new ExternalPoint { X = 3, Y = 4 },
+ ];
+ ForyRuntime writer = ForyRuntime.Builder().Compatible(false).Build();
+ writer.Register<ExternalPoint>(1013);
+ byte[] bytes = writer.Serialize(value);
+ long required = ListBudget<ExternalPoint>(value.Count);
+
+ ForyRuntime tooSmall = ForyRuntime.Builder()
+ .Compatible(false)
+ .MaxGraphMemoryBytes(required - 1)
+ .Build();
+ tooSmall.Register<ExternalPoint>(1013);
+ Assert.Throws<InvalidDataException>(
+ () => tooSmall.Deserialize<List<ExternalPoint>>(bytes));
+
+ ForyRuntime exact = ForyRuntime.Builder()
+ .Compatible(false)
+ .MaxGraphMemoryBytes(required)
+ .Build();
+ exact.Register<ExternalPoint>(1013);
+ Assert.Equal(value, exact.Deserialize<List<ExternalPoint>>(bytes));
+ }
+
[Fact]
public void ReadOnlySequenceUsesSameBudget()
{
diff --git a/csharp/tests/Fory.XlangPeer/ExternalTypeSerializers.cs b/csharp/tests/Fory.XlangPeer/ExternalTypeSerializers.cs
new file mode 100644
index 000000000..a5eca3cca
--- /dev/null
+++ b/csharp/tests/Fory.XlangPeer/ExternalTypeSerializers.cs
@@ -0,0 +1,56 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+using Apache.Fory;
+using Fory.ExternalTypes;
+
+namespace Apache.Fory.XlangPeer;
+
+[ForyStruct(Target = typeof(XlangUser))]
+internal abstract class XlangUserSerializer
+{
+ [ForyField(1)]
+ public abstract int Id { get; }
+
+ [ForyField(2)]
+ public abstract string Name { get; }
+}
+
+[ForyStruct(Target = typeof(XlangPoint))]
+internal abstract class XlangPointSerializer
+{
+ [ForyField(1)]
+ public abstract int X { get; }
+
+ [ForyField(2)]
+ public abstract int Y { get; }
+}
+
+[ForyEnum(Target = typeof(XlangStatus))]
+internal static class XlangStatusSerializer
+{
+}
+
+[ForyStruct(Target = typeof(XlangHolder))]
+internal abstract class XlangHolderSerializer
+{
+ [ForyField(1)]
+ public abstract List<XlangUser> Users { get; }
+
+ [ForyField(2)]
+ public abstract Dictionary<string, XlangUser> UsersByName { get; }
+}
diff --git a/csharp/tests/Fory.XlangPeer/Fory.XlangPeer.csproj b/csharp/tests/Fory.XlangPeer/Fory.XlangPeer.csproj
index b5a039459..bbb2865ed 100644
--- a/csharp/tests/Fory.XlangPeer/Fory.XlangPeer.csproj
+++ b/csharp/tests/Fory.XlangPeer/Fory.XlangPeer.csproj
@@ -9,6 +9,7 @@
</PropertyGroup>
<ItemGroup>
+ <ProjectReference Include="..\Fory.ExternalTypes\Fory.ExternalTypes.csproj" />
<ProjectReference Include="..\..\src\Fory\Fory.csproj" />
<ProjectReference Include="..\..\src\Fory.Generator\Fory.Generator.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
</ItemGroup>
diff --git a/csharp/tests/Fory.XlangPeer/Program.cs b/csharp/tests/Fory.XlangPeer/Program.cs
index 859c4eafb..cd993a06b 100644
--- a/csharp/tests/Fory.XlangPeer/Program.cs
+++ b/csharp/tests/Fory.XlangPeer/Program.cs
@@ -19,6 +19,7 @@ using System.Buffers;
using System.Numerics;
using System.Text;
using Apache.Fory;
+using Fory.ExternalTypes;
using ForyRuntime = Apache.Fory.Fory;
using S = Apache.Fory.Schema.Types;
@@ -243,6 +244,8 @@ internal static class Program
"test_unsigned_schema_compatible" => CaseUnsignedSchemaCompatible(input),
"test_nested_annotated_container_schema_consistent" => CaseNestedAnnotatedContainerSchemaConsistent(input),
"test_nested_annotated_container_compatible" => CaseNestedAnnotatedContainerCompatible(input),
+ "test_csharp_external_id" => CaseCSharpExternalId(input),
+ "test_csharp_external_name" => CaseCSharpExternalName(input),
_ => throw new InvalidOperationException($"unknown test case {caseName}"),
};
}
@@ -1085,6 +1088,69 @@ internal static class Program
return RoundTripSingle<NestedAnnotatedContainerCompatible>(input, fory);
}
+ private static byte[] CaseCSharpExternalId(byte[] input)
+ {
+ ForyRuntime fory = BuildFory(compatible: true);
+ RegisterCSharpTypesById(fory);
+ return ExchangeExternalValues(input, fory, nameof(CaseCSharpExternalId));
+ }
+
+ private static byte[] CaseCSharpExternalName(byte[] input)
+ {
+ ForyRuntime fory = BuildFory(compatible: false);
+ RegisterCSharpTypesByName(fory);
+ return ExchangeExternalValues(input, fory, nameof(CaseCSharpExternalName));
+ }
+
+ private static byte[] ExchangeExternalValues(
+ byte[] input,
+ ForyRuntime fory,
+ string caseName)
+ {
+ ReadOnlySequence<byte> sequence = new(input);
+ XlangUser user = fory.Deserialize<XlangUser>(ref sequence);
+ XlangPoint point = fory.Deserialize<XlangPoint>(ref sequence);
+ XlangStatus status = fory.Deserialize<XlangStatus>(ref sequence);
+ XlangHolder holder = fory.Deserialize<XlangHolder>(ref sequence);
+ List<XlangUser> users = fory.Deserialize<List<XlangUser>>(ref sequence);
+ Dictionary<string, XlangUser> usersByName =
+ fory.Deserialize<Dictionary<string, XlangUser>>(ref sequence);
+ EnsureConsumed(sequence, caseName);
+
+ EnsureUser(user, 7, "root", "class root");
+ Ensure(point.X == 3 && point.Y == -4, "struct root mismatch");
+ Ensure(status == XlangStatus.Done, "enum root mismatch");
+
+ Ensure(holder.Users.Count == 2, "holder list size mismatch");
+ EnsureUser(holder.Users[0], 11, "holder-a", "holder list element 0");
+ EnsureUser(holder.Users[1], 12, "holder-b", "holder list element 1");
+ Ensure(holder.UsersByName.Count == 2, "holder map size mismatch");
+ EnsureUser(holder.UsersByName["first"], 13, "map-a", "holder map first");
+ EnsureUser(holder.UsersByName["second"], 14, "map-b", "holder map second");
+
+ Ensure(users.Count == 2, "root list size mismatch");
+ EnsureUser(users[0], 21, "list-a", "root list element 0");
+ EnsureUser(users[1], 22, "list-b", "root list element 1");
+
+ Ensure(usersByName.Count == 2, "root map size mismatch");
+ EnsureUser(usersByName["left"], 31, "root-map-a", "root map left");
+ EnsureUser(usersByName["right"], 32, "root-map-b", "root map right");
+
+ List<byte> output = [];
+ Append(output, fory.Serialize(user));
+ Append(output, fory.Serialize(point));
+ Append(output, fory.Serialize(status));
+ Append(output, fory.Serialize(holder));
+ Append(output, fory.Serialize(users));
+ Append(output, fory.Serialize(usersByName));
+ return output.ToArray();
+ }
+
+ private static void EnsureUser(XlangUser user, int id, string name, string label)
+ {
+ Ensure(user.Id == id && user.Name == name, $"{label} mismatch");
+ }
+
private static byte[] RoundTripSingle<T>(byte[] input, ForyRuntime fory)
{
ReadOnlySequence<byte> sequence = new(input);
@@ -1107,6 +1173,22 @@ internal static class Program
fory.Register<SimpleStruct>("demo.simple_struct");
}
+ private static void RegisterCSharpTypesById(ForyRuntime fory)
+ {
+ fory.Register<XlangUser>(1301);
+ fory.Register<XlangPoint>(1302);
+ fory.Register<XlangStatus>(1303);
+ fory.Register<XlangHolder>(1304);
+ }
+
+ private static void RegisterCSharpTypesByName(ForyRuntime fory)
+ {
+ fory.Register<XlangUser>("csharp.external.User");
+ fory.Register<XlangPoint>("csharp.external.Point");
+ fory.Register<XlangStatus>("csharp.external.Status");
+ fory.Register<XlangHolder>("csharp.external.Holder");
+ }
+
private static ForyRuntime BuildFory(bool compatible, bool trackRef = false, bool checkStructVersion = false)
{
return ForyRuntime.Builder()
diff --git a/docs/guide/csharp/basic-serialization.md b/docs/guide/csharp/basic-serialization.md
index 5c88675bc..a4fc4854c 100644
--- a/docs/guide/csharp/basic-serialization.md
+++ b/docs/guide/csharp/basic-serialization.md
@@ -127,7 +127,8 @@ fory.Serialize<object?>(dynamicWriter, value);
- Reuse the same `Fory` or `ThreadSafeFory` instance for better performance.
- Primitive types and collections do not require user registration.
-- User `[ForyStruct]`, `[ForyEnum]`, `[ForyUnion]`, and custom serializer types should be registered explicitly.
+- Register user types handled by `[ForyStruct]`, `[ForyEnum]`, `[ForyUnion]`,
+ external structural serializers, or manual serializers explicitly.
## Related Topics
diff --git a/docs/guide/csharp/external-types.md b/docs/guide/csharp/external-types.md
new file mode 100644
index 000000000..d9678d5d3
--- /dev/null
+++ b/docs/guide/csharp/external-types.md
@@ -0,0 +1,211 @@
+---
+title: External Types
+sidebar_position: 6
+id: external_types
+license: |
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+---
+
+External-type serialization generates a serializer for a class, struct, or
+enum that cannot carry its own Fory annotation. The target can come from a
+referenced assembly or from generated or otherwise unmodifiable source in the
+consumer project. A local serializer declaration supplies the schema, while
+Fory reads and writes the target value directly.
+
+## Class and Struct Targets
+
+Suppose another package defines this class:
+
+```csharp
+namespace ThirdParty;
+
+public sealed class User
+{
+ public User()
+ {
+ }
+
+ public string Name { get; set; } = string.Empty;
+
+ public int Age { get; set; }
+}
+```
+
+Declare its external structural serializer in your project:
+
+```csharp
+using Apache.Fory;
+using S = Apache.Fory.Schema.Types;
+
+[ForyStruct(Target = typeof(ThirdParty.User))]
+internal abstract class UserSerializer
+{
+ [ForyField(1)]
+ public abstract string Name { get; }
+
+ [ForyField(2, Type = typeof(S.Int32))]
+ public abstract int Age { get; }
+}
+```
+
+The declaration is generator input only. Do not instantiate or register
+`UserSerializer`.
+
+The same form supports an external struct:
+
+```csharp
+[ForyStruct(Target = typeof(ThirdParty.Point))]
+internal abstract class PointSerializer
+{
+ [ForyField(1)]
+ public abstract int X { get; }
+
+ [ForyField(2)]
+ public abstract int Y { get; }
+}
+```
+
+## Enum Targets
+
+Use an empty static serializer declaration for an enum:
+
+```csharp
+[ForyEnum(Target = typeof(ThirdParty.Status))]
+internal static class StatusSerializer
+{
+}
+```
+
+The target enum's numeric values are authoritative. Do not copy its constants
+into the declaration. Every serialized numeric value must fit in the unsigned
+32-bit Fory enum tag range.
+
+## Registration and Root Values
+
+Register the target through the normal APIs:
+
+```csharp
+Fory fory = Fory.Builder().Build();
+fory.Register<ThirdParty.User>(100);
+fory.Register<ThirdParty.Status>("example.Status");
+
+byte[] bytes = fory.Serialize(user);
+ThirdParty.User decoded = fory.Deserialize<ThirdParty.User>(bytes);
+```
+
+The split namespace/name overloads and `ThreadSafeFory` registration work the
+same way. There is no separate external-type registration or root API.
+
+## Fields and Carriers
+
+Use the target type directly in generated models:
+
+```csharp
+[ForyStruct]
+public sealed class Group
+{
+ public ThirdParty.User Owner { get; set; } = new();
+
+ public List<ThirdParty.User> Users { get; set; } = [];
+
+ public Dictionary<string, ThirdParty.User> UsersByName { get; set; } = [];
+}
+```
+
+Root carrier composition also uses the ordinary typed API:
+
+```csharp
+byte[] bytes = fory.Serialize(new List<ThirdParty.User> { user });
+
+List<ThirdParty.User> decoded =
+ fory.Deserialize<List<ThirdParty.User>>(bytes);
+```
+
+External children are supported through the concrete carrier types already
+supported by the C# runtime:
+
+- `Nullable<T>` for external structs and one-dimensional `T[]`;
+- `List<T>`, `LinkedList<T>`, `Queue<T>`, and `Stack<T>`;
+- `HashSet<T>`, `SortedSet<T>`, and `ImmutableHashSet<T>`;
+- `Dictionary<TKey, TValue>`, `SortedDictionary<TKey, TValue>`,
+ `SortedList<TKey, TValue>`, `ConcurrentDictionary<TKey, TValue>`, and
+ `NullableKeyDictionary<TKey, TValue>`.
+
+Targets can appear as map keys or values and inside recursively nested
+carriers. Collection interface types are not supported as generated fields or
+typed roots.
+
+## Declaration and Target Requirements
+
+An external structural serializer declaration must be a non-generic abstract
+class containing only abstract get-only schema properties. Each property:
+
+- matches an accessible target field or property with the same case-sensitive
+ name;
+- has the same CLR type and generic shape;
+- has matching explicit nullability when the target metadata provides it;
+- can be read and assigned directly by generated code;
+- may use the standard `ForyField` ID and schema descriptor options.
+
+When target metadata is nullable-oblivious, the declaration selects schema
+nullability. Only members declared by the serializer are serialized; other
+target state keeps its normal default or derived behavior after
+deserialization.
+
+The target must be an accessible concrete class or struct with a legal
+parameterless construction path and writable state. Closed generic targets,
+such as `ThirdParty.Box<string>`, are supported; open generic targets are not.
+
+Targets that require private access, readonly or init-only assignment,
+constructor arguments, factories, member renaming, or value conversion require
+a [manual serializer](manual-serializers.md).
+
+## Schema Evolution
+
+Set `Evolving` on the serializer declaration:
+
+```csharp
+[ForyStruct(
+ Target = typeof(ThirdParty.User),
+ Evolving = false)]
+internal abstract class UserSerializer
+{
+ public abstract string Name { get; }
+}
+```
+
+Field IDs, field names, schema descriptors, and `Evolving` come from the
+declaration. Compatible and schema-consistent modes otherwise behave exactly as
+they do for an ordinary generated C# type.
+
+## Dynamic Values and References
+
+After registering the target, it can appear in `object`-based dynamic
+roots, fields, collections, and maps. Register every concrete target that can
+appear dynamically.
+
+Mutable external classes retain shared-reference and cycle support when
+reference tracking is enabled. External structs remain inline values.
+
+This feature does not add arbitrary interface or base-class polymorphism.
+
+## Related Topics
+
+- [Schema Metadata](schema-metadata.md)
+- [Type Registration](type-registration.md)
+- [Manual Serializers](manual-serializers.md)
+- [References](references.md)
+- [Schema Evolution](schema-evolution.md)
diff --git a/docs/guide/csharp/index.md b/docs/guide/csharp/index.md
index f2a41a25e..5623e2698 100644
--- a/docs/guide/csharp/index.md
+++ b/docs/guide/csharp/index.md
@@ -26,7 +26,9 @@ Apache Fory™ C# is a high-performance, cross-language serialization library fo
- High performance binary serialization for .NET 8+
- Xlang compatibility with Fory implementations in Java, Python, C++, Go, Rust,
JavaScript/TypeScript, Swift, Dart, Scala, and Kotlin
-- Source-generator-based serializers for `[ForyStruct]` types, plus `[ForyEnum]` and `[ForyUnion]` registration
+- Source-generator-based serializers for `[ForyStruct]` types, plus
+ `[ForyEnum]` and `[ForyUnion]` registration
+- Generated serializers for external class, struct, and enum targets
- Optional reference tracking for shared and circular object graphs
- Compatible mode for schema evolution
- Thread-safe wrapper (`ThreadSafeFory`) for multi-threaded services
@@ -80,7 +82,7 @@ User decoded = fory.Deserialize<User>(payload);
- `Serialize<T>(in T value)` / `Deserialize<T>(...)`
- `Serialize<object?>(...)` / `Deserialize<object?>(...)` for dynamic payloads
- `Register<T>(uint typeId)` and name registration APIs
-- `Register<T, TSerializer>(...)` for custom serializers
+- `Register<T, TSerializer>(...)` for manual serializers
## Documentation
@@ -90,8 +92,9 @@ User decoded = fory.Deserialize<User>(payload);
| [Basic Serialization](basic-serialization.md) | Typed and dynamic serialization APIs |
| [Xlang Serialization](xlang-serialization.md) | Interoperability guidance |
| [Schema Metadata](schema-metadata.md) | `[ForyField]` ids and schema type descriptors |
-| [Type Registration](type-registration.md) | Registering user types and custom serializers |
-| [Custom Serializers](custom-serializers.md) | Implementing `Serializer<T>` |
+| [Type Registration](type-registration.md) | Registering user types and manual serializers |
+| [External Types](external-types.md) | Serializers for third-party types |
+| [Manual Serializers](manual-serializers.md) | Implementing `Serializer<T>` |
| [References](references.md) | Shared/circular reference handling |
| [Schema Evolution](schema-evolution.md) | Compatible mode behavior |
| [Supported Types](supported-types.md) | Built-in and generated type support |
diff --git a/docs/guide/csharp/custom-serializers.md b/docs/guide/csharp/manual-serializers.md
similarity index 84%
rename from docs/guide/csharp/custom-serializers.md
rename to docs/guide/csharp/manual-serializers.md
index 4db844dfe..0fcf56841 100644
--- a/docs/guide/csharp/custom-serializers.md
+++ b/docs/guide/csharp/manual-serializers.md
@@ -1,7 +1,7 @@
---
-title: Custom Serializers
+title: Manual Serializers
sidebar_position: 11
-id: custom_serializers
+id: manual_serializers
license: |
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
@@ -19,7 +19,13 @@ license: |
limitations under the License.
---
-Use custom serializers when a type is not generated with `[ForyStruct]` or requires specialized encoding.
+Use a manual serializer when a type is not generated with `[ForyStruct]` or
+requires specialized encoding.
+
+[External-type serialization](external-types.md) generates serializers for
+accessible mutable third-party targets. Use a manual serializer for immutable,
+constructor-only, factory-only, inaccessible, renamed, converted, or
+custom-wire targets.
## Implement `Serializer<T>`
@@ -80,7 +86,7 @@ fory.Register<Point, PointSerializer>("com.example.Point");
1. Keep serializers deterministic and symmetric.
2. Use varint/fixed/tagged encoding intentionally for integer-heavy payloads.
-3. Register custom serializers on all reader/writer peers.
+3. Register manual serializers on all reader/writer peers.
4. Prefer generated `[ForyStruct]` serializers for normal domain models.
## Related Topics
diff --git a/docs/guide/csharp/references.md b/docs/guide/csharp/references.md
index 6b6b2363c..56c3c68bd 100644
--- a/docs/guide/csharp/references.md
+++ b/docs/guide/csharp/references.md
@@ -34,6 +34,10 @@ When enabled:
- Shared object identity is preserved.
- Circular object graphs can be serialized/deserialized safely.
+Mutable classes handled by
+[external-type serialization](external-types.md) use the same reference
+tracking. External structs remain inline values.
+
## Circular Reference Example
```csharp
@@ -73,4 +77,5 @@ supported; Fory rejects unresolved refs instead of returning a partial union.
- [Configuration](configuration.md)
- [Basic Serialization](basic-serialization.md)
+- [External Types](external-types.md)
- [Thread Safety](thread-safety.md)
diff --git a/docs/guide/csharp/schema-evolution.md b/docs/guide/csharp/schema-evolution.md
index 8143343e1..1dca52955 100644
--- a/docs/guide/csharp/schema-evolution.md
+++ b/docs/guide/csharp/schema-evolution.md
@@ -30,6 +30,11 @@ Fory fory = Fory.Builder()
Compatible mode writes type metadata that allows readers and writers with different struct definitions to interoperate.
+For an [external structural serializer](external-types.md), field names, field
+IDs, schema descriptors, and the `Evolving` setting come from the local
+serializer declaration. Register the third-party target with the same stable
+wire identity on every version.
+
Compatible readers also tolerate selected scalar field type changes when the value is lossless. A
matched field can read between `bool`, `string`, numeric scalars, and `decimal` when the converted
value has the same logical value. Boolean strings must be exactly `"0"`, `"1"`, `"true"`, or
@@ -95,5 +100,6 @@ Because C# uses the xlang wire format only, use `Compatible(false)` only after v
## Related Topics
- [Configuration](configuration.md)
+- [External Types](external-types.md)
- [Type Registration](type-registration.md)
- [Troubleshooting](troubleshooting.md)
diff --git a/docs/guide/csharp/schema-metadata.md b/docs/guide/csharp/schema-metadata.md
index 7c4194d0d..2a7455540 100644
--- a/docs/guide/csharp/schema-metadata.md
+++ b/docs/guide/csharp/schema-metadata.md
@@ -25,6 +25,20 @@ This page covers schema metadata for C# generated serializers.
Use `[ForyStruct]` to enable source-generated serializers. Use `[ForyField]` to assign an optional stable non-negative field id or to override the Fory schema type used for a field.
+External-type serialization puts `Target` on a local abstract serializer
+declaration. Its properties own the field names, IDs, schema descriptors,
+nullability, and `Evolving` setting. The target supplies the runtime values and
+directly accessed members.
+
+```csharp
+[ForyStruct(Target = typeof(ThirdParty.User))]
+internal abstract class UserSerializer
+{
+ [ForyField(1)]
+ public abstract string Name { get; }
+}
+```
+
```csharp
using Apache.Fory;
using S = Apache.Fory.Schema.Types;
@@ -119,5 +133,6 @@ public abstract partial record Shape
## Related Topics
- [Configuration](configuration.md)
+- [External Types](external-types.md)
- [Schema Evolution](schema-evolution.md)
- [Supported Types](supported-types.md)
diff --git a/docs/guide/csharp/supported-types.md b/docs/guide/csharp/supported-types.md
index 3148694ad..db6236377 100644
--- a/docs/guide/csharp/supported-types.md
+++ b/docs/guide/csharp/supported-types.md
@@ -76,8 +76,10 @@ This page summarizes built-in and generated type support in Apache Fory™ C#.
## User Types
-- `[ForyStruct]` classes/structs via source-generated serializers, plus `[ForyEnum]` enums and `[ForyUnion]` ADT records
-- Custom serializer types registered through `Register<T, TSerializer>(...)`
+- `[ForyStruct]` classes/structs via source-generated serializers
+- `[ForyEnum]` enums and `[ForyUnion]` ADT records
+- External class, struct, and enum targets through serializer declarations
+- Manual serializer types registered through `Register<T, TSerializer>(...)`
- `Union` / `Union2<...>` typed union support
## Dynamic Types
@@ -96,5 +98,6 @@ Dynamic object payloads via `Serialize<object?>` / `Deserialize<object?>` suppor
## Related Topics
- [Basic Serialization](basic-serialization.md)
+- [External Types](external-types.md)
- [Type Registration](type-registration.md)
- [Xlang Serialization](xlang-serialization.md)
diff --git a/docs/guide/csharp/type-registration.md b/docs/guide/csharp/type-registration.md
index bd9f54edc..ccba89646 100644
--- a/docs/guide/csharp/type-registration.md
+++ b/docs/guide/csharp/type-registration.md
@@ -54,14 +54,14 @@ separately:
fory.Register<User>("com.example", "User");
```
-## Register a Custom Serializer
+## Register a Manual Serializer
```csharp
Fory fory = Fory.Builder().Build();
fory.Register<MyType, MyTypeSerializer>(200);
```
-Name-based custom serializer registration is also supported:
+Name-based manual serializer registration is also supported:
```csharp
fory.Register<MyType, MyTypeSerializer>("com.example.MyType");
@@ -81,11 +81,14 @@ fory.Register<Order>(101);
- Register user-defined types on both writer and reader sides.
- Keep ID/name mappings consistent across services and languages.
+- For external-type serialization, register the third-party target, such as
+ `fory.Register<ThirdParty.User>(100)`, not the local serializer declaration.
- For the split overloads, `typeName` must be non-empty and must not contain dots.
- Register before high-volume serialization workloads to avoid missing type metadata.
## Related Topics
- [Basic Serialization](basic-serialization.md)
-- [Custom Serializers](custom-serializers.md)
+- [External Types](external-types.md)
+- [Manual Serializers](manual-serializers.md)
- [Xlang Serialization](xlang-serialization.md)
diff --git a/docs/guide/csharp/xlang-serialization.md b/docs/guide/csharp/xlang-serialization.md
index bf3c76c1b..2bba64332 100644
--- a/docs/guide/csharp/xlang-serialization.md
+++ b/docs/guide/csharp/xlang-serialization.md
@@ -50,6 +50,11 @@ fory.Register<Person>(100);
Use the same ID mapping on all languages.
+Third-party classes, structs, and enums can use
+[external-type serialization](external-types.md). Register the target type,
+not its local serializer declaration, with the same ID or name used by the
+other language peers.
+
## Register by Name
```csharp
@@ -125,5 +130,6 @@ C# `List<T>` maps to Fory `list<T>`. Use the schema marker
## Related Topics
- [Type Registration](type-registration.md)
+- [External Types](external-types.md)
- [Schema Evolution](schema-evolution.md)
- [Supported Types](supported-types.md)
diff --git a/docs/specification/xlang_implementation_guide.md b/docs/specification/xlang_implementation_guide.md
index 1f7be2a82..7a7163734 100644
--- a/docs/specification/xlang_implementation_guide.md
+++ b/docs/specification/xlang_implementation_guide.md
@@ -219,6 +219,96 @@ The ownership split is:
- `Fory` owns root framing and operation setup/reset
- `TypeResolver` owns registration and dynamic lookup
+#### C# target-keyed external serializers
+
+C# external-type serialization uses the target-keyed serializer resolver.
+
+`ForyStructAttribute` and `ForyEnumAttribute` carry an optional `Target` type.
+A local non-generic abstract class supplies an external struct schema, while an
+empty non-generic static class selects an external enum target:
+
+```csharp
+[ForyStruct(Target = typeof(ThirdParty.User))]
+internal abstract class UserSerializer
+{
+ [ForyField(1)]
+ public abstract string Name { get; }
+}
+
+[ForyEnum(Target = typeof(ThirdParty.Status))]
+internal static class StatusSerializer
+{
+}
+```
+
+These declarations are compile-time generator input only. They are never
+instantiated, reflected over by the runtime, registered, reference-published,
+or used as wire identities. The generator emits the canonical
+`Serializer<ThirdParty.User>` structural form and registers its generated
+factory under `ThirdParty.User`. External enums reuse
+`EnumSerializer<ThirdParty.Status>`. Application registration uses the target
+APIs:
+
+```csharp
+fory.Register<ThirdParty.User>(100);
+fory.Register<ThirdParty.Status>("example.Status");
+```
+
+The C# generator model must separate declaration identity from target identity,
+then reuse one structural serializer emitter for both ordinary and external
+targets. Runtime type positions, construction, member access, `TypeInfo`,
+compatible metadata, graph-memory ownership, reference publication, generated
+factory keys, root lookup, and dynamic lookup use the target. The declaration
+supplies only field names, IDs, schema descriptors, nullability, and the
+structural `Evolving` setting.
+
+Every generated ordinary or external struct uses
+`TypeResolver.RegisterGeneratedStruct<T, TSerializer>(bool evolving)` to carry
+generator-owned `Evolving` into the target `TypeInfo`. Generated enums and
+unions use `TypeResolver.RegisterGenerated<T, TSerializer>()`. `TypeInfo` does
+not recover structural metadata by reflecting a target attribute. The runtime
+must not reflect the external declaration, add a serializer capability
+interface, or create a second metadata registry. Multiple generated
+declarations for one target are rejected during generation when visible in one
+compilation and fail deterministically on the cold generated-factory
+registration path across assemblies. Explicit manual serializer registration
+uses the resolver's target replacement rules.
+
+External structural targets require an accessible concrete class or struct,
+legal parameterless construction, and directly readable and assignable
+members. Schema properties match target fields or properties by case-sensitive
+name and exact CLR/generic type. Explicit nullability must match; when target
+metadata is nullable-oblivious, the declaration supplies schema nullability.
+Immutable, constructor-only, factory-only, init-only, readonly, renamed,
+converted, or inaccessible shapes use a manual `Serializer<T>`. Generated
+class reads allocate and publish the final target before recursive children;
+target structs are inline values. The declaration is never a temporary graph
+owner.
+
+C# carrier composition is target-based. The resolver recursively
+binds `Nullable<T>`, one-dimensional `T[]`, `List<T>`, `LinkedList<T>`,
+`Queue<T>`, `Stack<T>`, `HashSet<T>`, `SortedSet<T>`,
+`ImmutableHashSet<T>`, `Dictionary<TKey, TValue>`,
+`SortedDictionary<TKey, TValue>`, `SortedList<TKey, TValue>`,
+`ConcurrentDictionary<TKey, TValue>`, and
+`NullableKeyDictionary<TKey, TValue>`. Ordinary generated targets, external
+structural serializers, manual serializers, fields, and roots use the same
+carrier bodies. External-type serialization has no carrier-provider family,
+field selector, root selector, callback, schema tree, per-element external
+dispatch, or additional allocation. Collection-interface, tuple, fixed-array,
+multidimensional-array, memory, and reference-wrapper families are unsupported.
+
+Dynamic `object` values and unions resolve concrete target types through
+`TypeResolver`. Arbitrary statically typed interface or base-class polymorphism
+is unsupported.
+
+External and equivalent ordinary generated hot bodies must be
+instruction-shape equivalent apart from target/member metadata tokens. Target
+selection is compile-time only. Cold duplicate-target error construction must
+stay out of successful hot-path inlining, and any dedicated cold error entrance
+must be marked no-inline. Successful serializer dispatch must not be marked
+cold.
+
Rust names these serializer operation boundaries explicitly:
- `Serializer::write` and `Serializer::read` process a complete value,
diff --git a/docs/specification/xlang_type_mapping.md b/docs/specification/xlang_type_mapping.md
index a3e877710..800360f21 100644
--- a/docs/specification/xlang_type_mapping.md
+++ b/docs/specification/xlang_type_mapping.md
@@ -112,6 +112,12 @@ FDL spells them as an encoding modifier plus a semantic integer type.
Notes:
+- C# external-type serialization maps a third-party class/struct or enum
+ through a local
+ `ForyStruct(Target = typeof(...))` or
+ `ForyEnum(Target = typeof(...))` serializer declaration. The runtime target
+ still uses the C# mapping shown above; declaration ownership is not a wire
+ distinction.
- Python `pyfory.Float16` and `pyfory.BFloat16` are reserved annotation markers; scalar values deserialize as native Python `float`.
- Python `BoolArray`, `Int8Array`, `Int16Array`, `Int32Array`, `Int64Array`, `UInt8Array`, `UInt16Array`, `UInt32Array`, `UInt64Array`, `Float16Array`, `BFloat16Array`, `Float32Array`, and `Float64Array` are public dense-array wrappers with list-like sequence behavior.
- JavaScript `BoolArray`, fallback `Float16Array`, and `BFloat16Array` are public dense-array wrappers backed by `Uint8Array` or `Uint16Array`. Scalar `float16` and `bfloat16` values use `number`. A JavaScript environment with native `Float16Array` may return that native carrier for `array<float16>`.
diff --git a/java/fory-core/src/test/java/org/apache/fory/xlang/CSharpXlangTest.java b/java/fory-core/src/test/java/org/apache/fory/xlang/CSharpXlangTest.java
index c584eaab7..95a94d061 100644
--- a/java/fory-core/src/test/java/org/apache/fory/xlang/CSharpXlangTest.java
+++ b/java/fory-core/src/test/java/org/apache/fory/xlang/CSharpXlangTest.java
@@ -25,10 +25,18 @@ import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
+import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
+import lombok.Data;
+import org.apache.fory.Fory;
+import org.apache.fory.annotation.ForyField;
+import org.apache.fory.annotation.ForyStruct;
+import org.apache.fory.memory.MemoryBuffer;
+import org.apache.fory.memory.MemoryUtils;
import org.apache.fory.test.TestUtils;
+import org.testng.Assert;
import org.testng.SkipException;
import org.testng.annotations.Test;
@@ -385,4 +393,120 @@ public class CSharpXlangTest extends XlangTestBase {
public void testListArrayCompatibleRead(boolean enableCodegen) throws java.io.IOException {
super.testListArrayCompatibleRead(enableCodegen);
}
+
+ @Test(groups = "xlang", dataProvider = "enableCodegenParallel")
+ public void testCSharpExternalId(boolean enableCodegen) throws IOException {
+ Fory fory =
+ Fory.builder().withXlang(true).withCompatible(true).withCodegen(enableCodegen).build();
+ registerExternalById(fory);
+ assertExternalRoundTrip(fory, "test_csharp_external_id");
+ }
+
+ @Test(groups = "xlang", dataProvider = "enableCodegenParallel")
+ public void testCSharpExternalName(boolean enableCodegen) throws IOException {
+ Fory fory =
+ Fory.builder().withXlang(true).withCompatible(false).withCodegen(enableCodegen).build();
+ registerExternalByName(fory);
+ assertExternalRoundTrip(fory, "test_csharp_external_name");
+ }
+
+ @SuppressWarnings("unchecked")
+ private void assertExternalRoundTrip(Fory fory, String caseName) throws IOException {
+ CSharpExternalUser user = newExternalUser(7, "root");
+
+ CSharpExternalPoint point = new CSharpExternalPoint();
+ point.x = 3;
+ point.y = -4;
+
+ CSharpExternalStatus status = CSharpExternalStatus.DONE;
+
+ CSharpExternalHolder holder = new CSharpExternalHolder();
+ holder.users = Arrays.asList(newExternalUser(11, "holder-a"), newExternalUser(12, "holder-b"));
+ holder.usersByName = new LinkedHashMap<>();
+ holder.usersByName.put("first", newExternalUser(13, "map-a"));
+ holder.usersByName.put("second", newExternalUser(14, "map-b"));
+
+ List<CSharpExternalUser> users =
+ Arrays.asList(newExternalUser(21, "list-a"), newExternalUser(22, "list-b"));
+ Map<String, CSharpExternalUser> usersByName = new LinkedHashMap<>();
+ usersByName.put("left", newExternalUser(31, "root-map-a"));
+ usersByName.put("right", newExternalUser(32, "root-map-b"));
+
+ MemoryBuffer buffer = MemoryUtils.buffer(256);
+ fory.serialize(buffer, user);
+ fory.serialize(buffer, point);
+ fory.serialize(buffer, status);
+ fory.serialize(buffer, holder);
+ fory.serialize(buffer, users);
+ fory.serialize(buffer, usersByName);
+
+ ExecutionContext ctx = prepareExecution(caseName, buffer.getBytes(0, buffer.writerIndex()));
+ runPeer(ctx);
+
+ MemoryBuffer result = readBuffer(ctx.dataFile());
+ Assert.assertEquals((CSharpExternalUser) fory.deserialize(result), user);
+ Assert.assertEquals((CSharpExternalPoint) fory.deserialize(result), point);
+ Assert.assertEquals((CSharpExternalStatus) fory.deserialize(result), status);
+ Assert.assertEquals((CSharpExternalHolder) fory.deserialize(result), holder);
+ Assert.assertEquals((List<CSharpExternalUser>) fory.deserialize(result), users);
+ Assert.assertEquals((Map<String, CSharpExternalUser>) fory.deserialize(result), usersByName);
+ Assert.assertEquals(result.remaining(), 0);
+ }
+
+ private static CSharpExternalUser newExternalUser(int id, String name) {
+ CSharpExternalUser user = new CSharpExternalUser();
+ user.id = id;
+ user.name = name;
+ return user;
+ }
+
+ private static void registerExternalById(Fory fory) {
+ fory.register(CSharpExternalUser.class, 1301);
+ fory.register(CSharpExternalPoint.class, 1302);
+ fory.register(CSharpExternalStatus.class, 1303);
+ fory.register(CSharpExternalHolder.class, 1304);
+ }
+
+ private static void registerExternalByName(Fory fory) {
+ fory.register(CSharpExternalUser.class, "csharp.external.User");
+ fory.register(CSharpExternalPoint.class, "csharp.external.Point");
+ fory.register(CSharpExternalStatus.class, "csharp.external.Status");
+ fory.register(CSharpExternalHolder.class, "csharp.external.Holder");
+ }
+
+ @Data
+ @ForyStruct
+ static class CSharpExternalUser {
+ @ForyField(id = 1)
+ int id;
+
+ @ForyField(id = 2)
+ String name;
+ }
+
+ @Data
+ @ForyStruct
+ static class CSharpExternalPoint {
+ @ForyField(id = 1)
+ int x;
+
+ @ForyField(id = 2)
+ int y;
+ }
+
+ enum CSharpExternalStatus {
+ UNKNOWN,
+ READY,
+ DONE,
+ }
+
+ @Data
+ @ForyStruct
+ static class CSharpExternalHolder {
+ @ForyField(id = 1)
+ List<CSharpExternalUser> users;
+
+ @ForyField(id = 2)
+ Map<String, CSharpExternalUser> usersByName;
+ }
}
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@fory.apache.org
For additional commands, e-mail: commits-help@fory.apache.org