Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Minor attribute cleanups for C# module #1753

Merged
merged 2 commits into from
Sep 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions crates/bindings-csharp/BSATN.Codegen/Utils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -182,9 +182,10 @@ IEnumerable<T> values
_ => constant.Value,
};

public static T ParseAs<T>(this AttributeData attrData)
public static T ParseAs<T>(this AttributeData attrData, System.Type? type = null)
where T : Attribute
{
type ??= typeof(T);
var ctorArgs = attrData.ConstructorArguments.Select(ResolveConstant).ToArray();
// For now only support attributes with a single constructor.
//
Expand All @@ -193,10 +194,10 @@ public static T ParseAs<T>(this AttributeData attrData)
// which prevent APIs like `Activator.CreateInstance` from finding the constructor.
//
// Expand logic in the future if it ever becomes actually necessary.
var attr = (T)typeof(T).GetConstructors().Single().Invoke(ctorArgs);
var attr = (T)type.GetConstructors().Single().Invoke(ctorArgs);
foreach (var arg in attrData.NamedArguments)
{
typeof(T).GetProperty(arg.Key).SetValue(attr, ResolveConstant(arg.Value));
type.GetProperty(arg.Key).SetValue(attr, ResolveConstant(arg.Value));
}
return attr;
}
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

75 changes: 45 additions & 30 deletions crates/bindings-csharp/Codegen/Module.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,37 @@ namespace SpacetimeDB.Codegen;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using SpacetimeDB.Internal;
using static Utils;

readonly record struct ColumnAttr(ColumnAttrs Mask, string? Table = null)
{
private static readonly ImmutableDictionary<string, System.Type> AttrTypes = ImmutableArray
.Create(
typeof(AutoIncAttribute),
typeof(PrimaryKeyAttribute),
typeof(UniqueAttribute),
typeof(IndexedAttribute)
)
.ToImmutableDictionary(t => t.FullName);

public static ColumnAttr Parse(AttributeData attrData)
{
if (
attrData.AttributeClass is not { } attrClass
|| !AttrTypes.TryGetValue(attrClass.ToString(), out var attrType)
)
{
return default;
}
var attr = attrData.ParseAs<ColumnAttribute>(attrType);
return new(attr.Mask, attr.Table);
}
}

record ColumnDeclaration : MemberDeclaration
{
public readonly EquatableArray<(string? table, ColumnAttrs mask)> Attrs;
public readonly EquatableArray<ColumnAttr> Attrs;
public readonly bool IsEquatable;
public readonly string FullTableName;

Expand All @@ -22,11 +48,16 @@ bool isEquatable
)
: base(name, type, typeInfo)
{
Attrs = new(ImmutableArray.Create((default(string), attrs)));
Attrs = new(ImmutableArray.Create(new ColumnAttr(attrs)));
IsEquatable = isEquatable;
FullTableName = tableName;
}

// 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, IFieldSymbol field)
: base(field)
{
Expand All @@ -35,21 +66,12 @@ public ColumnDeclaration(string tableName, IFieldSymbol field)
Attrs = new(
field
.GetAttributes()
.Select(a =>
(
table: a.NamedArguments.FirstOrDefault(a => a.Key == "Table").Value.Value
as string,
attr: a.AttributeClass?.ToString() switch
{
"SpacetimeDB.AutoIncAttribute" => ColumnAttrs.AutoInc,
"SpacetimeDB.PrimaryKeyAttribute" => ColumnAttrs.PrimaryKey,
"SpacetimeDB.UniqueAttribute" => ColumnAttrs.Unique,
"SpacetimeDB.IndexedAttribute" => ColumnAttrs.Indexed,
_ => ColumnAttrs.UnSet,
}
)
.Select(ColumnAttr.Parse)
.Where(a => a.Mask != ColumnAttrs.UnSet)
.GroupBy(
a => a.Table,
(key, group) => new ColumnAttr(CombineColumnAttrs(group), key)
)
.Where(a => a.attr != ColumnAttrs.UnSet)
.ToImmutableArray()
);

Expand All @@ -75,7 +97,7 @@ or SpecialType.System_Int64
_ => false,
};

var attrs = Attrs.Aggregate(ColumnAttrs.UnSet, (xs, x) => xs | x.mask);
var attrs = CombineColumnAttrs(Attrs);

if (attrs.HasFlag(ColumnAttrs.AutoInc) && !isInteger)
{
Expand Down Expand Up @@ -107,9 +129,7 @@ or SpecialType.System_Int64
}

public ColumnAttrs GetAttrs(string tableName) =>
Attrs
.Where(x => x.table == null || x.table == tableName)
.Aggregate(ColumnAttrs.UnSet, (xs, x) => xs | x.mask);
CombineColumnAttrs(Attrs.Where(x => x.Table == null || x.Table == tableName));

// For the `TableDesc` constructor.
public string GenerateColumnDef() =>
Expand All @@ -128,16 +148,11 @@ record TableView

public TableView(TableDeclaration table, AttributeData data)
{
Name =
data.NamedArguments.FirstOrDefault(x => x.Key == "Name").Value.Value as string
?? table.ShortName;

IsPublic = data.NamedArguments.Any(pair => pair is { Key: "Public", Value.Value: true });
var attr = data.ParseAs<TableAttribute>();

Scheduled = data
.NamedArguments.Where(pair => pair.Key == "Scheduled")
.Select(pair => (string?)pair.Value.Value)
.SingleOrDefault();
Name = attr.Name ?? table.ShortName;
IsPublic = attr.Public;
Scheduled = attr.Scheduled;
}
}

