Skip to content

Commit

Permalink
NET7+ parsing support
Browse files Browse the repository at this point in the history
  • Loading branch information
lucasteles committed Jun 22, 2023
1 parent 12c2206 commit afcc578
Show file tree
Hide file tree
Showing 20 changed files with 175 additions and 193 deletions.
2 changes: 1 addition & 1 deletion global.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"sdk": {
"version": "6.0.100",
"version": "7.0.304",
"rollForward": "latestMinor",
"allowPrerelease": true
}
Expand Down
7 changes: 4 additions & 3 deletions src/Strongly/EmbeddedSources.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ static class EmbeddedSources
public const string ToStringKey = "[TO_STRING]";
public const string DefaultToString = "Value[?].ToString()";
public const string NumberStyleKey = "[NUMBER_STYLE]";
public const string CtorKey = "[CTOR_VALUE]";
public const string CtorValueKey = "[CTOR_VALUE]";
public const string CtorKey = "[CTOR]";
public const string DefaultCtor = "Value = value;";

internal static readonly string StronglyAttributeSource =
Expand Down Expand Up @@ -68,7 +69,7 @@ static class EmbeddedSources
LoadEmbeddedResource("Base.Parsable_Number");

internal static readonly ResourceCollection GuidResources = new(
typeof(Guid).FullName,
typeof(Guid).FullName!,
AutoGeneratedHeader,
LoadEmbeddedResource("Guid.Guid_Base"),
LoadEmbeddedResource("Guid.Guid_NewtonsoftJsonConverter"),
Expand Down Expand Up @@ -241,7 +242,7 @@ static class EmbeddedSources
{
TemplateVars =
{
[CtorKey] =
[CtorValueKey] =
"Value = value ?? throw new System.ArgumentNullException(nameof(value));",
},
};
Expand Down
8 changes: 6 additions & 2 deletions src/Strongly/Parser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -256,7 +256,12 @@ public static bool IsAttributeTargetForGeneration(SyntaxNode node)
break;

var location = attribute.ApplicationSyntaxReference?.GetSyntax(ct).GetLocation();
return new StronglyConfiguration(backingType, converter, implementations, cast, math,

return new StronglyConfiguration(
backingType,
converter,
implementations,
cast, math,
location);
}

Expand Down Expand Up @@ -312,7 +317,6 @@ or SyntaxKind.StructDeclaration
or SyntaxKind.RecordDeclaration;
}


