# GFramework.SourceGenerators API 参考

> GFramework.SourceGenerators 模块的完整 API 参考文档，包含所有源代码生成器的详细说明。

## 📋 目录

- [日志生成器](#日志生成器)
- [上下文感知生成器](#上下文感知生成器)
- [枚举扩展生成器](#枚举扩展生成器)
- [诊断系统](#诊断系统)
- [通用工具](#通用工具)

## 日志生成器

### [Log] 属性

为标记的类自动生成 ILogger 字段。

#### 构造函数参数

```csharp
[Log(
    string fieldName = "Logger",              // 生成的字段名
    AccessModifier accessModifier = AccessModifier.Private, // 访问修饰符
    bool isStatic = true,                   // 是否生成静态字段
    string loggerName = null,                // 自定义日志器名称
    LogLevel minLevel = LogLevel.None,          // 最小日志级别
    bool includeLoggerInterface = false       // 是否包含 ILogger 接口
    bool enableConditionalCompilation = false  // 是否启用条件编译
    string loggerInterfaceName = "ILogger"      // 日志接口名称
    bool suppressAutoGeneratedAttribute = false // 是否抑制自动生成属性
    string category = null                     // 日志类别
    bool forceContextualLogging = false        // 是否强制上下文日志
    bool enableStructuredLogging = false       // 是否启用结构化日志
    string loggerFactoryName = null           // 日志工厂名称
    string logMessagePrefix = null            // 日志消息前缀
    bool enablePerformanceLogging = false       // 是否启用性能日志
    bool enableAsyncLogging = false           // 是否启用异步日志
    bool enableFluentLogging = false         // 是否启用流畅日志
    bool enableScopedLogging = false           // 是否启用作用域日志
)]
```

#### 生成的代码示例

```csharp
// 默认配置生成的代码
public partial class MyClass
{
    private static readonly ILogger Logger = 
        LoggerFactory.Create(builder => builder
            .AddConsole()
            .SetMinimumLevel(LogLevel.Information)
            .CreateLogger<MyClass>());
}

// 自定义配置生成的代码
[Log(
    fieldName = "CustomLogger",
    accessModifier = AccessModifier.Public,
    isStatic = false,
    loggerName = "Custom.MyClass",
    minLevel = LogLevel.Debug,
    includeLoggerInterface = true
)]
public partial class CustomClass : ILogger
{
    public ILogger CustomLogger { get; }
    
    static CustomClass()
    {
        CustomLogger = LoggerFactory.Create(builder => builder
            .AddConsole()
            .SetMinimumLevel(LogLevel.Debug)
            .CreateLogger<CustomClass>());
    }
}
```

#### 支持的方法

生成的 Logger 支持以下方法：

```csharp
// 基础日志方法
Logger.LogDebug("Debug message");
Logger.LogInformation("Info message");
Logger.LogWarning("Warning message");
Logger.LogError("Error message");
Logger.LogCritical("Critical message");

// 带格式化的日志方法
Logger.LogInformation("Player {Name} has {Health} health", playerName, playerHealth);

// 异步日志方法
await Logger.LogInformationAsync("Async message");

// 结构化日志
Logger.LogInformation(new { PlayerName = "John", Health = 100 }, "Player {Name} has {Health} health");
```

## 上下文感知生成器

### [ContextAware] 属性

为标记的类自动实现 IContextAware 接口。

#### 生成的代码示例

```csharp
[ContextAware]
public partial class MyClass : IContextAware
{
    private IContextAware.Context _context;
    
    public IContextAware.Context Context => _context ??= new LazyContext(this);
    
    public void SetContext(IContextAware.Context context)
    {
        _context = context;
    }
    
    public IContextAware.Context GetContext()
    {
        return _context;
    }
}

// 使用延迟初始化
[ContextAware(useLazy = true)]
public partial class LazyContextClass : IContextAware
{
    private Lazy<IContextAware.Context> _context;
    
    public IContextAware.Context Context => _context.Value;
    
    public void SetContext(IContextAware.Context context)
    {
        _context = new Lazy<IContextAware.Context>(() => context);
    }
}

// 带上下文验证
[ContextAware(validateContext = true)]
public partial class ValidatedContextClass : IContextAware
{
    private IContextAware.Context _context;
    
    public IContextAware.Context Context => 
    {
        get => _context;
        private set
        {
            _context = value;
            if (_context?.IsInvalid == true)
            {
                throw new InvalidOperationException("Context is invalid");
            }
        }
    }
}
```

#### 可用的方法

```csharp
// 获取模型
var playerModel = Context.GetModel<PlayerModel>();
var gameModel = Context.GetModel<GameModel>();

// 获取系统
var combatSystem = Context.GetSystem<CombatSystem>();
var audioSystem = Context.GetSystem<AudioSystem>();

// 获取工具
var storageUtility = Context.GetUtility<StorageUtility>();
var mathUtility = Context.GetUtility<MathUtility>();

// 发送事件
Context.SendEvent<PlayerDiedEvent>();
Context.SendEvent<DamageDealtEvent>(new DamageDealtEvent { Damage = 50 });

// 发送命令
Context.SendCommand(new AttackCommand());
var result = Context.SendCommand<AttackResult>(new AttackCommand());

// 发送查询
var canAttack = Context.SendQuery<CanAttackQuery>();
var playerData = Context.SendQuery<GetPlayerDataQuery>();
```

## 枚举扩展生成器

### [GenerateEnumExtensions] 属性

为枚举类型自动生成扩展方法。

#### 构造函数参数

```csharp
[GenerateEnumExtensions(
    bool generateIsMethods = true,         // 是否生成 IsX() 方法
    bool generateHasMethod = true,          // 是否生成 HasX() 方法
    bool generateInMethod = true,           // 是否生成 In(params T[]) 方法
    bool generateTryParseMethod = false,     // 是否生成 TryParse() 方法
    string customPrefix = "Is",              // 自定义方法名前缀
    bool includeToString = false,           // 是否生成 ToString 扩展
    bool generateAllMethod = false,         // 是否生成 All() 方法
    bool generateCountMethod = false,       // 是否生成 Count() 方法
    bool generateDescriptionMethod = false,  // 是否生成 Description() 方法
    bool generateValuesMethod = false,       // 是否生成 Values() 方法
    string customNamespace = null,          // 自定义命名空间
    bool generateExtensionMethods = true,    // 是否生成扩展方法
    bool generateFlagMethods = true,        // 是否为位标志枚举生成方法
    bool generateValidationMethods = false,  // 是否生成验证方法
    bool generateUtilityMethods = false,    // 是否生成工具方法
    bool generateQueryableMethods = false,  // 是否生成查询方法
    string customMethodNameFormat = null,     // 自定义方法名格式
    bool generateDocumentation = false,      // 是否生成文档注释
    bool generateExamples = false,          // 是否生成使用示例
)]
```

#### 普通枚举生成的代码示例

```csharp
[GenerateEnumExtensions]
public enum PlayerState
{
    Idle,
    Walking,
    Running,
    Jumping,
    Attacking
}

// 生成的扩展方法
public static class PlayerStateExtensions
{
    public static bool IsIdle(this PlayerState state) => state == PlayerState.Idle;
    public static bool IsWalking(this PlayerState state) => state == PlayerState.Walking;
    public static bool IsRunning(this PlayerState state) => state == PlayerState.Running;
    public static bool IsJumping(this PlayerState state) => state == PlayerState.Jumping;
    public static bool IsAttacking(this PlayerState state) => state == PlayerState.Attacking;
    
    public static bool In(this PlayerState state, params PlayerState[] values)
    {
        return values.Contains(state);
    }
}
```

#### 位标志枚举生成的代码示例

```csharp
[GenerateEnumExtensions]
[Flags]
public enum PlayerPermissions
{
    None = 0,
    CanMove = 1 << 0,
    CanAttack = 1 << 1,
    CanUseItems = 1 << 2,
    CanChat = 1 << 3,
    CanTrade = 1 << 4
}

// 生成的扩展方法
public static class PlayerPermissionsExtensions
{
    public static bool HasCanMove(this PlayerPermissions permissions) => permissions.HasFlag(PlayerPermissions.CanMove);
    public static bool HasCanAttack(this PlayerPermissions permissions) => permissions.HasFlag(PlayerPermissions.CanAttack);
    public static bool HasCanUseItems(this PlayerPermissions permissions) => permissions.HasFlag(PlayerPermissions.CanUseItems);
    
    public static bool HasAny(this PlayerPermissions permissions, params PlayerPermissions[] flags)
    {
        return flags.Any(flag => permissions.HasFlag(flag));
    }
    
    public static bool HasAll(this PlayerPermissions permissions, params PlayerPermissions[] flags)
    {
        return flags.All(flag => permissions.HasFlag(flag));
    }
    
    public static PlayerPermissions Add(this PlayerPermissions permissions, PlayerPermissions other)
    {
        return permissions | other;
    }
    
    public static PlayerPermissions Remove(this PlayerPermissions permissions, PlayerPermissions other)
    {
        return permissions & ~other;
    }
    
    public static PlayerPermissions Toggle(this PlayerPermissions permissions, PlayerPermissions flag)
    {
        return permissions ^ flag;
    }
}
```

#### 高级功能示例

```csharp
[GenerateEnumExtensions(
    customPrefix = "Is",
    includeToString = true,
    generateDescriptionMethod = true,
    generateUtilityMethods = true
)]
public enum GameState
{
    [Description("游戏菜单状态")]
    Menu,
    
    [Description("游戏进行中")]
    Playing,
    
    [Description("游戏暂停")]
    Paused,
    
    [Description("游戏结束")]
    GameOver
}

// 生成的扩展方法包含更多功能
public static class GameStateExtensions
{
    // IsX() 方法
    public static bool IsMenu(this GameState state) => state == GameState.Menu;
    public static bool IsPlaying(this GameState state) => state == GameState.Playing;
    public static bool IsPaused(this GameState state) => state == GameState.Paused;
    public static bool IsGameOver(this GameState state) => state == GameState.GameOver;
    
    // ToString() 扩展
    public static string ToDisplayString(this GameState state)
    {
        return state switch
        {
            GameState.Menu => "游戏菜单",
            GameState.Playing => "游戏进行中",
            GameState.Paused => "游戏暂停",
            GameState.GameOver => "游戏结束"
        };
    }
    
    // Description() 扩展
    public static string GetDescription(this GameState state)
    {
        return typeof(GameState)
            .GetMember(state.ToString())
            ?.GetCustomAttribute<DescriptionAttribute>()
            ?.Description ?? state.ToString();
    }
    
    // 工具方法
    public static bool IsFinalState(this GameState state) => state == GameState.GameOver;
    public static bool IsPlayingState(this GameState state) => state == GameState.Playing;
    public static bool CanPause(this GameState state) => state == GameState.Playing;
    
    // 验证方法
    public static bool IsValidTransition(this GameState from, GameState to)
    {
        return (from, to) switch
        {
            (GameState.Menu, GameState.Playing) => true,
            (GameState.Playing, GameState.Paused) => true,
            (GameState.Paused, GameState.Playing) => true,
            (GameState.Playing, GameState.GameOver) => true,
            _ => false
        };
    }
}
```

## 诊断系统

### GF_Logging_001 - 日志字段名冲突

当使用 `[Log]` 属性时，如果已存在同名字段或属性，会触发此诊断。

#### 示例

```csharp
// 错误示例：字段名冲突
[Log(fieldName = "Logger")]
public partial class MyClass
{
    private readonly ILogger Logger; // ❌ 冲突！
}

// 正确的解决方案
[Log(fieldName = "CustomLogger")]
public partial class MyClass
{
    private readonly ILogger CustomLogger; // ✅ 使用不同的字段名
}
```

#### 诊断消息

```
error GF_Logging_001: Logger field name 'Logger' conflicts with existing field in type 'MyClass'
```

### GF_Rule_001 - 上下文感知接口冲突

当使用 `[ContextAware]` 属性时，如果类型已经实现了 IContextAware 接口，会触发此诊断。

#### 示例

```csharp
// 错误示例：接口冲突
[ContextAware]
public partial class MyClass : IContextAware // ❌ 冲突！
{
    public IContextAware.Context Context { get; set; }
    public void SetContext(IContextAware.Context context) { }
    public IContextAware.Context GetContext() { return Context; }
}

// 正确的解决方案：移除手动实现
[ContextAware]
public partial class MyClass // ✅ 让生成器实现接口
{
    // 移除手动实现的代码
}
```

#### 诊断消息

```
error GF_Rule_001: Type 'MyClass' already implements 'IContextAware' interface. Remove the [ContextAware] attribute or manual implementation.
```

## 通用工具

### TypeHelper

类型操作的工具类。

#### 主要方法

```csharp
public static class TypeHelper
{
    // 类型检查
    public static bool IsNullable(Type type);
    public static bool IsGenericType(Type type);
    public static bool IsValueType(Type type);
    public static bool IsEnum(Type type);
    
    // 泛型类型信息
    public static Type GetGenericTypeDefinition(Type type);
    public static Type[] GetGenericArguments(Type type);
    public static bool ImplementsInterface(Type type, Type interfaceType);
    
    // 属性信息
    public static PropertyInfo[] GetProperties(Type type, BindingFlags flags = BindingFlags.Public | BindingFlags.Instance);
    public static PropertyInfo GetProperty(Type type, string name, BindingFlags flags = BindingFlags.Public | BindingFlags.Instance);
    public static bool HasProperty(Type type, string name);
    
    // 方法信息
    public static MethodInfo[] GetMethods(Type type, BindingFlags flags = BindingFlags.Public | BindingFlags.Instance);
    public static MethodInfo GetMethod(Type type, string name, BindingFlags flags = BindingFlags.Public | BindingFlags.Instance);
    public static bool HasMethod(Type type, string name);
    
    // 构造函数信息
    public static ConstructorInfo[] GetConstructors(Type type, BindingFlags flags = BindingFlags.Public | BindingFlags.Instance);
    public static ConstructorInfo GetConstructor(Type type, Type[] parameterTypes);
    
    // 可实例化检查
    public static bool HasParameterlessConstructor(Type type);
    public static bool HasConstructor(Type type, params Type[] parameterTypes);
}
```

### SymbolHelper

符号操作的工具类。

#### 主要方法

```csharp
public static class SymbolHelper
{
    // 获取符号信息
    public static ITypeSymbol GetSymbolInfo(INamedTypeSymbol symbol, Compilation compilation);
    public static IMethodSymbol GetMethodInfo(IMethodSymbol symbol);
    public static IPropertySymbol GetPropertyInfo(IPropertySymbol symbol);
    public static IEventSymbol GetEventInfo(IEventSymbol symbol);
    
    // 符号比较
    public static bool IsSameSymbol(ISymbol symbol1, ISymbol symbol2);
    public static string GetFullyQualifiedName(ISymbol symbol);
    public static string GetDocumentationCommentXml(ISymbol symbol);
    
    // 符号查找
    public static IEnumerable<ISymbol> GetMembers(INamedTypeSymbol symbol);
    public static ISymbol GetMember(INamedTypeSymbol symbol, string name);
    public static IEnumerable<AttributeData> GetAttributes(ISymbol symbol);
    public static T GetAttribute<T>(ISymbol symbol);
    public static bool HasAttribute<T>(ISymbol symbol);
}
```

### CompilationHelper

编译操作的工具类。

#### 主要方法

```csharp
public static class CompilationHelper
{
    // 获取编译
    public static Compilation GetCompilation(Compilation startingCompilation);
    public static Compilation GetCompilation(SyntaxTree syntaxTree);
    public static Compilation GetCompilation(IEnumerable<SyntaxTree> syntaxTrees);
    
    // 获取语义模型
    public static SemanticModel GetSemanticModel(Compilation compilation);
    public static SemanticModel GetSemanticModel(SyntaxTree syntaxTree);
    
    // 符号查找
    public static INamedTypeSymbol GetDeclaredTypeSymbol(Compilation compilation, string name);
    public static IMethodSymbol GetDeclaredMethodSymbol(Compilation compilation, string name);
    public static IPropertySymbol GetDeclaredPropertySymbol(Compilation compilation, string name);
    
    // 类型解析
    public static INamedTypeSymbol ResolveType(Compilation compilation, string metadataName);
    public static ITypeSymbol ResolveType(Compilation compilation, Type type);
    public static IMethodSymbol ResolveMethod(Compilation compilation, string methodFullName, params ITypeSymbol[] parameterTypes);
    
    // 编译检查
    public static bool HasCompilationErrors(Compilation compilation);
    public static IEnumerable<Diagnostic> GetCompilationDiagnostics(Compilation compilation);
    public static string GetCompilationErrors(Compilation compilation);
}
```

---

## 配置示例

### 项目文件配置

```xml
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
    <Nullable>enable</Nullable>
    <EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
    <CompilerGeneratedFilesOutputPath>Generated</CompilerGeneratedFilesOutputPath>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="GeWuYou.GFramework.SourceGenerators" Version="1.0.0" />
    <PackageReference Include="GeWuYou.GFramework.SourceGenerators.Attributes" Version="1.0.0" />
  </ItemGroup>

  <ItemGroup>
    <Compile Remove="$(CompilerGeneratedFilesOutputPath)/**/*.cs" />
  </ItemGroup>
</Project>
```

### 编辑器配置

```json
{
    "sourceGenerators": {
        "debug": true,
        "logLevel": "Information",
        "outputDirectory": "Generated",
        "enableDocumentation": true,
        "enablePerformanceLogging": false
    },
    "loggingGenerator": {
        "defaultFieldName": "Logger",
        "defaultAccessLevel": "Private",
        "defaultStatic": true,
        "defaultMinLevel": "None"
    },
    "contextAwareGenerator": {
        "useLazyInit": false,
        "validateContext": false
    },
    "enumExtensionsGenerator": {
        "generateIsMethods": true,
        "generateHasMethod": true,
        "generateInMethod": true,
        "customPrefix": "Is"
    }
}
```

---

**文档版本**: 1.0.0  
**更新日期**: 2026-01-12