Expand Down Expand Up @@ -347,7 +362,7 @@ public override Scope.Extensions ToExtensions()
nameof({{ShortName}}),
{{tuple.pos}},
nameof({{tuple.col.Name}}),
(SpacetimeDB.ColumnAttrs){{(int)tuple.attr}}
SpacetimeDB.Internal.ColumnAttrs.{{tuple.attr}}
)
"""
)
Expand Down
130 changes: 72 additions & 58 deletions crates/bindings-csharp/Runtime/Attrs.cs
Original file line number Diff line number Diff line change
@@ -1,73 +1,87 @@
namespace SpacetimeDB;

[Flags]
public enum ColumnAttrs : byte
namespace SpacetimeDB
{
UnSet = 0b0000,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Don't think the toplevel ns needs {}; namespace Internal {} is fine to use with namespace SpacetimeDB; afaik

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's necessary here because you can't mix file-scoped and regular namespace syntax, C# will complain. Idk why they made it so, but 🤷‍♂️

Indexed = 0b0001,
AutoInc = 0b0010,
Unique = Indexed | 0b0100,
Identity = Unique | AutoInc,
PrimaryKey = Unique | 0b1000,
PrimaryKeyAuto = PrimaryKey | AutoInc,
namespace Internal
{
[Flags]
public enum ColumnAttrs : byte
{
UnSet = 0b0000,
Indexed = 0b0001,
AutoInc = 0b0010,
Unique = Indexed | 0b0100,
Identity = Unique | AutoInc,
PrimaryKey = Unique | 0b1000,
PrimaryKeyAuto = PrimaryKey | AutoInc,
}

// A legacy alias, originally defined as `PrimaryKey | Identity` which is numerically same as above.
PrimaryKeyIdentity = PrimaryKeyAuto,
}
[AttributeUsage(AttributeTargets.Field)]
public abstract class ColumnAttribute : Attribute
{
public string? Table { get; init; }
internal abstract ColumnAttrs Mask { get; }
}
}

/// <summary>
/// Registers a type as the row structure of a SpacetimeDB table, enabling codegen for it.
///
/// <para>
/// Multiple [Table] attributes per type are supported. This is useful to reuse row types.
/// Each attribute instance must have a unique name and will create a SpacetimeDB table.
/// </para>
/// </summary>
[AttributeUsage(AttributeTargets.Struct | AttributeTargets.Class, AllowMultiple = true)]
public sealed class TableAttribute : Attribute
{
/// <summary>
/// This identifier is used to name the SpacetimeDB table on the host as well as the
/// table handle structures generated to access the table from within a reducer call.
/// Registers a type as the row structure of a SpacetimeDB table, enabling codegen for it.
///
/// <para>Defaults to the <c>nameof</c> of the target type.</para>
/// <para>
/// Multiple [Table] attributes per type are supported. This is useful to reuse row types.
/// Each attribute instance must have a unique name and will create a SpacetimeDB table.
/// </para>
/// </summary>
public string? Name { get; init; }
[AttributeUsage(AttributeTargets.Struct | AttributeTargets.Class, AllowMultiple = true)]
public sealed class TableAttribute : Attribute
{
/// <summary>
/// This identifier is used to name the SpacetimeDB table on the host as well as the
/// table handle structures generated to access the table from within a reducer call.
///
/// <para>Defaults to the <c>nameof</c> of the target type.</para>
/// </summary>
public string? Name { get; init; }

/// <summary>
/// Set to <c>true</c> to make the table visible to everyone.
///
/// <para>Defaults to the table only being visible to its owner.</para>
/// </summary>
public bool Public { get; init; } = false;
/// <summary>
/// Set to <c>true</c> to make the table visible to everyone.
///
/// <para>Defaults to the table only being visible to its owner.</para>
/// </summary>
public bool Public { get; init; } = false;

public string? Scheduled { get; init; }
}
public string? Scheduled { get; init; }
}

[AttributeUsage(AttributeTargets.Field)]
public abstract class ColumnAttribute : Attribute
{
public string? Table { get; init; }
}

public sealed class AutoIncAttribute : ColumnAttribute { }
public sealed class AutoIncAttribute : Internal.ColumnAttribute
{
internal override Internal.ColumnAttrs Mask => Internal.ColumnAttrs.AutoInc;
}

public sealed class PrimaryKeyAttribute : ColumnAttribute { }
public sealed class PrimaryKeyAttribute : Internal.ColumnAttribute
{
internal override Internal.ColumnAttrs Mask => Internal.ColumnAttrs.PrimaryKey;
}

public sealed class UniqueAttribute : ColumnAttribute { }
public sealed class UniqueAttribute : Internal.ColumnAttribute
{
internal override Internal.ColumnAttrs Mask => Internal.ColumnAttrs.Unique;
}

public sealed class IndexedAttribute : ColumnAttribute { }
public sealed class IndexedAttribute : Internal.ColumnAttribute
{
internal override Internal.ColumnAttrs Mask => Internal.ColumnAttrs.Indexed;
}

public static class ReducerKind
{
public const string Init = "__init__";
public const string Update = "__update__";
public const string Connect = "__identity_connected__";
public const string Disconnect = "__identity_disconnected__";
}
public static class ReducerKind
{
public const string Init = "__init__";
public const string Update = "__update__";
public const string Connect = "__identity_connected__";
public const string Disconnect = "__identity_disconnected__";
}

[AttributeUsage(AttributeTargets.Method, Inherited = false)]
public sealed class ReducerAttribute(string? name = null) : Attribute
{
public string? Name => name;
[AttributeUsage(AttributeTargets.Method, Inherited = false)]
public sealed class ReducerAttribute(string? name = null) : Attribute
{
public string? Name => name;
}
}
12 changes: 8 additions & 4 deletions crates/bindings-csharp/SpacetimeSharpSATS.sln
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "spacetimedb-quickstart-serv
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "sdk-test-multi-cs", "..\..\modules\sdk-test-multi-cs\sdk-test-multi-cs.csproj", "{960384A9-D78F-4C07-986A-1D1F3846AEBE}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "sdk-tests", "sdk-tests", "{D39E8203-6C3C-4C4B-9C7D-7911AA19D7CC}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -53,25 +55,27 @@ Global
{2C282EBD-8E37-4F4C-8EE1-E91E21E75FEE}.Release|Any CPU.ActiveCfg = Release|Any CPU
{2C282EBD-8E37-4F4C-8EE1-E91E21E75FEE}.Release|Any CPU.Build.0 = Release|Any CPU
{5393711C-44B0-4752-B8D0-852C73D6866F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{5393711C-44B0-4752-B8D0-852C73D6866F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{5393711C-44B0-4752-B8D0-852C73D6866F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{5393711C-44B0-4752-B8D0-852C73D6866F}.Release|Any CPU.Build.0 = Release|Any CPU
{40F1C615-EDD9-463F-A012-B232F6710FA5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{40F1C615-EDD9-463F-A012-B232F6710FA5}.Debug|Any CPU.Build.0 = Debug|Any CPU
{40F1C615-EDD9-463F-A012-B232F6710FA5}.Release|Any CPU.ActiveCfg = Release|Any CPU
{40F1C615-EDD9-463F-A012-B232F6710FA5}.Release|Any CPU.Build.0 = Release|Any CPU
{FDACD960-168E-44F9-B036-2E29EA391BE7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{FDACD960-168E-44F9-B036-2E29EA391BE7}.Debug|Any CPU.Build.0 = Debug|Any CPU
{FDACD960-168E-44F9-B036-2E29EA391BE7}.Release|Any CPU.ActiveCfg = Release|Any CPU
{FDACD960-168E-44F9-B036-2E29EA391BE7}.Release|Any CPU.Build.0 = Release|Any CPU
{960384A9-D78F-4C07-986A-1D1F3846AEBE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{960384A9-D78F-4C07-986A-1D1F3846AEBE}.Debug|Any CPU.Build.0 = Debug|Any CPU
{960384A9-D78F-4C07-986A-1D1F3846AEBE}.Release|Any CPU.ActiveCfg = Release|Any CPU
{960384A9-D78F-4C07-986A-1D1F3846AEBE}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{5393711C-44B0-4752-B8D0-852C73D6866F} = {D39E8203-6C3C-4C4B-9C7D-7911AA19D7CC}
{40F1C615-EDD9-463F-A012-B232F6710FA5} = {D39E8203-6C3C-4C4B-9C7D-7911AA19D7CC}
{FDACD960-168E-44F9-B036-2E29EA391BE7} = {D39E8203-6C3C-4C4B-9C7D-7911AA19D7CC}
{960384A9-D78F-4C07-986A-1D1F3846AEBE} = {D39E8203-6C3C-4C4B-9C7D-7911AA19D7CC}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {8A5DE392-1C9D-4806-B6C7-EDD4D33C5D1E}
EndGlobalSection
Expand Down
5 changes: 5 additions & 0 deletions modules/Directory.Build.props
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<!-- Only needed when referencing local dependencies as projects. For published packages, these are imported automatically. -->
<Import Project="../crates/bindings-csharp/Runtime/build/SpacetimeDB.Runtime.props" />

<!-- Prevent test projects from being picked up by `dotnet pack`. -->
<PropertyGroup>
<IsPackable>false</IsPackable>
</PropertyGroup>
</Project>
Loading