static IEnumerable<ConstructorInfo> GetConstructor(INamedTypeSymbol typeSymbol)
{
foreach (var ctor in typeSymbol.Constructors)
Expand Down
38 changes: 25 additions & 13 deletions src/Strongly/SourceGenerationHelper.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;

namespace Strongly;
Expand Down Expand Up @@ -85,7 +87,7 @@ static string CreateStrongValue(
var implementations = ctx.Config.Implementations;
var useParsable = implementations.IsSet(StronglyImplementations.Parsable);
var useIFormattable = implementations.IsSet(StronglyImplementations.IFormattable);
const bool useIParsable = false;
var useIParsable = implementations.IsSet(StronglyImplementations.Parsable);
var useIEquatable =
!ctx.IsRecord && implementations.IsSet(StronglyImplementations.IEquatable);
var useIComparable =
Expand Down Expand Up @@ -128,20 +130,23 @@ static string CreateStrongValue(

var hasCtor = ctx.Constructors.Any(c => c.ArgumentType == resources.InternalType);
var baseDef = EmbeddedSources.BaseTypeDef.Value + resources.Base.Value;
baseDef = baseDef.Replace("[CTOR]", hasCtor ? string.Empty : EmbeddedSources.Ctor.Value);

if (ctx.IsRecord)
{
var ctor = baseDef.Split('\n')
.First(x => x.Trim().StartsWith("public TYPENAME("))
.Trim().Split('(', ')')[1];
sb.Append($"readonly partial record struct TYPENAME({ctor}): INTERFACES {{ \n ");
var ctorIndex =
baseDef.IndexOf(EmbeddedSources.CtorKey, StringComparison.InvariantCulture);

baseDef = baseDef
.Substring(0, ctorIndex + EmbeddedSources.CtorKey.Length)
.Replace("readonly partial struct", "readonly partial record struct")
+ Environment.NewLine;
}
else
sb.Append(baseDef);

ReplaceInterfaces(sb, useIEquatable, useIComparable, useIParsable, useIFormattable);
baseDef = baseDef.Replace(EmbeddedSources.CtorKey,
hasCtor ? string.Empty : EmbeddedSources.Ctor.Value);

sb.Append(baseDef);

ReplaceInterfaces(sb, useIEquatable, useIComparable, useIParsable, useIFormattable);

if (useIComparable) sb.AppendLine(resources.Comparable.Value);
if (useIFormattable) sb.AppendLine(resources.Formattable.Value);
Expand Down Expand Up @@ -186,8 +191,8 @@ ctx.Config.Math is not (StronglyMath.None or StronglyMath.Default))
? toStr
: EmbeddedSources.DefaultToString);

sb.Replace(EmbeddedSources.CtorKey,
resources.TemplateVars.TryGetValue(EmbeddedSources.CtorKey, out var ctorInit)
sb.Replace(EmbeddedSources.CtorValueKey,
resources.TemplateVars.TryGetValue(EmbeddedSources.CtorValueKey, out var ctorInit)
? ctorInit
: EmbeddedSources.DefaultCtor);

Expand Down Expand Up @@ -219,9 +224,16 @@ bool useIFormattable
var interfaces = new List<string>();
if (useIComparable) interfaces.Add("System.IComparable<TYPENAME>");
if (useIEquatable) interfaces.Add("System.IEquatable<TYPENAME>");
if (useIParseable) interfaces.Add("System.IParsable<TYPENAME>");
if (useIFormattable) interfaces.Add("System.IFormattable");

var interfacesNet7 = new List<string>();
if (useIParseable) interfacesNet7.Add("System.IParsable<TYPENAME>");

if (interfaces.Count > 0 || interfacesNet7.Count > 0)
sb.Replace("INTERFACES_NET7", string.Join(", ", interfaces.Concat(interfacesNet7)));
else
sb.Replace(": INTERFACES_NET7", string.Empty);

if (interfaces.Count > 0)
sb.Replace("INTERFACES", string.Join(", ", interfaces));
else
Expand Down
22 changes: 11 additions & 11 deletions src/Strongly/Strongly.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -11,26 +11,26 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="3.3.3" PrivateAssets="all" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.2.0" PrivateAssets="all" />
<ProjectReference Include="..\Strongly.Attributes\Strongly.Attributes.csproj" PrivateAssets="All" />
<PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="3.3.3" PrivateAssets="all"/>
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.2.0" PrivateAssets="all"/>
<ProjectReference Include="..\Strongly.Attributes\Strongly.Attributes.csproj" PrivateAssets="All"/>
</ItemGroup>

<ItemGroup Condition="'$(TargetFramework)' == 'netstandard2.0'">
<PackageReference Include="IsExternalInit" Version="1.0.3" PrivateAssets="all" />
<PackageReference Include="Nullable" Version="1.3.1" PrivateAssets="all" />
<PackageReference Include="IsExternalInit" Version="1.0.3" PrivateAssets="all"/>
<PackageReference Include="Nullable" Version="1.3.1" PrivateAssets="all"/>
</ItemGroup>

<ItemGroup>
<Compile Remove="Templates\**\*.cs" />
<EmbeddedResource Include="Templates\**\*.cs" />
<EmbeddedResource Include="..\Strongly.Attributes\*.cs" Link="Templates\Sources\%(Filename)%(Extension)" />
<Compile Remove="Templates\**\*.cs"/>
<EmbeddedResource Include="Templates\**\*.cs"/>
<EmbeddedResource Include="..\Strongly.Attributes\*.cs" Link="Templates\Sources\%(Filename)%(Extension)"/>
</ItemGroup>

<ItemGroup>
<None Include="$(OutputPath)\$(AssemblyName).dll" Pack="true" PackagePath="analyzers/dotnet/cs" Visible="false" />
<None Include="$(OutputPath)\Strongly.Attributes.dll" Pack="true" PackagePath="analyzers/dotnet/cs" Visible="false" />
<None Include="$(OutputPath)\Strongly.Attributes.dll" Pack="true" PackagePath="lib\netstandard2.0" Visible="true" />
<None Include="$(OutputPath)\$(AssemblyName).dll" Pack="true" PackagePath="analyzers/dotnet/cs" Visible="false"/>
<None Include="$(OutputPath)\Strongly.Attributes.dll" Pack="true" PackagePath="analyzers/dotnet/cs" Visible="false"/>
<None Include="$(OutputPath)\Strongly.Attributes.dll" Pack="true" PackagePath="lib\netstandard2.0" Visible="true"/>
</ItemGroup>

</Project>
6 changes: 5 additions & 1 deletion src/Strongly/Templates/Base/Base_Type.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@

[System.Diagnostics.DebuggerDisplay("{Value}", Type = "TYPENAME")]
#if NET7_0_OR_GREATER
readonly partial struct TYPENAME : INTERFACES_NET7
#else
readonly partial struct TYPENAME : INTERFACES
#endif
{
public BASE_TYPENAME Value { get; }

[CTOR]

public override int GetHashCode() => [GET_HASH_CODE];
public static bool operator ==(TYPENAME a, TYPENAME b) => a.Equals(b);
public static bool operator !=(TYPENAME a, TYPENAME b) => !(a == b);
Expand Down
6 changes: 4 additions & 2 deletions src/Strongly/Templates/Base/Ctor.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
 public TYPENAME(BASE_TYPENAME value)

public TYPENAME(BASE_TYPENAME value)
{
[CTOR_VALUE]
}
}

20 changes: 0 additions & 20 deletions src/Strongly/Templates/Guid/Guid_IParsable.cs

This file was deleted.

24 changes: 23 additions & 1 deletion src/Strongly/Templates/Guid/Guid_Parsable.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
new TYPENAME(System.Guid.Parse(value));

public static bool TryParse(
[System.Diagnostics.CodeAnalysis.NotNullWhen(true)]string value,
[System.Diagnostics.CodeAnalysis.NotNullWhen(true)]string? value,
out TYPENAME result)
{
if (System.Guid.TryParse(value, out System.Guid parseResult))
Expand All @@ -13,3 +13,25 @@ public static bool TryParse(
result = default;
return false;
}

#if NET7_0_OR_GREATER
public static TYPENAME Parse(string value, System.IFormatProvider? provider) =>
new TYPENAME(System.Guid.Parse(value, provider));

public static bool TryParse(
[System.Diagnostics.CodeAnalysis.NotNullWhen(true)]string? value,
System.IFormatProvider? provider,
out TYPENAME result)
{
if (System.Guid.TryParse(
value,
provider,
out System.Guid parseResult))
{
result = new TYPENAME(parseResult);
return true;
}
result = default;
return false;
}
#endif
19 changes: 0 additions & 19 deletions src/Strongly/Templates/NewId/NewId_IParsable.cs

This file was deleted.

29 changes: 27 additions & 2 deletions src/Strongly/Templates/NewId/NewId_Parsable.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@



public static TYPENAME Parse(string value) =>
new TYPENAME(new MassTransit.NewId(in value));

public static bool TryParse(
[System.Diagnostics.CodeAnalysis.NotNullWhen(true)]string value,
[System.Diagnostics.CodeAnalysis.NotNullWhen(true)]string? value,
out TYPENAME result)
{
try
Expand All @@ -17,3 +18,27 @@ public static bool TryParse(
return false;
}
}

#if NET7_0_OR_GREATER
public static TYPENAME Parse(string value, System.IFormatProvider? provider)
{
var guid = System.Guid.Parse(value, provider);
return new TYPENAME(MassTransit.NewId.FromSequentialGuid(in guid));
}

public static bool TryParse(
[System.Diagnostics.CodeAnalysis.NotNullWhen(true)]string? value,
System.IFormatProvider? provider,
out TYPENAME result)
{
if (System.Guid.TryParse(value, provider, out var guid))
{
result = new TYPENAME(MassTransit.NewId.FromSequentialGuid(in guid));
return true;
}

result = default;
return false;
}
#endif

13 changes: 0 additions & 13 deletions src/Strongly/Templates/NullableString/NullableString_IParsable.cs

This file was deleted.

15 changes: 11 additions & 4 deletions src/Strongly/Templates/NullableString/NullableString_Parsable.cs
Original file line number Diff line number Diff line change
@@ -1,13 +1,20 @@
 public static TYPENAME Parse(string value) =>

public static TYPENAME Parse(string? value) =>
new TYPENAME(value?.Trim());

public static bool TryParse(
[System.Diagnostics.CodeAnalysis.NotNullWhen(true)]string value,
[System.Diagnostics.CodeAnalysis.NotNullWhen(true)]string? value,
out TYPENAME result)
{
result = new TYPENAME(value?.Trim());
return true;
}



public static TYPENAME Parse(string? value, System.IFormatProvider? provider) => Parse(value);

public static bool TryParse(
[System.Diagnostics.CodeAnalysis.NotNullWhen(true)]
string? value,
System.IFormatProvider? provider,
out TYPENAME result) => TryParse(value, out result);

17 changes: 0 additions & 17 deletions src/Strongly/Templates/String/String_IParsable.cs

This file was deleted.

Loading

0 comments on commit afcc578

Please sign in to comment.