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

Add ExpressionMethod Generator #2695

Closed
wants to merge 21 commits into from
Closed
Show file tree
Hide file tree
Changes from 9 commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
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
2 changes: 1 addition & 1 deletion NuGet/PackLocal.cmd
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
ECHO OFF
@ECHO OFF
viceroypenguin marked this conversation as resolved.
Show resolved Hide resolved

SET VERSION=%1
SET SNUPKG=%2
Expand Down
5 changes: 5 additions & 0 deletions NuGet/linq2db.nuspec
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,13 @@
</metadata>

<files>
<!-- Primary reference files -->
<file src="..\Source\LinqToDB\bin\Release\**\linq2db.pdb" target="lib\" />
<file src="..\Source\LinqToDB\bin\Release\**\linq2db.xml" target="lib\" />
<file src="..\Source\LinqToDB\bin\Release\**\linq2db.dll" target="lib\" />

<!-- Generators -->
<file src="..\Source\LinqToDB.Analyzers\bin\Release\netstandard2.0\linq2db.Analyzers.dll"
target="analyzers\dotnet\cs" />
</files>
</package>
3 changes: 3 additions & 0 deletions Source/LinqToDB.Analyzers/AnalyzerReleases.Shipped.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
; Shipped analyzer releases
; https://github.com/dotnet/roslyn-analyzers/blob/master/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md

10 changes: 10 additions & 0 deletions Source/LinqToDB.Analyzers/AnalyzerReleases.Unshipped.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
; Unshipped analyzer release
; https://github.com/dotnet/roslyn-analyzers/blob/master/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md

### New Rules
Rule ID | Category | Severity | Notes
--------|----------|----------|-------
LDBGEN001 | LinqToDB.ExpressionMethodGenerator | Error | Diagnostics
LDBGEN002 | LinqToDB.ExpressionMethodGenerator | Error | Diagnostics
LDBGEN003 | LinqToDB.ExpressionMethodGenerator | Error | Diagnostics
LDBGEN004 | LinqToDB.ExpressionMethodGenerator | Error | Diagnostics
46 changes: 46 additions & 0 deletions Source/LinqToDB.Analyzers/Diagnostics.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.CodeAnalysis;

namespace LinqToDB.Analyzers
{
internal static class Diagnostics
{
internal static readonly DiagnosticDescriptor ClassIsNotPartialError =
new DiagnosticDescriptor(
id: "LDBGEN001",
title: "Containing class is not marked 'partial'",
messageFormat: "Class '{0}' must be marked partial",
category: "LinqToDB.ExpressionMethodGenerator",
DiagnosticSeverity.Error,
isEnabledByDefault: true);

internal static readonly DiagnosticDescriptor MethodIsNotPartialError =
new DiagnosticDescriptor(
id: "LDBGEN002",
title: "Method is not marked 'partial'",
messageFormat: "Method '{0}' must be marked partial",
category: "LinqToDB.ExpressionMethodGenerator",
DiagnosticSeverity.Error,
isEnabledByDefault: true);

internal static readonly DiagnosticDescriptor MethodReturnsVoidError =
new DiagnosticDescriptor(
id: "LDBGEN003",
title: "Method has incorrect return type",
messageFormat: "Method '{0}' must not return void",
category: "LinqToDB.ExpressionMethodGenerator",
DiagnosticSeverity.Error,
isEnabledByDefault: true);

internal static readonly DiagnosticDescriptor MethodHasIncorrectShapeError =
new DiagnosticDescriptor(
id: "LDBGEN004",
title: "Method has too many statements",
messageFormat: "Method '{0}' must consist of a single return statement",
category: "LinqToDB.ExpressionMethodGenerator",
DiagnosticSeverity.Error,
isEnabledByDefault: true);
}
}
225 changes: 225 additions & 0 deletions Source/LinqToDB.Analyzers/ExpressionMethodGenerator.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,225 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;

