using System.Collections.Concurrent; using System.Reflection; using System.Runtime.Loader; using System.Text; using System.Text.Json.Nodes; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Text; using XFEWorkflow.Abstractions; namespace XFEWorkflow.Infrastructure.Compilation; public sealed class WorkflowCompilationException(IReadOnlyList diagnostics) : Exception(string.Join(Environment.NewLine, diagnostics.Select(x => $"{x.File}({x.Line},{x.Column}): {x.Message}"))) { public IReadOnlyList Diagnostics { get; } = diagnostics; } public sealed record CodeCompletion(string Label, string InsertText); public sealed class CodeCompiler : ICodeWorkflowExecutor, IDisposable { private readonly ConcurrentDictionary compiled = []; private readonly List contexts = []; private readonly Lazy> references; private static readonly CSharpParseOptions ParseOptions = new(LanguageVersion.CSharp14); public string CapabilityBindingsSource { get; set; } = ""; public CodeCompiler(string? referenceDirectory = null) => references = new(() => CreateReferences(referenceDirectory)); public static string WrapNode(string source, string fileName = "node.cs") => "using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Text.Json.Nodes; using XFEWorkflow.Abstractions;\n" + "public sealed class __XfeCodeNode : IWorkflow {\npublic async ValueTask ExecuteAsync(IWorkflowContext context, CancellationToken cancellationToken) {\n" + "#line 1 \"" + fileName.Replace("\\", "/").Replace("\"", "") + "\"\n" + source + "\n}\n}\n"; private List CreateReferences(string? directory) { directory ??= Path.Combine(AppContext.BaseDirectory, "CompilerReferences"); if (!Directory.Exists(directory) || !File.Exists(Path.Combine(directory, "System.Runtime.dll"))) throw new DirectoryNotFoundException("缺少随程序分发的 .NET 10 引用程序集:" + directory); var files = Directory.EnumerateFiles(directory, "*.dll").Concat([typeof(IWorkflow).Assembly.Location]); var extension = Path.Combine(AppContext.BaseDirectory, "XFEExtension.NetCore.dll"); if (File.Exists(extension)) files = files.Append(extension); return files.Distinct(StringComparer.OrdinalIgnoreCase).Select(x => MetadataReference.CreateFromFile(x)).Cast().ToList(); } private CSharpCompilation CreateCompilation(string source, bool body, string file) => CSharpCompilation.Create("XFEWorkflowCode_" + Guid.NewGuid().ToString("N"), new[] { CSharpSyntaxTree.ParseText(SourceText.From(body ? WrapNode(source, file) : source, Encoding.UTF8), ParseOptions, file) } .Concat(CapabilityBindingsSource.Length == 0 ? [] : new[] { CSharpSyntaxTree.ParseText(SourceText.From(CapabilityBindingsSource, Encoding.UTF8), ParseOptions, "PluginMethods.g.cs") }), references.Value, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, optimizationLevel: OptimizationLevel.Release, nullableContextOptions: NullableContextOptions.Enable)); public Task> AnalyzeAsync(string source, bool body, string file, CancellationToken ct = default) => Task.Run(() => CreateCompilation(source, body, file).GetDiagnostics(ct).Where(x => x.Severity is DiagnosticSeverity.Error or DiagnosticSeverity.Warning).Select(ConvertDiagnostic).ToList(), ct); private static WorkflowDiagnostic ConvertDiagnostic(Diagnostic diagnostic) { var span = diagnostic.Location.GetMappedLineSpan(); return new(diagnostic.GetMessage(), File: span.Path, Line: span.StartLinePosition.Line + 1, Column: span.StartLinePosition.Character + 1, IsError: diagnostic.Severity == DiagnosticSeverity.Error); } public async ValueTask ExecuteAsync(string source, bool isNodeBody, string fileName, IWorkflowContext context, CancellationToken ct) { ct.ThrowIfCancellationRequested(); var key = (isNodeBody ? "body:" : "workflow:") + fileName + ":" + source + CapabilityBindingsSource; if (!compiled.TryGetValue(key, out var type)) { var compilation = CreateCompilation(source, isNodeBody, fileName); using var dll = new MemoryStream(); using var pdb = new MemoryStream(); var result = compilation.Emit(dll, pdb, options: new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb), cancellationToken: ct); if (!result.Success) throw new WorkflowCompilationException(result.Diagnostics.Where(x => x.Severity == DiagnosticSeverity.Error).Select(ConvertDiagnostic).ToList()); dll.Position = 0; pdb.Position = 0; var loadContext = new AssemblyLoadContext(compilation.AssemblyName, true); loadContext.Resolving += (_, name) => AssemblyLoadContext.Default.Assemblies.FirstOrDefault(a => a.GetName().Name == name.Name); var assembly = loadContext.LoadFromStream(dll, pdb); var entries = assembly.GetTypes().Where(x => !x.IsAbstract && typeof(IWorkflow).IsAssignableFrom(x) && x.GetConstructor(Type.EmptyTypes) is not null).ToList(); if (entries.Count != 1) { loadContext.Unload(); throw new InvalidOperationException("代码必须包含一个具有无参数构造函数的 IWorkflow 实现"); } lock (contexts) contexts.Add(loadContext); type = entries[0]; compiled[key] = type; } var workflow = (IWorkflow)Activator.CreateInstance(type)!; try { return await workflow.ExecuteAsync(context, ct); } finally { if (workflow is IAsyncDisposable asyncDisposable) await asyncDisposable.DisposeAsync(); else if (workflow is IDisposable disposable) disposable.Dispose(); } } public async Task> CompleteAsync(string source, bool body, int position, CancellationToken ct = default) { using var workspace = new AdhocWorkspace(); var text = body ? WrapNode(source) : source; var prefixLength = body ? WrapNode("").IndexOf("#line", StringComparison.Ordinal) : 0; if (body) position += WrapNode("").IndexOf('\n', prefixLength) + 1; var project = workspace.AddProject(ProjectInfo.Create(ProjectId.CreateNewId(), VersionStamp.Create(), "Workflow", "Workflow", LanguageNames.CSharp, parseOptions: ParseOptions, compilationOptions: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary), metadataReferences: references.Value)); if (CapabilityBindingsSource.Length > 0) workspace.AddDocument(project.Id, "PluginMethods.g.cs", SourceText.From(CapabilityBindingsSource)); var document = workspace.AddDocument(project.Id, "workflow.cs", SourceText.From(text)); var service = CompletionService.GetService(document); if (service is null) return []; var list = await service.GetCompletionsAsync(document, Math.Clamp(position, 0, text.Length), cancellationToken: ct); return list?.ItemsList.Take(150).Select(x => new CodeCompletion(x.DisplayText, x.Properties.GetValueOrDefault("InsertionText", x.DisplayText))).ToList() ?? []; } public async Task CompileLibraryAsync(string source, string destination, CancellationToken ct = default) { var compilation = CreateCompilation(source, false, "plugin.g.cs"); using var dll = new MemoryStream(); var result = compilation.Emit(dll, cancellationToken: ct); if (!result.Success) throw new WorkflowCompilationException(result.Diagnostics.Where(x => x.Severity == DiagnosticSeverity.Error).Select(ConvertDiagnostic).ToList()); await File.WriteAllBytesAsync(destination, dll.ToArray(), ct); } public void Dispose() { compiled.Clear(); lock (contexts) { foreach (var context in contexts) context.Unload(); contexts.Clear(); } } }