feat(diagnostics): VM emits trace events + CallScriptDispatches stat

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
gamer147
2026-07-07 15:21:28 -04:00
parent 10cf79a41b
commit e010393b8a
6 changed files with 99 additions and 16 deletions

View File

@@ -1,10 +1,17 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Age.Engine.Diagnostics;
using Age.Engine.Model;
using Age.Engine.Sys4;
using Age.Engine.Vm;
using Xunit;
public class TraceSinkTests
{
private static OpcodeTable Table() => OpcodeTableJson.Load(Paths.OpcodesJson);
[Fact]
public void FactoriesSetKindAndFields()
{
@@ -41,4 +48,49 @@ public class TraceSinkTests
Assert.Contains("call-script 0x1ab =ADDITEM (resolved)", outp);
Assert.Contains("halt: exit @ 27994 steps", outp);
}
[Fact]
public void VmEmitsFrameCallScriptAndHaltEvents()
{
var t = Table();
// callee: exit. caller: call-script 5 ; exit.
var callee = ScriptAssembler.Assemble(t, "CALLEE",
new List<(int, Operand[])> { (0x2, Array.Empty<Operand>()) }, Array.Empty<string>());
var caller = ScriptAssembler.Assemble(t, "CALLER",
new List<(int, Operand[])> { (0x3, new[] { new Operand(0, 5) }), (0x2, Array.Empty<Operand>()) },
Array.Empty<string>());
var sink = new RecordingTraceSink();
var vm = new VirtualMachine(caller, t, new RecordingHost(), null,
new MapProvider(new() { [5] = callee }), sink);
vm.Run();
var kinds = sink.Events.Select(e => e.Kind).ToList();
Assert.Equal(TraceEventKind.FrameEnter, kinds[0]); // caller enters first
Assert.Equal(TraceEventKind.Halt, kinds[^1]); // halt is last
Assert.Equal(2, sink.Events.Count(e => e.Kind == TraceEventKind.FrameEnter)); // caller + callee
Assert.Equal(2, sink.Events.Count(e => e.Kind == TraceEventKind.FrameExit));
Assert.Contains(5L, sink.CallScriptIds);
Assert.Equal(1, vm.CallScriptDispatches);
}
[Fact]
public void StepEventsGatedByTracingSteps()
{
var t = Table();
// mov g[0x10]=7 ; exit => 2 executed instructions.
var body = new List<(int, Operand[])>
{
(0x55, new[] { new Operand(3, 0x10), new Operand(0, 7) }),
(0x2, Array.Empty<Operand>()),
};
var s = ScriptAssembler.Assemble(t, "S", body, Array.Empty<string>());
var off = new RecordingTraceSink { TracingSteps = false };
new VirtualMachine(s, t, new RecordingHost(), null, null, off).Run();
Assert.Empty(off.Events.Where(e => e.Kind == TraceEventKind.Step));
var on = new RecordingTraceSink { TracingSteps = true };
new VirtualMachine(s, t, new RecordingHost(), null, null, on).Run();
Assert.Equal(2, on.Events.Count(e => e.Kind == TraceEventKind.Step));
}
}