diff --git a/Source/Generator/Emitter.cs b/Source/Generator/Emitter.cs index 195ab98b..a50e28d6 100644 --- a/Source/Generator/Emitter.cs +++ b/Source/Generator/Emitter.cs @@ -32,41 +32,44 @@ 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); 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) @@ -79,52 +82,82 @@ static string Identifier(string type) return sb.ToString(); } - static void EmitCounters(StringBuilder sb) - { - 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(); - } + 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]; + } + + """); 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); - 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($$""" + [global::System.Runtime.CompilerServices.InterceptsLocation({{s.Version}}, "{{s.Data}}")] + {{signature}} + """); + + if (constraint is not null) { - sb.AppendLine($"\t\t\t=> {call};"); + sb.AppendLine($$""" + {{constraint}} + """); } - 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}}; + } + + """ + : $$""" + => {{call}}; + + """); } - sb.AppendLine("\t}"); - sb.AppendLine(); + 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 @@ -152,212 +185,227 @@ static void EmitInterceptors(StringBuilder sb, IReadOnlyList sites, Dictio } // 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; - - return true; - } - } - - // 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) + public readonly string[] Names; + + // 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. + 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) { @@ -367,166 +415,215 @@ 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. 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)}}), + """); } - 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{"); - 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 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}}; + } + + """); 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)}}); + // 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; + """); + for (int k = 0; k < slots.Length; k++) { SlotSpec s = slots[k]; if (s.NotMapped) { - sb.AppendLine($"\t\t\tl.O{k} = -1;"); + sb.AppendLine($$""" + l.O{{k}} = -1; + """); 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."); - else - sb.AppendLine("\t\t\t\tfull = false;"); - sb.AppendLine("\t\t\t}"); + // 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}}]; + if (o[{{k}}] >= 0) + { + if (o[{{k}}] <= last) ascending = false; + last = o[{{k}}]; + if (o[{{k}}] != {{literal[k]}}) literal = false; + } + else + { + {{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{"); - if (slots.Length > 0) sb.AppendLine($"\t\t\tpublic int {string.Join(", ", Enumerable.Range(0, slots.Length).Select(k => "O" + k))};"); + // 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 + ? "" + : $$""" + 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). + 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) { } + + """); - 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(); 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{"); - EmitRead(sb, m, styleB, ReadMode.Literal, literal, "\t\t\t"); - sb.AppendLine("\t\t};"); - sb.AppendLine(); + 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, 3); + sb.AppendLine(""" + }; + + """); } // Every mapped member declares its ordinal ([Column(Order = n)]): the declaration is trusted, as a hand-written reader trusts its ordinals. @@ -534,31 +631,50 @@ 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($"\t\tstatic {reader} Bind({DbReader} r)"); - sb.AppendLine("\t\t{"); - 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($$""" + 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 { - 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($$""" + static {{reader}} Bind({{DbReader}} r) => {{served}}; + """); } sb.AppendLine(); 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 + ? """ + 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 } @@ -596,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; @@ -613,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 { @@ -635,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++) @@ -669,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};"; @@ -677,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); } } @@ -697,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. @@ -749,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"; 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. 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() { 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)); } }