30 lines
929 B
C#
30 lines
929 B
C#
namespace Bts.BooleanExpressions.Arguments;
|
|
|
|
class Function : IArgument {
|
|
public const string FunctionPrefix = "function:";
|
|
|
|
readonly string name;
|
|
readonly IEnumerable<IArgument> args;
|
|
|
|
public Function(string name, IEnumerable<IArgument>? args = null) {
|
|
this.name = name;
|
|
this.args = args ?? Enumerable.Empty<IArgument>();
|
|
}
|
|
|
|
public delegate object? Delegate(List<object?> args);
|
|
|
|
public object? GetValue(IDictionary<string, object?> env) {
|
|
var argValues = args?.Select(a => a.GetValue(env))?.ToList() ?? new(0);
|
|
|
|
var k = FunctionPrefix + name;
|
|
if (!env.TryGetValue(k, out var fnObj)) {
|
|
throw new BooleanExpressionException($"Did not find function named '{name}'");
|
|
}
|
|
if (fnObj is not Delegate fn) {
|
|
throw new BooleanExpressionException(
|
|
$"Function {name} is not of type {typeof(Delegate)}");
|
|
}
|
|
return fn(argValues);
|
|
}
|
|
}
|