Skip to content

Commit

Permalink
add compare operators for Guid and fix bug when there no global attri…
Browse files Browse the repository at this point in the history
…bute
  • Loading branch information
lucasteles committed Aug 24, 2023
1 parent d223a66 commit f99bbd6
Show file tree
Hide file tree
Showing 13 changed files with 129 additions and 52 deletions.
12 changes: 9 additions & 3 deletions src/Strongly/EmbeddedSources.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,10 @@ static class EmbeddedSources
internal static readonly Lazy<string> MathAddition = LoadEmbeddedResource("Base.Math_Addition");
internal static readonly Lazy<string> MathDivision = LoadEmbeddedResource("Base.Math_Division");
internal static readonly Lazy<string> MathNegation = LoadEmbeddedResource("Base.Math_Negation");
internal static readonly Lazy<string> MathCompare = LoadEmbeddedResource("Base.Math_Compare");


internal static readonly Lazy<string> OperatorsCompare =
LoadEmbeddedResource("Base.Operators_Compare");

internal static readonly Lazy<string> MathSubtraction =
LoadEmbeddedResource("Base.Math_Subtraction");
Expand Down Expand Up @@ -80,7 +83,8 @@ static class EmbeddedSources
DefaultIComparable,
LoadEmbeddedResource("Guid.Guid_SwaggerSchemaFilter"),
LoadEmbeddedResource("Guid.Guid_Parsable"),
DefaultIFormattable
DefaultIFormattable,
LoadEmbeddedResource("Guid.Guid_OperatorsCompare")
)
{
Customizations =
Expand Down Expand Up @@ -319,7 +323,9 @@ public readonly record struct ResourceCollection(
Lazy<string> Comparable,
Lazy<string> SwaggerSchemaFilter,
Lazy<string> Parsable,
Lazy<string> Formattable)
Lazy<string> Formattable,
Lazy<string>? CompareOperators = null
)
{
public bool IsNumeric { get; init; } = false;
public bool NullableEnable { get; init; } = false;
Expand Down
10 changes: 6 additions & 4 deletions src/Strongly/Parser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,14 @@ static class Parser
const string StronglyDefaultsAttribute = "Strongly.StronglyDefaultsAttribute";

public static bool IsStructTargetForGeneration(SyntaxNode node)
=> node is TypeDeclarationSyntax { AttributeLists.Count: > 0 } t
=> node is TypeDeclarationSyntax {AttributeLists.Count: > 0} t
&& t.Modifiers.Any(SyntaxKind.PartialKeyword)
&&
(node.IsKind(SyntaxKind.StructDeclaration) ||
node.IsKind(SyntaxKind.RecordStructDeclaration));

public static bool IsAttributeTargetForGeneration(SyntaxNode node)
=> node is AttributeListSyntax { Target.Identifier: var id }
=> node is AttributeListSyntax {Target.Identifier: var id}
&& id.IsKind(SyntaxKind.AssemblyKeyword);

public static TypeDeclarationSyntax? GetStructSemanticTargetForGeneration(
Expand Down Expand Up @@ -261,8 +261,10 @@ public static bool IsAttributeTargetForGeneration(SyntaxNode node)
backingType,
converter,
implementations,
cast, math,
location);
cast,
math,
location
);
}

return null;
Expand Down
7 changes: 5 additions & 2 deletions src/Strongly/SourceGenerationHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -167,10 +167,10 @@ static string CreateStrongValue(
if (castOperators.IsSet(StronglyCast.ImplicitTo))
sb.AppendLine(EmbeddedSources.ImplicitTo.Value);

var math = ctx.Config.Math;
if (resources.IsNumeric &&
ctx.Config.Math is not (StronglyMath.None or StronglyMath.Default))
{
var math = ctx.Config.Math;
sb.AppendLine(EmbeddedSources.MathConst.Value);
if (math.IsSet(StronglyMath.Addition))
sb.AppendLine(EmbeddedSources.MathAddition.Value);
Expand All @@ -183,8 +183,11 @@ ctx.Config.Math is not (StronglyMath.None or StronglyMath.Default))
if (math.IsSet(StronglyMath.Negation))
sb.AppendLine(EmbeddedSources.MathNegation.Value);
if (math.IsSet(StronglyMath.Compare))
sb.AppendLine(EmbeddedSources.MathCompare.Value);
sb.AppendLine(EmbeddedSources.OperatorsCompare.Value);
}
else if (resources.CompareOperators is not null && math.IsSet(StronglyMath.Compare))
if (math.IsSet(StronglyMath.Compare))
sb.AppendLine(resources.CompareOperators.Value);

