-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFunctionCallNode.cs
More file actions
53 lines (50 loc) · 1.88 KB
/
FunctionCallNode.cs
File metadata and controls
53 lines (50 loc) · 1.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
namespace ExpressionParser
{
// A function call node. Supports IF(), CONCAT(), and NOW().
public class FunctionCallNode : ExpressionNode
{
private string _functionName;
private List<ExpressionNode> _arguments;
public FunctionCallNode(string functionName, List<ExpressionNode> arguments)
{
_functionName = functionName.ToUpperInvariant();
_arguments = arguments;
}
public override object Evaluate(Dictionary<string, object> variables)
{
switch (_functionName)
{
case "IF":
if (_arguments.Count != 3)
throw new Exception("IF function requires exactly three arguments.");
object conditionObj = _arguments[0].Evaluate(variables);
if (!(conditionObj is bool))
throw new Exception("The first argument to IF must be a boolean.");
bool condition = (bool)conditionObj;
return condition ? _arguments[1].Evaluate(variables) : _arguments[2].Evaluate(variables);
case "CONCAT":
{
string result = "";
foreach (var arg in _arguments)
{
object value = arg.Evaluate(variables);
if (value == null)
value = "";
else if (!(value is string))
value = value.ToString()!;
result += (string)value;
}
return result;
}
case "NOW":
{
if (_arguments.Count != 0)
throw new Exception("NOW function does not accept any arguments.");
return DateTime.Now;
}
default:
throw new Exception($"Unsupported function: {_functionName}");
}
}
}
}