Preview workflow diffs and compile C# without loading user code
This commit is contained in:
parent
444953d81a
commit
addac5ba77
77
PLCSharpWpf/Models/WorkflowScriptReview.cs
Normal file
77
PLCSharpWpf/Models/WorkflowScriptReview.cs
Normal file
@ -0,0 +1,77 @@
|
||||
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<ScriptDiagnostic> Diagnostics)
|
||||
{
|
||||
private static readonly Lazy<MetadataReference[]> 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);
|
||||
var types = tree.GetRoot().DescendantNodes().OfType<TypeDeclarationSyntax>()
|
||||
.Where(t => t.Identifier.ValueText == expected).Select(t => model.GetDeclaredSymbol(t))
|
||||
.Distinct<INamedTypeSymbol>(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<IMethodSymbol>())
|
||||
{
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
@ -18,6 +18,7 @@
|
||||
<!--<PackageReference Include="CommunityToolkit.Mvvm" Version="8.4.2" />-->
|
||||
<PackageReference Include="DotNetCore.Natasha.CSharp.Compiler" Version="10.1.2.2" />
|
||||
<PackageReference Include="DotNetCore.Natasha.CSharp.Compiler.Domain" Version="10.0.0.1" />
|
||||
<PackageReference Include="DiffPlex" Version="1.7.2" />
|
||||
<PackageReference Include="Libdmtx.Net" Version="0.7.9-dev.2" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="9.0.17" />
|
||||
<PackageReference Include="MiniExcel" Version="1.45.0" />
|
||||
@ -96,4 +97,4 @@
|
||||
<SubType>Code</SubType>
|
||||
</Compile>
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
</Project>
|
||||
|
||||
23
Tests/PLCSharp.Tests/WorkflowScriptReviewTests.cs
Normal file
23
Tests/PLCSharp.Tests/WorkflowScriptReviewTests.cs
Normal file
@ -0,0 +1,23 @@
|
||||
using PLCSharp.Models;
|
||||
|
||||
namespace PLCSharp.Tests;
|
||||
|
||||
public class WorkflowScriptReviewTests
|
||||
{
|
||||
[Fact]
|
||||
public void PreviewEmitsCodeWithoutExecutingItsConstructorAndReportsSourceErrors()
|
||||
{
|
||||
var id = Guid.NewGuid();
|
||||
var code = $"using PLCSharp.Models; using PLCSharp.Core.Common;\npublic class Extension_{id:N} {{\n" +
|
||||
"public " + $"Extension_{id:N}() => throw new System.Exception();\npublic void Run(GlobalModel m, FlowModel f) {{ }}\n}}";
|
||||
var valid = WorkflowScriptReview.Create(id, "// before", code);
|
||||
Assert.True(valid.Compiled, string.Join("\n", valid.Diagnostics));
|
||||
Assert.Contains("- // before", valid.Diff);
|
||||
Assert.Contains("+ public class", valid.Diff);
|
||||
var invalid = WorkflowScriptReview.Create(id, code, code.Replace("{ }", "{ missing(); }"));
|
||||
Assert.Contains(invalid.Diagnostics, d => d.Code == "CS0103" && d.Line == 4);
|
||||
Assert.False(invalid.Compiled);
|
||||
Assert.Contains(WorkflowScriptReview.Create(id, code, code.Replace("void Run", "async void Run")).Diagnostics, d => d.Code == "PLC001");
|
||||
}
|
||||
}
|
||||
|
||||
Loading…
Reference in New Issue
Block a user