feat(pbs): add service constants and runtime math integration

This commit is contained in:
2026-10-17 11:21:58 +01:00
parent 2a418085d2
commit d1e9259085
32 changed files with 1117 additions and 40 deletions
@@ -16,17 +16,21 @@ class PbsRuntimeAlignmentTest {
assertNotNull(stream); return new String(stream.readAllBytes(), java.nio.charset.StandardCharsets.UTF_8);
}
}
private static BytecodeModule compile(String name,String source) throws Exception {
static BytecodeModule compile(String name,String source) throws Exception {
return compile(name, source, SourceKind.SDK_INTERFACE);
}
static BytecodeModule compile(String name,String source,SourceKind sourceKind) throws Exception {
var diagnostics=DiagnosticSink.empty();
var fileId = new FileId(0);
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,SourceKind.SDK_INTERFACE,
var file=new PbsFrontendCompiler().compileParsedFile(fileId,ast,diagnostics,sourceKind,
new p.studio.compiler.source.identifiers.ModuleId(0),p.studio.utilities.structures.ReadOnlyList.empty(),
p.studio.compiler.messages.HostAdmissionContext.permissiveDefault(),p.studio.compiler.messages.FESurfaceContext.empty(),new p.studio.compiler.source.tables.NameTable());
assertFalse(diagnostics.hasErrors(), ()->diagnostics.stream().map(d->d.getCode()+":"+d.getMessage()).toList().toString());
var backend=IRBackend.builder().entryPointCallableName("Probe.main").entryPointModuleId(new p.studio.compiler.source.identifiers.ModuleId(0)).executableFunctions(file.executableFunctions())
.globals(file.globals()).registry(file.registry()).intrinsicPool(file.intrinsicPool()).callableSignatures(file.callableSignatures()).build();
var program=new LowerToIRVMService().lower(backend);
if (name.endsWith("-optimized")) program = new OptimizeIRVMService().optimize(program);
var module=new BytecodeEmitter().emit(program.coherentEmissionPlan());
new BytecodePreloadVerifierService().verify(module);
var directory=Path.of(System.getProperty("pbs.registryConformanceDirectory"));Files.createDirectories(directory);
@@ -0,0 +1,129 @@
package p.studio.compiler.backend.irvm;
import org.junit.jupiter.api.Test;
import p.studio.compiler.pbs.PbsFrontendCompiler;
import p.studio.compiler.source.diagnostics.DiagnosticSink;
import p.studio.compiler.source.identifiers.FileId;
import p.studio.compiler.models.SourceKind;
import static org.junit.jupiter.api.Assertions.*;
class PbsRuntimeMathTest {
static String sdk() throws Exception {
var result = new StringBuilder();
for (var name : new String[]{"math", "mathf"}) {
try (var stream = PbsFrontendCompiler.class.getResourceAsStream("/game/stdlib/1/sdk/"+name+"/main.pbs")) {
assertNotNull(stream);
result.append(new String(stream.readAllBytes(), java.nio.charset.StandardCharsets.UTF_8));
}
}
return result.toString();
}
@Test void constantsAndOverloadsCompile() throws Exception {
PbsRuntimeAlignmentTest.compile("math-pi", sdk()+"declare service Probe { fn main() -> float { return mathf.pi; } }");
PbsRuntimeAlignmentTest.compile("math-tau", sdk()+"declare service Probe { fn main() -> float { return mathf.tau; } }");
PbsRuntimeAlignmentTest.compile("math-literal", sdk()+"declare service Probe { fn main() -> float { return mathf.sin(-0.0); } }");
PbsRuntimeAlignmentTest.compile("math-long", "declare service Settings { declare const limit: long = 2147483648; } declare service Probe { fn main() -> long { return Settings.limit; } }");
PbsRuntimeAlignmentTest.compile("math-min", sdk()+"declare service Probe { fn main() -> long { let a: long = 42; let b: long = 55; return math.min(a,b); } }");
PbsRuntimeAlignmentTest.compile("math-service", "declare service Settings { declare const answer: int = 42; } declare service Probe { fn main() -> int { return Settings.answer; } }");
}
@Test void invalidMembersAndMixedCarriersReject() throws Exception {
for (var body : new String[]{"return math.min(1, 2 as long);", "return mathf.sin(1);", "mathf.pi = 3.0; return 0;"}) {
var diagnostics = DiagnosticSink.empty();
new PbsFrontendCompiler().compileFile(new FileId(0),sdk()+"declare service Probe { fn main() -> int { "+body+" } }",diagnostics,SourceKind.SDK_INTERFACE);
assertTrue(diagnostics.hasErrors(), body);
}
}
@Test void providerCorpusCompilesEverySignatureFromSource() throws Exception {
var directory = java.nio.file.Path.of(System.getProperty("pbs.registryConformanceDirectory"));
String corpus;
try (var stream = getClass().getResourceAsStream("/math/numeric-source.tsv")) {
assertNotNull(stream);
corpus = new String(stream.readAllBytes(), java.nio.charset.StandardCharsets.UTF_8);
}
var manifest = new StringBuilder();
var covered = new java.util.HashSet<Integer>();
int index = 0;
for (var row : corpus.lines().toList()) {
var parts = row.split(" ");
int id = Integer.parseInt(parts[0], 16);
var definition = java.util.Arrays.stream(IRVMIntrinsicDefinition.values()).filter(d -> d.finalId() == id).findFirst().orElseThrow();
var source = new StringBuilder(sdk()).append("declare service Probe { fn main() -> ")
.append(sourceType(definition.retLayout())).append(" {");
var arguments = new java.util.ArrayList<String>();
var types = definition.argLayout().split("\\|");
for (int i = 0; i < types.length; i++) {
source.append("let a").append(i).append(": ").append(sourceType(types[i])).append(" = ")
.append(literal(parts[i+1])).append(";");
arguments.add("a"+i);
}
var name = definition.canonicalName().replace(".i32.", ".").replace(".i64.", ".");
source.append("return ").append(name).append("(").append(String.join(",",arguments)).append("); } }");
var fixture = "math-vector-" + index++;
PbsRuntimeAlignmentTest.compile(fixture, source.toString());
manifest.append("pbs-").append(fixture).append(" ").append(row).append("\n");
PbsRuntimeAlignmentTest.compile(fixture+"-optimized", source.toString());
manifest.append("pbs-").append(fixture).append("-optimized ").append(row).append("\n");
covered.add(id);
}
assertEquals(26, covered.size());
java.nio.file.Files.writeString(directory.resolve("math-vectors.tsv"), manifest);
}
private static String sourceType(String type) {
return switch(type) { case "Int32" -> "int"; case "Int64" -> "long"; case "Float" -> "float"; default -> throw new IllegalArgumentException(type); };
}
private static String literal(String token) {
if (!token.startsWith("f:")) return token.substring(2);
long bits = Long.parseUnsignedLong(token.substring(2),16);
if (bits == Long.MIN_VALUE) return "-0.0";
var result = java.math.BigDecimal.valueOf(Double.longBitsToDouble(bits)).toPlainString();
return result.contains(".") ? result : result + ".0";
}
@Test void qualifiedConstantDependenciesAndFailures() throws Exception {
PbsRuntimeAlignmentTest.compile("math-dependency", "declare global answer: int = 999; declare service Settings { declare const base: int = 40; declare const answer: int = base + 2; fn read() -> int { return answer; } } declare service Probe { fn main() -> int { answer = 999; return Settings.read(); } }", SourceKind.PROJECT);
for (var members : new String[]{
"declare const a: int = 1; declare const a: int = 2;",
"declare const a: int = Settings.b; declare const b: int = Settings.a;",
"declare const a: int = missing;",
"declare const a: int = 1; fn a() -> int { return 2; }",
"declare const a: int = true;"}) {
var diagnostics = DiagnosticSink.empty();
new PbsFrontendCompiler().compileFile(new FileId(0), "declare service Settings { "+members+" }", diagnostics);
assertTrue(diagnostics.hasErrors(), members);
}
for (var expression : new String[]{"math.min(1, 2 as long)", "mathf.sin(1)", "math.to_i64(1 as long)"}) {
var diagnostics = DiagnosticSink.empty();
new PbsFrontendCompiler().compileFile(new FileId(0),sdk()+"declare service Probe { fn main() { "+expression+"; } }",diagnostics,SourceKind.SDK_INTERFACE);
assertTrue(diagnostics.stream().anyMatch(d -> d.getMessage().contains("explicit conversion")), expression);
}
}
@Test void realModuleImportsAndAliasesProducePbx(@org.junit.jupiter.api.io.TempDir java.nio.file.Path root) throws Exception {
java.nio.file.Files.createDirectories(root.resolve("src/config"));
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/config/main.pbs"), "declare service Settings { declare const answer: int = 42; }");
java.nio.file.Files.writeString(root.resolve("src/config/mod.barrel"), "pub service Settings;");
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 { math } from @sdk:math;
import { mathf as numbers } from @sdk:mathf;
import { Settings as config } from @app:config;
[Frame]
fn frame() -> void {
if config.answer != 42 { let fail = 1 / 0; }
if numbers.pi != 3.141592653589793 { let fail = 1 / 0; }
if numbers.sin(0.0) != 0.0 { let fail = 1 / 0; }
let value: long = 42;
if math.min(value, 55 as long) != value { 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-math-import.pbx"),result.bytecodeBytes());
}
}