using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Text;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
namespace AyCode.Core.Serializers.SourceGenerator;
///
/// Generates IGeneratedBinaryWriter implementations for [AcBinarySerializable] types.
/// Also generates a ModuleInitializer that auto-registers all writers at startup.
///
[Generator]
public class AcBinarySourceGenerator : IIncrementalGenerator
{
private const string AttributeName = "AyCode.Core.Serializers.Attributes.AcBinarySerializableAttribute";
// ────────────────────────────────────────────────────────────────────────────────────────────
// TEMPORARY (2026-05-08) — A/B test feature gates for hot-path overhead measurement.
//
// The generated SGen `WriteProperties` / `ScanObject` methods emit two kinds of overhead-blocks
// that are unconditionally present today but rarely exercised in typical workloads:
//
// 1. PropertyFilter guard (`UsePropertyFilter`) — every non-markerless property emit-site
// checks `context.HasPropertyFilter` + filter-context allocation + lambda-call.
// The benchmark workload never sets a property-filter → branch is always false →
// pure overhead (CPU cycles + i-cache pressure on the hot path).
//
// 2. Polymorphic object-with-type-name emit (`UsePolymorphType`) — `System.Object` declared
// properties emit `ObjectWithTypeName` marker + `WriteStringUtf8(AssemblyQualifiedName)`
// under `!context.UseMetadata`. Same: rarely used in typical DTO graphs.
//
// Setting either to `false` skips the corresponding emit at compile time → leaner generated
// code. The bench measures the actual delta vs MemPack apples-to-apples (which has neither
// of these features).
//
// Long-term: these flags will move to `[AcBinarySerializable(UsePropertyFilter = false, ...)]`
// attribute properties so consumers can opt out per type. Until then, keep both `false` for
// benchmark-vs-MemPack measurements; flip to `true` for production where the features are needed.
// ────────────────────────────────────────────────────────────────────────────────────────────
// UsePropertyFilter const removed — replaced by `[AcBinarySerializable(EnablePropertyFilterFeature = ...)]`
// attribute flag, propagated through SerializableClassInfo.EnablePropertyFilter to EmitProp/EmitScanProp.
private const bool UsePolymorphType = false;
private static readonly DiagnosticDescriptor CircularReferenceWarning = new(
id: "ACBIN001",
title: "Circular reference detected",
messageFormat: "Type '{0}' participates in a circular reference chain: {1}. Consider using ReferenceHandling.OnlyId or .All to avoid exponential serialization size.",
category: "AcBinarySerializer",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public void Initialize(IncrementalGeneratorInitializationContext context)
{
var classDeclarations = context.SyntaxProvider
.ForAttributeWithMetadataName(
AttributeName,
predicate: static (node, _) => node is ClassDeclarationSyntax || node is StructDeclarationSyntax,
transform: static (ctx, _) => GetClassInfo(ctx))
.Where(static info => info != null);
context.RegisterSourceOutput(classDeclarations.Collect(),
static (spc, classes) => Execute(classes!, spc));
}
private static SerializableClassInfo? GetClassInfo(GeneratorAttributeSyntaxContext context)
{
if (!(context.TargetSymbol is INamedTypeSymbol typeSymbol))
return null;
var namespaceName = typeSymbol.ContainingNamespace.IsGlobalNamespace
? string.Empty
: typeSymbol.ContainingNamespace.ToDisplayString();
var properties = new List();
// Read feature flags from [AcBinarySerializable] — disabled features eliminate
// corresponding code blocks from generated ScanObject/WriteProperties.
var enableIdTracking = true;
var enableRefHandling = true;
var enableInternString = true;
var enableMetadata = true;
var enablePropertyFilter = true;
var binarySerializableAttr = typeSymbol.GetAttributes().FirstOrDefault(a =>
a.AttributeClass?.ToDisplayString() == AttributeName);
if (binarySerializableAttr != null)
{
if (binarySerializableAttr.ConstructorArguments.Length == 1)
{
// Single bool ctor: AcBinarySerializable(enableAllFeatures)
var all = (bool)binarySerializableAttr.ConstructorArguments[0].Value!;
enableIdTracking = all;
enableRefHandling = all;
enableInternString = all;
enableMetadata = all;
enablePropertyFilter = all;
}
else if (binarySerializableAttr.ConstructorArguments.Length == 4)
{
// Four bool ctor: (metadata, idTracking, refHandling, internString) — filter defaults to true
enableMetadata = (bool)binarySerializableAttr.ConstructorArguments[0].Value!;
enableIdTracking = (bool)binarySerializableAttr.ConstructorArguments[1].Value!;
enableRefHandling = (bool)binarySerializableAttr.ConstructorArguments[2].Value!;
enableInternString = (bool)binarySerializableAttr.ConstructorArguments[3].Value!;
}
else if (binarySerializableAttr.ConstructorArguments.Length == 5)
{
// Five bool ctor: (metadata, idTracking, refHandling, internString, propertyFilter)
enableMetadata = (bool)binarySerializableAttr.ConstructorArguments[0].Value!;
enableIdTracking = (bool)binarySerializableAttr.ConstructorArguments[1].Value!;
enableRefHandling = (bool)binarySerializableAttr.ConstructorArguments[2].Value!;
enableInternString = (bool)binarySerializableAttr.ConstructorArguments[3].Value!;
enablePropertyFilter = (bool)binarySerializableAttr.ConstructorArguments[4].Value!;
}
}
foreach (var p in GetAllSerializablePropertySymbols(typeSymbol))
{
// String interning attribútum detektálás (null = no attr, true/false = explicit)
bool? stringInternAttr = null;
if (!enableInternString)
{
stringInternAttr = false;
}
else if (GetKind(p.Type) == PropertyTypeKind.String)
{
var attr = p.GetAttributes().FirstOrDefault(a => a.AttributeClass?.ToDisplayString() == "AyCode.Core.Serializers.Binaries.AcStringInternAttribute");
if (attr != null && attr.ConstructorArguments.Length == 1 && attr.ConstructorArguments[0].Kind == TypedConstantKind.Primitive)
{
stringInternAttr = (bool)attr.ConstructorArguments[0].Value!;
}
}
// For typeof(): strip trailing '?' from nullable reference types (typeof(T?) is invalid for ref types)
// Nullable value types (int?, Guid?) keep '?' because typeof(int?) == typeof(Nullable) is valid
var typeDisplayName = p.Type.ToDisplayString();
var typeNameForTypeof = (p.Type.NullableAnnotation == NullableAnnotation.Annotated && !p.Type.IsValueType)
? typeDisplayName.TrimEnd('?')
: typeDisplayName;
// Direct object write detection for Complex property types:
// Check if the property type has [AcBinarySerializable] (→ has generated writer)
// and if it implements IId (→ needs ref tracking in generated code)
var kind = GetKind(p.Type);
bool hasGenWriter = false;
bool propTypeIsIId = false;
bool propEnableMetadata = true;
bool childNeedsIdScan = true;
bool childNeedsAllRefScan = true;
bool childNeedsInternScan = true;
string? writerClassName = null;
string? propIdTypeName = null;
int childTypeNameHash = 0;
int[]? childPropertyHashes = null;
if (kind == PropertyTypeKind.Complex)
{
// Resolve to the actual type symbol (strip nullable annotation for ref types)
// For SharedTag? → SharedTag. OriginalDefinition handles generic types.
var resolvedType = p.Type is INamedTypeSymbol namedPropType
? namedPropType.OriginalDefinition
: p.Type;
hasGenWriter = resolvedType.Locations.Any(l => l.IsInSource)
&& resolvedType.GetAttributes().Any(a =>
a.AttributeClass?.ToDisplayString() == AttributeName);
if (hasGenWriter)
{
// Read child type's EnableMetadataFeature
propEnableMetadata = ReadEnableMetadata(resolvedType);
var childScanFlags = ComputeNeedsScan(resolvedType);
childNeedsIdScan = childScanFlags.needsIdScan;
childNeedsAllRefScan = childScanFlags.needsAllRefScan;
childNeedsInternScan = childScanFlags.needsInternScan;
var iidIface = resolvedType.AllInterfaces.FirstOrDefault(i =>
i.IsGenericType &&
i.OriginalDefinition.ToDisplayString() == "AyCode.Core.Interfaces.IId");
propTypeIsIId = iidIface != null;
if (iidIface != null)
propIdTypeName = iidIface.TypeArguments[0].ToDisplayString();
// Writer class: {Namespace}.{FlatName}_GeneratedWriter
var flatName = BuildFlatName((INamedTypeSymbol)resolvedType);
var ns = resolvedType.ContainingNamespace.IsGlobalNamespace
? string.Empty
: resolvedType.ContainingNamespace.ToDisplayString();
writerClassName = string.IsNullOrEmpty(ns)
? $"{flatName}_GeneratedWriter"
: $"{ns}.{flatName}_GeneratedWriter";
// UseMetadata: compute child type hash-es for inline metadata
childTypeNameHash = ComputeFnvHash(resolvedType.Name);
childPropertyHashes = ComputeChildPropertyHashes(resolvedType);
}
}
// Collection element type analysis for inline collection write
PropertyTypeKind elemKind = PropertyTypeKind.Unknown;
bool elemHasGenWriter = false;
bool elemIsIId = false;
bool elemEnableMetadata = true;
bool elemNeedsIdScan = true;
bool elemNeedsAllRefScan = true;
bool elemNeedsInternScan = true;
string? elemWriterClassName = null;
string? elemIdTypeName = null;
string? collKind = null;
string? collAddMethod = null;
bool collHasCapacityCtor = false;
string? elemFullTypeName = null;
int elementTypeNameHash = 0;
int[]? elementPropertyHashes = null;
if (kind == PropertyTypeKind.Collection)
{
var elemType = GetCollectionElementType(p.Type);
if (elemType != null)
{
elemKind = GetKind(elemType);
elemFullTypeName = elemType.ToDisplayString();
// Detect collection shape for inline write
if (p.Type is IArrayTypeSymbol)
collKind = "Array";
else if (p.Type is INamedTypeSymbol collNamedType)
{
var origDef = collNamedType.OriginalDefinition.ToDisplayString();
collKind = origDef switch
{
"System.Collections.Generic.List" => "List",
"System.Collections.Generic.IList" => "IndexedCollection",
"System.Collections.Generic.IReadOnlyList" => "IndexedCollection",
"System.Collections.Generic.HashSet" => "Counted", // has Count, no indexer
"System.Collections.Generic.Queue" => "Counted",
"System.Collections.Generic.ICollection" => "Counted",
"System.Collections.Generic.IReadOnlyCollection" => "Counted",
"System.Collections.Generic.SortedSet" => "Counted",
"System.Collections.Generic.LinkedList" => "Counted",
_ => null
};
// Determine add method + capacity ctor for Counted concrete types
if (collKind == "Counted")
{
collAddMethod = origDef switch
{
"System.Collections.Generic.HashSet" => "Add",
"System.Collections.Generic.SortedSet" => "Add",
"System.Collections.Generic.Queue" => "Enqueue",
"System.Collections.Generic.LinkedList" => "AddLast",
_ => null // ICollection, IReadOnlyCollection → backed by List
};
collHasCapacityCtor = origDef is
"System.Collections.Generic.HashSet" or
"System.Collections.Generic.Queue";
}
}
// For Complex element types, check for generated writer
if (elemKind == PropertyTypeKind.Complex)
{
var resolvedElem = elemType is INamedTypeSymbol namedElem
? namedElem.OriginalDefinition : elemType;
elemHasGenWriter = resolvedElem.Locations.Any(l => l.IsInSource)
&& resolvedElem.GetAttributes().Any(a =>
a.AttributeClass?.ToDisplayString() == AttributeName);
if (elemHasGenWriter)
{
// Read element type's EnableMetadataFeature
elemEnableMetadata = ReadEnableMetadata(resolvedElem);
var elemScanFlags = ComputeNeedsScan(resolvedElem);
elemNeedsIdScan = elemScanFlags.needsIdScan;
elemNeedsAllRefScan = elemScanFlags.needsAllRefScan;
elemNeedsInternScan = elemScanFlags.needsInternScan;
var elemIidIface = resolvedElem.AllInterfaces.FirstOrDefault(ifc =>
ifc.IsGenericType &&
ifc.OriginalDefinition.ToDisplayString() == "AyCode.Core.Interfaces.IId");
elemIsIId = elemIidIface != null;
if (elemIidIface != null)
elemIdTypeName = elemIidIface.TypeArguments[0].ToDisplayString();
var elemFlatName = BuildFlatName((INamedTypeSymbol)resolvedElem);
var ens = resolvedElem.ContainingNamespace.IsGlobalNamespace
? string.Empty : resolvedElem.ContainingNamespace.ToDisplayString();
elemWriterClassName = string.IsNullOrEmpty(ens)
? $"{elemFlatName}_GeneratedWriter"
: $"{ens}.{elemFlatName}_GeneratedWriter";
// UseMetadata: compute element type hash-es for inline metadata
elementTypeNameHash = ComputeFnvHash(resolvedElem.Name);
elementPropertyHashes = ComputeChildPropertyHashes(resolvedElem);
}
}
}
}
// Dictionary key/value type analysis for inline dictionary read
PropertyTypeKind dictKeyKind = PropertyTypeKind.Unknown;
PropertyTypeKind dictValueKind = PropertyTypeKind.Unknown;
string? dictKeyTypeName = null;
string? dictValueTypeName = null;
bool dictValueHasGenWriter = false;
string? dictValueWriterClassName = null;
bool dictValueIsIId = false;
bool dictValueEnableMetadata = true;
bool dictValueNeedsIdScan = true;
bool dictValueNeedsAllRefScan = true;
bool dictValueNeedsInternScan = true;
int dictValueTypeNameHash = 0;
int[]? dictValuePropertyHashes = null;
if (kind == PropertyTypeKind.Dictionary)
{
var (keyType, valueType) = GetDictionaryKeyValueTypes(p.Type);
if (keyType != null)
{
dictKeyKind = GetKind(keyType);
dictKeyTypeName = keyType.ToDisplayString();
}
if (valueType != null)
{
dictValueKind = GetKind(valueType);
dictValueTypeName = valueType.ToDisplayString();
if (dictValueKind == PropertyTypeKind.Complex)
{
var resolvedValue = valueType is INamedTypeSymbol nvt ? nvt.OriginalDefinition : valueType;
dictValueHasGenWriter = resolvedValue.Locations.Any(l => l.IsInSource)
&& resolvedValue.GetAttributes().Any(a =>
a.AttributeClass?.ToDisplayString() == AttributeName);
if (dictValueHasGenWriter)
{
var vfn = BuildFlatName((INamedTypeSymbol)resolvedValue);
var vns = resolvedValue.ContainingNamespace.IsGlobalNamespace
? string.Empty : resolvedValue.ContainingNamespace.ToDisplayString();
dictValueWriterClassName = string.IsNullOrEmpty(vns)
? $"{vfn}_GeneratedWriter"
: $"{vns}.{vfn}_GeneratedWriter";
dictValueEnableMetadata = ReadEnableMetadata(resolvedValue);
var dvScanFlags = ComputeNeedsScan(resolvedValue);
dictValueNeedsIdScan = dvScanFlags.needsIdScan;
dictValueNeedsAllRefScan = dvScanFlags.needsAllRefScan;
dictValueNeedsInternScan = dvScanFlags.needsInternScan;
var dvIidIface = resolvedValue.AllInterfaces.FirstOrDefault(ifc =>
ifc.IsGenericType &&
ifc.OriginalDefinition.ToDisplayString() == "AyCode.Core.Interfaces.IId");
dictValueIsIId = dvIidIface != null;
dictValueTypeNameHash = ComputeFnvHash(resolvedValue.Name);
dictValuePropertyHashes = ComputeChildPropertyHashes(resolvedValue);
}
}
}
}
properties.Add(new PropInfo(
p.Name,
typeDisplayName,
typeNameForTypeof,
kind,
p.Type.NullableAnnotation == NullableAnnotation.Annotated || IsNullableVT(p.Type),
p.Type.SpecialType == SpecialType.System_Object,
stringInternAttr, hasGenWriter, propTypeIsIId, writerClassName, propIdTypeName,
elemKind, elemHasGenWriter, elemIsIId, elemWriterClassName, elemIdTypeName, collKind, elemFullTypeName,
collAddMethod, collHasCapacityCtor,
dictKeyKind, dictValueKind, dictKeyTypeName, dictValueTypeName, dictValueHasGenWriter, dictValueWriterClassName,
dictValueIsIId, dictValueEnableMetadata, dictValueTypeNameHash, dictValuePropertyHashes,
dictValueNeedsIdScan, dictValueNeedsAllRefScan, dictValueNeedsInternScan,
childTypeNameHash, childPropertyHashes,
elementTypeNameHash, elementPropertyHashes,
propEnableMetadata, elemEnableMetadata,
childNeedsIdScan, childNeedsAllRefScan, childNeedsInternScan,
elemNeedsIdScan, elemNeedsAllRefScan, elemNeedsInternScan));
}
// IId: Id first (index 0), then alphabetical — matches runtime TypeMetadataBase ordering
// If EnableIdTrackingFeature == false, skip IId detection entirely → isIId = false
var isIId = false;
string? idTypeName = null;
if (enableIdTracking)
{
var iidInterface = typeSymbol.AllInterfaces.FirstOrDefault(i =>
i.IsGenericType &&
i.OriginalDefinition.ToDisplayString() == "AyCode.Core.Interfaces.IId");
if (iidInterface != null)
{
isIId = true;
idTypeName = iidInterface.TypeArguments[0].ToDisplayString();
}
}
// Properties are already in runtime-matching order from GetAllSerializablePropertySymbols:
// derived → base, each level sorted alphabetically (matches TypeMetadataBase.GetUnfilteredProperties).
var className = BuildFlatName(typeSymbol);
var typeNameHash = ComputeFnvHash(typeSymbol.Name);
var propertyNameHashes = properties.Select(prop => ComputeFnvHash(prop.Name)).ToArray();
var selfScanFlags = ComputeNeedsScan(typeSymbol);
return new SerializableClassInfo(namespaceName, className, typeSymbol.ToDisplayString(), properties, isIId, idTypeName, enableRefHandling, typeNameHash, propertyNameHashes, enableMetadata, enablePropertyFilter, selfScanFlags.needsIdScan, selfScanFlags.needsAllRefScan, selfScanFlags.needsInternScan);
}
private static void Execute(ImmutableArray classes, SourceProductionContext context)
{
if (classes.IsDefaultOrEmpty) return;
var valid = classes.Where(c => c != null).Cast().ToList();
if (valid.Count == 0) return;
DetectAndReportCycles(valid, context);
foreach (var ci in valid)
{
context.AddSource($"{ci.ClassName}_GeneratedWriter.g.cs", SourceText.From(GenWriter(ci), Encoding.UTF8));
context.AddSource($"{ci.ClassName}_GeneratedReader.g.cs", SourceText.From(GenReader(ci), Encoding.UTF8));
}
context.AddSource("AcBinaryGeneratedWriters_Init.g.cs", SourceText.From(GenInit(valid), Encoding.UTF8));
}
///
/// Detects circular reference chains among [AcBinarySerializable] types at compile time
/// and reports ACBIN001 warnings. Uses DFS with 3-color marking to find back-edges.
///
private static void DetectAndReportCycles(List classes, SourceProductionContext spc)
{
// Build lookup: WriterClassName → FullTypeName
var writerToFull = new Dictionary(classes.Count);
foreach (var ci in classes)
{
var writerName = string.IsNullOrEmpty(ci.Namespace)
? $"{ci.ClassName}_GeneratedWriter"
: $"{ci.Namespace}.{ci.ClassName}_GeneratedWriter";
writerToFull[writerName] = ci.FullTypeName;
}
// Build adjacency list: FullTypeName → set of referenced FullTypeNames
var adjacency = new Dictionary>(classes.Count);
foreach (var ci in classes)
{
var edges = new HashSet();
foreach (var p in ci.Properties)
{
if (p.TypeKind == PropertyTypeKind.Complex && p.HasGeneratedWriter && p.WriterClassName != null)
{
if (writerToFull.TryGetValue(p.WriterClassName, out var target))
edges.Add(target);
}
if (p.ElementKind == PropertyTypeKind.Complex && p.ElementHasGeneratedWriter && p.ElementWriterClassName != null)
{
if (writerToFull.TryGetValue(p.ElementWriterClassName, out var target))
edges.Add(target);
}
if (p.DictValueKind == PropertyTypeKind.Complex && p.DictValueHasGeneratedWriter && p.DictValueWriterClassName != null)
{
if (writerToFull.TryGetValue(p.DictValueWriterClassName, out var target))
edges.Add(target);
}
}
adjacency[ci.FullTypeName] = edges;
}
// DFS with 3-color marking: White=0, Gray=1, Black=2
var color = new Dictionary(classes.Count);
foreach (var ci in classes)
color[ci.FullTypeName] = 0;
var stack = new List();
var reported = new HashSet();
void Dfs(string node)
{
color[node] = 1; // Gray
stack.Add(node);
if (adjacency.TryGetValue(node, out var neighbors))
{
foreach (var next in neighbors)
{
if (!color.TryGetValue(next, out var c)) continue;
if (c == 1) // Gray → back-edge = cycle
{
var cycleStart = stack.IndexOf(next);
var parts = new List();
for (var i = cycleStart; i < stack.Count; i++)
parts.Add(ShortTypeName(stack[i]));
parts.Add(ShortTypeName(next)); // close the cycle
var cycleDesc = string.Join(" \u2192 ", parts);
for (var i = cycleStart; i < stack.Count; i++)
{
if (reported.Add(stack[i]))
{
spc.ReportDiagnostic(Diagnostic.Create(
CircularReferenceWarning, Location.None,
ShortTypeName(stack[i]), cycleDesc));
}
}
}
else if (c == 0) // White → unvisited
{
Dfs(next);
}
}
}
stack.RemoveAt(stack.Count - 1);
color[node] = 2; // Black
}
foreach (var ci in classes)
{
if (color[ci.FullTypeName] == 0)
Dfs(ci.FullTypeName);
}
}
private static string ShortTypeName(string fullTypeName)
{
var dot = fullTypeName.LastIndexOf('.');
return dot >= 0 ? fullTypeName.Substring(dot + 1) : fullTypeName;
}
private static string GenWriter(SerializableClassInfo ci)
{
var sb = new StringBuilder(4096);
sb.AppendLine("// ");
sb.AppendLine("#nullable enable");
sb.AppendLine("using System.Runtime.CompilerServices;");
sb.AppendLine("using System.Runtime.InteropServices;");
sb.AppendLine("using AyCode.Core.Serializers.Binaries;");
// IGeneratedBinaryWriter and other serializer types
sb.AppendLine("using AyCode.Core.Serializers;");
sb.AppendLine();
if (!string.IsNullOrEmpty(ci.Namespace))
sb.AppendLine($"namespace {ci.Namespace};");
sb.AppendLine();
sb.AppendLine($"internal sealed class {ci.ClassName}_GeneratedWriter : IGeneratedBinaryWriter");
sb.AppendLine("{");
sb.AppendLine($" internal static readonly {ci.ClassName}_GeneratedWriter Instance = new();");
sb.AppendLine($" internal static readonly int s_wrapperSlot = AcBinarySerializer.AllocateWrapperSlot();");
sb.AppendLine($" internal static readonly int s_typeNameHash = {ci.TypeNameHash};");
sb.Append( $" internal static readonly int[] s_propertyHashes = new int[] {{ ");
sb.Append(string.Join(", ", ci.PropertyNameHashes));
sb.AppendLine(" };");
sb.AppendLine();
sb.AppendLine(" public void WriteProperties(object value, AcBinarySerializer.BinarySerializationContext context) where TOutput : struct, IBinaryOutputBase");
sb.AppendLine(" {");
sb.AppendLine(" // Global recursion depth safety net — gated by context.NeedsDepthCheck");
sb.AppendLine(" // (pre-computed at Reset(): !HasAllRefHandling && MaxDepth > 0 && MaxDepthBehavior != Disable).");
sb.AppendLine(" // Local-cached flag: 1 ctx field-read, register-resident — re-used at inc and dec.");
sb.AppendLine(" var needsDepthCheck = context.NeedsDepthCheck;");
sb.AppendLine(" if (needsDepthCheck)");
sb.AppendLine(" {");
sb.AppendLine(" if (context.RecursionDepth >= context.MaxDepth)");
sb.AppendLine($" throw new System.InvalidOperationException(\"AcBinary serialize: recursion depth exceeded MaxDepth=\" + context.MaxDepth + \" at type '{ci.FullTypeName}' (depth=\" + context.RecursionDepth + \", position=\" + context.Position + \")\");");
sb.AppendLine(" context.RecursionDepth++;");
sb.AppendLine(" }");
sb.AppendLine();
sb.AppendLine($" var obj = Unsafe.As<{ci.FullTypeName}>(value);");
foreach (var p in ci.Properties)
{
sb.AppendLine();
EmitProp(sb, p, " ", ci.FullTypeName, ci.EnableMetadata, ci.EnablePropertyFilter);
}
sb.AppendLine();
sb.AppendLine(" if (needsDepthCheck) context.RecursionDepth--;");
sb.AppendLine(" }");
sb.AppendLine();
// ScanObject — full scan pass (null/depth + self ref tracking + property scan)
GenScanProperties(sb, ci);
sb.AppendLine();
// ScanForDuplicates — instance method on IGeneratedBinaryWriter, called from Serialize
sb.AppendLine(" public void ScanForDuplicates(object value, AcBinarySerializer.BinarySerializationContext context)");
sb.AppendLine(" where TOutput : struct, IBinaryOutputBase");
sb.AppendLine(" {");
sb.AppendLine(" if (!context.HasCaching) return;");
sb.AppendLine(" ScanObject(value, context);");
sb.AppendLine(" context.SortWritePlan();");
sb.AppendLine(" }");
sb.AppendLine("}");
return sb.ToString();
}
///
/// Generates the ScanObject method — full scan pass entry point for this type.
/// Includes: null/depth check, self ref tracking (IId or All mode), property scan.
/// Only emits code for reference properties (strings + complex types) — primitives are skipped.
///
private static void GenScanProperties(StringBuilder sb, SerializableClassInfo ci)
{
sb.AppendLine(" public void ScanObject(object value, AcBinarySerializer.BinarySerializationContext context) where TOutput : struct, IBinaryOutputBase");
sb.AppendLine(" {");
// Compile-time proven: no scan work needed for this type
if (!ci.NeedsScan)
{
sb.AppendLine(" // NeedsScan=false: no ref tracking, no string interning, no scannable children");
sb.AppendLine(" }");
return;
}
// Early return: skip scan when no active runtime feature matches this type's needs
if (!ci.NeedsIdScan)
{
if (ci.NeedsAllRefScan && ci.NeedsInternScan)
sb.AppendLine(" if (!context.HasAllRefHandling && !context.HasStringInterning) return;");
else if (ci.NeedsAllRefScan)
sb.AppendLine(" if (!context.HasAllRefHandling) return;");
else if (ci.NeedsInternScan)
sb.AppendLine(" if (!context.HasStringInterning) return;");
}
// Null guard — MaxDepth option removed (was: cycle protection via runtime depth check).
// Cycle safety now comes from IId-tracking; future [AcBinaryCircular] attr will mark non-IId circular refs.
sb.AppendLine(" if (value == null) return;");
sb.AppendLine();
sb.AppendLine($" var obj = Unsafe.As<{ci.FullTypeName}>(value);");
// Self ref tracking — inline TryTrack via wrapper (no bridge method overhead)
// Only emitted when the corresponding feature flag is enabled.
if (ci.IsIId)
{
var tryTrackMethod = ci.IdTypeName switch
{
"int" => "TryTrackInt32",
"long" => "TryTrackInt64",
"System.Guid" => "TryTrackGuid",
_ => "TryTrackInt32"
};
sb.AppendLine();
sb.AppendLine(" if (context.HasRefHandling)");
sb.AppendLine(" {");
sb.AppendLine($" var wrapper = context.GetWrapper(typeof({ci.FullTypeName}), s_wrapperSlot);");
sb.AppendLine(" var visitIndex = context.ScanVisitIndex++;");
sb.AppendLine($" if (!wrapper.{tryTrackMethod}(obj.Id, visitIndex, ref context.NextCacheIndexRef, out var cacheIndex, out var firstVisitIndex))");
sb.AppendLine(" {");
sb.AppendLine(" if (firstVisitIndex >= 0)");
sb.AppendLine(" context.AddWriteDuplicateEntry(firstVisitIndex, cacheIndex, isFirst: true, value: null);");
sb.AppendLine(" context.AddWriteDuplicateEntry(visitIndex, cacheIndex, isFirst: false, value: null);");
sb.AppendLine(" return;");
sb.AppendLine(" }");
sb.AppendLine(" }");
}
if (ci.EnableRefHandling && !ci.IsIId)
{
// Non-IId type: track via wrapper.TryTrackInt32 with RuntimeHelpers.GetHashCode
sb.AppendLine();
sb.AppendLine(" if (context.HasAllRefHandling)");
sb.AppendLine(" {");
sb.AppendLine($" var wrapper = context.GetWrapper(typeof({ci.FullTypeName}), s_wrapperSlot);");
sb.AppendLine(" var visitIndex = context.ScanVisitIndex++;");
sb.AppendLine(" if (!wrapper.TryTrackInt32(System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(value), visitIndex, ref context.NextCacheIndexRef, out var cacheIndex, out var firstVisitIndex))");
sb.AppendLine(" {");
sb.AppendLine(" if (firstVisitIndex >= 0)");
sb.AppendLine(" context.AddWriteDuplicateEntry(firstVisitIndex, cacheIndex, isFirst: true, value: null);");
sb.AppendLine(" context.AddWriteDuplicateEntry(visitIndex, cacheIndex, isFirst: false, value: null);");
sb.AppendLine(" return;");
sb.AppendLine(" }");
sb.AppendLine(" }");
}
// Collect scannable properties
var scanProps = ci.Properties.Where(p =>
p.TypeKind == PropertyTypeKind.String ||
p.TypeKind == PropertyTypeKind.Complex ||
p.TypeKind == PropertyTypeKind.Collection ||
p.TypeKind == PropertyTypeKind.Dictionary).ToList();
// Hoist UseStringInterning + IsValidForInterningString checks if any string scanning needed
var hasStringScan = scanProps.Any(p =>
(p.TypeKind == PropertyTypeKind.String && p.InterningFlags != 0) ||
(p.TypeKind == PropertyTypeKind.Collection && p.ElementKind == PropertyTypeKind.String && p.InterningFlags != 0) ||
(p.TypeKind == PropertyTypeKind.Dictionary && (p.DictKeyKind == PropertyTypeKind.String || p.DictValueKind == PropertyTypeKind.String) && p.InterningFlags != 0));
// Global recursion depth safety net — gated by context.NeedsDepthCheck
// (pre-computed at Reset(): !HasAllRefHandling && MaxDepth > 0 && MaxDepthBehavior != Disable).
// Emitted AFTER all early returns (NeedsScan=false, feature-flag, null guard, IId 2nd-occurrence)
// and BEFORE the property scan loop that recurses into children.
// Local-cached flag: 1 ctx field-read, register-resident — re-used at inc and dec (JIT-independent guarantee).
sb.AppendLine();
sb.AppendLine(" var needsDepthCheck = context.NeedsDepthCheck;");
sb.AppendLine(" if (needsDepthCheck)");
sb.AppendLine(" {");
sb.AppendLine(" if (context.RecursionDepth >= context.MaxDepth)");
sb.AppendLine($" throw new System.InvalidOperationException(\"AcBinary scan: recursion depth exceeded MaxDepth=\" + context.MaxDepth + \" at type '{ci.FullTypeName}' (depth=\" + context.RecursionDepth + \")\");");
sb.AppendLine(" context.RecursionDepth++;");
sb.AppendLine(" }");
if (hasStringScan)
{
// Use pre-computed InternBit from context (avoids Options.UseStringInterning field chain + shift per object).
// Per-property InterningFlags check uses internBit directly.
// Cannot combine flags (OR) because different properties may have different flags
// and Attribute mode must NOT scan All-only properties.
sb.AppendLine();
sb.AppendLine(" var internBit = context.InternBit;");
sb.AppendLine(" int minIntern = 0, maxIntern = 0;");
sb.AppendLine(" if (internBit > 1) { minIntern = context.MinStringInternLength; maxIntern = context.MaxStringInternLength; }");
}
var hasAnyScanProp = false;
foreach (var p in scanProps)
{
sb.AppendLine();
hasAnyScanProp = true;
EmitScanProp(sb, p, " ", ci.FullTypeName, ci.EnablePropertyFilter);
}
if (!hasAnyScanProp)
{
sb.AppendLine(" // No reference properties to scan");
}
sb.AppendLine();
sb.AppendLine(" if (needsDepthCheck) context.RecursionDepth--;");
sb.AppendLine(" }");
}
private static void EmitProp(StringBuilder sb, PropInfo p, string i, string fullTypeName, bool enableMetadata, bool enablePropertyFilter)
{
var a = $"obj.{p.Name}";
// Markerless types: write raw value only, no type marker, no PropertySkip
// Matches runtime WritePropertyMarkerless — these have ExpectedTypeCode
// NEVER filtered (runtime doesn't filter markerless properties either)
// When EnableMetadataFeature=false: always markerless (no UseMetadata branch needed)
// When EnableMetadataFeature=true: UseMetadata=true uses markered path (EmitSkip)
if (IsMarkerless(p.TypeKind))
{
if (!enableMetadata)
EmitMarkerless(sb, p.TypeKind, a, i);
else
EmitPropertyBridge(sb, p.TypeKind, a, i);
return;
}
// All non-markerless properties: emit PropertyFilter guard
// When filter returns false, write PropertySkip and skip the property write.
// Gated by `[AcBinarySerializable(EnablePropertyFilterFeature = ...)]` — when false, the entire
// filter-check block is omitted from emit (no `HasPropertyFilter` test, no filter-context allocation,
// no lambda-call) → leaner generated code on hot-path types that never use a property-filter.
if (enablePropertyFilter)
{
sb.AppendLine($"{i}if (context.HasPropertyFilter)");
sb.AppendLine($"{i}{{");
sb.AppendLine($"{i} var fc_{p.Name} = new BinaryPropertyFilterContext(obj, typeof({fullTypeName}), \"{p.Name}\", typeof({p.TypeNameForTypeof}), static o => (({fullTypeName})o).{p.Name});");
sb.AppendLine($"{i} if (!context.PropertyFilter!(in fc_{p.Name}))");
sb.AppendLine($"{i} {{");
sb.AppendLine($"{i} context.WriteByte(BinaryTypeCode.PropertySkip);");
sb.AppendLine($"{i} goto skip_{p.Name};");
sb.AppendLine($"{i} }}");
sb.AppendLine($"{i}}}");
}
// Nullable value types always use markered path (need Null marker)
if (IsNullableVTKind(p.TypeKind))
{
sb.AppendLine($"{i}if ({a}.HasValue)");
sb.AppendLine($"{i}{{");
EmitVal(sb, Underlying(p.TypeKind), $"{a}.Value", p.TypeNameForTypeof, i + " ");
sb.AppendLine($"{i}}}");
sb.AppendLine($"{i}else context.WriteByte(BinaryTypeCode.PropertySkip);");
sb.AppendLine($"{i}skip_{p.Name}:;");
return;
}
// Non-markerless types: write WITH type marker byte (markered path)
switch (p.TypeKind)
{
case PropertyTypeKind.String:
if (p.InterningFlags == 0)
sb.AppendLine($"{i}context.StringInternEligible = false;");
else
sb.AppendLine($"{i}context.StringInternEligible = ({p.InterningFlags} & context.InternBit) != 0;");
sb.AppendLine($"{i}AcBinarySerializer.WriteStringGenerated({a}, context);");
break;
case PropertyTypeKind.Complex:
// Complex object: direct write bypasses GetWrapper + WriteObject pipeline entirely
// when the property type has a generated writer. Falls back to WriteObjectGenerated otherwise.
if (p.HasGeneratedWriter)
EmitDirectObjectWrite(sb, p, a, i);
else if (p.IsObjectDeclaredType)
{
// System.Object property: runtime type unknown at compile time.
// Write ObjectWithTypeName prefix so deserializer can resolve the concrete type.
// Use value.GetType() for runtime type dispatch (not typeof(object)).
// Gated by `UsePolymorphType` (TEMPORARY const) — `false` skips the type-name emit
// entirely (deser will use the property's declared type, which is `object` so the
// round-trip would fail on polymorphic instances; safe ONLY when the workload is
// known not to use polymorphic object-typed properties — true for the benchmark).
sb.AppendLine($"{i}if ({a} == null) context.WriteByte(BinaryTypeCode.PropertySkip);");
sb.AppendLine($"{i}else");
sb.AppendLine($"{i}{{");
if (UsePolymorphType)
{
sb.AppendLine($"{i} if (!context.UseMetadata)");
sb.AppendLine($"{i} {{");
sb.AppendLine($"{i} context.WriteByte(BinaryTypeCode.ObjectWithTypeName);");
sb.AppendLine($"{i} context.WriteStringUtf8({a}.GetType().AssemblyQualifiedName!);");
sb.AppendLine($"{i} }}");
}
sb.AppendLine($"{i} AcBinarySerializer.WriteValueGenerated({a}, {a}.GetType(), context);");
sb.AppendLine($"{i}}}");
}
else if (p.IsNullable)
{
sb.AppendLine($"{i}if ({a} == null) context.WriteByte(BinaryTypeCode.PropertySkip);");
sb.AppendLine($"{i}else AcBinarySerializer.WriteObjectGenerated({a}, typeof({p.TypeNameForTypeof}), context);");
}
else
sb.AppendLine($"{i}AcBinarySerializer.WriteObjectGenerated({a}, typeof({p.TypeNameForTypeof}), context);");
break;
case PropertyTypeKind.Collection:
// Direct collection write for List/T[] with Complex element types that have generated writers
if (p.ElementHasGeneratedWriter && p.CollectionKind != null)
EmitDirectCollectionWrite(sb, p, a, i);
else if (p.IsNullable)
{
sb.AppendLine($"{i}if ({a} == null) context.WriteByte(BinaryTypeCode.PropertySkip);");
sb.AppendLine($"{i}else AcBinarySerializer.WriteValueGenerated({a}, typeof({p.TypeNameForTypeof}), context);");
}
else
sb.AppendLine($"{i}AcBinarySerializer.WriteValueGenerated({a}, typeof({p.TypeNameForTypeof}), context);");
break;
case PropertyTypeKind.Dictionary:
EmitDirectDictionaryWrite(sb, p, a, i);
break;
default:
EmitSkip(sb, p.TypeKind, a, p.TypeNameForTypeof, i);
break;
}
sb.AppendLine($"{i}skip_{p.Name}:;");
}
///
/// Returns true for property types that use markerless serialization in FastMode.
/// These types have ExpectedTypeCode at runtime — no type marker byte, no PropertySkip for defaults.
///
private static bool IsMarkerless(PropertyTypeKind k) => k switch
{
PropertyTypeKind.Int32 or PropertyTypeKind.Int64 or PropertyTypeKind.Int16 or
PropertyTypeKind.Byte or PropertyTypeKind.UInt16 or PropertyTypeKind.UInt32 or PropertyTypeKind.UInt64 or
PropertyTypeKind.Double or PropertyTypeKind.Single or PropertyTypeKind.Decimal or
PropertyTypeKind.DateTime or PropertyTypeKind.Guid or
PropertyTypeKind.TimeSpan or PropertyTypeKind.DateTimeOffset or
PropertyTypeKind.Boolean or PropertyTypeKind.Enum => true,
_ => false
};
///
/// Emits raw value only — no type marker, no PropertySkip.
/// Matches runtime WritePropertyMarkerless exactly.
///
private static void EmitMarkerless(StringBuilder sb, PropertyTypeKind k, string a, string i)
{
switch (k)
{
case PropertyTypeKind.Int32: sb.AppendLine($"{i}context.WriteVarInt({a});"); break;
case PropertyTypeKind.Int64: sb.AppendLine($"{i}context.WriteVarLong({a});"); break;
case PropertyTypeKind.Double: sb.AppendLine($"{i}context.WriteRaw({a});"); break;
case PropertyTypeKind.Single: sb.AppendLine($"{i}context.WriteRaw({a});"); break;
case PropertyTypeKind.Decimal: sb.AppendLine($"{i}context.WriteDecimalBits({a});"); break;
case PropertyTypeKind.DateTime: sb.AppendLine($"{i}context.WriteDateTimeBits({a});"); break;
case PropertyTypeKind.Guid: sb.AppendLine($"{i}context.WriteGuidBits({a});"); break;
case PropertyTypeKind.Byte: sb.AppendLine($"{i}context.WriteByte({a});"); break;
case PropertyTypeKind.Int16: sb.AppendLine($"{i}context.WriteRaw({a});"); break;
case PropertyTypeKind.UInt16: sb.AppendLine($"{i}context.WriteRaw({a});"); break;
case PropertyTypeKind.UInt32: sb.AppendLine($"{i}context.WriteVarUInt({a});"); break;
case PropertyTypeKind.UInt64: sb.AppendLine($"{i}context.WriteVarULong({a});"); break;
case PropertyTypeKind.TimeSpan: sb.AppendLine($"{i}context.WriteRaw({a}.Ticks);"); break;
case PropertyTypeKind.DateTimeOffset: sb.AppendLine($"{i}context.WriteDateTimeOffsetBits({a});"); break;
case PropertyTypeKind.Boolean: sb.AppendLine($"{i}context.WriteByte({a} ? (byte)1 : (byte)0);"); break;
case PropertyTypeKind.Enum: sb.AppendLine($"{i}context.WriteVarInt((int){a});"); break;
}
}
///
/// Emits a single bridge method call for markerless property types with enableMetadata=true.
/// The bridge method on BinarySerializationContext handles both UseMetadata=true (markered+skip)
/// and UseMetadata=false (markerless) paths internally. Replaces 7-11 lines of generated code with 1 line.
///
private static void EmitPropertyBridge(StringBuilder sb, PropertyTypeKind k, string a, string i)
{
var call = k switch
{
PropertyTypeKind.Int32 => $"context.WriteInt32Property({a});",
PropertyTypeKind.Int64 => $"context.WriteInt64Property({a});",
PropertyTypeKind.Boolean => $"context.WriteBoolProperty({a});",
PropertyTypeKind.Double => $"context.WriteFloat64Property({a});",
PropertyTypeKind.Single => $"context.WriteFloat32Property({a});",
PropertyTypeKind.Decimal => $"context.WriteDecimalProperty({a});",
PropertyTypeKind.DateTime => $"context.WriteDateTimeProperty({a});",
PropertyTypeKind.Guid => $"context.WriteGuidProperty({a});",
PropertyTypeKind.Byte => $"context.WriteByteProperty({a});",
PropertyTypeKind.Int16 => $"context.WriteInt16Property({a});",
PropertyTypeKind.UInt16 => $"context.WriteUInt16Property({a});",
PropertyTypeKind.UInt32 => $"context.WriteUInt32Property({a});",
PropertyTypeKind.UInt64 => $"context.WriteUInt64Property({a});",
PropertyTypeKind.Enum => $"context.WriteEnumInt32Property((int){a});",
PropertyTypeKind.TimeSpan => $"context.WriteTimeSpanProperty({a});",
PropertyTypeKind.DateTimeOffset => $"context.WriteDateTimeOffsetProperty({a});",
_ => null
};
if (call != null)
sb.AppendLine($"{i}{call}");
}
///
/// Emits direct object write — bypasses GetWrapper + WriteObject entirely.
#region Scan Pass Code Generation
///
/// Compile-time check: will EmitScanProp produce any scan work for this property?
/// When false, the entire block (including PropertyFilter guard) is skipped.
///
private static bool HasScanWork(PropInfo p) => p.TypeKind switch
{
PropertyTypeKind.String => p.InterningFlags != 0,
PropertyTypeKind.Complex when p.HasGeneratedWriter => p.ChildNeedsScan,
PropertyTypeKind.Complex => true,
PropertyTypeKind.Collection => HasCollectionScanWork(p),
PropertyTypeKind.Dictionary => HasDictionaryScanWork(p),
_ => false
};
private static bool HasCollectionScanWork(PropInfo p) => p.ElementKind switch
{
PropertyTypeKind.String => p.InterningFlags != 0,
PropertyTypeKind.Complex when p.ElementHasGeneratedWriter && p.CollectionKind != null => p.ElementNeedsScan,
PropertyTypeKind.Complex => true,
_ => false
};
private static bool HasDictionaryScanWork(PropInfo p)
{
if (p.DictKeyKind == PropertyTypeKind.String && p.InterningFlags != 0) return true;
if (p.DictValueKind == PropertyTypeKind.String && p.InterningFlags != 0) return true;
if (p.DictValueKind == PropertyTypeKind.Complex && p.DictValueHasGeneratedWriter) return p.DictValueNeedsScan;
if (p.DictValueKind == PropertyTypeKind.Complex) return true;
return false;
}
///
/// Emits scan pass code for a single property.
/// String: interning check + ScanInternString.
/// Complex (SGen): ref tracking via slot IdentityMap + recursive ScanProperties.
/// Complex (no SGen): fallback to ScanValueGenerated (runtime wrapper lookup).
/// Collection: iterate elements with same patterns.
///
private static void EmitScanProp(StringBuilder sb, PropInfo p, string i, string fullTypeName, bool enablePropertyFilter)
{
// Compile-time proven: no scan work for this property — skip entirely (including PropertyFilter guard)
if (!HasScanWork(p)) return;
var a = $"obj.{p.Name}";
// PropertyFilter: must match write pass — if filter skips property, scan must skip too
// Only for non-markerless properties (matching EmitProp behavior).
// Gated by `[AcBinarySerializable(EnablePropertyFilterFeature = ...)]` — same gate as the writer pass.
if (enablePropertyFilter && !IsMarkerless(p.TypeKind))
{
sb.AppendLine($"{i}if (context.HasPropertyFilter)");
sb.AppendLine($"{i}{{");
sb.AppendLine($"{i} var fc_{p.Name} = new BinaryPropertyFilterContext(obj, typeof({fullTypeName}), \"{p.Name}\", typeof({p.TypeNameForTypeof}), static o => (({fullTypeName})o).{p.Name});");
sb.AppendLine($"{i} if (!context.PropertyFilter!(in fc_{p.Name}))");
sb.AppendLine($"{i} goto scanskip_{p.Name};");
sb.AppendLine($"{i}}}");
}
switch (p.TypeKind)
{
case PropertyTypeKind.String:
EmitScanString(sb, p, a, i);
break;
case PropertyTypeKind.Complex:
if (p.HasGeneratedWriter)
EmitScanComplexSGen(sb, p, a, i);
else
EmitScanComplexRuntime(sb, p, a, i);
break;
case PropertyTypeKind.Collection:
EmitScanCollection(sb, p, a, i);
break;
case PropertyTypeKind.Dictionary:
EmitScanDictionary(sb, p, a, i);
break;
}
if (!IsMarkerless(p.TypeKind))
sb.AppendLine($"{i}scanskip_{p.Name}:;");
}
///
/// Emits scan pass code for a string property: interning flags check + ScanInternString.
///
private static void EmitScanString(StringBuilder sb, PropInfo p, string a, string i)
{
if (p.InterningFlags == 0)
{
// Never interned (explicit [AcStringIntern(false)] or no flags) — skip entirely
return;
}
// Per-property InterningFlags check with hoisted internBit (context.Options read once)
sb.AppendLine($"{i}if (({p.InterningFlags} & internBit) != 0)");
sb.AppendLine($"{i}{{");
sb.AppendLine($"{i} var str_{p.Name} = {a};");
sb.AppendLine($"{i} if (str_{p.Name} != null)");
sb.AppendLine($"{i} {{");
sb.AppendLine($"{i} var slen_{p.Name} = str_{p.Name}.Length;");
sb.AppendLine($"{i} if (slen_{p.Name} >= minIntern && (maxIntern == 0 || slen_{p.Name} <= maxIntern))");
sb.AppendLine($"{i} context.ScanInternString(str_{p.Name});");
sb.AppendLine($"{i} }}");
sb.AppendLine($"{i}}}");
}
///
/// Emits scan pass code for a Complex property with SGen writer.
/// No parent-side ref tracking — child ScanObject handles its own (ScanTrackObjectXxx).
///
private static void EmitScanComplexSGen(StringBuilder sb, PropInfo p, string a, string i)
{
// Compile-time proven: child scan is no-op — skip entirely
if (!p.ChildNeedsScan) return;
var writer = p.WriterClassName;
var childVar = $"sc_{p.Name}";
// 3-axis guard: IId → always call, AllRef → guard All mode, Intern → guard UseStringInterning
string? guard = null;
if (!p.ChildNeedsIdScan)
{
if (p.ChildNeedsAllRefScan && p.ChildNeedsInternScan)
guard = "context.HasAllRefHandling || context.HasStringInterning";
else if (p.ChildNeedsAllRefScan)
guard = "context.HasAllRefHandling";
else if (p.ChildNeedsInternScan)
guard = "context.HasStringInterning";
}
if (guard != null)
{
sb.AppendLine($"{i}if ({guard})");
sb.AppendLine($"{i}{{");
sb.AppendLine($"{i} var {childVar} = {a};");
sb.AppendLine($"{i} if ({childVar} != null)");
sb.AppendLine($"{i} {writer}.Instance.ScanObject({childVar}, context);");
sb.AppendLine($"{i}}}");
}
else
{
// IId in subtree — always call (active in OnlyId + All)
sb.AppendLine($"{i}var {childVar} = {a};");
sb.AppendLine($"{i}if ({childVar} != null)");
sb.AppendLine($"{i} {writer}.Instance.ScanObject({childVar}, context);");
}
}
///
/// Emits scan pass code for a Complex property without SGen writer (runtime fallback).
/// System.Object properties use value.GetType() for runtime type dispatch.
///
private static void EmitScanComplexRuntime(StringBuilder sb, PropInfo p, string a, string i)
{
var childVar = $"sc_{p.Name}";
sb.AppendLine($"{i}var {childVar} = {a};");
sb.AppendLine($"{i}if ({childVar} != null)");
if (p.IsObjectDeclaredType)
sb.AppendLine($"{i} AcBinarySerializer.ScanValueGenerated({childVar}, {childVar}.GetType(), context);");
else
sb.AppendLine($"{i} AcBinarySerializer.ScanValueGenerated({childVar}, typeof({p.TypeNameForTypeof}), context);");
}
///
/// Emits scan pass code for a Collection property.
/// Handles string collections (interning) and complex element collections (SGen or runtime fallback).
///
private static void EmitScanCollection(StringBuilder sb, PropInfo p, string a, string i)
{
// String element collection
if (p.ElementKind == PropertyTypeKind.String)
{
if (p.InterningFlags == 0) return; // never interned
sb.AppendLine($"{i}var scol_{p.Name} = {a};");
sb.AppendLine($"{i}if (scol_{p.Name} != null && ({p.InterningFlags} & internBit) != 0)");
sb.AppendLine($"{i}{{");
if (p.CollectionKind == "Array")
{
sb.AppendLine($"{i} for (var si_{p.Name} = 0; si_{p.Name} < scol_{p.Name}.Length; si_{p.Name}++)");
sb.AppendLine($"{i} {{");
sb.AppendLine($"{i} var se_{p.Name} = scol_{p.Name}[si_{p.Name}];");
}
else if (p.CollectionKind == "List")
{
sb.AppendLine($"{i} var span_{p.Name} = CollectionsMarshal.AsSpan(scol_{p.Name});");
sb.AppendLine($"{i} for (var si_{p.Name} = 0; si_{p.Name} < span_{p.Name}.Length; si_{p.Name}++)");
sb.AppendLine($"{i} {{");
sb.AppendLine($"{i} var se_{p.Name} = span_{p.Name}[si_{p.Name}];");
}
else if (p.CollectionKind == "IndexedCollection")
{
sb.AppendLine($"{i} for (var si_{p.Name} = 0; si_{p.Name} < scol_{p.Name}.Count; si_{p.Name}++)");
sb.AppendLine($"{i} {{");
sb.AppendLine($"{i} var se_{p.Name} = scol_{p.Name}[si_{p.Name}];");
}
else
{
sb.AppendLine($"{i} foreach (var se_{p.Name} in scol_{p.Name})");
sb.AppendLine($"{i} {{");
}
sb.AppendLine($"{i} if (se_{p.Name} != null)");
sb.AppendLine($"{i} {{");
sb.AppendLine($"{i} var slen_{p.Name} = se_{p.Name}.Length;");
sb.AppendLine($"{i} if (slen_{p.Name} >= minIntern && (maxIntern == 0 || slen_{p.Name} <= maxIntern))");
sb.AppendLine($"{i} context.ScanInternString(se_{p.Name});");
sb.AppendLine($"{i} }}");
sb.AppendLine($"{i} }}");
sb.AppendLine($"{i}}}");
return;
}
// Complex element collection with SGen writer
if (p.ElementKind == PropertyTypeKind.Complex && p.ElementHasGeneratedWriter && p.CollectionKind != null)
{
// Compile-time proven: element scan is no-op — skip entirely
if (!p.ElementNeedsScan) return;
var writer = p.ElementWriterClassName;
// 3-axis guard: IId → always scan, AllRef → guard All mode, Intern → guard UseStringInterning
string? elemGuard = null;
if (!p.ElementNeedsIdScan)
{
if (p.ElementNeedsAllRefScan && p.ElementNeedsInternScan)
elemGuard = "context.HasAllRefHandling || context.HasStringInterning";
else if (p.ElementNeedsAllRefScan)
elemGuard = "context.HasAllRefHandling";
else if (p.ElementNeedsInternScan)
elemGuard = "context.HasStringInterning";
}
// Guard entire collection scan with runtime check when no IId in element subtree
if (elemGuard != null)
sb.AppendLine($"{i}if ({elemGuard})");
sb.AppendLine($"{i}{{");
sb.AppendLine($"{i} var scol_{p.Name} = {a};");
sb.AppendLine($"{i} if (scol_{p.Name} != null)");
sb.AppendLine($"{i} {{");
if (p.CollectionKind == "Array")
{
sb.AppendLine($"{i} for (var si_{p.Name} = 0; si_{p.Name} < scol_{p.Name}.Length; si_{p.Name}++)");
sb.AppendLine($"{i} {{");
sb.AppendLine($"{i} var se_{p.Name} = scol_{p.Name}[si_{p.Name}];");
}
else if (p.CollectionKind == "List")
{
sb.AppendLine($"{i} var span_{p.Name} = CollectionsMarshal.AsSpan(scol_{p.Name});");
sb.AppendLine($"{i} for (var si_{p.Name} = 0; si_{p.Name} < span_{p.Name}.Length; si_{p.Name}++)");
sb.AppendLine($"{i} {{");
sb.AppendLine($"{i} var se_{p.Name} = span_{p.Name}[si_{p.Name}];");
}
else if (p.CollectionKind == "IndexedCollection")
{
sb.AppendLine($"{i} for (var si_{p.Name} = 0; si_{p.Name} < scol_{p.Name}.Count; si_{p.Name}++)");
sb.AppendLine($"{i} {{");
sb.AppendLine($"{i} var se_{p.Name} = scol_{p.Name}[si_{p.Name}];");
}
else // Counted (foreach)
{
sb.AppendLine($"{i} foreach (var se_{p.Name} in scol_{p.Name})");
sb.AppendLine($"{i} {{");
}
var e = $"se_{p.Name}";
// Null check only — ScanObject handles depth + ref tracking internally
sb.AppendLine($"{i} if ({e} == null) continue;");
sb.AppendLine($"{i} {writer}.Instance.ScanObject({e}, context);");
sb.AppendLine($"{i} }}");
sb.AppendLine($"{i} }}");
sb.AppendLine($"{i}}}");
return;
}
// Complex element collection without SGen writer — runtime fallback
if (p.ElementKind == PropertyTypeKind.Complex)
{
sb.AppendLine($"{i}var scol_{p.Name} = {a};");
sb.AppendLine($"{i}if (scol_{p.Name} != null)");
sb.AppendLine($"{i} AcBinarySerializer.ScanValueGenerated(scol_{p.Name}, typeof({p.TypeNameForTypeof}), context);");
return;
}
// Primitive element collection — no scanning needed
}
///
/// Emits inline dictionary scan. Iterates entries and:
/// - String keys: ScanInternString if interning flags match
/// - String values: ScanInternString if interning flags match
/// - Complex+SGen values: ScanObject on each value (handles ref tracking internally)
/// Eliminates GetWrapper dictionary lookup for all inlineable dictionary types.
///
private static void EmitScanDictionary(StringBuilder sb, PropInfo p, string a, string i)
{
var s = p.Name;
var hasStringKeys = p.DictKeyKind == PropertyTypeKind.String && p.InterningFlags != 0;
var hasStringValues = p.DictValueKind == PropertyTypeKind.String && p.InterningFlags != 0;
var hasComplexValues = p.DictValueKind == PropertyTypeKind.Complex && p.DictValueHasGeneratedWriter;
// No scanning needed for primitive-only dictionaries without internable strings or complex values
if (!hasStringKeys && !hasStringValues && !hasComplexValues) return;
// Complex+SGen values: compile-time proven scan is no-op → skip entirely
if (hasComplexValues && !p.DictValueNeedsScan && !hasStringKeys && !hasStringValues) return;
// Build guard expression for Complex+SGen values (3-axis: IId/AllRef/Intern)
string? complexGuard = null;
if (hasComplexValues && p.DictValueNeedsScan && !p.DictValueNeedsIdScan)
{
if (p.DictValueNeedsAllRefScan && p.DictValueNeedsInternScan)
complexGuard = "context.HasAllRefHandling || context.HasStringInterning";
else if (p.DictValueNeedsAllRefScan)
complexGuard = "context.HasAllRefHandling";
else if (p.DictValueNeedsInternScan)
complexGuard = "context.HasStringInterning";
}
// For string-only scan (no complex values), use simple interning loop
if (!hasComplexValues)
{
sb.AppendLine($"{i}var sd_{s} = {a};");
sb.AppendLine($"{i}if (sd_{s} != null && ({p.InterningFlags} & internBit) != 0)");
sb.AppendLine($"{i}{{");
sb.AppendLine($"{i} foreach (var sde_{s} in sd_{s})");
sb.AppendLine($"{i} {{");
if (hasStringKeys)
{
sb.AppendLine($"{i} if (sde_{s}.Key != null)");
sb.AppendLine($"{i} {{");
sb.AppendLine($"{i} var sklen_{s} = sde_{s}.Key.Length;");
sb.AppendLine($"{i} if (sklen_{s} >= minIntern && (maxIntern == 0 || sklen_{s} <= maxIntern))");
sb.AppendLine($"{i} context.ScanInternString(sde_{s}.Key);");
sb.AppendLine($"{i} }}");
}
if (hasStringValues)
{
sb.AppendLine($"{i} if (sde_{s}.Value != null)");
sb.AppendLine($"{i} {{");
sb.AppendLine($"{i} var svlen_{s} = sde_{s}.Value.Length;");
sb.AppendLine($"{i} if (svlen_{s} >= minIntern && (maxIntern == 0 || svlen_{s} <= maxIntern))");
sb.AppendLine($"{i} context.ScanInternString(sde_{s}.Value);");
sb.AppendLine($"{i} }}");
}
sb.AppendLine($"{i} }}");
sb.AppendLine($"{i}}}");
return;
}
// Complex+SGen values (with optional string key/value interning)
var writer = p.DictValueWriterClassName!;
// Guard entire scan block when no IId in value subtree
if (complexGuard != null && !hasStringKeys && !hasStringValues)
sb.AppendLine($"{i}if ({complexGuard})");
sb.AppendLine($"{i}{{");
sb.AppendLine($"{i} var sd_{s} = {a};");
sb.AppendLine($"{i} if (sd_{s} != null)");
sb.AppendLine($"{i} {{");
sb.AppendLine($"{i} foreach (var sde_{s} in sd_{s})");
sb.AppendLine($"{i} {{");
// String key interning
if (hasStringKeys)
{
sb.AppendLine($"{i} if (({p.InterningFlags} & internBit) != 0 && sde_{s}.Key != null)");
sb.AppendLine($"{i} {{");
sb.AppendLine($"{i} var sklen_{s} = sde_{s}.Key.Length;");
sb.AppendLine($"{i} if (sklen_{s} >= minIntern && (maxIntern == 0 || sklen_{s} <= maxIntern))");
sb.AppendLine($"{i} context.ScanInternString(sde_{s}.Key);");
sb.AppendLine($"{i} }}");
}
// String value interning
if (hasStringValues)
{
sb.AppendLine($"{i} if (({p.InterningFlags} & internBit) != 0 && sde_{s}.Value != null)");
sb.AppendLine($"{i} {{");
sb.AppendLine($"{i} var svlen_{s} = sde_{s}.Value.Length;");
sb.AppendLine($"{i} if (svlen_{s} >= minIntern && (maxIntern == 0 || svlen_{s} <= maxIntern))");
sb.AppendLine($"{i} context.ScanInternString(sde_{s}.Value);");
sb.AppendLine($"{i} }}");
}
// Complex value ScanObject
if (hasComplexValues)
{
sb.AppendLine($"{i} if (sde_{s}.Value != null)");
if (complexGuard != null)
{
sb.AppendLine($"{i} {{");
sb.AppendLine($"{i} if ({complexGuard})");
sb.AppendLine($"{i} {writer}.Instance.ScanObject(sde_{s}.Value, context);");
sb.AppendLine($"{i} }}");
}
else
sb.AppendLine($"{i} {writer}.Instance.ScanObject(sde_{s}.Value, context);");
}
sb.AppendLine($"{i} }}");
sb.AppendLine($"{i} }}");
sb.AppendLine($"{i}}}");
}
#endregion
///
/// Emits inline object write for a Complex property that has a generated writer.
/// Compile-time ChildNeedsRefScan eliminates TryConsumeWritePlanEntry when scan never tracks child.
/// !ChildNeedsRefScan + !ChildEnableMetadata → ZERO branches: just Object + WriteProperties.
///
private static void EmitDirectObjectWrite(StringBuilder sb, PropInfo p, string a, string i)
{
var writer = p.WriterClassName;
var refSuffix = p.IsIId ? "IId" : "All";
// Reference type properties can always be null at runtime regardless of nullable annotation
sb.AppendLine($"{i}if ({a} == null) context.WriteByte(BinaryTypeCode.PropertySkip);");
if (!p.ChildNeedsRefScan && !p.ChildEnableMetadata)
{
// Compile-time proven: no ref, no metadata → ZERO branches: always Object + WriteProperties
sb.AppendLine($"{i}else {{ context.WriteByte(BinaryTypeCode.Object); {writer}.Instance.WriteProperties({a}, context); }}");
}
else if (p.ChildNeedsRefScan && !p.ChildEnableMetadata)
{
sb.AppendLine($"{i}else if (context.WriteObjectRefMarker{refSuffix}()) {writer}.Instance.WriteProperties({a}, context);");
}
else if (!p.ChildNeedsRefScan && p.ChildEnableMetadata)
{
sb.AppendLine($"{i}else {{ context.WriteObjectMetaMarker({a}, {writer}.s_wrapperSlot); {writer}.Instance.WriteProperties({a}, context); }}");
}
else
{
sb.AppendLine($"{i}else if (context.WriteObjectFullMarker{refSuffix}({a}, {writer}.s_wrapperSlot)) {writer}.Instance.WriteProperties({a}, context);");
}
}
///
/// Emits inline metadata write: typeNameHash + (if first) propCount + property hashes.
/// All values are compile-time constants.
///
private static void EmitInlineMetadata(StringBuilder sb, int typeNameHash, int[] propertyHashes, string isFirstVar, string i)
{
sb.AppendLine($"{i}context.WriteRaw({typeNameHash});");
sb.AppendLine($"{i}if ({isFirstVar})");
sb.AppendLine($"{i}{{");
sb.AppendLine($"{i} context.WriteVarUInt({(uint)propertyHashes.Length});");
foreach (var hash in propertyHashes)
sb.AppendLine($"{i} context.WriteRaw({hash});");
sb.AppendLine($"{i}}}");
}
///
/// Emits inline collection write for List<T> / T[] where T is a Complex type with generated writer.
/// Bypasses GetWrapper + WriteArray + WriteValue per-element dispatch entirely.
/// Wire format: [Array marker][VarUInt count][elem₁ marker+props][elem₂ marker+props]...
/// Handles both UseMetadata=true and false inline — no fallback to WriteValueGenerated.
///
private static void EmitDirectCollectionWrite(StringBuilder sb, PropInfo p, string a, string i)
{
var writer = p.ElementWriterClassName;
// Reference type collections can always be null at runtime regardless of nullable annotation
sb.AppendLine($"{i}if ({a} == null) context.WriteByte(BinaryTypeCode.PropertySkip);");
sb.AppendLine($"{i}else");
sb.AppendLine($"{i}{{");
sb.AppendLine($"{i} context.WriteByte(BinaryTypeCode.Array);");
// Get count and iteration based on collection kind
if (p.CollectionKind == "Array")
{
sb.AppendLine($"{i} var arr_{p.Name} = {a};");
sb.AppendLine($"{i} context.WriteVarUInt((uint)arr_{p.Name}.Length);");
sb.AppendLine($"{i} for (var i_{p.Name} = 0; i_{p.Name} < arr_{p.Name}.Length; i_{p.Name}++)");
sb.AppendLine($"{i} {{");
sb.AppendLine($"{i} var elem_{p.Name} = arr_{p.Name}[i_{p.Name}];");
}
else if (p.CollectionKind == "Counted")
{
sb.AppendLine($"{i} var col_{p.Name} = {a};");
sb.AppendLine($"{i} context.WriteVarUInt((uint)col_{p.Name}.Count);");
sb.AppendLine($"{i} foreach (var elem_{p.Name} in col_{p.Name})");
sb.AppendLine($"{i} {{");
}
else if (p.CollectionKind == "IndexedCollection")
{
sb.AppendLine($"{i} var col_{p.Name} = {a};");
sb.AppendLine($"{i} context.WriteVarUInt((uint)col_{p.Name}.Count);");
sb.AppendLine($"{i} for (var i_{p.Name} = 0; i_{p.Name} < col_{p.Name}.Count; i_{p.Name}++)");
sb.AppendLine($"{i} {{");
sb.AppendLine($"{i} var elem_{p.Name} = col_{p.Name}[i_{p.Name}];");
}
else // List — CollectionsMarshal.AsSpan for zero-overhead iteration
{
sb.AppendLine($"{i} var span_{p.Name} = CollectionsMarshal.AsSpan({a});");
sb.AppendLine($"{i} context.WriteVarUInt((uint)span_{p.Name}.Length);");
sb.AppendLine($"{i} for (var i_{p.Name} = 0; i_{p.Name} < span_{p.Name}.Length; i_{p.Name}++)");
sb.AppendLine($"{i} {{");
sb.AppendLine($"{i} var elem_{p.Name} = span_{p.Name}[i_{p.Name}];");
}
// Per-element write
var e = $"elem_{p.Name}";
sb.AppendLine($"{i} if ({e} == null) {{ context.WriteByte(BinaryTypeCode.Null); continue; }}");
var elemRefSuffix = p.ElementIsIId ? "IId" : "All";
if (!p.ElementNeedsRefScan && !p.ElementEnableMetadata)
{
// Compile-time proven: no ref, no metadata → ZERO branches per element: always Object
sb.AppendLine($"{i} context.WriteByte(BinaryTypeCode.Object);");
sb.AppendLine($"{i} {writer}.Instance.WriteProperties({e}, context);");
}
else if (p.ElementNeedsRefScan && !p.ElementEnableMetadata)
{
sb.AppendLine($"{i} if (context.WriteObjectRefMarker{elemRefSuffix}()) {writer}.Instance.WriteProperties({e}, context);");
}
else if (!p.ElementNeedsRefScan && p.ElementEnableMetadata)
{
sb.AppendLine($"{i} context.WriteObjectMetaMarker({e}, {writer}.s_wrapperSlot);");
sb.AppendLine($"{i} {writer}.Instance.WriteProperties({e}, context);");
}
else
{
sb.AppendLine($"{i} if (context.WriteObjectFullMarker{elemRefSuffix}({e}, {writer}.s_wrapperSlot)) {writer}.Instance.WriteProperties({e}, context);");
}
sb.AppendLine($"{i} }}");
sb.AppendLine($"{i}}}");
}
///
/// Emits inline write of a primitive/string/enum value in non-property context (no PropertySkip).
/// Matches runtime TryWritePrimitive wire format: TinyInt for small int, type code + value otherwise.
/// Used for dictionary key/value writes.
///
private static void EmitWritePrimitiveValue(StringBuilder sb, PropertyTypeKind kind, string a, string suffix, string i)
{
switch (kind)
{
case PropertyTypeKind.Int32:
sb.AppendLine($"{i}if (BinaryTypeCode.TryEncodeTinyInt({a}, out var tk_{suffix})) context.WriteByte(tk_{suffix});");
sb.AppendLine($"{i}else {{ context.WriteByte(BinaryTypeCode.Int32); context.WriteVarInt({a}); }}");
break;
case PropertyTypeKind.Int64:
sb.AppendLine($"{i}if ({a} >= int.MinValue && {a} <= int.MaxValue)");
sb.AppendLine($"{i}{{");
sb.AppendLine($"{i} var iv_{suffix} = (int){a};");
sb.AppendLine($"{i} if (BinaryTypeCode.TryEncodeTinyInt(iv_{suffix}, out var tk_{suffix})) context.WriteByte(tk_{suffix});");
sb.AppendLine($"{i} else {{ context.WriteByte(BinaryTypeCode.Int32); context.WriteVarInt(iv_{suffix}); }}");
sb.AppendLine($"{i}}}");
sb.AppendLine($"{i}else {{ context.WriteByte(BinaryTypeCode.Int64); context.WriteVarLong({a}); }}");
break;
case PropertyTypeKind.Boolean:
sb.AppendLine($"{i}context.WriteByte({a} ? BinaryTypeCode.True : BinaryTypeCode.False);");
break;
case PropertyTypeKind.Double:
sb.AppendLine($"{i}context.WriteByte(BinaryTypeCode.Float64); context.WriteRaw({a});");
break;
case PropertyTypeKind.Single:
sb.AppendLine($"{i}context.WriteByte(BinaryTypeCode.Float32); context.WriteRaw({a});");
break;
case PropertyTypeKind.Decimal:
sb.AppendLine($"{i}context.WriteByte(BinaryTypeCode.Decimal); context.WriteDecimalBits({a});");
break;
case PropertyTypeKind.DateTime:
sb.AppendLine($"{i}context.WriteByte(BinaryTypeCode.DateTime); context.WriteDateTimeBits({a});");
break;
case PropertyTypeKind.Guid:
sb.AppendLine($"{i}context.WriteByte(BinaryTypeCode.Guid); context.WriteGuidBits({a});");
break;
case PropertyTypeKind.TimeSpan:
sb.AppendLine($"{i}context.WriteByte(BinaryTypeCode.TimeSpan); context.WriteRaw({a}.Ticks);");
break;
case PropertyTypeKind.DateTimeOffset:
sb.AppendLine($"{i}context.WriteByte(BinaryTypeCode.DateTimeOffset); context.WriteDateTimeOffsetBits({a});");
break;
case PropertyTypeKind.Byte:
sb.AppendLine($"{i}context.WriteByte(BinaryTypeCode.UInt8); context.WriteByte({a});");
break;
case PropertyTypeKind.Int16:
sb.AppendLine($"{i}context.WriteByte(BinaryTypeCode.Int16); context.WriteRaw({a});");
break;
case PropertyTypeKind.UInt16:
sb.AppendLine($"{i}context.WriteByte(BinaryTypeCode.UInt16); context.WriteRaw({a});");
break;
case PropertyTypeKind.UInt32:
sb.AppendLine($"{i}context.WriteByte(BinaryTypeCode.UInt32); context.WriteVarUInt({a});");
break;
case PropertyTypeKind.UInt64:
sb.AppendLine($"{i}context.WriteByte(BinaryTypeCode.UInt64); context.WriteVarULong({a});");
break;
case PropertyTypeKind.Enum:
sb.AppendLine($"{i}{{ var ev_{suffix} = (int){a}; context.WriteByte(BinaryTypeCode.Enum);");
sb.AppendLine($"{i} if (BinaryTypeCode.TryEncodeTinyInt(ev_{suffix}, out var te_{suffix})) context.WriteByte(te_{suffix});");
sb.AppendLine($"{i} else {{ context.WriteByte(BinaryTypeCode.Int32); context.WriteVarInt(ev_{suffix}); }} }}");
break;
}
}
///
/// Emits inline dictionary write. Wire format: [Dictionary][count][key₁ value₁ key₂ value₂ ...].
/// Keys/values are written with type codes matching runtime TryWritePrimitive/WriteValue.
/// Eliminates GetWrapper dictionary lookup for all inlineable key/value types.
///
private static void EmitDirectDictionaryWrite(StringBuilder sb, PropInfo p, string a, string i)
{
var s = p.Name;
var keyType = p.DictKeyTypeName ?? "object";
var valType = p.DictValueTypeName ?? "object";
// Reference type dictionaries can always be null at runtime regardless of nullable annotation
sb.AppendLine($"{i}if ({a} == null) context.WriteByte(BinaryTypeCode.PropertySkip);");
sb.AppendLine($"{i}else");
sb.AppendLine($"{i}{{");
sb.AppendLine($"{i} context.WriteByte(BinaryTypeCode.Dictionary);");
sb.AppendLine($"{i} context.WriteVarUInt((uint){a}.Count);");
sb.AppendLine($"{i} foreach (var kvp_{s} in {a})");
sb.AppendLine($"{i} {{");
var k = $"kvp_{s}.Key";
var v = $"kvp_{s}.Value";
var ii = i + " ";
// Write key
if (p.DictKeyKind == PropertyTypeKind.String)
{
if (p.InterningFlags == 0)
sb.AppendLine($"{ii}context.StringInternEligible = false;");
else
sb.AppendLine($"{ii}context.StringInternEligible = ({p.InterningFlags} & context.InternBit) != 0;");
sb.AppendLine($"{ii}AcBinarySerializer.WriteStringGenerated({k}, context);");
}
else if (IsMarkerless(p.DictKeyKind) || p.DictKeyKind == PropertyTypeKind.Enum)
{
EmitWritePrimitiveValue(sb, p.DictKeyKind, k, $"dk_{s}", ii);
}
else
{
sb.AppendLine($"{ii}AcBinarySerializer.WriteValueGenerated({k}, typeof({keyType}), context);");
}
// Write value
if (p.DictValueKind == PropertyTypeKind.String)
{
// String value: null → Null, non-null → WriteStringGenerated
sb.AppendLine($"{ii}if ({v} == null) context.WriteByte(BinaryTypeCode.Null);");
sb.AppendLine($"{ii}else");
sb.AppendLine($"{ii}{{");
if (p.InterningFlags == 0)
sb.AppendLine($"{ii} context.StringInternEligible = false;");
else
sb.AppendLine($"{ii} context.StringInternEligible = ({p.InterningFlags} & context.InternBit) != 0;");
sb.AppendLine($"{ii} AcBinarySerializer.WriteStringGenerated({v}, context);");
sb.AppendLine($"{ii}}}");
}
else if (IsMarkerless(p.DictValueKind) || p.DictValueKind == PropertyTypeKind.Enum)
{
EmitWritePrimitiveValue(sb, p.DictValueKind, v, $"dv_{s}", ii);
}
else if (p.DictValueKind == PropertyTypeKind.Complex && p.DictValueHasGeneratedWriter)
{
EmitDictValueComplexWrite(sb, p, v, s, ii);
}
else
{
// Fallback for non-inlineable value types
sb.AppendLine($"{ii}AcBinarySerializer.WriteValueGenerated({v}, typeof({valType}), context);");
}
sb.AppendLine($"{i} }}");
sb.AppendLine($"{i}}}");
}
///
/// Emits inline write for a Complex+SGen dictionary value with ref tracking and metadata support.
/// Delegates marker logic to runtime WriteObjectRefMarker/MetaMarker/FullMarker bridge.
///
private static void EmitDictValueComplexWrite(StringBuilder sb, PropInfo p, string v, string s, string i)
{
var writer = p.DictValueWriterClassName!;
sb.AppendLine($"{i}if ({v} == null) {{ context.WriteByte(BinaryTypeCode.Null); }}");
var dvRefSuffix = p.DictValueIsIId ? "IId" : "All";
if (!p.DictValueNeedsRefScan && !p.DictValueEnableMetadata)
{
// No ref, no metadata → always Object
sb.AppendLine($"{i}else {{ context.WriteByte(BinaryTypeCode.Object); {writer}.Instance.WriteProperties({v}, context); }}");
}
else if (p.DictValueNeedsRefScan && !p.DictValueEnableMetadata)
{
sb.AppendLine($"{i}else if (context.WriteObjectRefMarker{dvRefSuffix}()) {writer}.Instance.WriteProperties({v}, context);");
}
else if (!p.DictValueNeedsRefScan && p.DictValueEnableMetadata)
{
sb.AppendLine($"{i}else {{ context.WriteObjectMetaMarker({v}, {writer}.s_wrapperSlot); {writer}.Instance.WriteProperties({v}, context); }}");
}
else
{
sb.AppendLine($"{i}else if (context.WriteObjectFullMarker{dvRefSuffix}({v}, {writer}.s_wrapperSlot)) {writer}.Instance.WriteProperties({v}, context);");
}
}
private static void EmitSkip(StringBuilder sb, PropertyTypeKind k, string a, string typeName, string i)
{
switch (k)
{
case PropertyTypeKind.Int32:
{
// Mirrors runtime WritePropertyOrSkip → WriteInt32 (TinyInt optimization)
var s32 = a.Replace(".", "_");
sb.AppendLine($"{i}if ({a} == 0) context.WriteByte(BinaryTypeCode.PropertySkip);");
sb.AppendLine($"{i}else if (BinaryTypeCode.TryEncodeTinyInt({a}, out var ti_{s32})) context.WriteByte(ti_{s32});");
sb.AppendLine($"{i}else {{ context.WriteByte(BinaryTypeCode.Int32); context.WriteVarInt({a}); }}");
break;
}
case PropertyTypeKind.Int64:
{
// Mirrors runtime WritePropertyOrSkip → WriteInt64 → WriteInt32 (int range + TinyInt)
var s64 = a.Replace(".", "_");
sb.AppendLine($"{i}if ({a} == 0L) context.WriteByte(BinaryTypeCode.PropertySkip);");
sb.AppendLine($"{i}else if ({a} >= int.MinValue && {a} <= int.MaxValue)");
sb.AppendLine($"{i}{{");
sb.AppendLine($"{i} var iv_{s64} = (int){a};");
sb.AppendLine($"{i} if (BinaryTypeCode.TryEncodeTinyInt(iv_{s64}, out var ti_{s64})) context.WriteByte(ti_{s64});");
sb.AppendLine($"{i} else {{ context.WriteByte(BinaryTypeCode.Int32); context.WriteVarInt(iv_{s64}); }}");
sb.AppendLine($"{i}}}");
sb.AppendLine($"{i}else {{ context.WriteByte(BinaryTypeCode.Int64); context.WriteVarLong({a}); }}");
break;
}
case PropertyTypeKind.Boolean:
sb.AppendLine($"{i}if (!{a}) context.WriteByte(BinaryTypeCode.PropertySkip);");
sb.AppendLine($"{i}else context.WriteByte(BinaryTypeCode.True);");
break;
case PropertyTypeKind.Double:
sb.AppendLine($"{i}if ({a} == 0.0) context.WriteByte(BinaryTypeCode.PropertySkip);");
sb.AppendLine($"{i}else {{ context.WriteByte(BinaryTypeCode.Float64); context.WriteRaw({a}); }}");
break;
case PropertyTypeKind.Single:
sb.AppendLine($"{i}if ({a} == 0f) context.WriteByte(BinaryTypeCode.PropertySkip);");
sb.AppendLine($"{i}else {{ context.WriteByte(BinaryTypeCode.Float32); context.WriteRaw({a}); }}");
break;
case PropertyTypeKind.Decimal:
sb.AppendLine($"{i}if ({a} == 0m) context.WriteByte(BinaryTypeCode.PropertySkip);");
sb.AppendLine($"{i}else {{ context.WriteByte(BinaryTypeCode.Decimal); context.WriteDecimalBits({a}); }}");
break;
case PropertyTypeKind.DateTime:
sb.AppendLine($"{i}context.WriteByte(BinaryTypeCode.DateTime); context.WriteDateTimeBits({a});");
break;
case PropertyTypeKind.Guid:
sb.AppendLine($"{i}if ({a} == System.Guid.Empty) context.WriteByte(BinaryTypeCode.PropertySkip);");
sb.AppendLine($"{i}else {{ context.WriteByte(BinaryTypeCode.Guid); context.WriteGuidBits({a}); }}");
break;
case PropertyTypeKind.Byte:
sb.AppendLine($"{i}if ({a} == 0) context.WriteByte(BinaryTypeCode.PropertySkip);");
sb.AppendLine($"{i}else {{ context.WriteByte(BinaryTypeCode.UInt8); context.WriteByte({a}); }}");
break;
case PropertyTypeKind.Int16:
sb.AppendLine($"{i}if ({a} == 0) context.WriteByte(BinaryTypeCode.PropertySkip);");
sb.AppendLine($"{i}else {{ context.WriteByte(BinaryTypeCode.Int16); context.WriteRaw({a}); }}");
break;
case PropertyTypeKind.UInt16:
sb.AppendLine($"{i}if ({a} == 0) context.WriteByte(BinaryTypeCode.PropertySkip);");
sb.AppendLine($"{i}else {{ context.WriteByte(BinaryTypeCode.UInt16); context.WriteRaw({a}); }}");
break;
case PropertyTypeKind.UInt32:
sb.AppendLine($"{i}if ({a} == 0U) context.WriteByte(BinaryTypeCode.PropertySkip);");
sb.AppendLine($"{i}else {{ context.WriteByte(BinaryTypeCode.UInt32); context.WriteVarUInt({a}); }}");
break;
case PropertyTypeKind.UInt64:
sb.AppendLine($"{i}if ({a} == 0UL) context.WriteByte(BinaryTypeCode.PropertySkip);");
sb.AppendLine($"{i}else {{ context.WriteByte(BinaryTypeCode.UInt64); context.WriteVarULong({a}); }}");
break;
case PropertyTypeKind.Enum:
var s = a.Replace(".", "_");
sb.AppendLine($"{i}var ev_{s} = (int){a};");
sb.AppendLine($"{i}if (ev_{s} == 0) context.WriteByte(BinaryTypeCode.PropertySkip);");
sb.AppendLine($"{i}else if (BinaryTypeCode.TryEncodeTinyInt(ev_{s}, out var te_{s})) {{ context.WriteByte(BinaryTypeCode.Enum); context.WriteByte(te_{s}); }}");
sb.AppendLine($"{i}else {{ context.WriteByte(BinaryTypeCode.Enum); context.WriteByte(BinaryTypeCode.Int32); context.WriteVarInt(ev_{s}); }}");
break;
case PropertyTypeKind.TimeSpan:
sb.AppendLine($"{i}context.WriteByte(BinaryTypeCode.TimeSpan); context.WriteRaw({a}.Ticks);");
break;
case PropertyTypeKind.DateTimeOffset:
sb.AppendLine($"{i}context.WriteByte(BinaryTypeCode.DateTimeOffset); context.WriteDateTimeOffsetBits({a});");
break;
default:
sb.AppendLine($"{i}AcBinarySerializer.WriteValueGenerated({a}, typeof({typeName}), context);");
break;
}
}
private static void EmitVal(StringBuilder sb, PropertyTypeKind k, string a, string typeName, string i)
{
switch (k)
{
case PropertyTypeKind.Int32: sb.AppendLine($"{i}context.WriteByte(BinaryTypeCode.Int32); context.WriteVarInt({a});"); break;
case PropertyTypeKind.Int64: sb.AppendLine($"{i}context.WriteByte(BinaryTypeCode.Int64); context.WriteVarLong({a});"); break;
case PropertyTypeKind.Boolean: sb.AppendLine($"{i}context.WriteByte({a} ? BinaryTypeCode.True : BinaryTypeCode.False);"); break;
case PropertyTypeKind.Double: sb.AppendLine($"{i}context.WriteByte(BinaryTypeCode.Float64); context.WriteRaw({a});"); break;
case PropertyTypeKind.Single: sb.AppendLine($"{i}context.WriteByte(BinaryTypeCode.Float32); context.WriteRaw({a});"); break;
case PropertyTypeKind.Decimal: sb.AppendLine($"{i}context.WriteByte(BinaryTypeCode.Decimal); context.WriteDecimalBits({a});"); break;
case PropertyTypeKind.DateTime: sb.AppendLine($"{i}context.WriteByte(BinaryTypeCode.DateTime); context.WriteDateTimeBits({a});"); break;
case PropertyTypeKind.Guid: sb.AppendLine($"{i}context.WriteByte(BinaryTypeCode.Guid); context.WriteGuidBits({a});"); break;
default: EmitSkip(sb, k, a, typeName, i); break;
}
}
#region Reader Code Generation
///
/// Generates the IGeneratedBinaryReader implementation for a type.
/// Phase 1: handles markerless path (no UseMetadata). UseMetadata/ChainMode → runtime fallback.
/// Eliminates: GetWrapper dictionary lookup, CreateInstance delegate, property setter delegates,
/// AccessorType switch dispatch, ReadValue dispatch table.
///
private static string GenReader(SerializableClassInfo ci)
{
var sb = new StringBuilder(4096);
sb.AppendLine("// ");
sb.AppendLine("#nullable enable");
sb.AppendLine("using System.Runtime.CompilerServices;");
sb.AppendLine("using AyCode.Core.Serializers.Binaries;");
sb.AppendLine();
if (!string.IsNullOrEmpty(ci.Namespace))
sb.AppendLine($"namespace {ci.Namespace};");
sb.AppendLine();
sb.AppendLine($"internal sealed class {ci.ClassName}_GeneratedReader : IGeneratedBinaryReader");
sb.AppendLine("{");
sb.AppendLine($" internal static readonly {ci.ClassName}_GeneratedReader Instance = new();");
sb.AppendLine();
// ReadProperties — reads all properties into an existing instance (mirrors WriteProperties)
// No depth safety net on deserialize: wire format is linear + finite, the serializer-side counter
// already prevents pathological depth in well-formed payloads.
sb.AppendLine(" public void ReadProperties(object value, AcBinaryDeserializer.BinaryDeserializationContext context)");
sb.AppendLine(" where TInput : struct, IBinaryInputBase");
sb.AppendLine(" {");
sb.AppendLine($" var obj = Unsafe.As<{ci.FullTypeName}>(value);");
// Emit property reads — markerless for primitive types, markered for the rest
foreach (var p in ci.Properties)
{
sb.AppendLine();
EmitReadProp(sb, p, " ", ci.EnableMetadata);
}
sb.AppendLine(" }");
sb.AppendLine();
// ReadObject — IGeneratedBinaryReader implementation (delegates to ReadProperties)
sb.AppendLine(" public object? ReadObject(AcBinaryDeserializer.BinaryDeserializationContext context, int cacheIndex)");
sb.AppendLine(" where TInput : struct, IBinaryInputBase");
sb.AppendLine(" {");
sb.AppendLine($" var obj = new {ci.FullTypeName}();");
sb.AppendLine(" if (cacheIndex >= 0)");
sb.AppendLine(" context.RegisterInternedValueAt(cacheIndex, obj);");
sb.AppendLine(" ReadProperties(obj, context);");
sb.AppendLine(" return obj;");
sb.AppendLine(" }");
sb.AppendLine("}");
return sb.ToString();
}
///
/// Emits inline read code for a single property.
/// Markerless types: read raw value directly (no type code in stream).
/// Markered types: read type code byte, then dispatch.
/// Mirrors the serializer's EmitProp symmetry.
///
private static void EmitReadProp(StringBuilder sb, PropInfo p, string i, bool enableMetadata)
{
var a = $"obj.{p.Name}";
// Markerless types: read raw value directly — mirrors EmitMarkerless in writer
if (IsMarkerless(p.TypeKind))
{
if (p.TypeKind == PropertyTypeKind.Enum)
sb.AppendLine($"{i}{{ var ev = context.ReadVarInt(); {a} = Unsafe.As(ref ev); }}");
else
EmitReadMarkerless(sb, p.TypeKind, a, i);
return;
}
// String FastWire markerless fast-path: int32 sentinel header (-1 = null, 0 = empty, N > 0 = content).
// Wire-symmetric with `WriteStringGenerated` (SGen) and `WriteStringUtf16Markerless` (Runtime).
// Skips the typeCode-read entirely in FastWire mode; falls through to markered dispatch in Compact.
if (p.TypeKind == PropertyTypeKind.String)
{
sb.AppendLine($"{i}if (context.FastWire)");
sb.AppendLine($"{i}{{");
sb.AppendLine($"{i} {a} = context.ReadStringUtf16Markerless()!;");
sb.AppendLine($"{i}}}");
sb.AppendLine($"{i}else");
sb.AppendLine($"{i}{{");
sb.AppendLine($"{i} var tc_{p.Name} = context.ReadByte();");
sb.AppendLine($"{i} if (tc_{p.Name} != BinaryTypeCode.PropertySkip)");
sb.AppendLine($"{i} {{");
EmitReadString(sb, a, $"tc_{p.Name}", i + " ");
sb.AppendLine($"{i} }}");
sb.AppendLine($"{i}}}");
return;
}
// Markered types: read type code, then dispatch
var tc = $"tc_{p.Name}";
sb.AppendLine($"{i}var {tc} = context.ReadByte();");
// PropertySkip → leave default
sb.AppendLine($"{i}if ({tc} != BinaryTypeCode.PropertySkip)");
sb.AppendLine($"{i}{{");
// Nullable value types
if (IsNullableVTKind(p.TypeKind))
{
sb.AppendLine($"{i} if ({tc} == BinaryTypeCode.Null) {{ /* null */ }}");
sb.AppendLine($"{i} else");
sb.AppendLine($"{i} {{");
EmitReadMarkeredValue(sb, Underlying(p.TypeKind), a, tc, i + " ", p, nullable: true);
sb.AppendLine($"{i} }}");
}
else
{
switch (p.TypeKind)
{
case PropertyTypeKind.String:
EmitReadString(sb, a, tc, i + " ");
break;
case PropertyTypeKind.Complex:
EmitReadComplex(sb, p, a, tc, i + " ");
break;
case PropertyTypeKind.Collection:
EmitReadCollection(sb, p, a, tc, i + " ");
break;
case PropertyTypeKind.Dictionary:
EmitReadDictionary(sb, p, a, tc, i + " ");
break;
default:
// Unknown markered type (char, sbyte, etc.) — rewind + runtime fallback
sb.AppendLine($"{i} context._position--;");
if (p.IsNullable)
sb.AppendLine($"{i} {a} = ({p.TypeNameForTypeof}?)AcBinaryDeserializer.ReadValueGenerated(context, typeof({p.TypeNameForTypeof}));");
else
sb.AppendLine($"{i} {a} = ({p.TypeNameForTypeof})AcBinaryDeserializer.ReadValueGenerated(context, typeof({p.TypeNameForTypeof}))!;");
break;
}
}
sb.AppendLine($"{i}}}");
}
///
/// Emits raw value read — no type code in stream. Mirrors EmitMarkerless exactly.
///
private static void EmitReadMarkerless(StringBuilder sb, PropertyTypeKind k, string a, string i)
{
switch (k)
{
case PropertyTypeKind.Int32: sb.AppendLine($"{i}{a} = context.ReadVarInt();"); break;
case PropertyTypeKind.Int64: sb.AppendLine($"{i}{a} = context.ReadVarLong();"); break;
case PropertyTypeKind.Double: sb.AppendLine($"{i}{a} = context.ReadDoubleUnsafe();"); break;
case PropertyTypeKind.Single: sb.AppendLine($"{i}{a} = context.ReadSingleUnsafe();"); break;
case PropertyTypeKind.Decimal: sb.AppendLine($"{i}{a} = context.ReadDecimalUnsafe();"); break;
case PropertyTypeKind.DateTime: sb.AppendLine($"{i}{a} = context.ReadDateTimeUnsafe();"); break;
case PropertyTypeKind.Guid: sb.AppendLine($"{i}{a} = context.ReadGuidUnsafe();"); break;
case PropertyTypeKind.Byte: sb.AppendLine($"{i}{a} = context.ReadByte();"); break;
case PropertyTypeKind.Int16: sb.AppendLine($"{i}{a} = context.ReadInt16Unsafe();"); break;
case PropertyTypeKind.UInt16: sb.AppendLine($"{i}{a} = context.ReadUInt16Unsafe();"); break;
case PropertyTypeKind.UInt32: sb.AppendLine($"{i}{a} = context.ReadVarUInt();"); break;
case PropertyTypeKind.UInt64: sb.AppendLine($"{i}{a} = context.ReadVarULong();"); break;
case PropertyTypeKind.TimeSpan: sb.AppendLine($"{i}{a} = new System.TimeSpan(context.ReadRaw());"); break;
case PropertyTypeKind.DateTimeOffset: sb.AppendLine($"{i}{a} = context.ReadDateTimeOffsetUnsafe();"); break;
case PropertyTypeKind.Boolean: sb.AppendLine($"{i}{a} = context.ReadByte() != 0;"); break;
}
}
///
/// Emits inline string read from type code. Handles all H2Q6 (v3 wire format) string markers:
/// FixStrAscii (ASCII short, 135-166), StringAscii (ASCII long, 167),
/// StringSmall/Medium/Big (non-ASCII tiers, 91/94/103),
/// StringInternFirstSmall/Medium (interning tiers, 104/105),
/// StringInterned (cache ref, 92), StringEmpty (93), Null.
///
/// FixStrAscii is checked first as the hot path for short ASCII property names; non-ASCII
/// tier markers carry both charLen and utf8Len in fixed-width headers (1-pass decode).
///
private static void EmitReadString(StringBuilder sb, string a, string tc, string i)
{
// FixStrAscii is the hot path — most short strings (property names) are ASCII.
sb.AppendLine($"{i}if (BinaryTypeCode.IsFixStrAscii({tc}))");
sb.AppendLine($"{i}{{");
sb.AppendLine($"{i} var falen = BinaryTypeCode.DecodeFixStrAsciiLength({tc});");
sb.AppendLine($"{i} {a} = falen == 0 ? string.Empty : context.ReadAsciiBytesAsString(falen);");
sb.AppendLine($"{i}}}");
// Switch gives O(1) dispatch via JIT jump table for the remaining markers.
sb.AppendLine($"{i}else switch ({tc})");
sb.AppendLine($"{i}{{");
sb.AppendLine($"{i} case BinaryTypeCode.StringInterned:");
sb.AppendLine($"{i} {a} = context.GetInternedString((int)context.ReadVarUInt());");
sb.AppendLine($"{i} break;");
// H2Q6 StringSmall — non-ASCII utf8Len ≤ 255 — wire: [charLen:8][utf8Len:8][bytes], 1-pass decode.
// FastWire mode shares the marker value (=91); reader dispatches by mode.
sb.AppendLine($"{i} case BinaryTypeCode.StringSmall:");
sb.AppendLine($"{i} {{");
sb.AppendLine($"{i} if (context.FastWire)");
sb.AppendLine($"{i} {{");
sb.AppendLine($"{i} // Collection/dictionary element strings: markered FastWire body — int32 charLen + UTF-16 bytes.");
sb.AppendLine($"{i} // (Property-level strings take a separate markerless path in EmitReadProp; this case handles");
sb.AppendLine($"{i} // the markered StringSmall variant emitted by WriteStringWithDispatch from collection/runtime paths.)");
sb.AppendLine($"{i} var fwlen = context.ReadInt32Unsafe();");
sb.AppendLine($"{i} {a} = context.ReadStringUtf16(fwlen);");
sb.AppendLine($"{i} }}");
sb.AppendLine($"{i} else");
sb.AppendLine($"{i} {{");
sb.AppendLine($"{i} var sshdr = context.ReadTwoBytesUnsafe();");
sb.AppendLine($"{i} var sscharLen = (byte)sshdr;");
sb.AppendLine($"{i} var ssbyteLen = (byte)(sshdr >> 8);");
sb.AppendLine($"{i} {a} = ssbyteLen == 0 ? string.Empty : context.ReadStringUtf8WithCharLen(sscharLen, ssbyteLen);");
sb.AppendLine($"{i} }}");
sb.AppendLine($"{i} break;");
sb.AppendLine($"{i} }}");
// H2Q6 StringMedium — utf8Len ≤ 65535 — single uint read packs charLen:16 + utf8Len:16
sb.AppendLine($"{i} case BinaryTypeCode.StringMedium:");
sb.AppendLine($"{i} {{");
sb.AppendLine($"{i} var smpacked = context.ReadUInt32Unsafe();");
sb.AppendLine($"{i} var smcharLen = (ushort)smpacked;");
sb.AppendLine($"{i} var smbyteLen = (ushort)(smpacked >> 16);");
sb.AppendLine($"{i} {a} = smbyteLen == 0 ? string.Empty : context.ReadStringUtf8WithCharLen(smcharLen, smbyteLen);");
sb.AppendLine($"{i} break;");
sb.AppendLine($"{i} }}");
// H2Q6 StringBig — utf8Len > 65535 — single ulong read packs charLen:32 + utf8Len:32
sb.AppendLine($"{i} case BinaryTypeCode.StringBig:");
sb.AppendLine($"{i} {{");
sb.AppendLine($"{i} var sbpacked = context.ReadUInt64Unsafe();");
sb.AppendLine($"{i} var sbcharLen = (int)(uint)sbpacked;");
sb.AppendLine($"{i} var sbbyteLen = (int)(uint)(sbpacked >> 32);");
sb.AppendLine($"{i} {a} = sbbyteLen == 0 ? string.Empty : context.ReadStringUtf8WithCharLen(sbcharLen, sbbyteLen);");
sb.AppendLine($"{i} break;");
sb.AppendLine($"{i} }}");
sb.AppendLine($"{i} case BinaryTypeCode.StringAscii:");
sb.AppendLine($"{i} {{");
sb.AppendLine($"{i} var salen = (int)context.ReadVarUInt();");
sb.AppendLine($"{i} {a} = salen == 0 ? string.Empty : context.ReadAsciiBytesAsString(salen);");
sb.AppendLine($"{i} break;");
sb.AppendLine($"{i} }}");
// H2Q6 interning — Small tier
sb.AppendLine($"{i} case BinaryTypeCode.StringInternFirstSmall:");
sb.AppendLine($"{i} {{");
sb.AppendLine($"{i} context.DisableStringCaching();");
sb.AppendLine($"{i} var iscIdx = (int)context.ReadVarUInt();");
sb.AppendLine($"{i} var ishdr = context.ReadTwoBytesUnsafe();");
sb.AppendLine($"{i} var ischarLen = (byte)ishdr;");
sb.AppendLine($"{i} var isbyteLen = (byte)(ishdr >> 8);");
sb.AppendLine($"{i} var isv = isbyteLen == 0 ? string.Empty : context.ReadStringUtf8WithCharLen(ischarLen, isbyteLen);");
sb.AppendLine($"{i} context.RegisterInternedValueAt(iscIdx, isv);");
sb.AppendLine($"{i} {a} = isv;");
sb.AppendLine($"{i} break;");
sb.AppendLine($"{i} }}");
// H2Q6 interning — Medium tier — single uint header read
sb.AppendLine($"{i} case BinaryTypeCode.StringInternFirstMedium:");
sb.AppendLine($"{i} {{");
sb.AppendLine($"{i} context.DisableStringCaching();");
sb.AppendLine($"{i} var imcIdx = (int)context.ReadVarUInt();");
sb.AppendLine($"{i} var impacked = context.ReadUInt32Unsafe();");
sb.AppendLine($"{i} var imcharLen = (ushort)impacked;");
sb.AppendLine($"{i} var imbyteLen = (ushort)(impacked >> 16);");
sb.AppendLine($"{i} var imv = imbyteLen == 0 ? string.Empty : context.ReadStringUtf8WithCharLen(imcharLen, imbyteLen);");
sb.AppendLine($"{i} context.RegisterInternedValueAt(imcIdx, imv);");
sb.AppendLine($"{i} {a} = imv;");
sb.AppendLine($"{i} break;");
sb.AppendLine($"{i} }}");
sb.AppendLine($"{i} case BinaryTypeCode.Null:");
sb.AppendLine($"{i} {a} = null;");
sb.AppendLine($"{i} break;");
sb.AppendLine($"{i} case BinaryTypeCode.StringEmpty:");
sb.AppendLine($"{i} {a} = string.Empty;");
sb.AppendLine($"{i} break;");
sb.AppendLine($"{i}}}");
}
///
/// Emits inline read for a Complex property.
/// SGen reader only runs in non-metadata mode → ObjectWithMetadata never appears.
/// Compile-time ChildNeedsRefScan eliminates ObjectRefFirst/ObjectRef when provably unused.
/// Non-nullable + no ref → ZERO branches (tc consumed but ignored).
/// No SGen → runtime fallback via ReadValueGenerated.
///
private static void EmitReadComplex(StringBuilder sb, PropInfo p, string a, string tc, string i)
{
if (!p.HasGeneratedWriter)
{
// No SGen reader — runtime fallback (rewind + ReadValueGenerated)
if (p.IsNullable)
{
sb.AppendLine($"{i}if ({tc} == BinaryTypeCode.Null) {a} = null;");
sb.AppendLine($"{i}else");
sb.AppendLine($"{i}{{");
sb.AppendLine($"{i} context._position--;");
sb.AppendLine($"{i} {a} = ({p.TypeNameForTypeof}?)AcBinaryDeserializer.ReadValueGenerated(context, typeof({p.TypeNameForTypeof}));");
sb.AppendLine($"{i}}}");
}
else
{
sb.AppendLine($"{i}context._position--;");
sb.AppendLine($"{i}{a} = ({p.TypeNameForTypeof})AcBinaryDeserializer.ReadValueGenerated(context, typeof({p.TypeNameForTypeof}))!;");
}
return;
}
var reader = p.WriterClassName!.Replace("_GeneratedWriter", "_GeneratedReader");
var cast = $"({p.TypeNameForTypeof})";
if (!p.ChildNeedsRefScan)
{
// Compile-time proven: child never tracked → only Object (+ Null for nullable) in stream
// Inline: parent creates instance, calls ReadProperties directly (mirrors EmitDirectObjectWrite)
// FixObj slot bytes (0..SlotCount-1) are also valid markers here — populate slot cache
// to keep _nextRuntimeSlot in sync with the serializer's _nextTypeSlot counter.
if (p.IsNullable)
{
sb.AppendLine($"{i}if ({tc} == BinaryTypeCode.Null) {{ /* null */ }}");
sb.AppendLine($"{i}else");
sb.AppendLine($"{i}{{");
sb.AppendLine($"{i} if ({tc} < BinaryTypeCode.Object) {{ context.GetWrapper(typeof({p.TypeNameForTypeof}), {tc}); if ({tc} >= context._nextRuntimeSlot) context._nextRuntimeSlot = {tc} + 1; }}");
sb.AppendLine($"{i} var rc_{p.Name} = new {p.TypeNameForTypeof}();");
sb.AppendLine($"{i} {reader}.Instance.ReadProperties(rc_{p.Name}, context);");
sb.AppendLine($"{i} {a} = rc_{p.Name};");
sb.AppendLine($"{i}}}");
}
else
{
// ZERO branches — tc is always Object or FixObj
sb.AppendLine($"{i}{{");
sb.AppendLine($"{i} if ({tc} < BinaryTypeCode.Object) {{ context.GetWrapper(typeof({p.TypeNameForTypeof}), {tc}); if ({tc} >= context._nextRuntimeSlot) context._nextRuntimeSlot = {tc} + 1; }}");
sb.AppendLine($"{i} var rc_{p.Name} = new {p.TypeNameForTypeof}();");
sb.AppendLine($"{i} {reader}.Instance.ReadProperties(rc_{p.Name}, context);");
sb.AppendLine($"{i} {a} = rc_{p.Name};");
sb.AppendLine($"{i}}}");
}
}
else
{
// Ref tracking possible — switch on tc (Object / ObjectRefFirst / [Null] / ObjectRef /