GFramework/GFramework.SourceGenerators/rule/ContextAwareGenerator.cs
GwWuYou 2dea63e69f refactor(abstractions): 将抽象接口迁移至独立项目并更新引用
- 将架构相关接口从 GFramework.Core 迁移至 GFramework.Core.Abstractions 项目
- 更新项目引用配置,添加对抽象层项目的项目引用
- 修正命名空间引用,使用新的抽象层命名空间
- 调整类型定义,将 List<T> 替换为更通用的 IList<T> 接口
- 修复控制器接口命名空间错误
- 添加必要的 using 语句以支持新的抽象层引用
2025-12-28 10:37:18 +08:00

87 lines
2.7 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Linq;
using System.Text;
using GFramework.SourceGenerators.Abstractions.rule;
using GFramework.SourceGenerators.Common.generator;
using GFramework.SourceGenerators.diagnostics;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace GFramework.SourceGenerators.rule;
[Generator]
public sealed class ContextAwareGenerator : AttributeClassGeneratorBase
{
/// <summary>
/// 使用强类型 Attribute替代字符串
/// </summary>
protected override Type AttributeType => typeof(ContextAwareAttribute);
/// <summary>
/// 仅用于 Syntax 粗筛选
/// </summary>
protected override string AttributeShortNameWithoutSuffix => "ContextAware";
/// <summary>
/// 额外语义校验:必须实现 IContextAware
/// </summary>
protected override bool ValidateSymbol(
SourceProductionContext context,
ClassDeclarationSyntax syntax,
INamedTypeSymbol symbol,
AttributeData attr)
{
if (!symbol.AllInterfaces.Any(i =>
i.ToDisplayString() == typeof(IContextAware).FullName))
{
context.ReportDiagnostic(Diagnostic.Create(
ContextAwareDiagnostic.ClassMustImplementIContextAware,
syntax.Identifier.GetLocation(),
symbol.Name));
return false;
}
return true;
}
/// <summary>
/// 生成源码
/// </summary>
protected override string Generate(
INamedTypeSymbol symbol,
AttributeData attr)
{
var ns = symbol.ContainingNamespace.IsGlobalNamespace
? null
: symbol.ContainingNamespace.ToDisplayString();
var sb = new StringBuilder();
sb.AppendLine("// <auto-generated/>");
sb.AppendLine("#nullable enable");
if (ns is not null)
{
sb.AppendLine($"namespace {ns};");
sb.AppendLine();
}
sb.AppendLine($"partial class {symbol.Name}");
sb.AppendLine("{");
sb.AppendLine(
" protected GFramework.Core.architecture.IArchitectureContext Context { get; private set; } = null!;");
sb.AppendLine(" void GFramework.Core.rule.IContextAware.SetContext(");
sb.AppendLine(" GFramework.Core.architecture.IArchitectureContext context)");
sb.AppendLine(" {");
sb.AppendLine(" Context = context;");
sb.AppendLine(" }");
sb.AppendLine("}");
return sb.ToString().TrimEnd();
}
/// <summary>
/// 自定义生成文件名
/// </summary>
protected override string GetHintName(INamedTypeSymbol symbol)
=> $"{symbol.Name}.ContextAware.g.cs";
}