Locate recipe-scoped variable and workflow references with Roslyn
This commit is contained in:
parent
6db8425851
commit
46dc6282fc
@ -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());
|
||||
|
||||
|
||||
@ -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 }) });
|
||||
|
||||
74
PLCSharpWpf/Models/WorkflowReferences.cs
Normal file
74
PLCSharpWpf/Models/WorkflowReferences.cs
Normal file
@ -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<MetadataReference[]> References = new(() =>
|
||||
{
|
||||
var assemblies = ((string)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES")).Split(Path.PathSeparator);
|
||||
var needed = new HashSet<string>(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<object>();
|
||||
var diagnostics = new List<object>();
|
||||
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<InvocationExpressionSyntax>())
|
||||
{
|
||||
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<BinaryExpressionSyntax>().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 });
|
||||
}
|
||||
}
|
||||
@ -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()
|
||||
|
||||
Loading…
Reference in New Issue
Block a user