mirror of
https://github.com/GeWuYou/GFramework.git
synced 2026-05-07 00:39:00 +08:00
docs(config): 添加游戏内容配置系统完整文档
- 新增配置系统架构说明,涵盖 YAML 源文件、JSON Schema 结构描述、运行时只读查询等核心功能 - 完善推荐目录结构和 Schema 示例,包括怪物、物品配置表的标准定义方式 - 提供完整的接入模板,包含 csproj 配置、GameConfigHost 生命周期管理、GameConfigRuntime 读取入口 - 添加运行时校验行为说明,支持必填字段、类型匹配、数值范围、字符串长度、正则表达式、数组长度等多种约束 - 集成跨表引用功能,支持通过 x-gframework-ref-table 声明关联关系并进行有效性检查 - 添加开发期热重载支持,可自动监听配置目录和 schema 文件变更并重载对应表格 - 提供 VS Code 工具集成说明,包括配置浏览、raw 编辑、schema 打开、表单入口等功能 - 补充生成器接入约定,从 *.schema.json 自动生成配置类型、表包装、注册辅助等代码 - 添加完整的 Analyzer 规则文档,涵盖 GF_ConfigSchema_001 到 GF_ConfigSchema_008 等错误诊断码 - 增加单元测试验证,确保消费者项目可以正常使用生成的聚合注册辅助和强类型访问入口
This commit is contained in:
parent
3109beaa9b
commit
43b95c7513
@ -220,7 +220,8 @@ public class GeneratedConfigConsumerIntegrationTests
|
|||||||
},
|
},
|
||||||
"name": {
|
"name": {
|
||||||
"type": "string",
|
"type": "string",
|
||||||
"description": "Monster display name."
|
"description": "Monster display name.",
|
||||||
|
"x-gframework-index": true
|
||||||
},
|
},
|
||||||
"hp": {
|
"hp": {
|
||||||
"type": "integer",
|
"type": "integer",
|
||||||
@ -228,7 +229,8 @@ public class GeneratedConfigConsumerIntegrationTests
|
|||||||
},
|
},
|
||||||
"faction": {
|
"faction": {
|
||||||
"type": "string",
|
"type": "string",
|
||||||
"description": "Used by the integration test to validate generated non-unique queries."
|
"description": "Used by the integration test to validate generated non-unique queries.",
|
||||||
|
"x-gframework-index": true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -15,7 +15,8 @@
|
|||||||
},
|
},
|
||||||
"name": {
|
"name": {
|
||||||
"type": "string",
|
"type": "string",
|
||||||
"description": "Monster display name."
|
"description": "Monster display name.",
|
||||||
|
"x-gframework-index": true
|
||||||
},
|
},
|
||||||
"hp": {
|
"hp": {
|
||||||
"type": "integer",
|
"type": "integer",
|
||||||
@ -23,7 +24,8 @@
|
|||||||
},
|
},
|
||||||
"faction": {
|
"faction": {
|
||||||
"type": "string",
|
"type": "string",
|
||||||
"description": "Used by integration tests to validate generated non-unique queries."
|
"description": "Used by integration tests to validate generated non-unique queries.",
|
||||||
|
"x-gframework-index": true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -79,6 +79,7 @@ public class SchemaConfigGeneratorSnapshotTests
|
|||||||
"type": "string",
|
"type": "string",
|
||||||
"title": "Monster Name",
|
"title": "Monster Name",
|
||||||
"description": "Localized monster display name.",
|
"description": "Localized monster display name.",
|
||||||
|
"x-gframework-index": true,
|
||||||
"minLength": 3,
|
"minLength": 3,
|
||||||
"maxLength": 16,
|
"maxLength": 16,
|
||||||
"pattern": "^[A-Z][a-z]+$",
|
"pattern": "^[A-Z][a-z]+$",
|
||||||
|
|||||||
@ -267,6 +267,100 @@ public class SchemaConfigGeneratorTests
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 验证查询索引元数据必须是布尔值,避免 schema 作者误以为字符串或数字也会被解释为开关。
|
||||||
|
/// </summary>
|
||||||
|
[Test]
|
||||||
|
public void Run_Should_Report_Diagnostic_When_Lookup_Index_Metadata_Is_Not_Boolean()
|
||||||
|
{
|
||||||
|
const string source = """
|
||||||
|
namespace TestApp
|
||||||
|
{
|
||||||
|
public sealed class Dummy
|
||||||
|
{
|
||||||
|
}
|
||||||
|
}
|
||||||
|
""";
|
||||||
|
|
||||||
|
const string schema = """
|
||||||
|
{
|
||||||
|
"type": "object",
|
||||||
|
"required": ["id", "name"],
|
||||||
|
"properties": {
|
||||||
|
"id": { "type": "integer" },
|
||||||
|
"name": {
|
||||||
|
"type": "string",
|
||||||
|
"x-gframework-index": "yes"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
""";
|
||||||
|
|
||||||
|
var result = SchemaGeneratorTestDriver.Run(
|
||||||
|
source,
|
||||||
|
("monster.schema.json", schema));
|
||||||
|
|
||||||
|
var diagnostic = result.Results.Single().Diagnostics.Single();
|
||||||
|
|
||||||
|
Assert.Multiple(() =>
|
||||||
|
{
|
||||||
|
Assert.That(diagnostic.Id, Is.EqualTo("GF_ConfigSchema_008"));
|
||||||
|
Assert.That(diagnostic.Severity, Is.EqualTo(DiagnosticSeverity.Error));
|
||||||
|
Assert.That(diagnostic.GetMessage(), Does.Contain("x-gframework-index"));
|
||||||
|
Assert.That(diagnostic.GetMessage(), Does.Contain("boolean"));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 验证查询索引元数据不能绑定到不满足约束的字段上,避免为嵌套字段生成误导性 API。
|
||||||
|
/// </summary>
|
||||||
|
[Test]
|
||||||
|
public void Run_Should_Report_Diagnostic_When_Lookup_Index_Metadata_Target_Is_Not_Eligible()
|
||||||
|
{
|
||||||
|
const string source = """
|
||||||
|
namespace TestApp
|
||||||
|
{
|
||||||
|
public sealed class Dummy
|
||||||
|
{
|
||||||
|
}
|
||||||
|
}
|
||||||
|
""";
|
||||||
|
|
||||||
|
const string schema = """
|
||||||
|
{
|
||||||
|
"type": "object",
|
||||||
|
"required": ["id", "reward"],
|
||||||
|
"properties": {
|
||||||
|
"id": { "type": "integer" },
|
||||||
|
"reward": {
|
||||||
|
"type": "object",
|
||||||
|
"required": ["rarity"],
|
||||||
|
"properties": {
|
||||||
|
"rarity": {
|
||||||
|
"type": "string",
|
||||||
|
"x-gframework-index": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
""";
|
||||||
|
|
||||||
|
var result = SchemaGeneratorTestDriver.Run(
|
||||||
|
source,
|
||||||
|
("monster.schema.json", schema));
|
||||||
|
|
||||||
|
var diagnostic = result.Results.Single().Diagnostics.Single();
|
||||||
|
|
||||||
|
Assert.Multiple(() =>
|
||||||
|
{
|
||||||
|
Assert.That(diagnostic.Id, Is.EqualTo("GF_ConfigSchema_008"));
|
||||||
|
Assert.That(diagnostic.Severity, Is.EqualTo(DiagnosticSeverity.Error));
|
||||||
|
Assert.That(diagnostic.GetMessage(), Does.Contain("reward.rarity"));
|
||||||
|
Assert.That(diagnostic.GetMessage(), Does.Contain("top-level required non-key scalar"));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 验证引用元数据成员名在不同路径规范化后发生碰撞时,生成器仍会分配全局唯一的成员名。
|
/// 验证引用元数据成员名在不同路径规范化后发生碰撞时,生成器仍会分配全局唯一的成员名。
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@ -429,7 +523,10 @@ public class SchemaConfigGeneratorTests
|
|||||||
"required": ["id", "name"],
|
"required": ["id", "name"],
|
||||||
"properties": {
|
"properties": {
|
||||||
"id": { "type": "integer" },
|
"id": { "type": "integer" },
|
||||||
"name": { "type": "string" },
|
"name": {
|
||||||
|
"type": "string",
|
||||||
|
"x-gframework-index": true
|
||||||
|
},
|
||||||
"hp": { "type": "integer" },
|
"hp": { "type": "integer" },
|
||||||
"dropItems": {
|
"dropItems": {
|
||||||
"type": "array",
|
"type": "array",
|
||||||
@ -468,8 +565,12 @@ public class SchemaConfigGeneratorTests
|
|||||||
{
|
{
|
||||||
Assert.That(tableSource, Does.Contain("FindByName(string value)"));
|
Assert.That(tableSource, Does.Contain("FindByName(string value)"));
|
||||||
Assert.That(tableSource, Does.Contain("TryFindFirstByName(string value, out MonsterConfig? result)"));
|
Assert.That(tableSource, Does.Contain("TryFindFirstByName(string value, out MonsterConfig? result)"));
|
||||||
|
Assert.That(tableSource, Does.Contain("_nameIndex"));
|
||||||
|
Assert.That(tableSource, Does.Contain("BuildNameIndex"));
|
||||||
|
Assert.That(tableSource, Does.Contain("_nameIndex.Value.TryGetValue(value, out var matches)"));
|
||||||
Assert.That(tableSource, Does.Contain("FindByHp(int? value)"));
|
Assert.That(tableSource, Does.Contain("FindByHp(int? value)"));
|
||||||
Assert.That(tableSource, Does.Contain("TryFindFirstByHp(int? value, out MonsterConfig? result)"));
|
Assert.That(tableSource, Does.Contain("TryFindFirstByHp(int? value, out MonsterConfig? result)"));
|
||||||
|
Assert.That(tableSource, Does.Not.Contain("_hpIndex"));
|
||||||
Assert.That(tableSource, Does.Not.Contain("FindById("));
|
Assert.That(tableSource, Does.Not.Contain("FindById("));
|
||||||
Assert.That(tableSource, Does.Not.Contain("FindByDropItems("));
|
Assert.That(tableSource, Does.Not.Contain("FindByDropItems("));
|
||||||
Assert.That(tableSource, Does.Not.Contain("FindByTargetId("));
|
Assert.That(tableSource, Does.Not.Contain("FindByTargetId("));
|
||||||
|
|||||||
@ -10,6 +10,7 @@ namespace GFramework.Game.Config.Generated;
|
|||||||
public sealed partial class MonsterTable : global::GFramework.Game.Abstractions.Config.IConfigTable<int, MonsterConfig>
|
public sealed partial class MonsterTable : global::GFramework.Game.Abstractions.Config.IConfigTable<int, MonsterConfig>
|
||||||
{
|
{
|
||||||
private readonly global::GFramework.Game.Abstractions.Config.IConfigTable<int, MonsterConfig> _inner;
|
private readonly global::GFramework.Game.Abstractions.Config.IConfigTable<int, MonsterConfig> _inner;
|
||||||
|
private readonly global::System.Lazy<global::System.Collections.Generic.IReadOnlyDictionary<string, global::System.Collections.Generic.IReadOnlyList<MonsterConfig>>> _nameIndex;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Creates a generated table wrapper around the runtime config table instance.
|
/// Creates a generated table wrapper around the runtime config table instance.
|
||||||
@ -18,6 +19,9 @@ public sealed partial class MonsterTable : global::GFramework.Game.Abstractions.
|
|||||||
public MonsterTable(global::GFramework.Game.Abstractions.Config.IConfigTable<int, MonsterConfig> inner)
|
public MonsterTable(global::GFramework.Game.Abstractions.Config.IConfigTable<int, MonsterConfig> inner)
|
||||||
{
|
{
|
||||||
_inner = inner ?? throw new global::System.ArgumentNullException(nameof(inner));
|
_inner = inner ?? throw new global::System.ArgumentNullException(nameof(inner));
|
||||||
|
_nameIndex = new global::System.Lazy<global::System.Collections.Generic.IReadOnlyDictionary<string, global::System.Collections.Generic.IReadOnlyList<MonsterConfig>>>(
|
||||||
|
BuildNameIndex,
|
||||||
|
global::System.Threading.LazyThreadSafetyMode.ExecutionAndPublication);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
@ -53,28 +57,65 @@ public sealed partial class MonsterTable : global::GFramework.Game.Abstractions.
|
|||||||
return _inner.All();
|
return _inner.All();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Builds the exact-match lookup index declared for property 'name'.
|
||||||
|
/// </summary>
|
||||||
|
/// <returns>A read-only lookup index keyed by <c>Name</c>.</returns>
|
||||||
|
private global::System.Collections.Generic.IReadOnlyDictionary<string, global::System.Collections.Generic.IReadOnlyList<MonsterConfig>> BuildNameIndex()
|
||||||
|
{
|
||||||
|
return BuildLookupIndex(static config => config.Name);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Materializes a read-only exact-match lookup index from the current table snapshot.
|
||||||
|
/// </summary>
|
||||||
|
/// <typeparam name="TProperty">Indexed property type.</typeparam>
|
||||||
|
/// <param name="keySelector">Selects the indexed property from one config entry.</param>
|
||||||
|
/// <returns>A read-only dictionary whose values preserve snapshot iteration order.</returns>
|
||||||
|
private global::System.Collections.Generic.IReadOnlyDictionary<TProperty, global::System.Collections.Generic.IReadOnlyList<MonsterConfig>> BuildLookupIndex<TProperty>(
|
||||||
|
global::System.Func<MonsterConfig, TProperty> keySelector)
|
||||||
|
where TProperty : notnull
|
||||||
|
{
|
||||||
|
var buckets = new global::System.Collections.Generic.Dictionary<TProperty, global::System.Collections.Generic.List<MonsterConfig>>();
|
||||||
|
|
||||||
|
// Capture the current table snapshot once so indexed lookups stay deterministic for this wrapper instance.
|
||||||
|
foreach (var candidate in All())
|
||||||
|
{
|
||||||
|
var key = keySelector(candidate);
|
||||||
|
if (!buckets.TryGetValue(key, out var matches))
|
||||||
|
{
|
||||||
|
matches = new global::System.Collections.Generic.List<MonsterConfig>();
|
||||||
|
buckets.Add(key, matches);
|
||||||
|
}
|
||||||
|
|
||||||
|
matches.Add(candidate);
|
||||||
|
}
|
||||||
|
|
||||||
|
var materialized = new global::System.Collections.Generic.Dictionary<TProperty, global::System.Collections.Generic.IReadOnlyList<MonsterConfig>>(buckets.Count, buckets.Comparer);
|
||||||
|
foreach (var pair in buckets)
|
||||||
|
{
|
||||||
|
materialized.Add(pair.Key, global::System.Array.AsReadOnly(pair.Value.ToArray()));
|
||||||
|
}
|
||||||
|
|
||||||
|
return new global::System.Collections.ObjectModel.ReadOnlyDictionary<TProperty, global::System.Collections.Generic.IReadOnlyList<MonsterConfig>>(materialized);
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Finds all config entries whose property 'name' equals the supplied value.
|
/// Finds all config entries whose property 'name' equals the supplied value.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="value">The property value to match.</param>
|
/// <param name="value">The property value to match.</param>
|
||||||
/// <returns>A read-only snapshot containing every matching config entry.</returns>
|
/// <returns>A read-only snapshot containing every matching config entry.</returns>
|
||||||
/// <remarks>
|
/// <remarks>
|
||||||
/// The generated helper performs a deterministic linear scan over <see cref="All"/> so it stays compatible with runtime hot reload and does not require secondary index infrastructure.
|
/// This property declares <c>x-gframework-index</c>, so the generated helper resolves matches through a lazily materialized read-only lookup index built from the current table snapshot.
|
||||||
/// </remarks>
|
/// </remarks>
|
||||||
public global::System.Collections.Generic.IReadOnlyList<MonsterConfig> FindByName(string value)
|
public global::System.Collections.Generic.IReadOnlyList<MonsterConfig> FindByName(string value)
|
||||||
{
|
{
|
||||||
var matches = new global::System.Collections.Generic.List<MonsterConfig>();
|
if (_nameIndex.Value.TryGetValue(value, out var matches))
|
||||||
|
|
||||||
// Scan the current table snapshot on demand so generated helpers stay aligned with reloadable runtime data.
|
|
||||||
foreach (var candidate in All())
|
|
||||||
{
|
{
|
||||||
if (global::System.Collections.Generic.EqualityComparer<string>.Default.Equals(candidate.Name, value))
|
return matches;
|
||||||
{
|
|
||||||
matches.Add(candidate);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return matches.Count == 0 ? global::System.Array.Empty<MonsterConfig>() : matches.AsReadOnly();
|
return global::System.Array.Empty<MonsterConfig>();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@ -84,19 +125,15 @@ public sealed partial class MonsterTable : global::GFramework.Game.Abstractions.
|
|||||||
/// <param name="result">The first matching config entry when lookup succeeds; otherwise <see langword="null" />.</param>
|
/// <param name="result">The first matching config entry when lookup succeeds; otherwise <see langword="null" />.</param>
|
||||||
/// <returns><see langword="true" /> when a matching config entry is found; otherwise <see langword="false" />.</returns>
|
/// <returns><see langword="true" /> when a matching config entry is found; otherwise <see langword="false" />.</returns>
|
||||||
/// <remarks>
|
/// <remarks>
|
||||||
/// The generated helper walks the same snapshot exposed by <see cref="All"/> and returns the first match in iteration order.
|
/// This property declares <c>x-gframework-index</c>, so the generated helper returns the first element from the lazily materialized exact-match bucket.
|
||||||
/// </remarks>
|
/// </remarks>
|
||||||
public bool TryFindFirstByName(string value, out MonsterConfig? result)
|
public bool TryFindFirstByName(string value, out MonsterConfig? result)
|
||||||
{
|
{
|
||||||
// Keep the search path allocation-free for the first-match case by exiting as soon as one entry matches.
|
if (_nameIndex.Value.TryGetValue(value, out var matches) && matches.Count > 0)
|
||||||
foreach (var candidate in All())
|
|
||||||
{
|
{
|
||||||
if (global::System.Collections.Generic.EqualityComparer<string>.Default.Equals(candidate.Name, value))
|
result = matches[0];
|
||||||
{
|
|
||||||
result = candidate;
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
result = null;
|
result = null;
|
||||||
return false;
|
return false;
|
||||||
|
|||||||
@ -25,6 +25,7 @@
|
|||||||
GF_ConfigSchema_005 | GFramework.SourceGenerators.Config | Error | ConfigSchemaDiagnostics
|
GF_ConfigSchema_005 | GFramework.SourceGenerators.Config | Error | ConfigSchemaDiagnostics
|
||||||
GF_ConfigSchema_006 | GFramework.SourceGenerators.Config | Error | ConfigSchemaDiagnostics
|
GF_ConfigSchema_006 | GFramework.SourceGenerators.Config | Error | ConfigSchemaDiagnostics
|
||||||
GF_ConfigSchema_007 | GFramework.SourceGenerators.Config | Error | ConfigSchemaDiagnostics
|
GF_ConfigSchema_007 | GFramework.SourceGenerators.Config | Error | ConfigSchemaDiagnostics
|
||||||
|
GF_ConfigSchema_008 | GFramework.SourceGenerators.Config | Error | ConfigSchemaDiagnostics
|
||||||
GF_Priority_001 | GFramework.Priority | Error | PriorityDiagnostic
|
GF_Priority_001 | GFramework.Priority | Error | PriorityDiagnostic
|
||||||
GF_Priority_002 | GFramework.Priority | Warning | PriorityDiagnostic
|
GF_Priority_002 | GFramework.Priority | Warning | PriorityDiagnostic
|
||||||
GF_Priority_003 | GFramework.Priority | Error | PriorityDiagnostic
|
GF_Priority_003 | GFramework.Priority | Error | PriorityDiagnostic
|
||||||
|
|||||||
@ -11,6 +11,7 @@ namespace GFramework.SourceGenerators.Config;
|
|||||||
public sealed class SchemaConfigGenerator : IIncrementalGenerator
|
public sealed class SchemaConfigGenerator : IIncrementalGenerator
|
||||||
{
|
{
|
||||||
private const string ConfigPathMetadataKey = "x-gframework-config-path";
|
private const string ConfigPathMetadataKey = "x-gframework-config-path";
|
||||||
|
private const string LookupIndexMetadataKey = "x-gframework-index";
|
||||||
private const string GeneratedNamespace = "GFramework.Game.Config.Generated";
|
private const string GeneratedNamespace = "GFramework.Game.Config.Generated";
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
@ -279,11 +280,32 @@ public sealed class SchemaConfigGenerator : IIncrementalGenerator
|
|||||||
var title = TryGetMetadataString(property.Value, "title");
|
var title = TryGetMetadataString(property.Value, "title");
|
||||||
var description = TryGetMetadataString(property.Value, "description");
|
var description = TryGetMetadataString(property.Value, "description");
|
||||||
var refTableName = TryGetMetadataString(property.Value, "x-gframework-ref-table");
|
var refTableName = TryGetMetadataString(property.Value, "x-gframework-ref-table");
|
||||||
|
var indexedLookupMetadata = TryGetMetadataBoolean(property.Value, LookupIndexMetadataKey);
|
||||||
|
if (indexedLookupMetadata.Diagnostic is not null)
|
||||||
|
{
|
||||||
|
return ParsedPropertyResult.FromDiagnostic(
|
||||||
|
Diagnostic.Create(
|
||||||
|
ConfigSchemaDiagnostics.InvalidLookupIndexMetadata,
|
||||||
|
CreateFileLocation(filePath),
|
||||||
|
Path.GetFileName(filePath),
|
||||||
|
displayPath,
|
||||||
|
LookupIndexMetadataKey,
|
||||||
|
indexedLookupMetadata.Diagnostic!));
|
||||||
|
}
|
||||||
|
|
||||||
|
var isIndexedLookup = indexedLookupMetadata.Value ?? false;
|
||||||
if (!TryBuildPropertyIdentifier(filePath, displayPath, property.Name, out var propertyName, out var diagnostic))
|
if (!TryBuildPropertyIdentifier(filePath, displayPath, property.Name, out var propertyName, out var diagnostic))
|
||||||
{
|
{
|
||||||
return ParsedPropertyResult.FromDiagnostic(diagnostic!);
|
return ParsedPropertyResult.FromDiagnostic(diagnostic!);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (isIndexedLookup &&
|
||||||
|
!TryValidateIndexedLookupEligibility(filePath, property.Name, displayPath, isRequired, refTableName,
|
||||||
|
out diagnostic))
|
||||||
|
{
|
||||||
|
return ParsedPropertyResult.FromDiagnostic(diagnostic!);
|
||||||
|
}
|
||||||
|
|
||||||
switch (schemaType)
|
switch (schemaType)
|
||||||
{
|
{
|
||||||
case "integer":
|
case "integer":
|
||||||
@ -294,6 +316,7 @@ public sealed class SchemaConfigGenerator : IIncrementalGenerator
|
|||||||
isRequired,
|
isRequired,
|
||||||
title,
|
title,
|
||||||
description,
|
description,
|
||||||
|
isIndexedLookup,
|
||||||
new SchemaTypeSpec(
|
new SchemaTypeSpec(
|
||||||
SchemaNodeKind.Scalar,
|
SchemaNodeKind.Scalar,
|
||||||
"integer",
|
"integer",
|
||||||
@ -313,6 +336,7 @@ public sealed class SchemaConfigGenerator : IIncrementalGenerator
|
|||||||
isRequired,
|
isRequired,
|
||||||
title,
|
title,
|
||||||
description,
|
description,
|
||||||
|
isIndexedLookup,
|
||||||
new SchemaTypeSpec(
|
new SchemaTypeSpec(
|
||||||
SchemaNodeKind.Scalar,
|
SchemaNodeKind.Scalar,
|
||||||
"number",
|
"number",
|
||||||
@ -332,6 +356,7 @@ public sealed class SchemaConfigGenerator : IIncrementalGenerator
|
|||||||
isRequired,
|
isRequired,
|
||||||
title,
|
title,
|
||||||
description,
|
description,
|
||||||
|
isIndexedLookup,
|
||||||
new SchemaTypeSpec(
|
new SchemaTypeSpec(
|
||||||
SchemaNodeKind.Scalar,
|
SchemaNodeKind.Scalar,
|
||||||
"boolean",
|
"boolean",
|
||||||
@ -351,6 +376,7 @@ public sealed class SchemaConfigGenerator : IIncrementalGenerator
|
|||||||
isRequired,
|
isRequired,
|
||||||
title,
|
title,
|
||||||
description,
|
description,
|
||||||
|
isIndexedLookup,
|
||||||
new SchemaTypeSpec(
|
new SchemaTypeSpec(
|
||||||
SchemaNodeKind.Scalar,
|
SchemaNodeKind.Scalar,
|
||||||
"string",
|
"string",
|
||||||
@ -364,6 +390,18 @@ public sealed class SchemaConfigGenerator : IIncrementalGenerator
|
|||||||
null)));
|
null)));
|
||||||
|
|
||||||
case "object":
|
case "object":
|
||||||
|
if (isIndexedLookup)
|
||||||
|
{
|
||||||
|
return ParsedPropertyResult.FromDiagnostic(
|
||||||
|
Diagnostic.Create(
|
||||||
|
ConfigSchemaDiagnostics.InvalidLookupIndexMetadata,
|
||||||
|
CreateFileLocation(filePath),
|
||||||
|
Path.GetFileName(filePath),
|
||||||
|
displayPath,
|
||||||
|
LookupIndexMetadataKey,
|
||||||
|
"Only top-level required non-key scalar properties can declare a generated lookup index."));
|
||||||
|
}
|
||||||
|
|
||||||
if (!string.IsNullOrWhiteSpace(refTableName))
|
if (!string.IsNullOrWhiteSpace(refTableName))
|
||||||
{
|
{
|
||||||
return ParsedPropertyResult.FromDiagnostic(
|
return ParsedPropertyResult.FromDiagnostic(
|
||||||
@ -393,6 +431,7 @@ public sealed class SchemaConfigGenerator : IIncrementalGenerator
|
|||||||
isRequired,
|
isRequired,
|
||||||
title,
|
title,
|
||||||
description,
|
description,
|
||||||
|
false,
|
||||||
new SchemaTypeSpec(
|
new SchemaTypeSpec(
|
||||||
SchemaNodeKind.Object,
|
SchemaNodeKind.Object,
|
||||||
"object",
|
"object",
|
||||||
@ -406,7 +445,7 @@ public sealed class SchemaConfigGenerator : IIncrementalGenerator
|
|||||||
|
|
||||||
case "array":
|
case "array":
|
||||||
return ParseArrayProperty(filePath, property, isRequired, displayPath, propertyName, title,
|
return ParseArrayProperty(filePath, property, isRequired, displayPath, propertyName, title,
|
||||||
description, refTableName);
|
description, refTableName, isIndexedLookup);
|
||||||
|
|
||||||
default:
|
default:
|
||||||
return ParsedPropertyResult.FromDiagnostic(
|
return ParsedPropertyResult.FromDiagnostic(
|
||||||
@ -419,6 +458,76 @@ public sealed class SchemaConfigGenerator : IIncrementalGenerator
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 验证字段是否满足生成只读精确匹配索引的前提。
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="filePath">Schema 文件路径。</param>
|
||||||
|
/// <param name="schemaName">Schema 原始字段名。</param>
|
||||||
|
/// <param name="displayPath">逻辑字段路径。</param>
|
||||||
|
/// <param name="isRequired">字段是否必填。</param>
|
||||||
|
/// <param name="refTableName">可选的引用表名。</param>
|
||||||
|
/// <param name="diagnostic">不满足条件时输出的诊断。</param>
|
||||||
|
/// <returns>当前字段是否允许声明只读索引。</returns>
|
||||||
|
private static bool TryValidateIndexedLookupEligibility(
|
||||||
|
string filePath,
|
||||||
|
string schemaName,
|
||||||
|
string displayPath,
|
||||||
|
bool isRequired,
|
||||||
|
string? refTableName,
|
||||||
|
out Diagnostic? diagnostic)
|
||||||
|
{
|
||||||
|
diagnostic = null;
|
||||||
|
if (!IsTopLevelPropertyDisplayPath(displayPath))
|
||||||
|
{
|
||||||
|
diagnostic = Diagnostic.Create(
|
||||||
|
ConfigSchemaDiagnostics.InvalidLookupIndexMetadata,
|
||||||
|
CreateFileLocation(filePath),
|
||||||
|
Path.GetFileName(filePath),
|
||||||
|
displayPath,
|
||||||
|
LookupIndexMetadataKey,
|
||||||
|
"Only top-level required non-key scalar properties can declare a generated lookup index.");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!isRequired)
|
||||||
|
{
|
||||||
|
diagnostic = Diagnostic.Create(
|
||||||
|
ConfigSchemaDiagnostics.InvalidLookupIndexMetadata,
|
||||||
|
CreateFileLocation(filePath),
|
||||||
|
Path.GetFileName(filePath),
|
||||||
|
displayPath,
|
||||||
|
LookupIndexMetadataKey,
|
||||||
|
"Generated lookup indexes currently require a required scalar property so dictionary keys remain non-null.");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (string.Equals(schemaName, "id", StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
diagnostic = Diagnostic.Create(
|
||||||
|
ConfigSchemaDiagnostics.InvalidLookupIndexMetadata,
|
||||||
|
CreateFileLocation(filePath),
|
||||||
|
Path.GetFileName(filePath),
|
||||||
|
displayPath,
|
||||||
|
LookupIndexMetadataKey,
|
||||||
|
"The primary key already has Get/TryGet lookup semantics and should not declare a generated lookup index.");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!string.IsNullOrWhiteSpace(refTableName))
|
||||||
|
{
|
||||||
|
diagnostic = Diagnostic.Create(
|
||||||
|
ConfigSchemaDiagnostics.InvalidLookupIndexMetadata,
|
||||||
|
CreateFileLocation(filePath),
|
||||||
|
Path.GetFileName(filePath),
|
||||||
|
displayPath,
|
||||||
|
LookupIndexMetadataKey,
|
||||||
|
"Reference properties are excluded from generated lookup indexes because they already carry cross-table semantics.");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 解析数组属性,支持标量数组与对象数组。
|
/// 解析数组属性,支持标量数组与对象数组。
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@ -439,8 +548,21 @@ public sealed class SchemaConfigGenerator : IIncrementalGenerator
|
|||||||
string propertyName,
|
string propertyName,
|
||||||
string? title,
|
string? title,
|
||||||
string? description,
|
string? description,
|
||||||
string? refTableName)
|
string? refTableName,
|
||||||
|
bool isIndexedLookup)
|
||||||
{
|
{
|
||||||
|
if (isIndexedLookup)
|
||||||
|
{
|
||||||
|
return ParsedPropertyResult.FromDiagnostic(
|
||||||
|
Diagnostic.Create(
|
||||||
|
ConfigSchemaDiagnostics.InvalidLookupIndexMetadata,
|
||||||
|
CreateFileLocation(filePath),
|
||||||
|
Path.GetFileName(filePath),
|
||||||
|
displayPath,
|
||||||
|
LookupIndexMetadataKey,
|
||||||
|
"Only top-level required non-key scalar properties can declare a generated lookup index."));
|
||||||
|
}
|
||||||
|
|
||||||
if (!property.Value.TryGetProperty("items", out var itemsElement) ||
|
if (!property.Value.TryGetProperty("items", out var itemsElement) ||
|
||||||
itemsElement.ValueKind != JsonValueKind.Object ||
|
itemsElement.ValueKind != JsonValueKind.Object ||
|
||||||
!itemsElement.TryGetProperty("type", out var itemTypeElement) ||
|
!itemsElement.TryGetProperty("type", out var itemTypeElement) ||
|
||||||
@ -477,6 +599,7 @@ public sealed class SchemaConfigGenerator : IIncrementalGenerator
|
|||||||
isRequired,
|
isRequired,
|
||||||
title,
|
title,
|
||||||
description,
|
description,
|
||||||
|
false,
|
||||||
new SchemaTypeSpec(
|
new SchemaTypeSpec(
|
||||||
SchemaNodeKind.Array,
|
SchemaNodeKind.Array,
|
||||||
"array",
|
"array",
|
||||||
@ -528,6 +651,7 @@ public sealed class SchemaConfigGenerator : IIncrementalGenerator
|
|||||||
isRequired,
|
isRequired,
|
||||||
title,
|
title,
|
||||||
description,
|
description,
|
||||||
|
false,
|
||||||
new SchemaTypeSpec(
|
new SchemaTypeSpec(
|
||||||
SchemaNodeKind.Array,
|
SchemaNodeKind.Array,
|
||||||
"array",
|
"array",
|
||||||
@ -587,6 +711,9 @@ public sealed class SchemaConfigGenerator : IIncrementalGenerator
|
|||||||
{
|
{
|
||||||
var builder = new StringBuilder();
|
var builder = new StringBuilder();
|
||||||
var queryableProperties = CollectQueryableProperties(schema).ToArray();
|
var queryableProperties = CollectQueryableProperties(schema).ToArray();
|
||||||
|
var indexedQueryableProperties = queryableProperties
|
||||||
|
.Where(static property => property.IsIndexedLookup)
|
||||||
|
.ToArray();
|
||||||
builder.AppendLine("// <auto-generated />");
|
builder.AppendLine("// <auto-generated />");
|
||||||
builder.AppendLine("#nullable enable");
|
builder.AppendLine("#nullable enable");
|
||||||
builder.AppendLine();
|
builder.AppendLine();
|
||||||
@ -603,6 +730,12 @@ public sealed class SchemaConfigGenerator : IIncrementalGenerator
|
|||||||
builder.AppendLine("{");
|
builder.AppendLine("{");
|
||||||
builder.AppendLine(
|
builder.AppendLine(
|
||||||
$" private readonly global::GFramework.Game.Abstractions.Config.IConfigTable<{schema.KeyClrType}, {schema.ClassName}> _inner;");
|
$" private readonly global::GFramework.Game.Abstractions.Config.IConfigTable<{schema.KeyClrType}, {schema.ClassName}> _inner;");
|
||||||
|
foreach (var property in indexedQueryableProperties)
|
||||||
|
{
|
||||||
|
builder.AppendLine(
|
||||||
|
$" private readonly global::System.Lazy<global::System.Collections.Generic.IReadOnlyDictionary<{property.TypeSpec.ClrType}, global::System.Collections.Generic.IReadOnlyList<{schema.ClassName}>>> _{ToCamelCase(property.PropertyName)}Index;");
|
||||||
|
}
|
||||||
|
|
||||||
builder.AppendLine();
|
builder.AppendLine();
|
||||||
builder.AppendLine(" /// <summary>");
|
builder.AppendLine(" /// <summary>");
|
||||||
builder.AppendLine(" /// Creates a generated table wrapper around the runtime config table instance.");
|
builder.AppendLine(" /// Creates a generated table wrapper around the runtime config table instance.");
|
||||||
@ -612,6 +745,14 @@ public sealed class SchemaConfigGenerator : IIncrementalGenerator
|
|||||||
$" public {schema.TableName}(global::GFramework.Game.Abstractions.Config.IConfigTable<{schema.KeyClrType}, {schema.ClassName}> inner)");
|
$" public {schema.TableName}(global::GFramework.Game.Abstractions.Config.IConfigTable<{schema.KeyClrType}, {schema.ClassName}> inner)");
|
||||||
builder.AppendLine(" {");
|
builder.AppendLine(" {");
|
||||||
builder.AppendLine(" _inner = inner ?? throw new global::System.ArgumentNullException(nameof(inner));");
|
builder.AppendLine(" _inner = inner ?? throw new global::System.ArgumentNullException(nameof(inner));");
|
||||||
|
foreach (var property in indexedQueryableProperties)
|
||||||
|
{
|
||||||
|
builder.AppendLine(
|
||||||
|
$" _{ToCamelCase(property.PropertyName)}Index = new global::System.Lazy<global::System.Collections.Generic.IReadOnlyDictionary<{property.TypeSpec.ClrType}, global::System.Collections.Generic.IReadOnlyList<{schema.ClassName}>>>(");
|
||||||
|
builder.AppendLine($" Build{property.PropertyName}Index,");
|
||||||
|
builder.AppendLine(" global::System.Threading.LazyThreadSafetyMode.ExecutionAndPublication);");
|
||||||
|
}
|
||||||
|
|
||||||
builder.AppendLine(" }");
|
builder.AppendLine(" }");
|
||||||
builder.AppendLine();
|
builder.AppendLine();
|
||||||
builder.AppendLine(" /// <inheritdoc />");
|
builder.AppendLine(" /// <inheritdoc />");
|
||||||
@ -648,6 +789,18 @@ public sealed class SchemaConfigGenerator : IIncrementalGenerator
|
|||||||
builder.AppendLine(" return _inner.All();");
|
builder.AppendLine(" return _inner.All();");
|
||||||
builder.AppendLine(" }");
|
builder.AppendLine(" }");
|
||||||
|
|
||||||
|
if (indexedQueryableProperties.Length > 0)
|
||||||
|
{
|
||||||
|
foreach (var property in indexedQueryableProperties)
|
||||||
|
{
|
||||||
|
builder.AppendLine();
|
||||||
|
AppendIndexedLookupBuilderMethod(builder, schema, property);
|
||||||
|
}
|
||||||
|
|
||||||
|
builder.AppendLine();
|
||||||
|
AppendSharedLookupIndexBuilderMethod(builder, schema);
|
||||||
|
}
|
||||||
|
|
||||||
foreach (var property in queryableProperties)
|
foreach (var property in queryableProperties)
|
||||||
{
|
{
|
||||||
builder.AppendLine();
|
builder.AppendLine();
|
||||||
@ -1348,6 +1501,82 @@ public sealed class SchemaConfigGenerator : IIncrementalGenerator
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 为单个索引字段生成延迟构建器。
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="builder">输出缓冲区。</param>
|
||||||
|
/// <param name="schema">生成器级 schema 模型。</param>
|
||||||
|
/// <param name="property">声明了索引元数据的字段。</param>
|
||||||
|
private static void AppendIndexedLookupBuilderMethod(
|
||||||
|
StringBuilder builder,
|
||||||
|
SchemaFileSpec schema,
|
||||||
|
SchemaPropertySpec property)
|
||||||
|
{
|
||||||
|
builder.AppendLine(" /// <summary>");
|
||||||
|
builder.AppendLine(
|
||||||
|
$" /// Builds the exact-match lookup index declared for property '{EscapeXmlDocumentation(property.DisplayPath)}'.");
|
||||||
|
builder.AppendLine(" /// </summary>");
|
||||||
|
builder.AppendLine(
|
||||||
|
$" /// <returns>A read-only lookup index keyed by <c>{EscapeXmlDocumentation(property.PropertyName)}</c>.</returns>");
|
||||||
|
builder.AppendLine(
|
||||||
|
$" private global::System.Collections.Generic.IReadOnlyDictionary<{property.TypeSpec.ClrType}, global::System.Collections.Generic.IReadOnlyList<{schema.ClassName}>> Build{property.PropertyName}Index()");
|
||||||
|
builder.AppendLine(" {");
|
||||||
|
builder.AppendLine(
|
||||||
|
$" return BuildLookupIndex(static config => config.{property.PropertyName});");
|
||||||
|
builder.AppendLine(" }");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 为当前生成表输出共享索引构建逻辑。
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="builder">输出缓冲区。</param>
|
||||||
|
/// <param name="schema">生成器级 schema 模型。</param>
|
||||||
|
private static void AppendSharedLookupIndexBuilderMethod(
|
||||||
|
StringBuilder builder,
|
||||||
|
SchemaFileSpec schema)
|
||||||
|
{
|
||||||
|
builder.AppendLine(" /// <summary>");
|
||||||
|
builder.AppendLine(
|
||||||
|
" /// Materializes a read-only exact-match lookup index from the current table snapshot.");
|
||||||
|
builder.AppendLine(" /// </summary>");
|
||||||
|
builder.AppendLine(" /// <typeparam name=\"TProperty\">Indexed property type.</typeparam>");
|
||||||
|
builder.AppendLine(" /// <param name=\"keySelector\">Selects the indexed property from one config entry.</param>");
|
||||||
|
builder.AppendLine(" /// <returns>A read-only dictionary whose values preserve snapshot iteration order.</returns>");
|
||||||
|
builder.AppendLine(
|
||||||
|
$" private global::System.Collections.Generic.IReadOnlyDictionary<TProperty, global::System.Collections.Generic.IReadOnlyList<{schema.ClassName}>> BuildLookupIndex<TProperty>(");
|
||||||
|
builder.AppendLine($" global::System.Func<{schema.ClassName}, TProperty> keySelector)");
|
||||||
|
builder.AppendLine(" where TProperty : notnull");
|
||||||
|
builder.AppendLine(" {");
|
||||||
|
builder.AppendLine(" var buckets = new global::System.Collections.Generic.Dictionary<TProperty, global::System.Collections.Generic.List<" +
|
||||||
|
$"{schema.ClassName}>>();");
|
||||||
|
builder.AppendLine();
|
||||||
|
builder.AppendLine(
|
||||||
|
" // Capture the current table snapshot once so indexed lookups stay deterministic for this wrapper instance.");
|
||||||
|
builder.AppendLine(" foreach (var candidate in All())");
|
||||||
|
builder.AppendLine(" {");
|
||||||
|
builder.AppendLine(" var key = keySelector(candidate);");
|
||||||
|
builder.AppendLine(" if (!buckets.TryGetValue(key, out var matches))");
|
||||||
|
builder.AppendLine(" {");
|
||||||
|
builder.AppendLine($" matches = new global::System.Collections.Generic.List<{schema.ClassName}>();");
|
||||||
|
builder.AppendLine(" buckets.Add(key, matches);");
|
||||||
|
builder.AppendLine(" }");
|
||||||
|
builder.AppendLine();
|
||||||
|
builder.AppendLine(" matches.Add(candidate);");
|
||||||
|
builder.AppendLine(" }");
|
||||||
|
builder.AppendLine();
|
||||||
|
builder.AppendLine(
|
||||||
|
$" var materialized = new global::System.Collections.Generic.Dictionary<TProperty, global::System.Collections.Generic.IReadOnlyList<{schema.ClassName}>>(buckets.Count, buckets.Comparer);");
|
||||||
|
builder.AppendLine(" foreach (var pair in buckets)");
|
||||||
|
builder.AppendLine(" {");
|
||||||
|
builder.AppendLine(
|
||||||
|
$" materialized.Add(pair.Key, global::System.Array.AsReadOnly(pair.Value.ToArray()));");
|
||||||
|
builder.AppendLine(" }");
|
||||||
|
builder.AppendLine();
|
||||||
|
builder.AppendLine(
|
||||||
|
$" return new global::System.Collections.ObjectModel.ReadOnlyDictionary<TProperty, global::System.Collections.Generic.IReadOnlyList<{schema.ClassName}>>(materialized);");
|
||||||
|
builder.AppendLine(" }");
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 生成按字段匹配全部结果的轻量查询辅助。
|
/// 生成按字段匹配全部结果的轻量查询辅助。
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@ -1366,12 +1595,33 @@ public sealed class SchemaConfigGenerator : IIncrementalGenerator
|
|||||||
builder.AppendLine(" /// <param name=\"value\">The property value to match.</param>");
|
builder.AppendLine(" /// <param name=\"value\">The property value to match.</param>");
|
||||||
builder.AppendLine(" /// <returns>A read-only snapshot containing every matching config entry.</returns>");
|
builder.AppendLine(" /// <returns>A read-only snapshot containing every matching config entry.</returns>");
|
||||||
builder.AppendLine(" /// <remarks>");
|
builder.AppendLine(" /// <remarks>");
|
||||||
|
if (property.IsIndexedLookup)
|
||||||
|
{
|
||||||
|
builder.AppendLine(
|
||||||
|
" /// This property declares <c>x-gframework-index</c>, so the generated helper resolves matches through a lazily materialized read-only lookup index built from the current table snapshot.");
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
builder.AppendLine(
|
builder.AppendLine(
|
||||||
" /// The generated helper performs a deterministic linear scan over <see cref=\"All\"/> so it stays compatible with runtime hot reload and does not require secondary index infrastructure.");
|
" /// The generated helper performs a deterministic linear scan over <see cref=\"All\"/> so it stays compatible with runtime hot reload and does not require secondary index infrastructure.");
|
||||||
|
}
|
||||||
|
|
||||||
builder.AppendLine(" /// </remarks>");
|
builder.AppendLine(" /// </remarks>");
|
||||||
builder.AppendLine(
|
builder.AppendLine(
|
||||||
$" public global::System.Collections.Generic.IReadOnlyList<{schema.ClassName}> FindBy{property.PropertyName}({property.TypeSpec.ClrType} value)");
|
$" public global::System.Collections.Generic.IReadOnlyList<{schema.ClassName}> FindBy{property.PropertyName}({property.TypeSpec.ClrType} value)");
|
||||||
builder.AppendLine(" {");
|
builder.AppendLine(" {");
|
||||||
|
if (property.IsIndexedLookup)
|
||||||
|
{
|
||||||
|
builder.AppendLine(
|
||||||
|
$" if (_{ToCamelCase(property.PropertyName)}Index.Value.TryGetValue(value, out var matches))");
|
||||||
|
builder.AppendLine(" {");
|
||||||
|
builder.AppendLine(" return matches;");
|
||||||
|
builder.AppendLine(" }");
|
||||||
|
builder.AppendLine();
|
||||||
|
builder.AppendLine($" return global::System.Array.Empty<{schema.ClassName}>();");
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
builder.AppendLine(
|
builder.AppendLine(
|
||||||
$" var matches = new global::System.Collections.Generic.List<{schema.ClassName}>();");
|
$" var matches = new global::System.Collections.Generic.List<{schema.ClassName}>();");
|
||||||
builder.AppendLine();
|
builder.AppendLine();
|
||||||
@ -1388,6 +1638,8 @@ public sealed class SchemaConfigGenerator : IIncrementalGenerator
|
|||||||
builder.AppendLine();
|
builder.AppendLine();
|
||||||
builder.AppendLine(
|
builder.AppendLine(
|
||||||
$" return matches.Count == 0 ? global::System.Array.Empty<{schema.ClassName}>() : matches.AsReadOnly();");
|
$" return matches.Count == 0 ? global::System.Array.Empty<{schema.ClassName}>() : matches.AsReadOnly();");
|
||||||
|
}
|
||||||
|
|
||||||
builder.AppendLine(" }");
|
builder.AppendLine(" }");
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -1412,12 +1664,35 @@ public sealed class SchemaConfigGenerator : IIncrementalGenerator
|
|||||||
builder.AppendLine(
|
builder.AppendLine(
|
||||||
" /// <returns><see langword=\"true\" /> when a matching config entry is found; otherwise <see langword=\"false\" />.</returns>");
|
" /// <returns><see langword=\"true\" /> when a matching config entry is found; otherwise <see langword=\"false\" />.</returns>");
|
||||||
builder.AppendLine(" /// <remarks>");
|
builder.AppendLine(" /// <remarks>");
|
||||||
|
if (property.IsIndexedLookup)
|
||||||
|
{
|
||||||
|
builder.AppendLine(
|
||||||
|
" /// This property declares <c>x-gframework-index</c>, so the generated helper returns the first element from the lazily materialized exact-match bucket.");
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
builder.AppendLine(
|
builder.AppendLine(
|
||||||
" /// The generated helper walks the same snapshot exposed by <see cref=\"All\"/> and returns the first match in iteration order.");
|
" /// The generated helper walks the same snapshot exposed by <see cref=\"All\"/> and returns the first match in iteration order.");
|
||||||
|
}
|
||||||
|
|
||||||
builder.AppendLine(" /// </remarks>");
|
builder.AppendLine(" /// </remarks>");
|
||||||
builder.AppendLine(
|
builder.AppendLine(
|
||||||
$" public bool TryFindFirstBy{property.PropertyName}({property.TypeSpec.ClrType} value, out {schema.ClassName}? result)");
|
$" public bool TryFindFirstBy{property.PropertyName}({property.TypeSpec.ClrType} value, out {schema.ClassName}? result)");
|
||||||
builder.AppendLine(" {");
|
builder.AppendLine(" {");
|
||||||
|
if (property.IsIndexedLookup)
|
||||||
|
{
|
||||||
|
builder.AppendLine(
|
||||||
|
$" if (_{ToCamelCase(property.PropertyName)}Index.Value.TryGetValue(value, out var matches) && matches.Count > 0)");
|
||||||
|
builder.AppendLine(" {");
|
||||||
|
builder.AppendLine(" result = matches[0];");
|
||||||
|
builder.AppendLine(" return true;");
|
||||||
|
builder.AppendLine(" }");
|
||||||
|
builder.AppendLine();
|
||||||
|
builder.AppendLine(" result = null;");
|
||||||
|
builder.AppendLine(" return false;");
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
builder.AppendLine(
|
builder.AppendLine(
|
||||||
" // Keep the search path allocation-free for the first-match case by exiting as soon as one entry matches.");
|
" // Keep the search path allocation-free for the first-match case by exiting as soon as one entry matches.");
|
||||||
builder.AppendLine(" foreach (var candidate in All())");
|
builder.AppendLine(" foreach (var candidate in All())");
|
||||||
@ -1432,6 +1707,8 @@ public sealed class SchemaConfigGenerator : IIncrementalGenerator
|
|||||||
builder.AppendLine();
|
builder.AppendLine();
|
||||||
builder.AppendLine(" result = null;");
|
builder.AppendLine(" result = null;");
|
||||||
builder.AppendLine(" return false;");
|
builder.AppendLine(" return false;");
|
||||||
|
}
|
||||||
|
|
||||||
builder.AppendLine(" }");
|
builder.AppendLine(" }");
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -1715,6 +1992,17 @@ public sealed class SchemaConfigGenerator : IIncrementalGenerator
|
|||||||
return $"schemas/{Path.GetFileName(path)}";
|
return $"schemas/{Path.GetFileName(path)}";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 判断字段路径是否表示根对象的直接子字段。
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="displayPath">逻辑字段路径。</param>
|
||||||
|
/// <returns>根对象直接子字段时返回 <c>true</c>;否则返回 <c>false</c>。</returns>
|
||||||
|
private static bool IsTopLevelPropertyDisplayPath(string displayPath)
|
||||||
|
{
|
||||||
|
return displayPath.IndexOf('.') < 0 &&
|
||||||
|
displayPath.IndexOf('[') < 0;
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 将 schema 名称转换为 PascalCase 标识符。
|
/// 将 schema 名称转换为 PascalCase 标识符。
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@ -1731,6 +2019,26 @@ public sealed class SchemaConfigGenerator : IIncrementalGenerator
|
|||||||
return tokens.Length == 0 ? "Config" : string.Concat(tokens);
|
return tokens.Length == 0 ? "Config" : string.Concat(tokens);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 将 PascalCase 标识符转换为 camelCase 字段名。
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="value">PascalCase 标识符。</param>
|
||||||
|
/// <returns>适合作为私有字段名的 camelCase 标识符。</returns>
|
||||||
|
private static string ToCamelCase(string value)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(value))
|
||||||
|
{
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (value.Length == 1)
|
||||||
|
{
|
||||||
|
return char.ToLowerInvariant(value[0]).ToString();
|
||||||
|
}
|
||||||
|
|
||||||
|
return char.ToLowerInvariant(value[0]) + value.Substring(1);
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 将 schema 字段路径转换为可用于生成引用元数据成员的 PascalCase 标识符。
|
/// 将 schema 字段路径转换为可用于生成引用元数据成员的 PascalCase 标识符。
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@ -1784,6 +2092,28 @@ public sealed class SchemaConfigGenerator : IIncrementalGenerator
|
|||||||
return string.IsNullOrWhiteSpace(value) ? null : value;
|
return string.IsNullOrWhiteSpace(value) ? null : value;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 读取布尔元数据。
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="element">Schema 节点。</param>
|
||||||
|
/// <param name="propertyName">元数据字段名。</param>
|
||||||
|
/// <returns>布尔元数据值;不存在时返回空。</returns>
|
||||||
|
private static (bool? Value, string? Diagnostic) TryGetMetadataBoolean(JsonElement element, string propertyName)
|
||||||
|
{
|
||||||
|
if (!element.TryGetProperty(propertyName, out var metadataElement))
|
||||||
|
{
|
||||||
|
return (null, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (metadataElement.ValueKind != JsonValueKind.True &&
|
||||||
|
metadataElement.ValueKind != JsonValueKind.False)
|
||||||
|
{
|
||||||
|
return (null, $"Expected a JSON boolean but found '{metadataElement.ValueKind}'.");
|
||||||
|
}
|
||||||
|
|
||||||
|
return (metadataElement.GetBoolean(), null);
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 解析 schema 顶层配置目录元数据。
|
/// 解析 schema 顶层配置目录元数据。
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@ -2210,6 +2540,7 @@ public sealed class SchemaConfigGenerator : IIncrementalGenerator
|
|||||||
/// <param name="IsRequired">是否必填。</param>
|
/// <param name="IsRequired">是否必填。</param>
|
||||||
/// <param name="Title">字段标题元数据。</param>
|
/// <param name="Title">字段标题元数据。</param>
|
||||||
/// <param name="Description">字段描述元数据。</param>
|
/// <param name="Description">字段描述元数据。</param>
|
||||||
|
/// <param name="IsIndexedLookup">是否声明生成只读精确匹配索引。</param>
|
||||||
/// <param name="TypeSpec">字段类型模型。</param>
|
/// <param name="TypeSpec">字段类型模型。</param>
|
||||||
private sealed record SchemaPropertySpec(
|
private sealed record SchemaPropertySpec(
|
||||||
string SchemaName,
|
string SchemaName,
|
||||||
@ -2218,6 +2549,7 @@ public sealed class SchemaConfigGenerator : IIncrementalGenerator
|
|||||||
bool IsRequired,
|
bool IsRequired,
|
||||||
string? Title,
|
string? Title,
|
||||||
string? Description,
|
string? Description,
|
||||||
|
bool IsIndexedLookup,
|
||||||
SchemaTypeSpec TypeSpec);
|
SchemaTypeSpec TypeSpec);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
|
|||||||
@ -85,4 +85,15 @@ public static class ConfigSchemaDiagnostics
|
|||||||
SourceGeneratorsConfigCategory,
|
SourceGeneratorsConfigCategory,
|
||||||
DiagnosticSeverity.Error,
|
DiagnosticSeverity.Error,
|
||||||
true);
|
true);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// schema 字段的查询索引元数据无效。
|
||||||
|
/// </summary>
|
||||||
|
public static readonly DiagnosticDescriptor InvalidLookupIndexMetadata = new(
|
||||||
|
"GF_ConfigSchema_008",
|
||||||
|
"Config schema uses invalid lookup index metadata",
|
||||||
|
"Property '{1}' in schema file '{0}' uses invalid '{2}' metadata: {3}",
|
||||||
|
SourceGeneratorsConfigCategory,
|
||||||
|
DiagnosticSeverity.Error,
|
||||||
|
true);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -365,6 +365,18 @@ var slime = runtime.GetMonster(1);
|
|||||||
|
|
||||||
从当前阶段开始,生成的 `*Table` 包装会为“顶层、非主键、非引用的标量字段”额外产出轻量查询辅助。
|
从当前阶段开始,生成的 `*Table` 包装会为“顶层、非主键、非引用的标量字段”额外产出轻量查询辅助。
|
||||||
|
|
||||||
|
如果某个字段属于高频精确匹配条件,可以在 schema 中显式声明:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"type": "string",
|
||||||
|
"x-gframework-index": true
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
当前这个元数据只支持“顶层、必填、非主键、非引用标量字段”。命中该条件时,生成的 `FindBy*` /
|
||||||
|
`TryFindFirstBy*` API 不会变,但内部会改成按需构建只读精确匹配索引;没有声明的字段仍保持线性扫描。
|
||||||
|
|
||||||
如果 `monster.schema.json` 包含顶层标量字段 `name`、`faction`,则可以直接这样使用:
|
如果 `monster.schema.json` 包含顶层标量字段 `name`、`faction`,则可以直接这样使用:
|
||||||
|
|
||||||
```csharp
|
```csharp
|
||||||
@ -383,7 +395,8 @@ if (monsterTable.TryFindFirstByFaction("dungeon", out var firstDungeonMonster))
|
|||||||
- 只为顶层标量字段生成 `FindBy*` 与 `TryFindFirstBy*`
|
- 只为顶层标量字段生成 `FindBy*` 与 `TryFindFirstBy*`
|
||||||
- 主键字段继续只走 `Get / TryGet`
|
- 主键字段继续只走 `Get / TryGet`
|
||||||
- 嵌套对象、对象数组、标量数组和 `x-gframework-ref-table` 字段暂不生成查询辅助
|
- 嵌套对象、对象数组、标量数组和 `x-gframework-ref-table` 字段暂不生成查询辅助
|
||||||
- 查询实现基于 `All()` 做线性扫描,不引入运行时索引或缓存
|
- 只有显式声明 `x-gframework-index: true` 的字段才会生成惰性只读索引
|
||||||
|
- 未声明索引的字段继续基于 `All()` 做线性扫描,不引入额外运行时索引成本
|
||||||
|
|
||||||
这意味着它的定位是“减少业务层手写过滤样板”,而不是“替代专门索引结构”。
|
这意味着它的定位是“减少业务层手写过滤样板”,而不是“替代专门索引结构”。
|
||||||
|
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user