// SPDX-FileCopyrightText: 2026 Progmasoft // SPDX-License-Identifier: MIT using System; using System.Buffers.Binary; using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.Loader; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; namespace Progmasoft.Tazel.Project; /// /// The compiled project files of a module, in .tazel/scripts/: a file is compiled once and its assembly is /// loaded on later runs, so a run whose project files did not change does not start the compiler. /// /// /// The name of an assembly is the SHA-256 of everything its code depends on: the format of this cache, the build of /// Tazel (the options a file is compiled with are part of it), the .NET runtime, the type of the globals, the path the /// file is shown as, the plugins' assemblies, the imports and the text. Nothing else changes what a file compiles to. /// internal static class ScriptCache { /// The directory of the compiled files, below the state directory of the main module. public const string Directory = "scripts"; // Changes when what is cached or how it is named changes. private const string Format = "tazel-script/1"; /// The name of the compiled form of . public static string Key(string code, string shownPath, Type globals, ScriptEnvironment environment) { using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); void Add(string text) { var bytes = Encoding.UTF8.GetBytes(text); Span length = stackalloc byte[8]; BinaryPrimitives.WriteInt64LittleEndian(length, bytes.Length); hash.AppendData(length); hash.AppendData(bytes); } Add(Format); foreach (var assembly in new[] { typeof(ScriptCache).Assembly, typeof(Dsl.DslException).Assembly, typeof(object).Assembly }) { Add(assembly.ManifestModule.ModuleVersionId.ToString("N")); } Add(Environment.Version.ToString()); Add(globals.AssemblyQualifiedName ?? globals.FullName ?? globals.Name); Add(shownPath); foreach (var assembly in environment.Plugins) { Add(assembly.GetName().FullName); Add(assembly.ManifestModule.ModuleVersionId.ToString("N")); } foreach (var import in environment.Imports) { Add(import); } Add(code); return Convert.ToHexStringLower(hash.GetHashAndReset()); } // A file of the cache directory: a key is the hexadecimal SHA-256 that Key returns, so its name is never a path. private static string FileOf(string directory, string key, string suffix) { if (key.Length != 64 || !key.All(char.IsAsciiHexDigitLower)) { throw new ArgumentException($"'{key}' is not a key of the script cache", nameof(key)); } return Path.Combine(directory, Path.GetFileName(key + suffix)); } /// Whether keeps the compiled file named . public static bool IsKept(string directory, string key) => File.Exists(FileOf(directory, key, ".dll")); /// The compiled file named in , or null. public static byte[]? TryRead(string directory, string key) { try { var file = FileOf(directory, key, ".dll"); return File.Exists(file) && new FileInfo(file).LinkTarget is null ? File.ReadAllBytes(file) : null; } catch (Exception error) when (error is IOException or UnauthorizedAccessException) { return null; } } /// /// Keeps as : written beside it and moved into place, so a reader /// sees the whole file or none. A failure leaves the file uncached; the run goes on. /// public static void TryWrite(string directory, string key, byte[] image) { var partial = FileOf(directory, key, $".{Guid.NewGuid():N}.partial"); try { System.IO.Directory.CreateDirectory(directory); File.WriteAllBytes(partial, image); File.Move(partial, FileOf(directory, key, ".dll"), overwrite: true); } catch (Exception error) when (error is IOException or UnauthorizedAccessException) { try { File.Delete(partial); } catch (Exception again) when (again is IOException or UnauthorizedAccessException) { // Nothing more to do: a leftover .partial file is never read. } } } } /// What a project file is compiled with beyond the DSL: the plugins' assemblies and imports. internal sealed class ScriptEnvironment { private readonly Lazy context; private readonly ConcurrentDictionary loaded = new(StringComparer.Ordinal); private ScriptEnvironment(IReadOnlyList plugins, IReadOnlyList imports) { Plugins = plugins; Imports = imports; context = new Lazy(() => new ScriptLoadContext(plugins)); } /// The DSL alone. public static ScriptEnvironment Default { get; } = new([], []); /// The assemblies of the plugins, which project files may use. public IReadOnlyList Plugins { get; } /// The namespaces of the plugins that project files see without a using. public IReadOnlyList Imports { get; } /// The DSL with the assemblies and imports of plugins. public static ScriptEnvironment With(IEnumerable plugins, IEnumerable imports) => new(plugins.ToList(), imports.ToList()); /// /// The compiled file named , loaded once per environment, so running a file again in the /// same process does not load its assembly twice. /// public LoadedScript Entry(string key, Func image) => loaded.GetOrAdd(key, _ => { var bytes = image(); return new LoadedScript(bytes, context.Value.Entry(bytes)); }); } /// A compiled project file: its assembly and its entry, which takes the submission array. internal sealed record LoadedScript(byte[] Image, Func> Entry); /// Where compiled project files are loaded: the plugins' assemblies resolve to those already loaded. internal sealed class ScriptLoadContext : AssemblyLoadContext { // The class and the method Roslyn compiles the first submission of a script to. private const string SubmissionType = "Submission#0"; private const string FactoryMethod = ""; private readonly IReadOnlyList plugins; public ScriptLoadContext(IReadOnlyList plugins) : base("tazel-project-files") { this.plugins = plugins; } /// /// Loads and returns its entry, which takes the submission array: the globals first, a /// place for the submission itself second. /// public Func> Entry(byte[] image) { if (image.Length == 0) { return _ => Task.FromResult(null!); } using var stream = new MemoryStream(image, writable: false); var assembly = LoadFromStream(stream); var factory = assembly.GetType(SubmissionType, throwOnError: true)! .GetMethod(FactoryMethod, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static) ?? throw new BadImageFormatException($"a compiled project file has no {FactoryMethod}"); return factory.CreateDelegate>>(); } /// protected override Assembly? Load(AssemblyName assemblyName) => plugins.FirstOrDefault(plugin => string.Equals(plugin.GetName().Name, assemblyName.Name, StringComparison.Ordinal)); }