feat(pbs): integrate explicit runtime Random handles
This commit is contained in:
+271
@@ -0,0 +1,271 @@
|
||||
package p.studio.compiler.backend.irvm;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import p.studio.compiler.pbs.PbsFrontendCompiler;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class PbsRuntimeRandomTest {
|
||||
static String sdk() throws Exception {
|
||||
try (var stream = PbsFrontendCompiler.class.getResourceAsStream("/game/stdlib/1/sdk/random/main.pbs")) {
|
||||
assertNotNull(stream);
|
||||
return new String(stream.readAllBytes(), java.nio.charset.StandardCharsets.UTF_8);
|
||||
}
|
||||
}
|
||||
@Test void mixedCallsPreserveAliasing() throws Exception {
|
||||
for (var suffix : new String[]{"", "-optimized"}) {
|
||||
PbsRuntimeAlignmentTest.compile("random-mixed"+suffix, sdk()+"""
|
||||
declare service Probe {
|
||||
fn main() -> (a: float, b: long, c: long) {
|
||||
let rng = random.new(42 as long);
|
||||
let alias = rng;
|
||||
random.next(rng);
|
||||
let a = random.nextf(alias);
|
||||
let b = random.range(rng, -7 as long, -6 as long);
|
||||
let c = random.next(alias);
|
||||
return (a: a, b: b, c: c);
|
||||
}
|
||||
}
|
||||
""");
|
||||
}
|
||||
}
|
||||
|
||||
private static void pair(String name, String source) throws Exception {
|
||||
for (var suffix : new String[]{"", "-optimized"})
|
||||
compile("random-"+name+suffix, source);
|
||||
}
|
||||
static void compile(String name, String source) throws Exception {
|
||||
var diagnostics = p.studio.compiler.source.diagnostics.DiagnosticSink.empty();
|
||||
var sdkId = new p.studio.compiler.source.identifiers.FileId(1);
|
||||
var fileId = new p.studio.compiler.source.identifiers.FileId(0);
|
||||
var names = new p.studio.compiler.source.tables.NameTable();
|
||||
var modules = p.studio.utilities.structures.ReadOnlyList.from(
|
||||
new p.studio.compiler.source.tables.ModuleReference("test",p.studio.utilities.structures.ReadOnlyList.from("client")),
|
||||
new p.studio.compiler.source.tables.ModuleReference("sdk",p.studio.utilities.structures.ReadOnlyList.from("random")));
|
||||
var sdkAst = p.studio.compiler.pbs.parser.PbsParser.parse(p.studio.compiler.pbs.lexer.PbsLexer.lex(sdk(),sdkId,diagnostics), sdkId,diagnostics,p.studio.compiler.pbs.parser.PbsParser.ParseMode.INTERFACE_MODULE);
|
||||
var provider = new PbsFrontendCompiler().compileParsedFile(sdkId,sdkAst,diagnostics,p.studio.compiler.models.SourceKind.SDK_INTERFACE,
|
||||
new p.studio.compiler.source.identifiers.ModuleId(1),modules,
|
||||
p.studio.compiler.messages.HostAdmissionContext.permissiveDefault(),p.studio.compiler.messages.FESurfaceContext.empty(),names);
|
||||
var imported = new java.util.ArrayList<PbsFrontendCompiler.ImportedCallableSurface>();
|
||||
for (var signature : provider.callableSignatures()) {
|
||||
var executable = provider.executableFunctions().stream().filter(f -> f.callableName().equals(signature.callableName())).findFirst().orElseThrow();
|
||||
var method = signature.callableName().substring(signature.callableName().lastIndexOf('.')+1);
|
||||
String type = switch(method) { case "new" -> "Random"; case "nextf" -> "float"; case "$instance" -> "random"; default -> "long"; };
|
||||
imported.add(new PbsFrontendCompiler.ImportedCallableSurface(new p.studio.compiler.source.identifiers.ModuleId(1), signature.callableName(), signature.arity(), executable.returnSlots(),
|
||||
p.studio.compiler.pbs.ast.PbsAst.ReturnKind.PLAIN, p.studio.compiler.pbs.ast.PbsAst.TypeRef.simple(type,sdkAst.span()),signature.typeShape()));
|
||||
}
|
||||
var ast = p.studio.compiler.pbs.parser.PbsParser.parse(p.studio.compiler.pbs.lexer.PbsLexer.lex(source,fileId,diagnostics),fileId,diagnostics,p.studio.compiler.pbs.parser.PbsParser.ParseMode.INTERFACE_MODULE);
|
||||
var file = new PbsFrontendCompiler().compileParsedFile(fileId,ast,diagnostics,p.studio.compiler.models.SourceKind.PROJECT,
|
||||
new p.studio.compiler.source.identifiers.ModuleId(0),modules,
|
||||
p.studio.compiler.messages.HostAdmissionContext.permissiveDefault(),p.studio.compiler.messages.FESurfaceContext.empty(),names,
|
||||
sdkAst.topDecls(),p.studio.utilities.structures.ReadOnlyList.wrap(imported),p.studio.utilities.structures.ReadOnlyList.empty(),provider.reservedMetadata(),java.util.Map.of());
|
||||
assertFalse(diagnostics.hasErrors(), () -> name+": "+diagnostics.stream().map(d->d.getCode()+":"+d.getMessage()).toList());
|
||||
var functions = new java.util.ArrayList<>(file.executableFunctions().asList());
|
||||
var signatures = new java.util.ArrayList<>(file.callableSignatures().asList());
|
||||
String entry = "Probe.main";
|
||||
var initializer = functions.stream().filter(f -> f.callableName().startsWith("__pbs.file_init$")).findFirst();
|
||||
if (initializer.isPresent()) {
|
||||
var main = functions.stream().filter(f->f.callableName().equals("Probe.main")).findFirst().orElseThrow();
|
||||
var init = initializer.get();
|
||||
var id = new p.studio.compiler.source.identifiers.CallableId(signatures.size());
|
||||
entry = "$test.entry";
|
||||
int returns = main.returnSlots();
|
||||
signatures.add(new p.studio.compiler.source.tables.CallableSignatureRef(new p.studio.compiler.source.identifiers.ModuleId(0),entry,0,"test"));
|
||||
var instructions = p.studio.utilities.structures.ReadOnlyList.from(
|
||||
new p.studio.compiler.models.IRBackendExecutableFunction.Instruction(p.studio.compiler.models.IRBackendExecutableFunction.InstructionKind.CALL_FUNC,
|
||||
new p.studio.compiler.source.identifiers.ModuleId(0),init.callableName(),init.callableId(),null,null,0,0,init.span()),
|
||||
new p.studio.compiler.models.IRBackendExecutableFunction.Instruction(p.studio.compiler.models.IRBackendExecutableFunction.InstructionKind.CALL_FUNC,
|
||||
new p.studio.compiler.source.identifiers.ModuleId(0),main.callableName(),main.callableId(),null,null,0,returns,main.span()),
|
||||
new p.studio.compiler.models.IRBackendExecutableFunction.Instruction(p.studio.compiler.models.IRBackendExecutableFunction.InstructionKind.RET,"",null,null,main.span()));
|
||||
functions.add(new p.studio.compiler.models.IRBackendExecutableFunction(fileId,new p.studio.compiler.source.identifiers.ModuleId(0),entry,id,0,0,0,0,returns,returns,instructions,main.span(),main.metadata()));
|
||||
}
|
||||
var client = new p.studio.compiler.models.IRBackendFile(file.fileId(),file.functions(),file.syntheticFunctions(),file.globals(),
|
||||
p.studio.utilities.structures.ReadOnlyList.wrap(functions),file.reservedMetadata(),file.modulePool(),
|
||||
p.studio.utilities.structures.ReadOnlyList.wrap(signatures),file.intrinsicPool(),null,file.registry());
|
||||
var aggregator = p.studio.compiler.models.IRBackend.aggregator();
|
||||
aggregator.merge(provider); aggregator.merge(client);
|
||||
var backend = aggregator.entryPointCallableName(entry).entryPointModuleId(new p.studio.compiler.source.identifiers.ModuleId(0)).emit();
|
||||
var program = new LowerToIRVMService().lower(backend);
|
||||
if(name.endsWith("-optimized")) program = new OptimizeIRVMService().optimize(program);
|
||||
var module = new p.studio.compiler.backend.bytecode.BytecodeEmitter().emit(program.coherentEmissionPlan());
|
||||
if (name.startsWith("random-gc")) module = PbsStructuredValuesTest.withTestSafepoint(module);
|
||||
new p.studio.compiler.backend.bytecode.BytecodePreloadVerifierService().verify(module);
|
||||
java.nio.file.Files.write(java.nio.file.Path.of(System.getProperty("pbs.registryConformanceDirectory"),"pbs-"+name+".pbx"),module.serialize());
|
||||
}
|
||||
@Test void providerSeedVectors() throws Exception {
|
||||
String corpus;
|
||||
try (var stream = PbsRuntimeRandomTest.class.getResourceAsStream("/random/random-conformance.tsv")) {
|
||||
assertNotNull(stream);
|
||||
corpus = new String(stream.readAllBytes(), java.nio.charset.StandardCharsets.UTF_8);
|
||||
}
|
||||
var manifest = new StringBuilder();
|
||||
int index = 0;
|
||||
for (var row : corpus.lines().skip(1).toList()) {
|
||||
var parts = row.split("\\s+");
|
||||
for (var kind : new String[]{"next", "nextf"}) {
|
||||
String type = kind.equals("next") ? "long" : "float";
|
||||
int draw = Integer.parseInt(parts[1]);
|
||||
String name = "vector-"+index++;
|
||||
pair(name, "declare service Probe { fn main() -> "+type+" { let seed: long = "+parts[0]+"; let rng = random.new(seed); "
|
||||
+ "random.next(rng);".repeat(draw-1)+"return random."+kind+"(rng); } }");
|
||||
for (var suffix : new String[]{"", "-optimized"})
|
||||
manifest.append("pbs-random-").append(name).append(suffix).append(" ")
|
||||
.append(kind.equals("next") ? "l:"+parts[3] : "f:"+parts[4].toLowerCase())
|
||||
.append(" ").append(draw).append("\n");
|
||||
}
|
||||
}
|
||||
assertEquals(96, index);
|
||||
java.nio.file.Files.writeString(java.nio.file.Path.of(System.getProperty("pbs.registryConformanceDirectory"), "random-vectors.tsv"), manifest);
|
||||
}
|
||||
@Test void storageAndIndependentStreams() throws Exception {
|
||||
pair("storage", """
|
||||
declare struct Empty(pub value: Random) { ctor create() {} } declare global saved: Random = new Empty.create().value;
|
||||
declare struct Box(pub value: Random);
|
||||
fn echo(rng: Random) -> Random { return rng; }
|
||||
fn capture(rng: Random) -> Fn() -> long { return fn [rng]() -> long { return random.next(rng); }; }
|
||||
declare service Probe {
|
||||
fn main() -> (a: long, b: long, c: long, d: long, e: long) {
|
||||
let rng = random.new(42 as long);
|
||||
saved = echo(rng);
|
||||
let box = new Box(saved);
|
||||
let values: array Random = [box.value];
|
||||
let draw = capture(rng);
|
||||
let a = random.next(saved);
|
||||
let b = random.next(box.value);
|
||||
if let value = values[0] {
|
||||
let c = random.next(value);
|
||||
let d = draw();
|
||||
let other = random.new(42 as long);
|
||||
let e = random.next(other);
|
||||
return (a: a, b: b, c: c, d: d, e: e);
|
||||
}
|
||||
return (0 as long, 0 as long, 0 as long, 0 as long, 0 as long);
|
||||
}
|
||||
}
|
||||
""");
|
||||
pair("named", """
|
||||
declare global trace: int = 0;
|
||||
declare struct Empty(pub value: Random) { ctor create() {} } declare global rng: Random = new Empty.create().value;
|
||||
declare service Probe {
|
||||
fn receiver() -> Random { trace = trace * 10 + 1; return rng; }
|
||||
fn low() -> long { trace = trace * 10 + 2; random.next(rng); return -7; }
|
||||
fn high() -> long { trace = trace * 10 + 3; random.next(rng); return -6; }
|
||||
fn main() -> (trace: int, value: long, next: long) {
|
||||
rng = random.new(42 as long); trace = 0;
|
||||
let value = random.range apply (max: Probe.high(), rng: Probe.receiver(), min: Probe.low());
|
||||
return (trace: trace, value: value, next: random.next(rng));
|
||||
}
|
||||
}
|
||||
""");
|
||||
pair("positional", """
|
||||
declare global trace: int = 0;
|
||||
declare struct Empty(pub value: Random) { ctor create() {} } declare global rng: Random = new Empty.create().value;
|
||||
declare service Probe {
|
||||
fn receiver() -> Random { trace = trace * 10 + 1; return rng; }
|
||||
fn low() -> long { trace = trace * 10 + 2; random.next(rng); return -7; }
|
||||
fn high() -> long { trace = trace * 10 + 3; random.next(rng); return -6; }
|
||||
fn main() -> (trace: int, value: long, next: long) {
|
||||
rng = random.new(42 as long); trace = 0;
|
||||
let value = random.range(Probe.receiver(), Probe.low(), Probe.high());
|
||||
return (trace: trace, value: value, next: random.next(rng));
|
||||
}
|
||||
}
|
||||
""");
|
||||
}
|
||||
@Test void rangeBoundsAndNullDefaults() throws Exception {
|
||||
String[][] bounds = {{"0","1"},{"-10","-3"},{"-10","10"},{"0","16"},
|
||||
{"-9223372036854775808","0"},{"-1","9223372036854775807"},{"-9223372036854775808","9223372036854775807"},
|
||||
{"5","5"},{"6","5"}};
|
||||
for (int i=0; i<bounds.length; i++)
|
||||
pair("range-"+i, "declare service Probe { fn main() -> long { let rng = random.new(42 as long); let low: long = "+bounds[i][0]+"; let high: long = "+bounds[i][1]+"; return random.range(rng, low, high); } }");
|
||||
pair("rejection", """
|
||||
declare service Probe { fn main() -> (value: long, next: long) {
|
||||
let rng = random.new(42 as long); random.next(rng);
|
||||
let low: long = -9223372036854775808; let value = random.range(rng, low, 1 as long);
|
||||
return (value: value, next: random.next(rng));
|
||||
} }
|
||||
""");
|
||||
pair("null", "declare struct Empty(pub value: Random) { ctor create() {} } declare global empty: Random = new Empty.create().value; declare service Probe { fn main() -> long { return random.next(empty); } }");
|
||||
pair("typed-null", """
|
||||
declare struct Empty(pub value: Random) { ctor create() {} } declare global empty: Random = new Empty.create().value;
|
||||
declare service Probe { fn main() -> long {
|
||||
let values: array Random = [empty];
|
||||
if let value = values[0] { return random.next(value); }
|
||||
return 99;
|
||||
} }
|
||||
""");
|
||||
}
|
||||
@Test void incompatibleSourceCannotConstructOrAdaptRandom() throws Exception {
|
||||
for (var body : new String[]{"new Random();", "random.new(true);", "let seed: int = 42; random.new(seed);",
|
||||
"random.next(42);", "random.nextf(1.0);", "let rng = random.new(42 as long); random.range(rng, true, 2 as long);"}) {
|
||||
var diagnostics = p.studio.compiler.source.diagnostics.DiagnosticSink.empty();
|
||||
new PbsFrontendCompiler().compileFile(new p.studio.compiler.source.identifiers.FileId(0),
|
||||
sdk()+"declare service Probe { fn main() { "+body+" } }", diagnostics, p.studio.compiler.models.SourceKind.SDK_INTERFACE);
|
||||
assertTrue(diagnostics.hasErrors(), body);
|
||||
}
|
||||
}
|
||||
|
||||
@Test void installedSdkImportsAndAliases(@org.junit.jupiter.api.io.TempDir java.nio.file.Path root) throws Exception {
|
||||
java.nio.file.Files.createDirectories(root.resolve("src"));
|
||||
java.nio.file.Files.writeString(root.resolve("prometeu.json"), """
|
||||
{"name":"app","version":"1.0.0","language":"pbs","stdlib":"1","target":"Game","dependencies":[]}
|
||||
""");
|
||||
java.nio.file.Files.writeString(root.resolve("src/mod.barrel"), "pub fn frame() -> void;");
|
||||
java.nio.file.Files.writeString(root.resolve("src/main.pbs"), """
|
||||
import { Random as Generator, random as rng } from @sdk:random;
|
||||
fn echo(value: Generator) -> Generator { return value; }
|
||||
[Frame]
|
||||
fn frame() -> void {
|
||||
let generator: Generator = rng.new(42 as long);
|
||||
let expected: long = -8740965581747508376;
|
||||
if rng.next(echo(generator)) != expected { let fail = 1 / 0; }
|
||||
if rng.range(generator, -7 as long, -6 as long) != -7 as long { let fail = 1 / 0; }
|
||||
}
|
||||
""");
|
||||
var result = p.studio.compiler.workspaces.BuilderPipelineService.INSTANCE.compile(
|
||||
p.studio.compiler.models.BuilderPipelineContext.fromConfig(new p.studio.compiler.messages.BuilderPipelineConfig(false,root.toString())),
|
||||
p.studio.utilities.logs.LogAggregator.stdout());
|
||||
assertFalse(result.diagnostics().stream().anyMatch(d->d.isError()),result.diagnostics().toString());
|
||||
assertTrue(result.bytecodeBytes().length>0);
|
||||
java.nio.file.Files.write(java.nio.file.Path.of(System.getProperty("pbs.registryConformanceDirectory"),"pbs-random-import.pbx"),result.bytecodeBytes());
|
||||
}
|
||||
|
||||
@Test void referencesSurviveCollection() throws Exception {
|
||||
pair("gc", """
|
||||
declare struct Box(pub value: Random);
|
||||
fn make() -> (items: array Random, draw: Fn() -> long, box: Box) {
|
||||
let rng = random.new(42 as long);
|
||||
let items: array Random = [rng];
|
||||
let draw = fn [rng]() -> long { return random.next(rng); };
|
||||
return (items: items, draw: draw, box: new Box(rng));
|
||||
}
|
||||
declare service Probe {
|
||||
fn garbage() { random.new(1 as long); }
|
||||
fn collect() { let marker = 314159; }
|
||||
fn main() -> (a: long, b: long, c: long) {
|
||||
let roots = make();
|
||||
for i: int from 0 until 1100 { Probe.garbage(); }
|
||||
Probe.collect();
|
||||
if let rng = roots.items[0] {
|
||||
let a = random.next(rng);
|
||||
let draw = roots.draw;
|
||||
let b = draw();
|
||||
let c = random.next(roots.box.value);
|
||||
return (a: a, b: b, c: c);
|
||||
}
|
||||
return (0 as long, 0 as long, 0 as long);
|
||||
}
|
||||
}
|
||||
""");
|
||||
}
|
||||
|
||||
@Test void opaqueValuesRejectFieldsAndStructuralAdaptation() throws Exception {
|
||||
for (var source : new String[]{
|
||||
"declare service Probe { fn main() -> long { let rng = random.new(42 as long); return rng.state; } }",
|
||||
"declare struct Box(pub n: long); declare service Probe { fn main() -> Box { return random.new(42 as long); } }",
|
||||
"declare contract Draw { fn draw() -> long; } declare service Probe { fn main() -> Draw { return random.new(42 as long); } }",
|
||||
"declare contract Draw { fn draw() -> long; } declare service Probe { fn main() -> Draw { let rng = random.new(42 as long); return rng as Draw; } }"}) {
|
||||
var failure = assertThrows(org.opentest4j.AssertionFailedError.class, () -> compile("invalid", source), source);
|
||||
assertTrue(failure.getMessage().contains("E_SEM_"), failure.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -56,7 +56,7 @@ class PbsStructuredValuesTest {
|
||||
// PBS sync/closure syntax belongs to AGD82. This test-only driver hook replaces
|
||||
// an isolated marker assignment with FRAME_SYNC + NOPs, preserving every offset.
|
||||
// All allocations, roots, field/array access and post-GC assertions are compiled PBS.
|
||||
private static BytecodeModule withTestSafepoint(BytecodeModule module) {
|
||||
static BytecodeModule withTestSafepoint(BytecodeModule module) {
|
||||
byte[] code = module.code().clone();
|
||||
var marker = java.nio.ByteBuffer.allocate(6).order(java.nio.ByteOrder.LITTLE_ENDIAN)
|
||||
.putShort((short) 0x17).putInt(314159).array();
|
||||
|
||||
Reference in New Issue
Block a user