feat(pbs): add explicit guest lifecycle hooks

This commit is contained in:
2026-10-28 09:12:48 +00:00
parent eb7d6a2398
commit 9504f4694a
41 changed files with 1209 additions and 24 deletions
@@ -0,0 +1,157 @@
package p.studio.compiler.backend.irvm;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import p.studio.compiler.backend.bytecode.*;
import p.studio.compiler.lifecycle.LifecycleAssemblerService;
import p.studio.compiler.messages.*;
import p.studio.compiler.models.*;
import p.studio.compiler.models.registry.IRRegistry;
import p.studio.compiler.pbs.PbsFrontendCompiler;
import p.studio.compiler.pbs.lexer.PbsLexer;
import p.studio.compiler.pbs.parser.PbsParser;
import p.studio.compiler.source.diagnostics.DiagnosticSink;
import p.studio.compiler.source.identifiers.*;
import p.studio.compiler.source.tables.*;
import p.studio.utilities.structures.ReadOnlyList;
import java.nio.file.*;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
class PbsGuestLifecycleTest {
private static Path directory() { return Path.of(System.getProperty("pbs.registryConformanceDirectory")); }
private static final String BASE = """
declare global trace: int = 0;
declare global inits: int = 0;
declare global stage: int = 0;
declare global kept: array<int> = new array<int>(1);
fn BeforePause() -> void {}
fn BeforeResume() -> void {}
[Init] fn init() -> void { inits += 1; stage = 10; kept[0] = 7; }
fn effect(delta: int) -> void {
let action = fn [delta]() -> int { return delta; };
kept[0] = (kept[0] else 0) + action();
}
fn readTrace() -> int { return trace * 10000 + inits * 100 + (kept[0] else 0); }
[Frame] fn frame() -> void {
if inits != 1 or stage == 20 { let fail = 1 / 0; }
stage = 10;
FRAME_BODY
}
""";
private static String pause() { return """
[BeforePause] fn arbitraryPauseName() -> void {
if stage != 10 { let fail = 1 / 0; }
stage = 20; trace = trace * 10 + 2; effect(2);
}
"""; }
private static String resume(boolean hasPause) { return """
[BeforeResume] fn arbitraryResumeName() -> void {
if stage != EXPECTED { let fail = 1 / 0; }
stage = 30; trace = trace * 10 + 3; effect(3);
}
""".replace("EXPECTED", hasPause ? "20" : "10"); }
private static void compile(String name, String source, boolean pause, boolean resume) throws Exception {
var diagnostics = DiagnosticSink.empty(); var id = new FileId(0); var moduleId = new ModuleId(0);
var ast = PbsParser.parse(PbsLexer.lex(source, id, diagnostics), id, diagnostics);
var file = new PbsFrontendCompiler().compileParsedFile(id, ast, diagnostics, SourceKind.PROJECT, moduleId,
ReadOnlyList.from(new ModuleReference("test", ReadOnlyList.from("main"))),
HostAdmissionContext.permissiveDefault(), FESurfaceContext.empty(), new NameTable());
assertFalse(diagnostics.hasErrors(), () -> diagnostics.stream().map(d -> d.getCode()+":"+d.getMessage()).toList().toString());
var aggregator = IRBackend.aggregator(); aggregator.merge(file);
var backend = aggregator.lifecycleModuleOrder(ReadOnlyList.from(moduleId)).emit();
var issues = BuildingIssueSink.empty();
var assembled = new LifecycleAssemblerService().assemble(backend, issues);
assertFalse(issues.hasErrors(), issues.asCollection().toString());
Files.createDirectories(directory());
Files.writeString(directory().resolve("pbs-lifecycle-"+name+".pbs"), source);
for (boolean optimize : new boolean[]{false, true}) {
var program = new LowerToIRVMService().lower(assembled);
if (optimize) program = new OptimizeIRVMService().optimize(program);
var output = new BytecodeEmitter().emit(program.coherentEmissionPlan());
assertEquals(IRRegistry.Role.NONE, output.functions().get(0).metadata().role());
for (var role : List.of(IRRegistry.Role.BEFORE_PAUSE, IRRegistry.Role.BEFORE_RESUME)) {
int found = 0;
for (int i = 0; i < output.functions().size(); i++) {
var metadata = output.functions().get(i).metadata();
if (metadata.role() != role) continue;
found++; assertNotEquals(0, i);
assertTrue(metadata.signature().parameters().isEmpty());
assertTrue(metadata.signature().results().isEmpty());
assertTrue(metadata.captures().isEmpty());
}
assertEquals((role == IRRegistry.Role.BEFORE_PAUSE ? pause : resume) ? 1 : 0, found);
}
new BytecodePreloadVerifierService().verify(output);
var prefix = "pbs-lifecycle-"+name+(optimize ? "-optimized" : "");
Files.write(directory().resolve(prefix+".pbx"), output.serialize());
for (int i = 0; i < program.module().functions().size(); i++) {
if (program.module().functions().get(i).name().contains("readTrace")) {
Files.writeString(directory().resolve(prefix+".probe"), Integer.toString(i));
}
}
if (pause || resume) assertTrue(program.module().functions().stream().anyMatch(f -> f.name().contains("effect")));
}
}
@Test void sourceHooksSurviveAssemblyOptimizationAndExecuteWithNoCallers() throws Exception {
for (var name : List.of("both", "pause", "resume", "none")) {
boolean p = name.equals("both") || name.equals("pause"), r = name.equals("both") || name.equals("resume");
// A pause-only image legitimately resumes without a hook resetting its guest stage.
var base = BASE.replace("FRAME_BODY", "");
if (!r) base = base.replace(" or stage == 20", "");
compile(name, base + (p ? pause() : "") + (r ? resume(p) : ""), p, r);
}
compile("direct", BASE.replace("FRAME_BODY", "arbitraryPauseName(); arbitraryResumeName();") + pause() + resume(true), true, true);
compile("trap", BASE.replace("FRAME_BODY", "") + pause().replace("effect(2);", "effect(2); let fail = 1 / 0;") + resume(true), true, true);
compile("fuel", BASE.replace("FRAME_BODY", "") + pause().replace("effect(2);", "effect(2); while true { stage = 20; }") + resume(true), true, true);
compile("slices", BASE.replace("FRAME_BODY", "") + pause().replace("effect(2);", "effect(2); for i: int from 0 until 20000 { stage = 20; }") + resume(true), true, true);
}
@Test void importedHooksAreUniqueByDeclarationAndDoNotRequireFrameColocation(@TempDir Path root) throws Exception {
Files.createDirectories(root.resolve("src/hooks")); Files.createDirectories(root.resolve("src/facade"));
Files.writeString(root.resolve("prometeu.json"), """
{"name":"app","version":"1.0.0","language":"pbs","stdlib":"1","target":"Game","dependencies":[]}
""");
Files.writeString(root.resolve("src/mod.barrel"), "pub fn frame() -> void;");
Files.writeString(root.resolve("src/hooks/mod.barrel"), "pub fn selected() -> void;");
Files.writeString(root.resolve("src/hooks/main.pbs"), "[BeforePause] fn selected() -> void {}");
Files.writeString(root.resolve("src/facade/mod.barrel"), "pub fn selected() -> void;");
Files.writeString(root.resolve("src/facade/main.pbs"), "import { selected } from @app:hooks;");
Files.writeString(root.resolve("src/main.pbs"), """
import { selected as first } from @app:hooks;
import { selected as second } from @app:facade;
[Frame] fn frame() -> void {}
""");
var result = project(root);
assertFalse(result.diagnostics().stream().anyMatch(d -> d.isError()), result.diagnostics().toString());
Files.write(directory().resolve("pbs-lifecycle-imports.pbx"), result.bytecodeBytes());
Files.writeString(root.resolve("src/duplicate.pbs"), "[BeforePause] fn conflicting() -> void {}");
var conflict = p.studio.compiler.workspaces.BuilderPipelineService.INSTANCE.analyze(
BuilderPipelineContext.fromConfig(new BuilderPipelineConfig(false, root.toString())), p.studio.utilities.logs.LogAggregator.empty());
assertTrue(conflict.diagnostics().stream().anyMatch(d -> d.isError() && d.getMessage().contains("BeforePause")), conflict.diagnostics().toString());
}
private static CompileResult project(Path root) {
return p.studio.compiler.workspaces.BuilderPipelineService.INSTANCE.compile(
BuilderPipelineContext.fromConfig(new BuilderPipelineConfig(false, root.toString())), p.studio.utilities.logs.LogAggregator.empty());
}
@Test void syntheticPbxSyncFixturesCoverDirectAndTransitiveRejection() throws Exception {
// Independently labeled binary fixtures: PBS intentionally has no sync syntax.
for (boolean transitive : new boolean[]{false, true}) {
byte[] code = transitive ? new byte[]{0x51,0, 0x50,0,2,0,0,0, 0x51,0, (byte)0x80,0, 0x51,0}
: new byte[]{0x51,0, (byte)0x80,0, 0x51,0};
var functions = new java.util.ArrayList<BytecodeModule.FunctionMeta>();
functions.add(new BytecodeModule.FunctionMeta(0,2,0,0,0,0,IRRegistry.FunctionMetadata.empty()));
functions.add(new BytecodeModule.FunctionMeta(2,transitive ? 8 : 4,0,0,0,0,
new IRRegistry.FunctionMetadata(IRRegistry.Signature.empty(),null,IRRegistry.Role.BEFORE_PAUSE)));
if (transitive) functions.add(new BytecodeModule.FunctionMeta(10,4,0,0,0,0,IRRegistry.FunctionMetadata.empty()));
var module = new BytecodeModule(0,null,ReadOnlyList.wrap(functions),code,null,null,null,IRRegistry.empty());
new BytecodePreloadVerifierService().verify(module);
Files.createDirectories(directory());
Files.write(directory().resolve("synthetic-lifecycle-sync-"+(transitive ? "transitive" : "direct")+".pbx"),module.serialize());
}
}
}