From 49fe9d599a31c5786d6cd3d0d1cef0967e41c19e Mon Sep 17 00:00:00 2001 From: wanglei Date: Sat, 5 Dec 2026 21:32:39 +0800 Subject: [PATCH] Plan recipe variable renames from bound C# references --- PLCSharpWpf/Models/VariableRename.cs | 64 +++++++++++++++++++++ PLCSharpWpf/Models/WorkflowReferences.cs | 20 ++++++- Tests/PLCSharp.Tests/VariableRenameTests.cs | 43 ++++++++++++++ 3 files changed, 124 insertions(+), 3 deletions(-) create mode 100644 PLCSharpWpf/Models/VariableRename.cs create mode 100644 Tests/PLCSharp.Tests/VariableRenameTests.cs diff --git a/PLCSharpWpf/Models/VariableRename.cs b/PLCSharpWpf/Models/VariableRename.cs new file mode 100644 index 0000000..e400e23 --- /dev/null +++ b/PLCSharpWpf/Models/VariableRename.cs @@ -0,0 +1,64 @@ +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.Text; +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using System.Text.Json.Nodes; +using System.Text.Json.Serialization; + +namespace PLCSharp.Models; + +public sealed record RenamedScript(Guid Id, string Name, string Path, string Before, string After, WorkflowScriptReview Review); +public sealed record VariableRename(Guid VariableId, Guid RecipeId, string OldName, string NewName, + List Scripts, JsonArray ManualReferences, JsonArray ScanDiagnostics) +{ + public bool Compiled => Scripts.All(s => s.Review.Compiled) && ScanDiagnostics.Count == 0; + [JsonIgnore] internal string Scope { get; init; } + [JsonIgnore] internal string OriginalVariables { get; init; } + public Guid? UndoOf { get; init; } +} + +public sealed partial class ProjectDirectory +{ + internal const string VariablesPath = "configuration/variables.json"; + + internal string RenameScope(Guid recipe) + { + var inputs = Flows(recipe).OrderBy(w => w.ID).Select(w => new { w.ID, w.Code }); + return Convert.ToHexString(SHA256.HashData(JsonSerializer.SerializeToUtf8Bytes(inputs))); + } + + internal void CheckVariableName(Guid recipe, Guid id, string oldName, string newName) + { + if (string.IsNullOrWhiteSpace(newName) || newName != newName.Trim() || newName == oldName) + throw new ArgumentException("请输入不同的新名称,首尾不能有空白。"); + var rows = Data.Variables.Where(v => v.RecipeID == recipe).ToList(); + if (!rows.Any(v => v.ID == id && v.Name == oldName) || + rows.Any(v => v.ID != id && (v.Name == oldName || v.Name == newName))) + throw new ProjectConflictException("变量已更改或配方内存在重名。"); + } + + internal VariableRename PlanRename(Guid id, string newName) + { + var variable = Data.Variables.Single(v => v.ID == id); + CheckVariableName(variable.RecipeID, id, variable.Name, newName); + var analysis = WorkflowReferences.Find(this, "Variables", id.ToString(), forRename: true); + var hits = analysis["hits"].AsArray(); + var manual = new JsonArray(); + foreach (var hit in hits.Where(h => (string)h["confidence"] != "confirmed")) manual.Add(hit.DeepClone()); + var edits = new List(); + foreach (var group in hits.Where(h => (string)h["confidence"] == "confirmed").GroupBy(h => (Guid)h["workflowId"])) + { + var flow = Flows(variable.RecipeID).Single(w => w.ID == group.Key); + string replacement = SymbolDisplay.FormatLiteral(newName, quote: true); + var changes = group.Select(h => new TextChange(new TextSpan((int)h["start"], (int)h["length"]), replacement)) + .Distinct().OrderBy(c => c.Span.Start); + var next = SourceText.From(flow.Code).WithChanges(changes).ToString(); + edits.Add(new(flow.ID, flow.Name, ScriptPath(variable.RecipeID, flow.ID), flow.Code, next, + WorkflowScriptReview.Create(flow.ID, flow.Code, next))); + } + return new(id, variable.RecipeID, variable.Name, newName, edits, manual, analysis["diagnostics"].AsArray()) + { Scope = RenameScope(variable.RecipeID), OriginalVariables = baseline[VariablesPath] }; + } +} + diff --git a/PLCSharpWpf/Models/WorkflowReferences.cs b/PLCSharpWpf/Models/WorkflowReferences.cs index 06dd7b7..01e82e0 100644 --- a/PLCSharpWpf/Models/WorkflowReferences.cs +++ b/PLCSharpWpf/Models/WorkflowReferences.cs @@ -22,7 +22,7 @@ internal static class WorkflowReferences .Select(p => MetadataReference.CreateFromFile(p)).ToArray(); }); - internal static JsonNode Find(ProjectDirectory project, string kind, string id) + internal static JsonNode Find(ProjectDirectory project, string kind, string id, bool forRename = false) { var targetType = kind switch { "Variables" => typeof(Variable), "SystemVariables" => typeof(SystemVariable), "Workflows" => typeof(Workflow), _ => throw new ArgumentException("Expected Variables, SystemVariables or Workflows.") }; @@ -46,7 +46,7 @@ internal static class WorkflowReferences if (constant.HasValue && !Equals(constant.Value, name)) return; var position = location.GetLocation().GetLineSpan().StartLinePosition; hits.Add(new { workflowId = workflow.ID, workflow.Name, path, line = position.Line + 1, - column = position.Character + 1, expression = location.ToString(), + column = position.Character + 1, start = value.SpanStart, length = value.Span.Length, expression = location.ToString(), confidence = !constant.HasValue ? "dynamic" : bound ? "confirmed" : "possible" }); } var lookup = kind switch { "Variables" => "GetVariable", "Workflows" => "GetTask", _ => null }; @@ -65,10 +65,24 @@ internal static class WorkflowReferences { if (model.GetSymbolInfo(member).Symbol is IPropertySymbol property && property.Name == "Name" && property.ContainingType.ToDisplayString() == targetType.FullName) - Record(value, comparison, true); + Record(value, comparison, !forRename || IsRecipeVariablePredicate(member, model)); } } } return JsonSerializer.SerializeToNode(new { recipeId, targetId = id, name, hits, diagnostics }); } + private static bool IsRecipeVariablePredicate(ExpressionSyntax expression, SemanticModel model) + { + if (expression is not MemberAccessExpressionSyntax access || + model.GetSymbolInfo(access.Expression).Symbol is not IParameterSymbol parameter || + access.FirstAncestorOrSelf() is not { } lambda || + !SymbolEqualityComparer.Default.Equals(parameter.ContainingSymbol, model.GetSymbolInfo(lambda).Symbol) || + lambda.Parent?.Parent?.Parent is not InvocationExpressionSyntax call || + call.Expression is not MemberAccessExpressionSyntax method || + model.GetSymbolInfo(call).Symbol is not IMethodSymbol resolved || + resolved.ReducedFrom?.ContainingType.ToDisplayString() != "System.Linq.Enumerable") return false; + return model.GetSymbolInfo(method.Expression).Symbol is IPropertySymbol source && + source.Name == "Variables" && source.ContainingType.ToDisplayString() == typeof(VariablesModel).FullName; + } + } diff --git a/Tests/PLCSharp.Tests/VariableRenameTests.cs b/Tests/PLCSharp.Tests/VariableRenameTests.cs new file mode 100644 index 0000000..49c20cf --- /dev/null +++ b/Tests/PLCSharp.Tests/VariableRenameTests.cs @@ -0,0 +1,43 @@ +using PLCSharp.Models; +using PLCSharp.VVMs.GlobalVariables; +using PLCSharp.VVMs.Workflows; + +namespace PLCSharp.Tests; + +public class VariableRenameTests +{ + [Fact] + public void PreviewReplacesBoundArgumentsAndListsRuntimeLookups() + { + using var project = ProjectDirectory.New(); + var variable = new Variable { Name = "计数", RecipeID = project.DefaultRecipeId }; + project.Data.Add(variable); + project.Data.Save(); + var flow = new Workflow { Name = "搬运" }; + flow.Code = $$""" + using PLCSharp.Models; + using PLCSharp.Core.Common; + using System.Linq; + public class Extension_{{flow.ID:N}} { + public void Run(GlobalModel model, FlowModel f) { + const string label = "计数"; + _ = model.GetVariable(label); + _ = model.VariablesModel.Variables.FirstOrDefault(v => v.Name == "计数"); + _ = model.GetVariable(f.Step.ToString()); + // model.GetVariable("计数"); + } + } + """; + project.Flows(variable.RecipeID).Add(flow); + var preview = project.PlanRename(variable.ID, "完成数"); + Assert.True(preview.Compiled); + var edit = Assert.Single(preview.Scripts); + Assert.Contains("GetVariable(\"完成数\")", edit.After); + Assert.Contains("v.Name == \"完成数\"", edit.After); + Assert.Contains("const string label = \"计数\"", edit.After); + Assert.Contains("// model.GetVariable(\"计数\")", edit.After); + Assert.Single(preview.ManualReferences); + Assert.Equal(edit.Before, flow.Code); + } +} +