Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 22 additions & 16 deletions Source/Generator/Emitter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -486,7 +486,10 @@ file sealed class {{id}}
// the row reader of this layout, or null for the runtime map.
static {{reader}} Bind({{DbReader}} r)
{
{{Unseen(m, options)}} Layout[] layouts = s_layouts;
""");
sb.Append(Unseen(m, options));
sb.AppendLine($$"""
Layout[] layouts = s_layouts;
for (int i = 0; i < layouts.Length; i++)
{
Layout known = global::System.Threading.Volatile.Read(ref layouts[i]);
Expand Down Expand Up @@ -640,7 +643,10 @@ static void EmitTrusted(StringBuilder sb, ModelSpec m, Options options, bool sty
sb.AppendLine($$"""
static {{reader}} Bind({{DbReader}} r)
{
{{Unseen(m, options)}} global::System.Threading.Interlocked.Increment(ref OdxGeneratedCounters.Served);
""");
sb.Append(Unseen(m, options));
sb.AppendLine($$"""
global::System.Threading.Interlocked.Increment(ref OdxGeneratedCounters.Served);
global::System.Threading.Interlocked.Increment(ref OdxGeneratedCounters.Modes[3]);
return ReadLiteral;
}
Expand All @@ -658,9 +664,8 @@ static void EmitTrusted(StringBuilder sb, ModelSpec m, Options options, bool sty
EmitLiteralReader(sb, m, styleB, literal, reader);
}

// 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.
// 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
// 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 "";
Expand Down Expand Up @@ -811,8 +816,7 @@ static void EmitRead(StringBuilder sb, ModelSpec m, bool styleB, ReadMode mode,
static void EmitSlot(StringBuilder sb, SlotSpec s, int k, ReadMode mode, string indent, int literal, string target)
{
string o = mode == ReadMode.Literal ? literal.ToString(System.Globalization.CultureInfo.InvariantCulture) : "O" + k;
MemberRead r = s.Read;
string statement = Statement(s, target, r.General ? r.Expression : r.Expression.Replace("{0}", o), r.General).Replace("{O}", o);
string statement = Statement(s, target, o);
if (mode != ReadMode.Guarded)
{
sb.AppendLine(indent + statement);
Expand Down Expand Up @@ -858,26 +862,28 @@ static void CloseSequence(StringBuilder sb, ReadMode mode, int depth)
// 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
// 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
// general read check for it and throw SqlNullValueException, as the runtime does, instead of letting DBNull pass as a value.
// A nullable member is tested for NULL first, and null is stored, so the setter sees it.
static string Statement(SlotSpec s, string target, string read, bool general)
// A nullable member is tested for NULL first, and null is stored, so the setter sees it. o is the ordinal.
static string Statement(SlotSpec s, string target, string o)
{
string read = s.Read.Expression;
if (s.NonNullable)
{
if (!general) return target + " = " + read + ";";
if (s.CastRejectsNull) return target + " = " + read.Replace("{0}", "r.GetValue({O})") + ";";
if (!s.Read.General) return target + " = " + read.Replace("{0}", o) + ";";
if (s.CastRejectsNull) return target + " = " + read.Replace("{0}", $"r.GetValue({o})") + ";";

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

if (general)
if (s.Read.General)
{
string value = read.Replace("{0}", "c");
return $"{{ object c = r.GetValue({{O}}); {target} = c is null || c is global::System.DBNull ? default({s.Type}) : {value}; }}";
return $"{{ object c = r.GetValue({o}); {target} = c is null || c is global::System.DBNull ? default({s.Type}) : {value}; }}";
}

string present = s.NullableValue ? $"({s.Type})({read})" : read;
return $"{target} = r.IsDBNull({{O}}) ? default({s.Type}) : {present};";
string cell = read.Replace("{0}", o);
string present = s.NullableValue ? $"({s.Type})({cell})" : cell;
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.
Expand Down
4 changes: 1 addition & 3 deletions Source/Generator/MapGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,6 @@ public sealed class MapGenerator : IIncrementalGenerator
/// <summary>The namespace of the generated interceptors; the consuming project must list it in <c>InterceptorsNamespaces</c>.</summary>
public const string GeneratedNamespace = "Open.Database.Extensions.Generated";

static readonly SymbolDisplayFormat Fq = SymbolDisplayFormat.FullyQualifiedFormat;

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

return new Site(location.Version, location.Data, kind.Value, receiverType, returnType, spec);
}
Expand Down
43 changes: 25 additions & 18 deletions Source/Generator/ModelReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ static class ModelReader
const string NullValueAttribute = "Open.Database.Extensions.NullValueAttribute";
const string PriorityAttribute = "System.Runtime.CompilerServices.OverloadResolutionPriorityAttribute";

static readonly SymbolDisplayFormat Fq = SymbolDisplayFormat.FullyQualifiedFormat;
public static readonly SymbolDisplayFormat Fq = SymbolDisplayFormat.FullyQualifiedFormat;

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

// Whether the model or a base type is declared partial in this compilation. A type from a referenced assembly is already whole.
static bool IsPartial(INamedTypeSymbol t)
=> TypeAndBaseTypes(t).Any(static c => c.DeclaringSyntaxReferences
.Any(static r => r.GetSyntax() is TypeDeclarationSyntax type && type.Modifiers.Any(SyntaxKind.PartialKeyword)));

// The type, then each base type up to object: the order reflection reads members in.
static IEnumerable<INamedTypeSymbol> TypeAndBaseTypes(INamedTypeSymbol t)
{
for (INamedTypeSymbol? c = t; c is not null; c = c.BaseType)
{
if (c.DeclaringSyntaxReferences.Any(static r => r.GetSyntax() is TypeDeclarationSyntax type && type.Modifiers.Any(SyntaxKind.PartialKeyword)))
return true;
}

return false;
yield return c;
}

// 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.
static bool IsMappableShape(INamedTypeSymbol t, Compilation compilation)
{
if (IsScalar(t) || t.IsTupleType || t.IsAnonymousType || t.IsRefLikeType || t.IsStatic) return false;
if (t.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T) return false;
if (IsNullableValue(t)) return false;
if (t.TypeKind is not (TypeKind.Class or TypeKind.Struct)) return false; // interface, delegate, enum, ...
if (t.IsAbstract || ContainsTypeParameter(t)) return false;
if (!compilation.IsSymbolAccessibleWithin(t, compilation.Assembly) || !CanName(t, compilation)) return false;
Expand Down Expand Up @@ -229,7 +229,7 @@ static bool IsScalar(ITypeSymbol t)
{
var list = new List<IPropertySymbol>();
var names = new HashSet<string>(StringComparer.Ordinal);
for (INamedTypeSymbol? c = t; c is not null; c = c.BaseType)
foreach (INamedTypeSymbol c in TypeAndBaseTypes(t))
{
foreach (ISymbol m in c.GetMembers())
{
Expand All @@ -245,8 +245,8 @@ static bool IsScalar(ITypeSymbol t)

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;
bool nullableValue = IsNullableValue(type);
ITypeSymbol underlying = Underlying(type);

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

Expand All @@ -319,22 +319,24 @@ static bool DeclaresNullPolicy(INamedTypeSymbol t)
IFieldSymbol f => f.GetAttributes(),
_ => [],
};
if (HasAttribute(attributes, NullPolicyAttribute) || HasAttribute(attributes, NullValueAttribute)) return true;
if (HasNullAttribute(attributes)) return true;
}
}

foreach (IMethodSymbol constructor in t.InstanceConstructors)
{
foreach (IParameterSymbol p in constructor.Parameters)
{
ImmutableArray<AttributeData> attributes = p.GetAttributes();
if (HasAttribute(attributes, NullPolicyAttribute) || HasAttribute(attributes, NullValueAttribute)) return true;
if (HasNullAttribute(p.GetAttributes())) return true;
}
}

return false;
}

static bool HasNullAttribute(ImmutableArray<AttributeData> attributes)
=> HasAttribute(attributes, NullPolicyAttribute) || HasAttribute(attributes, NullValueAttribute);

// The types a reader has a getter for (char is declined above).
static readonly (SpecialType Type, string Getter)[] Getters =
[
Expand Down Expand Up @@ -369,6 +371,11 @@ static bool IsNonNullableReference(IParameterSymbol p)
return declared.NullableAnnotation == NullableAnnotation.NotAnnotated;
}

static bool IsNullableValue(ITypeSymbol t) => t.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T;

// T of a Nullable<T>, else the type itself.
static ITypeSymbol Underlying(ITypeSymbol t) => IsNullableValue(t) ? ((INamedTypeSymbol)t).TypeArguments[0] : t;

static bool IsReference(ITypeSymbol t) => !t.IsValueType && t.TypeKind is not (TypeKind.TypeParameter or TypeKind.Pointer or TypeKind.FunctionPointer);

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

object value = p.ExplicitDefaultValue;
bool nullable = p.Type.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T;
ITypeSymbol underlying = nullable ? ((INamedTypeSymbol)p.Type).TypeArguments[0] : p.Type;
bool nullable = IsNullableValue(p.Type);
ITypeSymbol underlying = Underlying(p.Type);
string? literal = Literal(value);
if (literal is null) return null;

Expand Down
12 changes: 1 addition & 11 deletions Source/Generator/Specs.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Immutable;

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

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

public int Length => Items.Length;

public T this[int index] => Items[index];

public bool Equals(EquatableArray<T> other)
{
ImmutableArray<T> a = Items, b = other.Items;
Expand All @@ -36,10 +30,6 @@ public override int GetHashCode()
foreach (T item in Items) h = unchecked(h * 31 + item.GetHashCode());
return h;
}

public IEnumerator<T> GetEnumerator() => ((IEnumerable<T>)Items).GetEnumerator();

IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}

/// <summary>
Expand Down