diff --git a/Source/Generator/Emitter.cs b/Source/Generator/Emitter.cs index a50e28d6..c05cb1be 100644 --- a/Source/Generator/Emitter.cs +++ b/Source/Generator/Emitter.cs @@ -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]); @@ -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; } @@ -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 ""; @@ -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); @@ -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. diff --git a/Source/Generator/MapGenerator.cs b/Source/Generator/MapGenerator.cs index dedc31d3..9b4b9352 100644 --- a/Source/Generator/MapGenerator.cs +++ b/Source/Generator/MapGenerator.cs @@ -21,8 +21,6 @@ public sealed class MapGenerator : IIncrementalGenerator /// The namespace of the generated interceptors; the consuming project must list it in InterceptorsNamespaces. public const string GeneratedNamespace = "Open.Database.Extensions.Generated"; - static readonly SymbolDisplayFormat Fq = SymbolDisplayFormat.FullyQualifiedFormat; - /// public void Initialize(IncrementalGeneratorInitializationContext context) { @@ -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); } diff --git a/Source/Generator/ModelReader.cs b/Source/Generator/ModelReader.cs index f04adfe9..88ccd1ac 100644 --- a/Source/Generator/ModelReader.cs +++ b/Source/Generator/ModelReader.cs @@ -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) { @@ -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()) { @@ -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 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; @@ -229,7 +229,7 @@ static bool IsScalar(ITypeSymbol t) { var list = new List(); var names = new HashSet(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()) { @@ -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. if (type.IsRefLikeType && !declared.NotMapped) return null; @@ -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; @@ -319,7 +319,7 @@ static bool DeclaresNullPolicy(INamedTypeSymbol t) IFieldSymbol f => f.GetAttributes(), _ => [], }; - if (HasAttribute(attributes, NullPolicyAttribute) || HasAttribute(attributes, NullValueAttribute)) return true; + if (HasNullAttribute(attributes)) return true; } } @@ -327,14 +327,16 @@ static bool DeclaresNullPolicy(INamedTypeSymbol t) { foreach (IParameterSymbol p in constructor.Parameters) { - ImmutableArray attributes = p.GetAttributes(); - if (HasAttribute(attributes, NullPolicyAttribute) || HasAttribute(attributes, NullValueAttribute)) return true; + if (HasNullAttribute(p.GetAttributes())) return true; } } return false; } + static bool HasNullAttribute(ImmutableArray 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 = [ @@ -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, 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. @@ -393,8 +400,8 @@ static bool HasDuplicateDeclaration(List 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; diff --git a/Source/Generator/Specs.cs b/Source/Generator/Specs.cs index 2b106abb..618d9c08 100644 --- a/Source/Generator/Specs.cs +++ b/Source/Generator/Specs.cs @@ -1,6 +1,4 @@ using System; -using System.Collections; -using System.Collections.Generic; using System.Collections.Immutable; namespace Open.Database.Extensions.Generator; @@ -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. /// An immutable array compared by its elements, so a record holding one stays equatable. -readonly struct EquatableArray(ImmutableArray items) : IEquatable>, IEnumerable +readonly struct EquatableArray(ImmutableArray items) : IEquatable> where T : IEquatable { public ImmutableArray Items => items.IsDefault ? ImmutableArray.Empty : items; - public int Length => Items.Length; - - public T this[int index] => Items[index]; - public bool Equals(EquatableArray other) { ImmutableArray a = Items, b = other.Items; @@ -36,10 +30,6 @@ public override int GetHashCode() foreach (T item in Items) h = unchecked(h * 31 + item.GetHashCode()); return h; } - - public IEnumerator GetEnumerator() => ((IEnumerable)Items).GetEnumerator(); - - IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } ///