-
-
Notifications
You must be signed in to change notification settings - Fork 699
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #1093 from TelegramBots/enum_converter_generator
Enum converter source generator
- Loading branch information
Showing
60 changed files
with
1,688 additions
and
809 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,73 @@ | ||
Telegram.Bot | ||
|
||
THIRD-PARTY SOFTWARE NOTICES AND INFORMATION | ||
Do Not Translate or Localize | ||
|
||
This project incorporates components from the projects listed below. The original copyright notices and the licenses under which Camunda received such components are set forth below. | ||
|
||
1. Newtonsoft.Json (https://github.com/JamesNK/Newtonsoft.Json) | ||
2. Scriban (https://github.com/scriban/scriban) | ||
3. Nullable (https://github.com/manuelroemer/Nullable) | ||
|
||
|
||
Newtonsoft.Json NOTICES AND INFORMATION BEGIN HERE | ||
========================================== | ||
The MIT License (MIT) | ||
|
||
Copyright (c) 2007 James Newton-King | ||
|
||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: | ||
|
||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. | ||
|
||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. | ||
|
||
Scriban NOTICES AND INFORMATION BEGIN HERE | ||
========================================== | ||
Copyright (c) 2016-2020, Alexandre Mutel | ||
All rights reserved. | ||
|
||
Redistribution and use in source and binary forms, with or without modification | ||
, are permitted provided that the following conditions are met: | ||
|
||
1. Redistributions of source code must retain the above copyright notice, this | ||
list of conditions and the following disclaimer. | ||
|
||
2. Redistributions in binary form must reproduce the above copyright notice, | ||
this list of conditions and the following disclaimer in the documentation | ||
and/or other materials provided with the distribution. | ||
|
||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND | ||
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED | ||
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE | ||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE | ||
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL | ||
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR | ||
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER | ||
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, | ||
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE | ||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | ||
|
||
Nullable NOTICES AND INFORMATION BEGIN HERE | ||
========================================== | ||
MIT License | ||
|
||
Copyright (c) Manuel Römer | ||
|
||
Permission is hereby granted, free of charge, to any person obtaining a copy | ||
of this software and associated documentation files (the "Software"), to deal | ||
in the Software without restriction, including without limitation the rights | ||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
copies of the Software, and to permit persons to whom the Software is | ||
furnished to do so, subject to the following conditions: | ||
|
||
The above copyright notice and this permission notice shall be included in all | ||
copies or substantial portions of the Software. | ||
|
||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
SOFTWARE. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,179 @@ | ||
using Microsoft.CodeAnalysis; | ||
using Microsoft.CodeAnalysis.CSharp.Syntax; | ||
using Microsoft.CodeAnalysis.Text; | ||
using Scriban; | ||
using System.Collections.Immutable; | ||
using System.Text; | ||
|
||
namespace EnumSerializer.Generator; | ||
|
||
[Generator] | ||
public class EnumConverterGenerator : IIncrementalGenerator | ||
{ | ||
const string JsonConverterAttribute = "Newtonsoft.Json.JsonConverterAttribute"; | ||
|
||
public void Initialize(IncrementalGeneratorInitializationContext context) | ||
{ | ||
IncrementalValuesProvider<EnumDeclarationSyntax> enumDeclarations = context.SyntaxProvider | ||
.CreateSyntaxProvider( | ||
predicate: static (s, _) => IsSyntaxTargetForGeneration(s), | ||
transform: static (ctx, _) => GetSemanticTargetForGeneration(ctx)) | ||
.Where(static m => m is not null)!; | ||
|
||
IncrementalValueProvider<(Compilation, ImmutableArray<EnumDeclarationSyntax>)> compilationAndEnums | ||
= context.CompilationProvider.Combine(enumDeclarations.Collect()); | ||
|
||
context.RegisterSourceOutput(compilationAndEnums, | ||
static (spc, source) => Execute(source.Item1, source.Item2, spc)); | ||
} | ||
|
||
static bool IsSyntaxTargetForGeneration(SyntaxNode node) | ||
=> node is EnumDeclarationSyntax { AttributeLists.Count: > 0 }; | ||
|
||
static EnumDeclarationSyntax? GetSemanticTargetForGeneration(GeneratorSyntaxContext context) | ||
{ | ||
// we know the node is a EnumDeclarationSyntax thanks to IsSyntaxTargetForGeneration | ||
var enumDeclarationSyntax = (EnumDeclarationSyntax)context.Node; | ||
|
||
// loop through all the attributes on the method | ||
foreach (AttributeListSyntax attributeListSyntax in enumDeclarationSyntax.AttributeLists) | ||
{ | ||
foreach (AttributeSyntax attributeSyntax in attributeListSyntax.Attributes) | ||
{ | ||
if (context.SemanticModel.GetSymbolInfo(attributeSyntax).Symbol | ||
is not IMethodSymbol attributeSymbol) | ||
{ | ||
// weird, we couldn't get the symbol, ignore it | ||
continue; | ||
} | ||
|
||
INamedTypeSymbol attributeContainingTypeSymbol = attributeSymbol.ContainingType; | ||
string fullName = attributeContainingTypeSymbol.ToDisplayString(); | ||
|
||
// Is the attribute the [JsonConverterAttribute] attribute? | ||
if (fullName == JsonConverterAttribute) | ||
{ | ||
// return the enum | ||
return enumDeclarationSyntax; | ||
} | ||
} | ||
} | ||
|
||
// we didn't find the attribute we were looking for | ||
return null; | ||
} | ||
|
||
static void Execute( | ||
Compilation compilation, | ||
ImmutableArray<EnumDeclarationSyntax> enums, | ||
SourceProductionContext context) | ||
{ | ||
if (enums.IsDefaultOrEmpty) | ||
{ | ||
// nothing to do yet | ||
return; | ||
} | ||
|
||
IEnumerable<EnumDeclarationSyntax> distinctEnums = enums.Distinct(); | ||
|
||
List<EnumInfo> enumsToProcess = GetTypesToGenerate(compilation, distinctEnums, context.CancellationToken); | ||
if (enumsToProcess.Count == 0) | ||
{ | ||
return; | ||
} | ||
|
||
Template template = Template.Parse(SourceGenerationHelper.ConverterTemplate); | ||
foreach (var enumToProcess in enumsToProcess) | ||
{ | ||
var result = SourceGenerationHelper.GenerateConverterClass(template, enumToProcess); | ||
context.AddSource( | ||
hintName: $"{enumToProcess.Name}Converter.g.cs", | ||
sourceText: SourceText.From(result, Encoding.UTF8) | ||
); | ||
} | ||
} | ||
|
||
static List<EnumInfo> GetTypesToGenerate( | ||
Compilation compilation, | ||
IEnumerable<EnumDeclarationSyntax> enums, CancellationToken ct) | ||
{ | ||
var enumsToProcess = new List<EnumInfo>(); | ||
INamedTypeSymbol? enumAttribute = compilation.GetTypeByMetadataName(JsonConverterAttribute); | ||
if (enumAttribute is null) | ||
{ | ||
// nothing to do if this type isn't available | ||
return enumsToProcess; | ||
} | ||
|
||
foreach (var enumDeclarationSyntax in enums) | ||
{ | ||
// stop if we're asked to | ||
ct.ThrowIfCancellationRequested(); | ||
|
||
SemanticModel semanticModel = compilation.GetSemanticModel(enumDeclarationSyntax.SyntaxTree); | ||
if (semanticModel.GetDeclaredSymbol(enumDeclarationSyntax, cancellationToken: ct) | ||
is not INamedTypeSymbol enumSymbol) | ||
{ | ||
// report diagnostic, something went wrong | ||
continue; | ||
} | ||
|
||
string name = enumSymbol.Name; | ||
string nameSpace = enumSymbol.ContainingNamespace.IsGlobalNamespace | ||
? string.Empty | ||
: enumSymbol.ContainingNamespace.ToString(); | ||
|
||
string fullyQualifiedName = enumSymbol.ToString(); | ||
|
||
var enumMembers = enumSymbol.GetMembers(); | ||
var members = new List<KeyValuePair<string, string>>(enumMembers.Length); | ||
|
||
foreach (var member in enumMembers) | ||
{ | ||
if (member is not IFieldSymbol field | ||
|| field.ConstantValue is null) | ||
{ | ||
continue; | ||
} | ||
|
||
string? displayName = null; | ||
foreach (var attribute in member.GetAttributes()) | ||
{ | ||
if (attribute.AttributeClass is null | ||
|| attribute.AttributeClass.Name != "DisplayAttribute") | ||
{ | ||
continue; | ||
} | ||
|
||
foreach (var namedArgument in attribute.NamedArguments) | ||
{ | ||
if (namedArgument.Key == "Name" && namedArgument.Value.Value?.ToString() is { } dn) | ||
{ | ||
displayName = dn; | ||
break; | ||
} | ||
} | ||
} | ||
|
||
members.Add(new( | ||
member.Name, | ||
displayName ?? ToSnakeCase(member.Name) | ||
)); | ||
} | ||
|
||
enumsToProcess.Add(new( | ||
name: name, | ||
ns: nameSpace, | ||
fullyQualifiedName: fullyQualifiedName, | ||
members: members | ||
)); | ||
} | ||
return enumsToProcess; | ||
} | ||
|
||
static string ToSnakeCase(string name) => | ||
string.Concat(name.Select((x, i) => i > 0 && char.IsUpper(x) | ||
? $"_{x}" | ||
: x.ToString()) | ||
).ToLower(); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
namespace EnumSerializer.Generator; | ||
|
||
public readonly struct EnumInfo | ||
{ | ||
public readonly string Name; | ||
public readonly string FullyQualifiedName; | ||
public readonly string Namespace; | ||
|
||
/// <summary> | ||
/// Key is the enum name. | ||
/// </summary> | ||
public readonly List<KeyValuePair<string, string>> Members; | ||
|
||
public EnumInfo( | ||
string name, | ||
string ns, | ||
string fullyQualifiedName, | ||
List<KeyValuePair<string, string>> members) | ||
{ | ||
Name = name; | ||
Namespace = ns; | ||
Members = members; | ||
FullyQualifiedName = fullyQualifiedName; | ||
} | ||
} |
25 changes: 25 additions & 0 deletions
25
src/EnumSerializer.Generator/EnumSerializer.Generator.csproj
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
<Project Sdk="Microsoft.NET.Sdk"> | ||
|
||
<PropertyGroup> | ||
<TargetFramework>netstandard2.0</TargetFramework> | ||
<LangVersion>10</LangVersion> | ||
<Nullable>enable</Nullable> | ||
<ImplicitUsings>enable</ImplicitUsings> | ||
<IncludeBuildOutput>false</IncludeBuildOutput> | ||
<IsRoslynComponent>true</IsRoslynComponent> | ||
<EnableNETAnalyzers>True</EnableNETAnalyzers> | ||
<EnforceCodeStyleInBuild>True</EnforceCodeStyleInBuild> | ||
</PropertyGroup> | ||
|
||
<!-- The following libraries include the source generator interfaces and types we need --> | ||
<ItemGroup> | ||
<PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="3.3.3" PrivateAssets="all" /> | ||
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.1.0" PrivateAssets="all" /> | ||
<PackageReference Include="Scriban" Version="5.4.4" GeneratePathProperty="true" PrivateAssets="all" /> | ||
|
||
<!-- This ensures the library will be packaged as a source generator when we use `dotnet pack` --> | ||
<None Include="$(OutputPath)\$(AssemblyName).dll" Pack="true" PackagePath="analyzers/dotnet/cs" Visible="false" /> | ||
|
||
<TargetPathWithTargetPlatformMoniker Include="$(PKGScriban)\lib\netstandard2.0\*.dll" IncludeRuntimeDependency="false" /> | ||
</ItemGroup> | ||
</Project> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
# Enum Converter Generator | ||
|
||
## Background | ||
|
||
Telegram.Bot library relies on [Json.NET converters](https://www.newtonsoft.com/json/help/html/CustomJsonConverter.htm) | ||
to map JSON input to various enums and vice versa. | ||
|
||
It's rather tedious and repeating task. So that's where C# source generators come to help. | ||
|
||
`EnumSerializer.Generator` looks for enums | ||
annotated with `[JsonConverter(typeof(TEnumConverter))]` attribute and generates a converter that handles all possible enum values for us. | ||
|
||
## Credits | ||
|
||
This project is heavily inspired by the series of posts by Andrew Lock [Creating an incremental generator](https://andrewlock.net/creating-a-source-generator-part-1-creating-an-incremental-source-generator/) and [NetEscapades.EnumGenerators | ||
](https://github.com/andrewlock/NetEscapades.EnumGenerators) project. | ||
|
||
We use Alexandre Mutel's [Scriban](https://github.com/scriban/scriban) templating engine to generate | ||
converter class output. |
Oops, something went wrong.