Cauldron/Cauldron.Core/RoslynHost.cs

47 lines
1.3 KiB
C#
Raw Normal View History

2023-07-26 18:46:15 +00:00
using System.Collections.Immutable;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Scripting;
2023-07-19 19:30:39 +00:00
using Microsoft.CodeAnalysis.Scripting;
2023-07-21 20:11:56 +00:00
namespace Cauldron.Core;
2023-07-19 19:30:39 +00:00
public class RoslynHost
{
/// <summary>
/// Run the provided C# script
/// </summary>
/// <param name="code">The script to run</param>
/// <param name="imports">Namespace imports for the script</param>
/// <param name="globals">Values that will be made available to the script</param>
/// <param name="cancellationToken"></param>
public static async Task RunScript(string code, string[] imports,
2023-07-26 18:46:15 +00:00
RoslynHostGlobals globals, CancellationToken cancellationToken = default)
2023-07-19 19:30:39 +00:00
{
ScriptOptions options = ScriptOptions.Default
.AddImports(imports);
2023-07-19 22:09:25 +00:00
await CSharpScript.RunAsync(code, options, globals,
cancellationToken: cancellationToken);
2023-07-19 19:30:39 +00:00
}
2023-07-26 18:46:15 +00:00
public static ImmutableArray<Diagnostic> BuildScript(string code, string[] imports,
RoslynHostGlobals globals)
{
ScriptOptions options = ScriptOptions.Default
.AddImports(imports);
Script<object> script = CSharpScript.Create(code, options, globals.GetType());
return script.GetCompilation().GetDiagnostics();
}
2023-07-19 19:30:39 +00:00
}
public class RoslynHostGlobals
{
2023-07-21 20:11:56 +00:00
public CauldronWriter Cauldron { get; set; }
2023-07-19 19:30:39 +00:00
2023-07-21 20:11:56 +00:00
public RoslynHostGlobals(CauldronWriter writer)
2023-07-19 19:30:39 +00:00
{
2023-07-21 20:11:56 +00:00
this.Cauldron = writer;
2023-07-19 19:30:39 +00:00
}
}