namespace LinqToDB.Analyzers
{
[Generator]
public class ExpressionMethodGenerator : ISourceGenerator
{
private class SyntaxReceiver : ISyntaxReceiver
{
public List<MethodDeclarationSyntax> CandidateMethods { get; } = new List<MethodDeclarationSyntax>();

public void OnVisitSyntaxNode(SyntaxNode syntaxNode)
{
// any field with at least one attribute is a candidate for property generation
if (syntaxNode is MethodDeclarationSyntax methodDeclarationSyntax
&& methodDeclarationSyntax.AttributeLists.Any()
&& methodDeclarationSyntax.AttributeLists
.SelectMany(a => a.Attributes)
.Any(a => a.Name.ToString().Contains("GenerateExpressionMethod")))
{
CandidateMethods.Add(methodDeclarationSyntax);
}
}
}

public void Initialize(GeneratorInitializationContext context)
{
// switch to DEBUG to test
#if false
if (!Debugger.IsAttached)
{
Debugger.Launch();
}
#endif

context.RegisterForSyntaxNotifications(() => new SyntaxReceiver());
}

public void Execute(GeneratorExecutionContext context)
{
if (context.SyntaxReceiver is not SyntaxReceiver receiver) return;
if (!receiver.CandidateMethods.Any()) return;

var compilation = context.Compilation;
if (compilation.GetTypeByMetadataName("LinqToDB.Mapping.GenerateExpressionMethodAttribute") is not { } attributeSymbol) return;

foreach (var c in GetCandidates(context, receiver).GroupBy(g => g.containingType))
{
var containingType = c.Key;
if (containingType.DeclaringSyntaxReferences.First().GetSyntax() is not ClassDeclarationSyntax containingTypeSyntax)
continue;

if (!containingTypeSyntax.Modifiers.Any(m => m.Text == "partial"))
viceroypenguin marked this conversation as resolved.
Show resolved Hide resolved
{
context.ReportDiagnostic(
Diagnostic.Create(
Diagnostics.ClassIsNotPartialError,
containingTypeSyntax.Identifier.GetLocation(),
containingType.Name));
continue;
}

if (c.Any(f => !f.valid)) continue;

var displayParts = containingType.ContainingNamespace.ToDisplayParts();
var names = displayParts
.Select(p => p.Symbol?.Name)
.Where(n => !string.IsNullOrWhiteSpace(n));
var fileName = string.Join(".", names) + "." + containingType.Name + ".ExpressionMethod.cs";

context.AddSource(fileName, BuildMethods(containingType.ContainingNamespace, containingTypeSyntax, c.Select(f => f.method)));
}
}

private static IEnumerable<(INamedTypeSymbol containingType, MethodDeclarationSyntax method, bool valid)> GetCandidates(
GeneratorExecutionContext context, SyntaxReceiver receiver)
{
foreach (var m in receiver.CandidateMethods)
{
var model = context.Compilation.GetSemanticModel(m.SyntaxTree);
var symbol = model.GetDeclaredSymbol(m);
if (symbol == null) continue;

var methodName = symbol.Name;
var containingType = symbol.ContainingType;
var valid = true;

if (!m.Modifiers.Any(m => m.Text == "partial"))
{
context.ReportDiagnostic(
Diagnostic.Create(
Diagnostics.MethodIsNotPartialError,
m.Identifier.GetLocation(),
methodName));
valid = false;
}

if (m.ReturnType.ToString() == "void")
{
context.ReportDiagnostic(
Diagnostic.Create(
Diagnostics.MethodReturnsVoidError,
m.ReturnType.GetLocation(),
methodName));
valid = false;
}

if (m.Body != null
&& (m.Body.Statements.Count > 1
|| m.Body.Statements[0] is not ReturnStatementSyntax))
{
context.ReportDiagnostic(
Diagnostic.Create(
Diagnostics.MethodHasIncorrectShapeError,
m.Body.Statements[1].GetLocation(),
methodName));
valid = false;
}

yield return (containingType, m, valid);
}
}

private static SourceText BuildMethods(INamespaceSymbol ns, ClassDeclarationSyntax classSyntax, IEnumerable<MethodDeclarationSyntax> methods)
{
var arrowMethodsSyntax = methods
.Where(m => m.ExpressionBody != null)
.SelectMany(BuildArrowMethod);
var bodyMethodsSyntax = methods
.Where(m => m.Body != null)
.SelectMany(BuildBodyMethod);

var unit = (CompilationUnitSyntax)classSyntax.SyntaxTree.GetRoot();
classSyntax = classSyntax
.WithMembers(new SyntaxList<MemberDeclarationSyntax>(
arrowMethodsSyntax.Concat(bodyMethodsSyntax)));

var newFile = SyntaxFactory.CompilationUnit()
.WithUsings(unit.Usings
// in case user did not include them in original file
.Add(SyntaxFactory.UsingDirective(SyntaxFactory.IdentifierName("System").WithLeadingTrivia(SyntaxFactory.Space)))
.Add(SyntaxFactory.UsingDirective(SyntaxFactory.IdentifierName("System.Linq.Expressions").WithLeadingTrivia(SyntaxFactory.Space))))
.WithMembers(SyntaxFactory.SingletonList<MemberDeclarationSyntax>(
SyntaxFactory.NamespaceDeclaration(SyntaxFactory.IdentifierName(ns.ToString()).WithLeadingTrivia(SyntaxFactory.Space))
.WithMembers(SyntaxFactory.SingletonList<MemberDeclarationSyntax>(classSyntax))));

return newFile.GetText(Encoding.UTF8);
}

private static IEnumerable<MethodDeclarationSyntax> BuildArrowMethod(MethodDeclarationSyntax m)
{
var newMethodName = $"__{m.Identifier.Text}Expression";
yield return BuildPartialOriginalMethod(m, newMethodName);

var expression = SyntaxFactory.ParenthesizedLambdaExpression()
.WithParameterList(m.ParameterList)
.WithExpressionBody(m.ExpressionBody!.Expression);

yield return BuildNewMethod(m, newMethodName, expression);
}

private static MethodDeclarationSyntax BuildNewMethod(MethodDeclarationSyntax m, string newMethodName, ParenthesizedLambdaExpressionSyntax expression)
{
var funcType =
SyntaxFactory.GenericName(
SyntaxFactory.Identifier("Func"),
SyntaxFactory.TypeArgumentList(
SyntaxFactory.SeparatedList(
m.ParameterList.Parameters
.Select(p => p.Type!))
.Add(m.ReturnType)));

var returnType =
SyntaxFactory.GenericName(
SyntaxFactory.Identifier("Expression"),
SyntaxFactory.TypeArgumentList(
SyntaxFactory.SingletonSeparatedList<TypeSyntax>(funcType)));

var method = SyntaxFactory.MethodDeclaration(returnType, newMethodName)
.WithModifiers(SyntaxFactory.TokenList(
SyntaxFactory.Token(SyntaxKind.PrivateKeyword).WithTrailingTrivia(SyntaxFactory.Space),
SyntaxFactory.Token(SyntaxKind.StaticKeyword).WithTrailingTrivia(SyntaxFactory.Space)))
.WithBody(SyntaxFactory.Block(
SyntaxFactory.SingletonList(
SyntaxFactory.ReturnStatement(expression))));
return method;
}

private static MethodDeclarationSyntax BuildPartialOriginalMethod(MethodDeclarationSyntax m, string newMethodName) =>
SyntaxFactory.MethodDeclaration(m.ReturnType, m.Identifier)
.WithParameterList(m.ParameterList)
.WithModifiers(m.Modifiers)
.WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken))
.WithAttributeLists(
SyntaxFactory.SingletonList(
SyntaxFactory.AttributeList(
SyntaxFactory.SingletonSeparatedList(
SyntaxFactory.Attribute(
SyntaxFactory.IdentifierName("LinqToDB.ExpressionMethodAttribute"),
SyntaxFactory.AttributeArgumentList(
SyntaxFactory.SingletonSeparatedList(SyntaxFactory.AttributeArgument(
SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(newMethodName))))))))));
viceroypenguin marked this conversation as resolved.
Show resolved Hide resolved

