feat(pbs): align typed values and Pad input facade
This commit is contained in:
@@ -189,8 +189,8 @@ acknowledge completed cleanup; control stays locked until cleanup is confirmed.
|
||||
The following findings are recorded for investigation after implementation; they
|
||||
are not considered fixed by the passing integration tests:
|
||||
|
||||
- **PBS/LSP SDK navigation:** definition lookup for the bundled SDK's `Input.pad()`
|
||||
currently returns no location. Project-source navigation and indexed SDK reference
|
||||
- **PBS/LSP SDK navigation:** the historical probe of the former `Input.pad()`
|
||||
API returned no location; the current input API is `Pad`/`Button` and `Touch`. Project-source navigation and indexed SDK reference
|
||||
reads work. Investigate SDK symbol resolution separately; an empty definition
|
||||
result is not evidence of missing runtime support or permission to edit the SDK.
|
||||
- **Build tooling:** the validation environment's JDK 25 triggers Kotlin's target-24
|
||||
|
||||
+83
@@ -0,0 +1,83 @@
|
||||
---
|
||||
id: LSN-0081
|
||||
ticket: pbs-existing-types-input-alignment
|
||||
title: PBS Typed Values and Direct Input Queries
|
||||
created: 2026-10-15
|
||||
tags: [compiler/pbs, runtime-integration]
|
||||
---
|
||||
|
||||
## Context and result
|
||||
|
||||
Owner: **compiler/pbs**, with shared compiler IR and installed Studio consumer propagation. DSC-0076 (AGD-0078, accepted DEC-0065, completed PLN-0144) aligned existing PBS values and input with the published runtime. The original object chain exposed intermediate input objects that had no useful runtime representation. PBS also omitted exact executable function metadata, causing the full installed example to fail at `Gfx.clear` under the shared typed registry validator.
|
||||
|
||||
The delivered implementation replaces those chains, produces typed function metadata, preserves complete value groups, and passes both actual-runtime execution and the full installed knowledge gate. The completed agenda, decision and plan were removed through framework housekeeping; this lesson preserves their implementation evidence.
|
||||
|
||||
## Public selectors and direct runtime endpoints
|
||||
|
||||
Use a nominal selector value and a public query:
|
||||
|
||||
```pbs
|
||||
let button = Button.A;
|
||||
let pressed = Pad.pressed(button);
|
||||
let frames: long = Pad.hold(button);
|
||||
let x: long = Touch.x();
|
||||
```
|
||||
|
||||
`Button` has twelve cases: Up, Down, Left, Right, A, B, X, Y, L, R, Start, Select. The four Pad operations are pressed, released, down and hold. Each public function dispatches through an exhaustive enum switch to one of the 48 zero-argument LowPad endpoints. For example, `Pad.pressed(Button.A)` reaches `LowPad.a_pressed()`, bound to `input.pad.a.pressed`. The selector is evaluated once and only the selected endpoint reads input. Obtaining or passing a Button has no input effect. Constant specialization is unnecessary for correctness.
|
||||
|
||||
Touch exposes pressed/released/down as Bool and hold/x/y as Int64. The implementation uses existing runtime endpoints, with no ABI or lifecycle redesign. `Input.pad().a()` and aliases of its intermediate object are removed; import diagnostics explain the replacement. Strings, integers and unrelated enums cannot substitute for Button. The source type remains nominal even though its executable carrier is Int32.
|
||||
|
||||
## Exact values must survive frontend lowering
|
||||
|
||||
The explicitly accepted integer mapping is `int` to Int32 and `long` to Int64. Integer literals default to int; an explicit long context admits Int64 literals. Conversions use existing `as` syntax. Variables of different numeric widths require explicit conversion. Pad.hold and Touch.hold/x/y therefore return long.
|
||||
|
||||
`PbsRuntimeTypes` connects source types and declarations to canonical registry types and exact parameter/result groups. Callable lookup includes arity so overloaded SDK functions do not overwrite each other's signatures. Existing unsupported source types retain their previous executable boundary; shared strict metadata validation was not relaxed to admit them.
|
||||
|
||||
Locals, parameters, calls and returns carry whole groups: vec2 uses two Float slots and pixel uses two Int64 coordinates plus color. Slot count alone never establishes type identity. Builtin constants are resolved through the shared constant catalog: vec2.zero materializes two Float zero values, without inventing a one-result intrinsic. The backend validates the declared group width against the catalog materialization.
|
||||
|
||||
Named application first evaluates expressions in source order, stores their complete groups, and then loads those values in parameter order. The runtime proof calls `combine apply (y: Probe.y(), x: Probe.x())`: effects record Y then X while combine receives x then y. Its final oracle is 211020.
|
||||
|
||||
## Qualification evidence
|
||||
|
||||
Qualification date: 2026-10-15; platform: Darwin arm64. Studio base revision: `603ed012272b137361ba618f6887f015f7317803` plus this delivery's working-tree changes. Runtime revision: `f7d7c167531bb662a1af9d73fc326bb476bf8aa7`. The runtime checkout was not modified. Default Gradle configuration; controlled input and no-platform configurations in the real runtime harness.
|
||||
|
||||
```sh
|
||||
./gradlew :prometeu-compiler:frontends:prometeu-frontend-pbs:test :prometeu-compiler:prometeu-build-pipeline:test :prometeu-compiler:prometeu-frontend-api:test :prometeu-lsp:prometeu-lsp-v1:test :prometeu-app:installedKnowledgeTest --console=plain
|
||||
CARGO_TARGET_DIR=/tmp/pln144-cargo-target python3 tools/pbx-conformance/run.py --runtime ../runtime
|
||||
git diff --check
|
||||
discussion validate
|
||||
```
|
||||
|
||||
| Suite | Passed | Existing skips | Failures/errors |
|
||||
| --- | ---: | ---: | ---: |
|
||||
| PBS frontend | 246 | 0 | 0 |
|
||||
| Build pipeline | 179 | 12 | 0 |
|
||||
| Frontend API | 28 | 0 | 0 |
|
||||
| LSP | 38 | 1 | 0 |
|
||||
| Full installed knowledge | 2 | 0 | 0 |
|
||||
|
||||
`PbsRuntimeAlignmentTest` generates 114 PBX programs through the production compiler, lowerer, emitter and preload verifier. The actual runtime harness loads and executes all of them:
|
||||
|
||||
- 48 Pad combinations using a local Button passed through a typed function, plus 48 direct constant combinations; controlled input asserts the exact returned value and exactly one selected read.
|
||||
- All six Touch queries, including signed x/y values. All 102 input programs are also executed without a platform and must trap with TRAP_UNAVAILABLE.
|
||||
- Twelve value/fault programs cover Int32, Int64, Float, String, color, vec2, pixel, tuple returns, named evaluation order, Int32 wrapping, checked narrowing and division by zero. Bool is covered by input queries. Registry default layouts are checked for all eight existing canonical value types.
|
||||
|
||||
Frontend negatives cover invalid Button arguments, mixed int/long variables, literal overflow and migration diagnostics. Existing shared tests continue to cover wrong typed signatures, stale touch signatures, unreachable removed IDs, and lifecycle assembly. The original full installed failure at `Gfx.clear` is fixed. This does not claim completion of the separate Studio desktop integration agenda. Existing upstream fault-schema gaps (LifecycleRole/NonFiniteValue) remain explicitly reported by the shared harness, without suppressing this delivery's oracles.
|
||||
|
||||
## Pitfalls and reusable patterns
|
||||
|
||||
- A dotted builtin target is already a complete catalog name: use `input.pad.a.pressed`, not a partial `a.pressed` that silently loses its owner.
|
||||
- A numeric literal's context must reach calls, returns and constructors; parsing an integer into a wide host value is insufficient to give it an Int64 guest type.
|
||||
- Handle the signed minimum literal before rejecting its positive magnitude. A positive value above Int64 maximum must produce a diagnostic, not become zero.
|
||||
- Preserve catalog overflow behavior: Int32 addition wraps; out-of-range narrowing traps with TRAP_NUMERIC_RANGE. Do not assume all numeric operations trap on overflow.
|
||||
- A switch can omit its final comparison only when exhaustive coverage is proven. Non-exhaustive statement switches must not execute an unmatched final arm.
|
||||
- A catalog or structural test alone cannot prove a frontend consumer. Generate PBS programs, run the real VM, and keep the full installed example as an independent gate.
|
||||
- Publish the focused canonical spec in installed knowledge as well as in the checkout. SDK exports, diagnostics, language services and examples must migrate together.
|
||||
|
||||
## References
|
||||
|
||||
- [Normative PBS input and existing-value contract](../../../docs/compiler/pbs/specs/input-and-existing-type-runtime-alignment.md)
|
||||
- [Shared runtime catalog contract](../../../docs/compiler/general/specs/runtime-catalog-support.md)
|
||||
- [Typed registry and PBX contract](../../../docs/compiler/general/specs/typed-registry-and-pbx-v0.md)
|
||||
- [PBS source-to-PBX qualification](../../../prometeu-compiler/prometeu-build-pipeline/src/test/java/p/studio/compiler/backend/irvm/PbsRuntimeAlignmentTest.java)
|
||||
- [Actual-runtime harness instructions](../../../tools/pbx-conformance/README.md)
|
||||
@@ -93,3 +93,14 @@ installed-runtime qualification remain separate consumer claims.
|
||||
See [typed common Registry and PBX v0](typed-registry-and-pbx-v0.md) for the
|
||||
frontend/backend boundary and [mirror policy](../../../vm-arch/README.md) for
|
||||
explicit verification commands.
|
||||
|
||||
|
||||
## PBS consumer
|
||||
|
||||
The [PBS input and value alignment contract](../../pbs/specs/input-and-existing-type-runtime-alignment.md)
|
||||
requires typed Pad/Button dispatch, direct LowPad endpoints and complete builtin
|
||||
value groups. Frontend numeric literal and builtin-constant operations retain
|
||||
explicit identity and width; common lowering resolves constant groups against
|
||||
`IRVMBuiltinConstantDefinition` and checks the declared result width. PBS does
|
||||
not introduce another catalog. Source execution and the full installed example
|
||||
are separate consumer gates beyond CSV parity.
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
# PBS input and existing value runtime alignment
|
||||
|
||||
Status: normative. Owner: `compiler/pbs`. Common ABI authority:
|
||||
[typed Registry/PBX](../../general/specs/typed-registry-and-pbx-v0.md) and
|
||||
[runtime catalogs](../../general/specs/runtime-catalog-support.md).
|
||||
|
||||
## Source types and exact carriers
|
||||
|
||||
| PBS source | Runtime identity | Ordered slots |
|
||||
| --- | --- | --- |
|
||||
| `int` | Int32 | Int32 |
|
||||
| `long` | Int64 | Int64 |
|
||||
| `float` | Float | Float (binary64) |
|
||||
| `bool` | Bool | Bool |
|
||||
| `str` | String | String |
|
||||
| builtin `color` shell | color | Int64 constrained to RGBA8888 |
|
||||
| builtin `vec2` shell | vec2 | Float x, Float y |
|
||||
| builtin `pixel` shell | pixel | Int64 x, Int64 y, Int64 color |
|
||||
|
||||
The canonical builtin metadata determines a shell's identity; its source name
|
||||
is not an ABI lookup rule. Equal widths do not permit substitution. Function
|
||||
metadata MUST declare ordered parameter and result identities. Slot counts are
|
||||
checked caches derived from those identities. Calls, locals and returns MUST
|
||||
preserve entire value groups. A vec2 is one logical value with two slots;
|
||||
a named output tuple is a fixed sequence of logical results, not a heap object.
|
||||
|
||||
`int` and `long` are distinct. Integer literals default to `int`; explicit
|
||||
`long` contexts (annotations, parameters and results) validate literals in the
|
||||
Int64 range and materialize them with that carrier. Out-of-range literals MUST
|
||||
be diagnosed, never replaced by zero. A typed variable does not change type
|
||||
because it appears in another expected context. Mixed int/long operations
|
||||
require an explicit conversion. Existing `as` syntax expresses conversion:
|
||||
|
||||
```pbs
|
||||
let frames: long = 2147483648;
|
||||
let offset: int = 10;
|
||||
let wide = offset as long;
|
||||
let narrow = frames as int;
|
||||
```
|
||||
|
||||
The final conversion faults if its value is outside Int32 range. Numeric
|
||||
conversions use published math/mathf conversion intrinsics, without adding
|
||||
math service facades. Int32/Int64 arithmetic preserves runtime wrapping;
|
||||
Float overflow and range-invalid conversions preserve runtime faults.
|
||||
Defaults are owned by the runtime storage contract: numeric zero, Float +0,
|
||||
Bool false, nullable String null, transparent color, zero vec2 and zero pixel.
|
||||
This does not introduce implicit source-variable initialization: VM locals
|
||||
start null and PBS definite-assignment rules still apply. NaN/infinity are not
|
||||
valid guest numeric defaults.
|
||||
|
||||
## Public input API
|
||||
|
||||
Import `Pad`, `Button` and `Touch` from `@sdk:input`. Button is a closed nominal
|
||||
PBS enum with cases Up, Down, Left, Right, A, B, X, Y, L, R, Start and Select.
|
||||
It identifies a button; it does not contain input state or perform a query.
|
||||
Locals and typed function parameters may carry Button values, including values
|
||||
selected during execution. Strings, integer indices and unrelated enums are
|
||||
not valid Button arguments.
|
||||
|
||||
| Public operation | Result |
|
||||
| --- | --- |
|
||||
| `Pad.pressed(button: Button)` | bool |
|
||||
| `Pad.released(button: Button)` | bool |
|
||||
| `Pad.down(button: Button)` | bool |
|
||||
| `Pad.hold(button: Button)` | long, held logical frames |
|
||||
| `Touch.pressed()`, `Touch.released()`, `Touch.down()` | bool |
|
||||
| `Touch.hold()` | long, held logical frames |
|
||||
| `Touch.x()`, `Touch.y()` | long |
|
||||
|
||||
```pbs
|
||||
import { Pad, Button, Touch } from @sdk:input;
|
||||
|
||||
fn jump(button: Button) -> bool {
|
||||
return Pad.pressed(button);
|
||||
}
|
||||
|
||||
fn held() -> long {
|
||||
let jump_button = Button.A;
|
||||
return Pad.hold(jump_button);
|
||||
}
|
||||
```
|
||||
|
||||
Pad dispatches to `LowPad.<button>_<query>()`, for example
|
||||
`LowPad.a_pressed()`. All 48 combinations map to the published direct endpoint.
|
||||
Each call MUST evaluate its selector once and execute exactly one chosen
|
||||
query. It MUST NOT read unselected buttons, speculate input faults or collect
|
||||
all button states. Constant specialization is optional; dynamic dispatch must
|
||||
work without optimization.
|
||||
|
||||
All 54 VM queries take zero arguments and no receiver. Button never crosses
|
||||
the intrinsic boundary as a selector. Touch x/y use current IDs 0x2134/0x2135
|
||||
and Int64 results. No new device, button-state object, snapshot or multi-pad
|
||||
contract is introduced. Known input without an available platform faults with
|
||||
TRAP_UNAVAILABLE; it never fabricates false or zero. Unknown and retired IDs
|
||||
are invalid even in unreachable code.
|
||||
|
||||
## Migration and diagnostics
|
||||
|
||||
The old Input root and intermediate InputPad/InputTouch/InputButton objects
|
||||
are removed. Replace `Input.pad().a().pressed()` with
|
||||
`Pad.pressed(Button.A)` and `Input.touch().x()` with `Touch.x()`.
|
||||
`let button = Input.pad().a();` is invalid; `let button = Button.A;` is valid.
|
||||
Migration diagnostics must point to the replacement surface. Hover, completion,
|
||||
exports and examples must advertise the same API and exact return types.
|
||||
When a consumer requires int coordinates, explicitly narrow a Touch result
|
||||
with `as int`; do not silently change the query's ABI.
|
||||
|
||||
## Lowering and observable order
|
||||
|
||||
PBS owns source enum dispatch and typed metadata. Common code owns catalog
|
||||
resolution, PBX validation and emission. The frontend MUST NOT maintain a
|
||||
second intrinsic or constant catalog. SDK executable methods admit the existing
|
||||
switch expression with value arms, apply and explicit numeric conversions
|
||||
needed by this facade; other unsupported SDK constructs remain diagnosed.
|
||||
|
||||
For named application such as `f apply (y: effect_y(), x: effect_x())`, evaluate
|
||||
Y then X exactly once, store complete groups in temporary locals, and reload
|
||||
in x,y parameter order. Reordering expressions instead of values is invalid.
|
||||
|
||||
Builtin constants are groups resolved by the shared constant catalog.
|
||||
`vec2.zero` materializes two Float slots; no intrinsic endpoint is invented.
|
||||
Colors may use a published constant or an independently published intrinsic.
|
||||
Function metadata must cover SDK wrappers such as Gfx.clear. Validation must
|
||||
not infer missing identities from widths or omit the full installed example.
|
||||
Preserve the existing lifecycle assembly and physical boot FunctionId zero.
|
||||
|
||||
## Conformance
|
||||
|
||||
The PBS source-to-production-PBX corpus and production runtime harness must
|
||||
cover all 54 input queries with controlled input and exactly-one-query checks,
|
||||
known-unavailable behavior, typed selectors, int/long boundaries and explicit
|
||||
conversions, Float/String/Bool, color/vec2/pixel groups, multiple returns and
|
||||
named-argument effects. Keep common registry wrong-carrier, retired-ID and stale
|
||||
signature tests active. Record runtime hash, Studio revision, platform and
|
||||
configuration. A catalog-only pass does not replace successful PBS execution
|
||||
or `:prometeu-app:installedKnowledgeTest`.
|
||||
@@ -296,3 +296,7 @@ This document is ready to move beyond temporary status only when:
|
||||
2. diagnostic identity, metadata, and attribution rules are explicit enough for conformance, including locale-agnostic token/template identity,
|
||||
3. the backend-originated failure boundary is explicit enough that PBS-facing diagnostics can be distinguished from internal tool failures,
|
||||
4. and cost/warning expectations are explicit where they are intended to be normative for v1.
|
||||
|
||||
## Existing values and input runtime alignment
|
||||
|
||||
The [PBS input and value alignment contract](../../../compiler/pbs/specs/input-and-existing-type-runtime-alignment.md) governs int/Int32, long/Int64, exact builtin carriers, the Pad/Button/LowPad and Touch API, named-argument evaluation order, migration diagnostics and executable conformance. It supersedes older input-object and untyped executable-lowering descriptions.
|
||||
|
||||
@@ -238,3 +238,7 @@ At frontend `IRBackend` emission time:
|
||||
4. module order in the declaration MUST propagate the explicit dependency order already derived from resolved project/module data, without sorting by `FileId`, textual module name, or synthetic callable name,
|
||||
5. PBS MUST NOT emit module init, project-init wrapper, published frame wrapper, physical entrypoint, or boot guard,
|
||||
6. and common lifecycle assembly remains the owner of derived artifacts, including the published wrapper that becomes the physical entrypoint and owns the final frame return.
|
||||
|
||||
## Existing values and input runtime alignment
|
||||
|
||||
The [PBS input and value alignment contract](../../../compiler/pbs/specs/input-and-existing-type-runtime-alignment.md) governs int/Int32, long/Int64, exact builtin carriers, the Pad/Button/LowPad and Touch API, named-argument evaluation order, migration diagnostics and executable conformance. It supersedes older input-object and untyped executable-lowering descriptions.
|
||||
|
||||
@@ -48,7 +48,7 @@ Rules:
|
||||
- `declare host` declarations are reserved to SDK/toolchain-controlled modules and are not formable in ordinary user-authored PBS source.
|
||||
- `declare builtin type` declarations are reserved to SDK/toolchain-controlled modules and are not formable in ordinary user-authored PBS source.
|
||||
- A host owner name is not an ordinary value expression in v1 core; it is used only as a qualified host-call owner.
|
||||
- The builtin simple types `int`, `float`, `bool`, and `str` are always present in the type namespace.
|
||||
- The builtin simple types `int`, `long`, `float`, `bool`, and `str` are always present in the type namespace.
|
||||
- Builtin simple types are resolved without import or declaration.
|
||||
- User-authored type declarations must not reuse builtin simple type names.
|
||||
|
||||
@@ -874,3 +874,7 @@ At minimum, deterministic static diagnostics are required for:
|
||||
- invalid optional intrinsic member call,
|
||||
- invalid builtin intrinsic member call,
|
||||
- member projection on a missing named output label.
|
||||
|
||||
## Existing values and input runtime alignment
|
||||
|
||||
The [PBS input and value alignment contract](../../../compiler/pbs/specs/input-and-existing-type-runtime-alignment.md) governs int/Int32, long/Int64, exact builtin carriers, the Pad/Button/LowPad and Touch API, named-argument evaluation order, migration diagnostics and executable conformance. It supersedes older input-object and untyped executable-lowering descriptions.
|
||||
|
||||
+9
-5
@@ -263,13 +263,13 @@ Example:
|
||||
```pbs
|
||||
[BuiltinType(name="color", version=1)]
|
||||
declare builtin type Color(
|
||||
pub raw: int,
|
||||
pub raw: long,
|
||||
);
|
||||
|
||||
[BuiltinType(name="pixel", version=1)]
|
||||
declare builtin type Pixel(
|
||||
pub x: int,
|
||||
pub y: int,
|
||||
pub x: long,
|
||||
pub y: long,
|
||||
pub color: Color,
|
||||
);
|
||||
```
|
||||
@@ -277,13 +277,13 @@ declare builtin type Pixel(
|
||||
Canonical semantic layout:
|
||||
|
||||
```text
|
||||
Pixel -> [int, int, Color]
|
||||
Pixel -> [long, long, Color]
|
||||
```
|
||||
|
||||
Canonical flattened slot layout:
|
||||
|
||||
```text
|
||||
Pixel -> [int, int, int]
|
||||
Pixel -> [long, long, long]
|
||||
```
|
||||
|
||||
## 13. Member Categories
|
||||
@@ -560,3 +560,7 @@ The current temporary contract is:
|
||||
7. `BuiltinConst(target, name, version)` exposes VM-owned builtin constants through reserved top-level `declare const` shells.
|
||||
8. Builtin projections, constants, and intrinsic calls must not lower through `SYSC`, `HOSTCALL`, or `SYSCALL`.
|
||||
9. Runtime-facing intrinsic artifacts are distinct from host-binding artifacts.
|
||||
|
||||
## Existing values and input runtime alignment
|
||||
|
||||
The [PBS input and value alignment contract](../../../compiler/pbs/specs/input-and-existing-type-runtime-alignment.md) governs int/Int32, long/Int64, exact builtin carriers, the Pad/Button/LowPad and Touch API, named-argument evaluation order, migration diagnostics and executable conformance. It supersedes older input-object and untyped executable-lowering descriptions.
|
||||
|
||||
@@ -387,3 +387,7 @@ This document is ready to move beyond temporary draft status only when:
|
||||
3. host-call interaction rules are stated without relying on informal prose elsewhere,
|
||||
4. the document can drive runtime conformance tests without decision backfill,
|
||||
5. the remaining TODO items are reduced to editorial integration rather than semantic uncertainty.
|
||||
|
||||
## Existing values and input runtime alignment
|
||||
|
||||
The [PBS input and value alignment contract](../../../compiler/pbs/specs/input-and-existing-type-runtime-alignment.md) governs int/Int32, long/Int64, exact builtin carriers, the Pad/Button/LowPad and Touch API, named-argument evaluation order, migration diagnostics and executable conformance. It supersedes older input-object and untyped executable-lowering descriptions.
|
||||
|
||||
@@ -559,8 +559,8 @@ are also checked. Rebuilding changes pixels/build identity and visibly marks the
|
||||
old capture stale. Images remain in memory; window screenshots are not evidence.
|
||||
|
||||
The fixture uses supported project-source LSP definition/symbol navigation and
|
||||
indexed SDK reads. A probe of the installed SDK's `Input.pad()` definition returns
|
||||
an empty result with the current language service; the gate does not claim SDK
|
||||
indexed SDK reads. The historical probe of the former SDK `Input.pad()` definition returned
|
||||
an empty result (the current facade is Pad/Button and Touch); the gate does not claim SDK
|
||||
symbol navigation where no location is returned. This is a language tooling
|
||||
limitation, not a headless or MCP execution fallback.
|
||||
|
||||
|
||||
@@ -284,14 +284,14 @@ class HeadlessMcpDesktopTest {
|
||||
assertTrue(value(call("studio_project_context", args())).path("languages").toString().contains("pbs"));
|
||||
value(call("studio_reference_read", args().put("referenceId", "pbs:quickstart").put("limit", 100)));
|
||||
var sdk = value(call("studio_reference_read", args().put("referenceId", "pbs:sdk:game:1:sdk/input/main.pbs").put("limit", 1000)));
|
||||
assertTrue(sdk.toString().contains("InputPad"), "Consult installed SDK source through the indexed read-only reference");
|
||||
assertTrue(sdk.toString().contains("LowPad"), "Consult installed SDK source through the indexed read-only reference");
|
||||
assertEquals(ControlState.WAITING_FOR_AGENT, project.automation().snapshot().state());
|
||||
task = value(call("studio_control_acquire", args())).path("taskId").asText();
|
||||
assertFalse(task.isBlank());
|
||||
// Agent-native edit of the installed example; SDK remains unchanged.
|
||||
String edited = Files.readString(source).replace("import { Gfx } from @sdk:gfx;",
|
||||
"import { Gfx } from @sdk:gfx;\nimport { Input } from @sdk:input;")
|
||||
.replace("x = x + 1;", "if (Input.pad().right().down()) { x = x + 3; } else { x = x + 1; }");
|
||||
"import { Gfx } from @sdk:gfx;\nimport { Pad, Button, Touch } from @sdk:input;")
|
||||
.replace("x = x + 1;", "if (Pad.down(Button.Right)) { x = x + 3; } else { x = x + 1; }");
|
||||
Files.writeString(source, edited);
|
||||
var query = args().put("operation", "diagnostics"); query.putObject("parameters").put("uri", source.toUri().toString());
|
||||
assertTrue(value(call("studio_language_query", query)).path("result").isEmpty());
|
||||
|
||||
@@ -13,9 +13,11 @@ dependencies {
|
||||
|
||||
// Build-time projection of owner-maintained sources; no second normative copy is edited by Studio.
|
||||
val pbsSpecs = rootProject.layout.projectDirectory.dir("docs/specs/compiler-languages/pbs")
|
||||
val pbsAlignmentSpecs = rootProject.layout.projectDirectory.dir("docs/compiler/pbs/specs")
|
||||
val pbsResources = layout.projectDirectory.dir("src/main/resources")
|
||||
val generatePbsKnowledge by tasks.registering(Sync::class) {
|
||||
from(pbsSpecs) { include("*.md"); into("pbs-knowledge/specs") }
|
||||
from(pbsAlignmentSpecs) { include("*.md"); into("pbs-knowledge/specs") }
|
||||
into(layout.buildDirectory.dir("generated/pbsKnowledge"))
|
||||
inputs.files(fileTree(pbsResources) { include("game/stdlib/**/*.pbs", "game/stdlib/**/*.barrel", "pbs-knowledge/examples/**") })
|
||||
doLast {
|
||||
@@ -27,7 +29,7 @@ val generatePbsKnowledge by tasks.registering(Sync::class) {
|
||||
entries.add(linkedMapOf("id" to id, "title" to title, "kind" to kind,
|
||||
"resource" to resource, "sha256" to digest, "sdkVersion" to sdk, "target" to target))
|
||||
}
|
||||
pbsSpecs.asFile.listFiles()!!.filter { it.extension == "md" }.sortedBy { it.name }.forEach { source ->
|
||||
(pbsSpecs.asFile.listFiles()!!.toList() + (pbsAlignmentSpecs.asFile.listFiles()?.toList() ?: emptyList())).filter { it.extension == "md" }.sortedBy { it.name }.forEach { source ->
|
||||
val chapter = source.name.substringBefore(". ")
|
||||
val quickstart = source.name == "README.md"
|
||||
entry(if (quickstart) "pbs:quickstart" else "pbs:spec:$chapter",
|
||||
|
||||
+1
-1
@@ -25,7 +25,7 @@ import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
public final class PBSSemanticTokenProvider implements FrontendSemanticTokenProvider {
|
||||
private static final Set<String> BUILTIN_TYPE_NAMES = Set.of("int", "float", "bool", "string", "i32", "i64", "f32", "f64");
|
||||
private static final Set<String> BUILTIN_TYPE_NAMES = Set.of("int", "long", "float", "bool", "string", "i32", "i64", "f32", "f64");
|
||||
private static final int DEFAULT_STDLIB_VERSION = 1;
|
||||
private static final AppMode DEFAULT_TARGET = AppMode.Game;
|
||||
private static final ResourceStdlibEnvironmentResolver STDLIB_RESOLVER = new ResourceStdlibEnvironmentResolver();
|
||||
|
||||
+1
-1
@@ -234,7 +234,7 @@ public final class PbsFrontendCompiler {
|
||||
effectiveModulePool,
|
||||
ReadOnlyList.wrap(callableSignatures),
|
||||
executableLowering.intrinsicPool(),
|
||||
lifecycleDeclaration);
|
||||
lifecycleDeclaration, executableLowering.registry());
|
||||
}
|
||||
|
||||
public String callableShapeSurfaceOf(final PbsAst.FunctionDecl functionDecl) {
|
||||
|
||||
+7
-1
@@ -43,6 +43,12 @@ public final class PbsModuleVisibilityValidator {
|
||||
}
|
||||
}
|
||||
|
||||
private static String inputMigrationHint(String module, String name) {
|
||||
return "@sdk:input".equals(module) && java.util.Set.of("Input", "InputType", "InputPad", "InputTouch", "InputButton").contains(name)
|
||||
? "; migrate to Pad.pressed/released/down/hold(Button.A) or Touch queries. Intermediate input objects are no longer values."
|
||||
: "";
|
||||
}
|
||||
|
||||
private ModuleExports validateModule(
|
||||
final ModuleUnit module,
|
||||
final NameTable nameTable,
|
||||
@@ -219,7 +225,7 @@ public final class PbsModuleVisibilityValidator {
|
||||
PbsLinkErrors.E_LINK_IMPORT_SYMBOL_UNRESOLVED.name(),
|
||||
"Symbol '%s' does not exist in module %s".formatted(
|
||||
importItem.name(),
|
||||
displayModule(targetModule)),
|
||||
displayModule(targetModule)) + inputMigrationHint(displayModule(targetModule), importItem.name()),
|
||||
importItem.span());
|
||||
continue;
|
||||
}
|
||||
|
||||
+195
-50
@@ -28,7 +28,7 @@ final class PbsExecutableBodyLowerer {
|
||||
final PbsExecutableMetadataIndex metadataIndex,
|
||||
final PbsExecutableCallableRegistry callableRegistry,
|
||||
final IntrinsicTable intrinsicIdTable) {
|
||||
final var localSlotByNameId = initialLocalSlots(functionDecl, nameTable);
|
||||
final var localSlotByNameId = initialLocalSlots(functionDecl, nameTable, metadataIndex.types());
|
||||
final var localOwnerByNameId = initialLocalOwners(functionDecl, nameTable, metadataIndex);
|
||||
final var context = new PbsExecutableLoweringContext(
|
||||
diagnostics,
|
||||
@@ -38,11 +38,13 @@ final class PbsExecutableBodyLowerer {
|
||||
intrinsicIdTable,
|
||||
localSlotByNameId,
|
||||
localOwnerByNameId,
|
||||
functionDecl.parameters().size());
|
||||
functionDecl.parameters().stream().mapToInt(p -> metadataIndex.types().slots(p.typeRef())).sum());
|
||||
for (var parameter : functionDecl.parameters()) context.localTypes.put(parameter.name(), parameter.typeRef());
|
||||
context.returnType = functionDecl.returnType();
|
||||
final var terminated = lowerBlock(functionDecl.body(), context);
|
||||
finalizeFunctionInstructions(functionDecl, context, terminated);
|
||||
|
||||
final var returnSlots = returnSlotsFor(functionDecl);
|
||||
final var returnSlots = functionDecl.returnKind() == PbsAst.ReturnKind.PLAIN ? context.types().slots(functionDecl.returnType()) : 0;
|
||||
final int maxStackSlots;
|
||||
try {
|
||||
maxStackSlots = stackAnalyzer.analyzeMaxStackSlots(ReadOnlyList.wrap(context.instructions()), returnSlots);
|
||||
@@ -56,7 +58,7 @@ final class PbsExecutableBodyLowerer {
|
||||
functionDecl.span());
|
||||
return null;
|
||||
}
|
||||
final var localSlots = Math.max(0, context.nextLocalSlot() - functionDecl.parameters().size());
|
||||
final var localSlots = Math.max(0, context.nextLocalSlot() - functionDecl.parameters().stream().mapToInt(p -> context.types().slots(p.typeRef())).sum());
|
||||
return new PbsLoweredExecutableBody(
|
||||
ReadOnlyList.wrap(context.instructions()),
|
||||
localSlots,
|
||||
@@ -65,10 +67,12 @@ final class PbsExecutableBodyLowerer {
|
||||
|
||||
private Map<NameId, Integer> initialLocalSlots(
|
||||
final PbsAst.FunctionDecl functionDecl,
|
||||
final NameTable nameTable) {
|
||||
final NameTable nameTable, final PbsRuntimeTypes types) {
|
||||
final var localSlotByNameId = new HashMap<NameId, Integer>();
|
||||
for (var paramIndex = 0; paramIndex < functionDecl.parameters().size(); paramIndex++) {
|
||||
localSlotByNameId.put(nameTable.register(functionDecl.parameters().get(paramIndex).name()), paramIndex);
|
||||
int slot = 0;
|
||||
for (var parameter : functionDecl.parameters()) {
|
||||
localSlotByNameId.put(nameTable.register(parameter.name()), slot);
|
||||
slot += types.slots(parameter.typeRef());
|
||||
}
|
||||
return localSlotByNameId;
|
||||
}
|
||||
@@ -155,7 +159,9 @@ final class PbsExecutableBodyLowerer {
|
||||
final var localOwner = callsiteEmitter.resolveExpressionOwnerForLowering(letStatement.initializer(), context);
|
||||
final var tupleProjection = tupleProjectionOf(letStatement.initializer(), context);
|
||||
final var valueSlots = Math.max(1, materializedValueSlots(letStatement.initializer(), context));
|
||||
lowerExpression(letStatement.initializer(), context);
|
||||
final var localType = letStatement.explicitType() != null ? letStatement.explicitType() : expressionType(letStatement.initializer(), context);
|
||||
lowerExpected(letStatement.initializer(), localType, context);
|
||||
context.localTypes.put(letStatement.name(), localType);
|
||||
final var localSlot = context.declareLocalSlots(letStatement.name(), valueSlots);
|
||||
context.bindLocalOwner(letStatement.name(), localOwner);
|
||||
context.bindLocalTupleProjection(letStatement.name(), tupleProjection);
|
||||
@@ -185,7 +191,7 @@ final class PbsExecutableBodyLowerer {
|
||||
final var localOwner = callsiteEmitter.resolveExpressionOwnerForLowering(assignStatement.value(), context);
|
||||
final var tupleProjection = tupleProjectionOf(assignStatement.value(), context);
|
||||
final var valueSlots = Math.max(1, materializedValueSlots(assignStatement.value(), context));
|
||||
lowerExpression(assignStatement.value(), context);
|
||||
lowerExpected(assignStatement.value(), context.localTypes.getOrDefault(target.rootName(), context.types().values.get(target.rootName())), context);
|
||||
if (targetLocalSlot != null) {
|
||||
context.bindLocalOwner(target.rootName(), localOwner);
|
||||
context.bindLocalTupleProjection(target.rootName(), tupleProjection);
|
||||
@@ -200,7 +206,7 @@ final class PbsExecutableBodyLowerer {
|
||||
} else {
|
||||
emitGetGlobal(targetGlobalSlot, assignStatement.span(), context);
|
||||
}
|
||||
lowerExpression(assignStatement.value(), context);
|
||||
lowerExpected(assignStatement.value(), context.localTypes.getOrDefault(target.rootName(), context.types().values.get(target.rootName())), context);
|
||||
emitBinaryOperatorInstruction(compoundAssignBinaryOperator(assignStatement.operator()), assignStatement.span(), context);
|
||||
if (targetLocalSlot != null) {
|
||||
context.bindLocalOwner(target.rootName(), "");
|
||||
@@ -235,7 +241,7 @@ final class PbsExecutableBodyLowerer {
|
||||
final PbsAst.ReturnStatement returnStatement,
|
||||
final PbsExecutableLoweringContext context) {
|
||||
if (returnStatement.value() != null) {
|
||||
lowerExpression(returnStatement.value(), context);
|
||||
lowerExpected(returnStatement.value(), context.returnType, context);
|
||||
}
|
||||
context.instructions().add(new IRBackendExecutableFunction.Instruction(
|
||||
IRBackendExecutableFunction.InstructionKind.RET,
|
||||
@@ -363,10 +369,7 @@ final class PbsExecutableBodyLowerer {
|
||||
}
|
||||
switch (expression) {
|
||||
case PbsAst.CallExpr callExpr -> lowerCallExpression(callExpr, context);
|
||||
case PbsAst.ApplyExpr applyExpr -> {
|
||||
lowerExpression(applyExpr.callee(), context);
|
||||
lowerExpression(applyExpr.argument(), context);
|
||||
}
|
||||
case PbsAst.ApplyExpr applyExpr -> lowerApply(applyExpr, context);
|
||||
case PbsAst.BinaryExpr binaryExpr -> {
|
||||
lowerExpression(binaryExpr.left(), context);
|
||||
lowerExpression(binaryExpr.right(), context);
|
||||
@@ -381,36 +384,36 @@ final class PbsExecutableBodyLowerer {
|
||||
lowerExpression(elseExpr.fallbackExpression(), context);
|
||||
}
|
||||
case PbsAst.IfExpr ifExpr -> lowerIfExpression(ifExpr, context);
|
||||
case PbsAst.SwitchExpr switchExpr -> lowerUnsupportedExpression(
|
||||
switchExpr.selector(),
|
||||
"switch expression is not lowerable in executable lowering v1",
|
||||
switchExpr.span(),
|
||||
context);
|
||||
case PbsAst.SwitchExpr switchExpr -> lowerSwitch(switchExpr, context);
|
||||
case PbsAst.HandleExpr handleExpr -> lowerUnsupportedExpression(
|
||||
handleExpr.value(),
|
||||
"handle expression is not lowerable in executable lowering v1",
|
||||
handleExpr.span(),
|
||||
context);
|
||||
case PbsAst.AsExpr asExpr -> lowerExpression(asExpr.expression(), context);
|
||||
case PbsAst.AsExpr asExpr -> lowerConversion(asExpr, context);
|
||||
case PbsAst.MemberExpr memberExpr -> lowerMemberExpression(memberExpr, context);
|
||||
case PbsAst.PropagateExpr propagateExpr -> lowerExpression(propagateExpr.expression(), context);
|
||||
case PbsAst.GroupExpr groupExpr -> lowerExpression(groupExpr.expression(), context);
|
||||
case PbsAst.NewExpr newExpr -> lowerExpressionList(newExpr.arguments(), context);
|
||||
case PbsAst.NewExpr newExpr -> {
|
||||
var fields = context.types().fields.get(newExpr.typeName());
|
||||
for(int i=0; i<newExpr.arguments().size(); i++) lowerExpected(newExpr.arguments().get(i), fields != null && i < fields.size() ? fields.get(i).typeRef() : null, context);
|
||||
}
|
||||
case PbsAst.BindExpr bindExpr -> lowerExpression(bindExpr.contextExpression(), context);
|
||||
case PbsAst.SomeExpr someExpr -> lowerExpression(someExpr.value(), context);
|
||||
case PbsAst.OkExpr okExpr -> lowerExpression(okExpr.value(), context);
|
||||
case PbsAst.TupleExpr tupleExpr -> {
|
||||
for (final var item : tupleExpr.items()) {
|
||||
lowerExpression(item.expression(), context);
|
||||
var expected = context.expectedType;
|
||||
for (int index=0; index<tupleExpr.items().size(); index++) {
|
||||
var item=tupleExpr.items().get(index);
|
||||
var fieldType=expected != null && expected.kind()==PbsAst.TypeRefKind.NAMED_TUPLE && index<expected.fields().size() ? expected.fields().get(index).typeRef() : null;
|
||||
lowerExpected(item.expression(), fieldType, context);
|
||||
}
|
||||
}
|
||||
case PbsAst.BlockExpr blockExpr -> lowerBlock(blockExpr.block(), context);
|
||||
case PbsAst.IdentifierExpr identifierExpr -> lowerIdentifierExpression(identifierExpr, context);
|
||||
case PbsAst.IntLiteralExpr intLiteralExpr -> lowerIntLiteral(intLiteralExpr, context);
|
||||
case PbsAst.FloatLiteralExpr ignored -> {
|
||||
}
|
||||
case PbsAst.BoundedLiteralExpr ignored -> {
|
||||
}
|
||||
case PbsAst.FloatLiteralExpr literal -> emitLiteral(IRBackendExecutableFunction.InstructionKind.PUSH_F64, Double.toString(literal.value()), literal.span(), context);
|
||||
case PbsAst.BoundedLiteralExpr literal -> emitPushI32(literal.value(), literal.span(), context);
|
||||
case PbsAst.StringLiteralExpr stringLiteralExpr -> emitPushConst(stringLiteralExpr.value(), stringLiteralExpr.span(), context);
|
||||
case PbsAst.BoolLiteralExpr boolLiteralExpr -> emitPushBool(boolLiteralExpr.value(), boolLiteralExpr.span(), context);
|
||||
case PbsAst.ThisExpr ignored -> {
|
||||
@@ -437,7 +440,10 @@ final class PbsExecutableBodyLowerer {
|
||||
final PbsExecutableLoweringContext context) {
|
||||
final var hostBinding = callsiteEmitter.resolveUniqueHostBinding(callExpr, context);
|
||||
if (hostBinding == null || hostBinding.assetLoweringParam() == null) {
|
||||
lowerExpressionList(callExpr.arguments(), context);
|
||||
final var signature = context.types().signatures.get(PbsRuntimeTypes.path(callExpr.callee())+"#"+callExpr.arguments().size());
|
||||
for (int i=0; i<callExpr.arguments().size(); i++) {
|
||||
lowerExpected(callExpr.arguments().get(i), signature != null && i < signature.parameters().size() ? signature.parameters().get(i).typeRef() : null, context);
|
||||
}
|
||||
return;
|
||||
}
|
||||
for (int i = 0; i < callExpr.arguments().size(); i++) {
|
||||
@@ -476,6 +482,10 @@ final class PbsExecutableBodyLowerer {
|
||||
private void lowerMemberExpression(
|
||||
final PbsAst.MemberExpr memberExpr,
|
||||
final PbsExecutableLoweringContext context) {
|
||||
if (memberExpr.receiver() instanceof PbsAst.IdentifierExpr owner) {
|
||||
final var enumValue = context.types().enumValue(owner.name(), memberExpr.memberName());
|
||||
if (enumValue != null) { emitPushI32(enumValue, memberExpr.span(), context); return; }
|
||||
}
|
||||
final var assetReference = flattenAssetReference(memberExpr);
|
||||
if (assetReference != null) {
|
||||
final var assetId = context.resolveAssetId(assetReference);
|
||||
@@ -492,6 +502,15 @@ final class PbsExecutableBodyLowerer {
|
||||
if (memberExpr.receiver() instanceof PbsAst.IdentifierExpr identifierExpr) {
|
||||
final var tupleProjection = context.resolveLocalTupleProjection(identifierExpr.name());
|
||||
final var localSlot = context.resolveLocalSlot(identifierExpr.name());
|
||||
var type = context.localTypes.get(identifierExpr.name());
|
||||
var fields = type == null ? null : context.types().fields.get(type.name());
|
||||
if (fields != null && localSlot != null) {
|
||||
int offset = 0;
|
||||
for (var field : fields) {
|
||||
if (field.name().equals(memberExpr.memberName())) { emitLoadLocalSlots(localSlot + offset, context.types().slots(field.typeRef()), memberExpr.span(), context); return; }
|
||||
offset += context.types().slots(field.typeRef());
|
||||
}
|
||||
}
|
||||
if (tupleProjection != null && localSlot != null) {
|
||||
final var fieldProjection = tupleProjection.fieldsByLabel().get(memberExpr.memberName());
|
||||
if (fieldProjection != null) {
|
||||
@@ -562,7 +581,7 @@ final class PbsExecutableBodyLowerer {
|
||||
if (tupleProjection != null) {
|
||||
emitLoadLocalSlots(slot, tupleProjection.slotCount(), identifierExpr.span(), context);
|
||||
} else {
|
||||
emitGetLocal(slot, identifierExpr.span(), context);
|
||||
emitLoadLocalSlots(slot, Math.max(1, context.types().slots(context.localTypes.get(identifierExpr.name()))), identifierExpr.span(), context);
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -586,18 +605,10 @@ final class PbsExecutableBodyLowerer {
|
||||
final p.studio.compiler.models.IRReservedMetadata.BuiltinConstSurface builtinConst,
|
||||
final p.studio.compiler.source.Span span,
|
||||
final PbsExecutableLoweringContext context) {
|
||||
final var canonicalName = builtinConst.canonicalTarget() + "." + builtinConst.canonicalName();
|
||||
context.instructions().add(new IRBackendExecutableFunction.Instruction(
|
||||
IRBackendExecutableFunction.InstructionKind.CALL_INTRINSIC,
|
||||
"",
|
||||
null,
|
||||
new IRBackendExecutableFunction.IntrinsicCallMetadata(
|
||||
canonicalName,
|
||||
builtinConst.canonicalVersion(),
|
||||
context.intrinsicIdTable().register(canonicalName, builtinConst.canonicalVersion())),
|
||||
0,
|
||||
1,
|
||||
span));
|
||||
context.instructions().add(new IRBackendExecutableFunction.Instruction(IRBackendExecutableFunction.InstructionKind.BUILTIN_CONST,
|
||||
ModuleId.none(), "", null, null, null,
|
||||
builtinConst.canonicalTarget() + "." + builtinConst.canonicalName() + "@" + builtinConst.canonicalVersion(), "", null,
|
||||
context.types().slots(context.types().values.get(builtinConst.sourceConstName())), span));
|
||||
}
|
||||
|
||||
private String flattenAssetReference(final PbsAst.Expression expression) {
|
||||
@@ -622,7 +633,7 @@ final class PbsExecutableBodyLowerer {
|
||||
}
|
||||
return switch (expression) {
|
||||
case PbsAst.CallExpr callExpr -> callsiteEmitter.returnSlotsOf(callExpr, context);
|
||||
case PbsAst.ApplyExpr ignored -> 0;
|
||||
case PbsAst.ApplyExpr apply -> callsiteEmitter.returnSlotsOf(applyCall(apply), context);
|
||||
case PbsAst.BinaryExpr ignored -> 1;
|
||||
case PbsAst.UnaryExpr ignored -> 1;
|
||||
case PbsAst.ElseExpr elseExpr ->
|
||||
@@ -633,7 +644,7 @@ final class PbsExecutableBodyLowerer {
|
||||
Math.max(
|
||||
blockValueSlots(ifExpr.thenBlock(), context),
|
||||
materializedValueSlots(ifExpr.elseExpression(), context));
|
||||
case PbsAst.SwitchExpr ignored -> 0;
|
||||
case PbsAst.SwitchExpr sw -> sw.arms().isEmpty() ? 0 : blockValueSlots(sw.arms().getFirst().block(), context);
|
||||
case PbsAst.HandleExpr ignored -> 0;
|
||||
case PbsAst.AsExpr asExpr -> materializedValueSlots(asExpr.expression(), context);
|
||||
case PbsAst.MemberExpr memberExpr -> {
|
||||
@@ -642,6 +653,9 @@ final class PbsExecutableBodyLowerer {
|
||||
yield 1;
|
||||
}
|
||||
if (memberExpr.receiver() instanceof PbsAst.IdentifierExpr identifierExpr) {
|
||||
var type = context.localTypes.get(identifierExpr.name());
|
||||
var fields = type == null ? null : context.types().fields.get(type.name());
|
||||
if (fields != null) for (var field : fields) if (field.name().equals(memberExpr.memberName())) yield context.types().slots(field.typeRef());
|
||||
final var tupleProjection = context.resolveLocalTupleProjection(identifierExpr.name());
|
||||
if (tupleProjection != null) {
|
||||
final var fieldProjection = tupleProjection.fieldsByLabel().get(memberExpr.memberName());
|
||||
@@ -650,6 +664,7 @@ final class PbsExecutableBodyLowerer {
|
||||
}
|
||||
}
|
||||
}
|
||||
if (memberExpr.receiver() instanceof PbsAst.IdentifierExpr owner && context.types().enumValue(owner.name(), memberExpr.memberName()) != null) yield 1;
|
||||
yield materializedValueSlots(memberExpr.receiver(), context);
|
||||
}
|
||||
case PbsAst.PropagateExpr propagateExpr -> materializedValueSlots(propagateExpr.expression(), context);
|
||||
@@ -670,8 +685,8 @@ final class PbsExecutableBodyLowerer {
|
||||
case PbsAst.IntLiteralExpr ignored -> 1;
|
||||
case PbsAst.StringLiteralExpr ignoredString -> 1;
|
||||
case PbsAst.BoolLiteralExpr ignoredBool -> 1;
|
||||
case PbsAst.FloatLiteralExpr ignoredFloat -> 0;
|
||||
case PbsAst.BoundedLiteralExpr ignoredBounded -> 0;
|
||||
case PbsAst.FloatLiteralExpr ignoredFloat -> 1;
|
||||
case PbsAst.BoundedLiteralExpr ignoredBounded -> 1;
|
||||
case PbsAst.ThisExpr ignoredThis -> 0;
|
||||
case PbsAst.NoneExpr ignoredNone -> 0;
|
||||
case PbsAst.ErrExpr ignoredErr -> 0;
|
||||
@@ -712,11 +727,11 @@ final class PbsExecutableBodyLowerer {
|
||||
private int identifierValueSlots(
|
||||
final PbsAst.IdentifierExpr identifierExpr,
|
||||
final PbsExecutableLoweringContext context) {
|
||||
if (!producesIdentifierValue(identifierExpr, context)) {
|
||||
return 0;
|
||||
}
|
||||
var constant = context.builtinConstByNameId().get(context.nameTable().register(identifierExpr.name()));
|
||||
if (constant != null) return context.types().slots(context.types().values.get(identifierExpr.name()));
|
||||
if (!producesIdentifierValue(identifierExpr, context)) return 0;
|
||||
final var tupleProjection = context.resolveLocalTupleProjection(identifierExpr.name());
|
||||
return tupleProjection == null ? 1 : tupleProjection.slotCount();
|
||||
return tupleProjection == null ? Math.max(1, context.types().slots(expressionType(identifierExpr, context))) : tupleProjection.slotCount();
|
||||
}
|
||||
|
||||
private PbsTupleProjection tupleProjectionOf(
|
||||
@@ -774,6 +789,10 @@ final class PbsExecutableBodyLowerer {
|
||||
private void lowerIntLiteral(
|
||||
final PbsAst.IntLiteralExpr intLiteralExpr,
|
||||
final PbsExecutableLoweringContext context) {
|
||||
if (context.expectedType != null && "long".equals(context.types().canonical(context.expectedType))) {
|
||||
emitLiteral(IRBackendExecutableFunction.InstructionKind.PUSH_I64, Long.toString(intLiteralExpr.value()), intLiteralExpr.span(), context);
|
||||
return;
|
||||
}
|
||||
if (intLiteralExpr.value() < Integer.MIN_VALUE || intLiteralExpr.value() > Integer.MAX_VALUE) {
|
||||
reportUnsupportedLowering(
|
||||
"int literal exceeds i32 lowering range: " + intLiteralExpr.value(),
|
||||
@@ -784,6 +803,132 @@ final class PbsExecutableBodyLowerer {
|
||||
emitPushI32((int) intLiteralExpr.value(), intLiteralExpr.span(), context);
|
||||
}
|
||||
|
||||
private PbsAst.CallExpr applyCall(PbsAst.ApplyExpr apply) {
|
||||
var argument = apply.argument();
|
||||
while (argument instanceof PbsAst.GroupExpr group) argument = group.expression();
|
||||
var values = argument instanceof PbsAst.TupleExpr tuple ? tuple.items().stream().map(PbsAst.TupleItem::expression).toList()
|
||||
: argument instanceof PbsAst.UnitExpr ? java.util.List.<PbsAst.Expression>of() : java.util.List.of(argument);
|
||||
return new PbsAst.CallExpr(apply.callee(), ReadOnlyList.wrap(values), apply.span());
|
||||
}
|
||||
|
||||
private void lowerApply(PbsAst.ApplyExpr apply, PbsExecutableLoweringContext c) {
|
||||
var call = applyCall(apply);
|
||||
var argument = apply.argument();
|
||||
while (argument instanceof PbsAst.GroupExpr group) argument = group.expression();
|
||||
if (!(argument instanceof PbsAst.TupleExpr tuple) || tuple.items().isEmpty() || tuple.items().getFirst().label() == null) {
|
||||
lowerCallExpression(call, c); return;
|
||||
}
|
||||
var signature = c.types().signatures.get(PbsRuntimeTypes.path(call.callee())+"#"+call.arguments().size());
|
||||
if(signature == null) { reportUnsupportedLowering("Named application requires a resolved signature", apply.span(), c); return; }
|
||||
var slots = new java.util.HashMap<String,Integer>();
|
||||
for(var item:tuple.items()) {
|
||||
var parameter = signature.parameters().stream().filter(p -> p.name().equals(item.label())).findFirst().orElse(null);
|
||||
if(parameter == null || slots.containsKey(item.label())) { reportUnsupportedLowering("Unknown or duplicate named argument: "+item.label(), item.span(), c); return; }
|
||||
// Evaluate source order once, then reorder complete value groups, never expressions.
|
||||
lowerExpected(item.expression(), parameter.typeRef(), c);
|
||||
int width = c.types().slots(parameter.typeRef());
|
||||
int slot = c.declareLocalSlots(c.nextLabel("argument"), width);
|
||||
emitStoreLocalSlots(slot, width, item.span(), c);
|
||||
slots.put(item.label(), slot);
|
||||
}
|
||||
for(var parameter:signature.parameters()) {
|
||||
var slot=slots.get(parameter.name());
|
||||
if(slot==null) { reportUnsupportedLowering("Missing named argument: "+parameter.name(), apply.span(), c); return; }
|
||||
emitLoadLocalSlots(slot,c.types().slots(parameter.typeRef()),apply.span(),c);
|
||||
}
|
||||
callsiteEmitter.emitCallsite(call,c);
|
||||
}
|
||||
|
||||
private void lowerExpected(PbsAst.Expression expression, PbsAst.TypeRef expected, PbsExecutableLoweringContext context) {
|
||||
var previous = context.expectedType;
|
||||
context.expectedType = expected;
|
||||
try { lowerExpression(expression, context); } finally { context.expectedType = previous; }
|
||||
}
|
||||
|
||||
private PbsAst.TypeRef expressionType(PbsAst.Expression e, PbsExecutableLoweringContext c) {
|
||||
if (e instanceof PbsAst.IdentifierExpr i) return c.localTypes.getOrDefault(i.name(), c.types().values.get(i.name()));
|
||||
if (e instanceof PbsAst.GroupExpr g) return expressionType(g.expression(), c);
|
||||
if (e instanceof PbsAst.AsExpr a) return PbsRuntimeTypes.type(a.contractName());
|
||||
if (e instanceof PbsAst.UnaryExpr u) return java.util.Set.of("!", "not").contains(u.operator()) ? PbsRuntimeTypes.type("bool") : expressionType(u.expression(), c);
|
||||
if (e instanceof PbsAst.BinaryExpr b) return java.util.Set.of("==", "!=", "<", "<=", ">", ">=", "&&", "||", "and", "or").contains(b.operator()) ? PbsRuntimeTypes.type("bool") : expressionType(b.left(), c);
|
||||
if (e instanceof PbsAst.IfExpr branch) return expressionType(branch.thenBlock().tailExpression(), c);
|
||||
if (e instanceof PbsAst.SwitchExpr branch && !branch.arms().isEmpty()) return expressionType(branch.arms().getFirst().block().tailExpression(), c);
|
||||
if (e instanceof PbsAst.ApplyExpr apply) return expressionType(applyCall(apply), c);
|
||||
if (e instanceof PbsAst.NewExpr value) return PbsRuntimeTypes.type(value.typeName());
|
||||
if (e instanceof PbsAst.CallExpr call) {
|
||||
var sig = c.types().signatures.get(PbsRuntimeTypes.path(call.callee())+"#"+call.arguments().size());
|
||||
return sig == null ? null : sig.returnType();
|
||||
}
|
||||
if (e instanceof PbsAst.MemberExpr m && m.receiver() instanceof PbsAst.IdentifierExpr i) {
|
||||
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());
|
||||
if (fields != null) for (var field : fields) if (field.name().equals(m.memberName())) return field.typeRef();
|
||||
if (owner != null && owner.kind() == PbsAst.TypeRefKind.NAMED_TUPLE)
|
||||
for (var field : owner.fields()) if (field.label().equals(m.memberName())) return field.typeRef();
|
||||
}
|
||||
if (e instanceof PbsAst.IntLiteralExpr || e instanceof PbsAst.BoundedLiteralExpr) return PbsRuntimeTypes.type("int");
|
||||
if (e instanceof PbsAst.FloatLiteralExpr) return PbsRuntimeTypes.type("float");
|
||||
if (e instanceof PbsAst.BoolLiteralExpr) return PbsRuntimeTypes.type("bool");
|
||||
if (e instanceof PbsAst.StringLiteralExpr) return PbsRuntimeTypes.type("str");
|
||||
return null;
|
||||
}
|
||||
|
||||
private void lowerConversion(PbsAst.AsExpr expr, PbsExecutableLoweringContext c) {
|
||||
var source = c.types().canonical(expressionType(expr.expression(), c));
|
||||
var target = expr.contractName();
|
||||
lowerExpected(expr.expression(), null, c);
|
||||
if (source.equals(target)) return;
|
||||
String name = switch(source + "->" + target) {
|
||||
case "int->long" -> "math.i32.to_i64"; case "long->int" -> "math.i64.to_i32";
|
||||
case "int->float" -> "math.i32.to_float"; case "long->float" -> "math.i64.to_float";
|
||||
case "float->int" -> "mathf.to_i32"; case "float->long" -> "mathf.to_i64";
|
||||
default -> null;
|
||||
};
|
||||
if (name == null) { reportUnsupportedLowering("Unsupported conversion " + source + " -> " + target, expr.span(), c); return; }
|
||||
c.instructions().add(new IRBackendExecutableFunction.Instruction(IRBackendExecutableFunction.InstructionKind.CALL_INTRINSIC,
|
||||
"", null, new IRBackendExecutableFunction.IntrinsicCallMetadata(name, 1, c.intrinsicIdTable().register(name, 1)), 1, 1, expr.span()));
|
||||
}
|
||||
|
||||
private void lowerSwitch(PbsAst.SwitchExpr expr, PbsExecutableLoweringContext c) {
|
||||
var slot = c.declareLocalSlot(c.nextLabel("switch_value"));
|
||||
lowerExpected(expr.selector(), null, c);
|
||||
emitSetLocal(slot, expr.span(), c);
|
||||
var end = c.nextLabel("switch_end");
|
||||
var selectorType = expressionType(expr.selector(), c);
|
||||
var enumDecl = selectorType == null ? null : c.types().enums.get(selectorType.name());
|
||||
var coveredCases = new java.util.HashSet<String>();
|
||||
var coveredBooleans = new java.util.HashSet<Boolean>();
|
||||
for (var arm : expr.arms()) {
|
||||
if (arm.pattern() instanceof PbsAst.EnumCaseSwitchPattern pattern) coveredCases.add(pattern.path().segments().get(1));
|
||||
if (arm.pattern() instanceof PbsAst.LiteralSwitchPattern pattern && pattern.literal() instanceof PbsAst.BoolLiteralExpr literal) coveredBooleans.add(literal.value());
|
||||
}
|
||||
boolean exhaustive = enumDecl != null && enumDecl.cases().stream().allMatch(item -> coveredCases.contains(item.name())) || coveredBooleans.size() == 2;
|
||||
for (int i=0; i<expr.arms().size(); i++) {
|
||||
var arm = expr.arms().get(i);
|
||||
var next = c.nextLabel("switch_next");
|
||||
boolean last = i == expr.arms().size()-1;
|
||||
boolean checked = !(arm.pattern() instanceof PbsAst.WildcardSwitchPattern) && !(last && exhaustive);
|
||||
if (checked) {
|
||||
emitGetLocal(slot, expr.span(), c);
|
||||
if (arm.pattern() instanceof PbsAst.EnumCaseSwitchPattern pattern) {
|
||||
var value = c.types().enumValue(pattern.path().segments().get(0), pattern.path().segments().get(1));
|
||||
emitPushI32(value, pattern.span(), c);
|
||||
} else if (arm.pattern() instanceof PbsAst.LiteralSwitchPattern literal) lowerExpected(literal.literal(), expressionType(expr.selector(), c), c);
|
||||
emitBinaryOperatorInstruction("==", expr.span(), c);
|
||||
emitJump(IRBackendExecutableFunction.InstructionKind.JMP_IF_FALSE, next, expr.span(), c);
|
||||
}
|
||||
lowerBlock(arm.block(), c);
|
||||
if (!last) emitJump(IRBackendExecutableFunction.InstructionKind.JMP, end, arm.span(), c);
|
||||
if (checked) emitLabel(next, arm.span(), c);
|
||||
}
|
||||
emitLabel(end, expr.span(), c);
|
||||
}
|
||||
|
||||
private void emitLiteral(IRBackendExecutableFunction.InstructionKind kind, String value, p.studio.compiler.source.Span span, PbsExecutableLoweringContext c) {
|
||||
c.instructions().add(new IRBackendExecutableFunction.Instruction(kind, ModuleId.none(), "", null, null, null, value, "", null, null, span));
|
||||
}
|
||||
|
||||
private void lowerCallsiteReceiver(
|
||||
final PbsAst.Expression callee,
|
||||
final PbsExecutableLoweringContext context) {
|
||||
|
||||
+13
-3
@@ -201,7 +201,7 @@ final class PbsExecutableCallsiteEmitter {
|
||||
final PbsAst.CallExpr callExpr,
|
||||
final PbsExecutableLoweringContext context,
|
||||
final IRReservedMetadata.HostMethodBinding host) {
|
||||
final var effectiveArgSlots = callExpr.arguments().size() + implicitReceiverArgSlots(callExpr.callee(), context);
|
||||
final var effectiveArgSlots = argumentSlots(callExpr, context) + implicitReceiverArgSlots(callExpr.callee(), context);
|
||||
context.instructions().add(new IRBackendExecutableFunction.Instruction(
|
||||
IRBackendExecutableFunction.InstructionKind.CALL_HOST,
|
||||
"",
|
||||
@@ -251,7 +251,7 @@ final class PbsExecutableCallsiteEmitter {
|
||||
reportUnsupportedLowering("executable lowering resolved callable without signature metadata", callExpr.span(), context);
|
||||
return;
|
||||
}
|
||||
final var effectiveArgSlots = callExpr.arguments().size() + implicitReceiverArgSlots(callExpr.callee(), context);
|
||||
final var effectiveArgSlots = argumentSlots(callExpr, context) + implicitReceiverArgSlots(callExpr.callee(), context);
|
||||
context.instructions().add(new IRBackendExecutableFunction.Instruction(
|
||||
IRBackendExecutableFunction.InstructionKind.CALL_FUNC,
|
||||
calleeSignature.moduleId(),
|
||||
@@ -411,13 +411,23 @@ final class PbsExecutableCallsiteEmitter {
|
||||
};
|
||||
}
|
||||
|
||||
private int argumentSlots(PbsAst.CallExpr call, PbsExecutableLoweringContext context) {
|
||||
var signature = context.types().signatures.get(PbsRuntimeTypes.path(call.callee())+"#"+call.arguments().size());
|
||||
return signature == null ? call.arguments().size() : signature.parameters().stream().mapToInt(p -> context.types().slots(p.typeRef())).sum();
|
||||
}
|
||||
|
||||
private int implicitReceiverArgSlots(
|
||||
final PbsAst.Expression callee,
|
||||
final PbsExecutableLoweringContext context) {
|
||||
if (!(callee instanceof PbsAst.MemberExpr memberExpr)) {
|
||||
return 0;
|
||||
}
|
||||
return receiverProducesRuntimeValue(memberExpr.receiver(), context) ? 1 : 0;
|
||||
if (!receiverProducesRuntimeValue(memberExpr.receiver(), context)) return 0;
|
||||
return switch (resolveExpressionOwner(memberExpr.receiver(), context)) {
|
||||
case "vec2" -> 2;
|
||||
case "pixel" -> 3;
|
||||
default -> 1;
|
||||
};
|
||||
}
|
||||
|
||||
private boolean receiverProducesRuntimeValue(
|
||||
|
||||
+4
@@ -22,6 +22,10 @@ final class PbsExecutableLoweringContext {
|
||||
private final Map<NameId, String> localOwnerByNameId;
|
||||
private final ArrayList<IRBackendExecutableFunction.Instruction> instructions = new ArrayList<>();
|
||||
private final ArrayDeque<PbsLoopTargets> loopTargets = new ArrayDeque<>();
|
||||
final Map<String, p.studio.compiler.pbs.ast.PbsAst.TypeRef> localTypes = new HashMap<>();
|
||||
p.studio.compiler.pbs.ast.PbsAst.TypeRef expectedType;
|
||||
p.studio.compiler.pbs.ast.PbsAst.TypeRef returnType;
|
||||
PbsRuntimeTypes types() { return metadataIndex.types(); }
|
||||
private int nextLabelId = 0;
|
||||
private int nextLocalSlot;
|
||||
|
||||
|
||||
+3
-1
@@ -18,7 +18,8 @@ public class PbsExecutableLoweringModels {
|
||||
public record PbsExecutableLoweringResult(
|
||||
ReadOnlyList<IRBackendExecutableFunction> executableFunctions,
|
||||
ReadOnlyList<CallableSignatureRef> callableSignatures,
|
||||
ReadOnlyList<IntrinsicReference> intrinsicPool) {
|
||||
ReadOnlyList<IntrinsicReference> intrinsicPool,
|
||||
p.studio.compiler.models.registry.IRRegistry registry) {
|
||||
}
|
||||
|
||||
record PbsLowerableCallable(
|
||||
@@ -42,6 +43,7 @@ public class PbsExecutableLoweringModels {
|
||||
}
|
||||
|
||||
record PbsExecutableMetadataIndex(
|
||||
PbsRuntimeTypes types,
|
||||
Map<NameId, List<IRReservedMetadata.HostMethodBinding>> hostByMethodName,
|
||||
Map<String, String> builtinCanonicalBySourceType,
|
||||
Map<NameId, String> builtinConstOwnerByNameId,
|
||||
|
||||
+9
-4
@@ -47,6 +47,10 @@ public final class PbsExecutableLoweringService {
|
||||
nameTable,
|
||||
metadataIndex.builtinCanonicalBySourceType(),
|
||||
importedCallables);
|
||||
for (var entry : callableRegistry.callableSignatureByCallableId().entrySet()) {
|
||||
var signature = metadataIndex.types().signatures.get(entry.getValue().callableName()+"#"+entry.getValue().arity());
|
||||
if (signature != null) callableRegistry.returnSlotsByCallableId().put(entry.getKey(), signature.returnKind() == PbsAst.ReturnKind.PLAIN ? metadataIndex.types().slots(signature.returnType()) : 0);
|
||||
}
|
||||
final var intrinsicIdTable = new IntrinsicTable();
|
||||
final var executableFunctions = new ArrayList<IRBackendExecutableFunction>(callableRegistry.localCallables().size());
|
||||
|
||||
@@ -72,7 +76,7 @@ public final class PbsExecutableLoweringService {
|
||||
return new PbsExecutableLoweringResult(
|
||||
ReadOnlyList.wrap(executableFunctions),
|
||||
callableRegistry.callableSignatures(),
|
||||
ReadOnlyList.wrap(intrinsicPool));
|
||||
ReadOnlyList.wrap(intrinsicPool), metadataIndex.types().registry());
|
||||
}
|
||||
|
||||
public String callableShapeSurfaceOf(final PbsAst.FunctionDecl functionDecl) {
|
||||
@@ -110,12 +114,13 @@ public final class PbsExecutableLoweringService {
|
||||
functionCallableId,
|
||||
safeToInt(functionDecl.span().getStart()),
|
||||
safeToInt(functionDecl.span().getEnd()),
|
||||
functionDecl.parameters().size(),
|
||||
functionDecl.parameters().stream().mapToInt(p -> metadataIndex.types().slots(p.typeRef())).sum(),
|
||||
loweredBody.localSlots(),
|
||||
callableRegistry.returnSlotsByCallableId().getOrDefault(functionCallableId, 0),
|
||||
functionDecl.returnKind() == PbsAst.ReturnKind.PLAIN ? metadataIndex.types().slots(functionDecl.returnType()) : 0,
|
||||
loweredBody.maxStackSlots(),
|
||||
loweredBody.instructions(),
|
||||
functionDecl.span());
|
||||
functionDecl.span(),
|
||||
metadataIndex.types().metadata(functionDecl));
|
||||
}
|
||||
|
||||
private int safeToInt(final long value) {
|
||||
|
||||
+1
@@ -48,6 +48,7 @@ final class PbsExecutableMetadataIndexFactory {
|
||||
intrinsicReturnOwnerByCanonical,
|
||||
diagnostics);
|
||||
return new PbsExecutableMetadataIndex(
|
||||
new PbsRuntimeTypes(ast, supplementalTopDecls, builtinCanonicalBySourceType),
|
||||
hostByMethodName,
|
||||
builtinCanonicalBySourceType,
|
||||
builtinConstOwnerByNameId,
|
||||
|
||||
+2
-1
@@ -38,7 +38,8 @@ final class PbsExecutableStackAnalyzer {
|
||||
var outHeight = incomingHeightByInstruction.get(index);
|
||||
|
||||
switch (instruction.kind()) {
|
||||
case PUSH_I32, PUSH_BOOL, PUSH_CONST, GET_LOCAL, GET_GLOBAL -> outHeight += 1;
|
||||
case PUSH_I32, PUSH_I64, PUSH_F64, PUSH_BOOL, PUSH_CONST, GET_LOCAL, GET_GLOBAL -> outHeight += 1;
|
||||
case BUILTIN_CONST -> outHeight += instruction.expectedRetSlots();
|
||||
case POP, SET_LOCAL, SET_GLOBAL -> {
|
||||
if (outHeight <= 0) {
|
||||
throw new ExecutableLoweringAnalysisException(
|
||||
|
||||
+92
@@ -0,0 +1,92 @@
|
||||
package p.studio.compiler.pbs.lowering;
|
||||
|
||||
import p.studio.compiler.models.registry.IRRegistry;
|
||||
import p.studio.compiler.pbs.ast.PbsAst;
|
||||
import p.studio.compiler.source.Span;
|
||||
import p.studio.utilities.structures.ReadOnlyList;
|
||||
import java.util.*;
|
||||
|
||||
/** PBS-owned source identities and layouts; never inferred from slot widths. */
|
||||
final class PbsRuntimeTypes {
|
||||
final Map<String, String> builtinNames;
|
||||
final Map<String, ReadOnlyList<PbsAst.BuiltinFieldDecl>> fields = new HashMap<>();
|
||||
final Map<String, PbsAst.EnumDecl> enums = new HashMap<>();
|
||||
final Map<String, PbsAst.FunctionSignature> signatures = new HashMap<>();
|
||||
final Map<String, PbsAst.TypeRef> values = new HashMap<>();
|
||||
private final Map<Integer, IRRegistry.TypeDeclaration> used = new TreeMap<>();
|
||||
|
||||
PbsRuntimeTypes(PbsAst.File ast, ReadOnlyList<PbsAst.TopDecl> supplemental, Map<String,String> builtins) {
|
||||
builtinNames = builtins;
|
||||
var declarations = new ArrayList<>(ast.topDecls().asList());
|
||||
declarations.addAll(supplemental.asList());
|
||||
for (var decl : declarations) {
|
||||
if (decl instanceof PbsAst.EnumDecl e) enums.put(e.name(), e);
|
||||
if (decl instanceof PbsAst.ConstDecl c) values.put(c.name(), c.explicitType());
|
||||
if (decl instanceof PbsAst.GlobalDecl g) values.put(g.name(), g.explicitType());
|
||||
if (decl instanceof PbsAst.FunctionDecl f) addSignature(f.name(), f);
|
||||
if (decl instanceof PbsAst.ServiceDecl s) for (var f : s.methods()) addSignature(s.name()+"."+f.name(), f);
|
||||
if (decl instanceof PbsAst.BuiltinTypeDecl b) {
|
||||
fields.put(b.name(), b.fields());
|
||||
for(var f:b.signatures()) signatures.put(b.name()+"."+f.name()+"#"+f.parameters().size(), f);
|
||||
}
|
||||
if (decl instanceof PbsAst.HostDecl h) for(var f:h.signatures()) signatures.put(h.name()+"."+f.name()+"#"+f.parameters().size(), f);
|
||||
}
|
||||
}
|
||||
private void addSignature(String name, PbsAst.FunctionDecl f) {
|
||||
signatures.put(name+"#"+f.parameters().size(), new PbsAst.FunctionSignature(f.name(), f.parameters(), f.returnKind(), f.returnType(), f.resultErrorType(), f.attributes(), f.span()));
|
||||
}
|
||||
static PbsAst.TypeRef type(String name) { return PbsAst.TypeRef.simple(name, Span.none()); }
|
||||
String canonical(PbsAst.TypeRef t) {
|
||||
if(t==null) return "void";
|
||||
if(t.kind()==PbsAst.TypeRefKind.GROUP) return canonical(t.inner());
|
||||
return builtinNames.getOrDefault(t.name(), t.name());
|
||||
}
|
||||
int slots(PbsAst.TypeRef t) {
|
||||
if(t==null || t.kind()==PbsAst.TypeRefKind.UNIT) return 0;
|
||||
if(t.kind()==PbsAst.TypeRefKind.GROUP) return slots(t.inner());
|
||||
if(t.kind()==PbsAst.TypeRefKind.NAMED_TUPLE) return t.fields().stream().mapToInt(f->slots(f.typeRef())).sum();
|
||||
return switch(canonical(t)) { case "vec2" -> 2; case "pixel" -> 3; default -> 1; };
|
||||
}
|
||||
IRRegistry.TypeRef registryType(PbsAst.TypeRef t) {
|
||||
int id = switch(canonical(t)) {
|
||||
case "int" -> 0x10; case "long" -> 0x11; case "float" -> 0x12;
|
||||
case "bool" -> 0x13; case "str" -> 0x14;
|
||||
case "color" -> 1; case "vec2" -> 2; case "pixel" -> 3;
|
||||
default -> { if(enums.containsKey(t.name())) yield 0x10;
|
||||
throw new UnsupportedOperationException("Unsupported PBS runtime type: "+t.name()); }
|
||||
};
|
||||
var ref=IRRegistry.TypeRef.builtin(id);
|
||||
used.putIfAbsent(id,new IRRegistry.TypeDeclaration(ref,null,new IRRegistry.Builtin(id)));
|
||||
return ref;
|
||||
}
|
||||
List<IRRegistry.TypeRef> results(PbsAst.TypeRef t) {
|
||||
if(t==null || t.kind()==PbsAst.TypeRefKind.UNIT) return List.of();
|
||||
if(t.kind()==PbsAst.TypeRefKind.GROUP) return results(t.inner());
|
||||
if(t.kind()==PbsAst.TypeRefKind.NAMED_TUPLE) return t.fields().stream().flatMap(f->results(f.typeRef()).stream()).toList();
|
||||
return List.of(registryType(t));
|
||||
}
|
||||
IRRegistry.FunctionMetadata metadata(PbsAst.FunctionDecl f) {
|
||||
// Preserve the pre-existing unsupported executable boundary for types outside this port.
|
||||
// The common backend still rejects missing typed metadata; never infer a carrier by width.
|
||||
try { return supportedMetadata(f); } catch (UnsupportedOperationException unsupported) { return null; }
|
||||
}
|
||||
private IRRegistry.FunctionMetadata supportedMetadata(PbsAst.FunctionDecl f) {
|
||||
var params=new ArrayList<IRRegistry.NamedType>();
|
||||
for(var p:f.parameters()) for(var type:results(p.typeRef())) params.add(new IRRegistry.NamedType(type,p.name()));
|
||||
var returns=f.returnKind()==PbsAst.ReturnKind.PLAIN ? results(f.returnType()) : List.<IRRegistry.TypeRef>of();
|
||||
return IRRegistry.FunctionMetadata.ordinary(new IRRegistry.Signature(ReadOnlyList.wrap(params),ReadOnlyList.wrap(returns)));
|
||||
}
|
||||
IRRegistry registry() { return new IRRegistry(ReadOnlyList.wrap(new ArrayList<>(used.values())),ReadOnlyList.empty()); }
|
||||
Integer enumValue(String owner,String label) {
|
||||
var e=enums.get(owner); if(e==null) return null;
|
||||
int index=0;
|
||||
for(var c:e.cases()) { if(c.name().equals(label)) return c.explicitValue()==null?index:Math.toIntExact(c.explicitValue()); index++; }
|
||||
return null;
|
||||
}
|
||||
static String path(PbsAst.Expression e) {
|
||||
if(e instanceof PbsAst.IdentifierExpr i) return i.name();
|
||||
if(e instanceof PbsAst.MemberExpr m) {var owner=path(m.receiver());return owner==null?null:owner+"."+m.memberName();}
|
||||
if(e instanceof PbsAst.GroupExpr g) return path(g.expression());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
+1
@@ -45,6 +45,7 @@ final class PbsExprLiteralSupport {
|
||||
try {
|
||||
return Long.parseLong(text);
|
||||
} catch (NumberFormatException ignored) {
|
||||
context.report(cursor.previous(), ParseErrors.E_PARSE_EXPECTED_TOKEN, "Integer literal is outside the Int64 range");
|
||||
return 0L;
|
||||
}
|
||||
}
|
||||
|
||||
+5
@@ -159,6 +159,11 @@ final class PbsExprParser {
|
||||
private PbsAst.Expression parseUnary() {
|
||||
if (cursor.match(PbsTokenKind.BANG, PbsTokenKind.MINUS, PbsTokenKind.NOT)) {
|
||||
final var operator = cursor.previous();
|
||||
if (operator.kind() == PbsTokenKind.MINUS && cursor.check(PbsTokenKind.INT_LITERAL)
|
||||
&& (cursor.peek().lexeme().equals("9223372036854775808") || cursor.peek().lexeme().equals("2147483648"))) {
|
||||
final var literal = cursor.advance();
|
||||
return new PbsAst.IntLiteralExpr(Long.parseLong("-" + literal.lexeme()), span(operator.start(), literal.end()));
|
||||
}
|
||||
final var right = parseUnary();
|
||||
return new PbsAst.UnaryExpr(operator.lexeme(), right, span(operator.start(), right.span().getEnd()));
|
||||
}
|
||||
|
||||
+1
-1
@@ -8,7 +8,7 @@ import p.studio.utilities.structures.ReadOnlyList;
|
||||
import java.util.*;
|
||||
|
||||
public final class PbsBuiltinLayoutResolver {
|
||||
private static final Set<String> BUILTIN_SCALAR_TYPES = Set.of("int", "float", "bool", "str");
|
||||
private static final Set<String> BUILTIN_SCALAR_TYPES = Set.of("int", "long", "float", "bool", "str");
|
||||
|
||||
private enum ResolveState {
|
||||
UNVISITED,
|
||||
|
||||
+12
@@ -357,6 +357,18 @@ public final class PbsDeclarationSemanticsValidator {
|
||||
validateSdkExecutableExpression(argument, diagnostics);
|
||||
}
|
||||
}
|
||||
case PbsAst.ApplyExpr apply -> {
|
||||
validateSdkExecutableExpression(apply.callee(), diagnostics);
|
||||
validateSdkExecutableExpression(apply.argument(), diagnostics);
|
||||
}
|
||||
case PbsAst.AsExpr conversion -> validateSdkExecutableExpression(conversion.expression(), diagnostics);
|
||||
case PbsAst.SwitchExpr switchExpr -> {
|
||||
validateSdkExecutableExpression(switchExpr.selector(), diagnostics);
|
||||
for (var arm : switchExpr.arms()) {
|
||||
for (var statement : arm.block().statements()) validateSdkExecutableStatement(statement, diagnostics);
|
||||
validateSdkExecutableExpression(arm.block().tailExpression(), diagnostics);
|
||||
}
|
||||
}
|
||||
case PbsAst.MemberExpr memberExpr ->
|
||||
validateSdkExecutableExpression(memberExpr.receiver(), diagnostics);
|
||||
case PbsAst.GroupExpr groupExpr ->
|
||||
|
||||
+1
-1
@@ -16,7 +16,7 @@ import java.util.*;
|
||||
import static p.studio.compiler.pbs.semantics.PbsFlowSemanticSupport.*;
|
||||
|
||||
public final class PbsEditorialSupportService {
|
||||
private static final Set<String> BUILTIN_TYPE_NAMES = Set.of("int", "float", "bool", "str", "string", "i32", "i64", "f32", "f64");
|
||||
private static final Set<String> BUILTIN_TYPE_NAMES = Set.of("int", "long", "float", "bool", "str", "string", "i32", "i64", "f32", "f64");
|
||||
private static final List<String> KEYWORDS = List.of(
|
||||
"fn", "declare", "let", "const", "global", "struct", "service", "host", "contract", "enum", "error", "callback",
|
||||
"if", "else", "switch", "for", "until", "step", "while", "break", "continue", "return",
|
||||
|
||||
+27
-3
@@ -29,15 +29,19 @@ final class PbsFlowCallableResolutionAnalyzer {
|
||||
final PbsFlowExpressionContext context) {
|
||||
final var callee = analyzeTargetExpression(callExpr.callee(), context, ExprUse.CALL_TARGET);
|
||||
|
||||
final var expectedInputs = callee.callables().size() == 1 ? callee.callables().getFirst().inputTypes() : java.util.List.<TypeView>of();
|
||||
final TypeView argumentType;
|
||||
if (callExpr.arguments().isEmpty()) {
|
||||
argumentType = TypeView.unit();
|
||||
} else if (callExpr.arguments().size() == 1) {
|
||||
argumentType = analyzeValueExpression(callExpr.arguments().getFirst(), context, null).type();
|
||||
argumentType = analyzeValueExpression(callExpr.arguments().getFirst(), context, expectedInputs.size() == 1 ? expectedInputs.getFirst() : null).type();
|
||||
} else {
|
||||
final var fields = new ArrayList<TupleField>(callExpr.arguments().size());
|
||||
int argumentIndex = 0;
|
||||
for (final var argument : callExpr.arguments()) {
|
||||
final var itemType = analyzeValueExpression(argument, context, null).type();
|
||||
final var expected = argumentIndex < expectedInputs.size() ? expectedInputs.get(argumentIndex) : null;
|
||||
argumentIndex++;
|
||||
final var itemType = analyzeValueExpression(argument, context, expected).type();
|
||||
fields.add(new TupleField(null, itemType));
|
||||
}
|
||||
argumentType = TypeView.tuple(fields);
|
||||
@@ -56,7 +60,27 @@ final class PbsFlowCallableResolutionAnalyzer {
|
||||
final PbsAst.ApplyExpr applyExpr,
|
||||
final PbsFlowExpressionContext context) {
|
||||
final var callee = analyzeTargetExpression(applyExpr.callee(), context, ExprUse.APPLY_TARGET);
|
||||
final var argument = analyzeValueExpression(applyExpr.argument(), context, null).type();
|
||||
TypeView argument;
|
||||
if (applyExpr.argument() instanceof PbsAst.TupleExpr tuple && !tuple.items().isEmpty()
|
||||
&& tuple.items().getFirst().label() != null && callee.callables().size() == 1) {
|
||||
var candidate = callee.callables().getFirst();
|
||||
var byName = new java.util.HashMap<String, TypeView>();
|
||||
for (var item : tuple.items()) {
|
||||
var parameter = candidate.parameters().stream().filter(p -> p.name().equals(item.label())).findFirst().orElse(null);
|
||||
if (parameter == null || byName.containsKey(item.label())) {
|
||||
Diagnostics.error(context.diagnostics(), "E_SEM_NAMED_ARGUMENT", "Unknown or duplicate named argument: " + item.label(), item.span());
|
||||
}
|
||||
byName.put(item.label(), analyzeValueExpression(item.expression(), context, parameter == null ? null : parameter.type()).type());
|
||||
}
|
||||
var fields = new ArrayList<TupleField>();
|
||||
for (var parameter : candidate.parameters()) {
|
||||
if (!byName.containsKey(parameter.name())) Diagnostics.error(context.diagnostics(), "E_SEM_NAMED_ARGUMENT", "Missing named argument: " + parameter.name(), applyExpr.span());
|
||||
fields.add(new TupleField(parameter.name(), byName.getOrDefault(parameter.name(), TypeView.unknown())));
|
||||
}
|
||||
argument = TypeView.tuple(fields);
|
||||
} else {
|
||||
argument = analyzeValueExpression(applyExpr.argument(), context, callee.callables().size() == 1 && callee.callables().getFirst().inputTypes().size() == 1 ? callee.callables().getFirst().inputTypes().getFirst() : null).type();
|
||||
}
|
||||
|
||||
return resolveCallableApplication(
|
||||
applyExpr.span(),
|
||||
|
||||
+8
@@ -35,6 +35,7 @@ final class PbsFlowSemanticSupport {
|
||||
UNKNOWN,
|
||||
UNIT,
|
||||
INT,
|
||||
LONG,
|
||||
FLOAT,
|
||||
BOOL,
|
||||
STR,
|
||||
@@ -77,6 +78,10 @@ final class PbsFlowSemanticSupport {
|
||||
return new TypeView(Kind.INT, "int", List.of(), null, null, List.of(), null);
|
||||
}
|
||||
|
||||
static TypeView longType() {
|
||||
return new TypeView(Kind.LONG, "long", List.of(), null, null, List.of(), null);
|
||||
}
|
||||
|
||||
static TypeView floatType() {
|
||||
return new TypeView(Kind.FLOAT, "float", List.of(), null, null, List.of(), null);
|
||||
}
|
||||
@@ -543,6 +548,9 @@ final class PbsFlowSemanticSupport {
|
||||
case UNIT -> TypeView.unit();
|
||||
case SELF, ERROR -> TypeView.unknown();
|
||||
case SIMPLE -> {
|
||||
if ("long".equals(typeRef.name())) {
|
||||
yield TypeView.longType();
|
||||
}
|
||||
if ("int".equals(typeRef.name())) {
|
||||
yield TypeView.intType();
|
||||
}
|
||||
|
||||
+24
-7
@@ -41,7 +41,11 @@ final class PbsFlowStructuralExpressionAnalyzer {
|
||||
final var model = context.model();
|
||||
final var diagnostics = context.diagnostics();
|
||||
|
||||
if (expression instanceof PbsAst.IntLiteralExpr) {
|
||||
if (expression instanceof PbsAst.IntLiteralExpr literal) {
|
||||
if (expectedType != null && expectedType.kind() == Kind.LONG) return ExprResult.type(TypeView.longType());
|
||||
if (literal.value() < Integer.MIN_VALUE || literal.value() > Integer.MAX_VALUE) {
|
||||
Diagnostics.error(diagnostics, "E_SEM_INTEGER_RANGE", "Integer literal exceeds int range; use an explicit long context", literal.span());
|
||||
}
|
||||
return ExprResult.type(TypeView.intType());
|
||||
}
|
||||
if (expression instanceof PbsAst.FloatLiteralExpr) {
|
||||
@@ -119,8 +123,11 @@ final class PbsFlowStructuralExpressionAnalyzer {
|
||||
}
|
||||
if (expression instanceof PbsAst.TupleExpr tupleExpr) {
|
||||
final var fields = new ArrayList<TupleField>(tupleExpr.items().size());
|
||||
int itemIndex=0;
|
||||
for (final var item : tupleExpr.items()) {
|
||||
final var value = analyzeValueExpression(item.expression(), context, null).type();
|
||||
var fieldExpected=expectedType != null && expectedType.kind()==Kind.TUPLE && itemIndex<expectedType.tupleFields().size() ? expectedType.tupleFields().get(itemIndex).type() : null;
|
||||
itemIndex++;
|
||||
final var value = analyzeValueExpression(item.expression(), context, fieldExpected).type();
|
||||
fields.add(new TupleField(item.label(), value));
|
||||
}
|
||||
return ExprResult.type(TypeView.tuple(fields));
|
||||
@@ -129,18 +136,22 @@ final class PbsFlowStructuralExpressionAnalyzer {
|
||||
return ExprResult.type(blockAnalysisDelegate.analyze(blockExpr.block(), context, context.valueContext()));
|
||||
}
|
||||
if (expression instanceof PbsAst.UnaryExpr unaryExpr) {
|
||||
final var operand = analyzeValueExpression(unaryExpr.expression(), context, null).type();
|
||||
final var operand = analyzeValueExpression(unaryExpr.expression(), context, expectedType).type();
|
||||
if ("!".equals(unaryExpr.operator()) || "not".equals(unaryExpr.operator())) {
|
||||
return ExprResult.type(TypeView.bool());
|
||||
}
|
||||
if ("-".equals(unaryExpr.operator()) && (typeOps.isInt(operand) || typeOps.isFloat(operand))) {
|
||||
if ("-".equals(unaryExpr.operator()) && (typeOps.isInt(operand) || operand.kind() == Kind.LONG || typeOps.isFloat(operand))) {
|
||||
return ExprResult.type(operand);
|
||||
}
|
||||
return ExprResult.type(TypeView.unknown());
|
||||
}
|
||||
if (expression instanceof PbsAst.BinaryExpr binaryExpr) {
|
||||
final var left = analyzeValueExpression(binaryExpr.left(), context, null).type();
|
||||
final var right = analyzeValueExpression(binaryExpr.right(), context, null).type();
|
||||
final var left = analyzeValueExpression(binaryExpr.left(), context, expectedType != null && expectedType.kind()==Kind.LONG ? expectedType : null).type();
|
||||
final var right = analyzeValueExpression(binaryExpr.right(), context, expectedType != null && expectedType.kind()==Kind.LONG ? expectedType : null).type();
|
||||
if ((left.kind() == Kind.LONG || right.kind() == Kind.LONG) && left.kind() != right.kind()
|
||||
&& left.kind() != Kind.UNKNOWN && right.kind() != Kind.UNKNOWN) {
|
||||
Diagnostics.error(diagnostics, "E_SEM_NUMERIC_TYPE_MISMATCH", "Mixed numeric types require an explicit as conversion", binaryExpr.span());
|
||||
}
|
||||
return ExprResult.type(typeOps.inferBinaryResult(binaryExpr.operator(), left, right));
|
||||
}
|
||||
if (expression instanceof PbsAst.NoneExpr noneExpr) {
|
||||
@@ -167,7 +178,13 @@ final class PbsFlowStructuralExpressionAnalyzer {
|
||||
return ExprResult.type(TypeView.unknown());
|
||||
}
|
||||
if (expression instanceof PbsAst.AsExpr asExpr) {
|
||||
analyzeValueExpression(asExpr.expression(), context, null);
|
||||
final var source = analyzeValueExpression(asExpr.expression(), context, null).type();
|
||||
if ("int".equals(asExpr.contractName()) || "long".equals(asExpr.contractName()) || "float".equals(asExpr.contractName())) {
|
||||
if (source.kind() != Kind.INT && source.kind() != Kind.LONG && source.kind() != Kind.FLOAT && source.kind() != Kind.UNKNOWN) {
|
||||
Diagnostics.error(diagnostics, "E_SEM_NUMERIC_TYPE_MISMATCH", "Numeric conversion requires a numeric operand", asExpr.span());
|
||||
}
|
||||
return ExprResult.type(typeOps.typeFromTypeRef(PbsAst.TypeRef.simple(asExpr.contractName(), asExpr.span()), model, null));
|
||||
}
|
||||
if (model.contracts.containsKey(asExpr.contractName())) {
|
||||
return ExprResult.type(TypeView.contract(asExpr.contractName()));
|
||||
}
|
||||
|
||||
+8
-2
@@ -15,6 +15,9 @@ final class PbsFlowTypeOps {
|
||||
if (isFloat(left) || isFloat(right)) {
|
||||
return TypeView.floatType();
|
||||
}
|
||||
if (left.kind() == Kind.LONG && right.kind() == Kind.LONG) {
|
||||
return TypeView.longType();
|
||||
}
|
||||
if (isInt(left) && isInt(right)) {
|
||||
return TypeView.intType();
|
||||
}
|
||||
@@ -46,7 +49,7 @@ final class PbsFlowTypeOps {
|
||||
return false;
|
||||
}
|
||||
return switch (actual.kind()) {
|
||||
case UNIT, INT, FLOAT, BOOL, STR -> true;
|
||||
case UNIT, INT, LONG, FLOAT, BOOL, STR -> true;
|
||||
case STRUCT, SERVICE, CONTRACT, CALLBACK, ENUM, ERROR, TYPE_REF, ASSET_NAMESPACE -> actual.name().equals(expected.name());
|
||||
case ADDRESSABLE -> true;
|
||||
case OPTIONAL -> compatible(actual.inner(), expected.inner());
|
||||
@@ -116,7 +119,7 @@ final class PbsFlowTypeOps {
|
||||
}
|
||||
|
||||
boolean isScalarComparable(final TypeView type) {
|
||||
return isBool(type) || isInt(type) || isFloat(type) || isStr(type);
|
||||
return type.kind() == Kind.LONG || isBool(type) || isInt(type) || isFloat(type) || isStr(type);
|
||||
}
|
||||
|
||||
boolean isUnit(final TypeView type) {
|
||||
@@ -172,6 +175,9 @@ final class PbsFlowTypeOps {
|
||||
}
|
||||
|
||||
private TypeView simpleType(final String name, final Model model) {
|
||||
if ("long".equals(name)) {
|
||||
return TypeView.longType();
|
||||
}
|
||||
if ("int".equals(name)) {
|
||||
return TypeView.intType();
|
||||
}
|
||||
|
||||
+1
-1
@@ -11,7 +11,7 @@ final class PbsInlineHintSurfaceFormatter {
|
||||
return switch (type.kind()) {
|
||||
case UNKNOWN, ASSET_NAMESPACE -> null;
|
||||
case UNIT -> "void";
|
||||
case INT, FLOAT, BOOL, STR -> type.name();
|
||||
case INT, LONG, FLOAT, BOOL, STR -> type.name();
|
||||
case STRUCT,
|
||||
SERVICE,
|
||||
CONTRACT,
|
||||
|
||||
+1
-1
@@ -315,7 +315,7 @@ final class PbsImportedSemanticContextService {
|
||||
}
|
||||
|
||||
private boolean isPrimitiveTypeName(final String typeName) {
|
||||
return "int".equals(typeName)
|
||||
return "long".equals(typeName) || "int".equals(typeName)
|
||||
|| "float".equals(typeName)
|
||||
|| "bool".equals(typeName)
|
||||
|| "str".equals(typeName)
|
||||
|
||||
+7
-7
@@ -3,7 +3,7 @@ Represents a packed RGBA color.
|
||||
""")]
|
||||
[BuiltinType(name = "color", version = 1)]
|
||||
declare builtin type Color(
|
||||
pub raw: int
|
||||
pub raw: long
|
||||
) {
|
||||
[Doc(markdown = """
|
||||
Builds a color from its packed integer representation.
|
||||
@@ -11,7 +11,7 @@ declare builtin type Color(
|
||||
- `raw`: packed color value.
|
||||
""")]
|
||||
[IntrinsicCall(name = "from_raw", version = 1)]
|
||||
fn from_raw(raw: int) -> Color;
|
||||
fn from_raw(raw: long) -> Color;
|
||||
|
||||
[Doc(markdown = """
|
||||
Builds an opaque color from red, green, and blue channels.
|
||||
@@ -21,7 +21,7 @@ declare builtin type Color(
|
||||
- `b`: blue channel.
|
||||
""")]
|
||||
[IntrinsicCall(name = "rgb", version = 1)]
|
||||
fn rgb(r: int, g: int, b: int) -> Color;
|
||||
fn rgb(r: long, g: long, b: long) -> Color;
|
||||
|
||||
[Doc(markdown = """
|
||||
Builds a color from red, green, blue, and alpha channels.
|
||||
@@ -32,7 +32,7 @@ declare builtin type Color(
|
||||
- `a`: alpha channel.
|
||||
""")]
|
||||
[IntrinsicCall(name = "rgba", version = 1)]
|
||||
fn rgba(r: int, g: int, b: int, a: int) -> Color;
|
||||
fn rgba(r: long, g: long, b: long, a: long) -> Color;
|
||||
|
||||
[Doc(markdown = """
|
||||
Parses a CSS-style RGBA color string.
|
||||
@@ -48,19 +48,19 @@ declare builtin type Color(
|
||||
- `value`: grayscale channel value.
|
||||
""")]
|
||||
[IntrinsicCall(name = "gray_scale", version = 1)]
|
||||
fn gray_scale(value: int) -> Color;
|
||||
fn gray_scale(value: long) -> Color;
|
||||
|
||||
[Doc(markdown = """
|
||||
Returns the packed RGB portion of this color.
|
||||
""")]
|
||||
[IntrinsicCall(name = "hex", version = 1)]
|
||||
fn hex() -> int;
|
||||
fn hex() -> long;
|
||||
|
||||
[Doc(markdown = """
|
||||
Returns the alpha channel of this color.
|
||||
""")]
|
||||
[IntrinsicCall(name = "alpha", version = 1)]
|
||||
fn alpha() -> int;
|
||||
fn alpha() -> long;
|
||||
}
|
||||
|
||||
[Doc(markdown = """
|
||||
|
||||
+192
-158
@@ -1,171 +1,205 @@
|
||||
[Doc(markdown = """
|
||||
Root input device provider.
|
||||
""")]
|
||||
[BuiltinType(name = "input", version = 1)]
|
||||
declare builtin type InputType() {
|
||||
[Doc(markdown = """
|
||||
Returns the gamepad input state.
|
||||
""")]
|
||||
[IntrinsicCall(name = "pad", version = 1)]
|
||||
fn pad() -> InputPad;
|
||||
|
||||
[Doc(markdown = """
|
||||
Returns the touch input state.
|
||||
""")]
|
||||
[IntrinsicCall(name = "touch", version = 1)]
|
||||
fn touch() -> InputTouch;
|
||||
}
|
||||
declare enum Button(Up, Down, Left, Right, A, B, X, Y, L, R, Start, Select);
|
||||
|
||||
[Doc(markdown = """
|
||||
Represents the current gamepad state.
|
||||
Direct zero-argument gamepad queries. Prefer Pad with a typed Button in game code.
|
||||
""")]
|
||||
[BuiltinType(name = "input.pad", version = 1)]
|
||||
declare builtin type InputPad() {
|
||||
[Doc(markdown = """
|
||||
Returns the up directional button.
|
||||
""")]
|
||||
[IntrinsicCall(name = "up", version = 1)]
|
||||
fn up() -> InputButton;
|
||||
|
||||
[Doc(markdown = """
|
||||
Returns the down directional button.
|
||||
""")]
|
||||
[IntrinsicCall(name = "down", version = 1)]
|
||||
fn down() -> InputButton;
|
||||
|
||||
[Doc(markdown = """
|
||||
Returns the left directional button.
|
||||
""")]
|
||||
[IntrinsicCall(name = "left", version = 1)]
|
||||
fn left() -> InputButton;
|
||||
|
||||
[Doc(markdown = """
|
||||
Returns the right directional button.
|
||||
""")]
|
||||
[IntrinsicCall(name = "right", version = 1)]
|
||||
fn right() -> InputButton;
|
||||
|
||||
[Doc(markdown = """
|
||||
Returns the A action button.
|
||||
""")]
|
||||
[IntrinsicCall(name = "a", version = 1)]
|
||||
fn a() -> InputButton;
|
||||
|
||||
[Doc(markdown = """
|
||||
Returns the B action button.
|
||||
""")]
|
||||
[IntrinsicCall(name = "b", version = 1)]
|
||||
fn b() -> InputButton;
|
||||
|
||||
[Doc(markdown = """
|
||||
Returns the X action button.
|
||||
""")]
|
||||
[IntrinsicCall(name = "x", version = 1)]
|
||||
fn x() -> InputButton;
|
||||
|
||||
[Doc(markdown = """
|
||||
Returns the Y action button.
|
||||
""")]
|
||||
[IntrinsicCall(name = "y", version = 1)]
|
||||
fn y() -> InputButton;
|
||||
|
||||
[Doc(markdown = """
|
||||
Returns the left shoulder button.
|
||||
""")]
|
||||
[IntrinsicCall(name = "l", version = 1)]
|
||||
fn l() -> InputButton;
|
||||
|
||||
[Doc(markdown = """
|
||||
Returns the right shoulder button.
|
||||
""")]
|
||||
[IntrinsicCall(name = "r", version = 1)]
|
||||
fn r() -> InputButton;
|
||||
|
||||
[Doc(markdown = """
|
||||
Returns the start button.
|
||||
""")]
|
||||
[IntrinsicCall(name = "start", version = 1)]
|
||||
fn start() -> InputButton;
|
||||
|
||||
[Doc(markdown = """
|
||||
Returns the select button.
|
||||
""")]
|
||||
[IntrinsicCall(name = "select", version = 1)]
|
||||
fn select() -> InputButton;
|
||||
declare builtin type LowPad() {
|
||||
[IntrinsicCall(name = "input.pad.up.pressed", version = 1)]
|
||||
fn up_pressed() -> bool;
|
||||
[IntrinsicCall(name = "input.pad.up.released", version = 1)]
|
||||
fn up_released() -> bool;
|
||||
[IntrinsicCall(name = "input.pad.up.down", version = 1)]
|
||||
fn up_down() -> bool;
|
||||
[IntrinsicCall(name = "input.pad.up.hold", version = 1)]
|
||||
fn up_hold() -> long;
|
||||
[IntrinsicCall(name = "input.pad.down.pressed", version = 1)]
|
||||
fn down_pressed() -> bool;
|
||||
[IntrinsicCall(name = "input.pad.down.released", version = 1)]
|
||||
fn down_released() -> bool;
|
||||
[IntrinsicCall(name = "input.pad.down.down", version = 1)]
|
||||
fn down_down() -> bool;
|
||||
[IntrinsicCall(name = "input.pad.down.hold", version = 1)]
|
||||
fn down_hold() -> long;
|
||||
[IntrinsicCall(name = "input.pad.left.pressed", version = 1)]
|
||||
fn left_pressed() -> bool;
|
||||
[IntrinsicCall(name = "input.pad.left.released", version = 1)]
|
||||
fn left_released() -> bool;
|
||||
[IntrinsicCall(name = "input.pad.left.down", version = 1)]
|
||||
fn left_down() -> bool;
|
||||
[IntrinsicCall(name = "input.pad.left.hold", version = 1)]
|
||||
fn left_hold() -> long;
|
||||
[IntrinsicCall(name = "input.pad.right.pressed", version = 1)]
|
||||
fn right_pressed() -> bool;
|
||||
[IntrinsicCall(name = "input.pad.right.released", version = 1)]
|
||||
fn right_released() -> bool;
|
||||
[IntrinsicCall(name = "input.pad.right.down", version = 1)]
|
||||
fn right_down() -> bool;
|
||||
[IntrinsicCall(name = "input.pad.right.hold", version = 1)]
|
||||
fn right_hold() -> long;
|
||||
[IntrinsicCall(name = "input.pad.a.pressed", version = 1)]
|
||||
fn a_pressed() -> bool;
|
||||
[IntrinsicCall(name = "input.pad.a.released", version = 1)]
|
||||
fn a_released() -> bool;
|
||||
[IntrinsicCall(name = "input.pad.a.down", version = 1)]
|
||||
fn a_down() -> bool;
|
||||
[IntrinsicCall(name = "input.pad.a.hold", version = 1)]
|
||||
fn a_hold() -> long;
|
||||
[IntrinsicCall(name = "input.pad.b.pressed", version = 1)]
|
||||
fn b_pressed() -> bool;
|
||||
[IntrinsicCall(name = "input.pad.b.released", version = 1)]
|
||||
fn b_released() -> bool;
|
||||
[IntrinsicCall(name = "input.pad.b.down", version = 1)]
|
||||
fn b_down() -> bool;
|
||||
[IntrinsicCall(name = "input.pad.b.hold", version = 1)]
|
||||
fn b_hold() -> long;
|
||||
[IntrinsicCall(name = "input.pad.x.pressed", version = 1)]
|
||||
fn x_pressed() -> bool;
|
||||
[IntrinsicCall(name = "input.pad.x.released", version = 1)]
|
||||
fn x_released() -> bool;
|
||||
[IntrinsicCall(name = "input.pad.x.down", version = 1)]
|
||||
fn x_down() -> bool;
|
||||
[IntrinsicCall(name = "input.pad.x.hold", version = 1)]
|
||||
fn x_hold() -> long;
|
||||
[IntrinsicCall(name = "input.pad.y.pressed", version = 1)]
|
||||
fn y_pressed() -> bool;
|
||||
[IntrinsicCall(name = "input.pad.y.released", version = 1)]
|
||||
fn y_released() -> bool;
|
||||
[IntrinsicCall(name = "input.pad.y.down", version = 1)]
|
||||
fn y_down() -> bool;
|
||||
[IntrinsicCall(name = "input.pad.y.hold", version = 1)]
|
||||
fn y_hold() -> long;
|
||||
[IntrinsicCall(name = "input.pad.l.pressed", version = 1)]
|
||||
fn l_pressed() -> bool;
|
||||
[IntrinsicCall(name = "input.pad.l.released", version = 1)]
|
||||
fn l_released() -> bool;
|
||||
[IntrinsicCall(name = "input.pad.l.down", version = 1)]
|
||||
fn l_down() -> bool;
|
||||
[IntrinsicCall(name = "input.pad.l.hold", version = 1)]
|
||||
fn l_hold() -> long;
|
||||
[IntrinsicCall(name = "input.pad.r.pressed", version = 1)]
|
||||
fn r_pressed() -> bool;
|
||||
[IntrinsicCall(name = "input.pad.r.released", version = 1)]
|
||||
fn r_released() -> bool;
|
||||
[IntrinsicCall(name = "input.pad.r.down", version = 1)]
|
||||
fn r_down() -> bool;
|
||||
[IntrinsicCall(name = "input.pad.r.hold", version = 1)]
|
||||
fn r_hold() -> long;
|
||||
[IntrinsicCall(name = "input.pad.start.pressed", version = 1)]
|
||||
fn start_pressed() -> bool;
|
||||
[IntrinsicCall(name = "input.pad.start.released", version = 1)]
|
||||
fn start_released() -> bool;
|
||||
[IntrinsicCall(name = "input.pad.start.down", version = 1)]
|
||||
fn start_down() -> bool;
|
||||
[IntrinsicCall(name = "input.pad.start.hold", version = 1)]
|
||||
fn start_hold() -> long;
|
||||
[IntrinsicCall(name = "input.pad.select.pressed", version = 1)]
|
||||
fn select_pressed() -> bool;
|
||||
[IntrinsicCall(name = "input.pad.select.released", version = 1)]
|
||||
fn select_released() -> bool;
|
||||
[IntrinsicCall(name = "input.pad.select.down", version = 1)]
|
||||
fn select_down() -> bool;
|
||||
[IntrinsicCall(name = "input.pad.select.hold", version = 1)]
|
||||
fn select_hold() -> long;
|
||||
}
|
||||
|
||||
[Doc(markdown = """
|
||||
Represents the current touch input state.
|
||||
Queries the selected gamepad button at the time of the call.
|
||||
""")]
|
||||
declare service Pad {
|
||||
[Doc(markdown = """
|
||||
Queries pressed for the selected button. Only that endpoint is executed.
|
||||
""")]
|
||||
fn pressed(button: Button) -> bool {
|
||||
return switch button {
|
||||
Button.Up: { LowPad.up_pressed() },
|
||||
Button.Down: { LowPad.down_pressed() },
|
||||
Button.Left: { LowPad.left_pressed() },
|
||||
Button.Right: { LowPad.right_pressed() },
|
||||
Button.A: { LowPad.a_pressed() },
|
||||
Button.B: { LowPad.b_pressed() },
|
||||
Button.X: { LowPad.x_pressed() },
|
||||
Button.Y: { LowPad.y_pressed() },
|
||||
Button.L: { LowPad.l_pressed() },
|
||||
Button.R: { LowPad.r_pressed() },
|
||||
Button.Start: { LowPad.start_pressed() },
|
||||
Button.Select: { LowPad.select_pressed() },
|
||||
};
|
||||
}
|
||||
[Doc(markdown = """
|
||||
Queries released for the selected button. Only that endpoint is executed.
|
||||
""")]
|
||||
fn released(button: Button) -> bool {
|
||||
return switch button {
|
||||
Button.Up: { LowPad.up_released() },
|
||||
Button.Down: { LowPad.down_released() },
|
||||
Button.Left: { LowPad.left_released() },
|
||||
Button.Right: { LowPad.right_released() },
|
||||
Button.A: { LowPad.a_released() },
|
||||
Button.B: { LowPad.b_released() },
|
||||
Button.X: { LowPad.x_released() },
|
||||
Button.Y: { LowPad.y_released() },
|
||||
Button.L: { LowPad.l_released() },
|
||||
Button.R: { LowPad.r_released() },
|
||||
Button.Start: { LowPad.start_released() },
|
||||
Button.Select: { LowPad.select_released() },
|
||||
};
|
||||
}
|
||||
[Doc(markdown = """
|
||||
Queries down for the selected button. Only that endpoint is executed.
|
||||
""")]
|
||||
fn down(button: Button) -> bool {
|
||||
return switch button {
|
||||
Button.Up: { LowPad.up_down() },
|
||||
Button.Down: { LowPad.down_down() },
|
||||
Button.Left: { LowPad.left_down() },
|
||||
Button.Right: { LowPad.right_down() },
|
||||
Button.A: { LowPad.a_down() },
|
||||
Button.B: { LowPad.b_down() },
|
||||
Button.X: { LowPad.x_down() },
|
||||
Button.Y: { LowPad.y_down() },
|
||||
Button.L: { LowPad.l_down() },
|
||||
Button.R: { LowPad.r_down() },
|
||||
Button.Start: { LowPad.start_down() },
|
||||
Button.Select: { LowPad.select_down() },
|
||||
};
|
||||
}
|
||||
[Doc(markdown = """
|
||||
Queries hold for the selected button. Only that endpoint is executed.
|
||||
""")]
|
||||
fn hold(button: Button) -> long {
|
||||
return switch button {
|
||||
Button.Up: { LowPad.up_hold() },
|
||||
Button.Down: { LowPad.down_hold() },
|
||||
Button.Left: { LowPad.left_hold() },
|
||||
Button.Right: { LowPad.right_hold() },
|
||||
Button.A: { LowPad.a_hold() },
|
||||
Button.B: { LowPad.b_hold() },
|
||||
Button.X: { LowPad.x_hold() },
|
||||
Button.Y: { LowPad.y_hold() },
|
||||
Button.L: { LowPad.l_hold() },
|
||||
Button.R: { LowPad.r_hold() },
|
||||
Button.Start: { LowPad.start_hold() },
|
||||
Button.Select: { LowPad.select_hold() },
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
[Doc(markdown = """
|
||||
Queries the current touch contact and coordinates.
|
||||
""")]
|
||||
[BuiltinType(name = "input.touch", version = 1)]
|
||||
declare builtin type InputTouch() {
|
||||
[Doc(markdown = """
|
||||
Returns the touch contact as a button state.
|
||||
""")]
|
||||
[IntrinsicCall(name = "button", version = 1)]
|
||||
fn button() -> InputButton;
|
||||
|
||||
[Doc(markdown = """
|
||||
Returns the current touch x coordinate.
|
||||
""")]
|
||||
[IntrinsicCall(name = "x", version = 1)]
|
||||
fn x() -> int;
|
||||
|
||||
[Doc(markdown = """
|
||||
Returns the current touch y coordinate.
|
||||
""")]
|
||||
[IntrinsicCall(name = "y", version = 1)]
|
||||
fn y() -> int;
|
||||
}
|
||||
|
||||
[Doc(markdown = """
|
||||
Represents one digital input button.
|
||||
""")]
|
||||
[BuiltinType(name = "input.button", version = 1)]
|
||||
declare builtin type InputButton() {
|
||||
[Doc(markdown = """
|
||||
Returns true on the frame where the button becomes down.
|
||||
""")]
|
||||
[IntrinsicCall(name = "pressed", version = 1)]
|
||||
declare builtin type Touch() {
|
||||
[IntrinsicCall(name = "input.touch.button.pressed", version = 1)]
|
||||
fn pressed() -> bool;
|
||||
|
||||
[Doc(markdown = """
|
||||
Returns true on the frame where the button becomes up.
|
||||
""")]
|
||||
[IntrinsicCall(name = "released", version = 1)]
|
||||
[IntrinsicCall(name = "input.touch.button.released", version = 1)]
|
||||
fn released() -> bool;
|
||||
|
||||
[Doc(markdown = """
|
||||
Returns true while the button is currently down.
|
||||
""")]
|
||||
[IntrinsicCall(name = "down", version = 1)]
|
||||
[IntrinsicCall(name = "input.touch.button.down", version = 1)]
|
||||
fn down() -> bool;
|
||||
|
||||
[Doc(markdown = """
|
||||
Returns how long the button has been held.
|
||||
""")]
|
||||
[IntrinsicCall(name = "hold", version = 1)]
|
||||
fn hold() -> int;
|
||||
}
|
||||
|
||||
[Doc(markdown = """
|
||||
High-level access to player input devices.
|
||||
""")]
|
||||
declare service Input
|
||||
{
|
||||
[Doc(markdown = """
|
||||
Returns the gamepad input state.
|
||||
""")]
|
||||
fn pad() -> InputPad
|
||||
{
|
||||
return InputType.pad();
|
||||
}
|
||||
|
||||
[Doc(markdown = """
|
||||
Returns the touch input state.
|
||||
""")]
|
||||
fn touch() -> InputTouch
|
||||
{
|
||||
return InputType.touch();
|
||||
}
|
||||
[IntrinsicCall(name = "input.touch.button.hold", version = 1)]
|
||||
fn hold() -> long;
|
||||
[IntrinsicCall(name = "x", version = 1)]
|
||||
fn x() -> long;
|
||||
[IntrinsicCall(name = "y", version = 1)]
|
||||
fn y() -> long;
|
||||
}
|
||||
|
||||
+4
-4
@@ -1,4 +1,4 @@
|
||||
pub struct InputPad;
|
||||
pub struct InputTouch;
|
||||
pub struct InputButton;
|
||||
pub service Input;
|
||||
pub enum Button;
|
||||
pub service Pad;
|
||||
pub struct Touch;
|
||||
pub struct LowPad;
|
||||
|
||||
+14
-5
@@ -41,6 +41,15 @@ class PbsGateUSdkInterfaceConformanceTest {
|
||||
@TempDir
|
||||
Path tempDir;
|
||||
|
||||
@Test
|
||||
void removedInputObjectsExplainTheirMigration() throws IOException {
|
||||
final var result = compileWorkspaceModule(tempDir.resolve("removed-input"), """
|
||||
import { Input } from @sdk:input;
|
||||
fn main() -> void { let button = Input.pad().a(); }
|
||||
""", "pub fn main() -> void;", 1, null);
|
||||
assertTrue(result.diagnostics().stream().anyMatch(d -> d.getMessage().contains("migrate to Pad.pressed")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void gateU_shouldClassifySourceKindForInterfaceDeclarations() {
|
||||
final var source = """
|
||||
@@ -88,12 +97,12 @@ class PbsGateUSdkInterfaceConformanceTest {
|
||||
import { Color } from @core:color;
|
||||
import { Composer } from @sdk:composer;
|
||||
import { Gfx } from @sdk:gfx;
|
||||
import { Input, InputPad, InputButton } from @sdk:input;
|
||||
import { Pad, Button, Touch } from @sdk:input;
|
||||
import { Assets } from @sdk:asset;
|
||||
import { Log } from @sdk:log;
|
||||
|
||||
declare contract Renderer {
|
||||
fn render(composer: Composer, gfx: Gfx, color: Color, input: Input, pad: InputPad, button: InputButton, assets: Assets, log: Log) -> void;
|
||||
fn render(composer: Composer, gfx: Gfx, color: Color, pad: Pad, button: Button, assets: Assets, log: Log) -> void;
|
||||
}
|
||||
""",
|
||||
"pub contract Renderer;",
|
||||
@@ -106,12 +115,12 @@ class PbsGateUSdkInterfaceConformanceTest {
|
||||
assertTrue(positive.irBackend().getReservedMetadata().builtinTypeSurfaces().stream()
|
||||
.anyMatch(t -> t.sourceTypeName().equals("Color")));
|
||||
assertTrue(positive.irBackend().getReservedMetadata().builtinTypeSurfaces().stream()
|
||||
.anyMatch(t -> t.sourceTypeName().equals("InputType") && t.canonicalTypeName().equals("input")));
|
||||
.anyMatch(t -> t.sourceTypeName().equals("LowPad") && t.canonicalTypeName().equals("input.pad")));
|
||||
assertFalse(positive.irBackend().getReservedMetadata().builtinConstSurfaces().stream()
|
||||
.anyMatch(c -> c.canonicalTarget().equals("input")));
|
||||
assertTrue(positive.irBackend().getReservedMetadata().builtinTypeSurfaces().stream()
|
||||
.anyMatch(t -> t.sourceTypeName().equals("InputButton")
|
||||
&& t.intrinsics().stream().anyMatch(i -> i.canonicalName().equals("input.button.hold"))));
|
||||
.anyMatch(t -> t.sourceTypeName().equals("LowPad")
|
||||
&& t.intrinsics().stream().anyMatch(i -> i.canonicalName().equals("input.pad.a.hold"))));
|
||||
assertTrue(positive.irBackend().getReservedMetadata().hostMethodBindings().stream()
|
||||
.anyMatch(h -> h.ownerName().equals("LowGfx")
|
||||
&& h.abiModule().equals("gfx2d")
|
||||
|
||||
+3
-3
@@ -133,11 +133,11 @@ final class PbsSemanticPresentationContractTest {
|
||||
@Test
|
||||
void shouldClassifyBuiltinTypesExposedByImportedStdlibModules() {
|
||||
final List<FrontendSemanticToken> semanticTokens = PBSDefinitions.PBS.getSemanticTokenProvider().tokenize("""
|
||||
import { Input } from @sdk:input;
|
||||
import { Pad, Button, Touch } from @sdk:input;
|
||||
|
||||
fn main() -> void {
|
||||
let touch : InputTouch = Input.touch();
|
||||
let pad : InputPad = Input.pad();
|
||||
let touch : long = Touch.x();
|
||||
let held : long = Pad.hold(Button.A);
|
||||
}
|
||||
""");
|
||||
|
||||
|
||||
+27
-70
@@ -1152,8 +1152,8 @@ class PBSFrontendPhaseServiceTest {
|
||||
.toList();
|
||||
assertTrue(intrinsicNames.contains("color.rgba"), "intrinsics=" + intrinsicNames);
|
||||
assertTrue(intrinsicNames.contains("color.html_rgba"), "intrinsics=" + intrinsicNames);
|
||||
assertTrue(intrinsicNames.contains("color.red"), "intrinsics=" + intrinsicNames);
|
||||
assertTrue(intrinsicNames.contains("color.transparent"), "intrinsics=" + intrinsicNames);
|
||||
assertTrue(irBackend.getExecutableFunctions().stream().flatMap(f -> f.instructions().stream()).anyMatch(i -> i.kind() == IRBackendExecutableFunction.InstructionKind.BUILTIN_CONST && i.label().equals("color.red@1")));
|
||||
assertTrue(irBackend.getExecutableFunctions().stream().flatMap(f -> f.instructions().stream()).anyMatch(i -> i.kind() == IRBackendExecutableFunction.InstructionKind.BUILTIN_CONST && i.label().equals("color.transparent@1")));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -1647,7 +1647,7 @@ class PBSFrontendPhaseServiceTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldResolveImportedBuiltinTypeChainsInExpressionFlowSemantics() throws IOException {
|
||||
void shouldResolveImportedPadFacadeAndTypedButton() throws IOException {
|
||||
final var projectRoot = tempDir.resolve("project-builtin-chain");
|
||||
final var sourceRoot = projectRoot.resolve("src");
|
||||
Files.createDirectories(sourceRoot);
|
||||
@@ -1656,12 +1656,12 @@ class PBSFrontendPhaseServiceTest {
|
||||
final var modBarrel = sourceRoot.resolve("mod.barrel");
|
||||
Files.writeString(sourceFile, """
|
||||
import { Log } from @sdk:log;
|
||||
import { Input } from @sdk:input;
|
||||
import { Pad, Button, Touch } from @sdk:input;
|
||||
|
||||
[Frame]
|
||||
fn frame() -> void
|
||||
{
|
||||
if (Input.pad().a().pressed())
|
||||
if (Pad.pressed(Button.A))
|
||||
{
|
||||
Log.debug("Hello World!");
|
||||
}
|
||||
@@ -1722,23 +1722,11 @@ class PBSFrontendPhaseServiceTest {
|
||||
.filter(instruction ->
|
||||
instruction.kind() == p.studio.compiler.models.IRBackendExecutableFunction.InstructionKind.CALL_INTRINSIC)
|
||||
.toList();
|
||||
final var inputPadExecutable = irBackend.getExecutableFunctions().stream()
|
||||
.filter(function -> "Input.pad".equals(function.callableName()))
|
||||
.findFirst()
|
||||
.orElseThrow();
|
||||
final var inputPadIntrinsics = inputPadExecutable.instructions().stream()
|
||||
.filter(instruction ->
|
||||
instruction.kind() == p.studio.compiler.models.IRBackendExecutableFunction.InstructionKind.CALL_INTRINSIC
|
||||
&& instruction.intrinsicCall() != null)
|
||||
.map(instruction -> instruction.intrinsicCall().canonicalName())
|
||||
.toList();
|
||||
assertTrue(callableCalls.contains("Input.pad"));
|
||||
assertTrue(intrinsicCalls.stream().anyMatch(instruction -> Integer.valueOf(1).equals(instruction.expectedArgSlots())));
|
||||
assertTrue(inputPadIntrinsics.contains("input.pad"));
|
||||
assertTrue(intrinsicCalls.stream().anyMatch(instruction ->
|
||||
instruction.intrinsicCall() != null && "input.pad.a".equals(instruction.intrinsicCall().canonicalName())));
|
||||
assertTrue(intrinsicCalls.stream().anyMatch(instruction ->
|
||||
instruction.intrinsicCall() != null && "input.button.pressed".equals(instruction.intrinsicCall().canonicalName())));
|
||||
assertTrue(callableCalls.contains("Pad.pressed"));
|
||||
assertTrue(intrinsicCalls.isEmpty());
|
||||
final var pad = irBackend.getExecutableFunctions().stream().filter(f -> f.callableName().equals("Pad.pressed")).findFirst().orElseThrow();
|
||||
assertEquals(12, pad.instructions().stream().filter(i -> i.intrinsicCall() != null).count());
|
||||
assertTrue(pad.instructions().stream().filter(i -> i.intrinsicCall() != null).allMatch(i -> i.expectedArgSlots() == 0));
|
||||
assertTrue(
|
||||
irBackend.getExecutableFunctions().stream().anyMatch(function -> "frame".equals(function.callableName())),
|
||||
"diagnostics="
|
||||
@@ -1748,7 +1736,7 @@ class PBSFrontendPhaseServiceTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldResolveIntrinsicChainsWithMethodNameCollisionsByOwnerIdentity() throws IOException {
|
||||
void shouldResolvePadAndTouchQueriesByOwnerIdentity() throws IOException {
|
||||
final var projectRoot = tempDir.resolve("project-intrinsic-owner-collision");
|
||||
final var sourceRoot = projectRoot.resolve("src");
|
||||
Files.createDirectories(sourceRoot);
|
||||
@@ -1756,13 +1744,13 @@ class PBSFrontendPhaseServiceTest {
|
||||
final var sourceFile = sourceRoot.resolve("main.pbs");
|
||||
final var modBarrel = sourceRoot.resolve("mod.barrel");
|
||||
Files.writeString(sourceFile, """
|
||||
import { Input } from @sdk:input;
|
||||
import { Pad, Button, Touch } from @sdk:input;
|
||||
|
||||
[Frame]
|
||||
fn frame() -> void
|
||||
{
|
||||
Input.pad().x().pressed();
|
||||
Input.touch().x();
|
||||
Pad.pressed(Button.X);
|
||||
Touch.x();
|
||||
}
|
||||
""");
|
||||
Files.writeString(modBarrel, "pub fn frame() -> void;");
|
||||
@@ -1811,37 +1799,16 @@ class PBSFrontendPhaseServiceTest {
|
||||
&& instruction.intrinsicCall() != null)
|
||||
.map(instruction -> instruction.intrinsicCall().canonicalName())
|
||||
.toList();
|
||||
final var inputPadExecutable = irBackend.getExecutableFunctions().stream()
|
||||
.filter(function -> "Input.pad".equals(function.callableName()))
|
||||
.findFirst()
|
||||
.orElseThrow();
|
||||
final var inputTouchExecutable = irBackend.getExecutableFunctions().stream()
|
||||
.filter(function -> "Input.touch".equals(function.callableName()))
|
||||
.findFirst()
|
||||
.orElseThrow();
|
||||
final var inputPadIntrinsics = inputPadExecutable.instructions().stream()
|
||||
.filter(instruction ->
|
||||
instruction.kind() == p.studio.compiler.models.IRBackendExecutableFunction.InstructionKind.CALL_INTRINSIC
|
||||
&& instruction.intrinsicCall() != null)
|
||||
.map(instruction -> instruction.intrinsicCall().canonicalName())
|
||||
.toList();
|
||||
final var inputTouchIntrinsics = inputTouchExecutable.instructions().stream()
|
||||
.filter(instruction ->
|
||||
instruction.kind() == p.studio.compiler.models.IRBackendExecutableFunction.InstructionKind.CALL_INTRINSIC
|
||||
&& instruction.intrinsicCall() != null)
|
||||
.map(instruction -> instruction.intrinsicCall().canonicalName())
|
||||
.toList();
|
||||
assertTrue(callableCalls.contains("Input.pad"));
|
||||
assertTrue(callableCalls.contains("Input.touch"));
|
||||
assertTrue(inputPadIntrinsics.contains("input.pad"));
|
||||
assertTrue(intrinsicCalls.contains("input.pad.x"));
|
||||
assertTrue(intrinsicCalls.contains("input.button.pressed"));
|
||||
assertTrue(inputTouchIntrinsics.contains("input.touch"));
|
||||
assertTrue(callableCalls.contains("Pad.pressed"));
|
||||
assertTrue(intrinsicCalls.contains("input.touch.x"));
|
||||
assertFalse(intrinsicCalls.contains("input.pad"));
|
||||
final var pad = irBackend.getExecutableFunctions().stream().filter(f -> f.callableName().equals("Pad.pressed")).findFirst().orElseThrow();
|
||||
assertTrue(pad.instructions().stream().anyMatch(i -> i.intrinsicCall() != null && i.intrinsicCall().canonicalName().equals("input.pad.x.pressed")));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldResolveIntrinsicCallsOnBuiltinValuesStoredInLocals() throws IOException {
|
||||
void shouldPassStoredButtonValuesToPadQueries() throws IOException {
|
||||
final var projectRoot = tempDir.resolve("project-intrinsic-local-builtin-receiver");
|
||||
final var sourceRoot = projectRoot.resolve("src");
|
||||
Files.createDirectories(sourceRoot);
|
||||
@@ -1849,14 +1816,14 @@ class PBSFrontendPhaseServiceTest {
|
||||
final var sourceFile = sourceRoot.resolve("main.pbs");
|
||||
final var modBarrel = sourceRoot.resolve("mod.barrel");
|
||||
Files.writeString(sourceFile, """
|
||||
import { Input } from @sdk:input;
|
||||
import { Pad, Button, Touch } from @sdk:input;
|
||||
|
||||
[Frame]
|
||||
fn frame() -> void
|
||||
{
|
||||
let touch = Input.touch();
|
||||
touch.x();
|
||||
touch.y();
|
||||
let button = Button.A;
|
||||
Pad.pressed(button);
|
||||
Touch.y();
|
||||
}
|
||||
""");
|
||||
Files.writeString(modBarrel, "pub fn frame() -> void;");
|
||||
@@ -1905,20 +1872,10 @@ class PBSFrontendPhaseServiceTest {
|
||||
&& instruction.intrinsicCall() != null)
|
||||
.map(instruction -> instruction.intrinsicCall().canonicalName())
|
||||
.toList();
|
||||
final var inputTouchExecutable = irBackend.getExecutableFunctions().stream()
|
||||
.filter(function -> "Input.touch".equals(function.callableName()))
|
||||
.findFirst()
|
||||
.orElseThrow();
|
||||
final var inputTouchIntrinsics = inputTouchExecutable.instructions().stream()
|
||||
.filter(instruction ->
|
||||
instruction.kind() == p.studio.compiler.models.IRBackendExecutableFunction.InstructionKind.CALL_INTRINSIC
|
||||
&& instruction.intrinsicCall() != null)
|
||||
.map(instruction -> instruction.intrinsicCall().canonicalName())
|
||||
.toList();
|
||||
assertTrue(callableCalls.contains("Input.touch"));
|
||||
assertTrue(inputTouchIntrinsics.contains("input.touch"));
|
||||
assertTrue(intrinsicCalls.contains("input.touch.x"));
|
||||
assertTrue(callableCalls.contains("Pad.pressed"));
|
||||
assertTrue(intrinsicCalls.contains("input.touch.y"));
|
||||
assertFalse(intrinsicCalls.contains("input.touch"));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -3,6 +3,7 @@ plugins {
|
||||
}
|
||||
|
||||
dependencies {
|
||||
testImplementation(project(":prometeu-compiler:frontends:prometeu-frontend-pbs"))
|
||||
api(project(":prometeu-infra"))
|
||||
implementation(project(":prometeu-compiler:prometeu-deps"))
|
||||
implementation(project(":prometeu-compiler:prometeu-compiler-core"))
|
||||
|
||||
+22
@@ -94,6 +94,28 @@ public class LowerToIRVMService {
|
||||
operations.add(BytecodeEmitter.Operation.pushI32(value, sourceSpan));
|
||||
functionPc += IRVMOp.PUSH_I32.immediateSize() + 2;
|
||||
}
|
||||
case PUSH_I64, PUSH_F64, BUILTIN_CONST -> {
|
||||
final java.util.List<BytecodeModule.ConstantPoolEntry> entries;
|
||||
if (instr.kind() == IRBackendExecutableFunction.InstructionKind.BUILTIN_CONST) {
|
||||
var key = instr.label().split("@", 2);
|
||||
int dot = key[0].lastIndexOf('.');
|
||||
entries = IRVMBuiltinConstantDefinition.resolve(key[0].substring(0, dot), key[0].substring(dot + 1), Long.parseLong(key[1]))
|
||||
.orElseThrow(() -> new IllegalArgumentException("Unknown builtin constant: " + instr.label())).materialize().asList();
|
||||
} else {
|
||||
entries = java.util.List.of(instr.kind() == IRBackendExecutableFunction.InstructionKind.PUSH_I64
|
||||
? new BytecodeModule.Int64Constant(Long.parseLong(instr.label()))
|
||||
: new BytecodeModule.Float64Constant(Double.parseDouble(instr.label())));
|
||||
}
|
||||
if (instr.kind() == IRBackendExecutableFunction.InstructionKind.BUILTIN_CONST && entries.size() != instr.expectedRetSlots())
|
||||
throw new IllegalArgumentException("Builtin constant group width differs from declared type: " + instr.label());
|
||||
for (var value : entries) {
|
||||
int index = constPool.indexOf(value);
|
||||
if (index < 0) { index = constPool.size(); constPool.add(value); }
|
||||
instructions.add(new IRVMInstruction(IRVMOp.PUSH_CONST, index));
|
||||
operations.add(BytecodeEmitter.Operation.pushConst(index, sourceSpan));
|
||||
functionPc += IRVMOp.PUSH_CONST.immediateSize() + 2;
|
||||
}
|
||||
}
|
||||
case PUSH_CONST -> {
|
||||
final var value = instr.label() == null ? "" : instr.label();
|
||||
final var constPoolIndex = constPoolIndexByString.computeIfAbsent(value, ignored -> {
|
||||
|
||||
+124
@@ -0,0 +1,124 @@
|
||||
package p.studio.compiler.backend.irvm;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import p.studio.compiler.pbs.PbsFrontendCompiler;
|
||||
import p.studio.compiler.models.IRBackend;
|
||||
import p.studio.compiler.backend.bytecode.*;
|
||||
import p.studio.compiler.source.diagnostics.DiagnosticSink;
|
||||
import p.studio.compiler.source.identifiers.FileId;
|
||||
import p.studio.compiler.models.SourceKind;
|
||||
import java.nio.file.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class PbsRuntimeAlignmentTest {
|
||||
private static String sdk(String path) throws Exception {
|
||||
try(var stream = PbsFrontendCompiler.class.getResourceAsStream("/game/stdlib/1/"+path+"/main.pbs")) {
|
||||
assertNotNull(stream); return new String(stream.readAllBytes(), java.nio.charset.StandardCharsets.UTF_8);
|
||||
}
|
||||
}
|
||||
private static BytecodeModule compile(String name,String source) 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,
|
||||
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);
|
||||
var module=new BytecodeEmitter().emit(program.coherentEmissionPlan());
|
||||
new BytecodePreloadVerifierService().verify(module);
|
||||
var directory=Path.of("build/registry-conformance");Files.createDirectories(directory);
|
||||
Files.write(directory.resolve("pbs-"+name+".pbx"),module.serialize());
|
||||
return module;
|
||||
}
|
||||
@Test void numericValuesAndExplicitConversionsReachProductionPbx() throws Exception {
|
||||
compile("numeric", """
|
||||
declare service Probe {
|
||||
fn widen(value: int) -> long { return value as long; }
|
||||
fn contextual() -> long { return 1; }
|
||||
fn receive(value: long) -> long { return value; }
|
||||
fn main() -> long {
|
||||
let large: long = 2147483648;
|
||||
let maximum: long = 9223372036854775807;
|
||||
Probe.contextual();
|
||||
Probe.receive(2147483648);
|
||||
return large + Probe.widen(7);
|
||||
}
|
||||
}
|
||||
""");
|
||||
compile("narrow", "declare service Probe { fn main() -> int { let value: long = 2147483648; return value as int; } }");
|
||||
compile("float", "declare service Probe { fn main() -> float { return 1.5 + 2.25; } }");
|
||||
compile("overflow", "declare service Probe { fn main() -> int { return 2147483647 + 1; } }");
|
||||
}
|
||||
@Test void allInputQueriesCompileFromThePublishedFacade() throws Exception {
|
||||
var input=sdk("sdk/input");
|
||||
for (var button : new String[]{"Up","Down","Left","Right","A","B","X","Y","L","R","Start","Select"}) {
|
||||
for(var query:new String[]{"pressed","released","down","hold"}) {
|
||||
var type=query.equals("hold")?"long":"bool";
|
||||
compile("pad-"+button.toLowerCase()+"-"+query,input+"\ndeclare service Probe { fn select(button: Button) -> Button { return button; } fn main() -> "+type+" { let button = Probe.select(Button."+button+"); return Pad."+query+"(button); } }");
|
||||
compile("pad-"+button.toLowerCase()+"-"+query+"-constant", input+"\ndeclare service Probe { fn main() -> "+type+" { return Pad."+query+"(Button."+button+"); } }");
|
||||
}
|
||||
}
|
||||
for(var query:new String[]{"pressed","released","down","hold","x","y"}) {
|
||||
var type=java.util.Set.of("hold","x","y").contains(query)?"long":"bool";
|
||||
compile("touch-"+query,input+"\ndeclare service Probe { fn main() -> "+type+" { return Touch."+query+"(); } }");
|
||||
}
|
||||
}
|
||||
@Test void completeBuiltinAndTupleGroupsReachProductionPbx() throws Exception {
|
||||
compile("vec2", """
|
||||
[BuiltinType(name = "vec2", version = 1)]
|
||||
declare builtin type Vector(pub x: float, pub y: float) {}
|
||||
[BuiltinConst(target = "vec2", name = "zero", version = 1)]
|
||||
declare const ZERO: Vector;
|
||||
declare service Probe {
|
||||
fn echo(value: Vector) -> Vector { return value; }
|
||||
fn main() -> Vector { let vector = Probe.echo(ZERO); return vector; }
|
||||
}
|
||||
""");
|
||||
compile("tuple", """
|
||||
declare service Probe {
|
||||
fn pair() -> (x: int, y: long) { return (x: 7, y: 8 as long); }
|
||||
fn main() -> (x: int, y: long) { let pair = Probe.pair(); return pair; }
|
||||
}
|
||||
""");
|
||||
compile("named", """
|
||||
declare global trace: int = 0;
|
||||
declare service Probe {
|
||||
fn x() -> int { trace = trace * 10 + 1; return 10; }
|
||||
fn y() -> int { trace = trace * 10 + 2; return 20; }
|
||||
fn combine(x: int, y: int) -> int { return x * 100 + y; }
|
||||
fn main() -> int {
|
||||
trace = 0;
|
||||
let value = Probe.combine apply (y: Probe.y(), x: Probe.x());
|
||||
return trace * 10000 + value;
|
||||
}
|
||||
}
|
||||
""");
|
||||
compile("color", sdk("core/color") + "declare service Probe { fn echo(value: Color) -> Color { return value; } fn main() -> Color { return Probe.echo(RED); } }");
|
||||
compile("pixel", sdk("core/color") + """
|
||||
[BuiltinType(name = "pixel", version = 1)]
|
||||
declare builtin type Pixel(pub x: long, pub y: long, pub color: Color) {}
|
||||
declare service Probe {
|
||||
fn echo(value: Pixel) -> Pixel { return value; }
|
||||
fn main() -> Pixel { let value = new Pixel(12, -34, RED); return Probe.echo(value); }
|
||||
}
|
||||
""");
|
||||
compile("string", "declare service Probe { fn echo(value: str) -> str { return value; } fn main() -> str { return Probe.echo(\"hello\"); } }");
|
||||
compile("division", "declare service Probe { fn main() -> int { return 1 / 0; } }");
|
||||
compile("minimum", "declare service Probe { fn main() -> long { return -9223372036854775808; } }");
|
||||
}
|
||||
@Test void wrongNumericAndButtonTypesAreRejected() throws Exception {
|
||||
for(var expression:new String[]{"1","1 as long","true","Other.A","\"A\""}) {
|
||||
var diagnostics=DiagnosticSink.empty();
|
||||
new PbsFrontendCompiler().compileFile(new FileId(0),sdk("sdk/input")+"\ndeclare enum Other(A); declare service Probe { fn main() -> bool { return Pad.pressed("+expression+"); } }",diagnostics,SourceKind.SDK_INTERFACE);
|
||||
assertTrue(diagnostics.hasErrors());
|
||||
}
|
||||
for(var source:new String[]{"fn main() -> long { let x: long = 1; let y: int = 1; return x + y; }", "fn main() -> int { return 2147483648; }", "fn main() -> long { return 9223372036854775808; }"}) {
|
||||
var diagnostics=DiagnosticSink.empty();
|
||||
new PbsFrontendCompiler().compileFile(new FileId(0),source,diagnostics);
|
||||
assertTrue(diagnostics.hasErrors());
|
||||
}
|
||||
}
|
||||
}
|
||||
+9
-1
@@ -255,7 +255,12 @@ public record IRBackendExecutableFunction(
|
||||
case REGISTRY -> {
|
||||
if (hostCall != null || intrinsicCall != null || calleeCallableId != null || !label.isEmpty() || !targetLabel.isEmpty()) throw new IllegalArgumentException("unexpected Registry instruction metadata");
|
||||
}
|
||||
case PUSH_I32 -> {
|
||||
case BUILTIN_CONST -> {
|
||||
if (label.isBlank() || expectedRetSlots == null || expectedRetSlots <= 0 || expectedArgSlots != null
|
||||
|| !targetLabel.isBlank() || !calleeCallableName.isBlank() || calleeCallableId != null || hostCall != null || intrinsicCall != null)
|
||||
throw new IllegalArgumentException("BUILTIN_CONST requires canonical identity and complete result width");
|
||||
}
|
||||
case PUSH_I32, PUSH_I64, PUSH_F64 -> {
|
||||
if (label.isBlank()) {
|
||||
throw new IllegalArgumentException("PUSH_I32 requires immediate label payload");
|
||||
}
|
||||
@@ -426,6 +431,9 @@ public record IRBackendExecutableFunction(
|
||||
public enum InstructionKind {
|
||||
REGISTRY,
|
||||
PUSH_I32,
|
||||
PUSH_I64,
|
||||
PUSH_F64,
|
||||
BUILTIN_CONST,
|
||||
PUSH_BOOL,
|
||||
PUSH_CONST,
|
||||
GET_LOCAL,
|
||||
|
||||
+2
-2
@@ -238,10 +238,10 @@ class CompilerLanguageServiceBridgeTest {
|
||||
new LspProjectContext("main", "pbs", Path.of(".")),
|
||||
Path.of("demo.pbs").toUri().toString(),
|
||||
"""
|
||||
import { Input } from @sdk:input;
|
||||
import { Pad, Button, Touch } from @sdk:input;
|
||||
|
||||
fn main() -> void {
|
||||
let touch : InputTouch = Input.touch();
|
||||
let touch : long = Touch.x();
|
||||
}
|
||||
""");
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Log } from @sdk:log;
|
||||
import { Input } from @sdk:input;
|
||||
import { Pad, Button, Touch } from @sdk:input;
|
||||
import { Composer } from @sdk:composer;
|
||||
import { Gfx } from @sdk:gfx;
|
||||
import { Assets } from @sdk:asset;
|
||||
@@ -56,16 +56,14 @@ fn frame() -> void
|
||||
}
|
||||
}
|
||||
|
||||
let touch : InputTouch = Input.touch();
|
||||
let pad : InputPad = Input.pad();
|
||||
|
||||
if (touch.button().released())
|
||||
if (Touch.released())
|
||||
{
|
||||
frame_counter = 0;
|
||||
tile_id = 0;
|
||||
}
|
||||
|
||||
if (touch.button().down())
|
||||
if (Touch.down())
|
||||
{
|
||||
frame_counter = frame_counter + 1;
|
||||
if (frame_counter > MAX_FRAMES)
|
||||
@@ -87,21 +85,21 @@ fn frame() -> void
|
||||
Log.info("camera_x:" + camera_x);
|
||||
|
||||
Composer.set_camera(camera_x, 0);
|
||||
Composer.emit_sprite(tile_id, 0, touch.x() - 16, touch.y() + 8, 2, 0, true, false, 0);
|
||||
Composer.emit_sprite(tile_id, 0, (Touch.x() as int) - 16, (Touch.y() as int) + 8, 2, 0, true, false, 0);
|
||||
|
||||
let a : int = 10;
|
||||
let b : int = 15;
|
||||
let total : int = a + b;
|
||||
|
||||
if (pad.a().pressed())
|
||||
if (Pad.pressed(Button.A))
|
||||
{
|
||||
total += 25;
|
||||
}
|
||||
else if (pad.b().pressed())
|
||||
else if (Pad.pressed(Button.B))
|
||||
{
|
||||
total += 5;
|
||||
}
|
||||
else if (pad.x().pressed())
|
||||
else if (Pad.pressed(Button.X))
|
||||
{
|
||||
total -= 10;
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ it does not implement a Java approximation of runtime admission.
|
||||
From the Studio root:
|
||||
|
||||
```sh
|
||||
./gradlew :prometeu-compiler:prometeu-build-pipeline:test --tests '*LinkedRegistryTest' --tests '*PbxRegistryConformanceTest' --tests '*TypedCommonPipelineTest' --tests '*RuntimeCatalogPipelineTest'
|
||||
./gradlew :prometeu-compiler:prometeu-build-pipeline:test --tests '*LinkedRegistryTest' --tests '*PbxRegistryConformanceTest' --tests '*TypedCommonPipelineTest' --tests '*RuntimeCatalogPipelineTest' --tests '*PbsRuntimeAlignmentTest'
|
||||
python3 tools/pbx-conformance/run.py --runtime ../runtime
|
||||
```
|
||||
|
||||
@@ -43,8 +43,9 @@ payload or reports those cases as conforming to the unmodified schema. Any
|
||||
other schema failure remains fatal. Track the runtime correction in AGD75;
|
||||
remove the exception once the schema is corrected.
|
||||
|
||||
This corpus qualifies common backend production, not PBS lowering, lifecycle
|
||||
selection, memcard persistence or installed-runtime deployment.
|
||||
The original registry/catalog fixtures qualify common backend production. The
|
||||
PBS fixtures below additionally qualify source lowering; this harness does not
|
||||
claim installed-runtime deployment or memcard persistence.
|
||||
|
||||
## Runtime catalog consumer fixtures
|
||||
|
||||
@@ -62,3 +63,26 @@ at load time, matching the runtime verifier's stricter rule despite the
|
||||
dispatcher's nullable String carrier. These are distinct outcomes. Run the separate provider-export check with
|
||||
`python3 tools/runtime-catalog/verify.py --runtime ../runtime` to compare the
|
||||
selected source revision, imported CSV bytes and exporter output as well.
|
||||
|
||||
|
||||
## PBS source and input qualification
|
||||
|
||||
`PbsRuntimeAlignmentTest` compiles actual SDK declarations and source programs
|
||||
through the PBS frontend, production common IR, typed Registry and PBX writer.
|
||||
Its 114 fixtures execute on the selected runtime: all 48 Pad combinations with
|
||||
both literal Button arguments and enum locals passed through a typed function,
|
||||
six Touch queries, numeric boundaries/conversions/faults, builtin groups,
|
||||
String, fixed multiple returns and named application with observable Y,X effects.
|
||||
|
||||
The controlled input platform asserts the exact button/coordinate reader and
|
||||
one read per public query. Each query is also executed without a platform to
|
||||
prove TRAP_UNAVAILABLE. The loaded PBS registries are checked for the defaults
|
||||
of all eight existing value types, including null String, positive Float zero
|
||||
and complete vec2/pixel groups. No source constructors or new collection API
|
||||
are introduced to test storage defaults.
|
||||
|
||||
The harness requires the complete fixture count. It must not pass by skipping
|
||||
missing PBS fixtures. Integer arithmetic wrapping is distinct from checked
|
||||
Int64-to-Int32 narrowing and Float numeric-range faults. The full installed
|
||||
knowledge gate remains separate and mandatory for SDK resource/producer
|
||||
integration.
|
||||
|
||||
@@ -37,6 +37,7 @@ impl NativeInterface for NoNative {
|
||||
fn main() {
|
||||
let root = std::path::PathBuf::from(std::env::args().nth(1).expect("fixture directory"));
|
||||
verify_catalog_fixtures(&root);
|
||||
verify_pbs_fixtures(&root);
|
||||
for name in [
|
||||
"minimal",
|
||||
"jump-end",
|
||||
@@ -408,3 +409,131 @@ fn replace(bytes: &[u8], kind: usize, payload: &[u8]) -> Vec<u8> {
|
||||
}
|
||||
output
|
||||
}
|
||||
|
||||
// Controlled provider boundary: every input read checks its identity and is counted.
|
||||
struct PbsInput {
|
||||
expected: usize,
|
||||
reads: std::cell::Cell<usize>,
|
||||
button: prometeu_hal::button::Button,
|
||||
}
|
||||
impl PbsInput {
|
||||
fn read(&self, index: usize) -> &prometeu_hal::button::Button {
|
||||
assert_eq!(index, self.expected, "PBS queried an unselected endpoint");
|
||||
self.reads.set(self.reads.get() + 1);
|
||||
&self.button
|
||||
}
|
||||
}
|
||||
impl prometeu_hal::PadBridge for PbsInput {
|
||||
fn begin_frame(&mut self, _: &prometeu_hal::InputSignals) { unreachable!() }
|
||||
fn any(&self) -> bool { unreachable!() }
|
||||
fn up(&self) -> &prometeu_hal::button::Button { self.read(0) }
|
||||
fn down(&self) -> &prometeu_hal::button::Button { self.read(1) }
|
||||
fn left(&self) -> &prometeu_hal::button::Button { self.read(2) }
|
||||
fn right(&self) -> &prometeu_hal::button::Button { self.read(3) }
|
||||
fn a(&self) -> &prometeu_hal::button::Button { self.read(4) }
|
||||
fn b(&self) -> &prometeu_hal::button::Button { self.read(5) }
|
||||
fn x(&self) -> &prometeu_hal::button::Button { self.read(6) }
|
||||
fn y(&self) -> &prometeu_hal::button::Button { self.read(7) }
|
||||
fn l(&self) -> &prometeu_hal::button::Button { self.read(8) }
|
||||
fn r(&self) -> &prometeu_hal::button::Button { self.read(9) }
|
||||
fn start(&self) -> &prometeu_hal::button::Button { self.read(10) }
|
||||
fn select(&self) -> &prometeu_hal::button::Button { self.read(11) }
|
||||
}
|
||||
impl prometeu_hal::TouchBridge for PbsInput {
|
||||
fn begin_frame(&mut self, _: &prometeu_hal::InputSignals) { unreachable!() }
|
||||
fn f(&self) -> &prometeu_hal::button::Button { self.read(12) }
|
||||
fn x(&self) -> i32 { self.read(13); -123 }
|
||||
fn y(&self) -> i32 { self.read(14); 456 }
|
||||
}
|
||||
impl prometeu_hal::InputPlatform for PbsInput {
|
||||
fn pad(&self) -> &dyn prometeu_hal::PadBridge { self }
|
||||
fn pad_mut(&mut self) -> &mut dyn prometeu_hal::PadBridge { self }
|
||||
fn touch(&self) -> &dyn prometeu_hal::TouchBridge { self }
|
||||
fn touch_mut(&mut self) -> &mut dyn prometeu_hal::TouchBridge { self }
|
||||
}
|
||||
impl prometeu_hal::RuntimePlatform for PbsInput {
|
||||
fn input(&self) -> &dyn prometeu_hal::InputPlatform { self }
|
||||
fn input_mut(&mut self) -> &mut dyn prometeu_hal::InputPlatform { self }
|
||||
fn wall_clock(&self) -> &dyn prometeu_hal::WallClock { unreachable!("non-input platform access") }
|
||||
fn render_submission_sink(&mut self) -> &mut dyn prometeu_hal::RenderSubmissionSink { unreachable!("non-input platform access") }
|
||||
fn render_backend(&mut self) -> &mut dyn prometeu_hal::RenderBackend { unreachable!("non-input platform access") }
|
||||
fn game2d_frame_composer(&mut self) -> &mut dyn prometeu_hal::Game2DFrameComposer { unreachable!("non-input platform access") }
|
||||
fn audio(&self) -> &dyn prometeu_hal::AudioBridge { unreachable!("non-input platform access") }
|
||||
fn audio_mut(&mut self) -> &mut dyn prometeu_hal::AudioBridge { unreachable!("non-input platform access") }
|
||||
fn assets(&self) -> &dyn prometeu_hal::AssetBridge { unreachable!("non-input platform access") }
|
||||
fn assets_mut(&mut self) -> &mut dyn prometeu_hal::AssetBridge { unreachable!("non-input platform access") }
|
||||
fn telemetry(&self) -> &dyn prometeu_hal::TelemetryPlatform { unreachable!("non-input platform access") }
|
||||
}
|
||||
fn verify_pbs_fixtures(root: &std::path::Path) {
|
||||
use prometeu_vm::LogicalFrameEndingReason as End;
|
||||
let buttons = ["up","down","left","right","a","b","x","y","l","r","start","select"];
|
||||
let mut count = 0;
|
||||
let mut defaults_checked = std::collections::BTreeSet::new();
|
||||
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-") || 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)
|
||||
.unwrap_or_else(|e| panic!("{name}: {e:?}"));
|
||||
for (index, ty) in image.registry().declarations().types.iter().enumerate() {
|
||||
if let prometeu_bytecode::registry::TypeKind::Builtin(id) = ty.kind {
|
||||
let expected = match id.0 {
|
||||
1 | 0x11 => vec![Value::Int64(0)],
|
||||
2 => vec![Value::Float(0.0), Value::Float(0.0)],
|
||||
3 => vec![Value::Int64(0), Value::Int64(0), Value::Int64(0)],
|
||||
0x10 => vec![Value::Int32(0)], 0x12 => vec![Value::Float(0.0)],
|
||||
0x13 => vec![Value::Boolean(false)], 0x14 => vec![Value::Null],
|
||||
_ => panic!("unexpected PBS builtin {}", id.0),
|
||||
};
|
||||
assert_eq!(image.registry().type_layout(prometeu_bytecode::registry::TypeId(index as u32)).unwrap().storage.default_values(), expected);
|
||||
defaults_checked.insert(id.0);
|
||||
}
|
||||
}
|
||||
let mut vm = VirtualMachine::from_image(image, Default::default());
|
||||
vm.prepare_boot_call().unwrap();
|
||||
let parts: Vec<_> = name.split('-').collect();
|
||||
if parts[1] == "pad" || parts[1] == "touch" {
|
||||
let query = if parts[1] == "pad" { &parts[3] } else { parts.last().unwrap() };
|
||||
let expected = if parts[1] == "pad" { buttons.iter().position(|b| *b == parts[2]).unwrap() }
|
||||
else { match *query { "x" => 13, "y" => 14, _ => 12 } };
|
||||
let button = prometeu_hal::button::Button { pressed: expected % 2 == 0, released: expected % 3 == 0, down: expected % 5 == 0, hold_frames: 100 + expected as u16 };
|
||||
let value = match *query {
|
||||
"pressed" => Value::Boolean(button.pressed), "released" => Value::Boolean(button.released), "down" => Value::Boolean(button.down),
|
||||
"hold" => Value::Int64(button.hold_frames.into()), "x" => Value::Int64(-123), "y" => Value::Int64(456), _ => unreachable!()
|
||||
};
|
||||
let mut input = PbsInput { expected, reads: std::cell::Cell::new(0), button };
|
||||
let report = vm.run_budget(10000, &mut NoNative, &mut HostContext::new(Some(&mut input))).unwrap();
|
||||
assert!(matches!(report.reason, End::Halted | End::EndOfRom), "{name}: {report:?}");
|
||||
assert_eq!(vm.operand_stack_top(1), vec![value], "{name}");
|
||||
assert_eq!(input.reads.get(), 1, "{name}: exactly one input query");
|
||||
let unavailable_image = ValidatedProgramImage::load(&bytes, &mut LoadBudget::new(LoadLimits::default()), caps::NONE).unwrap();
|
||||
let mut unavailable_vm = VirtualMachine::from_image(unavailable_image, Default::default());
|
||||
unavailable_vm.prepare_boot_call().unwrap();
|
||||
let unavailable = unavailable_vm.run_budget(10000, &mut NoNative, &mut HostContext::new(None)).unwrap();
|
||||
assert!(matches!(unavailable.reason, End::Trap(ref trap) if trap.code == prometeu_bytecode::TRAP_UNAVAILABLE));
|
||||
} else {
|
||||
let report = vm.run_budget(10000, &mut NoNative, &mut HostContext::new(None)).unwrap();
|
||||
match parts[1] {
|
||||
"numeric" => { assert!(matches!(report.reason, End::Halted | End::EndOfRom), "{report:?}"); assert_eq!(vm.operand_stack_top(1), vec![Value::Int64(2147483655)]); }
|
||||
"vec2" => { assert!(matches!(report.reason, End::Halted | End::EndOfRom)); assert_eq!(vm.operand_stack_top(2), vec![Value::Float(0.0),Value::Float(0.0)]); }
|
||||
"tuple" => { assert!(matches!(report.reason, End::Halted | End::EndOfRom)); assert_eq!(vm.operand_stack_top(2), vec![Value::Int64(8),Value::Int32(7)]); }
|
||||
"named" => { assert!(matches!(report.reason, End::Halted | End::EndOfRom)); assert_eq!(vm.operand_stack_top(1), vec![Value::Int32(211020)]); }
|
||||
"color" => { assert!(matches!(report.reason, End::Halted | End::EndOfRom)); assert_eq!(vm.operand_stack_top(1), vec![Value::Int64(0xFF0000FF)]); }
|
||||
"pixel" => { assert!(matches!(report.reason, End::Halted | End::EndOfRom), "{report:?}"); assert_eq!(vm.operand_stack_top(3), vec![Value::Int64(0xFF0000FF),Value::Int64(-34),Value::Int64(12)]); }
|
||||
"string" => { assert!(matches!(report.reason, End::Halted | End::EndOfRom)); assert!(matches!(&vm.operand_stack_top(1)[0], Value::String(value) if value.as_ref() == "hello")); }
|
||||
"division" => assert!(matches!(report.reason, End::Trap(ref trap) if trap.code == prometeu_bytecode::TRAP_DIV_ZERO)),
|
||||
"minimum" => { assert!(matches!(report.reason, End::Halted | End::EndOfRom)); assert_eq!(vm.operand_stack_top(1), vec![Value::Int64(i64::MIN)]); }
|
||||
"float" => { assert!(matches!(report.reason, End::Halted | End::EndOfRom), "{report:?}"); assert_eq!(vm.operand_stack_top(1), vec![Value::Float(3.75)]); }
|
||||
"overflow" => { assert!(matches!(report.reason, End::Halted | End::EndOfRom)); assert_eq!(vm.operand_stack_top(1), vec![Value::Int32(i32::MIN)]); }
|
||||
"narrow" => assert!(matches!(report.reason, End::Trap(ref trap) if trap.code == prometeu_bytecode::TRAP_NUMERIC_RANGE), "{name}: {report:?}"),
|
||||
_ => panic!("unasserted PBS fixture: {name}"),
|
||||
}
|
||||
}
|
||||
println!("PBS SOURCE/LOAD/EXEC PASS {name}");
|
||||
}
|
||||
assert_eq!(defaults_checked, [1,2,3,0x10,0x11,0x12,0x13,0x14].into_iter().collect());
|
||||
println!("PBS Registry defaults PASS: all eight existing value types");
|
||||
assert_eq!(count, 114, "The complete PBS qualification corpus must be present");
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user