151 lines
9.9 KiB
C#
151 lines
9.9 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 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)
|
|
{
|
|
var targetType = kind switch { "Variables" => typeof(Variable), "SystemVariables" => typeof(SystemVariable),
|
|
"VisionFunctions" => typeof(VisionFunction), "Axes" => typeof(Axis), "AxisPoints" => typeof(AxisPoint), "RobotPoints" => typeof(RobotPoint),
|
|
"Workflows" => typeof(Workflow), _ => throw new ArgumentException("Unsupported reference target.") };
|
|
var target = ProjectInspection.Query(project, "get", new() { ["kind"] = kind, ["id"] = id });
|
|
var recipeId = kind == "Axes" ? 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 hits = new List<object>();
|
|
var diagnostics = new List<object>();
|
|
foreach (var recipe in project.Recipes.Where(r => kind == "Axes" || 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 && !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;
|
|
}
|
|
|
|
var lookup = kind switch { "Variables" => "GetVariable", "Workflows" => "GetTask",
|
|
"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 == "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<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 = IsRecipePredicate(member, model, kind, IsTargetRobot);
|
|
if (bound != false || kind != "RobotPoints")
|
|
Record(value, comparison, bound == true || (!forRename && kind is not ("Axes" or "AxisPoints" or "RobotPoints" or "VisionFunctions")));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
return JsonSerializer.SerializeToNode(new { recipeId, targetId = id, name, hits, diagnostics });
|
|
}
|
|
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
|
|
{
|
|
"VisionFunctions" => source.Name == nameof(VisionsModel.VisionFunctions) &&
|
|
source.ContainingType.ToDisplayString() == typeof(VisionsModel).FullName,
|
|
"Axes" => source.Name == nameof(ControllersModel.Axes) &&
|
|
(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
|
|
};
|
|
}
|
|
|
|
}
|