sb.Replace(EmbeddedSources.ToStringKey,
resources.TemplateVars.TryGetValue(EmbeddedSources.ToStringKey, out var toStr)
Expand Down
5 changes: 3 additions & 2 deletions src/Strongly/StronglyConfiguration.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ public static StronglyConfiguration Combine(
(StronglyType.Default, null) => Defaults.BackingType,
(StronglyType.Default, StronglyType.Default) => Defaults.BackingType,
(StronglyType.Default, var globalDefault) => globalDefault.Value,
var (specificValue, _) => specificValue
var (specificValue, _) => specificValue,
};

var converter = (attributeValues.Converters, globalValues?.Converters) switch
Expand Down Expand Up @@ -84,6 +84,7 @@ public static StronglyConfiguration Combine(
converter,
implementations,
casts,
math);
math
);
}
}
2 changes: 1 addition & 1 deletion src/Strongly/StronglyGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ public void Initialize(IncrementalGeneratorInitializationContext context)
{
Config = StronglyConfiguration.Combine(
context.Config,
globalDefaults.Single()
globalDefaults.SingleOrDefault()
),
};
})
Expand Down
File renamed without changes.
6 changes: 6 additions & 0 deletions src/Strongly/Templates/Guid/Guid_OperatorsCompare.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
#if NET7_0_OR_GREATER
public static bool operator <(TYPENAME a, TYPENAME b) => (a.Value < b.Value);
public static bool operator >(TYPENAME a, TYPENAME b) => (a.Value > b.Value);
public static bool operator <=(TYPENAME a, TYPENAME b) => (a.Value <= b.Value);
public static bool operator >=(TYPENAME a, TYPENAME b) => (a.Value >= b.Value);
#endif
14 changes: 9 additions & 5 deletions test/Strongly.Tests/GuidIdTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ public void CanDeserializeFromGuid_WithNewtonsoftJsonProvider()
[Fact]
public void CanSerializeToNullableInt_WithNewtonsoftJsonProvider()
{
var entity = new EntityWithNullableId { Id = null };
var entity = new EntityWithNullableId {Id = null};

var json = NewtonsoftJsonSerializer.SerializeObject(entity);
var deserialize =
Expand Down Expand Up @@ -237,7 +237,7 @@ public void WhenEfValueConverterUsesValueConverter()
{
context.Database.EnsureCreated();
context.Entities.Add(
new TestEntity { Id = EfCoreGuidId.New() });
new TestEntity {Id = EfCoreGuidId.New()});
context.SaveChanges();
}

Expand Down Expand Up @@ -329,7 +329,7 @@ public void WhenConventionBasedEfValueConverterUsesValueConverter()
{
context.Database.EnsureCreated();
context.Entities.Add(
new TestEntity { Id = EfCoreGuidId.New() });
new TestEntity {Id = EfCoreGuidId.New()});
context.SaveChanges();
}

