using DiffPlex.DiffBuilder; using DiffPlex.DiffBuilder.Model; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using PLCSharp.Core.Common; using System.IO; using System.Text; namespace PLCSharp.Models; public sealed record ScriptDiagnostic(string Severity, string Code, int? Line, int? Column, string Message); public sealed record WorkflowScriptReview(string Diff, bool Compiled, List Diagnostics) { private static readonly Lazy References = new(() => ((string)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES")).Split(Path.PathSeparator) .Append(typeof(GlobalModel).Assembly.Location).Distinct(StringComparer.OrdinalIgnoreCase) .Select(path => MetadataReference.CreateFromFile(path)).ToArray()); internal static WorkflowScriptReview Create(Guid id, string before, string after) { if (after == null || after.Length > 128 * 1024) throw new ArgumentException("脚本长度上限为 128 Ki 个字符。"); var diff = new StringBuilder(); foreach (var line in InlineDiffBuilder.Diff(before ?? "", after, ignoreWhiteSpace: false).Lines) { string prefix = line.Type switch { ChangeType.Inserted => "+ ", ChangeType.Deleted => "- ", _ => " " }; diff.Append(prefix).AppendLine(line.Text); } if (before != after && (before ?? "").ReplaceLineEndings() == after.ReplaceLineEndings()) diff.AppendLine("(换行符发生变化)"); var tree = CSharpSyntaxTree.ParseText(after, path: id.ToString("D") + ".cs"); var compilation = CSharpCompilation.Create("PLCSharpWorkflowPreview", [tree], References.Value, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); using var output = new MemoryStream(); var result = compilation.Emit(output); var diagnostics = result.Diagnostics.Where(d => d.Severity is DiagnosticSeverity.Warning or DiagnosticSeverity.Error) .Select(d => { var position = d.Location.GetLineSpan().StartLinePosition; return new ScriptDiagnostic(d.Severity.ToString(), d.Id, d.Location.IsInSource ? position.Line + 1 : null, d.Location.IsInSource ? position.Character + 1 : null, d.GetMessage()); }).ToList(); if (result.Success) { string expected = $"Extension_{id:N}"; var model = compilation.GetSemanticModel(tree); foreach (var assignment in tree.GetRoot().DescendantNodes().OfType()) { if (model.GetSymbolInfo(assignment.Left).Symbol is not IPropertySymbol { Name: "Name" } property || !AiNamePolicy.IsProtectedType(property.ContainingType)) continue; var position = assignment.Left.GetLocation().GetLineSpan().StartLinePosition; diagnostics.Add(new("Error", "PLC002", position.Line + 1, position.Character + 1, "流程可以读取硬件、配方和点位名称,不能给这些名称赋值。")); } var types = tree.GetRoot().DescendantNodes().OfType() .Where(t => t.Identifier.ValueText == expected).Select(t => model.GetDeclaredSymbol(t)) .Distinct(SymbolEqualityComparer.Default).ToArray(); bool constructible = types.Length == 1 && types[0].Arity == 0 && !types[0].IsAbstract && types[0].InstanceConstructors.Any(c => c.Parameters.Length == 0 && c.DeclaredAccessibility == Microsoft.CodeAnalysis.Accessibility.Public); if (!constructible || !HasEntry(types[0], compilation)) diagnostics.Add(new("Error", "PLC001", null, null, $"需要可无参实例化的 {expected} 类型和同步入口 public void Run(GlobalModel, FlowModel)。")); } return new(diff.ToString(), diagnostics.All(d => d.Severity != "Error"), diagnostics); } private static bool HasEntry(INamedTypeSymbol type, CSharpCompilation compilation) { var app = compilation.SourceModule.ReferencedAssemblySymbols.Single(a => a.Identity.Name == typeof(GlobalModel).Assembly.GetName().Name); var global = app.GetTypeByMetadataName(typeof(GlobalModel).FullName); var flow = app.GetTypeByMetadataName(typeof(FlowModel).FullName); for (; type != null; type = type.BaseType) foreach (var method in type.GetMembers("Run").OfType()) { if (method.DeclaredAccessibility != Microsoft.CodeAnalysis.Accessibility.Public || method.IsStatic || method.Arity != 0 || method.Parameters.Length != 2 || method.Parameters.Any(p => p.RefKind != RefKind.None)) continue; if (SymbolEqualityComparer.Default.Equals(method.Parameters[0].Type, global) && SymbolEqualityComparer.Default.Equals(method.Parameters[1].Type, flow)) return method.ReturnsVoid && !method.IsAsync && !method.IsAbstract; } return false; } }