From 46dc6282fc08562dbb41af575eac672ffafdcb16 Mon Sep 17 00:00:00 2001 From: wanglei Date: Sat, 5 Dec 2026 21:15:24 +0800 Subject: [PATCH] Locate recipe-scoped variable and workflow references with Roslyn --- PLCSharp.Mcp/ProjectTools.cs | 3 + PLCSharpWpf/Models/ProjectInspection.cs | 1 + PLCSharpWpf/Models/WorkflowReferences.cs | 74 ++++++++++++++++++++++++ Tests/mcp_smoke.py | 15 +++++ 4 files changed, 93 insertions(+) create mode 100644 PLCSharpWpf/Models/WorkflowReferences.cs diff --git a/PLCSharp.Mcp/ProjectTools.cs b/PLCSharp.Mcp/ProjectTools.cs index 7bc0cb3..407cb22 100644 --- a/PLCSharp.Mcp/ProjectTools.cs +++ b/PLCSharp.Mcp/ProjectTools.cs @@ -7,6 +7,9 @@ namespace PLCSharp.Mcp; [McpServerToolType] internal sealed class ProjectTools(ProjectGateway gateway) { + [McpServerTool(Name = "find_references", ReadOnly = true), Description("Find C# references to a Variables, SystemVariables or Workflows ID within its recipe. Dynamic hits require human review.")] + public string FindReferences(string kind, string id) => gateway.Call("references", new() { ["kind"] = kind, ["id"] = id }); + [McpServerTool(Name = "get_project_summary", ReadOnly = true), Description("Read the bound PLCSharp project, default recipe and available object kinds.")] public string Summary() => gateway.Call("summary", new()); diff --git a/PLCSharpWpf/Models/ProjectInspection.cs b/PLCSharpWpf/Models/ProjectInspection.cs index ad71bff..3333b69 100644 --- a/PLCSharpWpf/Models/ProjectInspection.cs +++ b/PLCSharpWpf/Models/ProjectInspection.cs @@ -9,6 +9,7 @@ public static class ProjectInspection public static JsonNode Query(ProjectDirectory project, string operation, JsonObject args) { + if (operation == "references") return WorkflowReferences.Find(project, (string)args["kind"], (string)args["id"]); if (operation == "summary") return JsonSerializer.SerializeToNode(new { project.Id, project.DefaultRecipeId, project.Root, kinds = Kinds, recipes = project.Recipes.Select(r => new { r.ID, r.Name }) }); diff --git a/PLCSharpWpf/Models/WorkflowReferences.cs b/PLCSharpWpf/Models/WorkflowReferences.cs new file mode 100644 index 0000000..06dd7b7 --- /dev/null +++ b/PLCSharpWpf/Models/WorkflowReferences.cs @@ -0,0 +1,74 @@ +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using PLCSharp.VVMs.GlobalVariables; +using PLCSharp.VVMs.Workflows; +using System.IO; +using System.Text.Json; +using System.Text.Json.Nodes; + +namespace PLCSharp.Models; + +internal static class WorkflowReferences +{ + private static readonly Lazy References = new(() => + { + var assemblies = ((string)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES")).Split(Path.PathSeparator); + var needed = new HashSet(StringComparer.OrdinalIgnoreCase) { "System.Private.CoreLib", "System.Runtime", + "System.Linq", "System.Collections", "System.ObjectModel", "System.ComponentModel", "Prism.Core", + typeof(GlobalModel).Assembly.GetName().Name }; + return assemblies.Append(typeof(GlobalModel).Assembly.Location).Distinct(StringComparer.OrdinalIgnoreCase) + .Where(p => needed.Contains(Path.GetFileNameWithoutExtension(p))) + .Select(p => MetadataReference.CreateFromFile(p)).ToArray(); + }); + + internal static JsonNode Find(ProjectDirectory project, string kind, string id) + { + var targetType = kind switch { "Variables" => typeof(Variable), "SystemVariables" => typeof(SystemVariable), + "Workflows" => typeof(Workflow), _ => throw new ArgumentException("Expected Variables, SystemVariables or Workflows.") }; + var target = ProjectInspection.Query(project, "get", new() { ["kind"] = kind, ["id"] = id }); + var recipeId = Guid.Parse((string)target["RecipeID"]); + var name = (string)target["Name"]; + var hits = new List(); + var diagnostics = new List(); + foreach (var workflow in project.Flows(recipeId)) + { + var tree = CSharpSyntaxTree.ParseText(workflow.Code ?? ""); + var root = tree.GetRoot(); + var model = CSharpCompilation.Create("Inspect", [tree], References.Value).GetSemanticModel(tree); + var path = $"recipes/{recipeId:D}/workflows/{workflow.ID:D}.cs"; + foreach (var error in tree.GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error)) + diagnostics.Add(new { path, line = error.Location.GetLineSpan().StartLinePosition.Line + 1, message = error.GetMessage() }); + + void Record(ExpressionSyntax value, SyntaxNode location, bool bound) + { + var constant = model.GetConstantValue(value); + 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(), + confidence = !constant.HasValue ? "dynamic" : bound ? "confirmed" : "possible" }); + } + var lookup = kind switch { "Variables" => "GetVariable", "Workflows" => "GetTask", _ => null }; + foreach (var call in root.DescendantNodes().OfType()) + { + var methodName = call.Expression switch { MemberAccessExpressionSyntax m => m.Name.Identifier.ValueText, + MemberBindingExpressionSyntax b => b.Name.Identifier.ValueText, IdentifierNameSyntax n => n.Identifier.ValueText, _ => "" }; + if (methodName != lookup || call.ArgumentList.Arguments.Count != 1) continue; + var symbol = model.GetSymbolInfo(call).Symbol; + if (symbol != null && symbol.ContainingType?.ToDisplayString() != typeof(GlobalModel).FullName) continue; + Record(call.ArgumentList.Arguments[0].Expression, call, symbol != null); + } + foreach (var comparison in root.DescendantNodes().OfType().Where(e => e.IsKind(SyntaxKind.EqualsExpression))) + { + foreach (var (member, value) in new[] { (comparison.Left, comparison.Right), (comparison.Right, comparison.Left) }) + { + if (model.GetSymbolInfo(member).Symbol is IPropertySymbol property && property.Name == "Name" && + property.ContainingType.ToDisplayString() == targetType.FullName) + Record(value, comparison, true); + } + } + } + return JsonSerializer.SerializeToNode(new { recipeId, targetId = id, name, hits, diagnostics }); + } +} diff --git a/Tests/mcp_smoke.py b/Tests/mcp_smoke.py index a507365..9a54058 100644 --- a/Tests/mcp_smoke.py +++ b/Tests/mcp_smoke.py @@ -58,6 +58,21 @@ def verify(exe, source): assert variable["name"] == "计数" source_object = client.call("get_object", kind="Workflows", id=workflow["id"]) assert source_object["Code"] == "// portability fixture" + assert client.call("find_references", kind="Variables", id=variable["id"])["hits"] == [] + script = next(project.rglob("*.cs")) + script.write_text('''using PLCSharp.Models; +class Sample { + void Inspect(GlobalModel model, string runtimeName) { + // model.GetVariable("计数"); + model.GetVariable("计数"); + model.GetVariable(runtimeName); + model.GetTask("搬运"); + } +}''', encoding="utf-8") + hits = client.call("find_references", kind="Variables", id=variable["id"])["hits"] + assert [(h["line"], h["confidence"]) for h in hits] == [(5, "confirmed"), (6, "dynamic")], hits + flow_hit, = client.call("find_references", kind="Workflows", id=workflow["id"])["hits"] + assert flow_hit["line"] == 7 and flow_hit["confidence"] == "confirmed", flow_hit print(f'{summary["Id"]}: {len(summary["recipes"])} recipes, {workflow["name"]}, {variable["name"]}') finally: client.close()