private static IEnumerable<MethodDeclarationSyntax> BuildBodyMethod(MethodDeclarationSyntax m)
{
var newMethodName = $"__{m.Identifier.Text}Expression";
yield return BuildPartialOriginalMethod(m, newMethodName);

var retStatement = (ReturnStatementSyntax) m.Body!.Statements[0];
var expression = SyntaxFactory.ParenthesizedLambdaExpression()
.WithParameterList(m.ParameterList)
.WithExpressionBody(retStatement.Expression);

yield return BuildNewMethod(m, newMethodName, expression);
}
}
}
19 changes: 19 additions & 0 deletions Source/LinqToDB.Analyzers/LinqToDB.Analyzers.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<Project Sdk="Microsoft.NET.Sdk">
<Import Project="..\..\Build\linq2db.Default.props" />

<PropertyGroup>
<AssemblyName>linq2db.Analyzers</AssemblyName>
<RootNamespace>LinqToDB.Analyzers</RootNamespace>
</PropertyGroup>

<PropertyGroup>
<TargetFrameworks>netstandard2.0</TargetFrameworks>
<Configurations>Debug;Release</Configurations>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="3.8.0" PrivateAssets="all" />
<PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="3.3.2" PrivateAssets="all" />
</ItemGroup>

</Project>
44 changes: 44 additions & 0 deletions Source/LinqToDB/Mapping/GenerateExpressionMethodAttribute.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using JetBrains.Annotations;

namespace LinqToDB.Mapping
{
/// <summary>
/// <para>
/// When applied to method, tells linq2db to create an <see cref="ExpressionMethodAttribute"/> method
/// version of the function. This is only supported in C# 9 or later, using Source Generators.
/// </para>
///
/// <para>
/// Requirements:
/// </para>
///
/// <list type="bullet">
///
/// <item>
/// <term><c>class</c></term>
/// <description>The containing class must be marked <c>partial</c>, so that the generator can add new methods to it.</description>
/// </item>
/// <item>
/// <term><c>method</c></term>
/// <description>
/// <list type="bullet">
/// <item>Must have exactly one parameter.</item>
/// <item>Must not have <c>void</c> return type.</item>
/// <item>Must have a single statement returning a mapped object.</item>
/// </list>
/// </description>
/// </item>
/// </list>
/// </summary>
/// <remarks>
/// See <see href="https://devblogs.microsoft.com/dotnet/introducing-c-source-generators/"/> for additional information.
/// </remarks>
[PublicAPI]
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
public class GenerateExpressionMethodAttribute : Attribute { }
}
Loading