using Microsoft.CodeAnalysis; using System.Text.Json.Nodes; namespace PLCSharp.Models; internal static class AiNamePolicy { private static readonly HashSet Protected = new( ProjectConfiguration.Groups["hardware"].Concat(ProjectConfiguration.Groups["points"]) .Concat(["Recipes", "InterpolationSegments", "InterpolationPoints"])); private static readonly HashSet Types = Protected.Select(kind => WorkflowReferences.TargetType(kind).FullName).ToHashSet(); internal static void CheckRename(string kind) { if (kind != null && Protected.Contains(kind)) throw new ArgumentException("AI 可以引用硬件、配方和点位,但不能修改这些对象的名称。"); } internal static bool IsProtectedType(INamedTypeSymbol type) { for (; type != null; type = type.BaseType) if (Types.Contains(type.ToDisplayString())) return true; return false; } internal static void CheckInterpolationNames(JsonArray before, JsonArray after) { // Embedded segments and points have no stable ID. A simultaneous removal and addition // cannot be distinguished from a rename when the parent array is replaced. static void CheckNames(JsonArray oldItems, JsonArray newItems) { var oldNames = oldItems.Select(i => (string)i["Name"]).ToHashSet(); var newNames = newItems.Select(i => (string)i["Name"]).ToHashSet(); if (oldNames.Except(newNames).Any() && newNames.Except(oldNames).Any()) CheckRename("InterpolationPoints"); } CheckNames(before, after); foreach (var segment in before) { var next = after.FirstOrDefault(s => (string)s["Name"] == (string)segment["Name"]); if (next != null) CheckNames(JsonNode.Parse((string)segment["SerializedInterpolations"] ?? "[]").AsArray(), JsonNode.Parse((string)next["SerializedInterpolations"] ?? "[]").AsArray()); } } }