ScriptFoundry 0.1.0
See the version list below for details.
dotnet add package ScriptFoundry --version 0.1.0
NuGet\Install-Package ScriptFoundry -Version 0.1.0
<PackageReference Include="ScriptFoundry" Version="0.1.0" />
<PackageVersion Include="ScriptFoundry" Version="0.1.0" />
<PackageReference Include="ScriptFoundry" />
paket add ScriptFoundry --version 0.1.0
#r "nuget: ScriptFoundry, 0.1.0"
#:package ScriptFoundry@0.1.0
#addin nuget:?package=ScriptFoundry&version=0.1.0
#tool nuget:?package=ScriptFoundry&version=0.1.0
ScriptFoundry
Compile a restricted subset of C# into typed System.Func delegates using Roslyn. Scripts execute compiled IL, with explicit authorization of types and members. Requires .NET 10.
Quick start
using ScriptFoundry;
var compiler = new SafeCompiler();
using var script = compiler.Compile<Func<int, int>>("return x * 2;", "x");
Console.WriteLine(script.Function(21)); // 42
Parameter names follow the source; omitted names default to arg0, arg1, etc. Roslyn checks types, scopes, definite assignment, and return paths.
Configuration and permissions
var configuration = new SafeCompilerConfigurationBuilder()
.AllowType<Vector3D>(TypeAccess.PublicMembers)
.WithOptions(options => options with
{
CacheCapacity = 128,
MaxBatchScripts = 2_000
})
.Build();
var compiler = new SafeCompiler(configuration);
| API | Purpose |
|---|---|
AllowType<T>() / AllowType(Type) |
Authorize a type without exposing its members (TypeOnly). |
AllowType<T>(TypeAccess.PublicMembers) |
Expose supported public methods, constructors, operators, and property accessors, including compatible inherited members. |
AllowMethod(MethodInfo) |
Authorize one exact method or operator overload. |
AllowProperty(PropertyInfo, allowRead, allowWrite) |
Authorize reading and writing independently; compound assignments and increments require both. |
WithTypeRegistry / WithMethodRegistry / WithPropertyRegistry |
Supply custom authorization registries. |
WithOptions |
Set compiler options directly or update them with a function. |
AddDependency / AddDependencies |
Add assembly references without authorizing their types or members. |
Declaring, parameter, return, and property types must also be allowed. Permissions are additive: TypeOnly does not revoke previously granted access. Each Build() creates fresh default registries and snapshots dependencies; custom registries are reused by reference. Direct configuration through SafeCompilerConfiguration is also supported.
Application types and operators
Public classes and structs from your application work alongside runtime types. Assemblies containing registered types are referenced automatically, preserving host type identity.
// Vector3D is defined in the host application and authorized above.
using var script = compiler.Compile<Func<Vector3D>>("""
return new Vector3D(1, 2, 3) + new Vector3D(4, 5, 6);
""");
Supported custom operators include arithmetic, comparisons, bitwise operations, shifts, unary operations, and increments/decrements. Compound assignments are supported when they require no user-defined conversions. Custom conversions and short-circuit logical operators (&& / ||) are excluded.
Constructors require PublicMembers. Optional, params, and by-reference parameters, named arguments, and object/collection initializers are unsupported. Implicit parameterless struct construction is unsupported; explicit public struct constructors and public class constructors are supported. The playground defines Vector3D and VectorDescription in Program.cs and demonstrates both.
Async scripts
Func<..., Task> and Func<..., Task<T>> signatures generate async methods and support await on authorized task-returning calls.
var configuration = new SafeCompilerConfigurationBuilder()
.AllowType<Task>(TypeAccess.PublicMembers)
.Build();
using var script = new SafeCompiler(configuration)
.Compile<Func<int, Task<int>>>("await Task.Delay(10); return x * 2;", "x");
int result = await script.Function(21); // 42
Batch compilation
Compile different signatures into one assembly and one collectible load context:
var definitions = new[]
{
ScriptDefinition.Create<Func<int, int>>("double", "return x * 2;", "x"),
ScriptDefinition.Create<Func<int, int, int>>("sum", "return x + y;", "x", "y")
};
using var batch = compiler.CompileBatch(definitions);
var sum = batch.GetFunction<Func<int, int, int>>("sum");
Console.WriteLine(sum(3, 5)); // 8
Batch compilation supports async signatures, cancellation, per-script diagnostics, and all-or-nothing validation. Scripts cannot call each other. GetFunction<TDelegate> requires the exact declared delegate type; Functions returns a read-only delegate snapshot and Analyses exposes each script's AST and diagnostics.
Analysis and diagnostics
Analyze<TDelegate>(source, parameterNames) exposes a typed AST without emitting IL. Compile<TDelegate>(ast, parameterNames) accepts analyzed or manually constructed ASTs. Validation checks the original operations, generates C# from allowed nodes, and checks the generated operations again before compilation.
ScriptCompilationException carries structured diagnostics with IDs, messages, severity, and source positions. Compiled results expose GeneratedSource and ScriptId (or BatchId).
Supported language
Supports local variables, blocks, assignments, arithmetic and logical expressions, comparisons, bitwise operations, shifts, increments/decrements, if/else, ternaries, ??, standard casts, authorized member calls and construction, return, and await.
Rejects loops, recursion, cross-script calls, arrays, lambdas, delegate invocation, local functions, fields, indexers, reflection, GetType, typeof, dynamic, unsafe, interpolation, directives, and unsupported syntax. Generic methods, reduced extension methods, optional/params/by-reference parameters, and named arguments are excluded. String concatenation accepts only strings to avoid implicit ToString calls.
Primitive scalar types, void, Task, and CancellationToken are preauthorized; their members still require permission. Task<T> and Nullable<T> require allowed arguments; other closed generic types require explicit registration too.
Cache, lifetime, and limits
A bounded cache stores IL images, not delegates; authorization is rechecked on cache hits. ClearCache() clears it and CachedCompilationCount reports its size. Each compilation loads a new collectible assembly; batch functions share one. Dispose results when finished. Retained delegates, snapshots, or running calls delay unloading.
SafeCompilerOptions |
Default |
|---|---|
MaxSourceLength |
32,768 characters per script |
MaxAstNodes |
4,096 |
MaxAstDepth |
64 |
CacheCapacity |
64 images |
MaxBatchScripts |
10,000 |
MaxBatchSourceLength |
8,388,608 total characters |
These are compilation limits, not runtime memory or CPU quotas. Dependencies must provide assembly metadata on disk; single-file publishing, trimming, and NativeAOT are unsupported.
Cancellation and process isolation
Compilation accepts cancellation tokens. ScriptExecution.RunAsync(operation, timeout, cancellationToken) supports cooperative execution cancellation; it cannot forcibly interrupt synchronous code or members that ignore cancellation.
IsolatedScriptRunner executes scripts in ScriptFoundry.Worker, with one scalar input (arg0) and scalar result, including strings and decimals. IsolatedScriptOptions configures the .NET host, source limit, and timeout. The timeout covers startup, compilation, and execution; expiry terminates the worker process tree. Deploy the worker's full output directory, including dependencies and runtime files.
Authorization is not a security sandbox. Allowed members retain their effects, and virtual/interface calls use host-provided implementations. The worker runs with host credentials and does not impose OS memory, CPU, filesystem, or network restrictions.
Build and examples
dotnet build src/ScriptFoundry/ScriptFoundry.slnx -c Release
dotnet test --solution src/ScriptFoundry/ScriptFoundry.slnx -c Release
dotnet run --project src/ScriptFoundry/ScriptFoundry.Playground.Console -c Release -- --no-pause
dotnet run --project src/ScriptFoundry/ScriptFoundry.Playground.Console -c Release -- --benchmark
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net10.0
- Microsoft.CodeAnalysis.CSharp (>= 5.9.0)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.