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

Initial investigation of external converters #126

Open
wants to merge 10 commits into
base: master
Choose a base branch
from
Open
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
6 changes: 6 additions & 0 deletions .nuke/build.schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,12 @@
"type": "boolean",
"description": "Indicates to continue a previously failed build attempt"
},
"Filter": {
"type": "string"
},
"Framework": {
"type": "string"
},
"GithubToken": {
"type": "string"
},
Expand Down
4 changes: 4 additions & 0 deletions build/Build.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ class Build : NukeBuild
[Parameter] readonly string GithubToken;
[Parameter] readonly string NuGetToken;
[Parameter] readonly AbsolutePath PackagesDirectory = RootDirectory / "packages";
[Parameter] readonly string Filter;
[Parameter] readonly string Framework;

const string NugetOrgUrl = "https://api.nuget.org/v3/index.json";
bool IsTag => GitHubActions.Instance?.GitHubRef?.StartsWith("refs/tags/") ?? false;
Expand Down Expand Up @@ -88,6 +90,8 @@ class Build : NukeBuild
DotNetTest(s => s
.SetProjectFile(Solution)
.SetConfiguration(Configuration)
.When(!string.IsNullOrEmpty(Filter), x => x.SetFilter(Filter))
.When(!string.IsNullOrEmpty(Framework), x => x.SetFramework(Framework))
.EnableNoBuild()
.EnableNoRestore());
});
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by the StronglyTypedId source generator
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

#pragma warning disable 1591 // publicly visible type or member must be documented

#nullable enable

