godosa-engine

git clone https://git.godosa.eu/godosa-engine

master

raw · 22821 bytes

  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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
// Provenance: own design — shared run scripts (spec §5)
using System.Globalization;

namespace Godosa.Core.Runs.Scripts;

public sealed record ScriptRunOptions
{
    public bool Deterministic { get; init; } = true;
    /// <summary>Overrides the script's <c>seed</c> header; neither → 0 and the game's rng is left alone.</summary>
    public ulong? Seed { get; init; }
    public OutputLevel Output { get; init; } = OutputLevel.Labels;
    public OutputLevel Floor { get; init; } = OutputLevel.Quiet;
    public int StepCap { get; init; } = 36_000;
    public string? CacheDir { get; init; }
    public bool UseCache { get; init; } = true;
    /// <summary>false: checkpoints are markers — no digest (a whole-state serialization, slow in a big game), nothing
    /// cached (<c>--no-snapshots</c>).</summary>
    public bool Snapshots { get; init; } = true;
    public string? From { get; init; }
    public string? Until { get; init; }
    public string? ReportDir { get; init; }
    public long CacheCapBytes { get; init; } = 2L << 30;
}

public enum RunOutcome { Passed, Failed, Invalid, Stopped }

public sealed record RunResult(RunOutcome Outcome, int ExitCode, long Frames, string? Failure);

public sealed class ScriptRunner : IConditionContext
{
    private sealed class Active(Instr instr, long startFrame)
    {
        public Instr Instr { get; } = instr;
        public long StartFrame { get; } = startFrame;
        public int Frames { get; set; }
        public InputPlan? Plan { get; set; }
        /// <summary>The <see cref="Frames"/> value a plan's frame 0 lands on (0 for the step's own plan).</summary>
        public int PlanBase { get; set; }
        public int Sent { get; set; }
        public IRunAction? Action { get; init; }
        public Cond? Wait { get; init; }
        public int? WaitFrames { get; init; }
    }

    private sealed record Label(string Name, long Start, SourceRef At);

    private readonly ScriptProgram _program;
    private readonly IRunGame _game;
    private readonly ScriptRunOptions _options;
    private readonly RunOutput _out;
    private readonly VarScopes _vars;
    private readonly List<Label> _labels = [];
    private Active? _active;
    private sealed record TryFrame(int End, int ScopeDepth, int LabelCount);
    private readonly List<TryFrame> _tries = [];
    private int _pc;
    private bool _started;

    public ScriptRunner(ScriptProgram program, IRunGame game, ScriptRunOptions options, Action<string> output)
    {
        (_program, _game, _options) = (program, game, options);
        _out = new RunOutput(output, options.Floor);
        _vars = new VarScopes(options.Output);
        foreach (var (k, v) in program.Vars)
            _vars.Set(k, v);
    }

    public long FrameCount { get; private set; }

    /// <summary>Steps completed so far (a window host draws before the next one resolves its positions).</summary>
    public int StepsDone => _steps;

    /// <summary>Effective seed: options, else the script's <c>seed</c> header, else 0.</summary>
    public ulong Seed => _options.Seed ?? _program.Seed ?? 0;
    public RunResult? Result { get; private set; }
    public RunReport? Report { get; private set; }

    private readonly Queue<string> _recent = new();
    private readonly List<CheckpointRecord> _checkpoints = [];
    private readonly List<string> _warnings = [];
    private readonly System.Diagnostics.Stopwatch _wall = new();
    private int _steps, _cacheHits, _cacheMisses;
    private CheckpointCache? _cache;
    private IReadOnlyDictionary<int, string> _keys = new Dictionary<int, string>();

    public RunResult Run(long cap = HeadlessLoop.DefaultCap)
    {
        var (_, capped) = HeadlessLoop.Run(_ => Frame(), null, cap);
        if (capped && Result == null)
            Fail(_active?.Instr, $"frame cap {cap}");
        return Result ?? new RunResult(RunOutcome.Passed, 0, FrameCount, null);
    }

    /// <summary>A deferred checkpoint restore (<see cref="IRunGame.RestoreDeferred"/>) is under way: the host advances no
    /// game frame and calls <see cref="AfterFrame"/> not at all this frame; the next <see cref="BeforeFrame"/> goes on.</summary>
    public bool Restoring { get; private set; }

    public bool Frame()
    {
        BeforeFrame();
        if (Result != null)
            return false;
        if (Restoring)
            return true;
        Guard(_active?.Instr, _game.Advance);
        if (Result == null)
            AfterFrame();
        return Result == null;
    }

