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