aboutsummaryrefslogtreecommitdiffziptar.gz
path: root/src/Godosa.Core/Runs/Scripts/Condition.cs
blob: 346ee3b0bcfe3e81bc66e13e19b0e60b4853e10b (plain)
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
// Provenance: own design — shared run scripts (spec §3.6)
using System.Globalization;
using System.Text;

namespace Godosa.Core.Runs.Scripts;

public interface IConditionContext
{
    bool HasProbe(string name);
    RunValue Probe(string name, IReadOnlyList<string> args);
    long? Constant(string name);
}

/// <summary>Condition AST: or / and / not / comparison / atom. A bare identifier is a probe without arguments when the
/// game has one by that name, else a game constant.</summary>
public abstract record Cond
{
    public abstract RunValue Eval(IConditionContext c);

    public bool Test(IConditionContext c) => Truthy(Eval(c));

    public abstract IEnumerable<(string Name, IReadOnlyList<string> Args)> Probes();

    public abstract IEnumerable<string> Bare();

    public static string Describe(Cond cond, IConditionContext c) =>
        string.Join(" ", cond.Probes().Where(p => c.HasProbe(p.Name)).Distinct().Select(p =>
        {
            var label = p.Args.Count == 0 ? p.Name : $"{p.Name}({string.Join(",", p.Args)})";
            return $"{label}={c.Probe(p.Name, p.Args)}";
        }));

    internal static bool Truthy(RunValue v) => v.IsNumber ? v.Number != 0 : !string.IsNullOrEmpty(v.Text);
}

public sealed record OrCond(Cond A, Cond B) : Cond
{
    public override RunValue Eval(IConditionContext c) => RunValue.Of(A.Test(c) || B.Test(c));
    public override IEnumerable<(string, IReadOnlyList<string>)> Probes() => A.Probes().Concat(B.Probes());
    public override IEnumerable<string> Bare() => A.Bare().Concat(B.Bare());
}

public sealed record AndCond(Cond A, Cond B) : Cond
{
    public override RunValue Eval(IConditionContext c) => RunValue.Of(A.Test(c) && B.Test(c));
    public override IEnumerable<(string, IReadOnlyList<string>)> Probes() => A.Probes().Concat(B.Probes());
    public override IEnumerable<string> Bare() => A.Bare().Concat(B.Bare());
}

public sealed record NotCond(Cond A) : Cond
{
    public override RunValue Eval(IConditionContext c) => RunValue.Of(!A.Test(c));
    public override IEnumerable<(string, IReadOnlyList<string>)> Probes() => A.Probes();
    public override IEnumerable<string> Bare() => A.Bare();
}

public sealed record CompareCond(Cond A, string Op, Cond B) : Cond
{
    public override RunValue Eval(IConditionContext c)
    {
        var (a, b) = (A.Eval(c), B.Eval(c));
        if (a.IsNumber != b.IsNumber)
            throw new ScriptFault($"cannot compare {a} with {b}");
        var order = a.IsNumber ? a.Number!.Value.CompareTo(b.Number!.Value) : string.CompareOrdinal(a.Text, b.Text);
        if (!a.IsNumber && Op is "<" or "<=" or ">" or ">=")
            throw new ScriptFault($"cannot order strings {a} and {b}");
        return RunValue.Of(Op switch
        {
            "=" => order == 0, "!=" => order != 0, "<" => order < 0, "<=" => order <= 0, ">" => order > 0, _ => order >= 0,
        });
    }

    public override IEnumerable<(string, IReadOnlyList<string>)> Probes() => A.Probes().Concat(B.Probes());
    public override IEnumerable<string> Bare() => A.Bare().Concat(B.Bare());
}

public sealed record LiteralCond(RunValue Value) : Cond
{
    public override RunValue Eval(IConditionContext c) => Value;
    public override IEnumerable<(string, IReadOnlyList<string>)> Probes() => [];
    public override IEnumerable<string> Bare() => [];
}

/// <summary>A probe call <c>name(args)</c>, or a bare <c>name</c> (probe if the game has it, else a constant).</summary>
public sealed record NameCond(string Name, IReadOnlyList<string> Args, bool HasParens) : Cond
{
    public override RunValue Eval(IConditionContext c)
    {
        if (HasParens || c.HasProbe(Name))
            return c.Probe(Name, Args);
        return c.Constant(Name) is { } n ? RunValue.Of(n) : throw new ScriptFault($"unknown probe or constant {Name}");
    }