    public void BeforeFrame()
    {
        if (Result != null)
            return;
        if (!_started)
        {
            var ok = false;
            Guard(null, () => ok = Start());
            if (!ok || Result != null)
                return;
            if (Restoring = _cacheHits > 0 && _game.RestoreDeferred)
                return;
        }
        Restoring = false;
        Guard(_active?.Instr, () =>
        {
            while (_active == null && Result == null)
            {
                if (_pc >= _program.Code.Count)
                {
                    Finish(new RunResult(RunOutcome.Passed, 0, FrameCount, null), null);
                    return;
                }
                Exec(_program.Code[_pc++]);
            }
        });
        if (_active is { Plan: { } plan } a && Result == null)
        {
            Guard(a.Instr, () =>
            {
                foreach (var e in plan.Events.Where(e => e.Frame + a.PlanBase == a.Frames))
                {
                    _game.Input.Send(e.Event);
                    a.Sent++;
                    _out.Emit(OutputLevel.Trace, _vars.Level, $"  input f={FrameCount} {e.Event}");
                }
            });
        }
    }

    /// <param name="poll">false: the frame counts but the step is not polled (a window host whose next draw shows what this
    /// frame changed: a click resolved now would aim on the draw from before); the next frame polls it.</param>
    public void AfterFrame(bool poll = true)
    {
        if (Result != null || _active is not { } a)
            return;
        FrameCount++;
        a.Frames++;
        if (!poll)
            return;
        Guard(a.Instr, () =>
        {
            var status = Poll(a);
            if (status.Plan is { } more)
                (a.Plan, a.PlanBase, a.Sent) = (more, a.Frames, 0);
            if (status.State == StepState.Running && a.Frames >= _options.StepCap)
                status = StepStatus.Fault($"step exceeded {_options.StepCap} frames");
            if (status.State == StepState.Fault)
                throw new ScriptFault(status.Message ?? "fault");
            if (status.State == StepState.Done)
                Complete(a.Instr, a.Frames);
        });
    }

    private bool Start()
    {
        _started = true;
        _wall.Start();
        var errors = ScriptValidator.Validate(_program, _game, _options.Deterministic);
        if (errors.Count > 0)
        {
            foreach (var e in errors)
                _out.Always(e.ToString());
            Finish(new RunResult(RunOutcome.Invalid, 2, 0, errors[0].ToString()), null);
            return false;
        }
        var until = int.MaxValue;
        if (_options.Until is { } stop)
        {
            until = _program.Code.Select((c, n) => (c, n)).FirstOrDefault(x => x.c.A == stop && x.c.Op is Op.Checkpoint or Op.LabelEnd, (null!, -1)).Item2;
            if (until < 0)
                return Invalid($"unknown label or checkpoint {stop}");
        }
        if ((_options.Seed ?? _program.Seed) is { } seed && _game.Rng is { } rng)
            rng.Seed(unchecked((long)seed));
        if (_options.Deterministic && _options.CacheDir != null && _game.SupportsSnapshot)
        {
            _cache = new CheckpointCache(_options.CacheDir, _options.CacheCapBytes);
            _keys = CheckpointKeys.Compute(_program, _game.ContentVersion, Seed);
        }
        if (_options.From is { } from)
        {
            var index = _keys.Keys.Concat(_program.Code.Select((c, n) => (c, n)).Where(x => x.c.Op == Op.Checkpoint).Select(x => x.n))
                .Distinct().FirstOrDefault(n => _program.Code[n].A == from, -1);
            if (index < 0)
                return Invalid($"unknown checkpoint {from}");
            if (_cache?.Load(_keys[index]) is not { } entry)
                return Invalid($"checkpoint {from} not cached");
            Resume(index, entry);
        }
        else if (_cache != null && _options.UseCache)
        {
            foreach (var index in _keys.Keys.Where(k => k < until).OrderDescending())
            {
                if (_cache.Load(_keys[index]) is { } entry)
                {
                    Resume(index, entry);
                    break;
                }
            }
        }
        return true;
    }

    private bool Invalid(string message)
    {
        _out.Always(message);
        Finish(new RunResult(RunOutcome.Invalid, 2, 0, message), null);
        return false;
    }

