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

c# client generate #1707

Merged
merged 7 commits into from
Oct 4, 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
35 changes: 27 additions & 8 deletions crates/bindings-csharp/BSATN.Codegen/Utils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -184,29 +184,48 @@ IEnumerable<T> values
return sb;
}

private static object? ResolveConstant(TypedConstant constant) =>
constant.Kind switch
private static object? ResolveConstant(TypedConstant constant, System.Type targetType)
{
if (constant.Kind == TypedConstantKind.Array)
{
TypedConstantKind.Array => constant.Values.Select(ResolveConstant).ToArray(),
_ => constant.Value,
};
// We can't use LINQ ToArray() here because it doesn't support dynamic Type
// and will build `object[]` instead of the desired `T[]`.
var elementType = targetType.GetElementType();
var array = Array.CreateInstance(elementType, constant.Values.Length);
for (var i = 0; i < constant.Values.Length; i++)
{
array.SetValue(ResolveConstant(constant.Values[i], elementType), i);
}
return array;
}
return constant.Value;
}

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.
//
// Proper overload resolution is complicated due to implicit casts
// (in particular, enums are represented as integers in the attribute data),
// which prevent APIs like `Activator.CreateInstance` from finding the constructor.
//
// Expand logic in the future if it ever becomes actually necessary.
var attr = (T)type.GetConstructors().Single().Invoke(ctorArgs);
var ctor = type.GetConstructors().Single();

var ctorArgs = attrData
.ConstructorArguments.Zip(
ctor.GetParameters().Select(param => param.ParameterType),
ResolveConstant
)
.ToArray();
var attr = (T)ctor.Invoke(ctorArgs);
foreach (var arg in attrData.NamedArguments)
{
type.GetProperty(arg.Key).SetValue(attr, ResolveConstant(arg.Value));
var prop = type.GetProperty(arg.Key);
prop.SetValue(attr, ResolveConstant(arg.Value, prop.PropertyType));
}
return attr;
}
Expand Down
80 changes: 80 additions & 0 deletions crates/bindings-csharp/BSATN.Runtime/Builtins.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
namespace SpacetimeDB;

using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using SpacetimeDB.BSATN;
using SpacetimeDB.Internal;

Expand Down Expand Up @@ -125,3 +127,81 @@ public AlgebraicType GetAlgebraicType(ITypeRegistrar registrar) =>
// This must be explicitly forwarded to base, otherwise record will generate a new implementation.
public override string ToString() => base.ToString();
}

// We store time information in microseconds in internal usages.
//
// These utils allow to encode it as such in FFI and BSATN contexts
// and convert to standard C# types.

[StructLayout(LayoutKind.Sequential)] // we should be able to use it in FFI
[SpacetimeDB.Type] // we should be able to encode it to BSATN too
public partial struct DateTimeOffsetRepr(DateTimeOffset time)
{
public ulong MicrosecondsSinceEpoch = (ulong)time.Ticks / 10;

public readonly DateTimeOffset ToStd() =>
DateTimeOffset.UnixEpoch.AddTicks(10 * (long)MicrosecondsSinceEpoch);
}

[StructLayout(LayoutKind.Sequential)] // we should be able to use it in FFI
[SpacetimeDB.Type] // we should be able to encode it to BSATN too
public partial struct TimeSpanRepr(TimeSpan duration)
{
public ulong Microseconds = (ulong)duration.Ticks / 10;

public readonly TimeSpan ToStd() => TimeSpan.FromTicks(10 * (long)Microseconds);
}

// [SpacetimeDB.Type] - we have custom representation of time in microseconds, so implementing BSATN manually
public abstract partial record ScheduleAt
: SpacetimeDB.TaggedEnum<(DateTimeOffset Time, TimeSpan Interval)>
{
// Manual expansion of what would be otherwise generated by the [SpacetimeDB.Type] codegen.
public sealed record Time(DateTimeOffset Time_) : ScheduleAt;

public sealed record Interval(TimeSpan Interval_) : ScheduleAt;

public static implicit operator ScheduleAt(DateTimeOffset time) => new Time(time);

public static implicit operator ScheduleAt(TimeSpan interval) => new Interval(interval);

public readonly partial struct BSATN : IReadWrite<ScheduleAt>
{
[SpacetimeDB.Type]
private partial record ScheduleAtRepr
: SpacetimeDB.TaggedEnum<(DateTimeOffsetRepr Time, TimeSpanRepr Interval)>;

private static readonly ScheduleAtRepr.BSATN ReprBSATN = new();

public ScheduleAt Read(BinaryReader reader) =>
ReprBSATN.Read(reader) switch
{
ScheduleAtRepr.Time(var timeRepr) => new Time(timeRepr.ToStd()),
ScheduleAtRepr.Interval(var intervalRepr) => new Interval(intervalRepr.ToStd()),
_ => throw new SwitchExpressionException(),
};

public void Write(BinaryWriter writer, ScheduleAt value)
{
ReprBSATN.Write(
writer,
value switch
{
Time(var time) => new ScheduleAtRepr.Time(new(time)),
Interval(var interval) => new ScheduleAtRepr.Interval(new(interval)),
_ => throw new SwitchExpressionException(),
}
);
}

public AlgebraicType GetAlgebraicType(ITypeRegistrar registrar) =>
// Constructing a custom one instead of ScheduleAtRepr.GetAlgebraicType()
// to avoid leaking the internal *Repr wrappers in generated SATS.
new AlgebraicType.Sum(
[
new("Time", new AlgebraicType.U64(default)),
new("Interval", new AlgebraicType.U64(default)),
]
);
}
}
8 changes: 8 additions & 0 deletions crates/bindings-csharp/Codegen.Tests/fixtures/diag/Lib.cs
Original file line number Diff line number Diff line change
Expand Up @@ -374,3 +374,11 @@ public static void TestIncompatibleScheduleReducer(
TestIncompatibleSchedule table
) { }
}

[SpacetimeDB.Table]
[SpacetimeDB.Index]
public partial struct TestIndexWithoutColumns { }

[SpacetimeDB.Table]
[SpacetimeDB.Index(BTree = [])]
public partial struct TestIndexWithEmptyColumns { }
Loading
Loading