    public override IEnumerable<(string, IReadOnlyList<string>)> Probes() => [(Name, Args)];
    public override IEnumerable<string> Bare() => HasParens ? [] : [Name];
}

public static class ConditionParser
{
    public static Cond Parse(string text)
    {
        var tokens = Lex(text);
        var pos = 0;
        var cond = Or(tokens, ref pos);
        if (pos != tokens.Count)
            throw new FormatException($"unexpected '{tokens[pos]}' in condition '{text}'");
        return cond;
    }

    private static Cond Or(List<string> t, ref int pos)
    {
        var a = And(t, ref pos);
        while (pos < t.Count && t[pos] == "or")
        {
            pos++;
            a = new OrCond(a, And(t, ref pos));
        }
        return a;
    }

    private static Cond And(List<string> t, ref int pos)
    {
        var a = Not(t, ref pos);
        while (pos < t.Count && t[pos] == "and")
        {
            pos++;
            a = new AndCond(a, Not(t, ref pos));
        }
        return a;
    }

    private static Cond Not(List<string> t, ref int pos)
    {
        if (pos < t.Count && t[pos] == "not")
        {
            pos++;
            return new NotCond(Not(t, ref pos));
        }
        return Compare(t, ref pos);
    }

    private static Cond Compare(List<string> t, ref int pos)
    {
        var a = Atom(t, ref pos);
        if (pos < t.Count && t[pos] is "=" or "!=" or "<" or "<=" or ">" or ">=")
        {
            var op = t[pos++];
            return new CompareCond(a, op, Atom(t, ref pos));
        }
        return a;
    }

    private static Cond Atom(List<string> t, ref int pos)
    {
        if (pos >= t.Count)
            throw new FormatException("condition ends early");
        var tok = t[pos++];
        if (tok == "(")
        {
            var inner = Or(t, ref pos);
            if (pos >= t.Count || t[pos] != ")")
                throw new FormatException("missing ')'");
            pos++;
            return inner;
        }
        if (tok.StartsWith('"'))
            return new LiteralCond(RunValue.Of(tok[1..^1]));
        if (long.TryParse(tok, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out var n))
            return new LiteralCond(RunValue.Of(n));
        if (!char.IsLetter(tok[0]) && tok[0] != '_')
            throw new FormatException($"unexpected '{tok}'");
        var paren = tok.IndexOf('(');
        if (paren < 0)
            return new NameCond(tok, [], false);
        var args = tok[(paren + 1)..^1].Split(',', StringSplitOptions.TrimEntries).Where(a => a.Length > 0).ToArray();
        return new NameCond(tok[..paren], args, true);
    }

    private static List<string> Lex(string text)
    {
        var tokens = new List<string>();
        var i = 0;
        while (i < text.Length)
        {
            var c = text[i];
            if (c == ' ')
            {
                i++;
                continue;
            }
            if (c is '(' or ')')
            {
                tokens.Add(c.ToString());
                i++;
                continue;
            }
            if (c == '"')
            {
                var end = text.IndexOf('"', i + 1);
                if (end < 0)
                    throw new FormatException("unterminated quote");
                tokens.Add(text[i..(end + 1)]);
                i = end + 1;
                continue;
            }
            if (c is '=' or '!' or '<' or '>')
            {
                var two = i + 1 < text.Length && text[i + 1] == '=';
                var op = text.Substring(i, two ? 2 : 1);
                if (op == "!")
                    throw new FormatException("use != or not");
                tokens.Add(op);
                i += op.Length;
                continue;
            }
            var sb = new StringBuilder();
            var depth = 0;
            while (i < text.Length && (depth > 0 || (text[i] != ' ' && text[i] != ')' && !(text[i] is '=' or '!' or '<' or '>'))))
            {
                if (text[i] == '(' && sb.Length == 0)
                    break;
                if (text[i] == '(')
                    depth++;
                else if (text[i] == ')')
                    depth--;
                sb.Append(text[i++]);
            }
            if (sb.Length == 0)
                throw new FormatException($"unexpected '{text[i]}'");
            tokens.Add(sb.ToString());
        }
        return tokens;
    }
}