using GFramework.SourceGenerators.Common.Diagnostics;
namespace GFramework.SourceGenerators.Common.Extensions;
///
/// 提供生成方法名冲突校验的通用扩展。
///
public static class GeneratedMethodConflictExtensions
{
///
/// 检查目标类型上是否已存在与生成器保留方法同名的零参数方法,并在冲突时报告统一诊断。
///
/// 待校验的目标类型。
/// 源代码生成上下文。
/// 当冲突成员缺少源码位置时使用的后备位置。
/// 生成器将保留的零参数方法名集合。
/// 若发现任一冲突则返回 true。
public static bool ReportGeneratedMethodConflicts(
this INamedTypeSymbol typeSymbol,
SourceProductionContext context,
Location fallbackLocation,
params string[] generatedMethodNames)
{
var hasConflict = false;
foreach (var generatedMethodName in generatedMethodNames.Distinct(StringComparer.Ordinal))
{
var conflictingMethod = typeSymbol.GetMembers()
.OfType()
.FirstOrDefault(method =>
!method.IsImplicitlyDeclared &&
string.Equals(method.Name, generatedMethodName, StringComparison.Ordinal) &&
method.Parameters.Length == 0 &&
method.TypeParameters.Length == 0);
if (conflictingMethod is null)
continue;
context.ReportDiagnostic(Diagnostic.Create(
CommonDiagnostics.GeneratedMethodNameConflict,
conflictingMethod.Locations.FirstOrDefault() ?? fallbackLocation,
typeSymbol.Name,
generatedMethodName));
hasConflict = true;
}
return hasConflict;
}
}