    private void Resume(int index, CachedCheckpoint entry)
    {
        _game.SnapshotRestore(entry.Game);
        FrameCount = entry.State.Frame;
        _vars.Restore(entry.State.Scopes);
        _labels.Clear();
        _labels.AddRange(entry.State.Labels.Select(l => new Label(l.Name, l.Start, new SourceRef(l.File, l.Line))));
        _pc = index + 1;
        var name = _program.Code[index].A;
        _checkpoints.Add(new CheckpointRecord(name, FrameCount, entry.State.Digest.ToString("x16"), "resumed"));
        _cacheHits++;
        _out.Always($"resumed at {name} (cache) f={FrameCount}");
    }

    private StepStatus Poll(Active a)
    {
        if (a.Plan is { } plan && a.Sent < plan.Events.Count)
            return StepStatus.Running;
        if (a.Action != null)
            return a.Action.Poll();
        if (a.WaitFrames is { } n)
            return a.Frames >= n ? StepStatus.Done : StepStatus.Running;
        if (a.Wait is { } cond)
        {
            if (cond.Test(this))
                return StepStatus.Done;
            _out.Emit(OutputLevel.Trace, _vars.Level, $"  wait f={FrameCount} {a.Instr.A}: {Cond.Describe(cond, this)}");
            return a.Frames >= a.Instr.Timeout
                ? StepStatus.Fault($"timeout after {a.Instr.Timeout} frames: {a.Instr.A} ({Cond.Describe(cond, this)})")
                : StepStatus.Running;
        }
        return StepStatus.Done;
    }

    private void Exec(Instr i)
    {
        switch (i.Op)
        {
            case Op.Set:
                _vars.Set(i.A, Expand(i.B));
                break;
            case Op.Expect:
            {
                var cond = ConditionParser.Parse(Expand(i.A));
                if (!cond.Test(this))
                    throw new ScriptFault($"expect failed: {i.A} ({Cond.Describe(cond, this)})");
                Complete(i, 0);
                break;
            }
            case Op.Wait:
            {
                var cond = ConditionParser.Parse(Expand(i.A));
                if (cond.Test(this))
                    Complete(i, 0);
                else
                    _active = new Active(i, FrameCount) { Wait = cond };
                break;
            }
            case Op.Verb:
                Verb(i);
                break;
            case Op.ScopeBegin:
                _vars.Push(i.LocalVars, _vars.Level, i.Bindings.Select(b => new KeyValuePair<string, string>(b.Key, Expand(b.Value))).ToList());
                break;
            case Op.ScopeEnd:
                _vars.Pop();
                break;
            case Op.LabelBegin:
                _labels.Add(new Label(i.A, FrameCount, i.At));
                break;
            case Op.LabelEnd:
            {
                var label = _labels[^1];
                _labels.RemoveAt(_labels.Count - 1);
                _out.Emit(OutputLevel.Labels, _vars.Level, $"[{label.At} {label.Name}] done f={FrameCount} (+{FrameCount - label.Start})");
                if (_options.Deterministic)
                    _out.Emit(OutputLevel.Labels, _vars.Level, DigestLine.Format(FrameCount, FrameCount / 60.0, _game.Digest()));
                if (_options.Until == label.Name)
                    Finish(new RunResult(RunOutcome.Stopped, 0, FrameCount, null), null);
                break;
            }
            case Op.TryBegin:
                _tries.Add(new TryFrame(i.Jump, _vars.Depth, _labels.Count));
                break;
            case Op.TryEnd:
                if (_tries.Count > 0)
                    _tries.RemoveAt(_tries.Count - 1);
                break;
            case Op.Checkpoint:
            {
                if (!_options.Snapshots)
                {
                    _checkpoints.Add(new CheckpointRecord(i.A, FrameCount, "", "marker"));
                    _out.Emit(OutputLevel.Checkpoints, _vars.Level, $"checkpoint {i.A} f={FrameCount}");
                    if (_options.Until == i.A)
                        Finish(new RunResult(RunOutcome.Stopped, 0, FrameCount, null), null);
                    break;
                }
                var digest = _game.Digest();
                var source = "replayed";
                if (_cache != null && _game.SnapshotRefusal() is { } refusal)
                    _warnings.Add($"checkpoint {i.A} not cached: {refusal}");
                else if (_cache != null && _keys.TryGetValue(_pc - 1, out var key))
                {
                    var old = _cache.Load(key);
                    if (old != null && old.State.Digest == digest)
                        source = "cached";
                    else
                    {
                        if (old != null)
                            _warnings.Add($"checkpoint {i.A} digest differs from cache ({old.State.Digest:x16} → {digest:x16}); cache replaced");
                        try
                        {
                            _cache.Save(key, new CachedCheckpoint(new RunnerState(FrameCount, digest, _vars.Snapshot(),
                                [.. _labels.Select(l => new LabelState(l.Name, l.Start, l.At.File, l.At.Line))]), _game.SnapshotSave()));
                        }
                        catch (Exception e) when (e is IOException or UnauthorizedAccessException)
                        {
                            _warnings.Add($"checkpoint cache not written: {e.Message}");
                        }
                        _cacheMisses++;
                    }
                }
                _checkpoints.Add(new CheckpointRecord(i.A, FrameCount, digest.ToString("x16"), source));
                _out.Emit(OutputLevel.Checkpoints, _vars.Level, $"checkpoint {i.A} f={FrameCount}");
                if (_options.Deterministic)
                    _out.Emit(OutputLevel.Checkpoints, _vars.Level, DigestLine.Format(FrameCount, FrameCount / 60.0, digest));
                if (_options.Until == i.A)
                    Finish(new RunResult(RunOutcome.Stopped, 0, FrameCount, null), null);
                break;
            }
        }
    }

