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 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, bool forRename = false) { 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), "Cylinders" => typeof(Cylinder), "Robots" => typeof(Robot), "Connects" => typeof(Connect), "Cameras" => typeof(PLCSharp.VVMs.Vision.Camera.CameraBase), "ImageDatas" => typeof(ImageData), "LocalImageDatas" => typeof(LocalImageData), "Workflows" => typeof(Workflow), _ => throw new ArgumentException("Unsupported reference target.") }; var target = ProjectInspection.Query(project, "get", new() { ["kind"] = kind, ["id"] = id }); bool projectWide = kind is "Axes" or "DI" or "DQ" or "Cylinders" or "Robots" or "Connects" or "Cameras"; var recipeId = projectWide ? Guid.Empty : Guid.Parse((string)target["RecipeID"]); var name = (string)target["Name"]; var robotId = kind == "RobotPoints" ? Guid.Parse((string)target["RobotID"]) : Guid.Empty; var robots = kind == "RobotPoints" ? 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(); var diagnostics = new List(); 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" }); } // 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; } 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()) { var methodName = call.Expression switch { MemberAccessExpressionSyntax m => m.Name.Identifier.ValueText, MemberBindingExpressionSyntax b => b.Name.Identifier.ValueText, IdentifierNameSyntax n => n.Identifier.ValueText, _ => "" }; 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 || 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) { bool? bound = IsRecipePredicate(member, model, kind, kind == "LocalImageDatas" ? LocalOwner : IsTargetRobot); if (bound != false || kind is not ("RobotPoints" or "LocalImageDatas")) Record(value, comparison, bound == true || (!forRename && !projectWide && kind is not ("AxisPoints" or "RobotPoints" or "VisionFunctions" or "ImageDatas" or "LocalImageDatas"))); } } } } return JsonSerializer.SerializeToNode(new { recipeId, targetId = id, name, hits, diagnostics }); } private static bool? IsRecipePredicate(ExpressionSyntax expression, SemanticModel model, string kind, Func robotOwner) { 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 null; if (model.GetSymbolInfo(method.Expression).Symbol is not IPropertySymbol source) return null; return kind switch { "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, "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 }; } }