plcsharp/PLCSharpWpf/Models/WorkflowReferences.cs

75 lines
4.5 KiB
C#

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 });
}
}