Skip to content

Commit 1702507

Browse files
Generator: share repeated code, no change to the generated text (#303)
A refactor of the source generator's own code. The text it emits is byte-identical to before: the generated file of the generator tests (counters on and off) and of the generated benchmarks, compared with a recursive diff before and after, is empty. What changed: - The first line of a partial model's Bind is appended as a line of its own, not through a placeholder that only lined up with the tabs after it. - A member's read statement takes its ordinal as a parameter. The two-step replacement of a second placeholder is gone. - The fully qualified symbol display format is declared once, on ModelReader. - One helper says whether a type is Nullable<T> and one returns its underlying type; the three places that spelled it out use them. - One helper tells whether a member or parameter carries a null policy or null value attribute. - One iterator walks a type and its base types; the four loops that did it by hand use it. - EquatableArray drops its length, indexer and enumerator, which nothing used. Items, Equals and GetHashCode, which the incremental cache relies on, are unchanged. Looked at and left alone: - The two query-receiver tests in the interceptor are not repeated (each appears once, with different sets), so a helper would only add lines. - The public-setter pattern appears twice as a one-clause test and a third time inside a pattern a helper cannot replace; the helper would be longer than the code it replaces. - The empty strings Site carries for a typed query are documented where they are made and sit in the cached model; changing them gains nothing. Checks: whole solution Release build without warnings; generator tests and core tests in Release; dotnet format style and analyzers on the generator and its tests. Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
1 parent 2a391a6 commit 1702507

4 files changed

Lines changed: 49 additions & 48 deletions

File tree

‎Source/Generator/Emitter.cs‎

Lines changed: 22 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -486,7 +486,10 @@ file sealed class {{id}}
486486
// the row reader of this layout, or null for the runtime map.
487487
static {{reader}} Bind({{DbReader}} r)
488488
{
489-
{{Unseen(m, options)}} Layout[] layouts = s_layouts;
489+
""");
490+
sb.Append(Unseen(m, options));
491+
sb.AppendLine($$"""
492+
Layout[] layouts = s_layouts;
490493
for (int i = 0; i < layouts.Length; i++)
491494
{
492495
Layout known = global::System.Threading.Volatile.Read(ref layouts[i]);
@@ -640,7 +643,10 @@ static void EmitTrusted(StringBuilder sb, ModelSpec m, Options options, bool sty
640643
sb.AppendLine($$"""
641644
static {{reader}} Bind({{DbReader}} r)
642645
{
643-
{{Unseen(m, options)}} global::System.Threading.Interlocked.Increment(ref OdxGeneratedCounters.Served);
646+
""");
647+
sb.Append(Unseen(m, options));
648+
sb.AppendLine($$"""
649+
global::System.Threading.Interlocked.Increment(ref OdxGeneratedCounters.Served);
644650
global::System.Threading.Interlocked.Increment(ref OdxGeneratedCounters.Modes[3]);
645651
return ReadLiteral;
646652
}
@@ -658,9 +664,8 @@ static void EmitTrusted(StringBuilder sb, ModelSpec m, Options options, bool sty
658664
EmitLiteralReader(sb, m, styleB, literal, reader);
659665
}
660666

661-
// 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
662-
// 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
663-
// reads the result set.
667+
// The first line of a partial model's Bind, with its indent and line end (appended as it is, before the rest of the body), or nothing for a
668+
// model that is not partial. A model the built type does not match is served nothing, so the runtime map reads the result set.
664669
static string Unseen(ModelSpec m, Options options)
665670
{
666671
if (m.Partial is null) return "";
@@ -811,8 +816,7 @@ static void EmitRead(StringBuilder sb, ModelSpec m, bool styleB, ReadMode mode,
811816
static void EmitSlot(StringBuilder sb, SlotSpec s, int k, ReadMode mode, string indent, int literal, string target)
812817
{
813818
string o = mode == ReadMode.Literal ? literal.ToString(System.Globalization.CultureInfo.InvariantCulture) : "O" + k;
814-
MemberRead r = s.Read;
815-
string statement = Statement(s, target, r.General ? r.Expression : r.Expression.Replace("{0}", o), r.General).Replace("{O}", o);
819+
string statement = Statement(s, target, o);
816820
if (mode != ReadMode.Guarded)
817821
{
818822
sb.AppendLine(indent + statement);
@@ -858,26 +862,28 @@ static void CloseSequence(StringBuilder sb, ReadMode mode, int depth)
858862
// A member its type declares non-nullable is read as a hand-written reader reads it: its typed getter alone, or a plain cast of GetValue (a NULL makes
859863
// the getter or the cast throw, and Core's loop reports it). Only where a cast of DBNull would succeed (object, an interface DBNull implements) does a
860864
// general read check for it and throw SqlNullValueException, as the runtime does, instead of letting DBNull pass as a value.
861-
// A nullable member is tested for NULL first, and null is stored, so the setter sees it.
862-
static string Statement(SlotSpec s, string target, string read, bool general)
865+
// A nullable member is tested for NULL first, and null is stored, so the setter sees it. o is the ordinal.
866+
static string Statement(SlotSpec s, string target, string o)
863867
{
868+
string read = s.Read.Expression;
864869
if (s.NonNullable)
865870
{
866-
if (!general) return target + " = " + read + ";";
867-
if (s.CastRejectsNull) return target + " = " + read.Replace("{0}", "r.GetValue({O})") + ";";
871+
if (!s.Read.General) return target + " = " + read.Replace("{0}", o) + ";";
872+
if (s.CastRejectsNull) return target + " = " + read.Replace("{0}", $"r.GetValue({o})") + ";";
868873

869874
string required = read.Replace("{0}", "c");
870-
return $"{{ object c = r.GetValue({{O}}); {target} = c is null || c is global::System.DBNull ? throw new global::System.Data.SqlTypes.SqlNullValueException() : {required}; }}";
875+
return $"{{ object c = r.GetValue({o}); {target} = c is null || c is global::System.DBNull ? throw new global::System.Data.SqlTypes.SqlNullValueException() : {required}; }}";
871876
}
872877

873-
if (general)
878+
if (s.Read.General)
874879
{
875880
string value = read.Replace("{0}", "c");
876-
return $"{{ object c = r.GetValue({{O}}); {target} = c is null || c is global::System.DBNull ? default({s.Type}) : {value}; }}";
881+
return $"{{ object c = r.GetValue({o}); {target} = c is null || c is global::System.DBNull ? default({s.Type}) : {value}; }}";
877882
}
878883

879-
string present = s.NullableValue ? $"({s.Type})({read})" : read;
880-
return $"{target} = r.IsDBNull({{O}}) ? default({s.Type}) : {present};";
884+
string cell = read.Replace("{0}", o);
885+
string present = s.NullableValue ? $"({s.Type})({cell})" : cell;
886+
return $"{target} = r.IsDBNull({o}) ? default({s.Type}) : {present};";
881887
}
882888

883889
// The one place a tab is spelled: the indent of a generated line, which the templates carry as text.

‎Source/Generator/MapGenerator.cs‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,6 @@ public sealed class MapGenerator : IIncrementalGenerator
2121
/// <summary>The namespace of the generated interceptors; the consuming project must list it in <c>InterceptorsNamespaces</c>.</summary>
2222
public const string GeneratedNamespace = "Open.Database.Extensions.Generated";
2323

24-
static readonly SymbolDisplayFormat Fq = SymbolDisplayFormat.FullyQualifiedFormat;
25-
2624
/// <inheritdoc/>
2725
public void Initialize(IncrementalGeneratorInitializationContext context)
2826
{
@@ -92,7 +90,7 @@ static bool IsCandidate(SyntaxNode node)
9290
// The typed query's interceptor is generic and names neither type, so TParams may be a private or open type.
9391
(string receiverType, string returnType) = kind.Value == Receiver.TypedQuery
9492
? ("", "")
95-
: ((definition.IsExtensionMethod ? definition.Parameters[0].Type : definition.ContainingType).ToDisplayString(Fq), method.ReturnType.ToDisplayString(Fq));
93+
: ((definition.IsExtensionMethod ? definition.Parameters[0].Type : definition.ContainingType).ToDisplayString(ModelReader.Fq), method.ReturnType.ToDisplayString(ModelReader.Fq));
9694

9795
return new Site(location.Version, location.Data, kind.Value, receiverType, returnType, spec);
9896
}

‎Source/Generator/ModelReader.cs‎

Lines changed: 25 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ static class ModelReader
1919
const string NullValueAttribute = "Open.Database.Extensions.NullValueAttribute";
2020
const string PriorityAttribute = "System.Runtime.CompilerServices.OverloadResolutionPriorityAttribute";
2121

22-
static readonly SymbolDisplayFormat Fq = SymbolDisplayFormat.FullyQualifiedFormat;
22+
public static readonly SymbolDisplayFormat Fq = SymbolDisplayFormat.FullyQualifiedFormat;
2323

2424
public static ModelSpec? Read(INamedTypeSymbol t, Compilation compilation)
2525
{
@@ -66,7 +66,7 @@ static class ModelReader
6666
// at the call), and a required property that is not public with a public setter.
6767
if (!setsRequired)
6868
{
69-
for (INamedTypeSymbol? c = t; c is not null; c = c.BaseType)
69+
foreach (INamedTypeSymbol c in TypeAndBaseTypes(t))
7070
{
7171
foreach (ISymbol m in c.GetMembers())
7272
{
@@ -172,21 +172,21 @@ [.. properties.Where(static p => p.SetMethod is { DeclaredAccessibility: Accessi
172172

173173
// Whether the model or a base type is declared partial in this compilation. A type from a referenced assembly is already whole.
174174
static bool IsPartial(INamedTypeSymbol t)
175+
=> TypeAndBaseTypes(t).Any(static c => c.DeclaringSyntaxReferences
176+
.Any(static r => r.GetSyntax() is TypeDeclarationSyntax type && type.Modifiers.Any(SyntaxKind.PartialKeyword)));
177+
178+
// The type, then each base type up to object: the order reflection reads members in.
179+
static IEnumerable<INamedTypeSymbol> TypeAndBaseTypes(INamedTypeSymbol t)
175180
{
176181
for (INamedTypeSymbol? c = t; c is not null; c = c.BaseType)
177-
{
178-
if (c.DeclaringSyntaxReferences.Any(static r => r.GetSyntax() is TypeDeclarationSyntax type && type.Modifiers.Any(SyntaxKind.PartialKeyword)))
179-
return true;
180-
}
181-
182-
return false;
182+
yield return c;
183183
}
184184

185185
// Shape.Judge, minus what the runtime would throw for (the call then runs today's code and throws there), plus what generated code cannot name.
186186
static bool IsMappableShape(INamedTypeSymbol t, Compilation compilation)
187187
{
188188
if (IsScalar(t) || t.IsTupleType || t.IsAnonymousType || t.IsRefLikeType || t.IsStatic) return false;
189-
if (t.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T) return false;
189+
if (IsNullableValue(t)) return false;
190190
if (t.TypeKind is not (TypeKind.Class or TypeKind.Struct)) return false; // interface, delegate, enum, ...
191191
if (t.IsAbstract || ContainsTypeParameter(t)) return false;
192192
if (!compilation.IsSymbolAccessibleWithin(t, compilation.Assembly) || !CanName(t, compilation)) return false;
@@ -229,7 +229,7 @@ static bool IsScalar(ITypeSymbol t)
229229
{
230230
var list = new List<IPropertySymbol>();
231231
var names = new HashSet<string>(StringComparer.Ordinal);
232-
for (INamedTypeSymbol? c = t; c is not null; c = c.BaseType)
232+
foreach (INamedTypeSymbol c in TypeAndBaseTypes(t))
233233
{
234234
foreach (ISymbol m in c.GetMembers())
235235
{
@@ -245,8 +245,8 @@ static bool IsScalar(ITypeSymbol t)
245245

246246
static SlotSpec? Slot(string name, int position, ITypeSymbol type, bool nonNullableReference, bool initBound, bool required, Decoration declared, string? fallback, INamedTypeSymbol? dbNull)
247247
{
248-
bool nullableValue = type.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T;
249-
ITypeSymbol underlying = nullableValue ? ((INamedTypeSymbol)type).TypeArguments[0] : type;
248+
bool nullableValue = IsNullableValue(type);
249+
ITypeSymbol underlying = Underlying(type);
250250

251251
// A ref struct cannot be cast from a value or read by GetFieldValue<T>.
252252
if (type.IsRefLikeType && !declared.NotMapped) return null;
@@ -307,7 +307,7 @@ static bool CastRejectsNull(ITypeSymbol type, INamedTypeSymbol? dbNull)
307307
// speed, never correctness. A positional record's parameter carries its own attributes, and a [property:] target lands on the property: both are seen.
308308
static bool DeclaresNullPolicy(INamedTypeSymbol t)
309309
{
310-
for (INamedTypeSymbol? c = t; c is not null; c = c.BaseType)
310+
foreach (INamedTypeSymbol c in TypeAndBaseTypes(t))
311311
{
312312
if (HasAttribute(c.GetAttributes(), NullPolicyAttribute)) return true;
313313

@@ -319,22 +319,24 @@ static bool DeclaresNullPolicy(INamedTypeSymbol t)
319319
IFieldSymbol f => f.GetAttributes(),
320320
_ => [],
321321
};
322-
if (HasAttribute(attributes, NullPolicyAttribute) || HasAttribute(attributes, NullValueAttribute)) return true;
322+
if (HasNullAttribute(attributes)) return true;
323323
}
324324
}
325325

326326
foreach (IMethodSymbol constructor in t.InstanceConstructors)
327327
{
328328
foreach (IParameterSymbol p in constructor.Parameters)
329329
{
330-
ImmutableArray<AttributeData> attributes = p.GetAttributes();
331-
if (HasAttribute(attributes, NullPolicyAttribute) || HasAttribute(attributes, NullValueAttribute)) return true;
330+
if (HasNullAttribute(p.GetAttributes())) return true;
332331
}
333332
}
334333

335334
return false;
336335
}
337336

337+
static bool HasNullAttribute(ImmutableArray<AttributeData> attributes)
338+
=> HasAttribute(attributes, NullPolicyAttribute) || HasAttribute(attributes, NullValueAttribute);
339+
338340
// The types a reader has a getter for (char is declined above).
339341
static readonly (SpecialType Type, string Getter)[] Getters =
340342
[
@@ -369,6 +371,11 @@ static bool IsNonNullableReference(IParameterSymbol p)
369371
return declared.NullableAnnotation == NullableAnnotation.NotAnnotated;
370372
}
371373

374+
static bool IsNullableValue(ITypeSymbol t) => t.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T;
375+
376+
// T of a Nullable<T>, else the type itself.
377+
static ITypeSymbol Underlying(ITypeSymbol t) => IsNullableValue(t) ? ((INamedTypeSymbol)t).TypeArguments[0] : t;
378+
372379
static bool IsReference(ITypeSymbol t) => !t.IsValueType && t.TypeKind is not (TypeKind.TypeParameter or TypeKind.Pointer or TypeKind.FunctionPointer);
373380

374381
// RowMap.DuplicateDeclaration: two members declaring one ordinal, or one column name ignoring case.
@@ -393,8 +400,8 @@ static bool HasDuplicateDeclaration(List<SlotSpec> slots)
393400
if (!p.HasExplicitDefaultValue || p.ExplicitDefaultValue is null) return "default(" + type + ")";
394401

395402
object value = p.ExplicitDefaultValue;
396-
bool nullable = p.Type.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T;
397-
ITypeSymbol underlying = nullable ? ((INamedTypeSymbol)p.Type).TypeArguments[0] : p.Type;
403+
bool nullable = IsNullableValue(p.Type);
404+
ITypeSymbol underlying = Underlying(p.Type);
398405
string? literal = Literal(value);
399406
if (literal is null) return null;
400407

‎Source/Generator/Specs.cs‎

Lines changed: 1 addition & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
11
using System;
2-
using System.Collections;
3-
using System.Collections.Generic;
42
using System.Collections.Immutable;
53

64
namespace Open.Database.Extensions.Generator;
@@ -9,15 +7,11 @@ namespace Open.Database.Extensions.Generator;
97
// so an edit that does not change a model or a call site leaves every step cached.
108

119
/// <summary>An immutable array compared by its elements, so a record holding one stays equatable.</summary>
12-
readonly struct EquatableArray<T>(ImmutableArray<T> items) : IEquatable<EquatableArray<T>>, IEnumerable<T>
10+
readonly struct EquatableArray<T>(ImmutableArray<T> items) : IEquatable<EquatableArray<T>>
1311
where T : IEquatable<T>
1412
{
1513
public ImmutableArray<T> Items => items.IsDefault ? ImmutableArray<T>.Empty : items;
1614

17-
public int Length => Items.Length;
18-
19-
public T this[int index] => Items[index];
20-
2115
public bool Equals(EquatableArray<T> other)
2216
{
2317
ImmutableArray<T> a = Items, b = other.Items;
@@ -36,10 +30,6 @@ public override int GetHashCode()
3630
foreach (T item in Items) h = unchecked(h * 31 + item.GetHashCode());
3731
return h;
3832
}
39-
40-
public IEnumerator<T> GetEnumerator() => ((IEnumerable<T>)Items).GetEnumerator();
41-
42-
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
4333
}
4434

4535
/// <summary>

0 commit comments

Comments
 (0)