增量源码生成

This commit is contained in:
ChenYi 2025-04-28 09:53:45 +08:00
parent c5c428f551
commit cab0e1ed08
8 changed files with 233 additions and 8 deletions

View File

@ -62,6 +62,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "0.Docs", "0.Docs", "{D8346C
readme.md = readme.md
EndProjectSection
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "JiShe.CollectBus.SourceExtend", "shared\JiShe.CollectBus.SourceExtend\JiShe.CollectBus.SourceExtend.csproj", "{A34A4EA6-AEB0-4199-8E3A-6F042DBB51D9}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@ -148,6 +150,10 @@ Global
{75B7D419-C261-577D-58D6-AA3ACED9129F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{75B7D419-C261-577D-58D6-AA3ACED9129F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{75B7D419-C261-577D-58D6-AA3ACED9129F}.Release|Any CPU.Build.0 = Release|Any CPU
{A34A4EA6-AEB0-4199-8E3A-6F042DBB51D9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{A34A4EA6-AEB0-4199-8E3A-6F042DBB51D9}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A34A4EA6-AEB0-4199-8E3A-6F042DBB51D9}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A34A4EA6-AEB0-4199-8E3A-6F042DBB51D9}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
@ -173,6 +179,7 @@ Global
{8A61DF78-069B-40B5-8811-614E2960443E} = {3C3F9DB2-EC97-4464-B49F-BF1A0C2B46DC}
{E27377CC-E2D3-4237-060F-96EA214D3129} = {3C3F9DB2-EC97-4464-B49F-BF1A0C2B46DC}
{75B7D419-C261-577D-58D6-AA3ACED9129F} = {3C3F9DB2-EC97-4464-B49F-BF1A0C2B46DC}
{A34A4EA6-AEB0-4199-8E3A-6F042DBB51D9} = {EBF7C01F-9B4F-48E6-8418-2CBFDA51EB0B}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {4324B3B4-B60B-4E3C-91D8-59576B4E26DD}

View File

@ -11,5 +11,6 @@
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\shared\JiShe.CollectBus.Common\JiShe.CollectBus.Common.csproj" />
<ProjectReference Include="..\..\shared\JiShe.CollectBus.SourceExtend\JiShe.CollectBus.SourceExtend.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false"/>
</ItemGroup>
</Project>

View File

@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using JiShe.CollectBus.Common.Attributes;
using JiShe.CollectBus.IoTDB.Attribute;
using JiShe.CollectBus.IoTDB.Enums;
using JiShe.CollectBus.IoTDB.Provider;
@ -13,6 +14,7 @@ namespace JiShe.CollectBus.IoTDB.Model
/// Table模型单项数据实体
/// </summary>
[EntityType(EntityTypeEnum.TableModel)]
[GenerateAccessors]
public class TableModelSingleMeasuringEntity<T> : IoTEntity
{
/// <summary>

View File

@ -23,7 +23,7 @@
<ItemGroup>
<ProjectReference Include="..\..\modules\JiShe.CollectBus.FreeSql\JiShe.CollectBus.FreeSql.csproj" />
<ProjectReference Include="..\..\modules\JiShe.CollectBus.IoTDB\JiShe.CollectBus.IoTDB.csproj" />
<ProjectReference Include="..\..\shared\JiShe.CollectBus.Common\JiShe.CollectBus.Common.csproj" />
<ProjectReference Include="..\..\shared\JiShe.CollectBus.Common\JiShe.CollectBus.Common.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
<ProjectReference Include="..\..\shared\JiShe.CollectBus.Domain.Shared\JiShe.CollectBus.Domain.Shared.csproj" />
</ItemGroup>

View File

@ -0,0 +1,187 @@
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JiShe.CollectBus.SourceExtend
{
/// <summary>
/// 复杂类型源生成器
/// </summary>
[Generator]
public sealed class PropertyAccessorGenerator : IIncrementalGenerator
{
private const string AttributeName = "GenerateAccessors";
public void Initialize(IncrementalGeneratorInitializationContext context)
{
// 步骤1筛选带有 [GenerateAccessors] 的类
var classDeclarations = context.SyntaxProvider
.CreateSyntaxProvider(
predicate: static (s, _) => IsClassWithAttribute(s),
transform: static (ctx, _) => GetClassDeclaration(ctx))
.Where(static c => c is not null);
// 步骤2编译符号并生成代码
var compilationAndClasses = context.CompilationProvider.Combine(classDeclarations.Collect());
context.RegisterSourceOutput(compilationAndClasses, (spc, source) =>
GenerateCode(source.Left, source.Right!, spc));
}
private static bool IsClassWithAttribute(SyntaxNode node)
{
return node is ClassDeclarationSyntax { AttributeLists.Count: > 0 };
}
private static ClassDeclarationSyntax? GetClassDeclaration(GeneratorSyntaxContext context)
{
var classDecl = (ClassDeclarationSyntax)context.Node;
foreach (var attributeList in classDecl.AttributeLists)
{
foreach (var attribute in attributeList.Attributes)
{
var symbol = context.SemanticModel.GetSymbolInfo(attribute).Symbol;
if (symbol?.ContainingType.ToDisplayString() == $"{nameof(PropertyAccessorGenerator)}.{AttributeName}")
{
return classDecl;
}
}
}
return null;
}
private static void GenerateCode(
Compilation compilation,
IEnumerable<ClassDeclarationSyntax> classes,
SourceProductionContext context)
{
var processedTypes = new HashSet<ITypeSymbol>(SymbolEqualityComparer.Default);
foreach (var classDecl in classes.Distinct())
{
var model = compilation.GetSemanticModel(classDecl.SyntaxTree);
var classSymbol = model.GetDeclaredSymbol(classDecl)!;
if (!processedTypes.Add(classSymbol)) continue;
var code = BuildAccessorsForType(classSymbol, compilation, processedTypes);
context.AddSource($"{classSymbol.Name}Accessors.g.cs", code);
}
}
private static string BuildAccessorsForType(
INamedTypeSymbol classSymbol,
Compilation compilation,
HashSet<ITypeSymbol> processedTypes)
{
var code = new StringBuilder();
code.AppendLine("// <auto-generated/>");
code.AppendLine("#nullable enable");
code.AppendLine();
code.AppendLine($"namespace {classSymbol.ContainingNamespace.ToDisplayString()};");
code.AppendLine();
// 处理泛型参数
var genericParams = classSymbol.IsGenericType
? $"<{string.Join(", ", classSymbol.TypeParameters.Select(t => t.Name))}>"
: "";
code.AppendLine($"public static class {classSymbol.Name}Accessors{genericParams}");
code.AppendLine("{");
foreach (var prop in classSymbol.GetMembers().OfType<IPropertySymbol>())
{
if (prop.IsIndexer) continue;
GeneratePropertyAccessors(prop, code, compilation, processedTypes);
}
code.AppendLine("}");
return code.ToString();
}
private static void GeneratePropertyAccessors(
IPropertySymbol prop,
StringBuilder code,
Compilation compilation,
HashSet<ITypeSymbol> processedTypes)
{
var propType = prop.Type;
var parentType = prop.ContainingType.ToDisplayString();
// 处理元组类型
if (propType.IsTupleType && propType is INamedTypeSymbol tupleType)
{
GenerateTupleAccessors(prop, tupleType, code);
}
else if (propType is INamedTypeSymbol namedType)
{
GenerateStandardAccessors(prop, namedType, code);
ProcessNestedType(namedType, compilation, processedTypes);
}
}
private static void GenerateTupleAccessors(IPropertySymbol prop, INamedTypeSymbol tupleType, StringBuilder code)
{
var elements = tupleType.TupleElements;
var parentType = prop.ContainingType.ToDisplayString();
for (int i = 0; i < elements.Length; i++)
{
var element = elements[i];
var elementType = element.Type.ToDisplayString();
var elementName = element.CorrespondingTupleField?.Name ?? $"Item{i + 1}";
code.AppendLine($" public static {elementType} Get{prop.Name}_{elementName}({parentType} obj)");
code.AppendLine($" => obj.{prop.Name}.{elementName};");
if (prop.SetMethod != null)
{
var assignments = elements.Select((e, idx) =>
idx == i ? "value" : $"obj.{prop.Name}.{e.Name}");
code.AppendLine($" public static void Set{prop.Name}_{elementName}({parentType} obj, {elementType} value)");
code.AppendLine($" => obj.{prop.Name} = ({string.Join(", ", assignments)});");
}
}
}
private static void GenerateStandardAccessors(IPropertySymbol prop, INamedTypeSymbol propType, StringBuilder code)
{
var typeName = propType.ToDisplayString();
var parentType = prop.ContainingType.ToDisplayString();
code.AppendLine($" public static {typeName} Get{prop.Name}({parentType} obj)");
code.AppendLine($" => obj.{prop.Name};");
if (prop.SetMethod != null)
{
code.AppendLine($" public static void Set{prop.Name}({parentType} obj, {typeName} value)");
code.AppendLine($" => obj.{prop.Name} = value;");
}
}
private static void ProcessNestedType(INamedTypeSymbol typeSymbol, Compilation compilation, HashSet<ITypeSymbol> processedTypes)
{
if (ShouldGenerateForType(typeSymbol) && processedTypes.Add(typeSymbol))
{
var code = BuildAccessorsForType(typeSymbol, compilation, processedTypes);
// 注意:实际项目中需要通过 SourceProductionContext 添加源代码
}
}
private static bool ShouldGenerateForType(INamedTypeSymbol typeSymbol)
{
return !typeSymbol.IsTupleType &&
!typeSymbol.IsAnonymousType &&
!typeSymbol.IsNativeIntegerType &&
typeSymbol.DeclaredAccessibility == Accessibility.Public &&
!typeSymbol.Name.StartsWith("<");
}
}
}

View File

@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JiShe.CollectBus.SourceExtend
{
/// <summary>
/// 标记需要生成源码的类
/// </summary>
[AttributeUsage(AttributeTargets.Class)]
public class GenerateAccessorsAttribute : Attribute
{
}
}

View File

@ -0,0 +1,12 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.1</TargetFramework>
<LangVersion>12.0</LangVersion>
<Nullable>enable</Nullable>
<EnforceExtendedAnalyzerRules>true</EnforceExtendedAnalyzerRules>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.13.0" />
</ItemGroup>
</Project>