plcsharp/PLCSharpWpf/Models/WorkflowReferences.cs

301 lines
23 KiB
C#

using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using PLCSharp.VVMs.GlobalVariables;
using PLCSharp.VVMs.MotionController;
using PLCSharp.VVMs.Robots;
using PLCSharp.VVMs.Cylinders;
using PLCSharp.VVMs.Connects;
using Microsoft.CodeAnalysis.Operations;
using PLCSharp.VVMs.Workflows;
using PLCSharp.VVMs.Vision;
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, bool forRename = false, NestedName nested = null, string memberName = null, JsonNode candidate = null)
{
var targetType = kind switch { "Variables" => typeof(Variable), "SystemVariables" => typeof(SystemVariable),
"VisionFunctions" => typeof(VisionFunction), "DI" => typeof(DI), "DQ" => typeof(DQ), "Axes" => typeof(Axis), "AxisPoints" => typeof(AxisPoint), "RobotPoints" => typeof(RobotPoint),
"CanvasConfigs" => typeof(PLCSharp.VVMs.Homepage.CanvasConfig), "Controllers" => typeof(Controller), "Cylinders" => typeof(Cylinder), "Robots" => typeof(Robot), "Connects" => typeof(Connect),
"Cameras" => typeof(PLCSharp.VVMs.Vision.Camera.CameraBase), "ImageDatas" => typeof(ImageData), "LocalImageDatas" => typeof(LocalImageData),
"ControlMeasurements" => typeof(PLCSharp.VVMs.Homepage.TableControl.RangeValue), "VisionLocalVariables" => typeof(LocalVariableItem),
"InterpolationSegments" => typeof(Interpolation), "InterpolationPoints" => typeof(InterpolationPoint),
"Recipes" => typeof(PLCSharp.VVMs.Recipe.Recipe), "CustomControls" => typeof(PLCSharp.VVMs.Homepage.CustomControl),
"Matrices" => typeof(Matrix), "RobotMatrices" => typeof(RobotMatrix), "InterpolationGroups" => typeof(InterpolationGroup),
"Workflows" => typeof(Workflow), _ => throw new ArgumentException("Unsupported reference target.") };
var target = candidate ?? ProjectInspection.Query(project, "get", new() { ["kind"] = nested?.Table ?? kind, ["id"] = id });
bool projectWide = kind is "Controllers" or "Axes" or "DI" or "DQ" or "Cylinders" or "Robots" or "Connects" or "Cameras" or "Recipes";
var recipeId = projectWide ? Guid.Empty : Guid.Parse((string)target["RecipeID"]);
var name = nested == null ? (string)target["Name"] : memberName;
var uniqueOwner = nested != null && ProjectConfiguration.Capture(project.Data, [nested.Table], false)[nested.Table].AsArray()
.Count(r => Guid.Parse((string)r["RecipeID"]) == recipeId && (string)r["Name"] == nested.OwnerName) == 1;
var robotId = kind is "RobotPoints" or "RobotMatrices" ? Guid.Parse((string)target["RobotID"]) : Guid.Empty;
var robots = kind is "RobotPoints" or "RobotMatrices" ? project.Data.Robots.Select(r => new { r.ID, r.Name }).ToList() : [];
var ownerId = kind == "LocalImageDatas" ? Guid.Parse((string)target["FuncID"]) : Guid.Empty;
var owners = kind == "LocalImageDatas" ? project.Data.VisionFunctions.Where(f => f.RecipeID == recipeId)
.Select(f => new { f.ID, f.Name }).ToList() : [];
var hits = new List<object>();
var diagnostics = new List<object>();
foreach (var recipe in project.Recipes.Where(r => projectWide || r.ID == recipeId))
foreach (var workflow in project.Flows(recipe.ID))
{
var tree = CSharpSyntaxTree.ParseText(workflow.Code ?? "");
var root = tree.GetRoot();
var model = CSharpCompilation.Create("Inspect", [tree], References.Value).GetSemanticModel(tree);
var path = $"recipes/{recipe.ID: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 && (string.IsNullOrEmpty(name) || !Equals(constant.Value, name))) return;
var position = location.GetLocation().GetLineSpan().StartLinePosition;
hits.Add(new { recipeId = recipe.ID, workflowId = workflow.ID, workflow.Name, path, line = position.Line + 1,
column = position.Character + 1, start = value.SpanStart, length = value.Span.Length, expression = location.ToString(),
confidence = !constant.HasValue ? "dynamic" : bound ? "confirmed" : "possible" });
}
if (candidate != null)
{
// Indexing, iteration and predicates on a collection may select an object at runtime.
var collectionName = kind == "RobotPoints" ? "Points" : kind;
foreach (var access in root.DescendantNodes().OfType<MemberAccessExpressionSyntax>())
{
if (model.GetSymbolInfo(access).Symbol is not IPropertySymbol property) continue;
bool singleton = kind == "Controllers" && property.Name == nameof(ControllersModel.Controller) &&
property.ContainingType.ToDisplayString() == typeof(ControllersModel).FullName;
singleton |= kind == "CanvasConfigs" && property.Name == nameof(GlobalModel.CurrentCanvasConfig) &&
property.ContainingType.ToDisplayString() == typeof(GlobalModel).FullName;
bool collection = property.Name == collectionName && property.Type is INamedTypeSymbol list &&
list.TypeArguments.Length == 1 && list.TypeArguments[0].ToDisplayString() == targetType.FullName;
if (!singleton && !collection) continue;
var invocation = access.Parent?.Parent as InvocationExpressionSyntax;
if (collection && invocation?.ArgumentList.Arguments.Count == 1 &&
invocation.ArgumentList.Arguments[0].Expression is SimpleLambdaExpressionSyntax lambda &&
lambda.Body is BinaryExpressionSyntax eq && eq.IsKind(SyntaxKind.EqualsExpression) &&
new[] { eq.Left, eq.Right }.Any(e => model.GetSymbolInfo(e).Symbol is IPropertySymbol { Name: "Name" } n &&
n.ContainingType.ToDisplayString() == targetType.FullName)) continue;
var position = access.GetLocation().GetLineSpan().StartLinePosition;
hits.Add(new { recipeId = recipe.ID, workflowId = workflow.ID, workflow.Name, path, line = position.Line + 1,
column = position.Character + 1, expression = (invocation as SyntaxNode ?? access.Parent ?? access).ToString(),
confidence = singleton ? "confirmed" : "dynamic" });
}
}
// Return null when the receiver cannot be tied to a configured robot.
bool? IsTargetRobot(ExpressionSyntax receiver)
{
if (receiver is not InvocationExpressionSyntax get ||
model.GetSymbolInfo(get).Symbol is not IMethodSymbol { Name: "GetRobot" } method ||
method.ContainingType.ToDisplayString() != typeof(GlobalModel).FullName ||
get.ArgumentList.Arguments.Count != 1 ||
model.GetConstantValue(get.ArgumentList.Arguments[0].Expression) is not { HasValue: true, Value: string robotName }) return null;
var matches = robots.Where(r => r.Name == robotName).ToArray();
return matches.Length == 1 ? matches[0].ID == robotId : null;
}
bool? LocalOwner(ExpressionSyntax receiver)
{
if (receiver is not InvocationExpressionSyntax get ||
model.GetSymbolInfo(get).Symbol is not IMethodSymbol { Name: nameof(GlobalModel.GetVisionFunction) } method ||
method.ContainingType.ToDisplayString() != typeof(GlobalModel).FullName ||
get.ArgumentList.Arguments.Count != 1 ||
model.GetConstantValue(get.ArgumentList.Arguments[0].Expression) is not { HasValue: true, Value: string ownerName }) return null;
var matches = owners.Where(f => f.Name == ownerName).ToArray();
return matches.Length == 1 ? matches[0].ID == ownerId : null;
}
bool? MemberOwner(ExpressionSyntax receiver)
{
bool? NamedLookup(ExpressionSyntax expression, string expectedMethod)
{
if (expression is not InvocationExpressionSyntax get || get.ArgumentList.Arguments.Count != 1 ||
model.GetSymbolInfo(get).Symbol is not IMethodSymbol method || method.Name != expectedMethod ||
method.ContainingType.ToDisplayString() != typeof(GlobalModel).FullName ||
model.GetConstantValue(get.ArgumentList.Arguments[0].Expression) is not { HasValue: true, Value: string label }) return null;
return label != nested.OwnerName ? false : uniqueOwner ? true : null;
}
if (kind == "ControlMeasurements") return NamedLookup(receiver, nameof(GlobalModel.GetCustomControl));
if (kind == "VisionLocalVariables" && receiver is MemberAccessExpressionSyntax parameters &&
model.GetSymbolInfo(parameters).Symbol is IPropertySymbol { Name: "Params" } p &&
p.ContainingType.ToDisplayString() == typeof(VisionFunction).FullName)
return NamedLookup(parameters.Expression, nameof(GlobalModel.GetVisionFunction));
return MatchInterpolationOwner(receiver, model, nested, uniqueOwner);
}
var lookup = kind switch { "ImageDatas" => nameof(GlobalModel.GetImageData), "Variables" => "GetVariable", "Workflows" => "GetTask",
"Robots" => nameof(GlobalModel.GetRobot), "Connects" => nameof(GlobalModel.GetConnect),
"VisionFunctions" => nameof(GlobalModel.GetVisionFunction), _ => 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 (kind == "ControlMeasurements" && methodName == "SetMeasurementValue" &&
model.GetOperation(call) is IInvocationOperation measure &&
measure.TargetMethod.ContainingType.ToDisplayString() == typeof(PLCSharp.VVMs.Homepage.CustomControl).FullName &&
measure.Arguments.FirstOrDefault(a => a.Parameter?.Name == "name")?.Syntax is ArgumentSyntax item)
{
var owner = MemberOwner((call.Expression as MemberAccessExpressionSyntax)?.Expression);
if (owner != false) Record(item.Expression, call, owner == true);
continue;
}
if (kind == "Connects" && methodName is nameof(ConnectsModel.ApplyAllDataToServer) or nameof(ConnectsModel.ApplyDataItemToServer))
{
if (model.GetOperation(call) is IInvocationOperation operation &&
operation.TargetMethod.ContainingType.ToDisplayString() == typeof(ConnectsModel).FullName &&
operation.Arguments.FirstOrDefault(a => a.Parameter?.Name == "connectName")?.Syntax is ArgumentSyntax argument)
Record(argument.Expression, call, true);
continue;
}
if (kind == "RobotPoints" && methodName is "RunPoint" or "Jog")
{
if (model.GetOperation(call) is IInvocationOperation invocation)
{
var method = invocation.TargetMethod;
while (method.OverriddenMethod != null) method = method.OverriddenMethod;
if (method.ContainingType.ToDisplayString() != typeof(Robot).FullName) continue;
var argument = invocation.Arguments.FirstOrDefault(a => a.Parameter?.Name == "pointName");
var owner = IsTargetRobot((call.Expression as MemberAccessExpressionSyntax)?.Expression);
if (owner != false && argument?.Syntax is ArgumentSyntax syntax)
Record(syntax.Expression, call, owner == true);
}
else if (call.ArgumentList.Arguments.FirstOrDefault() is { } unresolved)
Record(unresolved.Expression, call, false);
continue;
}
if ((methodName != lookup && !(kind == "CustomControls" && methodName is "GetImageControl" or "GetCustomControl")) || 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)
{
bool? bound = kind == "Recipes" && member is MemberAccessExpressionSyntax access &&
model.GetSymbolInfo(access.Expression).Symbol is IPropertySymbol { Name: nameof(GlobalModel.CurrentRecipe) } current &&
current.ContainingType.ToDisplayString() == typeof(GlobalModel).FullName ? true : IsRecipePredicate(member, model, kind, nested != null ? MemberOwner : kind == "LocalImageDatas" ? LocalOwner : IsTargetRobot);
if (bound != false || nested == null && kind is not ("RobotPoints" or "RobotMatrices" or "LocalImageDatas"))
Record(value, comparison, bound == true || (nested == null && !forRename && !projectWide && kind is not ("AxisPoints" or "RobotPoints" or "VisionFunctions" or "ImageDatas" or "LocalImageDatas" or "RobotMatrices" or "Matrices" or "InterpolationGroups" or "CustomControls" or "SystemVariables")));
}
}
}
}
return JsonSerializer.SerializeToNode(new { recipeId, targetId = id, name, hits, diagnostics });
}
private static bool? MatchInterpolationOwner(ExpressionSyntax receiver, SemanticModel model, NestedName nested, bool uniqueOwner)
{
// Only a bound LINQ lookup with one direct name equality proves the owner.
bool TryLookup(ExpressionSyntax expr, Type itemType, string collection, out ExpressionSyntax parent, out string name)
{
parent = null;
name = null;
if (expr is not InvocationExpressionSyntax call ||
model.GetSymbolInfo(call).Symbol is not IMethodSymbol { Name: "First" or "FirstOrDefault" or "Single" or "SingleOrDefault" } m ||
m.ReducedFrom?.ContainingType.ToDisplayString() != "System.Linq.Enumerable" ||
call.Expression is not MemberAccessExpressionSyntax { Expression: MemberAccessExpressionSyntax source } ||
model.GetSymbolInfo(source).Symbol is not IPropertySymbol prop || prop.Name != collection ||
call.ArgumentList.Arguments.Count != 1 || call.ArgumentList.Arguments[0].Expression is not SimpleLambdaExpressionSyntax lambda ||
lambda.Body is not BinaryExpressionSyntax eq || !eq.IsKind(SyntaxKind.EqualsExpression)) return false;
foreach (var (field, value) in new[] { (eq.Left, eq.Right), (eq.Right, eq.Left) })
if (field is MemberAccessExpressionSyntax access && model.GetSymbolInfo(field).Symbol is IPropertySymbol { Name: "Name" } n &&
n.ContainingType.ToDisplayString() == itemType.FullName &&
SymbolEqualityComparer.Default.Equals(model.GetSymbolInfo(access.Expression).Symbol, model.GetDeclaredSymbol(lambda.Parameter)) &&
model.GetConstantValue(value) is { HasValue: true, Value: string label })
{
parent = source.Expression;
name = label;
return true;
}
return false;
}
if (nested.Kind == "InterpolationPoints")
{
if (!TryLookup(receiver, typeof(Interpolation), nameof(InterpolationGroup.Interpolations), out receiver, out var segment)) return null;
if (segment != nested.SegmentName) return false;
}
if (!TryLookup(receiver, typeof(InterpolationGroup), nameof(ControllersModel.InterpolationGroups), out var controller, out var group) ||
model.GetTypeInfo(controller).Type?.ToDisplayString() != typeof(ControllersModel).FullName) return null;
return group != nested.OwnerName ? false : uniqueOwner ? true : null;
}
private static bool? IsRecipePredicate(ExpressionSyntax expression, SemanticModel model, string kind, Func<ExpressionSyntax, bool?> robotOwner)
{
if (expression is not MemberAccessExpressionSyntax access ||
model.GetSymbolInfo(access.Expression).Symbol is not IParameterSymbol parameter ||
access.FirstAncestorOrSelf<LambdaExpressionSyntax>() 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 null;
if (model.GetSymbolInfo(method.Expression).Symbol is not IPropertySymbol source) return null;
return kind switch
{
"VisionLocalVariables" or "ControlMeasurements" or "InterpolationSegments" or "InterpolationPoints"
when method.Expression is MemberAccessExpressionSyntax collection &&
(source.Name, source.ContainingType.ToDisplayString()) switch
{
("Variables", "PLCSharp.VVMs.Vision.VisionParams") => true,
("RangeValues", "PLCSharp.VVMs.Homepage.CustomControl") => true,
("Interpolations", "PLCSharp.VVMs.MotionController.InterpolationGroup") => true,
("InterpolationPoints", "PLCSharp.VVMs.MotionController.Interpolation") => true,
_ => false
} => robotOwner(collection.Expression),
"VisionLocalVariables" or "ControlMeasurements" or "InterpolationSegments" or "InterpolationPoints" => null,
"Cameras" or "ImageDatas" when source.Name == kind && source.ContainingType.ToDisplayString() == typeof(VisionsModel).FullName => true,
"ImageDatas" when source.Name == kind && source.ContainingType.ToDisplayString() == typeof(VisionFunction).FullName => true,
"LocalImageDatas" when source.Name == kind && source.ContainingType.ToDisplayString() == typeof(VisionFunction).FullName &&
method.Expression is MemberAccessExpressionSyntax collection => robotOwner(collection.Expression),
"LocalImageDatas" => null,
"Recipes" or "CustomControls" => source.Name == kind && source.ContainingType.ToDisplayString() == typeof(GlobalModel).FullName,
"Matrices" or "InterpolationGroups" => source.Name == kind && source.ContainingType.ToDisplayString() == typeof(ControllersModel).FullName,
"SystemVariables" => source.Name == kind && source.ContainingType.ToDisplayString() == typeof(VariablesModel).FullName,
"RobotMatrices" when source.Name == kind && source.ContainingType.ToDisplayString() == typeof(Robot).FullName &&
method.Expression is MemberAccessExpressionSyntax matrices => robotOwner(matrices.Expression),
"RobotMatrices" => null,
"Cylinders" => source.Name == kind && source.ContainingType.ToDisplayString() == typeof(CylinderModel).FullName,
"Robots" => source.Name == kind && source.ContainingType.ToDisplayString() == typeof(RobotModel).FullName,
"Connects" => source.Name == kind && source.ContainingType.ToDisplayString() == typeof(ConnectsModel).FullName,
"VisionFunctions" => source.Name == nameof(VisionsModel.VisionFunctions) &&
source.ContainingType.ToDisplayString() == typeof(VisionsModel).FullName,
"DI" or "DQ" or "Axes" => source.Name == kind &&
(source.ContainingType.ToDisplayString() == typeof(ControllersModel).FullName ||
source.ContainingType.ToDisplayString() == typeof(Controller).FullName &&
method.Expression is MemberAccessExpressionSyntax axes &&
model.GetSymbolInfo(axes.Expression).Symbol is IPropertySymbol controller &&
controller.Name == nameof(ControllersModel.Controller) &&
controller.ContainingType.ToDisplayString() == typeof(ControllersModel).FullName),
"AxisPoints" => source.Name == nameof(ControllersModel.AxisPoints) &&
source.ContainingType.ToDisplayString() == typeof(ControllersModel).FullName,
"RobotPoints" when source.Name == nameof(Robot.Points) && source.ContainingType.ToDisplayString() == typeof(Robot).FullName &&
method.Expression is MemberAccessExpressionSyntax points => robotOwner(points.Expression),
"RobotPoints" => null,
"Workflows" => source.Name == nameof(WorkflowsModel.Workflows) &&
source.ContainingType.ToDisplayString() == typeof(WorkflowsModel).FullName,
"Variables" => source.Name == nameof(VariablesModel.Variables) &&
source.ContainingType.ToDisplayString() == typeof(VariablesModel).FullName,
_ => false
};
}
}