From 2468d7361c11d4cf6c309e83cade3002f53f0836 Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Tue, 1 Dec 2026 12:51:46 -0800 Subject: [PATCH 1/5] Generator: emit the template-shaped text from raw string literals, and tidy the specs The emitter wrote the header, the counters, the interceptors, the model's slot table, Bind, Resolve and the trusted reader one AppendLine at a time. They are now raw string literals with the generated text laid out as it is emitted; only the parts computed per slot (EmitRead, Statement) stay code. The generated output is byte-identical. Also: - SlotSpec.Parameter was written and never read: removed. - The model list and its ids are built with Distinct and OrderBy instead of a dictionary used as a set plus a sort. - The partial model's settable names are joined with string.Join. - A redundant local in ModelReader is folded into its test. Co-Authored-By: Claude Opus 5.5 --- Source/Generator/Emitter.cs | 371 ++++++++++++++++++-------------- Source/Generator/ModelReader.cs | 11 +- Source/Generator/Specs.cs | 2 - 3 files changed, 217 insertions(+), 167 deletions(-) diff --git a/Source/Generator/Emitter.cs b/Source/Generator/Emitter.cs index 195ab98b..1877a8c7 100644 --- a/Source/Generator/Emitter.cs +++ b/Source/Generator/Emitter.cs @@ -32,34 +32,33 @@ static class Emitter public static string Emit(IReadOnlyList sites, Options options) { var sb = new StringBuilder(); - sb.AppendLine("// "); - sb.AppendLine("// Open.Database.Extensions source generator: Map() served by generated row readers."); - sb.AppendLine("#nullable disable"); - sb.AppendLine("#pragma warning disable"); - sb.AppendLine(); - sb.AppendLine("namespace System.Runtime.CompilerServices"); - sb.AppendLine("{"); - sb.AppendLine("\t[global::System.AttributeUsage(global::System.AttributeTargets.Method, AllowMultiple = true)]"); - sb.AppendLine("\tfile sealed class InterceptsLocationAttribute(int version, string data) : global::System.Attribute { }"); - sb.AppendLine("}"); - sb.AppendLine(); - sb.AppendLine("namespace Open.Database.Extensions.Generated"); - sb.AppendLine("{"); + sb.AppendLine(""" +// +// Open.Database.Extensions source generator: Map() served by generated row readers. +#nullable disable +#pragma warning disable + +namespace System.Runtime.CompilerServices +{ + [global::System.AttributeUsage(global::System.AttributeTargets.Method, AllowMultiple = true)] + file sealed class InterceptsLocationAttribute(int version, string data) : global::System.Attribute { } +} + +namespace Open.Database.Extensions.Generated +{ +"""); if (options.Counters) EmitCounters(sb); // One class per model type, in a stable order. - var models = new List(); - var ids = new Dictionary(); - foreach (Site s in sites) - { - if (ids.ContainsKey(s.Model)) continue; - ids.Add(s.Model, ""); - models.Add(s.Model); - } + List models = sites + .Select(static s => s.Model) + .Distinct() + .OrderBy(static m => m.Type, StringComparer.Ordinal) + .ToList(); - models.Sort((a, b) => string.CompareOrdinal(a.Type, b.Type)); - for (int i = 0; i < models.Count; i++) ids[models[i]] = "M" + i + "_" + Identifier(models[i].Type); + var ids = new Dictionary(); + for (int i = 0; i < models.Count; i++) ids.Add(models[i], "M" + i + "_" + Identifier(models[i].Type)); EmitInterceptors(sb, sites, ids, options); EmitShared(sb); @@ -79,52 +78,60 @@ static string Identifier(string type) return sb.ToString(); } - static void EmitCounters(StringBuilder sb) + static void EmitCounters(StringBuilder sb) => sb.AppendLine(""" + /// Test-only counters (OdxGeneratorCounters=true): how often the generated code was called and what it did. Never in a shipped build. + /// Counted per call and per result set only: a row reader counts nothing. + public static class OdxGeneratedCounters { - sb.AppendLine("\t/// Test-only counters (OdxGeneratorCounters=true): how often the generated code was called and what it did. Never in a shipped build."); - sb.AppendLine("\t/// Counted per call and per result set only: a row reader counts nothing."); - sb.AppendLine("\tpublic static class OdxGeneratedCounters"); - sb.AppendLine("\t{"); - sb.AppendLine("\t\t/// Interceptor calls (a Map<T>() call that ran the generated code)."); - sb.AppendLine("\t\tpublic static long Intercepted;"); - sb.AppendLine("\t\t/// Result sets bound and served by generated row readers."); - sb.AppendLine("\t\tpublic static long Served;"); - sb.AppendLine("\t\t/// Result sets bound and declined to the runtime map."); - sb.AppendLine("\t\tpublic static long Declined;"); - sb.AppendLine("\t\t/// Result sets bound, by read mode: 0 runtime, 1 full, 2 guarded, 3 trusted model, 4 identity (constant ordinals)."); - sb.AppendLine("\t\tpublic static readonly long[] Modes = new long[5];"); - sb.AppendLine("\t}"); - sb.AppendLine(); + /// Interceptor calls (a Map<T>() call that ran the generated code). + public static long Intercepted; + /// Result sets bound and served by generated row readers. + public static long Served; + /// Result sets bound and declined to the runtime map. + public static long Declined; + /// Result sets bound, by read mode: 0 runtime, 1 full, 2 guarded, 3 trusted model, 4 identity (constant ordinals). + public static readonly long[] Modes = new long[5]; } +"""); + static void EmitInterceptors(StringBuilder sb, IReadOnlyList sites, Dictionary ids, Options options) { - sb.AppendLine("\tfile static class OdxInterceptors"); - sb.AppendLine("\t{"); + sb.AppendLine(""" + file static class OdxInterceptors + { +"""); + for (int i = 0; i < sites.Count; i++) { Site s = sites[i]; - sb.AppendLine($"\t\t[global::System.Runtime.CompilerServices.InterceptsLocation({s.Version}, \"{s.Data}\")]"); (string signature, string? constraint, string call) = Interceptor(s, i, ids[s.Model]); - sb.AppendLine("\t\t" + signature); + sb.AppendLine($$""" + [global::System.Runtime.CompilerServices.InterceptsLocation({{s.Version}}, "{{s.Data}}")] + {{signature}} +"""); + if (constraint is not null) sb.AppendLine("\t\t\t" + constraint); - if (options.Counters) - { - sb.AppendLine("\t\t{"); - sb.AppendLine("\t\t\tglobal::System.Threading.Interlocked.Increment(ref OdxGeneratedCounters.Intercepted);"); - sb.AppendLine($"\t\t\treturn {call};"); - sb.AppendLine("\t\t}"); - } - else - { - sb.AppendLine($"\t\t\t=> {call};"); - } - sb.AppendLine(); + // A counted interceptor needs a block for the increment; the plain one is an expression body. + sb.AppendLine(options.Counters + ? $$""" + { + global::System.Threading.Interlocked.Increment(ref OdxGeneratedCounters.Intercepted); + return {{call}}; } - sb.AppendLine("\t}"); - sb.AppendLine(); +""" + : $$""" + => {{call}}; + +"""); + } + + sb.AppendLine(""" + } + +"""); } // An interceptor takes the receiver as the method it replaces does: by value for a class or an extension's parameter, by `in` for the @@ -367,40 +374,48 @@ static void EmitModel(StringBuilder sb, ModelSpec m, string id, Options options) int[] literal = LiteralOrdinals(m); string reader = $"global::System.Func<{DbReader}, {T}>"; - sb.AppendLine($"\t// {T}"); - sb.AppendLine($"\tfile sealed class {id}"); - sb.AppendLine("\t{"); - // ---- the map ---- // Made on first use, not by a static initializer: a model the runtime cannot map throws at the call, as Map() throws, not a TypeInitializationException. // A race makes two maps, each correct; the last one stays. - sb.AppendLine($"\t\t// The map every intercepted call of {m.Name} passes to Map(RowMap?): Core calls Bind once per result set."); - sb.AppendLine($"\t\tstatic {Ns}.RowMap<{T}> s_map;"); - sb.AppendLine(); - sb.AppendLine($"\t\tpublic static {Ns}.RowMap<{T}> Map => s_map ??= {Ns}.Generation.GeneratedRowMap.Create<{T}>(Bind);"); - sb.AppendLine(); + sb.AppendLine($$""" + // {{T}} + file sealed class {{id}} + { + // The map every intercepted call of {{m.Name}} passes to Map(RowMap?): Core calls Bind once per result set. + static {{Ns}}.RowMap<{{T}}> s_map; + + public static {{Ns}}.RowMap<{{T}}> Map => s_map ??= {{Ns}}.Generation.GeneratedRowMap.Create<{{T}}>(Bind); + +"""); if (m.Partial is { } shape) { // Another source generator may have added to a partial model what this one could not see, and the readers would not set it. Checked once // per type against the built type; if it differs, Bind serves nothing and the runtime map reads this model. - string names = string.Concat(shape.Settable.Items.Select(static n => ", " + Str(n))); - sb.AppendLine($"\t\tstatic readonly bool s_asSeen = OdxShape.AsSeen(typeof({T}).GetProperties(global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.Instance),"); - sb.AppendLine($"\t\t\ttypeof({T}).GetConstructors().Length, {shape.Constructors}, new string[] {{ {(names.Length == 0 ? "" : names.Substring(2))} }});"); - sb.AppendLine(); + string names = string.Join(", ", shape.Settable.Items.Select(Str)); + sb.AppendLine($$""" + static readonly bool s_asSeen = OdxShape.AsSeen(typeof({{T}}).GetProperties(global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.Instance), + typeof({{T}}).GetConstructors().Length, {{shape.Constructors}}, new string[] { {{names}} }); + +"""); } if (m.AllOrdered) { EmitTrusted(sb, m, options, styleB, literal, reader); - sb.AppendLine("\t}"); - sb.AppendLine(); + sb.AppendLine(""" + } + +"""); return; } // ---- the slot table ---- - sb.AppendLine("\t\tstatic readonly OdxSlot[] Slots ="); - sb.AppendLine("\t\t["); + sb.AppendLine(""" + static readonly OdxSlot[] Slots = + [ +"""); + foreach (SlotSpec s in slots) { // Invariant: Order is -1 where none is declared, and a culture's minus sign need not be the one C# reads. @@ -408,52 +423,66 @@ static void EmitModel(StringBuilder sb, ModelSpec m, string id, Options options) sb.AppendLine($"\t\t\tnew({Str(s.Name)}, {Str(s.Column)}, {order}, {Bool(s.NotMapped)}, {Bool(s.Required)}),"); } - sb.AppendLine("\t\t];"); - sb.AppendLine(); - // The layouts met lately (a few, as queries over one model with different column lists alternate); a slot is replaced in turn. A layout is // complete before it is published, and references are swapped atomically, so concurrent queries share them safely. - sb.AppendLine("\t\tstatic readonly Layout[] s_layouts = new Layout[8];"); - sb.AppendLine("\t\tstatic int s_next;"); - sb.AppendLine(); + sb.AppendLine(""" + ]; + + static readonly Layout[] s_layouts = new Layout[8]; + static int s_next; + +"""); // ---- Bind: once per result set ---- - sb.AppendLine("\t\t// Once per result set (Core's loop, after its first row is read): the row reader of this layout, or null for the runtime map."); - sb.AppendLine($"\t\tstatic {reader} Bind({DbReader} r)"); - sb.AppendLine("\t\t{"); + sb.AppendLine($$""" + // Once per result set (Core's loop, after its first row is read): the row reader of this layout, or null for the runtime map. + static {{reader}} Bind({{DbReader}} r) + { +"""); + if (m.Partial is not null) sb.AppendLine("\t\t\t" + Unseen(options)); - sb.AppendLine("\t\t\tLayout[] layouts = s_layouts;"); - sb.AppendLine("\t\t\tfor (int i = 0; i < layouts.Length; i++)"); - sb.AppendLine("\t\t\t{"); - sb.AppendLine("\t\t\t\tLayout known = global::System.Threading.Volatile.Read(ref layouts[i]);"); - sb.AppendLine($"\t\t\t\tif (known != null && known.Matches(r)) return {(options.Counters ? "Count(known)" : "known.Row")};"); - sb.AppendLine("\t\t\t}"); - sb.AppendLine(); - sb.AppendLine("\t\t\tLayout l = Resolve(r);"); - sb.AppendLine("\t\t\tglobal::System.Threading.Volatile.Write(ref layouts[unchecked((int)((uint)global::System.Threading.Interlocked.Increment(ref s_next) % (uint)layouts.Length))], l);"); - sb.AppendLine($"\t\t\treturn {(options.Counters ? "Count(l)" : "l.Row")};"); - sb.AppendLine("\t\t}"); - sb.AppendLine(); + + string known = options.Counters ? "Count(known)" : "known.Row"; + string resolved = options.Counters ? "Count(l)" : "l.Row"; + sb.AppendLine($$""" + Layout[] layouts = s_layouts; + for (int i = 0; i < layouts.Length; i++) + { + Layout known = global::System.Threading.Volatile.Read(ref layouts[i]); + if (known != null && known.Matches(r)) return {{known}}; + } + + Layout l = Resolve(r); + global::System.Threading.Volatile.Write(ref layouts[unchecked((int)((uint)global::System.Threading.Interlocked.Increment(ref s_next) % (uint)layouts.Length))], l); + return {{resolved}}; + } + +"""); if (options.Counters) { - sb.AppendLine($"\t\tstatic {reader} Count(Layout l)"); - sb.AppendLine("\t\t{"); - sb.AppendLine("\t\t\tglobal::System.Threading.Interlocked.Increment(ref l.Row == null ? ref OdxGeneratedCounters.Declined : ref OdxGeneratedCounters.Served);"); - sb.AppendLine("\t\t\tglobal::System.Threading.Interlocked.Increment(ref OdxGeneratedCounters.Modes[l.Mode]);"); - sb.AppendLine("\t\t\treturn l.Row;"); - sb.AppendLine("\t\t}"); - sb.AppendLine(); + sb.AppendLine($$""" + static {{reader}} Count(Layout l) + { + global::System.Threading.Interlocked.Increment(ref l.Row == null ? ref OdxGeneratedCounters.Declined : ref OdxGeneratedCounters.Served); + global::System.Threading.Interlocked.Increment(ref OdxGeneratedCounters.Modes[l.Mode]); + return l.Row; + } + +"""); } // ---- Resolve: once per new layout ---- - sb.AppendLine($"\t\tstatic Layout Resolve({DbReader} r)"); - sb.AppendLine("\t\t{"); - sb.AppendLine("\t\t\tvar l = new Layout(r);"); - sb.AppendLine($"\t\t\tint[] o = OdxMatch.Slots(l.Names, Slots, {Bool(m.Decorated)});"); - sb.AppendLine("\t\t\tif (o == null) return l; // A check the runtime throws for: it serves (throws) it."); - sb.AppendLine("\t\t\tbool full = true, literal = true, ascending = true;"); - sb.AppendLine("\t\t\tint last = -1;"); + sb.AppendLine($$""" + static Layout Resolve({{DbReader}} r) + { + var l = new Layout(r); + int[] o = OdxMatch.Slots(l.Names, Slots, {{Bool(m.Decorated)}}); + if (o == null) return l; // A check the runtime throws for: it serves (throws) it. + bool full = true, literal = true, ascending = true; + int last = -1; +"""); + for (int k = 0; k < slots.Length; k++) { SlotSpec s = slots[k]; @@ -463,70 +492,87 @@ static void EmitModel(StringBuilder sb, ModelSpec m, string id, Options options) continue; } - sb.AppendLine($"\t\t\tl.O{k} = o[{k}];"); - sb.AppendLine($"\t\t\tif (o[{k}] >= 0)"); - sb.AppendLine("\t\t\t{"); - sb.AppendLine($"\t\t\t\tif (o[{k}] <= last) ascending = false;"); - sb.AppendLine($"\t\t\t\tlast = o[{k}];"); - sb.AppendLine($"\t\t\t\tif (o[{k}] != {literal[k]}) literal = false;"); - sb.AppendLine("\t\t\t}"); - sb.AppendLine("\t\t\telse"); - sb.AppendLine("\t\t\t{"); - if (s.InitBound) - sb.AppendLine("\t\t\t\treturn l; // An init-only member with no column keeps what its type gives it, which an object initializer cannot leave alone."); + string absent = s.InitBound + ? "return l; // An init-only member with no column keeps what its type gives it, which an object initializer cannot leave alone." + : "full = false;"; + + sb.AppendLine($$""" + l.O{{k}} = o[{{k}}]; + if (o[{{k}}] >= 0) + { + if (o[{{k}}] <= last) ascending = false; + last = o[{{k}}]; + if (o[{{k}}] != {{literal[k]}}) literal = false; + } else - sb.AppendLine("\t\t\t\tfull = false;"); - sb.AppendLine("\t\t\t}"); + { + {{absent}} + } +"""); } - sb.AppendLine("\t\t\tl.Ordinals = o;"); // Every slot fed in ascending column order: constant ordinals when each sits at its declaration position (4, the identity: read in slot order, // which is column order), else the layout's (1). Anything else is guarded (2), read in column order. - sb.AppendLine("\t\t\tl.Mode = !full || !ascending ? 2 : literal ? 4 : 1;"); - sb.AppendLine("\t\t\tif (l.Mode == 2) l.Sequence = OdxMatch.Sequence(o, Slots);"); - sb.AppendLine("\t\t\t// The row reader of the mode, chosen here once: the rows never ask which mode they are in."); - sb.AppendLine("\t\t\tswitch (l.Mode)"); - sb.AppendLine("\t\t\t{"); - sb.AppendLine("\t\t\t\tcase 4: l.Row = ReadLiteral; break;"); - sb.AppendLine("\t\t\t\tcase 1: l.Row = l.ReadFull; break;"); - sb.AppendLine("\t\t\t\tcase 2: l.Row = l.ReadGuarded; break;"); - sb.AppendLine("\t\t\t}"); - sb.AppendLine(); - sb.AppendLine("\t\t\treturn l;"); - sb.AppendLine("\t\t}"); - sb.AppendLine(); + sb.AppendLine(""" + l.Ordinals = o; + l.Mode = !full || !ascending ? 2 : literal ? 4 : 1; + if (l.Mode == 2) l.Sequence = OdxMatch.Sequence(o, Slots); + // The row reader of the mode, chosen here once: the rows never ask which mode they are in. + switch (l.Mode) + { + case 4: l.Row = ReadLiteral; break; + case 1: l.Row = l.ReadFull; break; + case 2: l.Row = l.ReadGuarded; break; + } + + return l; + } + +"""); EmitLiteralReader(sb, m, styleB, literal, reader); // ---- the layout and its row readers ---- - sb.AppendLine("\t\t// One result-set layout and, for a mode that reads the layout's ordinals, its row readers (delegates closed over the layout)."); - sb.AppendLine("\t\tsealed class Layout : OdxLayout"); - sb.AppendLine("\t\t{"); + sb.AppendLine(""" + // One result-set layout and, for a mode that reads the layout's ordinals, its row readers (delegates closed over the layout). + sealed class Layout : OdxLayout + { +"""); + if (slots.Length > 0) sb.AppendLine($"\t\t\tpublic int {string.Join(", ", Enumerable.Range(0, slots.Length).Select(k => "O" + k))};"); - sb.AppendLine(); - sb.AppendLine("\t\t\t// The row reader Bind returns for this layout; null when the runtime serves it."); - sb.AppendLine($"\t\t\tpublic {reader} Row;"); - sb.AppendLine(); - sb.AppendLine($"\t\t\tpublic Layout({DbReader} r) : base(r) {{ }}"); - sb.AppendLine(); + sb.AppendLine($$""" + + // The row reader Bind returns for this layout; null when the runtime serves it. + public {{reader}} Row; + + public Layout({{DbReader}} r) : base(r) { } + +"""); + EmitMethod(sb, m, "ReadFull", styleB, ReadMode.Full, literal); EmitMethod(sb, m, "ReadGuarded", styleB, ReadMode.Guarded, literal); - sb.AppendLine("\t\t}"); + sb.AppendLine(""" + } + } - sb.AppendLine("\t}"); - sb.AppendLine(); +"""); } // The literal row reader: a static lambda over the reader alone. static void EmitLiteralReader(StringBuilder sb, ModelSpec m, bool styleB, int[] literal, string reader) { - sb.AppendLine("\t\t// Every member at its constant ordinal: the reads, and nothing else."); - sb.AppendLine($"\t\tstatic readonly {reader} ReadLiteral = static ({DbReader} r) =>"); - sb.AppendLine("\t\t{"); + sb.AppendLine($$""" + // Every member at its constant ordinal: the reads, and nothing else. + static readonly {{reader}} ReadLiteral = static ({{DbReader}} r) => + { +"""); + EmitRead(sb, m, styleB, ReadMode.Literal, literal, "\t\t\t"); - sb.AppendLine("\t\t};"); - sb.AppendLine(); + sb.AppendLine(""" + }; + +"""); } // Every mapped member declares its ordinal ([Column(Order = n)]): the declaration is trusted, as a hand-written reader trusts its ordinals. @@ -537,17 +583,24 @@ static void EmitTrusted(StringBuilder sb, ModelSpec m, Options options, bool sty sb.AppendLine("\t\t// Every member declares its column ordinal: the declaration is trusted and nothing about the result is checked."); if (options.Counters) { - sb.AppendLine($"\t\tstatic {reader} Bind({DbReader} r)"); - sb.AppendLine("\t\t{"); + sb.AppendLine($$""" + static {{reader}} Bind({{DbReader}} r) + { +"""); + if (m.Partial is not null) sb.AppendLine("\t\t\t" + Unseen(options)); - sb.AppendLine("\t\t\tglobal::System.Threading.Interlocked.Increment(ref OdxGeneratedCounters.Served);"); - sb.AppendLine("\t\t\tglobal::System.Threading.Interlocked.Increment(ref OdxGeneratedCounters.Modes[3]);"); - sb.AppendLine("\t\t\treturn ReadLiteral;"); - sb.AppendLine("\t\t}"); + + sb.AppendLine(""" + global::System.Threading.Interlocked.Increment(ref OdxGeneratedCounters.Served); + global::System.Threading.Interlocked.Increment(ref OdxGeneratedCounters.Modes[3]); + return ReadLiteral; + } +"""); } else { - sb.AppendLine($"\t\tstatic {reader} Bind({DbReader} r) => {(m.Partial is null ? "ReadLiteral" : "s_asSeen ? ReadLiteral : null")};"); + string served = m.Partial is null ? "ReadLiteral" : "s_asSeen ? ReadLiteral : null"; + sb.AppendLine($"\t\tstatic {reader} Bind({DbReader} r) => {served};"); } sb.AppendLine(); diff --git a/Source/Generator/ModelReader.cs b/Source/Generator/ModelReader.cs index 54a2e1a3..f04adfe9 100644 --- a/Source/Generator/ModelReader.cs +++ b/Source/Generator/ModelReader.cs @@ -121,15 +121,14 @@ static class ModelReader if (declared.NotMapped || declared.Invalid) return null; // [NotMapped] on a member a constructor parameter sets, or a declaration that is not valid: a type error at run time. // A required property the constructor also sets would have to be set again in an object initializer; the runtime sets it once. Not described here. - bool required = property?.IsRequired == true && !setsRequired; - if (required) return null; + if (property?.IsRequired == true && !setsRequired) return null; string? fallback = Fallback(parameter); if (fallback is null) return null; if (!CanName(parameter.Type, compilation)) return null; - SlotSpec? slot = Slot(name, parameter.Name, i, parameter.Type, IsNonNullableReference(parameter), false, false, declared, fallback, dbNull); + SlotSpec? slot = Slot(name, i, parameter.Type, IsNonNullableReference(parameter), false, false, declared, fallback, dbNull); if (slot is null) return null; slots.Add(slot); } @@ -146,7 +145,7 @@ static class ModelReader // What generated code names: the member (its setter included) and its type. if (!declared.NotMapped && (IsRetired(p) || IsRetired(setter) || !SyntaxFacts.IsValidIdentifier(p.Name) || !CanName(p.Type, compilation))) return null; - SlotSpec? slot = Slot(p.Name, null, -1, p.Type, IsNonNullableReference(p), setter.IsInitOnly || required, required, declared, null, dbNull); + SlotSpec? slot = Slot(p.Name, -1, p.Type, IsNonNullableReference(p), setter.IsInitOnly || required, required, declared, null, dbNull); if (slot is null) return null; slots.Add(slot); } @@ -244,7 +243,7 @@ static bool IsScalar(ITypeSymbol t) return list; } - static SlotSpec? Slot(string name, string? parameter, int position, ITypeSymbol type, bool nonNullableReference, bool initBound, bool required, Decoration declared, string? fallback, INamedTypeSymbol? dbNull) + static SlotSpec? Slot(string name, int position, ITypeSymbol type, bool nonNullableReference, bool initBound, bool required, Decoration declared, string? fallback, INamedTypeSymbol? dbNull) { bool nullableValue = type.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T; ITypeSymbol underlying = nullableValue ? ((INamedTypeSymbol)type).TypeArguments[0] : type; @@ -262,7 +261,7 @@ static bool IsScalar(ITypeSymbol t) if (underlying.SpecialType == SpecialType.System_Char || underlying.TypeKind == TypeKind.TypeParameter) return null; return new SlotSpec( - name, parameter, position, + name, position, type.ToDisplayString(Fq), nullableValue, nonNullable, CastRejectsNull(type, dbNull), initBound, required, declared.Column, declared.Order, declared.NotMapped, diff --git a/Source/Generator/Specs.cs b/Source/Generator/Specs.cs index 2866b120..2b106abb 100644 --- a/Source/Generator/Specs.cs +++ b/Source/Generator/Specs.cs @@ -51,8 +51,6 @@ sealed record MemberRead(string Expression, bool General); /// What one column can feed (RowMap's Slot): a constructor parameter, or a settable public instance property, in slot order. sealed record SlotSpec( string Name, - // The constructor parameter's name, for a slot fed through the constructor; null for a property that is set. - string? Parameter, // The constructor parameter's position, -1 for a property that is set. int Position, // The member's declared type. From 1a747eea3e5bbdbcec65b15cfa8c6e14018e831f Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Tue, 1 Dec 2026 12:59:48 -0800 Subject: [PATCH 2/5] Generator: write the generated file with one line ending AppendLine writes the host's line ending and a raw string literal keeps the line endings of the file the generator was built from, so a generator built on Windows and run on Linux or macOS emitted a mix. The finished text is now normalized to LF once before it is added to the compilation, and a test asserts the generated file has no carriage return. Also renames two locals in Emitter.EmitModel that read like the generated names beside them. Co-Authored-By: Claude Opus 5.5 --- Source/Generator/Emitter.cs | 13 ++++++++----- .../GeneratedSourceTests.cs | 5 +++++ 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/Source/Generator/Emitter.cs b/Source/Generator/Emitter.cs index 1877a8c7..520bc3d0 100644 --- a/Source/Generator/Emitter.cs +++ b/Source/Generator/Emitter.cs @@ -65,7 +65,10 @@ namespace Open.Database.Extensions.Generated foreach (ModelSpec m in models) EmitModel(sb, m, ids[m], options); sb.AppendLine("}"); - return sb.ToString(); + + // One line ending whatever the platform: AppendLine writes the host's, a raw literal keeps the line endings of the file the generator + // was built from, and the output must not depend on either. + return sb.Replace("\r\n", "\n").ToString(); } static string Identifier(string type) @@ -442,19 +445,19 @@ file sealed class {{id}} if (m.Partial is not null) sb.AppendLine("\t\t\t" + Unseen(options)); - string known = options.Counters ? "Count(known)" : "known.Row"; - string resolved = options.Counters ? "Count(l)" : "l.Row"; + string knownRow = options.Counters ? "Count(known)" : "known.Row"; + string newRow = options.Counters ? "Count(l)" : "l.Row"; sb.AppendLine($$""" Layout[] layouts = s_layouts; for (int i = 0; i < layouts.Length; i++) { Layout known = global::System.Threading.Volatile.Read(ref layouts[i]); - if (known != null && known.Matches(r)) return {{known}}; + if (known != null && known.Matches(r)) return {{knownRow}}; } Layout l = Resolve(r); global::System.Threading.Volatile.Write(ref layouts[unchecked((int)((uint)global::System.Threading.Interlocked.Increment(ref s_next) % (uint)layouts.Length))], l); - return {{resolved}}; + return {{newRow}}; } """); diff --git a/Tests/Open.Database.Extensions.Generator.Tests/GeneratedSourceTests.cs b/Tests/Open.Database.Extensions.Generator.Tests/GeneratedSourceTests.cs index d550da58..46665561 100644 --- a/Tests/Open.Database.Extensions.Generator.Tests/GeneratedSourceTests.cs +++ b/Tests/Open.Database.Extensions.Generator.Tests/GeneratedSourceTests.cs @@ -39,6 +39,11 @@ static string Binder(string source, string model) static List Stores(string binder, string member) => [.. binder.Split('\n').Where(line => line.Contains($"item.{member} = ", StringComparison.Ordinal))]; + // The generated text does not depend on the platform that built or runs the generator: one line ending throughout. + [Fact] + public void The_generated_file_uses_one_line_ending() + => Assert.DoesNotContain("\r", GeneratedSource(), StringComparison.Ordinal); + [Fact] public void The_generator_writes_no_NULL_check_helper_for_a_non_nullable_member() { From 3ccc9ffb284bbd3202af45f0c1925ca469b84ebf Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Tue, 1 Dec 2026 13:07:16 -0800 Subject: [PATCH 3/5] Generator: fold the optional Bind and Layout lines into their templates, and cover two more shapes Bind and the Layout class were each split into a template, a conditional AppendLine and a second template. The partial model's check and the ordinal fields are now holes at the start of a line, so each is one template. Generator.Tests gains a partial model with nothing settable (the list of settable names the built type is checked against is empty) and a model with no member to map (a layout with no ordinal field), so those paths of the emitter are generated and read in the test project. The generated output for every model in the test project, and for the benchmark project, is unchanged. Co-Authored-By: Claude Opus 5.5 --- Source/Generator/Emitter.cs | 48 +++++++++---------- .../ParityTests.Partial.cs | 24 ++++++++++ 2 files changed, 46 insertions(+), 26 deletions(-) diff --git a/Source/Generator/Emitter.cs b/Source/Generator/Emitter.cs index 520bc3d0..d75feea7 100644 --- a/Source/Generator/Emitter.cs +++ b/Source/Generator/Emitter.cs @@ -437,18 +437,13 @@ file sealed class {{id}} """); // ---- Bind: once per result set ---- + string knownRow = options.Counters ? "Count(known)" : "known.Row"; + string newRow = options.Counters ? "Count(l)" : "l.Row"; sb.AppendLine($$""" // Once per result set (Core's loop, after its first row is read): the row reader of this layout, or null for the runtime map. static {{reader}} Bind({{DbReader}} r) { -"""); - - if (m.Partial is not null) sb.AppendLine("\t\t\t" + Unseen(options)); - - string knownRow = options.Counters ? "Count(known)" : "known.Row"; - string newRow = options.Counters ? "Count(l)" : "l.Row"; - sb.AppendLine($$""" - Layout[] layouts = s_layouts; +{{Unseen(m, options)}} Layout[] layouts = s_layouts; for (int i = 0; i < layouts.Length; i++) { Layout known = global::System.Threading.Volatile.Read(ref layouts[i]); @@ -536,16 +531,16 @@ static Layout Resolve({{DbReader}} r) EmitLiteralReader(sb, m, styleB, literal, reader); // ---- the layout and its row readers ---- - sb.AppendLine(""" + // The ordinal fields are a line of their own with its indent and line end, or nothing for a model with no slot. + string fields = slots.Length == 0 + ? "" + : $"\t\t\tpublic int {string.Join(", ", Enumerable.Range(0, slots.Length).Select(k => "O" + k))};\n"; + + sb.AppendLine($$""" // One result-set layout and, for a mode that reads the layout's ordinals, its row readers (delegates closed over the layout). sealed class Layout : OdxLayout { -"""); - - if (slots.Length > 0) sb.AppendLine($"\t\t\tpublic int {string.Join(", ", Enumerable.Range(0, slots.Length).Select(k => "O" + k))};"); - - sb.AppendLine($$""" - +{{fields}} // The row reader Bind returns for this layout; null when the runtime serves it. public {{reader}} Row; @@ -589,12 +584,7 @@ static void EmitTrusted(StringBuilder sb, ModelSpec m, Options options, bool sty sb.AppendLine($$""" static {{reader}} Bind({{DbReader}} r) { -"""); - - if (m.Partial is not null) sb.AppendLine("\t\t\t" + Unseen(options)); - - sb.AppendLine(""" - global::System.Threading.Interlocked.Increment(ref OdxGeneratedCounters.Served); +{{Unseen(m, options)}} global::System.Threading.Interlocked.Increment(ref OdxGeneratedCounters.Served); global::System.Threading.Interlocked.Increment(ref OdxGeneratedCounters.Modes[3]); return ReadLiteral; } @@ -610,11 +600,17 @@ static void EmitTrusted(StringBuilder sb, ModelSpec m, Options options, bool sty EmitLiteralReader(sb, m, styleB, literal, reader); } - // A partial model the built type does not match: nothing served, so the runtime map reads the result set. - static string Unseen(Options options) - => options.Counters - ? "if (!s_asSeen) { global::System.Threading.Interlocked.Increment(ref OdxGeneratedCounters.Declined); global::System.Threading.Interlocked.Increment(ref OdxGeneratedCounters.Modes[0]); return null; }" - : "if (!s_asSeen) return null;"; + // The first line of a partial model's Bind, with its indent and line end (a template puts it at the start of a line, before the indent of the + // line after it), or nothing for a model that is not partial. A model the built type does not match is served nothing, so the runtime map + // reads the result set. + static string Unseen(ModelSpec m, Options options) + { + if (m.Partial is null) return ""; + + return options.Counters + ? "\t\t\tif (!s_asSeen) { global::System.Threading.Interlocked.Increment(ref OdxGeneratedCounters.Declined); global::System.Threading.Interlocked.Increment(ref OdxGeneratedCounters.Modes[0]); return null; }\n" + : "\t\t\tif (!s_asSeen) return null;\n"; + } enum ReadMode { Literal, Full, Guarded } diff --git a/Tests/Open.Database.Extensions.Generator.Tests/ParityTests.Partial.cs b/Tests/Open.Database.Extensions.Generator.Tests/ParityTests.Partial.cs index ed85904b..e84d8f89 100644 --- a/Tests/Open.Database.Extensions.Generator.Tests/ParityTests.Partial.cs +++ b/Tests/Open.Database.Extensions.Generator.Tests/ParityTests.Partial.cs @@ -54,6 +54,17 @@ internal sealed partial class TrustedPartialPost public string? Name { get; set; } } +// Nothing settable: built through its constructor alone, so the list of settable names the built type is checked against is empty. +internal sealed partial class PartialConstructorPost(int id) +{ + public int Id { get; } = id; +} + +// No member to map: a model with no slot at all. +internal sealed class MemberlessPost +{ +} + public partial class ParityTests { static TableQuery Named() => new([Col.Of("Id"), Col.Of("Name")], [1, "one"]); @@ -86,5 +97,18 @@ public void A_partial_model_with_only_what_was_seen_is_served_by_generated_code( start = Counts.Now(); Assert.Equal("one", Named().Map().Single().Name); Served(Counts.Now().Since(start)); + + start = Counts.Now(); + Assert.Equal(1, Named().Map().Single().Id); + Served(Counts.Now().Since(start)); + } + + [Fact] + public void A_model_with_no_member_to_map_is_read_as_the_runtime_map_reads_it() + { + var start = Counts.Now(); + + Assert.NotNull(Named().Map().Single()); + Served(Counts.Now().Since(start)); } } From f6feba000fb693c5b8ef18fec0dd5bac5983447e Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Tue, 1 Dec 2026 17:12:42 -0800 Subject: [PATCH 4/5] Generator: close every raw string literal at the indent of the line that opens it The closing quotes of the raw string literals in the emitter were at column 0, so the template text sat at column 0 inside indented methods. Each literal now closes at the indent of the line where it opens (an expression body, a statement, a ternary arm), and its content is that indent plus the generated indent, so the compiler strips the code's indent and the generated text is unchanged. The generated file is byte-identical to before for the test project (counters on and off) and the benchmark project. Co-Authored-By: Claude Sonnet 5.5 --- Source/Generator/Emitter.cs | 597 ++++++++++++++++++------------------ 1 file changed, 298 insertions(+), 299 deletions(-) diff --git a/Source/Generator/Emitter.cs b/Source/Generator/Emitter.cs index d75feea7..4a32852f 100644 --- a/Source/Generator/Emitter.cs +++ b/Source/Generator/Emitter.cs @@ -33,20 +33,20 @@ public static string Emit(IReadOnlyList sites, Options options) { var sb = new StringBuilder(); sb.AppendLine(""" -// -// Open.Database.Extensions source generator: Map() served by generated row readers. -#nullable disable -#pragma warning disable + // + // Open.Database.Extensions source generator: Map() served by generated row readers. + #nullable disable + #pragma warning disable -namespace System.Runtime.CompilerServices -{ - [global::System.AttributeUsage(global::System.AttributeTargets.Method, AllowMultiple = true)] - file sealed class InterceptsLocationAttribute(int version, string data) : global::System.Attribute { } -} + namespace System.Runtime.CompilerServices + { + [global::System.AttributeUsage(global::System.AttributeTargets.Method, AllowMultiple = true)] + file sealed class InterceptsLocationAttribute(int version, string data) : global::System.Attribute { } + } -namespace Open.Database.Extensions.Generated -{ -"""); + namespace Open.Database.Extensions.Generated + { + """); if (options.Counters) EmitCounters(sb); @@ -82,59 +82,59 @@ static string Identifier(string type) } static void EmitCounters(StringBuilder sb) => sb.AppendLine(""" - /// Test-only counters (OdxGeneratorCounters=true): how often the generated code was called and what it did. Never in a shipped build. - /// Counted per call and per result set only: a row reader counts nothing. - public static class OdxGeneratedCounters - { - /// Interceptor calls (a Map<T>() call that ran the generated code). - public static long Intercepted; - /// Result sets bound and served by generated row readers. - public static long Served; - /// Result sets bound and declined to the runtime map. - public static long Declined; - /// Result sets bound, by read mode: 0 runtime, 1 full, 2 guarded, 3 trusted model, 4 identity (constant ordinals). - public static readonly long[] Modes = new long[5]; - } + /// Test-only counters (OdxGeneratorCounters=true): how often the generated code was called and what it did. Never in a shipped build. + /// Counted per call and per result set only: a row reader counts nothing. + public static class OdxGeneratedCounters + { + /// Interceptor calls (a Map<T>() call that ran the generated code). + public static long Intercepted; + /// Result sets bound and served by generated row readers. + public static long Served; + /// Result sets bound and declined to the runtime map. + public static long Declined; + /// Result sets bound, by read mode: 0 runtime, 1 full, 2 guarded, 3 trusted model, 4 identity (constant ordinals). + public static readonly long[] Modes = new long[5]; + } -"""); + """); static void EmitInterceptors(StringBuilder sb, IReadOnlyList sites, Dictionary ids, Options options) { sb.AppendLine(""" - file static class OdxInterceptors - { -"""); + file static class OdxInterceptors + { + """); for (int i = 0; i < sites.Count; i++) { Site s = sites[i]; (string signature, string? constraint, string call) = Interceptor(s, i, ids[s.Model]); sb.AppendLine($$""" - [global::System.Runtime.CompilerServices.InterceptsLocation({{s.Version}}, "{{s.Data}}")] - {{signature}} -"""); + [global::System.Runtime.CompilerServices.InterceptsLocation({{s.Version}}, "{{s.Data}}")] + {{signature}} + """); if (constraint is not null) sb.AppendLine("\t\t\t" + constraint); // A counted interceptor needs a block for the increment; the plain one is an expression body. sb.AppendLine(options.Counters ? $$""" - { - global::System.Threading.Interlocked.Increment(ref OdxGeneratedCounters.Intercepted); - return {{call}}; - } + { + global::System.Threading.Interlocked.Increment(ref OdxGeneratedCounters.Intercepted); + return {{call}}; + } -""" + """ : $$""" - => {{call}}; + => {{call}}; -"""); + """); } sb.AppendLine(""" - } + } -"""); + """); } // An interceptor takes the receiver as the method it replaces does: by value for a class or an extension's parameter, by `in` for the @@ -162,212 +162,211 @@ file static class OdxInterceptors } // What every model shares: the slot table entry, the layout base, and RowMap.Match for a map with no pairs. - static void EmitShared(StringBuilder sb) => sb.AppendLine( -""" - // What one slot declares, for the matcher (RowMap's Slot, for a map with no pairs). - file sealed class OdxSlot(string name, string column, int order, bool notMapped, bool required) - { - public readonly string Name = name; - public readonly string Column = column; - public readonly int Order = order; - public readonly bool NotMapped = notMapped; - public readonly bool Required = required; - } - - // One result-set layout: the column names, and what the generated code does with it. - file abstract class OdxLayout - { - public readonly string[] Names; - - // 0: the runtime map serves it. 1: every slot fed in ascending column order (no presence test). - // 2: some slots absent, or the columns not in slot order (guarded, read in column order). - // 3: not a layout's mode: what the counters call a trusted model, which has no layout. - // 4: as 1, each slot at its declaration position among the mapped slots (columns 0..n-1, more columns after them ignored): constant ordinals, - // for a model that does not declare its ordinals. The common shape (SELECT the members in their order) reads like a hand-written selector. - public int Mode; - - // The column of each slot, -1 for none (in slot order); null when the runtime serves the layout. - public int[] Ordinals; - - // The fed slots in column order: the order a guarded read takes, as the runtime reads and sets (and a SequentialAccess reader needs). - public int[] Sequence; - - protected OdxLayout(global::System.Data.IDataRecord r) + static void EmitShared(StringBuilder sb) => sb.AppendLine(""" + // What one slot declares, for the matcher (RowMap's Slot, for a map with no pairs). + file sealed class OdxSlot(string name, string column, int order, bool notMapped, bool required) { - int n = r.FieldCount; - Names = new string[n]; - for (int i = 0; i < n; i++) Names[i] = r.GetName(i); + public readonly string Name = name; + public readonly string Column = column; + public readonly int Order = order; + public readonly bool NotMapped = notMapped; + public readonly bool Required = required; } - public bool Matches(global::System.Data.Common.DbDataReader r) + // One result-set layout: the column names, and what the generated code does with it. + file abstract class OdxLayout { - string[] names = Names; - if (r.FieldCount != names.Length) return false; - for (int i = 0; i < names.Length; i++) - if (!string.Equals(r.GetName(i), names[i], global::System.StringComparison.Ordinal)) return false; + public readonly string[] Names; - return true; - } - } + // 0: the runtime map serves it. 1: every slot fed in ascending column order (no presence test). + // 2: some slots absent, or the columns not in slot order (guarded, read in column order). + // 3: not a layout's mode: what the counters call a trusted model, which has no layout. + // 4: as 1, each slot at its declaration position among the mapped slots (columns 0..n-1, more columns after them ignored): constant ordinals, + // for a model that does not declare its ordinals. The common shape (SELECT the members in their order) reads like a hand-written selector. + public int Mode; - // Whether the built type of a partial model has the constructors and settable properties the generator saw. - file static class OdxShape - { - public static bool AsSeen(global::System.Reflection.PropertyInfo[] properties, int constructors, int expected, string[] settable) - { - if (constructors != expected) return false; - int found = 0; - foreach (global::System.Reflection.PropertyInfo p in properties) + // The column of each slot, -1 for none (in slot order); null when the runtime serves the layout. + public int[] Ordinals; + + // The fed slots in column order: the order a guarded read takes, as the runtime reads and sets (and a SequentialAccess reader needs). + public int[] Sequence; + + protected OdxLayout(global::System.Data.IDataRecord r) { - if (p.GetSetMethod() == null || p.GetIndexParameters().Length != 0) continue; - if (global::System.Array.IndexOf(settable, p.Name) < 0) return false; - found++; + int n = r.FieldCount; + Names = new string[n]; + for (int i = 0; i < n; i++) Names[i] = r.GetName(i); } - return found == settable.Length; + public bool Matches(global::System.Data.Common.DbDataReader r) + { + string[] names = Names; + if (r.FieldCount != names.Length) return false; + for (int i = 0; i < names.Length; i++) + if (!string.Equals(r.GetName(i), names[i], global::System.StringComparison.Ordinal)) return false; + + return true; + } } - } - file static class OdxMatch - { - // The fed slots (a column, mapped) ordered by their column. - public static int[] Sequence(int[] ordinals, OdxSlot[] slots) + // Whether the built type of a partial model has the constructors and settable properties the generator saw. + file static class OdxShape { - int n = 0; - for (int k = 0; k < ordinals.Length; k++) - if (ordinals[k] >= 0 && !slots[k].NotMapped) n++; - - int[] sequence = new int[n], columns = new int[n]; - n = 0; - for (int k = 0; k < ordinals.Length; k++) + public static bool AsSeen(global::System.Reflection.PropertyInfo[] properties, int constructors, int expected, string[] settable) { - if (ordinals[k] < 0 || slots[k].NotMapped) continue; - sequence[n] = k; - columns[n++] = ordinals[k]; - } + if (constructors != expected) return false; + int found = 0; + foreach (global::System.Reflection.PropertyInfo p in properties) + { + if (p.GetSetMethod() == null || p.GetIndexParameters().Length != 0) continue; + if (global::System.Array.IndexOf(settable, p.Name) < 0) return false; + found++; + } - global::System.Array.Sort(columns, sequence); - return sequence; + return found == settable.Length; + } } - // RowMap.Match, ClaimOrdinals and RequireColumns for a map with no pairs: the column of each slot (-1: none), - // or null when the runtime would throw for this result set (a declared ordinal or column that is not there, a required member with no column). - public static int[] Slots(string[] names, OdxSlot[] slots, bool decorated) + file static class OdxMatch { - int n = slots.Length; - int[] feeds = new int[names.Length]; - for (int i = 0; i < feeds.Length; i++) feeds[i] = -1; - bool[] filled = new bool[n]; - string[] columns = new string[n]; - for (int p = 0; p < n; p++) columns[p] = slots[p].NotMapped ? null : slots[p].Column ?? slots[p].Name; - - int claimed = 0; - if (decorated) + // The fed slots (a column, mapped) ordered by their column. + public static int[] Sequence(int[] ordinals, OdxSlot[] slots) { - for (int p = 0; p < n; p++) + int n = 0; + for (int k = 0; k < ordinals.Length; k++) + if (ordinals[k] >= 0 && !slots[k].NotMapped) n++; + + int[] sequence = new int[n], columns = new int[n]; + n = 0; + for (int k = 0; k < ordinals.Length; k++) { - OdxSlot slot = slots[p]; - if (slot.Order < 0) continue; + if (ordinals[k] < 0 || slots[k].NotMapped) continue; + sequence[n] = k; + columns[n++] = ordinals[k]; + } - string expected = columns[p] ?? slot.Name; - if (slot.Order >= names.Length || !string.Equals(names[slot.Order], expected, global::System.StringComparison.OrdinalIgnoreCase)) return null; + global::System.Array.Sort(columns, sequence); + return sequence; + } - feeds[slot.Order] = p; - filled[p] = true; - claimed++; + // RowMap.Match, ClaimOrdinals and RequireColumns for a map with no pairs: the column of each slot (-1: none), + // or null when the runtime would throw for this result set (a declared ordinal or column that is not there, a required member with no column). + public static int[] Slots(string[] names, OdxSlot[] slots, bool decorated) + { + int n = slots.Length; + int[] feeds = new int[names.Length]; + for (int i = 0; i < feeds.Length; i++) feeds[i] = -1; + bool[] filled = new bool[n]; + string[] columns = new string[n]; + for (int p = 0; p < n; p++) columns[p] = slots[p].NotMapped ? null : slots[p].Column ?? slots[p].Name; + + int claimed = 0; + if (decorated) + { + for (int p = 0; p < n; p++) + { + OdxSlot slot = slots[p]; + if (slot.Order < 0) continue; + + string expected = columns[p] ?? slot.Name; + if (slot.Order >= names.Length || !string.Equals(names[slot.Order], expected, global::System.StringComparison.OrdinalIgnoreCase)) return null; + + feeds[slot.Order] = p; + filled[p] = true; + claimed++; + } } - } - int unmatched = names.Length - claimed - Feed(Index(columns, slots, decorated, global::System.StringComparer.Ordinal), names, feeds, filled); - if (unmatched > 0) unmatched -= Feed(Index(columns, slots, decorated, global::System.StringComparer.OrdinalIgnoreCase), names, feeds, filled); - if (unmatched > 0 && NameIndex(slots, filled) is { } byName) Feed(byName, names, feeds, filled); + int unmatched = names.Length - claimed - Feed(Index(columns, slots, decorated, global::System.StringComparer.Ordinal), names, feeds, filled); + if (unmatched > 0) unmatched -= Feed(Index(columns, slots, decorated, global::System.StringComparer.OrdinalIgnoreCase), names, feeds, filled); + if (unmatched > 0 && NameIndex(slots, filled) is { } byName) Feed(byName, names, feeds, filled); - for (int p = 0; p < n; p++) - if ((slots[p].Required || slots[p].Column != null) && !filled[p]) return null; + for (int p = 0; p < n; p++) + if ((slots[p].Required || slots[p].Column != null) && !filled[p]) return null; - int[] ordinals = new int[n]; - for (int p = 0; p < n; p++) ordinals[p] = -1; - for (int i = 0; i < feeds.Length; i++) - if (feeds[i] >= 0) ordinals[feeds[i]] = i; + int[] ordinals = new int[n]; + for (int p = 0; p < n; p++) ordinals[p] = -1; + for (int i = 0; i < feeds.Length; i++) + if (feeds[i] >= 0) ordinals[feeds[i]] = i; - return ordinals; - } + return ordinals; + } - static int Feed(global::System.Collections.Generic.Dictionary index, string[] names, int[] feeds, bool[] filled) - { - int fed = 0; - for (int i = 0; i < names.Length; i++) + static int Feed(global::System.Collections.Generic.Dictionary index, string[] names, int[] feeds, bool[] filled) { - if (feeds[i] >= 0 || names[i] == null || !index.TryGetValue(names[i], out int p) || filled[p]) continue; + int fed = 0; + for (int i = 0; i < names.Length; i++) + { + if (feeds[i] >= 0 || names[i] == null || !index.TryGetValue(names[i], out int p) || filled[p]) continue; - filled[p] = true; - feeds[i] = p; - fed++; - } + filled[p] = true; + feeds[i] = p; + fed++; + } - return fed; - } + return fed; + } - static global::System.Collections.Generic.Dictionary Index(string[] columns, OdxSlot[] slots, bool decorated, global::System.StringComparer comparer) - { - var index = new global::System.Collections.Generic.Dictionary(columns.Length, comparer); - if (decorated) + static global::System.Collections.Generic.Dictionary Index(string[] columns, OdxSlot[] slots, bool decorated, global::System.StringComparer comparer) { - for (int p = 0; p < columns.Length; p++) - if (slots[p].Column != null && columns[p] is { } declared && !index.ContainsKey(declared)) index.Add(declared, p); - } + var index = new global::System.Collections.Generic.Dictionary(columns.Length, comparer); + if (decorated) + { + for (int p = 0; p < columns.Length; p++) + if (slots[p].Column != null && columns[p] is { } declared && !index.ContainsKey(declared)) index.Add(declared, p); + } - for (int p = 0; p < columns.Length; p++) - if (columns[p] is { } column && !index.ContainsKey(column)) index.Add(column, p); + for (int p = 0; p < columns.Length; p++) + if (columns[p] is { } column && !index.ContainsKey(column)) index.Add(column, p); - return index; - } + return index; + } - static global::System.Collections.Generic.Dictionary NameIndex(OdxSlot[] slots, bool[] filled) - { - global::System.Collections.Generic.Dictionary index = null; - for (int p = 0; p < slots.Length; p++) + static global::System.Collections.Generic.Dictionary NameIndex(OdxSlot[] slots, bool[] filled) { - if (filled[p] || slots[p].Column != null || slots[p].NotMapped) continue; - - index ??= new(slots.Length, IgnoreCaseAndUnderscores.Instance); - if (!index.ContainsKey(slots[p].Name)) index.Add(slots[p].Name, p); - } + global::System.Collections.Generic.Dictionary index = null; + for (int p = 0; p < slots.Length; p++) + { + if (filled[p] || slots[p].Column != null || slots[p].NotMapped) continue; - return index; - } + index ??= new(slots.Length, IgnoreCaseAndUnderscores.Instance); + if (!index.ContainsKey(slots[p].Name)) index.Add(slots[p].Name, p); + } - sealed class IgnoreCaseAndUnderscores : global::System.Collections.Generic.IEqualityComparer - { - public static readonly IgnoreCaseAndUnderscores Instance = new(); + return index; + } - public bool Equals(string x, string y) + sealed class IgnoreCaseAndUnderscores : global::System.Collections.Generic.IEqualityComparer { - if (ReferenceEquals(x, y)) return true; - if (x is null || y is null) return false; + public static readonly IgnoreCaseAndUnderscores Instance = new(); - int i = 0, j = 0; - while (true) + public bool Equals(string x, string y) { - while (i < x.Length && x[i] == '_') i++; - while (j < y.Length && y[j] == '_') j++; - if (i == x.Length || j == y.Length) return i == x.Length && j == y.Length; - if (char.ToUpperInvariant(x[i++]) != char.ToUpperInvariant(y[j++])) return false; + if (ReferenceEquals(x, y)) return true; + if (x is null || y is null) return false; + + int i = 0, j = 0; + while (true) + { + while (i < x.Length && x[i] == '_') i++; + while (j < y.Length && y[j] == '_') j++; + if (i == x.Length || j == y.Length) return i == x.Length && j == y.Length; + if (char.ToUpperInvariant(x[i++]) != char.ToUpperInvariant(y[j++])) return false; + } } - } - public int GetHashCode(string name) - { - int hash = 17; - foreach (char c in name) - if (c != '_') hash = unchecked(hash * 31 + char.ToUpperInvariant(c)); + public int GetHashCode(string name) + { + int hash = 17; + foreach (char c in name) + if (c != '_') hash = unchecked(hash * 31 + char.ToUpperInvariant(c)); - return hash; + return hash; + } } } - } -"""); + """); static void EmitModel(StringBuilder sb, ModelSpec m, string id, Options options) { @@ -381,15 +380,15 @@ static void EmitModel(StringBuilder sb, ModelSpec m, string id, Options options) // Made on first use, not by a static initializer: a model the runtime cannot map throws at the call, as Map() throws, not a TypeInitializationException. // A race makes two maps, each correct; the last one stays. sb.AppendLine($$""" - // {{T}} - file sealed class {{id}} - { - // The map every intercepted call of {{m.Name}} passes to Map(RowMap?): Core calls Bind once per result set. - static {{Ns}}.RowMap<{{T}}> s_map; + // {{T}} + file sealed class {{id}} + { + // The map every intercepted call of {{m.Name}} passes to Map(RowMap?): Core calls Bind once per result set. + static {{Ns}}.RowMap<{{T}}> s_map; - public static {{Ns}}.RowMap<{{T}}> Map => s_map ??= {{Ns}}.Generation.GeneratedRowMap.Create<{{T}}>(Bind); + public static {{Ns}}.RowMap<{{T}}> Map => s_map ??= {{Ns}}.Generation.GeneratedRowMap.Create<{{T}}>(Bind); -"""); + """); if (m.Partial is { } shape) { @@ -397,27 +396,27 @@ file sealed class {{id}} // per type against the built type; if it differs, Bind serves nothing and the runtime map reads this model. string names = string.Join(", ", shape.Settable.Items.Select(Str)); sb.AppendLine($$""" - static readonly bool s_asSeen = OdxShape.AsSeen(typeof({{T}}).GetProperties(global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.Instance), - typeof({{T}}).GetConstructors().Length, {{shape.Constructors}}, new string[] { {{names}} }); + static readonly bool s_asSeen = OdxShape.AsSeen(typeof({{T}}).GetProperties(global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.Instance), + typeof({{T}}).GetConstructors().Length, {{shape.Constructors}}, new string[] { {{names}} }); -"""); + """); } if (m.AllOrdered) { EmitTrusted(sb, m, options, styleB, literal, reader); sb.AppendLine(""" - } + } -"""); + """); return; } // ---- the slot table ---- sb.AppendLine(""" - static readonly OdxSlot[] Slots = - [ -"""); + static readonly OdxSlot[] Slots = + [ + """); foreach (SlotSpec s in slots) { @@ -429,57 +428,57 @@ file sealed class {{id}} // The layouts met lately (a few, as queries over one model with different column lists alternate); a slot is replaced in turn. A layout is // complete before it is published, and references are swapped atomically, so concurrent queries share them safely. sb.AppendLine(""" - ]; + ]; - static readonly Layout[] s_layouts = new Layout[8]; - static int s_next; + static readonly Layout[] s_layouts = new Layout[8]; + static int s_next; -"""); + """); // ---- Bind: once per result set ---- string knownRow = options.Counters ? "Count(known)" : "known.Row"; string newRow = options.Counters ? "Count(l)" : "l.Row"; sb.AppendLine($$""" - // Once per result set (Core's loop, after its first row is read): the row reader of this layout, or null for the runtime map. - static {{reader}} Bind({{DbReader}} r) - { -{{Unseen(m, options)}} Layout[] layouts = s_layouts; - for (int i = 0; i < layouts.Length; i++) - { - Layout known = global::System.Threading.Volatile.Read(ref layouts[i]); - if (known != null && known.Matches(r)) return {{knownRow}}; - } - - Layout l = Resolve(r); - global::System.Threading.Volatile.Write(ref layouts[unchecked((int)((uint)global::System.Threading.Interlocked.Increment(ref s_next) % (uint)layouts.Length))], l); - return {{newRow}}; - } + // Once per result set (Core's loop, after its first row is read): the row reader of this layout, or null for the runtime map. + static {{reader}} Bind({{DbReader}} r) + { + {{Unseen(m, options)}} Layout[] layouts = s_layouts; + for (int i = 0; i < layouts.Length; i++) + { + Layout known = global::System.Threading.Volatile.Read(ref layouts[i]); + if (known != null && known.Matches(r)) return {{knownRow}}; + } + + Layout l = Resolve(r); + global::System.Threading.Volatile.Write(ref layouts[unchecked((int)((uint)global::System.Threading.Interlocked.Increment(ref s_next) % (uint)layouts.Length))], l); + return {{newRow}}; + } -"""); + """); if (options.Counters) { sb.AppendLine($$""" - static {{reader}} Count(Layout l) - { - global::System.Threading.Interlocked.Increment(ref l.Row == null ? ref OdxGeneratedCounters.Declined : ref OdxGeneratedCounters.Served); - global::System.Threading.Interlocked.Increment(ref OdxGeneratedCounters.Modes[l.Mode]); - return l.Row; - } - -"""); + static {{reader}} Count(Layout l) + { + global::System.Threading.Interlocked.Increment(ref l.Row == null ? ref OdxGeneratedCounters.Declined : ref OdxGeneratedCounters.Served); + global::System.Threading.Interlocked.Increment(ref OdxGeneratedCounters.Modes[l.Mode]); + return l.Row; + } + + """); } // ---- Resolve: once per new layout ---- sb.AppendLine($$""" - static Layout Resolve({{DbReader}} r) - { - var l = new Layout(r); - int[] o = OdxMatch.Slots(l.Names, Slots, {{Bool(m.Decorated)}}); - if (o == null) return l; // A check the runtime throws for: it serves (throws) it. - bool full = true, literal = true, ascending = true; - int last = -1; -"""); + static Layout Resolve({{DbReader}} r) + { + var l = new Layout(r); + int[] o = OdxMatch.Slots(l.Names, Slots, {{Bool(m.Decorated)}}); + if (o == null) return l; // A check the runtime throws for: it serves (throws) it. + bool full = true, literal = true, ascending = true; + int last = -1; + """); for (int k = 0; k < slots.Length; k++) { @@ -495,38 +494,38 @@ static Layout Resolve({{DbReader}} r) : "full = false;"; sb.AppendLine($$""" - l.O{{k}} = o[{{k}}]; - if (o[{{k}}] >= 0) - { - if (o[{{k}}] <= last) ascending = false; - last = o[{{k}}]; - if (o[{{k}}] != {{literal[k]}}) literal = false; - } - else - { - {{absent}} - } -"""); + l.O{{k}} = o[{{k}}]; + if (o[{{k}}] >= 0) + { + if (o[{{k}}] <= last) ascending = false; + last = o[{{k}}]; + if (o[{{k}}] != {{literal[k]}}) literal = false; + } + else + { + {{absent}} + } + """); } // Every slot fed in ascending column order: constant ordinals when each sits at its declaration position (4, the identity: read in slot order, // which is column order), else the layout's (1). Anything else is guarded (2), read in column order. sb.AppendLine(""" - l.Ordinals = o; - l.Mode = !full || !ascending ? 2 : literal ? 4 : 1; - if (l.Mode == 2) l.Sequence = OdxMatch.Sequence(o, Slots); - // The row reader of the mode, chosen here once: the rows never ask which mode they are in. - switch (l.Mode) - { - case 4: l.Row = ReadLiteral; break; - case 1: l.Row = l.ReadFull; break; - case 2: l.Row = l.ReadGuarded; break; - } - - return l; - } + l.Ordinals = o; + l.Mode = !full || !ascending ? 2 : literal ? 4 : 1; + if (l.Mode == 2) l.Sequence = OdxMatch.Sequence(o, Slots); + // The row reader of the mode, chosen here once: the rows never ask which mode they are in. + switch (l.Mode) + { + case 4: l.Row = ReadLiteral; break; + case 1: l.Row = l.ReadFull; break; + case 2: l.Row = l.ReadGuarded; break; + } + + return l; + } -"""); + """); EmitLiteralReader(sb, m, styleB, literal, reader); @@ -537,40 +536,40 @@ static Layout Resolve({{DbReader}} r) : $"\t\t\tpublic int {string.Join(", ", Enumerable.Range(0, slots.Length).Select(k => "O" + k))};\n"; sb.AppendLine($$""" - // One result-set layout and, for a mode that reads the layout's ordinals, its row readers (delegates closed over the layout). - sealed class Layout : OdxLayout - { -{{fields}} - // The row reader Bind returns for this layout; null when the runtime serves it. - public {{reader}} Row; + // One result-set layout and, for a mode that reads the layout's ordinals, its row readers (delegates closed over the layout). + sealed class Layout : OdxLayout + { + {{fields}} + // The row reader Bind returns for this layout; null when the runtime serves it. + public {{reader}} Row; - public Layout({{DbReader}} r) : base(r) { } + public Layout({{DbReader}} r) : base(r) { } -"""); + """); EmitMethod(sb, m, "ReadFull", styleB, ReadMode.Full, literal); EmitMethod(sb, m, "ReadGuarded", styleB, ReadMode.Guarded, literal); sb.AppendLine(""" - } - } + } + } -"""); + """); } // The literal row reader: a static lambda over the reader alone. static void EmitLiteralReader(StringBuilder sb, ModelSpec m, bool styleB, int[] literal, string reader) { sb.AppendLine($$""" - // Every member at its constant ordinal: the reads, and nothing else. - static readonly {{reader}} ReadLiteral = static ({{DbReader}} r) => - { -"""); + // Every member at its constant ordinal: the reads, and nothing else. + static readonly {{reader}} ReadLiteral = static ({{DbReader}} r) => + { + """); EmitRead(sb, m, styleB, ReadMode.Literal, literal, "\t\t\t"); sb.AppendLine(""" - }; + }; -"""); + """); } // Every mapped member declares its ordinal ([Column(Order = n)]): the declaration is trusted, as a hand-written reader trusts its ordinals. @@ -582,13 +581,13 @@ static void EmitTrusted(StringBuilder sb, ModelSpec m, Options options, bool sty if (options.Counters) { sb.AppendLine($$""" - static {{reader}} Bind({{DbReader}} r) - { -{{Unseen(m, options)}} global::System.Threading.Interlocked.Increment(ref OdxGeneratedCounters.Served); - global::System.Threading.Interlocked.Increment(ref OdxGeneratedCounters.Modes[3]); - return ReadLiteral; - } -"""); + static {{reader}} Bind({{DbReader}} r) + { + {{Unseen(m, options)}} global::System.Threading.Interlocked.Increment(ref OdxGeneratedCounters.Served); + global::System.Threading.Interlocked.Increment(ref OdxGeneratedCounters.Modes[3]); + return ReadLiteral; + } + """); } else { From dad49211681d92dd3c82a7e5e430cd9b344d05f1 Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Tue, 1 Dec 2026 17:24:57 -0800 Subject: [PATCH 5/5] Generator: write the generated comments vertically, and keep tabs out of the emitter's strings The comments in the generated file are broken at the sentence and the colon, one clause to a line, so none runs past about 80 columns. The XML documentation stays on the one public generated type (the test-only counters class) and is now a multi-line summary on the class and on every member; the types and members that are file-local keep plain comments, as nothing outside the generated file can see them. Every fixed text in the emitter that spelled a tab as an escape (the interceptor constraint, the slot table entries, the layout's ordinal fields, the partial model's check, the trusted Bind, the reader methods and the guarded read's loop and cases) is now a raw string literal. The row readers take their indent as a depth, and one helper spells it. The generated code is identical to before once comments are left out (the test project with counters on and off, and the benchmark project); only the comment lines differ. Co-Authored-By: Claude Sonnet 5.5 --- Source/Generator/Emitter.cs | 205 +++++++++++++++++++++++++----------- 1 file changed, 144 insertions(+), 61 deletions(-) diff --git a/Source/Generator/Emitter.cs b/Source/Generator/Emitter.cs index 4a32852f..a50e28d6 100644 --- a/Source/Generator/Emitter.cs +++ b/Source/Generator/Emitter.cs @@ -34,7 +34,8 @@ public static string Emit(IReadOnlyList sites, Options options) var sb = new StringBuilder(); sb.AppendLine(""" // - // Open.Database.Extensions source generator: Map() served by generated row readers. + // Open.Database.Extensions source generator: + // Map() served by generated row readers. #nullable disable #pragma warning disable @@ -82,17 +83,34 @@ static string Identifier(string type) } static void EmitCounters(StringBuilder sb) => sb.AppendLine(""" - /// Test-only counters (OdxGeneratorCounters=true): how often the generated code was called and what it did. Never in a shipped build. - /// Counted per call and per result set only: a row reader counts nothing. + /// + /// Test-only counters (OdxGeneratorCounters=true): + /// how often the generated code was called and what it did. + /// Never in a shipped build. + /// + /// + /// Counted per call and per result set only: a row reader counts nothing. + /// public static class OdxGeneratedCounters { - /// Interceptor calls (a Map<T>() call that ran the generated code). + /// + /// Interceptor calls + /// (a Map<T>() call that ran the generated code). + /// public static long Intercepted; - /// Result sets bound and served by generated row readers. + /// + /// Result sets bound and served by generated row readers. + /// public static long Served; - /// Result sets bound and declined to the runtime map. + /// + /// Result sets bound and declined to the runtime map. + /// public static long Declined; - /// Result sets bound, by read mode: 0 runtime, 1 full, 2 guarded, 3 trusted model, 4 identity (constant ordinals). + /// + /// Result sets bound, by read mode: + /// 0 runtime, 1 full, 2 guarded, 3 trusted model, + /// 4 identity (constant ordinals). + /// public static readonly long[] Modes = new long[5]; } @@ -114,7 +132,12 @@ file static class OdxInterceptors {{signature}} """); - if (constraint is not null) sb.AppendLine("\t\t\t" + constraint); + if (constraint is not null) + { + sb.AppendLine($$""" + {{constraint}} + """); + } // A counted interceptor needs a block for the increment; the plain one is an expression body. sb.AppendLine(options.Counters @@ -163,7 +186,8 @@ file static class OdxInterceptors // What every model shares: the slot table entry, the layout base, and RowMap.Match for a map with no pairs. static void EmitShared(StringBuilder sb) => sb.AppendLine(""" - // What one slot declares, for the matcher (RowMap's Slot, for a map with no pairs). + // What one slot declares, for the matcher + // (RowMap's Slot, for a map with no pairs). file sealed class OdxSlot(string name, string column, int order, bool notMapped, bool required) { public readonly string Name = name; @@ -173,22 +197,33 @@ file sealed class OdxSlot(string name, string column, int order, bool notMapped, public readonly bool Required = required; } - // One result-set layout: the column names, and what the generated code does with it. + // One result-set layout: the column names, + // and what the generated code does with it. file abstract class OdxLayout { public readonly string[] Names; - // 0: the runtime map serves it. 1: every slot fed in ascending column order (no presence test). - // 2: some slots absent, or the columns not in slot order (guarded, read in column order). - // 3: not a layout's mode: what the counters call a trusted model, which has no layout. - // 4: as 1, each slot at its declaration position among the mapped slots (columns 0..n-1, more columns after them ignored): constant ordinals, - // for a model that does not declare its ordinals. The common shape (SELECT the members in their order) reads like a hand-written selector. + // How the layout is read. + // 0: the runtime map serves it. + // 1: every slot fed in ascending column order (no presence test). + // 2: some slots absent, or the columns not in slot order + // (guarded, read in column order). + // 3: not a layout's mode: what the counters call a trusted model, + // which has no layout. + // 4: as 1, each slot at its declaration position among the mapped slots + // (columns 0..n-1, more columns after them ignored): + // constant ordinals, for a model that does not declare its ordinals. + // The common shape (SELECT the members in their order) + // reads like a hand-written selector. public int Mode; - // The column of each slot, -1 for none (in slot order); null when the runtime serves the layout. + // The column of each slot, -1 for none (in slot order); + // null when the runtime serves the layout. public int[] Ordinals; - // The fed slots in column order: the order a guarded read takes, as the runtime reads and sets (and a SequentialAccess reader needs). + // The fed slots in column order: + // the order a guarded read takes, as the runtime reads and sets + // (and a SequentialAccess reader needs). public int[] Sequence; protected OdxLayout(global::System.Data.IDataRecord r) @@ -209,7 +244,8 @@ public bool Matches(global::System.Data.Common.DbDataReader r) } } - // Whether the built type of a partial model has the constructors and settable properties the generator saw. + // Whether the built type of a partial model + // has the constructors and settable properties the generator saw. file static class OdxShape { public static bool AsSeen(global::System.Reflection.PropertyInfo[] properties, int constructors, int expected, string[] settable) @@ -249,8 +285,11 @@ public static int[] Sequence(int[] ordinals, OdxSlot[] slots) return sequence; } - // RowMap.Match, ClaimOrdinals and RequireColumns for a map with no pairs: the column of each slot (-1: none), - // or null when the runtime would throw for this result set (a declared ordinal or column that is not there, a required member with no column). + // RowMap.Match, ClaimOrdinals and RequireColumns + // for a map with no pairs: the column of each slot (-1: none), + // or null when the runtime would throw for this result set + // (a declared ordinal or column that is not there, + // a required member with no column). public static int[] Slots(string[] names, OdxSlot[] slots, bool decorated) { int n = slots.Length; @@ -383,7 +422,9 @@ static void EmitModel(StringBuilder sb, ModelSpec m, string id, Options options) // {{T}} file sealed class {{id}} { - // The map every intercepted call of {{m.Name}} passes to Map(RowMap?): Core calls Bind once per result set. + // The map every intercepted call of {{m.Name}} + // passes to Map(RowMap?). + // Core calls Bind once per result set. static {{Ns}}.RowMap<{{T}}> s_map; public static {{Ns}}.RowMap<{{T}}> Map => s_map ??= {{Ns}}.Generation.GeneratedRowMap.Create<{{T}}>(Bind); @@ -422,7 +463,9 @@ file sealed class {{id}} { // Invariant: Order is -1 where none is declared, and a culture's minus sign need not be the one C# reads. string order = s.Order.ToString(System.Globalization.CultureInfo.InvariantCulture); - sb.AppendLine($"\t\t\tnew({Str(s.Name)}, {Str(s.Column)}, {order}, {Bool(s.NotMapped)}, {Bool(s.Required)}),"); + sb.AppendLine($$""" + new({{Str(s.Name)}}, {{Str(s.Column)}}, {{order}}, {{Bool(s.NotMapped)}}, {{Bool(s.Required)}}), + """); } // The layouts met lately (a few, as queries over one model with different column lists alternate); a slot is replaced in turn. A layout is @@ -439,7 +482,8 @@ file sealed class {{id}} string knownRow = options.Counters ? "Count(known)" : "known.Row"; string newRow = options.Counters ? "Count(l)" : "l.Row"; sb.AppendLine($$""" - // Once per result set (Core's loop, after its first row is read): the row reader of this layout, or null for the runtime map. + // Once per result set (Core's loop, after its first row is read): + // the row reader of this layout, or null for the runtime map. static {{reader}} Bind({{DbReader}} r) { {{Unseen(m, options)}} Layout[] layouts = s_layouts; @@ -475,7 +519,8 @@ static Layout Resolve({{DbReader}} r) { var l = new Layout(r); int[] o = OdxMatch.Slots(l.Names, Slots, {{Bool(m.Decorated)}}); - if (o == null) return l; // A check the runtime throws for: it serves (throws) it. + // A check the runtime throws for: it serves (throws) it. + if (o == null) return l; bool full = true, literal = true, ascending = true; int last = -1; """); @@ -485,13 +530,15 @@ static Layout Resolve({{DbReader}} r) SlotSpec s = slots[k]; if (s.NotMapped) { - sb.AppendLine($"\t\t\tl.O{k} = -1;"); + sb.AppendLine($$""" + l.O{{k}} = -1; + """); continue; } - string absent = s.InitBound - ? "return l; // An init-only member with no column keeps what its type gives it, which an object initializer cannot leave alone." - : "full = false;"; + // An init-only member with no column keeps what its type gives it, which an object initializer cannot leave + // alone: the layout is not served (its row reader stays unset) and the runtime map reads the result set. + string absent = s.InitBound ? "return l;" : "full = false;"; sb.AppendLine($$""" l.O{{k}} = o[{{k}}]; @@ -514,7 +561,8 @@ static Layout Resolve({{DbReader}} r) l.Ordinals = o; l.Mode = !full || !ascending ? 2 : literal ? 4 : 1; if (l.Mode == 2) l.Sequence = OdxMatch.Sequence(o, Slots); - // The row reader of the mode, chosen here once: the rows never ask which mode they are in. + // The row reader of the mode, chosen here once: + // the rows never ask which mode they are in. switch (l.Mode) { case 4: l.Row = ReadLiteral; break; @@ -531,16 +579,22 @@ static Layout Resolve({{DbReader}} r) // ---- the layout and its row readers ---- // The ordinal fields are a line of their own with its indent and line end, or nothing for a model with no slot. + string ordinals = string.Join(", ", Enumerable.Range(0, slots.Length).Select(k => "O" + k)); string fields = slots.Length == 0 ? "" - : $"\t\t\tpublic int {string.Join(", ", Enumerable.Range(0, slots.Length).Select(k => "O" + k))};\n"; + : $$""" + public int {{ordinals}}; + + """; sb.AppendLine($$""" - // One result-set layout and, for a mode that reads the layout's ordinals, its row readers (delegates closed over the layout). + // One result-set layout and, for a mode that reads the layout's + // ordinals, its row readers (delegates closed over the layout). sealed class Layout : OdxLayout { {{fields}} - // The row reader Bind returns for this layout; null when the runtime serves it. + // The row reader Bind returns for this layout; + // null when the runtime serves it. public {{reader}} Row; public Layout({{DbReader}} r) : base(r) { } @@ -565,7 +619,7 @@ static void EmitLiteralReader(StringBuilder sb, ModelSpec m, bool styleB, int[] { """); - EmitRead(sb, m, styleB, ReadMode.Literal, literal, "\t\t\t"); + EmitRead(sb, m, styleB, ReadMode.Literal, literal, 3); sb.AppendLine(""" }; @@ -577,7 +631,10 @@ static void EmitLiteralReader(StringBuilder sb, ModelSpec m, bool styleB, int[] // not match gives what the member's getter gives: the provider's conversion or its exception, or, where the types agree, the value at that position. static void EmitTrusted(StringBuilder sb, ModelSpec m, Options options, bool styleB, int[] literal, string reader) { - sb.AppendLine("\t\t// Every member declares its column ordinal: the declaration is trusted and nothing about the result is checked."); + sb.AppendLine(""" + // Every member declares its column ordinal: + // the declaration is trusted and nothing about the result is checked. + """); if (options.Counters) { sb.AppendLine($$""" @@ -592,7 +649,9 @@ static void EmitTrusted(StringBuilder sb, ModelSpec m, Options options, bool sty else { string served = m.Partial is null ? "ReadLiteral" : "s_asSeen ? ReadLiteral : null"; - sb.AppendLine($"\t\tstatic {reader} Bind({DbReader} r) => {served};"); + sb.AppendLine($$""" + static {{reader}} Bind({{DbReader}} r) => {{served}}; + """); } sb.AppendLine(); @@ -607,8 +666,14 @@ static string Unseen(ModelSpec m, Options options) if (m.Partial is null) return ""; return options.Counters - ? "\t\t\tif (!s_asSeen) { global::System.Threading.Interlocked.Increment(ref OdxGeneratedCounters.Declined); global::System.Threading.Interlocked.Increment(ref OdxGeneratedCounters.Modes[0]); return null; }\n" - : "\t\t\tif (!s_asSeen) return null;\n"; + ? """ + if (!s_asSeen) { global::System.Threading.Interlocked.Increment(ref OdxGeneratedCounters.Declined); global::System.Threading.Interlocked.Increment(ref OdxGeneratedCounters.Modes[0]); return null; } + + """ + : """ + if (!s_asSeen) return null; + + """; } enum ReadMode { Literal, Full, Guarded } @@ -647,16 +712,22 @@ static string Code(string name) // A row reader of the layout: an instance method (the delegate is closed over the layout, so no thunk), reading the layout's ordinals. static void EmitMethod(StringBuilder sb, ModelSpec m, string name, bool styleB, ReadMode mode, int[] literal) { - sb.AppendLine($"\t\t\tpublic {m.Type} {name}({DbReader} r)"); - sb.AppendLine("\t\t\t{"); - EmitRead(sb, m, styleB, mode, literal, "\t\t\t\t"); - sb.AppendLine("\t\t\t}"); - sb.AppendLine(); + sb.AppendLine($$""" + public {{m.Type}} {{name}}({{DbReader}} r) + { + """); + + EmitRead(sb, m, styleB, mode, literal, 4); + sb.AppendLine(""" + } + + """); } // The body of a row reader: the reads, the construction, the sets, and return. No try region: Core's loop reports a failure. - static void EmitRead(StringBuilder sb, ModelSpec m, bool styleB, ReadMode mode, int[] literal, string I) + static void EmitRead(StringBuilder sb, ModelSpec m, bool styleB, ReadMode mode, int[] literal, int depth) { + string I = Tabs(depth); string T = m.Type; var slots = m.Slots.Items; @@ -664,14 +735,14 @@ static void EmitRead(StringBuilder sb, ModelSpec m, bool styleB, ReadMode mode, { // RowMap.CreateThenSet: new T(), then each fed cell read and set in column order (ascending: slot order). sb.AppendLine($"{I}var item = {m.Create};"); - string at = OpenSequence(sb, mode, I); + string at = OpenSequence(sb, mode, depth); foreach (int k in ReadOrder(slots, mode, literal)) { SlotSpec s = slots[k]; EmitSlot(sb, s, k, mode, at, literal[k], "item." + Code(s.Name)); } - CloseSequence(sb, mode, I); + CloseSequence(sb, mode, depth); } else { @@ -686,14 +757,14 @@ static void EmitRead(StringBuilder sb, ModelSpec m, bool styleB, ReadMode mode, sb.AppendLine($"{I}{s.Type} v{k} = {s.Fallback ?? "default(" + s.Type + ")"};"); } - string readAt = OpenSequence(sb, mode, I); + string readAt = OpenSequence(sb, mode, depth); foreach (int k in ReadOrder(slots, mode, literal)) { SlotSpec s = slots[k]; EmitSlot(sb, s, k, mode, readAt, literal[k], "v" + k); } - CloseSequence(sb, mode, I); + CloseSequence(sb, mode, depth); var args = new string[m.ParameterCount]; for (int k = 0; k < slots.Length; k++) @@ -720,7 +791,7 @@ static void EmitRead(StringBuilder sb, ModelSpec m, bool styleB, ReadMode mode, .ToList(); if (sets.Count > 0) { - string setAt = OpenSequence(sb, mode, I); + string setAt = OpenSequence(sb, mode, depth); foreach (int k in sets) { string set = $"item.{Code(slots[k].Name)} = v{k};"; @@ -728,7 +799,7 @@ static void EmitRead(StringBuilder sb, ModelSpec m, bool styleB, ReadMode mode, else sb.AppendLine(setAt + set); } - CloseSequence(sb, mode, I); + CloseSequence(sb, mode, depth); } } @@ -748,30 +819,39 @@ static void EmitSlot(StringBuilder sb, SlotSpec s, int k, ReadMode mode, string return; } - sb.AppendLine($"{indent}case {k}:"); - sb.AppendLine($"{indent}\t{statement}"); - sb.AppendLine($"{indent}\tbreak;"); + sb.AppendLine($$""" + {{indent}}case {{k}}: + {{indent}} {{statement}} + {{indent}} break; + """); } // A guarded read walks the fed slots in column order (Layout.Sequence), one switch case per slot; the other modes read in slot order (their columns ascend). // Returns the indent of the cases. - static string OpenSequence(StringBuilder sb, ReadMode mode, string indent) + static string OpenSequence(StringBuilder sb, ReadMode mode, int depth) { + string indent = Tabs(depth); if (mode != ReadMode.Guarded) return indent; - sb.AppendLine(indent + "foreach (int k in Sequence)"); - sb.AppendLine(indent + "{"); - sb.AppendLine(indent + "\tswitch (k)"); - sb.AppendLine(indent + "\t{"); - return indent + "\t\t"; + sb.AppendLine($$""" + {{indent}}foreach (int k in Sequence) + {{indent}}{ + {{indent}} switch (k) + {{indent}} { + """); + + return Tabs(depth + 2); } - static void CloseSequence(StringBuilder sb, ReadMode mode, string indent) + static void CloseSequence(StringBuilder sb, ReadMode mode, int depth) { if (mode != ReadMode.Guarded) return; - sb.AppendLine(indent + "\t}"); - sb.AppendLine(indent + "}"); + string indent = Tabs(depth); + sb.AppendLine($$""" + {{indent}} } + {{indent}}} + """); } // The statement that reads a member's cell into its target (the property, or the local a constructor takes); {O} is the ordinal. @@ -800,6 +880,9 @@ static string Statement(SlotSpec s, string target, string read, bool general) return $"{target} = r.IsDBNull({{O}}) ? default({s.Type}) : {present};"; } + // The one place a tab is spelled: the indent of a generated line, which the templates carry as text. + static string Tabs(int count) => new('\t', count); + static string Str(string? s) => s is null ? "null" : Microsoft.CodeAnalysis.CSharp.SymbolDisplay.FormatLiteral(s, true); static string Bool(bool b) => b ? "true" : "false";