| | | 1 | | using System.Collections.Immutable; |
| | | 2 | | using System.Reflection; |
| | | 3 | | using System.Text; |
| | | 4 | | using Kestrun.SharedState; |
| | | 5 | | using Microsoft.CodeAnalysis; |
| | | 6 | | using Microsoft.CodeAnalysis.CSharp; |
| | | 7 | | using Microsoft.CodeAnalysis.CSharp.Scripting; |
| | | 8 | | using Microsoft.CodeAnalysis.Scripting; |
| | | 9 | | using Serilog.Events; |
| | | 10 | | using Kestrun.Logging; |
| | | 11 | | using Kestrun.Hosting; |
| | | 12 | | |
| | | 13 | | namespace Kestrun.Languages; |
| | | 14 | | |
| | | 15 | | |
| | | 16 | | internal static class CSharpDelegateBuilder |
| | | 17 | | { |
| | | 18 | | /// <summary> |
| | | 19 | | /// Builds a C# delegate for handling HTTP requests. |
| | | 20 | | /// </summary> |
| | | 21 | | /// <param name="host">The Kestrun host instance.</param> |
| | | 22 | | /// <param name="code">The C# code to execute.</param> |
| | | 23 | | /// <param name="args">Arguments to inject as variables into the script.</param> |
| | | 24 | | /// <param name="extraImports">Additional namespaces to import.</param> |
| | | 25 | | /// <param name="extraRefs">Additional assemblies to reference.</param> |
| | | 26 | | /// <param name="languageVersion">The C# language version to use.</param> |
| | | 27 | | /// <returns>A delegate that handles HTTP requests.</returns> |
| | | 28 | | /// <exception cref="ArgumentNullException">Thrown if the code is null or whitespace.</exception> |
| | | 29 | | /// <exception cref="CompilationErrorException">Thrown if the C# code compilation fails.</exception> |
| | | 30 | | /// <remarks> |
| | | 31 | | /// This method compiles the provided C# code into a script and returns a delegate that can be used to handle HTTP r |
| | | 32 | | /// It supports additional imports and references, and can inject global variables into the script. |
| | | 33 | | /// The delegate will execute the provided C# code within the context of an HTTP request, allowing access to the req |
| | | 34 | | /// </remarks> |
| | | 35 | | internal static RequestDelegate Build(KestrunHost host, |
| | | 36 | | string code, Dictionary<string, object?>? args, string[]? extraImports, |
| | | 37 | | Assembly[]? extraRefs, LanguageVersion languageVersion = LanguageVersion.CSharp12) |
| | | 38 | | { |
| | 37 | 39 | | if (host.Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 40 | | { |
| | 26 | 41 | | host.Logger.Debug("Building C# delegate, script length={Length}, imports={ImportsCount}, refs={RefsCount}, l |
| | 26 | 42 | | code?.Length, extraImports?.Length ?? 0, extraRefs?.Length ?? 0, languageVersion); |
| | | 43 | | } |
| | | 44 | | |
| | | 45 | | // Validate inputs |
| | 37 | 46 | | if (string.IsNullOrWhiteSpace(code)) |
| | | 47 | | { |
| | 1 | 48 | | throw new ArgumentNullException(nameof(code), "C# code cannot be null or whitespace."); |
| | | 49 | | } |
| | | 50 | | // 1. Compile the C# code into a script |
| | | 51 | | // - Use CSharpScript.Create() to create a script with the provided code |
| | | 52 | | // - Use ScriptOptions to specify imports, references, and language version |
| | | 53 | | // - Inject the provided arguments into the globals |
| | 36 | 54 | | var script = Compile(code, host.Logger, extraImports, extraRefs, null, languageVersion); |
| | | 55 | | |
| | | 56 | | // 2. Return a delegate that executes the script |
| | | 57 | | // - The delegate takes an HttpContext and returns a Task |
| | | 58 | | // - It creates a KestrunContext and KestrunResponse from the HttpContext |
| | | 59 | | // - It executes the script with the provided globals and locals |
| | | 60 | | // - It applies the response to the HttpContext |
| | 36 | 61 | | if (host.Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 62 | | { |
| | 25 | 63 | | host.Logger.Debug("C# delegate built successfully, script length={Length}, imports={ImportsCount}, refs={Ref |
| | 25 | 64 | | code?.Length, extraImports?.Length ?? 0, extraRefs?.Length ?? 0, languageVersion); |
| | | 65 | | } |
| | | 66 | | |
| | 36 | 67 | | return async ctx => |
| | 36 | 68 | | { |
| | 36 | 69 | | try |
| | 36 | 70 | | { |
| | 15 | 71 | | if (host.Logger.IsEnabled(LogEventLevel.Debug)) |
| | 36 | 72 | | { |
| | 3 | 73 | | host.Logger.DebugSanitized("Preparing execution for C# script at {Path}", ctx.Request.Path); |
| | 36 | 74 | | } |
| | 36 | 75 | | |
| | 15 | 76 | | var (Globals, Response, Context) = await DelegateBuilder.PrepareExecutionAsync(host, ctx, args).Configur |
| | 36 | 77 | | |
| | 36 | 78 | | // Execute the script with the current context and shared state |
| | 15 | 79 | | if (host.Logger.IsEnabled(LogEventLevel.Debug)) |
| | 36 | 80 | | { |
| | 3 | 81 | | host.Logger.DebugSanitized("Executing C# script for {Path}", ctx.Request.Path); |
| | 36 | 82 | | } |
| | 36 | 83 | | |
| | 15 | 84 | | _ = await script.RunAsync(Globals).ConfigureAwait(false); |
| | 10 | 85 | | if (host.Logger.IsEnabled(LogEventLevel.Debug)) |
| | 36 | 86 | | { |
| | 3 | 87 | | host.Logger.DebugSanitized("C# script executed successfully for {Path}", ctx.Request.Path); |
| | 36 | 88 | | } |
| | 36 | 89 | | |
| | 36 | 90 | | // Apply the response to the Kestrun context |
| | 10 | 91 | | await DelegateBuilder.ApplyResponseAsync(ctx, Response, host.Logger).ConfigureAwait(false); |
| | 10 | 92 | | } |
| | 36 | 93 | | finally |
| | 36 | 94 | | { |
| | 36 | 95 | | // Intentionally do not call Response.CompleteAsync here to keep the pipeline open |
| | 36 | 96 | | // for middleware like StatusCodePages to generate bodies for status-only responses. |
| | 36 | 97 | | } |
| | 46 | 98 | | }; |
| | | 99 | | } |
| | | 100 | | |
| | | 101 | | /// <summary> |
| | | 102 | | /// Compiles the provided C# code into a script. |
| | | 103 | | /// This method supports additional imports and references, and can inject global variables into the script. |
| | | 104 | | /// It returns a compiled script that can be executed later. |
| | | 105 | | /// </summary> |
| | | 106 | | /// <param name="code">The C# code to compile.</param> |
| | | 107 | | /// <param name="log">The logger instance.</param> |
| | | 108 | | /// <param name="extraImports">Additional namespaces to import.</param> |
| | | 109 | | /// <param name="extraRefs">Additional assembly references.</param> |
| | | 110 | | /// <param name="locals">Local variables to inject into the script.</param> |
| | | 111 | | /// <param name="languageVersion">The C# language version to use.</param> |
| | | 112 | | /// <returns>A compiled script that can be executed later.</returns> |
| | | 113 | | /// <exception cref="ArgumentNullException">Thrown when the code is null or whitespace.</exception> |
| | | 114 | | /// <exception cref="CompilationErrorException">Thrown when there are compilation errors.</exception> |
| | | 115 | | /// <remarks> |
| | | 116 | | /// This method compiles the provided C# code into a script using Roslyn. |
| | | 117 | | /// It supports additional imports and references, and can inject global variables into the script. |
| | | 118 | | /// The script can be executed later with the provided globals and locals. |
| | | 119 | | /// It is useful for scenarios where dynamic C# code execution is required, such as in web applications or scripting |
| | | 120 | | /// </remarks> |
| | | 121 | | internal static Script<object> Compile( |
| | | 122 | | string? code, Serilog.ILogger log, string[]? extraImports, |
| | | 123 | | Assembly[]? extraRefs, IReadOnlyDictionary<string, object?>? locals, LanguageVersion languageVersion = Langu |
| | | 124 | | ) |
| | | 125 | | { |
| | 59 | 126 | | if (log.IsEnabled(LogEventLevel.Debug)) |
| | | 127 | | { |
| | 48 | 128 | | log.Debug("Compiling C# script, length={Length}, imports={ImportsCount}, refs={RefsCount}, lang={Lang}", |
| | 48 | 129 | | code?.Length, extraImports?.Length ?? 0, extraRefs?.Length ?? 0, languageVersion); |
| | | 130 | | } |
| | | 131 | | |
| | | 132 | | // Validate inputs |
| | 59 | 133 | | if (string.IsNullOrWhiteSpace(code)) |
| | | 134 | | { |
| | 0 | 135 | | throw new ArgumentNullException(nameof(code), "C# code cannot be null or whitespace."); |
| | | 136 | | } |
| | | 137 | | |
| | | 138 | | // References and imports |
| | 59 | 139 | | var coreRefs = DelegateBuilder.BuildBaselineReferences(); |
| | | 140 | | // Core references + Kestrun + extras |
| | | 141 | | // Note: Order matters, Kestrun must come after core to avoid conflicts |
| | 59 | 142 | | var kestrunAssembly = typeof(KestrunHost).Assembly; // Kestrun.dll |
| | 59 | 143 | | var kestrunRef = MetadataReference.CreateFromFile(kestrunAssembly.Location); |
| | 59 | 144 | | var kestrunNamespaces = CollectKestrunNamespaces(kestrunAssembly); |
| | | 145 | | // Create script options |
| | 59 | 146 | | var opts = CreateScriptOptions(DelegateBuilder.PlatformImports, kestrunNamespaces, coreRefs, kestrunRef); |
| | 59 | 147 | | opts = AddExtraImports(opts, extraImports); |
| | 59 | 148 | | opts = AddExtraReferences(opts, extraRefs, log); |
| | | 149 | | |
| | | 150 | | // Include currently loaded assemblies (deduplicated) to minimize missing reference issues. |
| | 59 | 151 | | opts = AddLoadedAssemblyReferences(opts, log); |
| | | 152 | | |
| | | 153 | | // Globals/locals injection plus dynamic discovery of namespaces & assemblies needed |
| | 59 | 154 | | var (CodeWithPreamble, DynamicImports, DynamicReferences) = BuildGlobalsAndLocalsPreamble(code, locals, log); |
| | 59 | 155 | | code = CodeWithPreamble; |
| | | 156 | | |
| | 59 | 157 | | if (DynamicImports.Count > 0) |
| | | 158 | | { |
| | 35 | 159 | | var newImports = DynamicImports.Except(opts.Imports, StringComparer.Ordinal).ToArray(); |
| | 35 | 160 | | if (newImports.Length > 0) |
| | | 161 | | { |
| | 0 | 162 | | opts = opts.WithImports(opts.Imports.Concat(newImports)); |
| | 0 | 163 | | if (log.IsEnabled(LogEventLevel.Debug)) |
| | | 164 | | { |
| | 0 | 165 | | log.Debug("Added {ImportCount} dynamic imports derived from globals/locals: {Imports}", newImports.L |
| | | 166 | | } |
| | | 167 | | } |
| | | 168 | | } |
| | | 169 | | |
| | 59 | 170 | | if (DynamicReferences.Count > 0) |
| | | 171 | | { |
| | | 172 | | // Avoid duplicates by location |
| | 35 | 173 | | var existingRefPaths = new HashSet<string>(opts.MetadataReferences |
| | 35 | 174 | | .OfType<PortableExecutableReference>() |
| | 8973 | 175 | | .Select(r => r.FilePath ?? string.Empty) |
| | 9008 | 176 | | .Where(p => !string.IsNullOrEmpty(p)), StringComparer.OrdinalIgnoreCase); |
| | | 177 | | |
| | 35 | 178 | | var newRefs = DynamicReferences |
| | 45 | 179 | | .Where(r => !string.IsNullOrEmpty(r.Location) && File.Exists(r.Location) && !existingRefPaths.Contains(r |
| | 0 | 180 | | .Select(r => MetadataReference.CreateFromFile(r.Location)) |
| | 35 | 181 | | .ToArray(); |
| | | 182 | | |
| | 35 | 183 | | if (newRefs.Length > 0) |
| | | 184 | | { |
| | 0 | 185 | | opts = opts.WithReferences(opts.MetadataReferences.Concat(newRefs)); |
| | 0 | 186 | | if (log.IsEnabled(LogEventLevel.Debug)) |
| | | 187 | | { |
| | 0 | 188 | | log.Debug("Added {RefCount} dynamic assembly reference(s) derived from globals/locals.", newRefs.Len |
| | | 189 | | } |
| | | 190 | | } |
| | | 191 | | } |
| | | 192 | | |
| | | 193 | | // Compile |
| | 59 | 194 | | var script = CSharpScript.Create(code, opts, typeof(CsGlobals)); |
| | 59 | 195 | | var diagnostics = CompileAndGetDiagnostics(script, log); |
| | 59 | 196 | | ThrowIfDiagnosticsNull(diagnostics); |
| | 59 | 197 | | ThrowOnErrors(diagnostics, log); |
| | 58 | 198 | | LogWarnings(diagnostics, log); |
| | 58 | 199 | | LogSuccessIfNoWarnings(diagnostics, log); |
| | | 200 | | |
| | 58 | 201 | | return script; |
| | | 202 | | } |
| | | 203 | | |
| | | 204 | | /// <summary>Collects metadata references for all non-dynamic loaded assemblies with a physical location.</summary> |
| | | 205 | | /// <param name="log">Logger.</param> |
| | | 206 | | /// <returns>Tuple of references and total count considered.</returns> |
| | | 207 | | private static (IEnumerable<MetadataReference> Refs, int Total) CollectLoadedAssemblyReferences(Serilog.ILogger log) |
| | | 208 | | { |
| | | 209 | | try |
| | | 210 | | { |
| | 59 | 211 | | var loaded = AppDomain.CurrentDomain.GetAssemblies(); |
| | 59 | 212 | | var refs = new List<MetadataReference>(loaded.Length); |
| | 59 | 213 | | var considered = 0; |
| | 35512 | 214 | | foreach (var a in loaded) |
| | | 215 | | { |
| | 17697 | 216 | | considered++; |
| | 17697 | 217 | | if (a.IsDynamic) |
| | | 218 | | { |
| | | 219 | | continue; |
| | | 220 | | } |
| | 17548 | 221 | | if (string.IsNullOrEmpty(a.Location) || !File.Exists(a.Location)) |
| | | 222 | | { |
| | | 223 | | continue; |
| | | 224 | | } |
| | | 225 | | try |
| | | 226 | | { |
| | 15218 | 227 | | refs.Add(MetadataReference.CreateFromFile(a.Location)); |
| | 15218 | 228 | | } |
| | 0 | 229 | | catch (Exception ex) |
| | | 230 | | { |
| | 0 | 231 | | if (log.IsEnabled(LogEventLevel.Debug)) |
| | | 232 | | { |
| | 0 | 233 | | log.Debug(ex, "Failed to add loaded assembly reference: {Assembly}", a.FullName); |
| | | 234 | | } |
| | 0 | 235 | | } |
| | | 236 | | } |
| | 59 | 237 | | return (refs, considered); |
| | | 238 | | } |
| | 0 | 239 | | catch (Exception ex) |
| | | 240 | | { |
| | 0 | 241 | | log.Warning(ex, "Failed to enumerate loaded assemblies for dynamic references."); |
| | 0 | 242 | | return (Array.Empty<MetadataReference>(), 0); |
| | | 243 | | } |
| | 59 | 244 | | } |
| | | 245 | | |
| | | 246 | | /// <summary> |
| | | 247 | | /// Builds the core assembly references for the script. |
| | | 248 | | /// </summary> |
| | | 249 | | /// <returns>The core assembly references.</returns> |
| | | 250 | | |
| | | 251 | | /// <summary> |
| | | 252 | | /// Collects the namespaces from the Kestrun assembly. |
| | | 253 | | /// </summary> |
| | | 254 | | /// <param name="kestrunAssembly">The Kestrun assembly.</param> |
| | | 255 | | /// <returns>The collected namespaces.</returns> |
| | | 256 | | private static string[] CollectKestrunNamespaces(Assembly kestrunAssembly) |
| | | 257 | | { |
| | 59 | 258 | | return [.. kestrunAssembly |
| | 59 | 259 | | .GetExportedTypes() |
| | 9204 | 260 | | .Select(t => t.Namespace) |
| | 9204 | 261 | | .Where(ns => !string.IsNullOrEmpty(ns) && ns!.StartsWith("Kestrun", StringComparison.Ordinal)) |
| | 9086 | 262 | | .Select(ns => ns!) |
| | 59 | 263 | | .Distinct()]; |
| | | 264 | | } |
| | | 265 | | |
| | | 266 | | /// <summary> |
| | | 267 | | /// Creates script options for the VB.NET script. |
| | | 268 | | /// </summary> |
| | | 269 | | /// <param name="platformImports">The platform-specific namespaces to import.</param> |
| | | 270 | | /// <param name="kestrunNamespaces">The Kestrun-specific namespaces to import.</param> |
| | | 271 | | /// <param name="coreRefs">The core assembly references to include.</param> |
| | | 272 | | /// <param name="kestrunRef">The Kestrun assembly reference to include.</param> |
| | | 273 | | /// <returns>The created script options.</returns> |
| | | 274 | | private static ScriptOptions CreateScriptOptions( |
| | | 275 | | IEnumerable<string> platformImports, |
| | | 276 | | IEnumerable<string> kestrunNamespaces, |
| | | 277 | | IEnumerable<MetadataReference> coreRefs, |
| | | 278 | | MetadataReference kestrunRef) |
| | | 279 | | { |
| | 59 | 280 | | var allImports = platformImports.Concat(kestrunNamespaces) ?? []; |
| | | 281 | | // Keep default references then add our core + Kestrun to avoid losing essential BCL assemblies |
| | 59 | 282 | | var opts = ScriptOptions.Default |
| | 59 | 283 | | .WithImports(allImports) |
| | 59 | 284 | | .AddReferences(coreRefs) |
| | 59 | 285 | | .AddReferences(kestrunRef); |
| | 59 | 286 | | return opts; |
| | | 287 | | } |
| | | 288 | | |
| | | 289 | | /// <summary> |
| | | 290 | | /// Adds extra using directives to the script options. |
| | | 291 | | /// </summary> |
| | | 292 | | /// <param name="opts">The script options to modify.</param> |
| | | 293 | | /// <param name="extraImports">The extra using directives to add.</param> |
| | | 294 | | /// <returns>The modified script options.</returns> |
| | | 295 | | private static ScriptOptions AddExtraImports(ScriptOptions opts, string[]? extraImports) |
| | | 296 | | { |
| | 59 | 297 | | extraImports ??= ["Kestrun"]; |
| | 59 | 298 | | if (!extraImports.Contains("Kestrun")) |
| | | 299 | | { |
| | 1 | 300 | | var importsList = extraImports.ToList(); |
| | 1 | 301 | | importsList.Add("Kestrun"); |
| | 1 | 302 | | extraImports = [.. importsList]; |
| | | 303 | | } |
| | 59 | 304 | | return extraImports.Length > 0 |
| | 59 | 305 | | ? opts.WithImports(opts.Imports.Concat(extraImports)) |
| | 59 | 306 | | : opts; |
| | | 307 | | } |
| | | 308 | | |
| | | 309 | | /// <summary> |
| | | 310 | | /// Adds extra assembly references to the script options. |
| | | 311 | | /// </summary> |
| | | 312 | | /// <param name="opts">The script options to modify.</param> |
| | | 313 | | /// <param name="extraRefs">The extra assembly references to add.</param> |
| | | 314 | | /// <param name="log">The logger to use for logging.</param> |
| | | 315 | | /// <returns>The modified script options.</returns> |
| | | 316 | | private static ScriptOptions AddExtraReferences(ScriptOptions opts, Assembly[]? extraRefs, Serilog.ILogger log) |
| | | 317 | | { |
| | 59 | 318 | | if (extraRefs is not { Length: > 0 }) |
| | | 319 | | { |
| | 59 | 320 | | return opts; |
| | | 321 | | } |
| | | 322 | | |
| | 0 | 323 | | foreach (var r in extraRefs) |
| | | 324 | | { |
| | 0 | 325 | | if (string.IsNullOrEmpty(r.Location)) |
| | | 326 | | { |
| | 0 | 327 | | log.Warning("Skipping dynamic assembly with no location: {Assembly}", r.FullName); |
| | | 328 | | } |
| | 0 | 329 | | else if (!File.Exists(r.Location)) |
| | | 330 | | { |
| | 0 | 331 | | log.Warning("Skipping missing assembly file: {Location}", r.Location); |
| | | 332 | | } |
| | | 333 | | } |
| | | 334 | | |
| | 0 | 335 | | var safeRefs = extraRefs |
| | 0 | 336 | | .Where(r => !string.IsNullOrEmpty(r.Location) && File.Exists(r.Location)) |
| | 0 | 337 | | .Select(r => MetadataReference.CreateFromFile(r.Location)); |
| | | 338 | | |
| | 0 | 339 | | return opts.WithReferences(opts.MetadataReferences.Concat(safeRefs)); |
| | | 340 | | } |
| | | 341 | | |
| | | 342 | | /// <summary> |
| | | 343 | | /// Adds references for all currently loaded (non-duplicate) assemblies to the script options. |
| | | 344 | | /// </summary> |
| | | 345 | | /// <param name="opts">Current script options.</param> |
| | | 346 | | /// <param name="log">Logger.</param> |
| | | 347 | | /// <returns>Updated script options.</returns> |
| | | 348 | | private static ScriptOptions AddLoadedAssemblyReferences(ScriptOptions opts, Serilog.ILogger log) |
| | | 349 | | { |
| | | 350 | | // Optionally include all currently loaded assemblies to reduce missing reference issues. |
| | | 351 | | // Roslyn will de-duplicate by file path internally but we still filter to avoid redundant work. |
| | 59 | 352 | | var (loadedRefs, loadedCount) = CollectLoadedAssemblyReferences(log); |
| | 59 | 353 | | if (loadedCount <= 0) |
| | | 354 | | { |
| | 0 | 355 | | return opts; |
| | | 356 | | } |
| | | 357 | | |
| | 59 | 358 | | var existingPaths = new HashSet<string>(opts.MetadataReferences |
| | 59 | 359 | | .OfType<PortableExecutableReference>() |
| | 10950 | 360 | | .Select(r => r.FilePath ?? string.Empty) |
| | 11009 | 361 | | .Where(p => !string.IsNullOrEmpty(p)), StringComparer.OrdinalIgnoreCase); |
| | | 362 | | |
| | 59 | 363 | | var newLoadedRefs = loadedRefs |
| | 15218 | 364 | | .Where(r => r is PortableExecutableReference pe && !string.IsNullOrEmpty(pe.FilePath) && !existingPaths.Cont |
| | 59 | 365 | | .ToArray(); |
| | | 366 | | |
| | 59 | 367 | | if (newLoadedRefs.Length == 0) |
| | | 368 | | { |
| | 0 | 369 | | return opts; |
| | | 370 | | } |
| | | 371 | | |
| | 59 | 372 | | var updated = opts.WithReferences(opts.MetadataReferences.Concat(newLoadedRefs)); |
| | 59 | 373 | | if (log.IsEnabled(LogEventLevel.Debug)) |
| | | 374 | | { |
| | 48 | 375 | | log.Debug("Added {RefCount} loaded assembly reference(s) (of {TotalLoaded}) for dynamic script compilation." |
| | | 376 | | } |
| | 59 | 377 | | return updated; |
| | | 378 | | } |
| | | 379 | | |
| | | 380 | | /// <summary> |
| | | 381 | | /// Prepends global and local variable declarations to the provided code. |
| | | 382 | | /// </summary> |
| | | 383 | | /// <param name="code">The original code to modify.</param> |
| | | 384 | | /// <param name="locals">The local variables to include.</param> |
| | | 385 | | /// <returns>The modified code with global and local variable declarations.</returns> |
| | | 386 | | /// <summary>Builds the preamble variable declarations for globals & locals and discovers required namespaces an |
| | | 387 | | /// <param name="log">Logger instance.</param> |
| | | 388 | | /// <returns>Tuple containing code with preamble, dynamic imports, dynamic references.</returns> |
| | | 389 | | private static (string CodeWithPreamble, List<string> DynamicImports, List<Assembly> DynamicReferences) BuildGlobals |
| | | 390 | | string? code, |
| | | 391 | | IReadOnlyDictionary<string, object?>? locals, |
| | | 392 | | Serilog.ILogger log) |
| | | 393 | | { |
| | | 394 | | // Merge globals + locals |
| | 59 | 395 | | var merged = MergeGlobalsAndLocals(locals); |
| | | 396 | | |
| | | 397 | | // Build preamble & discover dynamic imports/refs |
| | 59 | 398 | | var (preamble, imports, refs) = GeneratePreambleAndDiscover(merged); |
| | | 399 | | |
| | | 400 | | // Append original code |
| | 59 | 401 | | var finalCode = preamble.Length > 0 ? preamble + (code ?? string.Empty) : code ?? string.Empty; |
| | | 402 | | |
| | | 403 | | // Filter references to only those with locations |
| | 104 | 404 | | var filteredRefs = refs.Where(r => !string.IsNullOrEmpty(r.Location)).ToList(); |
| | | 405 | | |
| | 59 | 406 | | LogDynamicDiscovery(imports, filteredRefs, log); |
| | | 407 | | |
| | 59 | 408 | | return (finalCode, imports.ToList(), filteredRefs); |
| | | 409 | | } |
| | | 410 | | |
| | | 411 | | /// <summary> |
| | | 412 | | /// Creates a merged dictionary of global shared state and the supplied <paramref name="locals"/>. |
| | | 413 | | /// Local values override globals when a key collision occurs (case-insensitive). |
| | | 414 | | /// </summary> |
| | | 415 | | /// <param name="locals">Optional locals dictionary passed in at compile time.</param> |
| | | 416 | | /// <returns>A mutable dictionary keyed by variable name mapping to its source store name and value.</returns> |
| | | 417 | | private static Dictionary<string, (string Dict, object? Value)> MergeGlobalsAndLocals(IReadOnlyDictionary<string, ob |
| | | 418 | | { |
| | 59 | 419 | | var merged = new Dictionary<string, (string Dict, object? Value)>(StringComparer.OrdinalIgnoreCase); |
| | 59 | 420 | | var allGlobals = SharedStateStore.Snapshot(); |
| | 672 | 421 | | foreach (var g in allGlobals) |
| | | 422 | | { |
| | 277 | 423 | | merged[g.Key] = ("Globals", g.Value); |
| | | 424 | | } |
| | 59 | 425 | | if (locals is { Count: > 0 }) |
| | | 426 | | { |
| | 76 | 427 | | foreach (var l in locals) |
| | | 428 | | { |
| | 20 | 429 | | merged[l.Key] = ("Locals", l.Value); |
| | | 430 | | } |
| | | 431 | | } |
| | 59 | 432 | | return merged; |
| | | 433 | | } |
| | | 434 | | |
| | | 435 | | /// <summary> |
| | | 436 | | /// Iterates all merged global + local variables and builds a textual preamble of variable declarations. |
| | | 437 | | /// While building, collects the required namespace imports and assembly references inferred from the runtime value |
| | | 438 | | /// </summary> |
| | | 439 | | /// <param name="merged">Merged globals + locals produced by <see cref="MergeGlobalsAndLocals"/>.</param> |
| | | 440 | | /// <returns>Tuple containing the preamble text builder, discovered namespace import set, and assembly reference set |
| | | 441 | | private static (StringBuilder Preamble, HashSet<string> Imports, HashSet<Assembly> Refs) GeneratePreambleAndDiscover |
| | | 442 | | Dictionary<string, (string Dict, object? Value)> merged) |
| | | 443 | | { |
| | 59 | 444 | | var preambleBuilder = new StringBuilder(); |
| | 59 | 445 | | var dynamicImports = new HashSet<string>(StringComparer.Ordinal); |
| | 59 | 446 | | var dynamicRefs = new HashSet<Assembly>(); |
| | | 447 | | |
| | 708 | 448 | | foreach (var kvp in merged) |
| | | 449 | | { |
| | 295 | 450 | | AppendVariableDeclarationAndCollect(kvp, preambleBuilder, dynamicImports, dynamicRefs); |
| | | 451 | | } |
| | | 452 | | |
| | 59 | 453 | | return (preambleBuilder, dynamicImports, dynamicRefs); |
| | | 454 | | } |
| | | 455 | | |
| | | 456 | | /// <summary> |
| | | 457 | | /// Appends a single variable declaration for the provided key/value and gathers any dynamic imports & reference |
| | | 458 | | /// </summary> |
| | | 459 | | /// <param name="kvp">The merged key and its (source dictionary name, value).</param> |
| | | 460 | | /// <param name="preambleBuilder">Builder accumulating declaration lines.</param> |
| | | 461 | | /// <param name="dynamicImports">Set capturing namespaces to import.</param> |
| | | 462 | | /// <param name="dynamicRefs">Set capturing assemblies that must be referenced.</param> |
| | | 463 | | private static void AppendVariableDeclarationAndCollect( |
| | | 464 | | KeyValuePair<string, (string Dict, object? Value)> kvp, |
| | | 465 | | StringBuilder preambleBuilder, |
| | | 466 | | HashSet<string> dynamicImports, |
| | | 467 | | HashSet<Assembly> dynamicRefs) |
| | | 468 | | { |
| | 295 | 469 | | var valueType = kvp.Value.Value?.GetType(); |
| | 295 | 470 | | var typeName = FormatTypeName(valueType); |
| | 295 | 471 | | _ = preambleBuilder.AppendLine($"var {kvp.Key} = ({typeName}){kvp.Value.Dict}[\"{kvp.Key}\"]; "); |
| | | 472 | | |
| | 295 | 473 | | if (valueType == null) |
| | | 474 | | { |
| | 160 | 475 | | return; |
| | | 476 | | } |
| | | 477 | | |
| | 135 | 478 | | TryAddNamespace(dynamicImports, valueType.Namespace); |
| | 135 | 479 | | CollectGenericArguments(valueType, dynamicImports, dynamicRefs); |
| | 135 | 480 | | _ = dynamicRefs.Add(valueType.Assembly); |
| | 135 | 481 | | } |
| | | 482 | | |
| | | 483 | | /// <summary> |
| | | 484 | | /// Adds a namespace string to the imports set if it is non-empty. |
| | | 485 | | /// </summary> |
| | | 486 | | /// <param name="imports">Namespace accumulator set.</param> |
| | | 487 | | /// <param name="ns">Namespace candidate.</param> |
| | | 488 | | private static void TryAddNamespace(HashSet<string> imports, string? ns) |
| | | 489 | | { |
| | 202 | 490 | | if (!string.IsNullOrEmpty(ns)) |
| | | 491 | | { |
| | 202 | 492 | | _ = imports.Add(ns!); |
| | | 493 | | } |
| | 202 | 494 | | } |
| | | 495 | | |
| | | 496 | | /// <summary> |
| | | 497 | | /// For a generic type, collects namespaces and assemblies for each generic argument. |
| | | 498 | | /// </summary> |
| | | 499 | | /// <param name="valueType">The possibly generic value type.</param> |
| | | 500 | | /// <param name="imports">Namespace accumulator set.</param> |
| | | 501 | | /// <param name="refs">Assembly reference accumulator set.</param> |
| | | 502 | | private static void CollectGenericArguments(Type valueType, HashSet<string> imports, HashSet<Assembly> refs) |
| | | 503 | | { |
| | 135 | 504 | | if (!valueType.IsGenericType) |
| | | 505 | | { |
| | 88 | 506 | | return; |
| | | 507 | | } |
| | 228 | 508 | | foreach (var ga in valueType.GetGenericArguments()) |
| | | 509 | | { |
| | 67 | 510 | | TryAddNamespace(imports, ga.Namespace); |
| | 67 | 511 | | _ = refs.Add(ga.Assembly); |
| | | 512 | | } |
| | 47 | 513 | | } |
| | | 514 | | |
| | | 515 | | /// <summary> |
| | | 516 | | /// Emits a debug log summarizing the dynamic imports and assembly references that were discovered. |
| | | 517 | | /// </summary> |
| | | 518 | | /// <param name="imports">Collected imports.</param> |
| | | 519 | | /// <param name="refs">Collected assembly references (filtered to those with physical locations).</param> |
| | | 520 | | /// <param name="log">Logger.</param> |
| | | 521 | | private static void LogDynamicDiscovery(HashSet<string> imports, List<Assembly> refs, Serilog.ILogger log) |
| | | 522 | | { |
| | 59 | 523 | | if (log.IsEnabled(LogEventLevel.Debug) && (imports.Count > 0 || refs.Count > 0)) |
| | | 524 | | { |
| | 24 | 525 | | log.Debug("Discovered {ImportCount} dynamic import(s) and {RefCount} reference(s) from globals/locals.", imp |
| | | 526 | | } |
| | 59 | 527 | | } |
| | | 528 | | |
| | | 529 | | // Produces a C# friendly type name for reflection types (handles generics, arrays, nullable, and fallbacks). |
| | | 530 | | private static string FormatTypeName(Type? t) |
| | | 531 | | { |
| | 363 | 532 | | if (t == null) |
| | | 533 | | { |
| | 160 | 534 | | return "object"; |
| | | 535 | | } |
| | 203 | 536 | | if (t.IsGenericParameter) |
| | | 537 | | { |
| | 0 | 538 | | return "object"; |
| | | 539 | | } |
| | 203 | 540 | | if (t.IsArray) |
| | | 541 | | { |
| | 1 | 542 | | return FormatTypeName(t.GetElementType()) + "[]"; |
| | | 543 | | } |
| | | 544 | | // Nullable<T> |
| | 202 | 545 | | if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>)) |
| | | 546 | | { |
| | 0 | 547 | | return FormatTypeName(t.GetGenericArguments()[0]) + "?"; |
| | | 548 | | } |
| | 202 | 549 | | if (t.IsGenericType) |
| | | 550 | | { |
| | | 551 | | try |
| | | 552 | | { |
| | 47 | 553 | | var genericDefName = t.Name; |
| | 47 | 554 | | var tickIndex = genericDefName.IndexOf('`'); |
| | 47 | 555 | | if (tickIndex > 0) |
| | | 556 | | { |
| | 47 | 557 | | genericDefName = genericDefName[..tickIndex]; |
| | | 558 | | } |
| | 47 | 559 | | var args = t.GetGenericArguments().Select(FormatTypeName); |
| | 47 | 560 | | return (t.Namespace != null ? t.Namespace + "." : string.Empty) + genericDefName + "<" + string.Join("," |
| | | 561 | | } |
| | 0 | 562 | | catch |
| | | 563 | | { |
| | 0 | 564 | | return "object"; |
| | | 565 | | } |
| | | 566 | | } |
| | | 567 | | // Non generic |
| | 155 | 568 | | return t.FullName ?? t.Name ?? "object"; |
| | 47 | 569 | | } |
| | | 570 | | |
| | | 571 | | /// <summary> |
| | | 572 | | /// Compiles the provided VB.NET script and returns any diagnostics. |
| | | 573 | | /// </summary> |
| | | 574 | | /// <param name="script">The VB.NET script to compile.</param> |
| | | 575 | | /// <param name="log">The logger to use for logging.</param> |
| | | 576 | | /// <returns>A collection of diagnostics produced during compilation, or null if compilation failed.</returns> |
| | | 577 | | private static ImmutableArray<Diagnostic>? CompileAndGetDiagnostics(Script<object> script, Serilog.ILogger log) |
| | | 578 | | { |
| | | 579 | | try |
| | | 580 | | { |
| | 59 | 581 | | return script.Compile(); |
| | | 582 | | } |
| | 0 | 583 | | catch (CompilationErrorException ex) |
| | | 584 | | { |
| | 0 | 585 | | log.Error(ex, "C# script compilation failed with errors."); |
| | 0 | 586 | | return null; |
| | | 587 | | } |
| | 59 | 588 | | } |
| | | 589 | | |
| | | 590 | | private static void ThrowIfDiagnosticsNull(ImmutableArray<Diagnostic>? diagnostics) |
| | | 591 | | { |
| | 59 | 592 | | if (diagnostics == null) |
| | | 593 | | { |
| | 0 | 594 | | throw new CompilationErrorException("C# script compilation failed with no diagnostics.", []); |
| | | 595 | | } |
| | 59 | 596 | | } |
| | | 597 | | |
| | | 598 | | /// <summary> |
| | | 599 | | /// Throws a CompilationErrorException if the diagnostics are null. |
| | | 600 | | /// </summary> |
| | | 601 | | /// <param name="diagnostics">The compilation diagnostics.</param> |
| | | 602 | | /// <param name="log">The logger to use for logging.</param> |
| | | 603 | | /// <exception cref="CompilationErrorException"></exception> |
| | | 604 | | private static void ThrowOnErrors(ImmutableArray<Diagnostic>? diagnostics, Serilog.ILogger log) |
| | | 605 | | { |
| | 60 | 606 | | if (diagnostics?.Any(d => d.Severity == DiagnosticSeverity.Error) != true) |
| | | 607 | | { |
| | 58 | 608 | | return; |
| | | 609 | | } |
| | | 610 | | |
| | 2 | 611 | | var errors = diagnostics?.Where(d => d.Severity == DiagnosticSeverity.Error).ToArray(); |
| | 1 | 612 | | if (errors is not { Length: > 0 }) |
| | | 613 | | { |
| | 0 | 614 | | return; |
| | | 615 | | } |
| | | 616 | | |
| | 1 | 617 | | var sb = new StringBuilder(); |
| | 1 | 618 | | _ = sb.AppendLine($"C# script compilation completed with {errors.Length} error(s):"); |
| | 4 | 619 | | foreach (var error in errors) |
| | | 620 | | { |
| | 1 | 621 | | var location = error.Location.IsInSource |
| | 1 | 622 | | ? $" at line {error.Location.GetLineSpan().StartLinePosition.Line + 1}" |
| | 1 | 623 | | : string.Empty; |
| | 1 | 624 | | var msg = $" Error [{error.Id}]: {error.GetMessage()}{location}"; |
| | 1 | 625 | | log.Error(msg); |
| | 1 | 626 | | _ = sb.AppendLine(msg); |
| | | 627 | | } |
| | 1 | 628 | | throw new CompilationErrorException("C# route code compilation failed\n" + sb.ToString(), diagnostics ?? []); |
| | | 629 | | } |
| | | 630 | | |
| | | 631 | | /// <summary> |
| | | 632 | | /// Logs warning messages if the compilation succeeded with warnings. |
| | | 633 | | /// </summary> |
| | | 634 | | /// <param name="diagnostics">The compilation diagnostics.</param> |
| | | 635 | | /// <param name="log">The logger to use for logging.</param> |
| | | 636 | | private static void LogWarnings(ImmutableArray<Diagnostic>? diagnostics, Serilog.ILogger log) |
| | | 637 | | { |
| | 58 | 638 | | var warnings = diagnostics?.Where(d => d.Severity == DiagnosticSeverity.Warning).ToArray(); |
| | 58 | 639 | | if (warnings is not null && warnings.Length != 0) |
| | | 640 | | { |
| | 0 | 641 | | log.Warning($"C# script compilation completed with {warnings.Length} warning(s):"); |
| | 0 | 642 | | foreach (var warning in warnings) |
| | | 643 | | { |
| | 0 | 644 | | var location = warning.Location.IsInSource |
| | 0 | 645 | | ? $" at line {warning.Location.GetLineSpan().StartLinePosition.Line + 1}" |
| | 0 | 646 | | : string.Empty; |
| | 0 | 647 | | log.Warning($" Warning [{warning.Id}]: {warning.GetMessage()}{location}"); |
| | | 648 | | } |
| | | 649 | | } |
| | 58 | 650 | | } |
| | | 651 | | |
| | | 652 | | /// <summary> |
| | | 653 | | /// Logs a success message if the compilation succeeded without warnings. |
| | | 654 | | /// </summary> |
| | | 655 | | /// <param name="diagnostics">The compilation diagnostics.</param> |
| | | 656 | | /// <param name="log">The logger to use for logging.</param> |
| | | 657 | | private static void LogSuccessIfNoWarnings(ImmutableArray<Diagnostic>? diagnostics, Serilog.ILogger log) |
| | | 658 | | { |
| | 58 | 659 | | var warnings = diagnostics?.Where(d => d.Severity == DiagnosticSeverity.Warning).ToArray(); |
| | 58 | 660 | | if (warnings != null && warnings.Length == 0 && log.IsEnabled(LogEventLevel.Debug)) |
| | | 661 | | { |
| | 47 | 662 | | log.Debug("C# script compiled successfully with no warnings."); |
| | | 663 | | } |
| | 58 | 664 | | } |
| | | 665 | | } |