-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathModule.cs
More file actions
2516 lines (2256 loc) · 103 KB
/
Module.cs
File metadata and controls
2516 lines (2256 loc) · 103 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
namespace SpacetimeDB.Codegen;
using System;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using SpacetimeDB.Internal;
using static Utils;
/// <summary>
/// Represents column attributes parsed from field attributes in table classes.
/// Used to track metadata like primary keys, unique constraints, and default values.
/// </summary>
/// <param name="Mask">Bitmask representing the column attributes (PrimaryKey, Unique, etc.)</param>
/// <param name="Table">Optional table name if the attribute is table-specific</param>
/// <param name="Value">Optional value for attributes like Default that carry additional data</param>
readonly record struct ColumnAttr(ColumnAttrs Mask, string? Table = null, string? Value = null)
{
// Maps attribute type names to their corresponding attribute types
private static readonly ImmutableDictionary<string, System.Type> AttrTypes = ImmutableArray
.Create(
typeof(AutoIncAttribute),
typeof(PrimaryKeyAttribute),
typeof(UniqueAttribute),
typeof(DefaultAttribute)
)
.ToImmutableDictionary(t => t.FullName!);
/// <summary>
/// Parses a Roslyn AttributeData into a ColumnAttr instance.
/// </summary>
/// <param name="attrData">The attribute data to parse</param>
/// <returns>A ColumnAttr instance representing the parsed attribute, or default if the attribute type is not recognized</returns>
public static ColumnAttr Parse(AttributeData attrData)
{
if (
attrData.AttributeClass is not { } attrClass
|| !AttrTypes.TryGetValue(attrClass.ToString(), out var attrType)
)
{
return default;
}
// Special handling for DefaultAttribute as it contains an additional value
if (attrClass.ToString() == typeof(DefaultAttribute).FullName)
{
var defaultAttr = attrData.ParseAs<DefaultAttribute>(attrType);
return new(defaultAttr.Mask, defaultAttr.Table, defaultAttr.Value);
}
// Handle standard column attributes (PrimaryKey, Unique, AutoInc)
var attr = attrData.ParseAs<ColumnAttribute>(attrType);
return new(attr.Mask, attr.Table);
}
}
record SettingsDeclaration
{
public readonly string FullName;
public readonly string? CaseConversionPolicy;
private static readonly string[] CaseConversionPolicyTypeNames =
[
"SpacetimeDB.CaseConversionPolicy",
"SpacetimeDB.Internal.CaseConversionPolicy", // backward compat
];
public SettingsDeclaration(GeneratorAttributeSyntaxContext context, DiagReporter diag)
{
var fieldSymbol = (IFieldSymbol)context.TargetSymbol;
FullName = SymbolToName(fieldSymbol);
if (!fieldSymbol.IsConst)
{
diag.Report(ErrorDescriptor.SettingsMustBeConstCaseConversionPolicy, fieldSymbol);
return;
}
if (!CaseConversionPolicyTypeNames.Contains(fieldSymbol.Type.ToString()))
{
diag.Report(ErrorDescriptor.SettingsMustBeConstCaseConversionPolicy, fieldSymbol);
return;
}
if (fieldSymbol.ConstantValue is null)
{
diag.Report(ErrorDescriptor.SettingsMustBeConstCaseConversionPolicy, fieldSymbol);
return;
}
try
{
var n = Convert.ToInt32(fieldSymbol.ConstantValue);
CaseConversionPolicy = n switch
{
0 => "None",
1 => "SnakeCase",
2 => "CamelCase",
3 => "PascalCase",
_ => null,
};
}
catch
{
CaseConversionPolicy = null;
}
if (CaseConversionPolicy is null)
{
diag.Report(ErrorDescriptor.SettingsMustBeConstCaseConversionPolicy, fieldSymbol);
}
}
}
/// <summary>
/// Represents a reference to a column in a table, combining its index and name.
/// Used to maintain references to columns for indexing and querying purposes.
/// </summary>
/// <param name="Index">The zero-based index of the column in the table</param>
/// <param name="Name">The name of the column as defined in the source code</param>
record ColumnRef(int Index, string Name);
/// <summary>
/// Represents the declaration of a column in a table.
/// Contains metadata and attributes for the column, including its type, constraints, and indexes.
/// </summary>
record ColumnDeclaration : MemberDeclaration
{
public readonly EquatableArray<ColumnAttr> Attrs;
public readonly EquatableArray<TableIndex> Indexes;
public readonly bool IsEquatable;
public readonly string FullTableName;
public readonly int ColumnIndex;
public readonly string? ColumnDefaultValue;
// A helper to combine multiple column attributes into a single mask.
// Note: it doesn't check the table names, this is left up to the caller.
private static ColumnAttrs CombineColumnAttrs(IEnumerable<ColumnAttr> attrs) =>
attrs.Aggregate(ColumnAttrs.UnSet, (mask, attr) => mask | attr.Mask);
public ColumnDeclaration(string tableName, int index, IFieldSymbol field, DiagReporter diag)
: base(field, diag)
{
FullTableName = tableName;
ColumnIndex = index;
Attrs = new(
field
.GetAttributes()
.Select(ColumnAttr.Parse)
.Where(a => a.Mask != ColumnAttrs.UnSet)
.GroupBy(
a => a.Table,
(key, group) => new ColumnAttr(CombineColumnAttrs(group), key)
)
.ToImmutableArray()
);
Indexes = new(
field
.GetAttributes()
.Where(TableIndex.CanParse)
.Select(a => new TableIndex(new ColumnRef(index, field.Name), a, diag))
.ToImmutableArray()
);
ColumnDefaultValue = field
.GetAttributes()
.Select(ColumnAttr.Parse)
.Where(a => a.Mask == ColumnAttrs.Default)
.Select(a => a.Value)
.ToList()
.FirstOrDefault();
var type = field.Type;
var isInteger = type.SpecialType switch
{
SpecialType.System_Byte
or SpecialType.System_SByte
or SpecialType.System_Int16
or SpecialType.System_UInt16
or SpecialType.System_Int32
or SpecialType.System_UInt32
or SpecialType.System_Int64
or SpecialType.System_UInt64 => true,
SpecialType.None => type.ToString()
is "System.Int128"
or "System.UInt128"
or "SpacetimeDB.I128"
or "SpacetimeDB.U128"
or "SpacetimeDB.I256"
or "SpacetimeDB.U256",
_ => false,
};
var attrs = CombineColumnAttrs(Attrs);
if (attrs.HasFlag(ColumnAttrs.AutoInc) && !isInteger)
{
diag.Report(ErrorDescriptor.AutoIncNotInteger, field);
}
// Check whether this is a sum type without a payload.
var isAllUnitEnum = false;
if (type.TypeKind == Microsoft.CodeAnalysis.TypeKind.Enum)
{
isAllUnitEnum = true;
}
else if (type.BaseType?.OriginalDefinition.ToString() == "SpacetimeDB.TaggedEnum<Variants>")
{
if (
type.BaseType.TypeArguments.FirstOrDefault() is INamedTypeSymbol
{
IsTupleType: true,
TupleElements: var taggedEnumVariants
}
)
{
isAllUnitEnum = taggedEnumVariants.All(
(field) => field.Type.ToString() == "SpacetimeDB.Unit"
);
}
}
IsEquatable =
(
isInteger
|| isAllUnitEnum
|| type.SpecialType switch
{
SpecialType.System_String or SpecialType.System_Boolean => true,
SpecialType.None => type.ToString()
is "SpacetimeDB.ConnectionId"
or "SpacetimeDB.Identity"
or "SpacetimeDB.Uuid",
_ => false,
}
)
&& type.NullableAnnotation != NullableAnnotation.Annotated;
if (attrs.HasFlag(ColumnAttrs.Unique) && !IsEquatable)
{
diag.Report(ErrorDescriptor.UniqueNotEquatable, field);
}
if (
attrs.HasFlag(ColumnAttrs.Default)
&& (
attrs.HasFlag(ColumnAttrs.AutoInc)
|| attrs.HasFlag(ColumnAttrs.PrimaryKey)
|| attrs.HasFlag(ColumnAttrs.Unique)
)
)
{
diag.Report(ErrorDescriptor.IncompatibleDefaultAttributesCombination, field);
}
}
public ColumnAttrs GetAttrs(TableAccessor tableAccessor) =>
CombineColumnAttrs(Attrs.Where(x => x.Table == null || x.Table == tableAccessor.Name));
// For the `TableDesc` constructor.
public string GenerateColumnDef() =>
$"new (nameof({Name}), BSATN.{Name}{TypeUse.BsatnFieldSuffix}.GetAlgebraicType(registrar))";
}
record Scheduled(string ReducerName, int ScheduledAtColumn);
record TableAccessor
{
public readonly string Name;
public readonly string? CanonicalName;
public readonly bool IsPublic;
public readonly bool IsEvent;
public readonly Scheduled? Scheduled;
public TableAccessor(TableDeclaration table, AttributeData data, DiagReporter diag)
{
var attr = data.ParseAs<TableAttribute>();
Name = attr.Accessor ?? table.ShortName;
CanonicalName = attr.Name;
IsPublic = attr.Public;
IsEvent = attr.Event;
if (
attr.Scheduled is { } reducer
&& table.GetColumnIndex(data, attr.ScheduledAt, diag) is { } scheduledAtIndex
)
{
try
{
Scheduled = new(reducer, scheduledAtIndex);
if (
table.GetPrimaryKey(this) is not { } pk
|| table.Members[pk].Type.Name != "ulong"
)
{
throw new InvalidOperationException(
$"{Name} is a scheduled table but doesn't have a primary key of type `ulong`."
);
}
if (
table.Members[Scheduled.ScheduledAtColumn].Type.Name != "SpacetimeDB.ScheduleAt"
)
{
throw new InvalidOperationException(
$"{Name}.{attr.ScheduledAt} is marked with `ScheduledAt`, but doesn't have the expected type `SpacetimeDB.ScheduleAt`."
);
}
}
catch (Exception e)
{
diag.Report(ErrorDescriptor.InvalidScheduledDeclaration, (data, e.Message));
}
}
}
}
enum TableIndexType
{
BTree,
}
/// <summary>
/// Represents an index on a database table accessor, used to optimize queries.
/// Supports B-tree indexing (and potentially other types in the future).
/// </summary>
record TableIndex
{
public readonly EquatableArray<ColumnRef> Columns;
public readonly string? Table;
public readonly string AccessorName;
public readonly string? CanonicalName;
public readonly TableIndexType Type;
// See: bindings_sys::index_id_from_name for documentation of this format.
// Guaranteed not to contain quotes, so does not need to be escaped when embedded in a string.
private readonly string StandardNameSuffix;
/// <summary>
/// Primary constructor that initializes all fields.
/// Other constructors delegate to this one to avoid code duplication.
/// </summary>
/// <param name="accessorName">Name to use when accessing this index. If null, will be generated from column names.</param>
/// <param name="canonicalName">Explicit canonical name override for this index, if any.</param>
/// <param name="columns">The columns that make up this index.</param>
/// <param name="tableName">The name of the table this index belongs to, if any.</param>
/// <param name="type">The type of index (currently only B-tree is supported).</param>
private TableIndex(
string? accessorName,
string? canonicalName,
ImmutableArray<ColumnRef> columns,
string? tableName,
TableIndexType type
)
{
Columns = new(columns);
Table = tableName;
var columnNames = string.Join("_", columns.Select(c => c.Name));
AccessorName = accessorName ?? columnNames;
CanonicalName = canonicalName;
Type = type;
StandardNameSuffix = $"_{columnNames}_idx_{Type.ToString().ToLower()}";
}
/// <summary>
/// Creates a B-tree index on a single column with auto-generated name.
/// </summary>
/// <param name="col">The column to index.</param>
public TableIndex(ColumnRef col)
: this(
null,
null,
ImmutableArray.Create(col),
null,
TableIndexType.BTree // this might become hash in the future
) { }
/// <summary>
/// Creates an index with the given attribute and columns.
/// Used internally by other constructors that parse attributes.
/// </summary>
private TableIndex(
global::SpacetimeDB.Index.BTreeAttribute attr,
ImmutableArray<ColumnRef> columns
)
: this(attr.Accessor, attr.Name, columns, attr.Table, TableIndexType.BTree) { }
/// <summary>
/// Creates an index from a table declaration and attribute data.
/// Validates the index configuration and reports any errors through the diag reporter.
/// </summary>
private TableIndex(
TableDeclaration table,
global::SpacetimeDB.Index.BTreeAttribute attr,
AttributeData data,
DiagReporter diag
)
: this(
attr,
attr.Columns.Select(name => new ColumnRef(
table.GetColumnIndex(data, name, diag) ?? -1,
name
))
.Where(c => c.Index != -1)
.ToImmutableArray()
)
{
if (attr.Columns.Length == 0)
{
diag.Report(ErrorDescriptor.EmptyIndexColumns, data);
}
}
/// <summary>
/// Creates an index by parsing attribute data from a table declaration.
/// </summary>
public TableIndex(TableDeclaration table, AttributeData data, DiagReporter diag)
: this(table, data.ParseAs<global::SpacetimeDB.Index.BTreeAttribute>(), data, diag) { }
/// <summary>
/// Creates an index for a single column with attribute data.
/// Validates that no additional columns were specified in the attribute.
/// </summary>
private TableIndex(
ColumnRef column,
global::SpacetimeDB.Index.BTreeAttribute attr,
AttributeData data,
DiagReporter diag
)
: this(attr, ImmutableArray.Create(column))
{
if (attr.Columns.Length != 0)
{
diag.Report(ErrorDescriptor.UnexpectedIndexColumns, data);
}
}
/// <summary>
/// Creates an index for a single column by parsing attribute data.
/// </summary>
public TableIndex(ColumnRef col, AttributeData data, DiagReporter diag)
: this(col, data.ParseAs<global::SpacetimeDB.Index.BTreeAttribute>(), data, diag) { }
// `FullName` and Roslyn have different ways of representing nested types in full names -
// one uses a `Parent+Child` syntax, the other uses `Parent.Child`.
// Manually fixup one to the other.
private static readonly string BTreeAttrName =
typeof(global::SpacetimeDB.Index.BTreeAttribute).FullName.Replace('+', '.');
public static bool CanParse(AttributeData data) =>
data.AttributeClass?.ToString() == BTreeAttrName;
public string GenerateIndexDef(TableAccessor tableAccessor) =>
$$"""
new(
SourceName: "{{StandardIndexName(tableAccessor)}}",
AccessorName: "{{AccessorName}}",
Algorithm: new SpacetimeDB.Internal.RawIndexAlgorithm.{{Type}}([{{string.Join(
", ",
Columns.Select(c => c.Index)
)}}])
)
""";
public string StandardIndexName(TableAccessor tableAccessor) =>
tableAccessor.Name + StandardNameSuffix;
}
/// <summary>
/// Represents a table declaration in a module.
/// Handles table metadata, accessors, indexes, and column declarations for code generation.
/// </summary>
record TableDeclaration : BaseTypeDeclaration<ColumnDeclaration>
{
public readonly Accessibility Visibility;
public readonly EquatableArray<TableAccessor> TableAccessors;
public readonly EquatableArray<TableIndex> Indexes;
private readonly bool isRowStruct;
public int? GetColumnIndex(AttributeData attrContext, string name, DiagReporter diag)
{
var index = Members
.Select((col, i) => (col, i))
.FirstOrDefault(pair => pair.col.Name == name);
if (index.col is null)
{
diag.Report(ErrorDescriptor.UnknownColumn, (attrContext, name, ShortName));
return null;
}
return index.i;
}
public TableDeclaration(GeneratorAttributeSyntaxContext context, DiagReporter diag)
: base(context, diag)
{
var typeSyntax = (TypeDeclarationSyntax)context.TargetNode;
isRowStruct = ((INamedTypeSymbol)context.TargetSymbol).IsValueType;
if (Kind is TypeKind.Sum)
{
diag.Report(ErrorDescriptor.TableTaggedEnum, typeSyntax);
}
var container = context.TargetSymbol;
Visibility = container.DeclaredAccessibility;
while (container != null)
{
switch (container.DeclaredAccessibility)
{
case Accessibility.ProtectedAndInternal:
case Accessibility.NotApplicable:
case Accessibility.Internal:
case Accessibility.Public:
if (Visibility < container.DeclaredAccessibility)
{
Visibility = container.DeclaredAccessibility;
}
break;
default:
diag.Report(ErrorDescriptor.InvalidTableVisibility, typeSyntax);
throw new Exception(
"Table row type visibility must be public or internal, including containing types."
);
}
container = container.ContainingType;
}
TableAccessors = new(
context.Attributes.Select(a => new TableAccessor(this, a, diag)).ToImmutableArray()
);
Indexes = new(
context
.TargetSymbol.GetAttributes()
.Where(TableIndex.CanParse)
.Select(a => new TableIndex(this, a, diag))
.ToImmutableArray()
);
}
protected override ColumnDeclaration ConvertMember(
int index,
IFieldSymbol field,
DiagReporter diag
) => new(FullName, index, field, diag);
public IEnumerable<string> GenerateTableAccessorFilters(TableAccessor tableAccessor)
{
var vis = SyntaxFacts.GetText(Visibility);
var globalName = $"global::{FullName}";
var uniqueIndexBase = isRowStruct ? "UniqueIndex" : "RefUniqueIndex";
foreach (var ct in GetConstraints(tableAccessor, ColumnAttrs.Unique))
{
var f = ct.Col;
if (!f.IsEquatable)
{
// Skip - we already emitted diagnostic for this during parsing, and generated code would
// only produce a lot of noisy typechecking errors.
continue;
}
var standardIndexName = ct.ToIndex().StandardIndexName(tableAccessor);
var updateMethod = ct.Attr.HasFlag(ColumnAttrs.PrimaryKey)
? $"public {globalName} Update({globalName} row) => DoUpdate(row);"
: "";
yield return $$"""
{{vis}} sealed class {{f.Name}}UniqueIndex : {{uniqueIndexBase}}<{{tableAccessor.Name}}, {{globalName}}, {{f.Type.Name}}, {{f.Type.BSATNName}}> {
internal {{f.Name}}UniqueIndex() : base("{{standardIndexName}}") {}
// Important: don't move this to the base class.
// C# generics don't play well with nullable types and can't accept both struct-type-based and class-type-based
// `globalName` in one generic definition, leading to buggy `Row?` expansion for either one or another.
public {{globalName}}? Find({{f.Type.Name}} key) => FindSingle(key);
{{updateMethod}}
}
{{vis}} {{f.Name}}UniqueIndex {{f.Name}} => new();
""";
}
foreach (var index in GetIndexes(tableAccessor))
{
var name = index.AccessorName;
// Skip bad declarations. Empty name means no columns, which we have already reported with a meaningful error.
// Emitting this will result in further compilation errors due to missing property name.
if (name == "")
{
continue;
}
var members = index.Columns.Select(c => Members[c.Index]).ToArray();
var standardIndexName = index.StandardIndexName(tableAccessor);
yield return $$"""
{{vis}} sealed class {{name}}Index() : SpacetimeDB.Internal.IndexBase<{{globalName}}>("{{standardIndexName}}") {
""";
for (var n = 0; n < members.Length; n++)
{
var types = string.Join(
", ",
members.Take(n + 1).Select(m => $"{m.Type.Name}, {m.Type.BSATNName}")
);
var scalars = members.Take(n).Select(m => $"{m.Type.Name} {m.Name}");
var lastScalar = $"{members[n].Type.Name} {members[n].Name}";
var lastBounds =
$"global::SpacetimeDB.Bound<{members[n].Type.Name}> {members[n].Name}";
var argsScalar = string.Join(", ", scalars.Append(lastScalar));
var argsBounds = string.Join(", ", scalars.Append(lastBounds));
string argName;
if (n > 0)
{
argName = "f";
argsScalar = $"({argsScalar}) f";
argsBounds = $"({argsBounds}) f";
}
else
{
argName = members[0].Name;
}
yield return $$"""
public IEnumerable<{{globalName}}> Filter({{argsScalar}}) =>
DoFilter(new SpacetimeDB.Internal.BTreeIndexBounds<{{types}}>({{argName}}));
public ulong Delete({{argsScalar}}) =>
DoDelete(new SpacetimeDB.Internal.BTreeIndexBounds<{{types}}>({{argName}}));
public IEnumerable<{{globalName}}> Filter({{argsBounds}}) =>
DoFilter(new SpacetimeDB.Internal.BTreeIndexBounds<{{types}}>({{argName}}));
public ulong Delete({{argsBounds}}) =>
DoDelete(new SpacetimeDB.Internal.BTreeIndexBounds<{{types}}>({{argName}}));
""";
}
yield return $"}}\n {vis} {name}Index {name} => new();\n";
}
}
private IEnumerable<string> GenerateReadOnlyAccessorFilters(TableAccessor tableAccessor)
{
var vis = SyntaxFacts.GetText(Visibility);
var globalName = $"global::{FullName}";
var uniqueIndexBase = isRowStruct
? "global::SpacetimeDB.Internal.ReadOnlyUniqueIndex"
: "global::SpacetimeDB.Internal.ReadOnlyRefUniqueIndex";
foreach (var ct in GetConstraints(tableAccessor, ColumnAttrs.Unique))
{
var f = ct.Col;
if (!f.IsEquatable)
{
continue;
}
var standardIndexName = ct.ToIndex().StandardIndexName(tableAccessor);
yield return $$$"""
public sealed class {{{f.Name}}}Index
: {{{uniqueIndexBase}}}<
global::SpacetimeDB.Internal.ViewHandles.{{{tableAccessor.Name}}}ReadOnly,
{{{globalName}}},
{{{f.Type.Name}}},
{{{f.Type.BSATNName}}}>
{
internal {{{f.Name}}}Index() : base("{{{standardIndexName}}}") { }
public {{{globalName}}}? Find({{{f.Type.Name}}} key) => FindSingle(key);
}
public {{{f.Name}}}Index {{{f.Name}}} => new();
""";
}
foreach (var index in GetIndexes(tableAccessor))
{
if (string.IsNullOrEmpty(index.AccessorName))
{
continue;
}
var members = index.Columns.Select(c => Members[c.Index]).ToArray();
var standardIndexName = index.StandardIndexName(tableAccessor);
var name = index.AccessorName;
var blocks = new List<string>
{
$$$"""
public sealed class {{{name}}}Index
: global::SpacetimeDB.Internal.ReadOnlyIndexBase<{{{globalName}}}>
{
internal {{{name}}}Index() : base("{{{standardIndexName}}}") {}
""",
};
for (var n = 0; n < members.Length; n++)
{
var declaringMembers = members.Take(n + 1).ToArray();
var types = string.Join(
", ",
declaringMembers.Select(m => $"{m.Type.Name}, {m.Type.BSATNName}")
);
var scalarArgs = string.Join(
", ",
declaringMembers.Select(m => $"{m.Type.Name} {m.Name}")
);
var boundsArgs = string.Join(
", ",
declaringMembers
.Take(n)
.Select(m => $"{m.Type.Name} {m.Name}")
.Append(
$"global::SpacetimeDB.Bound<{declaringMembers[^1].Type.Name}> {declaringMembers[^1].Name}"
)
);
var ctorArg = n == 0 ? declaringMembers[0].Name : "f";
if (n > 0)
{
scalarArgs = $"({scalarArgs}) f";
boundsArgs = $"({boundsArgs}) f";
}
blocks.Add(
$$$"""
public IEnumerable<{{{globalName}}}> Filter({{{scalarArgs}}}) =>
DoFilter(new global::SpacetimeDB.Internal.BTreeIndexBounds<{{{types}}}>({{{ctorArg}}}));
public IEnumerable<{{{globalName}}}> Filter({{{boundsArgs}}}) =>
DoFilter(new global::SpacetimeDB.Internal.BTreeIndexBounds<{{{types}}}>({{{ctorArg}}}));
"""
);
}
blocks.Add($"}}\n{vis} {name}Index {name} => new();");
yield return string.Join("\n", blocks);
}
}
/// <summary>
/// Represents a generated accessor for a table, providing different access patterns
/// and visibility levels for the underlying table data.
/// </summary>
/// <param name="tableAccessorName">Name of the generated accessor type</param>
/// <param name="tableName">Fully qualified name of the table type</param>
/// <param name="tableAccessor">C# source code for the accessor implementation</param>
/// <param name="getter">C# property getter for accessing the accessor</param>
public record struct GeneratedTableAccessor(
string tableAccessorName,
string tableName,
string tableAccessor,
string getter
);
/// <summary>
/// Generates accessor implementations for all table accessors defined in this table declaration.
/// Each accessor represents a different way to access or filter the table's data.
/// </summary>
/// <returns>Collection of Accessor records containing generated code for each accessor</returns>
public IEnumerable<GeneratedTableAccessor> GenerateTableAccessors()
{
// Don't try to generate accessors if this table is a sum type.
// We already emitted a diagnostic, and attempting to generate accessors will only result in more noisy errors.
if (Kind is TypeKind.Sum)
{
yield break;
}
foreach (var v in TableAccessors)
{
var autoIncFields = Members.Where(m => m.GetAttrs(v).HasFlag(ColumnAttrs.AutoInc));
var globalName = $"global::{FullName}";
var iTable = $"global::SpacetimeDB.Internal.ITableView<{v.Name}, {globalName}>";
yield return new(
v.Name,
globalName,
$$$"""
{{{SyntaxFacts.GetText(Visibility)}}} readonly struct {{{v.Name}}} : {{{iTable}}} {
public static {{{globalName}}} ReadGenFields(System.IO.BinaryReader reader, {{{globalName}}} row) {
{{{string.Join(
"\n",
autoIncFields.Select(m =>
$$"""
if (row.{{m.Name}} == default)
{
row.{{m.Name}} = {{globalName}}.BSATN.{{m.Name}}{{TypeUse.BsatnFieldSuffix}}.Read(reader);
}
"""
)
)}}}
return row;
}
public static SpacetimeDB.Internal.RawTableDefV10 MakeTableDesc(SpacetimeDB.BSATN.ITypeRegistrar registrar) => new (
SourceName: nameof({{{v.Name}}}),
ProductTypeRef: (uint) new {{{globalName}}}.BSATN().GetAlgebraicType(registrar).Ref_,
PrimaryKey: [{{{GetPrimaryKey(v)?.ToString() ?? ""}}}],
Indexes: [
{{{string.Join(
",\n",
GetConstraints(v, ColumnAttrs.Unique)
.Select(c => c.ToIndex())
.Concat(GetIndexes(v))
.Select(b => b.GenerateIndexDef(v))
)}}}
],
Constraints: {{{GenConstraintList(v, ColumnAttrs.Unique, $"{iTable}.MakeUniqueConstraint")}}},
Sequences: {{{GenConstraintList(v, ColumnAttrs.AutoInc, $"{iTable}.MakeSequence")}}},
TableType: SpacetimeDB.Internal.TableType.User,
TableAccess: SpacetimeDB.Internal.TableAccess.{{{(v.IsPublic ? "Public" : "Private")}}},
DefaultValues: [],
IsEvent: {{{(v.IsEvent ? "true" : "false")}}}
);
public static SpacetimeDB.Internal.RawScheduleDefV10? MakeScheduleDesc() => {{{(
v.Scheduled is { } scheduled
? $"{iTable}.MakeSchedule(\"{scheduled.ReducerName}\", {scheduled.ScheduledAtColumn})"
: "null"
)}}};
public ulong Count => {{{iTable}}}.DoCount();
public IEnumerable<{{{globalName}}}> Iter() => {{{iTable}}}.DoIter();
public {{{globalName}}} Insert({{{globalName}}} row) => {{{iTable}}}.DoInsert(row);
public bool Delete({{{globalName}}} row) => {{{iTable}}}.DoDelete(row);
{{{string.Join("\n", GenerateTableAccessorFilters(v))}}}
}
""",
$"{SyntaxFacts.GetText(Visibility)} global::SpacetimeDB.Internal.TableHandles.{v.Name} {v.Name} => new();"
);
}
}
public record struct GeneratedReadOnlyAccessor(
string tableAccessorName,
string tableName,
string readOnlyAccessor,
string readOnlyGetter
);
public IEnumerable<GeneratedReadOnlyAccessor> GenerateReadOnlyAccessors()
{
if (Kind is TypeKind.Sum)
{
yield break;
}
foreach (var accessor in TableAccessors)
{
var globalName = $"global::{FullName}";
var readOnlyIndexDecls = string.Join("\n", GenerateReadOnlyAccessorFilters(accessor));
var visibility = SyntaxFacts.GetText(Visibility);
yield return new(
accessor.Name,
globalName,
$$$"""
{{{visibility}}} sealed class {{{accessor.Name}}}ReadOnly
: global::SpacetimeDB.Internal.ReadOnlyTableView<{{{globalName}}}>
{
internal {{{accessor.Name}}}ReadOnly() : base("{{{accessor.Name}}}") { }
public ulong Count => DoCount();
{{{readOnlyIndexDecls}}}
}
""",
$"{visibility} global::SpacetimeDB.Internal.ViewHandles.{accessor.Name}ReadOnly {accessor.Name} => new();"
);
}
}
public IEnumerable<string> GenerateQueryBuilderMembers()
{
if (Kind is TypeKind.Sum)
{
yield break;
}
var vis = SyntaxFacts.GetText(Visibility);
var globalRowName = $"global::{FullName}";
foreach (var accessor in TableAccessors)
{
var tableName = accessor.Name;
var colsTypeName = $"{accessor.Name}Cols";
var ixColsTypeName = $"{accessor.Name}IxCols";
string ColDecl(ColumnDeclaration col)
{
var typeName = col.Type.Name;
var isNullable = typeName.EndsWith("?", StringComparison.Ordinal);
var valueTypeName = isNullable ? typeName[..^1] : typeName;
var colType = isNullable
? "global::SpacetimeDB.NullableCol"
: "global::SpacetimeDB.Col";
return $"public readonly {colType}<{globalRowName}, {valueTypeName}> {col.Name};";
}
string ColInit(ColumnDeclaration col)
{
var typeName = col.Type.Name;
var isNullable = typeName.EndsWith("?", StringComparison.Ordinal);
var valueTypeName = isNullable ? typeName[..^1] : typeName;
var colType = isNullable
? "global::SpacetimeDB.NullableCol"
: "global::SpacetimeDB.Col";
return $"{col.Name} = new {colType}<{globalRowName}, {valueTypeName}>(tableName, \"{col.Name}\");";
}
var colsDecls = string.Join("\n ", Members.Select(ColDecl));
var colsInits = string.Join("\n ", Members.Select(ColInit));
var ixPositions = new global::System.Collections.Generic.HashSet<int>();
foreach (var c in GetConstraints(accessor, ColumnAttrs.PrimaryKey | ColumnAttrs.Unique))
{
ixPositions.Add(c.Pos);
}
foreach (var ix in GetIndexes(accessor))
{
foreach (var colRef in ix.Columns.Array)
{
ixPositions.Add(colRef.Index);
}
}
var ixMembers = Members
.Select((m, i) => (m, i))
.Where(pair => ixPositions.Contains(pair.i))
.Select(pair => pair.m)
.ToArray();
string IxColDecl(ColumnDeclaration col)
{
var typeName = col.Type.Name;
var isNullable = typeName.EndsWith("?", StringComparison.Ordinal);
var valueTypeName = isNullable ? typeName[..^1] : typeName;
var colType = isNullable
? "global::SpacetimeDB.NullableIxCol"
: "global::SpacetimeDB.IxCol";
return $"public readonly {colType}<{globalRowName}, {valueTypeName}> {col.Name};";
}
string IxColInit(ColumnDeclaration col)
{
var typeName = col.Type.Name;
var isNullable = typeName.EndsWith("?", StringComparison.Ordinal);
var valueTypeName = isNullable ? typeName[..^1] : typeName;
var colType = isNullable
? "global::SpacetimeDB.NullableIxCol"
: "global::SpacetimeDB.IxCol";
return $"{col.Name} = new {colType}<{globalRowName}, {valueTypeName}>(tableName, \"{col.Name}\");";
}
var ixColsDecls = string.Join("\n ", ixMembers.Select(IxColDecl));
var ixColsInits = string.Join("\n ", ixMembers.Select(IxColInit));
yield return $$"""
{{vis}} readonly struct {{colsTypeName}}
{
{{colsDecls}}
internal {{colsTypeName}}(string tableName)
{
{{colsInits}}
}
}
{{vis}} readonly struct {{ixColsTypeName}}
{
{{ixColsDecls}}
internal {{ixColsTypeName}}(string tableName)
{
{{ixColsInits}}
}
}
public readonly partial struct QueryBuilder
{
{{vis}} global::SpacetimeDB.Table<{{globalRowName}}, {{colsTypeName}}, {{ixColsTypeName}}> {{accessor.Name}}() =>
new("{{tableName}}", new {{colsTypeName}}("{{tableName}}"), new {{ixColsTypeName}}("{{tableName}}"));
}
""";
}
}
/// <summary>
/// Represents a default value for a table field, used during table creation.
/// </summary>
/// <param name="tableName">Name of the table containing the field</param>