Skip to content

Commit

Permalink
Add ToString methods (#437)
Browse files Browse the repository at this point in the history
* Specify runner versions

Latest macos runner had missing dependencies for testing, macos-12 still has these.

* Add ToString methods

* Allow upstream branch to trigger CI

* Specify runner versions

* Opt-in for method generation

* Opt-in for method generation
  • Loading branch information
trumully authored Nov 14, 2024
1 parent 53da419 commit 03b052b
Show file tree
Hide file tree
Showing 9 changed files with 159 additions and 4 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/dotnet.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ name: .NET

on:
push:
branches: [ main ]
branches: [ main, upstream ]
pull_request:
branches: [ main ]
branches: [ main, upstream ]
workflow_dispatch:

jobs:
Expand Down
3 changes: 3 additions & 0 deletions src/FlatSharp.Compiler/CompilerOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,9 @@ public IList<FlatBufferDeserializationOption> Deserializers
}
}

[Option("generate-methods", Hidden = false, Default = false, HelpText = "Enable generation of methods.")]
public bool GenerateMethods { get; set; }

[Option("class-definitions-only", Hidden = false, HelpText = "Emits only class and data definitions. No serializers.")]
public bool ClassDefinitionsOnly { get; set; }

Expand Down
4 changes: 4 additions & 0 deletions src/FlatSharp.Compiler/FlatSharp.Compiler.targets
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,10 @@
<CompilerCommand>$(CompilerCommand) --normalize-field-names $(FlatSharpNameNormalization)</CompilerCommand>
</PropertyGroup>

<PropertyGroup Condition=" '$(FlatSharpGenerateMethods)' == 'true' ">
<CompilerCommand>$(CompilerCommand) --generate-methods</CompilerCommand>
</PropertyGroup>

<PropertyGroup Condition=" '$(FlatSharpClassDefinitionsOnly)' == 'true' ">
<CompilerCommand>$(CompilerCommand) --class-definitions-only</CompilerCommand>
</PropertyGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,8 @@ protected sealed override void OnWriteCode(CodeWriter writer, CompileContext con
writer.AppendLine("this.OnInitialized(context);");
}

foreach (var property in this.properties.OrderBy(x => x.Key))
var orderedProperties = this.properties.OrderBy(x => x.Key);
foreach (var property in orderedProperties)
{
int index = property.Key;
PropertyFieldModel model = property.Value;
Expand All @@ -99,6 +100,14 @@ protected sealed override void OnWriteCode(CodeWriter writer, CompileContext con
sv.WriteCode(writer, context);
}

if (context.Options.GenerateMethods)
{
// This matches C# records
string fieldStrings = string.Join(", ", orderedProperties.Select(p => p.Value.FieldName).Select(n => $"{n} = {{this.{n}}}"));
string fieldStringsWithSpace = this.properties.Count == 0 ? " " : $" {fieldStrings} ";
writer.AppendLine($"public override string ToString() => $\"{this.Name} {{{{{fieldStringsWithSpace}}}}}\";");
}

this.EmitExtraData(writer, context);
}
}
Expand Down
8 changes: 8 additions & 0 deletions src/FlatSharp.Compiler/SchemaModel/ValueStructSchemaModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,14 @@ protected override void OnWriteCode(CodeWriter writer, CompileContext context)
writer.AppendLine();
}

if (context.Options.GenerateMethods)
{
// This matches C# records
string fieldStrings = string.Join(", ", this.fields.Select(x => $"{x.Name} = {{this.{x.Name}}}"));
string fieldStringsWithSpace = this.fields.Count == 0 ? " " : $" {fieldStrings} ";
writer.AppendLine($"public override string ToString() => $\"{this.Name} {{{{{fieldStringsWithSpace}}}}}\";");
}

