aboutsummaryrefslogtreecommitdiffziptar.gz
path: root/src/Godosa.Core/Runs/Scripts/Vars.cs
blob: a01da62c61e5741fb24634d0f2f8d16ae05b7395 (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
// Provenance: own design — shared run scripts (spec §3.3)
using System.Text;

namespace Godosa.Core.Runs.Scripts;

public static class VarsFile
{
    public static (Dictionary<string, string> Values, List<ScriptError> Errors) Parse(string path, string text)
    {
        var values = new Dictionary<string, string>(StringComparer.Ordinal);
        var errors = new List<ScriptError>();
        var lines = text.TrimStart('\uFEFF').Replace("\r\n", "\n").Split('\n');
        for (var i = 0; i < lines.Length; i++)
        {
            var line = StepLexer.StripComment(lines[i]).Trim();
            if (line.Length == 0)
                continue;
            var eq = line.IndexOf('=');
            var name = eq > 0 ? line[..eq].Trim() : "";
            if (name.Length == 0 || name.Contains(' '))
            {
                errors.Add(new ScriptError(new SourceRef(path, i + 1), "bad vars line (name = value)"));
                continue;
            }
            values[name] = line[(eq + 1)..].Trim();
        }
        return (values, errors);
    }
}

/// <summary><c>${name}</c> expansion, innermost first (<c>${ui.rest.${hours}}</c>); <c>${probe:name(args)}</c> = a probe
/// value; a <c>$</c> not followed by <c>{</c> is literal.</summary>
public static class VarExpander
{
    public static string Expand(string text, Func<string, string?> lookup, Func<string, RunValue>? probe)
    {
        var sb = new StringBuilder();
        var i = 0;
        while (i < text.Length)
        {
            if (text[i] == '$' && i + 1 < text.Length && text[i + 1] == '{')
            {
                i += 2;
                sb.Append(Reference(text, ref i, lookup, probe));
                continue;
            }
            sb.Append(text[i++]);
        }
        return sb.ToString();
    }

    /// <summary>Resolves the reference opened before <paramref name="i"/> (nested references in its name first); the
    /// value is used as is, never scanned again.</summary>
    private static string Reference(string text, ref int i, Func<string, string?> lookup, Func<string, RunValue>? probe)
    {
        var name = new StringBuilder();
        while (true)
        {
            if (i >= text.Length)
                throw new ScriptFault($"unclosed ${{ in '{text}'");
            if (text[i] == '}')
            {
                i++;
                break;
            }
            if (text[i] == '$' && i + 1 < text.Length && text[i + 1] == '{')
            {
                i += 2;
                name.Append(Reference(text, ref i, lookup, probe));
                continue;
            }
            name.Append(text[i++]);
        }
        var n = name.ToString();
        if (n.Length == 0)
            throw new ScriptFault("empty ${}");
        if (n.StartsWith("probe:", StringComparison.Ordinal))
            return (probe ?? throw new ScriptFault($"no probes here: ${{{n}}}"))(n["probe:".Length..]).ToString();
        return lookup(n) ?? throw new ScriptFault($"unresolved variable ${{{n}}}");
    }

    /// <summary>Plain names inside the innermost <c>${…}</c> (no nested <c>${</c>, no <c>probe:</c>).</summary>
    public static IEnumerable<string> Names(string text)
    {
        for (var i = 0; i < text.Length - 1; i++)
        {
            if (text[i] != '$' || text[i + 1] != '{')
                continue;
            var close = text.IndexOf('}', i + 2);
            if (close < 0)
                yield break;
            var inner = text[(i + 2)..close];
            if (inner.Length > 0 && !inner.Contains("${", StringComparison.Ordinal) && !inner.StartsWith("probe:", StringComparison.Ordinal))
                yield return inner;
        }
    }
}

public sealed record ScopeState(Dictionary<string, string> Vars, bool Local, OutputLevel Level);

/// <summary>Variable scopes: root (globals), include scopes (vars go to root, output level scoped), def-call scopes
/// (local vars). Lookup walks from the top down.</summary>
public sealed class VarScopes
{
    private readonly List<ScopeState> _stack;

    public VarScopes(OutputLevel level) => _stack = [new ScopeState(new Dictionary<string, string>(StringComparer.Ordinal), false, level)];

    public int Depth => _stack.Count;

    public OutputLevel Level
    {
        get => _stack[^1].Level;
        set => _stack[^1] = _stack[^1] with { Level = value };
    }

    public void Push(bool local, OutputLevel level, IEnumerable<KeyValuePair<string, string>> bindings) =>
        _stack.Add(new ScopeState(new Dictionary<string, string>(bindings, StringComparer.Ordinal), local, level));

    public void Pop()
    {
        if (_stack.Count > 1)
            _stack.RemoveAt(_stack.Count - 1);
    }

    public void PopTo(int depth)
    {
        while (_stack.Count > Math.Max(1, depth))
            _stack.RemoveAt(_stack.Count - 1);
    }

    public string? Get(string name)
    {
        for (var i = _stack.Count - 1; i >= 0; i--)
        {
            if (_stack[i].Vars.TryGetValue(name, out var v))
                return v;
        }
        return null;
    }

    public void Set(string name, string value)
    {
        for (var i = _stack.Count - 1; i >= 1; i--)
        {
            if (_stack[i].Local)
            {
                _stack[i].Vars[name] = value;
                return;
            }
        }
        _stack[0].Vars[name] = value;
    }

    public Dictionary<string, string> Visible()
    {
        var all = new Dictionary<string, string>(StringComparer.Ordinal);
        foreach (var scope in _stack)
            foreach (var (k, v) in scope.Vars)
                all[k] = v;
        return all;
    }

    public List<ScopeState> Snapshot() =>
        [.. _stack.Select(s => s with { Vars = new Dictionary<string, string>(s.Vars, StringComparer.Ordinal) })];

    public void Restore(IReadOnlyList<ScopeState> scopes)
    {
        _stack.Clear();
        _stack.AddRange(scopes.Select(s => s with { Vars = new Dictionary<string, string>(s.Vars, StringComparer.Ordinal) }));
        if (_stack.Count == 0)
            _stack.Add(new ScopeState(new Dictionary<string, string>(StringComparer.Ordinal), false, OutputLevel.Labels));
    }
}