namespace StronglyTypedIds
{
/// <summary>
/// Place on partial structs to generate converters for a strongly-typed ID, <typeparamref name="T"/>.
/// </summary>
[global::System.AttributeUsage(global::System.AttributeTargets.Struct, Inherited = false, AllowMultiple = false)]
[global::System.Diagnostics.Conditional("STRONGLY_TYPED_ID_USAGES")]
public sealed class StronglyTypedIdConvertersAttribute<T> : global::System.Attribute
where T: struct
{
/// <summary>
/// Generate converters for a strongly typed ID
/// </summary>
/// <param name="templateNames">The names of the template to use to generate the converters.
/// Templates must be added to the project using the format NAME.typedid,
/// where NAME is the name of the template passed in <paramref name="templateNames"/>.
/// If no templates are provided, the default value is used, as specified by
/// <see cref="StronglyTypedIdConvertersDefaultsAttribute"/>
/// <typeparam name="T">The StronglyTyped ID implementation for which these converters are associated</typeparam>
/// </param>
public StronglyTypedIdConvertersAttribute(params string[] templateNames)
{
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by the StronglyTypedId source generator
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

#pragma warning disable 1591 // publicly visible type or member must be documented

#nullable enable

namespace StronglyTypedIds
{
/// <summary>
/// Used to control the default templates to use with <see cref="StronglyTypedIdConvertersAttribute{T}"/> instances
/// </summary>
[global::System.AttributeUsage(global::System.AttributeTargets.Assembly, Inherited = false, AllowMultiple = false)]
[global::System.Diagnostics.Conditional("STRONGLY_TYPED_ID_USAGES")]
public sealed class StronglyTypedIdConvertersDefaultsAttribute : global::System.Attribute
{
/// <summary>
/// Set the default template to use for strongly typed ID converter types
/// </summary>
/// <param name="templateName">The name of the template to use to generate the converter type.
/// Templates must be added to the project using the format NAME.typedid,
/// where NAME is the name of the template passed in <paramref name="templateName"/>.
/// </param>
public StronglyTypedIdConvertersDefaultsAttribute(string templateName)
{
}

/// <summary>
/// Set the default templates to use for strongly typed ID converter types
/// </summary>
/// <param name="templateName">The name of the template to use to generate the converter type.
/// Templates must be added to the project using the format NAME.typedid,
/// where NAME is the name of the template passed in <paramref name="templateName"/>.
/// </param>
/// <param name="templateNames">The names of additional custom templates to use to generate the converter type.
/// Templates must be added to the project using the format NAME.typedid,
/// where NAME is the name of the template passed in <paramref name="templateNames"/>.
/// </param>
public StronglyTypedIdConvertersDefaultsAttribute(string templateName, params string[] templateNames)
{
}
}
}
2 changes: 1 addition & 1 deletion src/StronglyTypedIds.Templates/guid-dapper.typedid
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
partial struct PLACEHOLDERID
partial struct TARGETTYPE
{
public partial class DapperTypeHandler : global::Dapper.SqlMapper.TypeHandler<PLACEHOLDERID>
{
Expand Down
2 changes: 1 addition & 1 deletion src/StronglyTypedIds.Templates/guid-efcore.typedid
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
partial struct PLACEHOLDERID
partial struct TARGETTYPE
{
public partial class EfCoreValueConverter : global::Microsoft.EntityFrameworkCore.Storage.ValueConversion.ValueConverter<PLACEHOLDERID, global::System.Guid>
{
Expand Down
2 changes: 1 addition & 1 deletion src/StronglyTypedIds.Templates/int-dapper.typedid
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
partial struct PLACEHOLDERID
partial struct TARGETTYPE
{
public partial class DapperTypeHandler : global::Dapper.SqlMapper.TypeHandler<PLACEHOLDERID>
{
Expand Down
2 changes: 1 addition & 1 deletion src/StronglyTypedIds.Templates/int-efcore.typedid
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
partial struct PLACEHOLDERID
partial struct TARGETTYPE
{
public partial class EfCoreValueConverter : global::Microsoft.EntityFrameworkCore.Storage.ValueConversion.ValueConverter<PLACEHOLDERID, int>
{
Expand Down
2 changes: 1 addition & 1 deletion src/StronglyTypedIds.Templates/long-dapper.typedid
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
partial struct PLACEHOLDERID
partial struct TARGETTYPE
{
public partial class DapperTypeHandler : global::Dapper.SqlMapper.TypeHandler<PLACEHOLDERID>
{
Expand Down
2 changes: 1 addition & 1 deletion src/StronglyTypedIds.Templates/long-efcore.typedid
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
partial struct PLACEHOLDERID
partial struct TARGETTYPE
{
public partial class EfCoreValueConverter : global::Microsoft.EntityFrameworkCore.Storage.ValueConversion.ValueConverter<PLACEHOLDERID, long>
{
Expand Down
2 changes: 1 addition & 1 deletion src/StronglyTypedIds.Templates/string-dapper.typedid
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
partial struct PLACEHOLDERID
partial struct TARGETTYPE
{
public partial class DapperTypeHandler : global::Dapper.SqlMapper.TypeHandler<PLACEHOLDERID>
{
Expand Down
2 changes: 1 addition & 1 deletion src/StronglyTypedIds.Templates/string-efcore.typedid
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
partial struct PLACEHOLDERID
partial struct TARGETTYPE
{
public partial class EfCoreValueConverter : global::Microsoft.EntityFrameworkCore.Storage.ValueConversion.ValueConverter<PLACEHOLDERID, string>
{
Expand Down
16 changes: 16 additions & 0 deletions src/StronglyTypedIds/Diagnostics/MissingDefaultsDiagnostic.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
using Microsoft.CodeAnalysis;

namespace StronglyTypedIds.Diagnostics;

internal static class MissingDefaultsDiagnostic
{
internal const string Id = "STRONGID005";
internal const string Message = "You must specify the default template to use for converters using [StronglyTypedIdConvertersDefaults]";
internal const string Title = "Missing [StronglyTypedIdConvertersDefaults] attribute";

public static DiagnosticInfo CreateInfo(Location location) =>
new(new DiagnosticDescriptor(
Id, Title, Message, category: Constants.Usage, defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true),
location);
}
2 changes: 2 additions & 0 deletions src/StronglyTypedIds/EmbeddedSources.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ internal static partial class EmbeddedSources
private static readonly Assembly ThisAssembly = typeof(EmbeddedSources).Assembly;
internal static readonly string StronglyTypedIdAttributeSource = LoadAttributeTemplateForEmitting("StronglyTypedIdAttribute");
internal static readonly string StronglyTypedIdDefaultsAttributeSource = LoadAttributeTemplateForEmitting("StronglyTypedIdDefaultsAttribute");
internal static readonly string StronglyTypedIdConvertersAttributeSource = LoadAttributeTemplateForEmitting("StronglyTypedIdConvertersAttribute");
internal static readonly string StronglyTypedIdConvertersDefaultsAttributeSource = LoadAttributeTemplateForEmitting("StronglyTypedIdConvertersDefaultsAttribute");
internal static readonly string TemplateSource = LoadAttributeTemplateForEmitting("Template");

internal static readonly string AutoGeneratedHeader = LoadEmbeddedResource("StronglyTypedIds.Templates.AutoGeneratedHeader.cs");
Expand Down
147 changes: 145 additions & 2 deletions src/StronglyTypedIds/Parser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,10 @@ internal static class Parser
{
public const string StronglyTypedIdAttribute = "StronglyTypedIds.StronglyTypedIdAttribute";
public const string StronglyTypedIdDefaultsAttribute = "StronglyTypedIds.StronglyTypedIdDefaultsAttribute";
public const string StronglyTypedIdConvertersAttribute = "StronglyTypedIds.StronglyTypedIdConvertersAttribute`1";
public const string StronglyTypedIdConvertersDefaultsAttribute = "StronglyTypedIds.StronglyTypedIdConvertersDefaultsAttribute";

public static Result<(StructToGenerate info, bool valid)> GetStructSemanticTarget(GeneratorAttributeSyntaxContext ctx, CancellationToken ct)
public static Result<(StructToGenerate info, bool valid)> GetIdSemanticTarget(GeneratorAttributeSyntaxContext ctx, CancellationToken ct)
{
var structSymbol = ctx.TargetSymbol as INamedTypeSymbol;
if (structSymbol is null)
Expand Down Expand Up @@ -88,7 +90,7 @@ internal static class Parser
return new Result<(StructToGenerate, bool)>((toGenerate, true), errors);
}

public static Result<(Defaults defaults, bool valid)> GetDefaults(
public static Result<(Defaults defaults, bool valid)> GetIdDefaults(
GeneratorAttributeSyntaxContext ctx, CancellationToken ct)
{
var assemblyAttributes = ctx.TargetSymbol.GetAttributes();
Expand Down Expand Up @@ -147,6 +149,147 @@ internal static class Parser
}

var defaults = new Defaults(template, templateNames, attributeLocation!, hasMultiple);
return new Result<(Defaults, bool)>((defaults, true), errors);
}

public static Result<(ConverterToGenerate info, bool valid)> GetConvertersSemanticTarget(GeneratorAttributeSyntaxContext ctx, CancellationToken ct)
{
var structSymbol = ctx.TargetSymbol as INamedTypeSymbol;
if (structSymbol is null)
{
return Result<ConverterToGenerate>.Fail();
}

var structSyntax = (StructDeclarationSyntax)ctx.TargetNode;

var hasMisconfiguredInput = false;
List<DiagnosticInfo>? diagnostics = null;
string[]? templateNames = null;
LocationInfo? attributeLocation = null;
string? idName = null;

foreach (AttributeData attribute in structSymbol.GetAttributes())
{
if (!((attribute.AttributeClass?.Name == "StronglyTypedIdConvertersAttribute" ||
attribute.AttributeClass?.Name == "StronglyTypedIdConverters") &&
attribute.AttributeClass.IsGenericType &&
attribute.AttributeClass.TypeArguments.Length == 1))
{
// wrong attribute
continue;
}

// Can never have template
(var result, (_, templateNames)) = GetConstructorValues(attribute);
hasMisconfiguredInput |= result;

if (attribute.ApplicationSyntaxReference?.GetSyntax() is { } s)
{
attributeLocation = LocationInfo.CreateFrom(s);
}

var typeParameter = attribute.AttributeClass.TypeArguments[0];
idName = typeParameter.ToString();
}

var hasPartialModifier = false;
foreach (var modifier in structSyntax.Modifiers)
{
if (modifier.IsKind(SyntaxKind.PartialKeyword))
{
hasPartialModifier = true;
break;
}
}

if (!hasPartialModifier)
{
diagnostics ??= new();
diagnostics.Add(NotPartialDiagnostic.CreateInfo(structSyntax));
}

var errors = diagnostics is null
? EquatableArray<DiagnosticInfo>.Empty
: new EquatableArray<DiagnosticInfo>(diagnostics.ToArray());

if (hasMisconfiguredInput || idName is null)
{
return new Result<(ConverterToGenerate, bool)>((default, false), errors);
}

string nameSpace = GetNameSpace(structSyntax);
ParentClass? parentClass = GetParentClasses(structSyntax);
var name = structSymbol.Name;

var toGenerate = new ConverterToGenerate(
name: name,
nameSpace: nameSpace,
idName: idName,
templateNames: templateNames,
templateLocation: attributeLocation!,
parent: parentClass);

return new Result<(ConverterToGenerate, bool)>((toGenerate, true), errors);
}

public static Result<(Defaults defaults, bool valid)> GetConverterDefaults(
GeneratorAttributeSyntaxContext ctx, CancellationToken ct)
{
var assemblyAttributes = ctx.TargetSymbol.GetAttributes();
if (assemblyAttributes.IsDefaultOrEmpty)
{
return Result<Defaults>.Fail();
}

// We only return the first config that we find
string[]? templateNames = null;
LocationInfo? attributeLocation = null;
List<DiagnosticInfo>? diagnostics = null;
bool hasMisconfiguredInput = false;
bool hasMultiple = false;

// if we have multiple attributes we still check them, so that we can add extra diagnostics if necessary
// the "first" one found won't be flagged as a duplicate though.
foreach (AttributeData attribute in assemblyAttributes)
{
if (!((attribute.AttributeClass?.Name == "StronglyTypedIdConvertersDefaultsAttribute" ||
attribute.AttributeClass?.Name == "StronglyTypedIdConvertersDefaults") &&
attribute.AttributeClass.ToDisplayString() == StronglyTypedIdConvertersDefaultsAttribute))
{
// wrong attribute
continue;
}

var syntax = attribute.ApplicationSyntaxReference?.GetSyntax();
if (templateNames is not null || hasMisconfiguredInput)
{
hasMultiple = true;
if (syntax is not null)
{
diagnostics ??= new();
diagnostics.Add(MultipleAssemblyAttributeDiagnostic.CreateInfo(syntax));
}
}

(var result, (_, templateNames)) = GetConstructorValues(attribute);
hasMisconfiguredInput |= result;

if (syntax is not null)
{
attributeLocation = LocationInfo.CreateFrom(syntax);
}
}

var errors = diagnostics is null
? EquatableArray<DiagnosticInfo>.Empty
: new EquatableArray<DiagnosticInfo>(diagnostics.ToArray());

if (hasMisconfiguredInput)
{
return new Result<(Defaults, bool)>((default, false), errors);
}

var defaults = new Defaults(template: null, templateNames, attributeLocation!, hasMultiple);

return new Result<(Defaults, bool)>((defaults, true), errors);
}
Expand Down
Loading
Loading