Expand All @@ -344,7 +344,9 @@ public class ConventionsDbContext : DbContext
{
public DbSet<TestEntity> Entities { get; set; }

public ConventionsDbContext(DbContextOptions options) : base(options) { }
public ConventionsDbContext(DbContextOptions options) : base(options)
{
}

protected override void ConfigureConventions(
ModelConfigurationBuilder configurationBuilder)
Expand Down Expand Up @@ -397,7 +399,9 @@ public class TestDbContext : DbContext
{
public DbSet<TestEntity> Entities { get; set; }

public TestDbContext(DbContextOptions options) : base(options) { }
public TestDbContext(DbContextOptions options) : base(options)
{
}

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
Expand Down
24 changes: 19 additions & 5 deletions test/Strongly.Tests/SequentialGuidIdTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ public void DifferentTypesAreUnequal()
var foo = SequentialGuidId1.New();

//Assert.NotEqual(bar, foo); // does not compile
Assert.NotEqual((object)bar, (object)foo);
Assert.NotEqual((object) bar, (object) foo);
}

[Fact]
Expand All @@ -82,7 +82,7 @@ public void CantCreateEmptyGeneratedId1()
var bar = new SequentialGuidId2();

//Assert.NotEqual(bar, foo); // does not compile
Assert.NotEqual((object)bar, (object)foo);
Assert.NotEqual((object) bar, (object) foo);
}

[Fact]
Expand Down Expand Up @@ -160,7 +160,7 @@ public void CanDeserializeFromSequentialGuid_WithNewtonsoftJsonProvider()
[Fact]
public void CanSerializeToNullableInt_WithNewtonsoftJsonProvider()
{
var entity = new EntityWithNullableId { Id = null };
var entity = new EntityWithNullableId {Id = null};

var json = NewtonsoftJsonSerializer.SerializeObject(entity);
var deserialize =
Expand Down Expand Up @@ -251,7 +251,7 @@ public void WhenEfValueConverterUsesValueConverter()
{
context.Database.EnsureCreated();
context.Entities.Add(
new TestEntity { Id = EfCoreSequentialGuidId.New() });
new TestEntity {Id = EfCoreSequentialGuidId.New()});
context.SaveChanges();
}

Expand Down Expand Up @@ -345,7 +345,7 @@ public void WhenConventionBasedEfValueConverterUsesValueConverter()
{
context.Database.EnsureCreated();
context.Entities.Add(
new TestEntity { Id = EfCoreSequentialGuidId.New() });
new TestEntity {Id = EfCoreSequentialGuidId.New()});
context.SaveChanges();
}

Expand Down Expand Up @@ -441,4 +441,18 @@ public class EntityWithNullableId
{
public NewtonsoftJsonSequentialGuidId? Id { get; set; }
}

#if NET7_0_OR_GREATER
[Fact]
public void ComparableOperators()
{
var value1 = ComparableGuid.New();
var value2 = ComparableGuid.New();

Assert.True(value1 < value2);
Assert.True(value1 <= value2);
Assert.True(value2 > value1);
Assert.True(value2 >= value1);
}
#endif
}
26 changes: 13 additions & 13 deletions test/Strongly.Tests/Strongly.Tests.csproj
Original file line number Diff line number Diff line change
@@ -1,32 +1,32 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFrameworks>net6.0;net7.0</TargetFrameworks>
<TargetFrameworks>net7.0;net6.0</TargetFrameworks>
<IsPackable>false</IsPackable>
<EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
<InvariantGlobalization>true</InvariantGlobalization>
<RootNamespace>Strongly.IntegrationTests</RootNamespace>
</PropertyGroup>

<ItemGroup>
<ProjectReference Include="..\..\src\Strongly\Strongly.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
<ProjectReference Include="..\..\src\Strongly.Attributes\Strongly.Attributes.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="true" />
<ProjectReference Include="..\..\src\Strongly\Strongly.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false"/>
<ProjectReference Include="..\..\src\Strongly.Attributes\Strongly.Attributes.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="true"/>
</ItemGroup>

<ItemGroup>
<Content Include="xunit.runner.json" CopyToOutputDirectory="PreserveNewest" />
<Content Include="xunit.runner.json" CopyToOutputDirectory="PreserveNewest"/>
</ItemGroup>