    private void Verb(Instr i)
    {
        var tokens = ExpandTokens(i.B);
        switch (i.A)
        {
            case "log":
                _out.Always(tokens[0].Text);
                return;
            case "output":
                _vars.Level = RunOutput.Parse(tokens[0].Text);
                return;
            case "rng":
                Rng(tokens);
                return;
            case "wait-frames":
            {
                var n = Durations.Frames(tokens[0].Text) ?? throw new ScriptFault($"bad frame count '{tokens[0].Text}'");
                if (n == 0)
                    Complete(i, 0);
                else
                    _active = new Active(i, FrameCount) { WaitFrames = n };
                return;
            }
        }
        if (InputPlans.IsInputVerb(i.A))
        {
            _active = new Active(i, FrameCount) { Plan = InputPlans.For(i.A, tokens, t => Positions.Resolve(t, _game)) };
            return;
        }
        var action = _game.Actions[i.A];
        var start = action.Begin(tokens.Select(t => t.Text).ToList());
        if (start.Status is { State: StepState.Fault } fault)
            throw new ScriptFault(fault.Message ?? "fault");
        if (start.Plan == null && start.Status is { State: StepState.Done })
        {
            Complete(i, 0);
            return;
        }
        _active = new Active(i, FrameCount) { Plan = start.Plan, Action = action };
    }

    private void Rng(List<Token> t)
    {
        var rng = _game.Rng ?? throw new ScriptFault("game has no rng hook");
        long N(string s) => long.TryParse(s, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out var v) ? v : throw new ScriptFault($"bad number '{s}'");
        switch (t[0].Text)
        {
            case "seed" when t.Count == 2:
                rng.Seed(N(t[1].Text));
                break;
            case "next" when t.Count == 3:
                rng.ForceNext(t[1].Text, N(t[2].Text));
                break;
            default:
                throw new ScriptFault("rng seed <n> | rng next <kind> <value>");
        }
    }

    private void Complete(Instr i, int frames)
    {
        _active = null;
        var label = _labels.Count > 0 ? $" {_labels[^1].Name}" : "";
        _out.Emit(OutputLevel.Steps, _vars.Level, $"[{i.At}{label}] {i.Text} done f={FrameCount} (+{frames})");
        _steps++;
        _recent.Enqueue($"{i.At} {i.Text} f={FrameCount}");
        while (_recent.Count > 20)
            _recent.Dequeue();
    }

    /// <summary>Quoted arguments expand inside their token (a value with quotes or spaces stays one argument); unquoted ones
    /// expand, then split (a variable may hold several arguments).</summary>
    private List<Token> ExpandTokens(string text) =>
        [.. StepLexer.Tokens(text).SelectMany(t => t.Quoted ? [new Token(Expand(t.Text), true)] : StepLexer.Tokens(Expand(t.Text)))];

    private string Expand(string text) => VarExpander.Expand(text, _vars.Get, p =>
    {
        var cond = ConditionParser.Parse(p);
        return cond.Eval(this);
    });

