From d1e9259085e3a09758e46555fa110e8e2bccf30e Mon Sep 17 00:00:00 2001 From: bQUARKz Date: Sat, 17 Oct 2026 11:21:58 +0100 Subject: [PATCH] feat(pbs): add service constants and runtime math integration --- ...e-constants-and-source-math-conformance.md | 160 +++++++++++ .../service-constants-and-runtime-math.md | 118 ++++++++ .../pbs/3. Core Syntax Specification.md | 9 +- .../pbs/4. Static Semantics Specification.md | 7 +- .../backend/irvm/PbsRuntimeAlignmentTest.java | 8 +- .../backend/irvm/PbsRuntimeMathTest.java | 129 +++++++++ .../test/resources/math/numeric-source.tsv | 261 ++++++++++++++++++ .../src/test/resources/math/provenance.txt | 3 + .../pbs/PbsReservedMetadataExtractor.java | 5 + .../compiler/pbs/PbsServiceConstants.java | 30 ++ .../p/studio/compiler/pbs/ast/PbsAst.java | 5 + .../lowering/PbsExecutableBodyLowerer.java | 89 +++++- .../pbs/lowering/PbsRuntimeTypes.java | 3 + .../pbs/parser/PbsDeclarationParser.java | 18 +- .../pbs/semantics/PbsAstDocumentSymbols.java | 4 +- .../semantics/PbsConstSemanticsValidator.java | 32 ++- .../PbsDeclarationSemanticsValidator.java | 15 + .../semantics/PbsEditorialSupportService.java | 15 +- .../pbs/semantics/PbsFlowBodyAnalyzer.java | 1 + .../PbsFlowCallableResolutionAnalyzer.java | 4 +- .../pbs/semantics/PbsFlowSemanticSupport.java | 13 +- .../PbsFlowStructuralExpressionAnalyzer.java | 4 + .../PbsImportedSemanticContextService.java | 4 +- .../resources/game/stdlib/1/sdk/math/main.pbs | 29 ++ .../game/stdlib/1/sdk/math/mod.barrel | 1 + .../game/stdlib/1/sdk/mathf/main.pbs | 37 +++ .../game/stdlib/1/sdk/mathf/mod.barrel | 1 + .../examples/game/1/src/math.pbs | 8 + .../PbsEditorialSupportServiceTest.java | 9 + tools/pbx-conformance/README.md | 29 ++ tools/pbx-conformance/main.rs | 98 ++++++- tools/pbx-conformance/run.py | 8 +- 32 files changed, 1117 insertions(+), 40 deletions(-) create mode 100644 discussion/lessons/DSC-0081-pbs-runtime-math-integration/LSN-0085-service-constants-and-source-math-conformance.md create mode 100644 docs/compiler/pbs/specs/service-constants-and-runtime-math.md create mode 100644 prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsRuntimeMathTest.java create mode 100644 prometeu-architecture-tests/src/test/resources/math/numeric-source.tsv create mode 100644 prometeu-architecture-tests/src/test/resources/math/provenance.txt create mode 100644 prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/PbsServiceConstants.java create mode 100644 prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/sdk/math/main.pbs create mode 100644 prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/sdk/math/mod.barrel create mode 100644 prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/sdk/mathf/main.pbs create mode 100644 prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/sdk/mathf/mod.barrel create mode 100644 prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/pbs-knowledge/examples/game/1/src/math.pbs diff --git a/discussion/lessons/DSC-0081-pbs-runtime-math-integration/LSN-0085-service-constants-and-source-math-conformance.md b/discussion/lessons/DSC-0081-pbs-runtime-math-integration/LSN-0085-service-constants-and-source-math-conformance.md new file mode 100644 index 00000000..333f7645 --- /dev/null +++ b/discussion/lessons/DSC-0081-pbs-runtime-math-integration/LSN-0085-service-constants-and-source-math-conformance.md @@ -0,0 +1,160 @@ +--- +id: LSN-0085 +ticket: pbs-runtime-math-integration +title: Service constants and source-to-runtime math conformance +created: 2026-10-17 +tags: [runtime-integration] +--- + +## Original problem and ownership + +Owner: compiler/pbs. Supporting contract: compiler/general; runtime numeric +semantics remain owned by the VM. This lesson consolidates accepted DEC-0069 +and implemented PLN-0148 from AGD-0083 / DSC-0081. + +The common compiler already represented all runtime math identities and canonical +constants. That did not make them usable from PBS source. The remaining work was +service syntax, exact overload resolution, SDK publication, constant reads and +source-to-production execution evidence. + +## Consolidated decision + +The user explicitly chose services themselves as namespaces. Services export +constants alongside methods; there is no separate namespace declaration or new +numeric builtin type. The same capability applies to project and SDK services. + +`math` exposes exact int/long overloads and `mathf` exposes Float functions. +Conversions between numeric carriers are explicit. The compiler consumes its +existing manually ported, independently checked common catalog. It does not query +a runtime checkout during normal compilation or duplicate the VM's math backend. + +Pi and tau use canonical builtin constant materialization, not zero-argument +intrinsics. Mathematical calls retain their faults and costs even with literal +arguments. Qualification must start with source and compare exact bits, faults +and cycles on a named runtime build. + +## Final implementation + +The service AST retains constant declarations with their owner. Parser, declaration +checks, dependency/cycle validation, type resolution, lowering and editor member +surfaces carry them through. Constants are immutable, exported with their service, +and available through qualified reads and import aliases. Within the owner, a +constant reference takes precedence over a same-named global; locals retain their +normal lexical precedence. Explicit long annotations contextually type integer +constant literals, without converting references to already typed int constants. + +SDK services at `@sdk:math` and `@sdk:mathf` bind their 26 exact signatures through +reserved IntrinsicCall metadata. Each generated callable loads its declared +arguments, calls the common catalog identity and returns. Consequently its normal +CALL/GET_LOCAL/RET overhead is distinct from the intrinsic's own charge. Imports +with aliases resolve to the original provider callable identity. + +BuiltinConst metadata on service constants records the qualified source name. +The existing BUILTIN_CONST instruction materializes `IRVMBuiltinConstantDefinition`. +Pi and tau retain bits `0x400921FB54442D18` and `0x401921FB54442D18`. A qualified +constant read does not construct a singleton or call a getter. Constant-only +probes cost six cycles: an ordinary load plus the root return. + +```pbs +import { math } from @sdk:math; +import { mathf as numbers } from @sdk:mathf; + +fn example(counter: long, angle: float) -> float { + let bounded = math.clamp(counter, 0 as long, 100 as long); + return math.to_float(bounded) + numbers.sin(angle) + numbers.pi; +} +``` + +General service constants use ordinary source expressions: + +```pbs +declare service Settings { + declare const base: int = 40; + declare const answer: int = base + 2; + fn read() -> int { return answer; } +} +``` + +## Qualification and reproducibility + +Runtime revision: `f7d7c167531bb662a1af9d73fc326bb476bf8aa7`, unchanged clean checkout. +Platform: macOS 27.0.1 arm64. Production harness profiles: dev and release; +VM feature: resource-diagnostics, default load limits, NONE capabilities for math. +Java build uses JDK 25; installed launcher uses the existing distribution runtime. + +The corpus contains 261 independent numeric cases, emitted both normally and with +the PBS/common optimizer enabled: 522 mandatory cases in each runtime profile. +It combines the first 240 scalar provider fixture rows with exact published +contract examples, removing duplicates. It covers all 26 signatures, signed zeros, +subnormals, finite extrema, checked conversions, ties-to-even, invalid clamp, +negative sqrt, abs(MIN) and atan2 axes. Additional probes cover pi/tau, direct +literal sin, ordinary int/long constants, dependencies and a real project with +SDK imports, service aliases and exported project constants. + +Every numeric case checks the selected intrinsic identity, exactly one retained +call, exact result bits or fault code, and per-instruction charging. Numeric costs +come from independent fixture rows; other instruction costs come from the provider +ISA contract. A full-budget execution must charge the sum of those steps. +Optimized and unoptimized versions must charge identical totals. + +| Gate | Result | +| --- | --- | +| PBS frontend suite | 249 tests passed | +| Common backend suite | 175 passed, 12 pre-existing skips | +| Selected architecture/source suites | Math, existing values/input, structured values and closures passed | +| Installed knowledge | Both gates passed; packaged example imports math and aliased mathf | +| Complete production harness | Passed in dev and release, including 522 math vectors per profile | +| Workflow and patch integrity | discussion validate and git diff --check passed | + +| Evidence artifact | SHA-256 | +| --- | --- | +| Runtime Cargo.lock | cffad9ed62f38a591538abd81dd39270d6022397342c8189f4ac6c7baaa8e795 | +| INTRINSICS.csv | 0c1bb78a9b81d1e3480ef5713f3d70f0b06772a7dfab2fd00c1f0a6364f98daa | +| BUILTIN_CONSTANTS.csv | e407e4718127aa7ef7b1097b5b4b67d86dd979235e73a551a7c36b628cddc039 | +| Provider numeric-conformance.tsv | 5536ee18cadaf32e3719b0e8d541dfcf1a84a49ea978a702101547c5ccdee3fe | +| Consumer numeric-source.tsv | 95067131dbc7a4252352424ee52f4b9215c8d8ecd80124218a38819211ff7ccb | + +Reproduce from the Studio root: + +```sh +./gradlew :prometeu-compiler:frontends:prometeu-frontend-pbs:test :prometeu-compiler:prometeu-build-pipeline:test +./gradlew :prometeu-architecture-tests:test --tests '*PbsRuntimeMathTest' --tests '*PbsRuntimeAlignmentTest' --tests '*PbsStructuredValuesTest' --tests '*PbsClosuresTest' +./gradlew :prometeu-app:installedKnowledgeTest +python3 tools/pbx-conformance/run.py --runtime ../runtime +python3 tools/pbx-conformance/run.py --runtime ../runtime --release +``` + +Optional CARGO_TARGET_DIR can preserve harness compilation artifacts in a temporary +directory. The script never writes to the runtime checkout. Use --math-only for +the complete math subset; it still rejects missing mandatory math fixtures. + +Qualification on macOS/x86_64 and Linux/x86_64 remains pending. This delivery does +not qualify those hosts, installed-runtime deployment or a complete reference game. +The existing provider schema gaps for LifecycleRole and NonFiniteValue remain +explicitly reported by the full harness; original payloads are preserved. + +## Pitfalls and maintenance + +- Catalog parity is not source integration. Test the facade, imports, overloads, + actual emission and production VM together. +- Constants are not nullary intrinsics. Preserve their canonical bits and ordinary + load costs independently of method binding. +- A service alias changes source spelling, not the provider callable identity. +- Preserve constant ownership during expansion. Caller locals/globals must not + accidentally change the lexical meaning of a constant's initializer. +- Float equality hides the sign of zero. Conformance must compare raw bits. +- Intrinsic costs exclude wrapper and argument-producing instructions. Charge and + compare the complete program without treating virtual cycles as CPU timings. +- Extend the corpus and its mandatory count together. Never silently skip absent + fixtures, accept host tolerances, or replace provider oracles with compiler output. + +## References + +- [Service constants and runtime math specification](../../../docs/compiler/pbs/specs/service-constants-and-runtime-math.md) +- [Runtime catalog policy](../../../docs/compiler/general/specs/runtime-catalog-support.md) +- [Production harness](../../../tools/pbx-conformance/README.md) +- [Catalog-port lesson](../DSC-0075-compiler-runtime-catalog-parity/LSN-0080-manual-runtime-catalog-port-and-conformance.md) +- Historical execution artifacts: DEC-0069 and PLN-0148, removed by CLI housekeeping after completion. + +Tooling note: the CLI has no lesson-allocation command. LSN-0085 was selected from +the next counter; CLI housekeeping registers the lesson and advances that counter. diff --git a/docs/compiler/pbs/specs/service-constants-and-runtime-math.md b/docs/compiler/pbs/specs/service-constants-and-runtime-math.md new file mode 100644 index 00000000..a256289f --- /dev/null +++ b/docs/compiler/pbs/specs/service-constants-and-runtime-math.md @@ -0,0 +1,118 @@ +# Service constants and runtime math + +Owner: compiler/pbs. Common catalog authority: compiler/general. Numeric behavior, +exact identities, faults and virtual costs remain owned by the runtime. + +## Services are the public namespaces + +A service groups methods and immutable constants. The service barrel entry exports +both; constants are not independently exported as top-level symbols. This applies +to project code and SDK interfaces. Import aliases preserve the service identity. + +```pbs +// @app:settings/main.pbs; mod.barrel contains: pub service Settings; +declare service Settings { + declare const base: int = 40; + declare const answer: int = base + 2; + fn read() -> int { return answer; } +} +``` + +Consumers can import `Settings` and read `Settings.answer`. Constants use the same +explicit type and constant-expression rules as top-level constants. Constant +initializers cannot invoke functions. Qualified dependencies are permitted; +unqualified names inside a constant initializer resolve in its owning service +before the top-level constant scope. Duplicate constants, a constant sharing a +method name, unresolved references, type mismatches and dependency cycles are +compile-time errors. Assignments to constants are invalid. + +Reading `Service.constant` materializes its value without creating a singleton or +calling a getter. Ordinary methods retain existing service semantics. Constant +members are included in completion, hover, definition and document symbols. + +## SDK math services + +```pbs +import { math } from @sdk:math; +import { mathf as numbers } from @sdk:mathf; + +fn example(counter: long, angle: float) -> float { + let bounded = math.clamp(counter, 0 as long, 100 as long); + return math.to_float(bounded) + numbers.sin(angle) + numbers.pi; +} +``` + +`math` supplies `min`, `max`, `clamp` and `abs`, each with exact `int` and `long` +overloads. `mathf` supplies `min`, `max`, `clamp`, `abs`, `floor`, `ceil`, `trunc`, +`round`, `sqrt`, `sin`, `cos` and `atan2`, all with `float` arguments and results. +`atan2` takes `(y, x)`; angles are radians. `float` is the runtime's finite binary64. + +The six conversions are: + +| Source call | Argument | Result | +| --- | --- | --- | +| `math.to_i64` | int | long | +| `math.to_i32` | long | int | +| `math.to_float` | int | float | +| `math.to_float` | long | float | +| `mathf.to_i32` | float | int | +| `mathf.to_i64` | float | long | + +These are 26 exact intrinsic signatures in total. There are no identity +conversions. A mixed `int`/`long` call to `math.min` is invalid; the diagnostic +requires explicit conversion. Existing contextual integer literal rules do not +authorize implicit conversion of an already typed argument. Arithmetic opcode +promotion rules are unchanged. + +## Binding and materialization + +SDK service method signatures may carry `[IntrinsicCall(name = "...", version = 1)]` +and terminate with `;`. They have no PBS body or implicit numeric receiver in their +runtime signature. This reserved declaration form is restricted to SDK interfaces. +The generated callable loads its ordered arguments and invokes the exact common +catalog identity. No frontend numeric ID/cost map or host math implementation is +introduced. Normal compilation uses local versioned resources, not a runtime checkout. + +SDK service constants may use `BuiltinConst` and omit their initializer: + +```pbs +declare service mathf { + [BuiltinConst(target = "mathf", name = "pi", version = 1)] + declare const pi: float; +} +``` + +`mathf.pi` and `mathf.tau` MUST materialize `IRVMBuiltinConstantDefinition` values: +`0x400921FB54442D18` and `0x401921FB54442D18`. They are ordinary constant loads, +never synthetic intrinsic calls or host-calculated values. A constant expression +cannot replace a mathematical call: executable calls with literal arguments MUST +remain executable, including when their result is discarded or optimization runs. + +## Numeric conformance + +The runtime contract specifies signed zeros, subnormals, finite overflow, checked +conversions and ties-to-even rounding. For example, `sqrt(-0)` preserves -0, +`abs(-0)` produces +0, `round(2.5)` produces 2 and `round(3.5)` produces 4. Negative +nonzero sqrt and inverted clamp limits trap NUMERIC_DOMAIN. Integer abs(MIN) and +out-of-range conversions trap NUMERIC_RANGE. The frontend MUST preserve these +outcomes, argument order and virtual cycle accounting. + +Integration evidence MUST begin with PBS source and end at the production VM. +The checked-in independent corpus combines provider MPFR-verified rows with exact +published contract examples. Tests require all 26 signatures, constants, mixed-type +rejections, explicit conversions, signed zeros, subnormals, extrema, range/domain +faults and atan2 axes. Both optimized and unoptimized emission are exercised. +The harness compares exact result bits and trap codes, and checks each executed +instruction's charge against the provider opcode contract and each numeric call +against its independent fixture cost. A full-budget run must charge their sum. +Constant-only probes additionally require exactly a load and root return cost. + +Local qualification requires macOS/arm64 dev and release with runtime revision, +configuration and catalog/oracle hashes recorded. macOS/x86_64 and Linux/x86_64 +remain separately pending; local results and cross-compilation do not qualify them. + +## References + +- [Common runtime catalog support](../../general/specs/runtime-catalog-support.md) +- [Runtime numeric contract](../../../../../runtime/docs/specs/runtime/02d-gameplay-math-and-numeric-semantics.md) +- [Production conformance harness](../../../../tools/pbx-conformance/README.md) diff --git a/docs/specs/compiler-languages/pbs/3. Core Syntax Specification.md b/docs/specs/compiler-languages/pbs/3. Core Syntax Specification.md index 2621012d..112db062 100644 --- a/docs/specs/compiler-languages/pbs/3. Core Syntax Specification.md +++ b/docs/specs/compiler-languages/pbs/3. Core Syntax Specification.md @@ -192,7 +192,7 @@ Rules: - A `host` barrel entry must resolve to exactly one top-level `declare host` declaration in module scope. - A `struct` barrel entry governs the visibility of the struct declaration and of all methods declared directly in that struct body. - A `host` barrel entry governs the visibility of the host declaration and of all method signatures declared directly in that host body. -- A `service` barrel entry governs the visibility of the service declaration, its canonical singleton value, and all methods declared directly in that service body. +- A `service` barrel entry governs the visibility of the service declaration, its canonical singleton value, and all methods and constants declared directly in that service body. - A `global` barrel entry governs visibility of one top-level `declare global` declaration. - Methods declared inside a `struct`, `host`, or `service` are never exported independently through `mod.barrel`. @@ -371,18 +371,19 @@ Function types use `Fn(T1, T2) -> R`. Lambdas use `fn [captures](name: Type) -> ```ebnf ServiceDecl ::= 'declare' 'service' Identifier ServiceBody ServiceBody ::= '{' ServiceMember* '}' -ServiceMember ::= 'fn' Identifier ParamList ReturnAnn? Block +ServiceMember ::= 'fn' Identifier ParamList ReturnAnn? Block | ConstDecl +// SDK only: an IntrinsicCall-attributed service signature may end in ';'. ``` Rules: - `declare service Name { ... }` declares a nominal service type together with its canonical module-owned singleton value `Name`. -- A service body contains only method declarations. +- A service body contains method declarations and `declare const` members. SDK service intrinsic signatures may terminate with `;`; see [Service constants and runtime math](../../../compiler/pbs/specs/service-constants-and-runtime-math.md). - Service methods have an implicit receiver binding `this` of type `Self` and do not declare `this: Self` explicitly. - Services do not declare fields. - Services do not declare `ctor`. - Services are never constructed with `new`. -- Service method visibility follows the `service` entry for that declaration in `mod.barrel`; service methods are never exported independently. +- Service method visibility follows the `service` entry for that declaration in `mod.barrel`; service methods and constants are never exported independently. ### 7.4 Functions diff --git a/docs/specs/compiler-languages/pbs/4. Static Semantics Specification.md b/docs/specs/compiler-languages/pbs/4. Static Semantics Specification.md index 230ba04a..c30a2c1d 100644 --- a/docs/specs/compiler-languages/pbs/4. Static Semantics Specification.md +++ b/docs/specs/compiler-languages/pbs/4. Static Semantics Specification.md @@ -96,7 +96,7 @@ Rules: - The `Host` attribute syntax itself is not exported as runtime metadata; instead, its canonical identity participates in PBX host-binding emission as defined by the Host ABI Binding specification. - `BuiltinType` is valid only on a reserved top-level `declare builtin type` declaration. - `BuiltinConst` is valid only on a reserved top-level `declare const` declaration that omits an initializer. -- `IntrinsicCall` is valid only on a method signature declared directly inside a reserved `declare builtin type` body. +- `IntrinsicCall` is valid on a method signature inside a reserved `declare builtin type` body or an SDK service body. SDK service signatures have no implementation body and bind their exact declared argument/result carriers to the common intrinsic catalog. - Builtin metadata is consumed by the compiler during VM-owned builtin and intrinsic lowering rather than by host-binding lowering. - `Init` and `Frame` are consumed by lifecycle analysis and lowering rather than by ordinary runtime reflection. - `InitAllowed` is consumed by init-time host-admission analysis and does not become ordinary userland metadata. @@ -349,6 +349,11 @@ Rules: ### 3.6 Structs, services, methods, and contracts +Service constants follow [Service constants and runtime math](../../../compiler/pbs/specs/service-constants-and-runtime-math.md). +They are immutable members exported with their service. Qualified constant reads +materialize the constant without constructing a singleton or invoking a method. + + Rules: - Struct values are heap-backed reference values in v1 core. diff --git a/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsRuntimeAlignmentTest.java b/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsRuntimeAlignmentTest.java index 67ccc5ac..05a53d82 100644 --- a/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsRuntimeAlignmentTest.java +++ b/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsRuntimeAlignmentTest.java @@ -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); diff --git a/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsRuntimeMathTest.java b/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsRuntimeMathTest.java new file mode 100644 index 00000000..d337f0a0 --- /dev/null +++ b/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsRuntimeMathTest.java @@ -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(); + 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(); + 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()); + } +} diff --git a/prometeu-architecture-tests/src/test/resources/math/numeric-source.tsv b/prometeu-architecture-tests/src/test/resources/math/numeric-source.tsv new file mode 100644 index 00000000..14a22b71 --- /dev/null +++ b/prometeu-architecture-tests/src/test/resources/math/numeric-source.tsv @@ -0,0 +1,261 @@ +3000 i:7 i:3 i:3 2 +3001 i:7 i:3 i:7 2 +3002 i:9 i:0 i:5 i:5 4 +3003 i:-7 i:7 2 +3004 l:2147483648 l:2147483649 l:2147483648 2 +3005 l:2147483648 l:2147483649 l:2147483649 2 +3006 l:9 l:0 l:5 l:5 4 +3007 l:-7 l:7 2 +3008 f:8000000000000000 f:0000000000000000 f:8000000000000000 2 +3009 f:8000000000000000 f:0000000000000000 f:0000000000000000 2 +300a f:8000000000000000 f:0000000000000000 f:3ff0000000000000 f:0000000000000000 4 +300b f:8000000000000000 f:0000000000000000 2 +3013 f:3ff0000000000000 f:0000000000000000 f:3ff921fb54442d18 48 +3014 i:-2147483648 l:-2147483648 2 +3015 l:2147483647 i:2147483647 2 +3016 i:2147483647 f:41dfffffffc00000 2 +3017 l:9223372036854775807 f:43e0000000000000 2 +3003 i:-2147483648 trap:13 2 +3007 l:-9223372036854775808 trap:13 2 +3002 i:0 i:2 i:1 trap:12 4 +300a f:0000000000000000 f:4000000000000000 f:3ff0000000000000 trap:12 4 +3010 f:bff0000000000000 trap:12 16 +3013 f:0000000000000000 f:0000000000000000 trap:12 48 +3013 f:8000000000000000 f:bff0000000000000 f:c00921fb54442d18 48 +3013 f:0000000000000000 f:bff0000000000000 f:400921fb54442d18 48 +300f f:4004000000000000 f:4000000000000000 4 +300f f:400c000000000000 f:4010000000000000 4 +3015 l:2147483648 trap:13 2 +3018 f:41e0000000000000 trap:13 2 +3019 f:43e0000000000000 trap:13 2 +3019 f:c3e0000000000000 l:-9223372036854775808 2 +3017 l:9007199254740993 f:4340000000000000 2 +3010 f:0000000000000000 f:0000000000000000 16 +300c f:0000000000000000 f:0000000000000000 4 +300d f:0000000000000000 f:0000000000000000 4 +300e f:0000000000000000 f:0000000000000000 4 +300f f:0000000000000000 f:0000000000000000 4 +3018 f:0000000000000000 i:0 2 +3019 f:0000000000000000 l:0 2 +3011 f:0000000000000000 f:0000000000000000 32 +3012 f:0000000000000000 f:3ff0000000000000 32 +3011 f:8000000000000000 f:8000000000000000 32 +3012 f:8000000000000000 f:3ff0000000000000 32 +3013 f:0000000000000000 f:54edb5f397cc207d f:0000000000000000 48 +3010 f:0000000000000001 f:1e60000000000000 16 +300c f:0000000000000001 f:0000000000000000 4 +300d f:0000000000000001 f:3ff0000000000000 4 +300e f:0000000000000001 f:0000000000000000 4 +300f f:0000000000000001 f:0000000000000000 4 +3018 f:0000000000000001 i:0 2 +3019 f:0000000000000001 l:0 2 +3011 f:0000000000000001 f:0000000000000001 32 +3012 f:0000000000000001 f:3ff0000000000000 32 +3011 f:8000000000000001 f:8000000000000001 32 +3012 f:8000000000000001 f:3ff0000000000000 32 +3013 f:0000000000000001 f:823a3f3c9decf2dd f:400921fb54442d18 48 +3010 f:0000000000000002 f:1e66a09e667f3bcd 16 +300c f:0000000000000002 f:0000000000000000 4 +300d f:0000000000000002 f:3ff0000000000000 4 +300e f:0000000000000002 f:0000000000000000 4 +300f f:0000000000000002 f:0000000000000000 4 +3018 f:0000000000000002 i:0 2 +3019 f:0000000000000002 l:0 2 +3011 f:0000000000000002 f:0000000000000002 32 +3012 f:0000000000000002 f:3ff0000000000000 32 +3011 f:8000000000000002 f:8000000000000002 32 +3012 f:8000000000000002 f:3ff0000000000000 32 +3013 f:0000000000000002 f:8c9f4dfeacaf0126 f:400921fb54442d18 48 +3010 f:000fffffffffffff f:1fffffffffffffff 16 +300c f:000fffffffffffff f:0000000000000000 4 +300d f:000fffffffffffff f:3ff0000000000000 4 +300e f:000fffffffffffff f:0000000000000000 4 +300f f:000fffffffffffff f:0000000000000000 4 +3018 f:000fffffffffffff i:0 2 +3019 f:000fffffffffffff l:0 2 +3011 f:000fffffffffffff f:000fffffffffffff 32 +3012 f:000fffffffffffff f:3ff0000000000000 32 +3011 f:800fffffffffffff f:800fffffffffffff 32 +3012 f:800fffffffffffff f:3ff0000000000000 32 +3013 f:000fffffffffffff f:09ed7f8a283eb81c f:36115b63b5562616 48 +3010 f:0010000000000000 f:2000000000000000 16 +300c f:0010000000000000 f:0000000000000000 4 +300d f:0010000000000000 f:3ff0000000000000 4 +300e f:0010000000000000 f:0000000000000000 4 +300f f:0010000000000000 f:0000000000000000 4 +3018 f:0010000000000000 i:0 2 +3019 f:0010000000000000 l:0 2 +3011 f:0010000000000000 f:0010000000000000 32 +3012 f:0010000000000000 f:3ff0000000000000 32 +3011 f:8010000000000000 f:8010000000000000 32 +3012 f:8010000000000000 f:3ff0000000000000 32 +3013 f:0010000000000000 f:3feffffffffffffe f:0010000000000001 48 +3010 f:3fdfffffffffffff f:3fe6a09e667f3bcc 16 +300c f:3fdfffffffffffff f:0000000000000000 4 +300d f:3fdfffffffffffff f:3ff0000000000000 4 +300e f:3fdfffffffffffff f:0000000000000000 4 +300f f:3fdfffffffffffff f:0000000000000000 4 +3018 f:3fdfffffffffffff i:0 2 +3019 f:3fdfffffffffffff l:0 2 +3011 f:3fdfffffffffffff f:3fdeaee8744b05ef 32 +3012 f:3fdfffffffffffff f:3fec1528065b7d50 32 +3011 f:bfdfffffffffffff f:bfdeaee8744b05ef 32 +3012 f:bfdfffffffffffff f:3fec1528065b7d50 32 +3013 f:3fdfffffffffffff f:07faa1d222d1148d f:3ff921fb54442d18 48 +3010 f:3fe0000000000000 f:3fe6a09e667f3bcd 16 +300c f:3fe0000000000000 f:0000000000000000 4 +300d f:3fe0000000000000 f:3ff0000000000000 4 +300e f:3fe0000000000000 f:0000000000000000 4 +300f f:3fe0000000000000 f:0000000000000000 4 +3018 f:3fe0000000000000 i:0 2 +3019 f:3fe0000000000000 l:0 2 +3011 f:3fe0000000000000 f:3fdeaee8744b05f0 32 +3012 f:3fe0000000000000 f:3fec1528065b7d50 32 +3011 f:bfe0000000000000 f:bfdeaee8744b05f0 32 +3012 f:bfe0000000000000 f:3fec1528065b7d50 32 +3013 f:3fe0000000000000 f:ad7bbd56db31c9ec f:3ff921fb54442d18 48 +3010 f:3fe0000000000001 f:3fe6a09e667f3bcd 16 +300c f:3fe0000000000001 f:0000000000000000 4 +300d f:3fe0000000000001 f:3ff0000000000000 4 +300e f:3fe0000000000001 f:0000000000000000 4 +300f f:3fe0000000000001 f:3ff0000000000000 4 +3018 f:3fe0000000000001 i:0 2 +3019 f:3fe0000000000001 l:0 2 +3011 f:3fe0000000000001 f:3fdeaee8744b05f2 32 +3012 f:3fe0000000000001 f:3fec1528065b7d4f 32 +3011 f:bfe0000000000001 f:bfdeaee8744b05f2 32 +3012 f:bfe0000000000001 f:3fec1528065b7d4f 32 +3013 f:3fe0000000000001 f:3ffffffffffffffe f:3fcf5b75f92c80e1 48 +3010 f:3ff0000000000000 f:3ff0000000000000 16 +300c f:3ff0000000000000 f:3ff0000000000000 4 +300d f:3ff0000000000000 f:3ff0000000000000 4 +300e f:3ff0000000000000 f:3ff0000000000000 4 +300f f:3ff0000000000000 f:3ff0000000000000 4 +3018 f:3ff0000000000000 i:1 2 +3019 f:3ff0000000000000 l:1 2 +3011 f:3ff0000000000000 f:3feaed548f090cee 32 +3012 f:3ff0000000000000 f:3fe14a280fb5068c 32 +3011 f:bff0000000000000 f:bfeaed548f090cee 32 +3012 f:bff0000000000000 f:3fe14a280fb5068c 32 +3013 f:3ff0000000000000 f:3fe0000000000002 f:3ff1b6e192ebbe44 48 +3010 f:4000000000000000 f:3ff6a09e667f3bcd 16 +300c f:4000000000000000 f:4000000000000000 4 +300d f:4000000000000000 f:4000000000000000 4 +300e f:4000000000000000 f:4000000000000000 4 +300f f:4000000000000000 f:4000000000000000 4 +3018 f:4000000000000000 i:2 2 +3019 f:4000000000000000 l:2 2 +3011 f:4000000000000000 f:3fed18f6ead1b446 32 +3012 f:4000000000000000 f:bfdaa22657537205 32 +3011 f:c000000000000000 f:bfed18f6ead1b446 32 +3012 f:c000000000000000 f:bfdaa22657537205 32 +3013 f:4000000000000000 f:3ff921fb54442d18 f:3fecf5f1e82b5390 48 +3010 f:3ff921fb54442d18 f:3ff40d931ff62705 16 +300c f:3ff921fb54442d18 f:3ff0000000000000 4 +300d f:3ff921fb54442d18 f:4000000000000000 4 +300e f:3ff921fb54442d18 f:3ff0000000000000 4 +300f f:3ff921fb54442d18 f:4000000000000000 4 +3018 f:3ff921fb54442d18 i:1 2 +3019 f:3ff921fb54442d18 l:1 2 +3011 f:3ff921fb54442d18 f:3ff0000000000000 32 +3012 f:3ff921fb54442d18 f:3c91a62633145c07 32 +3011 f:bff921fb54442d18 f:bff0000000000000 32 +3012 f:bff921fb54442d18 f:3c91a62633145c07 32 +3013 f:3ff921fb54442d18 f:ea3931a1dc0ba585 f:400921fb54442d18 48 +3010 f:400921fb54442d18 f:3ffc5bf891b4ef6a 16 +300c f:400921fb54442d18 f:4008000000000000 4 +300d f:400921fb54442d18 f:4010000000000000 4 +300e f:400921fb54442d18 f:4008000000000000 4 +300f f:400921fb54442d18 f:4008000000000000 4 +3018 f:400921fb54442d18 i:3 2 +3019 f:400921fb54442d18 l:3 2 +3011 f:400921fb54442d18 f:3ca1a62633145c07 32 +3012 f:400921fb54442d18 f:bff0000000000000 32 +3011 f:c00921fb54442d18 f:bca1a62633145c07 32 +3012 f:c00921fb54442d18 f:bff0000000000000 32 +3013 f:400921fb54442d18 f:7103ecf9a81fd654 f:0ef42e61ed6e3c59 48 +3010 f:401921fb54442d18 f:40040d931ff62705 16 +300c f:401921fb54442d18 f:4018000000000000 4 +300d f:401921fb54442d18 f:401c000000000000 4 +300e f:401921fb54442d18 f:4018000000000000 4 +300f f:401921fb54442d18 f:4018000000000000 4 +3018 f:401921fb54442d18 i:6 2 +3019 f:401921fb54442d18 l:6 2 +3011 f:401921fb54442d18 f:bcb1a62633145c07 32 +3012 f:401921fb54442d18 f:3ff0000000000000 32 +3011 f:c01921fb54442d18 f:3cb1a62633145c07 32 +3012 f:c01921fb54442d18 f:3ff0000000000000 32 +3013 f:401921fb54442d18 f:22f1a991580a3c2b f:3ff921fb54442d18 48 +3010 f:7fefffffffffffff f:5fefffffffffffff 16 +300c f:7fefffffffffffff f:7fefffffffffffff 4 +300d f:7fefffffffffffff f:7fefffffffffffff 4 +300e f:7fefffffffffffff f:7fefffffffffffff 4 +300f f:7fefffffffffffff f:7fefffffffffffff 4 +3018 f:7fefffffffffffff trap:13 2 +3019 f:7fefffffffffffff trap:13 2 +3011 f:7fefffffffffffff f:3f7452fc98b34e97 32 +3012 f:7fefffffffffffff f:bfefffe62ecfab75 32 +3011 f:ffefffffffffffff f:bf7452fc98b34e97 32 +3012 f:ffefffffffffffff f:bfefffe62ecfab75 32 +3013 f:7fefffffffffffff f:3ff921fb54442d19 f:3ff921fb54442d18 48 +3010 f:000ffffffffffffe f:1ffffffffffffffe 16 +300c f:000ffffffffffffe f:0000000000000000 4 +300d f:000ffffffffffffe f:3ff0000000000000 4 +300e f:000ffffffffffffe f:0000000000000000 4 +300f f:000ffffffffffffe f:0000000000000000 4 +3018 f:000ffffffffffffe i:0 2 +3019 f:000ffffffffffffe l:0 2 +3011 f:000ffffffffffffe f:000ffffffffffffe 32 +3012 f:000ffffffffffffe f:3ff0000000000000 32 +3011 f:800ffffffffffffe f:800ffffffffffffe 32 +3012 f:800ffffffffffffe f:3ff0000000000000 32 +3013 f:000ffffffffffffe f:074caaf9d0e6af80 f:38b1dc162179e06b 48 +3013 f:000fffffffffffff f:272b6a7c6b3a7cd8 f:18d2acdd5ccefbb4 48 +3010 f:0010000000000001 f:2000000000000000 16 +300c f:0010000000000001 f:0000000000000000 4 +300d f:0010000000000001 f:3ff0000000000000 4 +300e f:0010000000000001 f:0000000000000000 4 +300f f:0010000000000001 f:0000000000000000 4 +3018 f:0010000000000001 i:0 2 +3019 f:0010000000000001 l:0 2 +3011 f:0010000000000001 f:0010000000000001 32 +3012 f:0010000000000001 f:3ff0000000000000 32 +3011 f:8010000000000001 f:8010000000000001 32 +3012 f:8010000000000001 f:3ff0000000000000 32 +3013 f:0010000000000001 f:3feffffffffffffe f:0010000000000002 48 +3010 f:0010000000000002 f:2000000000000001 16 +300c f:0010000000000002 f:0000000000000000 4 +300d f:0010000000000002 f:3ff0000000000000 4 +300e f:0010000000000002 f:0000000000000000 4 +300f f:0010000000000002 f:0000000000000000 4 +3018 f:0010000000000002 i:0 2 +3019 f:0010000000000002 l:0 2 +3011 f:0010000000000002 f:0010000000000002 32 +3012 f:0010000000000002 f:3ff0000000000000 32 +3011 f:8010000000000002 f:8010000000000002 32 +3012 f:8010000000000002 f:3ff0000000000000 32 +3013 f:0010000000000002 f:7721df366e8fb3fd f:0000000000000000 48 +3010 f:3fdffffffffffffd f:3fe6a09e667f3bcc 16 +300c f:3fdffffffffffffd f:0000000000000000 4 +300d f:3fdffffffffffffd f:3ff0000000000000 4 +300e f:3fdffffffffffffd f:0000000000000000 4 +300f f:3fdffffffffffffd f:0000000000000000 4 +3018 f:3fdffffffffffffd i:0 2 +3019 f:3fdffffffffffffd l:0 2 +3011 f:3fdffffffffffffd f:3fdeaee8744b05ed 32 +3012 f:3fdffffffffffffd f:3fec1528065b7d50 32 +3011 f:bfdffffffffffffd f:bfdeaee8744b05ed 32 +3012 f:bfdffffffffffffd f:3fec1528065b7d50 32 +3013 f:3fdffffffffffffd f:7feffffffffffffe f:0002000000000000 48 +3010 f:3fdffffffffffffe f:3fe6a09e667f3bcc 16 +300c f:3fdffffffffffffe f:0000000000000000 4 +300d f:3fdffffffffffffe f:3ff0000000000000 4 +300e f:3fdffffffffffffe f:0000000000000000 4 +300f f:3fdffffffffffffe f:0000000000000000 4 +3018 f:3fdffffffffffffe i:0 2 +3019 f:3fdffffffffffffe l:0 2 +3011 f:3fdffffffffffffe f:3fdeaee8744b05ee 32 +3012 f:3fdffffffffffffe f:3fec1528065b7d50 32 +3011 f:bfdffffffffffffe f:bfdeaee8744b05ee 32 +3012 f:bfdffffffffffffe f:3fec1528065b7d50 32 +3013 f:3fdffffffffffffe f:401921fb54442d17 f:3fb45438e80932c3 48 diff --git a/prometeu-architecture-tests/src/test/resources/math/provenance.txt b/prometeu-architecture-tests/src/test/resources/math/provenance.txt new file mode 100644 index 00000000..b3c2c5fc --- /dev/null +++ b/prometeu-architecture-tests/src/test/resources/math/provenance.txt @@ -0,0 +1,3 @@ +Runtime revision: f7d7c167531bb662a1af9d73fc326bb476bf8aa7 +Provider fixture SHA-256: 5536ee18cadaf32e3719b0e8d541dfcf1a84a49ea978a702101547c5ccdee3fe +First 240 scalar rows of numeric-conformance.tsv plus exact examples from 02d-gameplay-math-and-numeric-semantics.md. No host math oracle. diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/PbsReservedMetadataExtractor.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/PbsReservedMetadataExtractor.java index d2f97d05..618145d4 100644 --- a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/PbsReservedMetadataExtractor.java +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/PbsReservedMetadataExtractor.java @@ -41,6 +41,11 @@ public final class PbsReservedMetadataExtractor { extractBuiltinTypeSurface(builtinTypeDecl, inferredLayoutsByName, builtinTypeSurfaces); continue; } + if (topDecl instanceof PbsAst.ServiceDecl service) { + for (var constant : service.constants()) extractBuiltinConstSurface( + new PbsAst.ConstDecl(service.name() + "." + constant.name(), constant.explicitType(), + constant.initializer(), constant.attributes(), constant.span()), builtinConstSurfaces); + } if (topDecl instanceof PbsAst.ConstDecl constDecl) { extractBuiltinConstSurface(constDecl, builtinConstSurfaces); } diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/PbsServiceConstants.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/PbsServiceConstants.java new file mode 100644 index 00000000..8c8ba37c --- /dev/null +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/PbsServiceConstants.java @@ -0,0 +1,30 @@ +package p.studio.compiler.pbs; + +import p.studio.compiler.pbs.ast.PbsAst; +import p.studio.utilities.structures.ReadOnlyList; +import java.util.LinkedHashMap; +import java.util.Map; + +/** Constant identities retain their service owner, including across imports. */ +public final class PbsServiceConstants { + private PbsServiceConstants() {} + + public static Map collect(ReadOnlyList declarations) { + var result = new LinkedHashMap(); + for (var declaration : declarations) { + if (declaration instanceof PbsAst.ConstDecl constant) result.putIfAbsent(constant.name(), constant); + if (declaration instanceof PbsAst.ServiceDecl service) + for (var constant : service.constants()) result.putIfAbsent(service.name() + "." + constant.name(), constant); + } + return result; + } + + public static String path(PbsAst.Expression expression) { + if (expression instanceof PbsAst.IdentifierExpr name) return name.name(); + if (expression instanceof PbsAst.MemberExpr member) { + var owner = path(member.receiver()); + return owner == null ? null : owner + "." + member.memberName(); + } + return null; + } +} diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/ast/PbsAst.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/ast/PbsAst.java index 3c38dafb..181edbbb 100644 --- a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/ast/PbsAst.java +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/ast/PbsAst.java @@ -180,8 +180,13 @@ public final class PbsAst { public record ServiceDecl( String name, ReadOnlyList methods, + ReadOnlyList constants, ReadOnlyList attributes, Span span) implements TopDecl { + public ServiceDecl(String name, ReadOnlyList methods, + ReadOnlyList attributes, Span span) { + this(name, methods, ReadOnlyList.empty(), attributes, span); + } } public record ErrorDecl( diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/lowering/PbsExecutableBodyLowerer.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/lowering/PbsExecutableBodyLowerer.java index 5351a76b..5f479db6 100644 --- a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/lowering/PbsExecutableBodyLowerer.java +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/lowering/PbsExecutableBodyLowerer.java @@ -58,7 +58,29 @@ final class PbsExecutableBodyLowerer { int slot = context.declareLocalSlots(capture.label(), context.types().slots(type)); emitStoreLocalSlots(slot, context.types().slots(type), capture.span(), context); } - final var terminated = lowerBlock(functionDecl.body(), context); + var binding = functionDecl.attributes().stream().filter(a -> "IntrinsicCall".equals(a.name())).findFirst(); + final boolean terminated; + if (binding.isPresent()) { + var attribute = binding.get(); + var name = attribute.arguments().stream().filter(a -> "name".equals(a.name())) + .map(a -> ((PbsAst.AttributeStringValue) a.value()).value()).findFirst().orElseThrow(); + if (name.startsWith("\"")) name = name.substring(1, name.length()-1); + long version = attribute.arguments().stream().filter(a -> "version".equals(a.name())) + .mapToLong(a -> ((PbsAst.AttributeIntValue) a.value()).value()).findFirst().orElseThrow(); + int slots = 0; + for (var parameter : functionDecl.parameters()) { + int width = context.types().slots(parameter.typeRef()); + emitLoadLocalSlots(slots, width, parameter.span(), context); + slots += width; + } + context.instructions().add(new IRBackendExecutableFunction.Instruction( + IRBackendExecutableFunction.InstructionKind.CALL_INTRINSIC, "", null, + new IRBackendExecutableFunction.IntrinsicCallMetadata(name, version, intrinsicIdTable.register(name, version)), + slots, context.types().slots(functionDecl.returnType()), functionDecl.span())); + context.instructions().add(new IRBackendExecutableFunction.Instruction( + IRBackendExecutableFunction.InstructionKind.RET, "", null, null, null, functionDecl.span())); + terminated = true; + } else terminated = lowerBlock(functionDecl.body(), context); finalizeFunctionInstructions(functionDecl, context, terminated); final var returnSlots = functionDecl.returnKind() == PbsAst.ReturnKind.PLAIN ? context.types().slots(functionDecl.returnType()) : 0; @@ -612,6 +634,21 @@ final class PbsExecutableBodyLowerer { final PbsAst.MemberExpr memberExpr, final PbsExecutableLoweringContext context) { var receiverType = PbsRuntimeTypes.unwrap(expressionType(memberExpr.receiver(), context)); + var service = receiverType == null ? null : context.types().services.get(receiverType.name()); + if (service != null) { + var key = service.name() + "." + memberExpr.memberName(); + if (context.types().constants.containsKey(key)) { + boolean staticOwner = memberExpr.receiver() instanceof PbsAst.IdentifierExpr name + && !context.localTypes.containsKey(name.name()) && context.types().services.containsKey(name.name()); + if (!staticOwner && !(memberExpr.receiver() instanceof PbsAst.ThisExpr)) { + lowerExpected(memberExpr.receiver(), receiverType, context); + context.instructions().add(new IRBackendExecutableFunction.Instruction( + IRBackendExecutableFunction.InstructionKind.POP, "", null, null, memberExpr.span())); + } + lowerConstant(key, memberExpr.span(), context); + return; + } + } if (receiverType != null && receiverType.kind() == PbsAst.TypeRefKind.ARRAY && memberExpr.memberName().equals("length")) { lowerExpected(memberExpr.receiver(), receiverType, context); registry(ARRAY_LEN, context.types().arrayStorage(), 0, 1, 1, memberExpr.span(), context); @@ -753,6 +790,11 @@ final class PbsExecutableBodyLowerer { } return; } + var memberKey = context.serviceOwner + "." + identifierExpr.name(); + if (context.types().constants.containsKey(memberKey)) { + lowerConstant(memberKey, identifierExpr.span(), context); + return; + } final var globalSlot = context.resolveGlobalSlot(identifierExpr.name()); if (globalSlot != null) { emitGetGlobal(globalSlot, identifierExpr.span(), context); @@ -774,6 +816,25 @@ final class PbsExecutableBodyLowerer { } } + private void lowerConstant(String key, Span span, PbsExecutableLoweringContext context) { + var constant = context.types().constants.get(key); + var previousOwner = context.serviceOwner; + var previousExpected = context.expectedType; + try { + context.serviceOwner = key.contains(".") ? key.substring(0, key.lastIndexOf('.')) : ""; + context.expectedType = constant.explicitType(); + if (constant.initializer() != null) lowerConstExpression(constant.initializer(), context); + else { + var builtin = context.builtinConstByNameId().get(context.nameTable().register(key)); + if (builtin == null) reportUnsupportedLowering("Missing builtin constant: " + key, span, context); + else emitBuiltinConstFetch(builtin, span, context); + } + } finally { + context.serviceOwner = previousOwner; + context.expectedType = previousExpected; + } + } + private void emitBuiltinConstFetch( final p.studio.compiler.models.IRReservedMetadata.BuiltinConstSurface builtinConst, final p.studio.compiler.source.Span span, @@ -904,7 +965,8 @@ final class PbsExecutableBodyLowerer { } return context.resolveLocalSlot(identifierExpr.name()) != null || context.resolveGlobalSlot(identifierExpr.name()) != null - || context.resolveConstDecl(identifierExpr.name()) != null; + || context.resolveConstDecl(identifierExpr.name()) != null + || context.types().constants.containsKey(context.serviceOwner + "." + identifierExpr.name()); } private int identifierValueSlots( @@ -944,6 +1006,8 @@ final class PbsExecutableBodyLowerer { lowerIntLiteral(new PbsAst.IntLiteralExpr(boundedLiteralExpr.value(), boundedLiteralExpr.span()), context); case PbsAst.StringLiteralExpr stringLiteralExpr -> emitPushConst(stringLiteralExpr.value(), stringLiteralExpr.span(), context); case PbsAst.BoolLiteralExpr boolLiteralExpr -> emitPushBool(boolLiteralExpr.value(), boolLiteralExpr.span(), context); + case PbsAst.FloatLiteralExpr literal -> lowerExpression(literal, context); + case PbsAst.MemberExpr member -> lowerMemberExpression(member, context); case PbsAst.GroupExpr groupExpr -> lowerConstExpression(groupExpr.expression(), context); case PbsAst.UnaryExpr unaryExpr -> { lowerConstExpression(unaryExpr.expression(), context); @@ -955,9 +1019,10 @@ final class PbsExecutableBodyLowerer { emitBinaryOperatorInstruction(binaryExpr.operator(), binaryExpr.span(), context); } case PbsAst.IdentifierExpr identifierExpr -> { - final var referenced = context.resolveConstDecl(identifierExpr.name()); - if (referenced != null && referenced.initializer() != null) { - lowerConstExpression(referenced.initializer(), context); + var key = context.serviceOwner + "." + identifierExpr.name(); + if (!context.types().constants.containsKey(key)) key = identifierExpr.name(); + if (context.types().constants.containsKey(key)) { + lowerConstant(key, identifierExpr.span(), context); } else { reportUnsupportedLowering("const identifier is not lowerable: " + identifierExpr.name(), identifierExpr.span(), context); } @@ -1046,6 +1111,12 @@ final class PbsExecutableBodyLowerer { if (e instanceof PbsAst.ElseExpr fallback) {var opt = PbsRuntimeTypes.unwrap(expressionType(fallback.optionalExpression(), c)); return opt == null ? null : opt.inner();} if (e instanceof PbsAst.IndexExpr index) {var array = PbsRuntimeTypes.unwrap(expressionType(index.receiver(), c)); return array == null ? null : PbsAst.TypeRef.optional(array.inner(), index.span());} if (e instanceof PbsAst.MemberExpr member) { + var serviceType = expressionType(member.receiver(), c); + var service = serviceType == null ? null : c.types().services.get(serviceType.name()); + if (service != null) { + var constant = c.types().constants.get(service.name() + "." + member.memberName()); + if (constant != null) return constant.explicitType(); + } var receiver = PbsRuntimeTypes.unwrap(expressionType(member.receiver(), c)); if (receiver != null && receiver.kind() == PbsAst.TypeRefKind.ARRAY && member.memberName().equals("length")) return PbsRuntimeTypes.type("long"); if (receiver != null && receiver.kind() == PbsAst.TypeRefKind.NAMED_TUPLE) @@ -1055,7 +1126,7 @@ final class PbsExecutableBodyLowerer { } if (e instanceof PbsAst.IdentifierExpr i) { if(c.types().services.containsKey(i.name()))return PbsRuntimeTypes.type(i.name()); - var local = c.localTypes.getOrDefault(i.name(), c.types().values.get(i.name())); + var local = c.localTypes.getOrDefault(i.name(), c.types().values.getOrDefault(c.serviceOwner + "." + i.name(), c.types().values.get(i.name()))); if (local != null) return local; var functions = c.types().functions.get(i.name()); if (functions != null && !functions.isEmpty()) { @@ -1107,6 +1178,10 @@ final class PbsExecutableBodyLowerer { return sig == null ? null : sig.returnType(); } if (e instanceof PbsAst.MemberExpr m && m.receiver() instanceof PbsAst.IdentifierExpr i) { + if (!c.localTypes.containsKey(i.name())) { + var key = c.types().aliases.getOrDefault(i.name(), i.name()) + "." + m.memberName(); + if (c.types().constants.containsKey(key)) return c.types().constants.get(key).explicitType(); + } if (c.types().enums.containsKey(i.name())) return PbsRuntimeTypes.type(i.name()); var owner = c.localTypes.get(i.name()); var fields = owner == null ? null : c.types().fields.get(owner.name()); @@ -1694,7 +1769,7 @@ final class PbsExecutableBodyLowerer { } int pops=0; for(int i=0;im.name().equals(member.memberName())&¶metersMatch(m.parameters(),call.arguments(),c) && returnMatches(m.returnType(),owner.name(),c)).findFirst().orElse(null); diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/lowering/PbsRuntimeTypes.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/lowering/PbsRuntimeTypes.java index c1dcd388..75021063 100644 --- a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/lowering/PbsRuntimeTypes.java +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/lowering/PbsRuntimeTypes.java @@ -18,6 +18,7 @@ final class PbsRuntimeTypes { final Map signatures = new HashMap<>(); final Map> functions = new HashMap<>(); final Map values = new HashMap<>(); + final Map constants = new HashMap<>(); private final Map used = new TreeMap<>(); final Map structs = new LinkedHashMap<>(); final Map contracts = new LinkedHashMap<>(); @@ -52,6 +53,8 @@ final class PbsRuntimeTypes { } if (decl instanceof PbsAst.HostDecl h) for(var f:h.signatures()) signatures.put(h.name()+"."+f.name()+"#"+f.parameters().size(), f); } + constants.putAll(p.studio.compiler.pbs.PbsServiceConstants.collect(ReadOnlyList.wrap(declarations))); + constants.forEach((name, constant) -> values.put(name, constant.explicitType())); for (var imported : ast.imports()) for (var item : imported.items()) { if (item.alias() == null || item.alias().isBlank()) continue; aliases.put(item.alias(), item.name()); diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/parser/PbsDeclarationParser.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/parser/PbsDeclarationParser.java index 289c1951..a2812ac3 100644 --- a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/parser/PbsDeclarationParser.java +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/parser/PbsDeclarationParser.java @@ -454,24 +454,36 @@ final class PbsDeclarationParser { final var name = consume(PbsTokenKind.IDENTIFIER, "Expected service name"); consume(PbsTokenKind.LEFT_BRACE, "Expected '{' to start service body"); final var methods = new ArrayList(); + final var constants = new ArrayList(); while (!cursor.check(PbsTokenKind.RIGHT_BRACE) && !cursor.isAtEnd()) { var methodAttributes = ReadOnlyList.empty(); if (cursor.check(PbsTokenKind.LEFT_BRACKET)) { methodAttributes = attributeParser.parseAttributeList(); } + if (cursor.match(PbsTokenKind.DECLARE)) { + var declaration = cursor.previous(); + consume(PbsTokenKind.CONST, "Expected const in service declaration"); + constants.add(parseConstDeclaration(declaration, methodAttributes)); + continue; + } if (!cursor.match(PbsTokenKind.FN)) { if (!methodAttributes.isEmpty()) { reportAttributesNotAllowed(methodAttributes, "Attributes are valid only on service methods in service bodies"); } report(cursor.peek(), ParseErrors.E_PARSE_INVALID_DECL_SHAPE, - "Service body accepts only method declarations"); + "Service body accepts methods and declare const declarations"); cursor.advance(); continue; } - methods.add(parseFunctionLike(cursor.previous(), methodAttributes)); + if (methodAttributes.stream().anyMatch(a -> "IntrinsicCall".equals(a.name()))) { + var signature = parseFunctionSignature(cursor.previous(), methodAttributes); + methods.add(new PbsAst.FunctionDecl(signature.name(), signature.parameters(), signature.returnKind(), + signature.returnType(), signature.resultErrorType(), signature.attributes(), PbsAst.LifecycleMarker.NONE, + new PbsAst.Block(ReadOnlyList.empty(), null, signature.span()), signature.span())); + } else methods.add(parseFunctionLike(cursor.previous(), methodAttributes)); } final var rightBrace = consume(PbsTokenKind.RIGHT_BRACE, "Expected '}' to end service body"); - return new PbsAst.ServiceDecl(name.lexeme(), ReadOnlyList.wrap(methods), attributes, span(declareToken.start(), rightBrace.end())); + return new PbsAst.ServiceDecl(name.lexeme(), ReadOnlyList.wrap(methods), ReadOnlyList.wrap(constants), attributes, span(declareToken.start(), rightBrace.end())); } private PbsAst.ErrorDecl parseErrorDeclaration( diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsAstDocumentSymbols.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsAstDocumentSymbols.java index e5611235..06356a93 100644 --- a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsAstDocumentSymbols.java +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsAstDocumentSymbols.java @@ -38,12 +38,14 @@ final class PbsAstDocumentSymbols { return structSymbol(structDecl); } if (topDecl instanceof PbsAst.ServiceDecl serviceDecl) { + var members = new ArrayList<>(methodSymbols(serviceDecl.methods())); + for (var constant : serviceDecl.constants()) symbolFor(constant).ifPresent(members::add); return namedSymbol( serviceDecl.name(), PbsEditorialSymbolKind.SERVICE, "", serviceDecl.span(), - methodSymbols(serviceDecl.methods())); + List.copyOf(members)); } if (topDecl instanceof PbsAst.ContractDecl contractDecl) { return namedSymbol( diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsConstSemanticsValidator.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsConstSemanticsValidator.java index 28d62a12..bd7d4edb 100644 --- a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsConstSemanticsValidator.java +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsConstSemanticsValidator.java @@ -30,7 +30,7 @@ final class PbsConstSemanticsValidator { } final var declaredType = typeOps.typeFromTypeRef(constDecl.explicitType(), model, null); - final var analysis = analyzeConstExpression(constDecl.initializer(), constByName, model, diagnostics); + final var analysis = analyzeConstExpression(constDecl.initializer(), constByName, model, diagnostics, entry.getKey().contains(".") ? entry.getKey().substring(0, entry.getKey().lastIndexOf('.')) : "", declaredType); dependencyGraph.put(entry.getKey(), analysis.dependencies()); if (!analysis.constant()) { @@ -55,11 +55,7 @@ final class PbsConstSemanticsValidator { private LinkedHashMap collectConstDeclarations(final PbsAst.File ast) { final var constByName = new LinkedHashMap(); - for (final var topDecl : ast.topDecls()) { - if (topDecl instanceof PbsAst.ConstDecl constDecl) { - constByName.putIfAbsent(constDecl.name(), constDecl); - } - } + constByName.putAll(p.studio.compiler.pbs.PbsServiceConstants.collect(ast.topDecls())); return constByName; } @@ -67,9 +63,10 @@ final class PbsConstSemanticsValidator { final PbsAst.Expression expression, final Map constByName, final Model model, - final DiagnosticSink diagnostics) { + final DiagnosticSink diagnostics, final String owner, final TypeView expectedType) { if (expression instanceof PbsAst.IntLiteralExpr || expression instanceof PbsAst.BoundedLiteralExpr) { - return new ConstAnalysis(TypeView.intType(), true, null, Set.of()); + return new ConstAnalysis(expectedType != null && expectedType.kind() == PbsFlowSemanticSupport.Kind.LONG + ? TypeView.longType() : TypeView.intType(), true, null, Set.of()); } if (expression instanceof PbsAst.FloatLiteralExpr) { return new ConstAnalysis(TypeView.floatType(), true, null, Set.of()); @@ -81,12 +78,13 @@ final class PbsConstSemanticsValidator { return new ConstAnalysis(TypeView.bool(), true, null, Set.of()); } if (expression instanceof PbsAst.GroupExpr groupExpr) { - return analyzeConstExpression(groupExpr.expression(), constByName, model, diagnostics); + return analyzeConstExpression(groupExpr.expression(), constByName, model, diagnostics, owner, expectedType); } if (expression instanceof PbsAst.IdentifierExpr identifierExpr) { - final var depName = identifierExpr.name(); + final var depName = !owner.isEmpty() && constByName.containsKey(owner + "." + identifierExpr.name()) + ? owner + "." + identifierExpr.name() : identifierExpr.name(); final var depDecl = constByName.get(depName); - if (depDecl == null || depDecl.explicitType() == null || depDecl.initializer() == null) { + if (depDecl == null || depDecl.explicitType() == null) { p.studio.compiler.source.diagnostics.Diagnostics.error(diagnostics, PbsSemanticsErrors.E_SEM_CONST_UNRESOLVED_REFERENCE.name(), "Const initializer references unresolved const '%s'".formatted(depName), @@ -100,6 +98,10 @@ final class PbsConstSemanticsValidator { Set.of(depName)); } if (expression instanceof PbsAst.MemberExpr memberExpr) { + var path = p.studio.compiler.pbs.PbsServiceConstants.path(memberExpr); + var constant = constByName.get(path); + if (constant != null) return new ConstAnalysis( + typeOps.typeFromTypeRef(constant.explicitType(), model, null), true, null, Set.of(path)); if (memberExpr.receiver() instanceof PbsAst.IdentifierExpr enumIdentifier) { final var cases = model.enums.get(enumIdentifier.name()); if (cases != null && cases.contains(memberExpr.memberName())) { @@ -109,7 +111,7 @@ final class PbsConstSemanticsValidator { return new ConstAnalysis(TypeView.unknown(), false, memberExpr.span(), Set.of()); } if (expression instanceof PbsAst.UnaryExpr unaryExpr) { - final var operand = analyzeConstExpression(unaryExpr.expression(), constByName, model, diagnostics); + final var operand = analyzeConstExpression(unaryExpr.expression(), constByName, model, diagnostics, owner, expectedType); if (!operand.constant()) { return operand; } @@ -122,8 +124,8 @@ final class PbsConstSemanticsValidator { return new ConstAnalysis(TypeView.unknown(), false, unaryExpr.span(), operand.dependencies()); } if (expression instanceof PbsAst.BinaryExpr binaryExpr) { - final var left = analyzeConstExpression(binaryExpr.left(), constByName, model, diagnostics); - final var right = analyzeConstExpression(binaryExpr.right(), constByName, model, diagnostics); + final var left = analyzeConstExpression(binaryExpr.left(), constByName, model, diagnostics, owner, expectedType); + final var right = analyzeConstExpression(binaryExpr.right(), constByName, model, diagnostics, owner, expectedType); final var deps = mergeDependencies(left.dependencies(), right.dependencies()); if (!left.constant()) { return new ConstAnalysis(TypeView.unknown(), false, left.invalidSpan(), deps); @@ -230,7 +232,7 @@ final class PbsConstSemanticsValidator { } private boolean isNumeric(final TypeView type) { - return typeOps.isInt(type) || typeOps.isFloat(type); + return typeOps.isInt(type) || type.kind() == PbsFlowSemanticSupport.Kind.LONG || typeOps.isFloat(type); } private boolean isArithmeticOperator(final String operator) { diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsDeclarationSemanticsValidator.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsDeclarationSemanticsValidator.java index 5eb92823..5a7ebce2 100644 --- a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsDeclarationSemanticsValidator.java +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsDeclarationSemanticsValidator.java @@ -232,9 +232,24 @@ public final class PbsDeclarationSemanticsValidator { final PbsDeclarationRuleValidator rules, final boolean interfaceModule, final DiagnosticSink diagnostics) { + final var members = new java.util.HashSet(); + for (var constant : serviceDecl.constants()) { + validateDocAttributes(constant.attributes(), "service constants", diagnostics); + var missingAllowed = validateConstDeclarationAttributes(constant, interfaceModule, diagnostics); + rules.validateConstDeclaration(constant, !missingAllowed); + if (!members.add(constant.name()) || serviceDecl.methods().stream().anyMatch(m -> m.name().equals(constant.name()))) + p.studio.compiler.source.diagnostics.Diagnostics.error(diagnostics, + "E_SEM_DUPLICATE_SERVICE_MEMBER", "Duplicate service member: " + constant.name(), constant.span()); + } final var methodScope = PbsCallableScope.serviceMethods(nameTable.register(serviceDecl.name())); for (final var method : serviceDecl.methods()) { validateDocAttributes(method.attributes(), "service methods", diagnostics); + if (method.attributes().stream().anyMatch(a -> ATTR_INTRINSIC_CALL.equals(a.name()))) { + if (!interfaceModule) reportInterfaceNonDeclarativeDecl(method.span(), + "Intrinsic service signatures are valid only in SDK interfaces", diagnostics); + validateIntrinsicCallAttributes(new PbsAst.FunctionSignature(method.name(), method.parameters(), + method.returnKind(), method.returnType(), method.resultErrorType(), method.attributes(), method.span()), diagnostics); + } validateCallable( methodScope, method.name(), diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsEditorialSupportService.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsEditorialSupportService.java index 04063d8a..f0120f89 100644 --- a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsEditorialSupportService.java +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsEditorialSupportService.java @@ -757,6 +757,12 @@ public final class PbsEditorialSupportService { } } } else if (receiverType.kind() == Kind.SERVICE || receiverType.kind() == Kind.CONTRACT) { + var prefix = receiverType.name() + "."; + model.serviceConstants.forEach((name, constant) -> { + if (name.startsWith(prefix)) completions.put(constant.name(), new PbsEditorialCompletionCandidate( + constant.name(), PbsEditorialSymbolKind.CONST, formatType(model.constTypes.get(name)), + receiverType.name(), Model.documentationFromAttributes(constant.attributes()))); + }); final Map> methods = receiverType.kind() == Kind.SERVICE ? Optional.ofNullable(model.services.get(receiverType.name())).map(ServiceInfo::methods).orElse(Map.of()) : Optional.ofNullable(model.contracts.get(receiverType.name())).map(ContractInfo::methods).orElse(Map.of()); @@ -864,6 +870,11 @@ public final class PbsEditorialSupportService { } } if (receiverType.kind() == Kind.SERVICE || receiverType.kind() == Kind.CONTRACT) { + var key = receiverType.name() + "." + memberName; + var constant = model.serviceConstants.get(key); + if (constant != null) return Optional.of(new PbsEditorialResolvedSymbol(memberName, + PbsEditorialSymbolKind.CONST, formatType(model.constTypes.get(key)), receiverType.name(), + List.of(), Model.documentationFromAttributes(constant.attributes()))); final Map> methods = receiverType.kind() == Kind.SERVICE ? Optional.ofNullable(model.services.get(receiverType.name())).map(ServiceInfo::methods).orElse(Map.of()) : Optional.ofNullable(model.contracts.get(receiverType.name())).map(ContractInfo::methods).orElse(Map.of()); @@ -981,6 +992,8 @@ public final class PbsEditorialSupportService { return callableLocations(structInfo.methods().get(memberName)); } if (receiverType.kind() == Kind.SERVICE || receiverType.kind() == Kind.CONTRACT) { + var constant = model.serviceConstants.get(receiverType.name() + "." + memberName); + if (constant != null) return locations(constant.span()); final Map> methods = receiverType.kind() == Kind.SERVICE ? Optional.ofNullable(model.services.get(receiverType.name())).map(ServiceInfo::methods).orElse(Map.of()) : Optional.ofNullable(model.contracts.get(receiverType.name())).map(ContractInfo::methods).orElse(Map.of()); @@ -2146,7 +2159,7 @@ public final class PbsEditorialSupportService { builtinTypeDecl.span()); } if (topDecl instanceof PbsAst.ServiceDecl serviceDecl) { - return new PbsAst.ServiceDecl(newName, serviceDecl.methods(), serviceDecl.attributes(), serviceDecl.span()); + return new PbsAst.ServiceDecl(newName, serviceDecl.methods(), serviceDecl.constants(), serviceDecl.attributes(), serviceDecl.span()); } if (topDecl instanceof PbsAst.HostDecl hostDecl) { return new PbsAst.HostDecl(newName, hostDecl.signatures(), hostDecl.attributes(), hostDecl.span()); diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsFlowBodyAnalyzer.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsFlowBodyAnalyzer.java index 69318048..7ba25241 100644 --- a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsFlowBodyAnalyzer.java +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsFlowBodyAnalyzer.java @@ -172,6 +172,7 @@ final class PbsFlowBodyAnalyzer { final DiagnosticSink diagnostics) { final var receiverType = TypeView.service(serviceDecl.name()); for (final var method : serviceDecl.methods()) { + if (method.attributes().stream().anyMatch(a -> "IntrinsicCall".equals(a.name()))) continue; validateCallableBody( method.parameters(), method.body(), diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsFlowCallableResolutionAnalyzer.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsFlowCallableResolutionAnalyzer.java index cbb3b446..a0a8e6b8 100644 --- a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsFlowCallableResolutionAnalyzer.java +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsFlowCallableResolutionAnalyzer.java @@ -217,6 +217,8 @@ final class PbsFlowCallableResolutionAnalyzer { if (service == null) { return ExprResult.type(TypeView.unknown()); } + var constant = model.constTypes.get(receiver.name() + "." + memberExpr.memberName()); + if (constant != null) return ExprResult.type(constant); final var methods = service.methods().get(memberExpr.memberName()); if (methods != null && !methods.isEmpty()) { if (use == ExprUse.VALUE) { @@ -293,7 +295,7 @@ final class PbsFlowCallableResolutionAnalyzer { if (compatible.isEmpty()) { Diagnostics.error(diagnostics, PbsSemanticsErrors.E_SEM_APPLY_UNRESOLVED_OVERLOAD.name(), - "No callable overload matches the provided argument", + "No callable overload matches the provided argument; numeric carriers require explicit conversion", wholeSpan); return ExprResult.type(TypeView.unknown()); } diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsFlowSemanticSupport.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsFlowSemanticSupport.java index bd520cc1..808d97b5 100644 --- a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsFlowSemanticSupport.java +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsFlowSemanticSupport.java @@ -197,6 +197,7 @@ final class PbsFlowSemanticSupport { final Map> enums = new HashMap<>(); final Map> errors = new HashMap<>(); final Map constTypes = new HashMap<>(); + final Map serviceConstants = new HashMap<>(); final Map globalTypes = new HashMap<>(); final Map serviceSingletons = new HashMap<>(); final Set knownBuiltinTypeNames = new HashSet<>(); @@ -230,6 +231,11 @@ final class PbsFlowSemanticSupport { for (final var topDecl : supplementalTopDecls) { model.ingestTopDecl(topDecl); } + for (var imported : ast.imports()) for (var item : imported.items()) { + if (item.alias() == null || item.alias().isBlank() || !model.services.containsKey(item.name())) continue; + model.services.put(item.alias(), model.services.get(item.name())); + model.serviceSingletons.put(item.alias(), TypeView.service(item.name())); + } model.ingestAssetSurface(feSurfaceContext, diagnostics); return model; } @@ -333,6 +339,11 @@ final class PbsFlowSemanticSupport { method.span(), documentationFromAttributes(method.attributes()))); } + for (var constant : serviceDecl.constants()) { + var key = serviceDecl.name() + "." + constant.name(); + constTypes.put(key, typeFrom(constant.explicitType())); + serviceConstants.put(key, constant); + } services.put(serviceDecl.name(), new ServiceInfo(methods)); serviceSingletons.put(serviceDecl.name(), TypeView.service(serviceDecl.name())); return; @@ -494,7 +505,7 @@ final class PbsFlowSemanticSupport { return new CallableSymbol(name, semanticParameters, input, callableReturn(returnKind, returnType, resultErrorType), span, documentation); } - private String documentationFromAttributes(final ReadOnlyList attributes) { + static String documentationFromAttributes(final ReadOnlyList attributes) { for (final var attribute : attributes) { if (!"Doc".equals(attribute.name()) || attribute.arguments().isEmpty()) { continue; diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsFlowStructuralExpressionAnalyzer.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsFlowStructuralExpressionAnalyzer.java index f7100758..27519883 100644 --- a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsFlowStructuralExpressionAnalyzer.java +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsFlowStructuralExpressionAnalyzer.java @@ -114,6 +114,10 @@ final class PbsFlowStructuralExpressionAnalyzer { return ExprResult.type(serviceType); } + if (receiverType != null && receiverType.kind() == Kind.SERVICE) { + var member = model.constTypes.get(receiverType.name() + "." + identifierExpr.name()); + if (member != null) return ExprResult.type(member); + } final var constType = model.constTypes.get(identifierExpr.name()); if (constType != null) { return ExprResult.type(constType); diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/services/PbsImportedSemanticContextService.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/services/PbsImportedSemanticContextService.java index 8c77b7eb..7e3df9e3 100644 --- a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/services/PbsImportedSemanticContextService.java +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/services/PbsImportedSemanticContextService.java @@ -87,7 +87,7 @@ final class PbsImportedSemanticContextService { if (topDecl instanceof PbsAst.ServiceDecl serviceDecl) { var accessor = p.studio.compiler.pbs.lowering.PbsExecutableCallableRegistryFactory.singletonAccessor(serviceDecl); appendImportedCallable(importedCallables, importedCallableKeys, - new PbsFrontendCompiler.ImportedCallableSurface(importedModuleId, localName+".$instance", 0, 1, + new PbsFrontendCompiler.ImportedCallableSurface(importedModuleId, serviceDecl.name()+".$instance", 0, 1, accessor.returnKind(), accessor.returnType(), frontendCompiler.callableShapeSurfaceOf(accessor))); for (final var method : serviceDecl.methods()) { appendImportedCallable( @@ -95,7 +95,7 @@ final class PbsImportedSemanticContextService { importedCallableKeys, new PbsFrontendCompiler.ImportedCallableSurface( importedModuleId, - localName + "." + method.name(), + serviceDecl.name() + "." + method.name(), method.parameters().size(), returnSlotsFor(method), method.returnKind(), diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/sdk/math/main.pbs b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/sdk/math/main.pbs new file mode 100644 index 00000000..ec8abd71 --- /dev/null +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/sdk/math/main.pbs @@ -0,0 +1,29 @@ +[Doc(markdown = """ +Runtime-owned numeric operations with exact carrier signatures. +""")] +declare service math { + [IntrinsicCall(name = "math.i32.min", version = 1)] + fn min(a: int, b: int) -> int; + [IntrinsicCall(name = "math.i32.max", version = 1)] + fn max(a: int, b: int) -> int; + [IntrinsicCall(name = "math.i32.clamp", version = 1)] + fn clamp(value: int, min: int, max: int) -> int; + [IntrinsicCall(name = "math.i32.abs", version = 1)] + fn abs(value: int) -> int; + [IntrinsicCall(name = "math.i32.to_i64", version = 1)] + fn to_i64(value: int) -> long; + [IntrinsicCall(name = "math.i32.to_float", version = 1)] + fn to_float(value: int) -> float; + [IntrinsicCall(name = "math.i64.min", version = 1)] + fn min(a: long, b: long) -> long; + [IntrinsicCall(name = "math.i64.max", version = 1)] + fn max(a: long, b: long) -> long; + [IntrinsicCall(name = "math.i64.clamp", version = 1)] + fn clamp(value: long, min: long, max: long) -> long; + [IntrinsicCall(name = "math.i64.abs", version = 1)] + fn abs(value: long) -> long; + [IntrinsicCall(name = "math.i64.to_i32", version = 1)] + fn to_i32(value: long) -> int; + [IntrinsicCall(name = "math.i64.to_float", version = 1)] + fn to_float(value: long) -> float; +} diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/sdk/math/mod.barrel b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/sdk/math/mod.barrel new file mode 100644 index 00000000..3fe1fb97 --- /dev/null +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/sdk/math/mod.barrel @@ -0,0 +1 @@ +pub service math; diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/sdk/mathf/main.pbs b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/sdk/mathf/main.pbs new file mode 100644 index 00000000..34a1f17c --- /dev/null +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/sdk/mathf/main.pbs @@ -0,0 +1,37 @@ +[Doc(markdown = """ +Runtime-owned numeric operations with exact carrier signatures. +""")] +declare service mathf { + [IntrinsicCall(name = "mathf.min", version = 1)] + fn min(a: float, b: float) -> float; + [IntrinsicCall(name = "mathf.max", version = 1)] + fn max(a: float, b: float) -> float; + [IntrinsicCall(name = "mathf.clamp", version = 1)] + fn clamp(value: float, min: float, max: float) -> float; + [IntrinsicCall(name = "mathf.abs", version = 1)] + fn abs(value: float) -> float; + [IntrinsicCall(name = "mathf.floor", version = 1)] + fn floor(value: float) -> float; + [IntrinsicCall(name = "mathf.ceil", version = 1)] + fn ceil(value: float) -> float; + [IntrinsicCall(name = "mathf.trunc", version = 1)] + fn trunc(value: float) -> float; + [IntrinsicCall(name = "mathf.round", version = 1)] + fn round(value: float) -> float; + [IntrinsicCall(name = "mathf.sqrt", version = 1)] + fn sqrt(value: float) -> float; + [IntrinsicCall(name = "mathf.sin", version = 1)] + fn sin(angle: float) -> float; + [IntrinsicCall(name = "mathf.cos", version = 1)] + fn cos(angle: float) -> float; + [IntrinsicCall(name = "mathf.atan2", version = 1)] + fn atan2(y: float, x: float) -> float; + [IntrinsicCall(name = "mathf.to_i32", version = 1)] + fn to_i32(value: float) -> int; + [IntrinsicCall(name = "mathf.to_i64", version = 1)] + fn to_i64(value: float) -> long; + [BuiltinConst(target = "mathf", name = "pi", version = 1)] + declare const pi: float; + [BuiltinConst(target = "mathf", name = "tau", version = 1)] + declare const tau: float; +} diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/sdk/mathf/mod.barrel b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/sdk/mathf/mod.barrel new file mode 100644 index 00000000..e72c737d --- /dev/null +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/sdk/mathf/mod.barrel @@ -0,0 +1 @@ +pub service mathf; diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/pbs-knowledge/examples/game/1/src/math.pbs b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/pbs-knowledge/examples/game/1/src/math.pbs new file mode 100644 index 00000000..9bfd1ed9 --- /dev/null +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/pbs-knowledge/examples/game/1/src/math.pbs @@ -0,0 +1,8 @@ +import { math } from @sdk:math; +import { mathf as numbers } from @sdk:mathf; + +fn mathExample() -> float { + let counter: long = 42; + let bounded = math.clamp(counter, 0 as long, 100 as long); + return math.to_float(bounded) + numbers.sin(0.0) + numbers.pi; +} diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/test/java/p/studio/compiler/pbs/semantics/PbsEditorialSupportServiceTest.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/test/java/p/studio/compiler/pbs/semantics/PbsEditorialSupportServiceTest.java index 4319e099..54987551 100644 --- a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/test/java/p/studio/compiler/pbs/semantics/PbsEditorialSupportServiceTest.java +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/test/java/p/studio/compiler/pbs/semantics/PbsEditorialSupportServiceTest.java @@ -16,6 +16,15 @@ import static org.junit.jupiter.api.Assertions.*; final class PbsEditorialSupportServiceTest { private final PbsEditorialSupportService service = new PbsEditorialSupportService(); + @Test void serviceConstantsHaveCompletionHoverAndDefinition() { + String source = "declare service Settings { declare const answer: int = 42; } fn main() -> int { return Settings.answer; }"; + var ast = parseOrdinary(source); + int use = source.indexOf("Settings.answer"); + assertTrue(service.completion(source, ast, ReadOnlyList.empty(), use+9).stream().anyMatch(c -> c.label().equals("answer") && c.kind() == PbsEditorialSymbolKind.CONST)); + assertTrue(service.hover(source, ast, ReadOnlyList.empty(), use+10).isPresent()); + assertFalse(service.definition(source, ast, ReadOnlyList.empty(), use+10).isEmpty()); + } + @Test void closuresExposeCapturedObjectsAndOwnParameters() { String source = """ diff --git a/tools/pbx-conformance/README.md b/tools/pbx-conformance/README.md index 515e18e2..921e1819 100644 --- a/tools/pbx-conformance/README.md +++ b/tools/pbx-conformance/README.md @@ -131,3 +131,32 @@ threshold collections, retained closure/object reachability after frame one, and reclamation after release. The remaining root is the global array. PBS publishes FRAME_ROOT and the existing guarded wrapper returns normally. No sync syntax, new frame integration, suspension or coroutine is introduced. + +## PBS service constants and runtime math + +`PbsRuntimeMathTest` produces 261 independent numeric cases in both ordinary and +optimized bytecode (522 mandatory executions per runtime profile), covering all +26 math/mathf signatures. The checked-in corpus preserves 240 provider scalar +fixture rows and exact contract examples (duplicates removed); provenance is in +`prometeu-architecture-tests/src/test/resources/math/provenance.txt`. + +The harness verifies exact bits/faults, selected intrinsic identity and one +retained call per case. Single-step charging is compared with the provider's +opcode costs and independent fixture call cost; full-budget charging must equal +their sum, and optimization must preserve total cycles. Additional cases exercise +pi/tau, literal sin, ordinary int/long service constants, constant dependencies, +and real module imports with service aliases. The installed example also imports +both SDK services, so installedKnowledgeTest covers their packaged resources. + +```sh +./gradlew :prometeu-architecture-tests:test --tests '*PbsRuntimeMathTest' +python3 tools/pbx-conformance/run.py --runtime ../runtime --math-only +python3 tools/pbx-conformance/run.py --runtime ../runtime --math-only --release +``` + +Omit `--math-only` for the full existing corpus. `--release` selects the optimized +Rust runtime harness; it is independent of the PBS optimizer variants included in +every run. Optional `CARGO_TARGET_DIR` can retain build artifacts outside the +runtime checkout. Each invocation prints runtime revision, platform, profile, +features, lockfile and provider catalog/oracle hashes. Local evidence qualifies +macOS/arm64 only; macOS/x86_64 and Linux/x86_64 remain pending. diff --git a/tools/pbx-conformance/main.rs b/tools/pbx-conformance/main.rs index 80d2f052..6876e536 100644 --- a/tools/pbx-conformance/main.rs +++ b/tools/pbx-conformance/main.rs @@ -36,6 +36,8 @@ impl NativeInterface for NoNative { fn main() { let root = std::path::PathBuf::from(std::env::args().nth(1).expect("fixture directory")); + verify_pbs_math_fixtures(&root); + if std::env::args().any(|arg| arg == "--math-only") { return; } verify_catalog_fixtures(&root); verify_pbs_fixtures(&root); verify_pbs_structured_fixtures(&root); @@ -475,7 +477,7 @@ fn verify_pbs_fixtures(root: &std::path::Path) { for entry in std::fs::read_dir(root).unwrap() { let path = entry.unwrap().path(); let name = path.file_stem().unwrap().to_str().unwrap(); - if name.starts_with("pbs-structured-") || !name.starts_with("pbs-") || path.extension().and_then(|v| v.to_str()) != Some("pbx") { continue; } + if name.starts_with("pbs-math-") || name.starts_with("pbs-structured-") || !name.starts_with("pbs-") || path.extension().and_then(|v| v.to_str()) != Some("pbx") { continue; } count += 1; let bytes = std::fs::read(&path).unwrap(); let image = ValidatedProgramImage::load(&bytes, &mut LoadBudget::new(LoadLimits::default()), caps::NONE) @@ -630,3 +632,97 @@ fn verify_pbs_closure_frames(root: &std::path::Path) { } println!("PBS CLOSURE FRAME LIFECYCLE/RETENTION/GC PASS"); } + +// The expected results/call costs are independent provider fixtures. Step costs +// use the published opcode contract, not observed timings or compiler estimates. +fn verify_pbs_math_fixtures(root: &std::path::Path) { + use prometeu_vm::LogicalFrameEndingReason as End; + use prometeu_bytecode::isa::core::CoreOpCode as OpCode; + let corpus = std::fs::read_to_string(root.join("math-vectors.tsv")).expect("mandatory math corpus"); + let mut covered = std::collections::BTreeSet::new(); + let mut count = 0; + let mut original_cycles = std::collections::BTreeMap::new(); + let mut names = std::collections::BTreeSet::new(); + for line in corpus.lines() { + let parts: Vec<_> = line.split_whitespace().collect(); + let name = parts[0]; + assert!(names.insert(parts[0]), "duplicate math fixture"); + let id = u32::from_str_radix(parts[1], 16).unwrap(); + let expected = parts[parts.len()-2]; + let cost: u64 = parts.last().unwrap().parse().unwrap(); + let bytes = std::fs::read(root.join(format!("{name}.pbx"))).unwrap(); + let image = ValidatedProgramImage::load(&bytes, &mut LoadBudget::new(LoadLimits::default()), caps::NONE).unwrap(); + let code = image.code().to_vec(); + let mut vm = VirtualMachine::from_image(image, Default::default()); + vm.prepare_boot_call().unwrap(); + let mut total = 0; + let mut calls = 0; + let ending = loop { + let pc = vm.pc(); + let opcode = OpCode::try_from(u16::from_le_bytes(code[pc..pc+2].try_into().unwrap())).unwrap(); + let cycles = if opcode == OpCode::Intrinsic { + let actual = u32::from_le_bytes(code[pc+2..pc+6].try_into().unwrap()); + assert_eq!(actual, id, "{name}: wrong overload or unexpected conversion"); + calls += 1; + cost + } else { opcode.cycles() }; + let report = vm.run_budget(1, &mut NoNative, &mut HostContext::new(None)).unwrap(); + assert_eq!(report.cycles_used, cycles, "{name}: cycle charge at {pc}, {opcode:?}"); + total += cycles; + if matches!(report.reason, End::Halted | End::EndOfRom | End::Trap(_)) { break report.reason; } + assert!(total < 10000, "{name}: nonterminating source fixture"); + }; + assert_eq!(calls, 1, "{name}: preserve literal calls and no hidden conversions"); + if let Some(code) = expected.strip_prefix("trap:") { + let code = u32::from_str_radix(code,16).unwrap(); + assert!(matches!(ending, End::Trap(ref trap) if trap.code == code), "{name}: {ending:?}"); + } else { + assert!(matches!(ending, End::Halted | End::EndOfRom), "{name}: {ending:?}"); + let value = vm.operand_stack_top(1); + let actual = match &value[0] { + Value::Float(value) => format!("f:{:016x}",value.to_bits()), + Value::Int32(value) => format!("i:{value}"), + Value::Int64(value) => format!("l:{value}"), + value => panic!("{name}: unexpected value {value:?}"), + }; + assert_eq!(actual, expected, "{name}: exact result bits"); + } + // A full-budget execution must charge exactly the independently checked steps. + let image = ValidatedProgramImage::load(&bytes, &mut LoadBudget::new(LoadLimits::default()), caps::NONE).unwrap(); + let mut vm = VirtualMachine::from_image(image, Default::default()); + vm.prepare_boot_call().unwrap(); + let report = vm.run_budget(10000, &mut NoNative, &mut HostContext::new(None)).unwrap(); + assert_eq!(report.cycles_used, total, "{name}: aggregate cost"); + if let Some(original) = name.strip_suffix("-optimized") { + assert_eq!(original_cycles.get(original), Some(&total), "{name}: optimization changed cycles"); + } else { original_cycles.insert(name.to_string(), total); } + covered.insert(id); + count += 1; + } + assert_eq!(covered, (0x3000..=0x3019).collect()); + assert_eq!(count, 522, "mandatory boundary corpus missing"); + for (name, expected) in [("pi", Value::Float(f64::from_bits(0x400921fb54442d18))), + ("tau", Value::Float(f64::from_bits(0x401921fb54442d18))), + ("literal", Value::Float(-0.0)), ("dependency", Value::Int32(42)), ("long", Value::Int64(2147483648)), + ("service", Value::Int32(42)), ("min", Value::Int64(42))] { + let bytes = std::fs::read(root.join(format!("pbs-math-{name}.pbx"))).unwrap(); + let image = ValidatedProgramImage::load(&bytes, &mut LoadBudget::new(LoadLimits::default()), caps::NONE).unwrap(); + let mut vm = VirtualMachine::from_image(image, Default::default()); + vm.prepare_boot_call().unwrap(); + let report = vm.run_budget(10000, &mut NoNative, &mut HostContext::new(None)).unwrap(); + assert!(matches!(report.reason, End::Halted | End::EndOfRom), "{name}: {report:?}"); + let actual = vm.operand_stack_top(1); + match (&actual[0], &expected) { + (Value::Float(a), Value::Float(b)) => assert_eq!(a.to_bits(), b.to_bits(), "{name}"), + _ => assert_eq!(actual, vec![expected]), + } + if name == "pi" || name == "tau" || name == "service" { assert_eq!(report.cycles_used, 6, "constant load + root RET only"); } + } + let bytes = std::fs::read(root.join("pbs-math-import.pbx")).expect("real SDK imports fixture"); + let image = ValidatedProgramImage::load(&bytes, &mut LoadBudget::new(LoadLimits::default()), caps::NONE).unwrap(); + let mut vm = VirtualMachine::from_image(image, Default::default()); + vm.prepare_boot_call().unwrap(); + let report = vm.run_budget(10000, &mut NoNative, &mut HostContext::new(None)).unwrap(); + assert!(matches!(report.reason, End::Halted | End::EndOfRom), "import: {report:?}"); + println!("PBS MATH PASS: {count} exact bits/faults/cycle vectors; all 26 signatures; service constants"); +} diff --git a/tools/pbx-conformance/run.py b/tools/pbx-conformance/run.py index 9ada0de8..3b93c2f9 100644 --- a/tools/pbx-conformance/run.py +++ b/tools/pbx-conformance/run.py @@ -1,5 +1,6 @@ """Build a production-loader harness without writing into the runtime checkout.""" import argparse +import hashlib import json import pathlib import platform @@ -10,10 +11,15 @@ parser = argparse.ArgumentParser() parser.add_argument("--runtime", type=pathlib.Path, default=pathlib.Path("../runtime")) parser.add_argument("--fixtures", type=pathlib.Path, default=pathlib.Path("prometeu-compiler/prometeu-build-pipeline/build/registry-conformance")) parser.add_argument("--online", action="store_true", help="Allow Cargo to fetch uncached dependencies") +parser.add_argument("--release", action="store_true", help="Execute an optimized runtime harness") +parser.add_argument("--math-only", action="store_true", help="Run the complete PBS math corpus only") args = parser.parse_args() runtime = args.runtime.resolve() print("runtime", subprocess.check_output(["git", "-C", str(runtime), "rev-parse", "HEAD"], text=True).strip(), flush=True) print("platform", platform.platform(), "limits=default capabilities=NONE", flush=True) +print("profile", "release" if args.release else "dev", "features=resource-diagnostics", flush=True) +for relative in ["Cargo.lock", "docs/vm-arch/INTRINSICS.csv", "docs/vm-arch/BUILTIN_CONSTANTS.csv", "crates/console/prometeu-vm/tests/fixtures/numeric-conformance.tsv"]: + print("sha256", relative, hashlib.sha256((runtime / relative).read_bytes()).hexdigest(), flush=True) with tempfile.TemporaryDirectory(prefix="pbx-conformance-") as directory: root = pathlib.Path(directory) manifest = '[package]\nname="studio-pbx-conformance"\nversion="0.1.0"\nedition="2024"\n[dependencies]\n' @@ -25,4 +31,4 @@ with tempfile.TemporaryDirectory(prefix="pbx-conformance-") as directory: (root / "Cargo.lock").write_text((runtime / "Cargo.lock").read_text()) (root / "src").mkdir() (root / "src/main.rs").write_text(pathlib.Path(__file__).with_name("main.rs").read_text()) - subprocess.run(["cargo", "run", *([] if args.online else ["--offline"]), "--manifest-path", str(root / "Cargo.toml"), "--", str(args.fixtures.resolve()), str(runtime / "devtools/headless-protocol/response.schema.json")], check=True) + subprocess.run(["cargo", "run", *(["--release"] if args.release else []), *([] if args.online else ["--offline"]), "--manifest-path", str(root / "Cargo.toml"), "--", str(args.fixtures.resolve()), str(runtime / "devtools/headless-protocol/response.schema.json"), *(["--math-only"] if args.math_only else [])], check=True)