foreach (var sv in this.structVectors)
{
writer.AppendSummaryComment($"Gets the number of items in the {sv.Name} vector.");
Expand Down
6 changes: 6 additions & 0 deletions src/FlatSharp.Compiler/SchemaModel/ValueUnionSchemaModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,12 @@ protected override void OnWriteCode(CodeWriter writer, CompileContext context)
writer.AppendLine();
writer.AppendLine("public byte Discriminator { get; }");

if (!generateUnsafeItems && context.Options.GenerateMethods)
{
string item = this.union.Values.Count == 0 ? " " : $" this.value ";
writer.AppendLine($"public override string ToString() => $\"{this.Name} {{{{ {{{item}}} }}}}\";");
}

int index = 1;
foreach (var item in innerTypes)
{
Expand Down
32 changes: 31 additions & 1 deletion src/Tests/FlatSharpEndToEndTests/FlatSharpEndToEndTests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,36 @@

<ItemGroup>
<FlatSharpSchema Include="**\*.fbs" />
<FlatSharpSchema Remove="ToStringMethods/ToStringMethods.fbs" />
</ItemGroup>
</Project>

<Target Name="FlatSharpFbsCompileToString" BeforeTargets="ResolveAssemblyReferences">
<PropertyGroup>
<CompilerVersion>net8.0</CompilerVersion>
</PropertyGroup>

<PropertyGroup>
<FlatSharpOutput>$(IntermediateOutputPath)</FlatSharpOutput>
<FlatSharpOutput Condition=" '$(FlatSharpMutationTestingMode)' == 'true' ">$(MSBuildProjectDirectory)/</FlatSharpOutput>
<FlatSharpOutput>$(FlatSharpOutput)ToStringMethods</FlatSharpOutput>
</PropertyGroup>

<MakeDir Directories="$(FlatSharpOutput)" Condition="!Exists('$(FlatSharpOutput)')" />

<!-- find compiler and set base command -->
<PropertyGroup>
<CompilerPath>$([System.IO.Path]::GetFullPath('$(MSBuildThisFileDirectory)\..\tools\$(CompilerVersion)\FlatSharp.Compiler.dll'))</CompilerPath>
<CompilerPath Condition=" '$(FlatSharpCompilerPath)' != '' ">$(FlatSharpCompilerPath)</CompilerPath>
<CompilerCommand>dotnet &quot;$(CompilerPath)&quot; --input &quot;ToStringMethods/ToStringMethods.fbs&quot; --output &quot;$(FlatSharpOutput)&quot; --generate-methods</CompilerCommand>
</PropertyGroup>

<Message Text="$(CompilerCommand)" Importance="high" />
<Exec Command="$(CompilerCommand)" CustomErrorRegularExpression=".*" />

<ItemGroup>
<GeneratedFbsToString Include="$([MSBuild]::EnsureTrailingSlash('$(FlatSharpOutput)'))FlatSharp*.cs" />
<Compile Include="@(GeneratedFbsToString)" />
<FileWrites Include="@(GeneratedFbsToString)" />
</ItemGroup>
</Target>
</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
using FlatSharp.Internal;

namespace FlatSharpEndToEndTests.ToStringMethods;

[TestClass]
public class ToStringTests
{
[TestMethod]
public void Table_ToString()
{
Assert.AreEqual("MyTable { FieldA = hello, FieldB = 123 }", new MyTable { FieldA = "hello", FieldB = 123}.ToString());
}

[TestMethod]
public void EmptyTable_ToString()
{
Assert.AreEqual("MyEmptyTable { }", new MyEmptyTable().ToString());
}

[TestMethod]
public void Struct_ToString()
{
Assert.AreEqual("MyStruct { FieldA = 456, FieldB = 123 }", new MyStruct { FieldA = 456, FieldB = 123}.ToString());
}

[TestMethod]
public void ValueStruct_ToString()
{
Assert.AreEqual("MyValueStruct { FieldX = 1, FieldY = 2 }", new MyValueStruct { FieldX = 1f, FieldY = 2f}.ToString());
}

[TestMethod]
public void UnionStructs_ToString()
{
Assert.AreEqual("StructUnion { A { V = 0 } }", new StructUnion(new A { V = 0 }).ToString());
Assert.AreEqual("StructUnion { B { V = 1 } }", new StructUnion(new B { V = 1 }).ToString());
Assert.AreEqual("StructUnion { C { V = 2 } }", new StructUnion(new C { V = 2 }).ToString());
Assert.AreEqual("StructUnion { D { V = 3 } }", new StructUnion(new D { V = 3 }).ToString());
}

[TestMethod]
public void UnionTables_ToString()
{
Assert.AreEqual("TableUnion { MyTable { FieldA = hello, FieldB = 10 } }", new TableUnion(new MyTable { FieldA = "hello", FieldB = 10 }).ToString());
Assert.AreEqual("TableUnion { MyEmptyTable { } }", new TableUnion(new MyEmptyTable()).ToString());
}

[TestMethod]
public void UnionMixed_ToString()
{
Assert.AreEqual("MixedUnion { A { V = 0 } }", new MixedUnion(new A { V = 0 }).ToString());
Assert.AreEqual("MixedUnion { A { V = 2 } }", new MixedUnion(new A { V = 2 }).ToString());
Assert.AreEqual("MixedUnion { B { V = 0 } }", new MixedUnion(new B { V = 0 }).ToString());
Assert.AreEqual("MixedUnion { MyTable { FieldA = hi, FieldB = 21 } }", new MixedUnion(new MyTable { FieldA = "hi", FieldB = 21 }).ToString());
Assert.AreEqual("MixedUnion { MyEmptyTable { } }", new MixedUnion(new MyEmptyTable()).ToString());

}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
// Declare FlatSharp attributes.

attribute "fs_serializer";
attribute "fs_valueStruct";

namespace FlatSharpEndToEndTests.ToStringMethods;


table MyTable (fs_serializer) {
FieldA: string;
FieldB: int;
}

table MyEmptyTable (fs_serializer) {
}

struct MyStruct {
FieldA: int;
FieldB: int;
}


struct MyValueStruct (fs_valueStruct) {
FieldX: float;
FieldY: float;
}

struct A { V : uint; }
struct B { V : uint; }
struct C { V : uint; }
struct D { V : uint; }

union StructUnion { A, B, C, D }

union TableUnion { MyTable, MyEmptyTable }

union MixedUnion { A, B, MyTable, MyEmptyTable }

0 comments on commit 03b052b

Please sign in to comment.