    private void Guard(Instr? at, Action step)
    {
        try
        {
            step();
        }
        catch (ScriptFault e)
        {
            Fail(at ?? CurrentOrLast(), e.Message);
        }
        catch (FormatException e)
        {
            Fail(at ?? CurrentOrLast(), e.Message);
        }
        catch (Exception e) when (e is not OutOfMemoryException)
        {
            Fail(at ?? CurrentOrLast(), $"{e.GetType().Name}: {e.Message}");
        }
    }

    private Instr? CurrentOrLast() => _pc > 0 && _pc <= _program.Code.Count ? _program.Code[_pc - 1] : null;

    private void Fail(Instr? at, string reason)
    {
        ReleaseHeld();
        _active = null;
        if (_tries.Count > 0)
        {
            var t = _tries[^1];
            _tries.RemoveAt(_tries.Count - 1);
            _vars.PopTo(t.ScopeDepth);
            _labels.RemoveRange(t.LabelCount, _labels.Count - t.LabelCount);
            _out.Always($"try failed at {at?.At}: {reason}");
            _pc = t.End + 1;
            return;
        }
        var where = at == null ? "" : $" {at.At} {at.Text}";
        byte[]? snap = null;
        if (_game.SupportsSnapshot)
        {
            try
            {
                snap = _game.SnapshotSave();
            }
            catch (Exception e) when (e is not OutOfMemoryException)
            {
                _warnings.Add($"failure save not written: {e.Message}");
            }
        }
        string dump;
        try
        {
            dump = _game.Dump();
        }
        catch (Exception e) when (e is not OutOfMemoryException)
        {
            dump = $"(dump failed: {e.Message})";
        }
        var failure = new FailureInfo(at?.At.ToString() ?? "", at?.Chain.Select(c => c.ToString()).ToList() ?? [], at?.Text ?? "",
            _labels.Count > 0 ? _labels[^1].Name : null, reason, [.. _recent], dump, _vars.Visible(),
            snap != null && _options.ReportDir != null ? Path.Combine(_options.ReportDir, "fail.snap") : null);
        _out.Always($"FAIL{where}: {reason}");
        Finish(new RunResult(RunOutcome.Failed, 1, FrameCount, reason), failure, snap);
    }

    private void Finish(RunResult result, FailureInfo? failure, byte[]? failSnapshot = null)
    {
        Result = result;
        _wall.Stop();
        Report = new RunReport(_program.Entry, _program.Mode, Seed, _options.Deterministic, result.Outcome, FrameCount,
            _steps, _wall.Elapsed.TotalSeconds, _cacheHits, _cacheMisses, [.. _checkpoints], [.. _warnings], failure);
        if (_options.ReportDir is not { } dir)
            return;
        try
        {
            ReportWriter.Write(dir, Report, failSnapshot);
        }
        catch (Exception e) when (e is IOException or UnauthorizedAccessException)
        {
            _warnings.Add($"report not written: {e.Message}");
            Report = Report with { Warnings = [.. _warnings] };
            _out.Always($"warning: report not written: {e.Message}");
        }
    }

    /// <summary>Review focus 1: a half-sent plan leaves no button or key held — pending ups are sent now.</summary>
    private void ReleaseHeld()
    {
        if (_active is not { Plan: { } plan } a)
            return;
        var sent = plan.Events.Take(a.Sent).Select(e => e.Event).ToList();
        foreach (var pending in plan.Events.Skip(a.Sent).Select(e => e.Event))
        {
            var held = pending.Kind switch
            {
                InputKind.Up => sent.Count(e => e.Kind == InputKind.Down && e.Button == pending.Button)
                    > sent.Count(e => e.Kind == InputKind.Up && e.Button == pending.Button),
                InputKind.KeyUp => sent.Count(e => e.Kind == InputKind.KeyDown && e.Key == pending.Key)
                    > sent.Count(e => e.Kind == InputKind.KeyUp && e.Key == pending.Key),
                _ => false,
            };
            if (held)
            {
                try
                {
                    _game.Input.Send(pending);
                }
                catch (Exception e) when (e is not OutOfMemoryException)
                {
                    // The game is failing anyway; the report carries the first error.
                }
                sent.Add(pending);
            }
        }
    }

    bool IConditionContext.HasProbe(string name) => _game.Probes.ContainsKey(name);

    RunValue IConditionContext.Probe(string name, IReadOnlyList<string> args) =>
        _game.Probes.TryGetValue(name, out var p) ? p.Eval(args) : throw new ScriptFault($"unknown probe {name}");

    long? IConditionContext.Constant(string name) => _game.Constants.TryGetValue(name, out var v) ? v : null;
}