<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="6.0.0-*" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="6.0.0-*" />
<PackageReference Include="System.Text.Json" Version="6.0.0-*" />
<PackageReference Include="Swashbuckle.AspNetCore.Annotations" Version="6.4.0" />
<PackageReference Include="NewId" Version="4.0.0-develop.44" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.5.0" />
<PackageReference Include="Dapper" Version="2.0.90" />
<PackageReference Include="xunit" Version="2.4.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="6.0.0-*"/>
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="6.0.0-*"/>
<PackageReference Include="System.Text.Json" Version="6.0.0-*"/>
<PackageReference Include="Swashbuckle.AspNetCore.Annotations" Version="6.4.0"/>
<PackageReference Include="NewId" Version="4.0.0-develop.44"/>
<PackageReference Include="Newtonsoft.Json" Version="13.0.1"/>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.5.0"/>
<PackageReference Include="Dapper" Version="2.0.90"/>
<PackageReference Include="xunit" Version="2.4.1"/>
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.3">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
Expand Down
64 changes: 48 additions & 16 deletions test/Strongly.Tests/Types/GuidId.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,60 +3,92 @@
namespace Strongly.IntegrationTests.Types;

[Strongly(StronglyType.Guid)]
public partial struct GuidId1 { }
public partial struct GuidId1
{
}

[Strongly(StronglyType.Guid)]
public partial struct GuidId2 { }
public partial struct GuidId2
{
}

[Strongly(StronglyType.Guid, StronglyConverter.None)]
public partial struct NoConverterGuidId { }
public partial struct NoConverterGuidId
{
}

[Strongly(StronglyType.Guid, StronglyConverter.TypeConverter)]
public partial struct NoJsonGuidId { }
public partial struct NoJsonGuidId
{
}

[Strongly(StronglyType.Guid, StronglyConverter.NewtonsoftJson)]
public partial struct NewtonsoftJsonGuidId { }
public partial struct NewtonsoftJsonGuidId
{
}

[Strongly(StronglyType.Guid,
StronglyConverter.TypeConverter | StronglyConverter.SystemTextJson)]
public partial struct SystemTextJsonGuidId { }
public partial struct SystemTextJsonGuidId
{
}

[Strongly(StronglyType.Guid,
StronglyConverter.NewtonsoftJson | StronglyConverter.SystemTextJson)]
public partial struct BothJsonGuidId { }
public partial struct BothJsonGuidId
{
}

[Strongly(StronglyType.Guid, StronglyConverter.EfValueConverter)]
public partial struct EfCoreGuidId { }
public partial struct EfCoreGuidId
{
}

[Strongly(StronglyType.Guid, StronglyConverter.DapperTypeHandler)]
public partial struct DapperGuidId { }
public partial struct DapperGuidId
{
}

#if NET5_0_OR_GREATER
[Strongly(StronglyType.Guid, StronglyConverter.SwaggerSchemaFilter)]
public partial struct SwaggerGuidId { }
public partial struct SwaggerGuidId
{
}
#endif

[Strongly(StronglyType.Guid,
implementations: StronglyImplementations.IEquatable | StronglyImplementations.IComparable)]
public partial struct BothGuidId { }
public partial struct BothGuidId
{
}

[Strongly(StronglyType.Guid, implementations: StronglyImplementations.IEquatable)]
public partial struct EquatableGuidId { }
public partial struct EquatableGuidId
{
}

[Strongly(StronglyType.Guid, implementations: StronglyImplementations.IComparable)]
public partial struct ComparableGuidId { }
public partial struct ComparableGuidId
{
}

[Strongly(StronglyType.Guid)]
public partial record struct RecordGuidId1;

[Strongly(StronglyType.Guid, cast: StronglyCast.Implicit)]
public partial struct ImplicitGuid { }
public partial struct ImplicitGuid
{
}

[Strongly(StronglyType.Guid, cast: StronglyCast.Explicit)]
public partial struct ExplicitGuid { }
public partial struct ExplicitGuid
{
}

[Strongly(StronglyType.Guid, implementations: StronglyImplementations.IFormattable)]
public partial struct FormattableGuidId { }
public partial struct FormattableGuidId
{
}

[Strongly(StronglyType.Guid)]
public partial struct CtorGuidId
Expand Down
Loading

0 comments on commit f99bbd6

Please sign in to comment.