feat(pbs): add array-backed Stack and circular Queue

This commit is contained in:
2026-10-27 09:37:10 +00:00
parent 01a1968689
commit 0016d92ac3
34 changed files with 5274 additions and 9 deletions
@@ -0,0 +1,193 @@
---
id: LSN-0095
ticket: pbs-sdk-stack-queue
title: Private array stacks and circular queues
created: 2026-10-27
tags: [compiler-pbs, collections, stack, queue, snapshot-cursor, failure-phases]
---
# Private array stacks and circular queues
**Worker:** Lesson Worker. **Owner domain:** `compiler/pbs`.
DSC-0097 executed accepted DEC-0080 through PLN-0158, covering R1–R9 completely.
The durable normative reference is [SDK Stack and Queue](../../../docs/compiler/pbs/specs/sdk-stack-and-queue.md).
[Qualification evidence](evidence/README.md) retains commands, fingerprints,
counts, raw logs and coverage after disposal of the workflow control artifacts.
## Original problem and delivered result
PBS had typed arrays, generic source structs, mutable collections and a shared
snapshot Cursor, but none automatically defined Stack/Queue's API, growth, resource
policy or removal order. Wrapping List/Linked would inherit different storage and
allocation costs without resolving those product choices.
The delivered `stack<T>` owns a dense private array and consumes LIFO. `queue<T>`
owns a circular private array and consumes FIFO. Both reuse checked arithmetic,
ordinary typed storage/copy and the exact shared Cursor implementation. Queue
dequeue does not shift the remaining values; insertion does not allocate a collection
node. No runtime change, new ISA, public node or universal Element was required.
## Separate physical capacity from occupied positions
Both collections start empty, with capacity 16 by default or the exact explicit
capacity, including zero. Int capacities promote locally without granting implicit
conversion to element arguments. Contextual/diamond construction still requires
an expected concrete generic type. Aliases/reexports retain original SDK authority.
```pbs
fn example() -> int {
let history = new stack<int>(0);
let pending: queue<int> = new queue<>(2);
history.push(20);
history.push(22);
pending.enqueue(20);
pending.enqueue(22);
// Stack first returns 22; Queue first returns 20.
return (history.pop() else 0) + (pending.dequeue() else 0);
}
```
Explicit capacity is not a maximum size. Growth reuses the checked formula
`min(u32max, max(required, capacity + max(1, ceil(capacity/2))))`, validating the
required size before clamping. From zero the capacities are 1,2,3,5,8,... .
Physical limits and ordinary quotas remain distinct; negative/above-u32 requests
terminate through the trusted SDK check, while actual storage instructions retain
their own failures. Pop/dequeue/clear retain capacity and never expose an indexer.
Stack occupies `[0,size)`. Queue's logical position i is start+i, wrapped into its
backing. Empty Queue normalizes start to zero. Zero-capacity operations do not
perform circular access; the first insertion grows before selecting a destination.
At maximum u32 capacity, start+offset still fits long without narrowing.
## Wrapped growth copies two complete regions
A capacity-four Queue can have physical slots `[4,5,2,3]`, start=2 and logical
contents `[2,3,4,5]`. Enqueueing 6 prepares capacity six with `[2,3,4,5,6,empty]`:
copy the occupied suffix, then the wrapped prefix, then insert privately. Only
afterward install backing, start=0 and size=5 in sequence. Old/candidate arrays
coexist under ordinary quotas; preparation never edits the old array.
Stack similarly prepares its copied dense prefix and new top before installing
the backing. In-capacity push/enqueue write only their inactive destination and
then count. There is no whole-backing reconstruction on ordinary operations.
Complete tuple/native/contract/function/reference groups retain their ownership
and identity; packing costs are still ordinary runtime costs.
## Dense storage still needs an optional result
Pop/dequeue/peek return optional T: none means empty, while zero/false are present.
Type/resource failures never become absence. T directly optional is rejected,
including grouping, consistently with Array/List/Linked. Struct payloads containing
optional fields remain valid, as does an optional collection itself. This avoids
an extra private cell per item merely to circumvent Array's type restriction.
Object insertion preserves shared instance identity and occurrences; snapshots
do not freeze objects. The same object inserted twice remains two positions, and
later object field mutation is visible through aliases. Capacity growth replaces
private storage without replacing the public collection identity.
## Prepare returns before clearing, then document actual writes
Pop prepares its optional return, clears the old top and updates size. Dequeue
prepares return and next start/count, clears the front, assigns start (zero if
empty), then size. Clear visits occupied slots in Stack index/Queue FIFO order
before resetting metadata. Inactive storage must be empty after every success.
An empty removal and all reads/capture perform no collection writes.
This preparation is not a transaction. Before the first write, refusal preserves
the prior collection. After it, earlier stores may remain and invariants can be
incomplete; there is no rollback, safe reuse or recovery promise. Budget/debugger
pauses remain resumable instruction boundaries. Optional carriers, including typed
absence, can allocate and must be prepared before destructive writes.
The actual corpus observes 18 Stack and 12 Queue natural refusals after writes
in each profile, all in clear, by comparing complete original-object states at
each instruction with the successful execution prefix. It therefore does not
mistake partial clear for whole-method rollback. Separate test-only growth probes
demonstrate capacity=3 with appended 42 and old size=2 after a later allocation
fault. Those probes do not ship or describe natural refusal frequency.
## Share traversal protocol, choose each collection's order
Stack captures top → base; Queue captures front → back. For inserted 20,22 the
snapshots are 22,20 and 20,22. Both finish capture before returning and use one
immutable private singly linked non-circular node per occurrence, with no snapshot
array or association to editable source slots. Later growth/removal/clear does
not alter the captured sequence. Capture costs O(n) work and additional nodes.
The existing Cursor state table is unchanged:
| State | current() | hasNext() | next() |
| --- | --- | --- | --- |
| Born empty | none | false | No change |
| Current has successor | some(current value) | true | Follow successor |
| Last, including singleton | some(final value) | false | No change |
Consume current before checking whether to advance. A hasNext-only loop skips
the final item; waiting for current to become absent does not finish a nonempty
snapshot. Prefix nodes can become unreachable, but final current remains retained.
Real provider collections observe 1,200 → 1 → 1 → 0 snapshot nodes/payloads,
with no retained source backing. Removal/clear/reuse fixtures observe
64 → 61 → 0 → 1 → 0 payloads and one live backing until final owner release.
These tests assert advancing GC collection counters, not merely safepoint entry.
Clear retains capacity but not discarded values, and replaced growth arrays
disappear after actual collection. No immediate reclamation is promised.
## Compiler integration stays smaller than the source algorithms
Trusted `SdkStack`/`SdkQueue` metadata selects constructor naming, optional-element
diagnostics and localized capacity conversion. Capacity-constructor handling is
separate from positional indexer eligibility: adding a capacity constructor must
not grant brackets or int-to-long payload conversion. Project homonyms remain
ordinary generic structs, and project code cannot forge the reserved attributes.
The editor exposes the concrete eight-method API, both constructor overloads and
original SDK definition locations, hiding storage/start/length. The English spec
and [executable example](../../../prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/pbs-knowledge/examples/game/1/src/stack-queue.pbs)
ship in installed knowledge. An isolated JVM compiles that actual installed-JAR
example outside the checkout; production VM execution independently observes both
completed snapshots retaining final values 20 and 22. An alias/reexport workspace
fixture proves the same source/SDK authority through module boundaries.
## Qualification and maintenance limits
| Gate | Result |
| --- | --- |
| Standard JUnit reports | 1,091 cases; zero failures/errors; 13 existing skips |
| Installed knowledge | Two passing isolated-JAR tests |
| Mandatory new PBX files | 106, all required in each runtime profile |
| Behavior/expected-fault executions per profile | 58, including both producers |
| Natural quota refusals per profile | 364 total; 30 after visible writes |
| Separate post-write growth probes per profile | Four |
| GC observations per profile | 36, both collections/producers |
| Import/installed source executions per profile | Two |
| Complete production harness | Passed in debug and release |
The selected runtime remains clean at
`dcf6561ea73446e0a3e1cf1c73eda20923b38df0`; no runtime write or commit occurred.
Qualification is local macOS/arm64, not a benchmark, cross-host qualification or
installed game readiness claim. Existing disabled JUnit cases and upstream
LifecycleRole/NonFiniteValue schema gaps remain explicit in the retained evidence.
Avoid these maintenance mistakes:
- Do not equate capacity with count, or use a capacity-zero remainder/access.
- Do not shift a Queue on every dequeue or wrap these collections over List/Linked.
- Do not skip clearing inactive references because later insertion overwrites them.
- Do not flatten optional absence into zero/false or hide storage faults as none.
- Do not confuse a prepared return/candidate with whole-method atomicity.
- Do not grant an indexer while adding capacity-constructor recognition.
- Do not replace the accepted snapshot table with a conventional live iterator.
- Do not count test probes as natural failures or safepoints as actual collections.
## Durable references
- [Stack/Queue spec](../../../docs/compiler/pbs/specs/sdk-stack-and-queue.md) and
[shared Cursor](../../../docs/compiler/pbs/specs/sdk-list-and-cursor.md).
- [SDK algorithms](../../../prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/sdk/collections/main.pbs).
- [Source/PBX corpus](../../../prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsStackQueueTest.java).
- [Conformance module](../../../tools/pbx-conformance/stack_queue.rs) and
[reproduction instructions](../../../tools/pbx-conformance/README.md).
- [Sequential mutation lessons](../DSC-0096-runtime-storage-isa-consumer-migration/LSN-0092-sequential-collection-mutations-need-explicit-failure-boundaries.md).
- [Evidence and R1–R9 coverage](evidence/README.md).
@@ -0,0 +1,106 @@
# Stack/Queue implementation and qualification evidence
Owner: `compiler/pbs`. Accepted DEC-0080 / completed PLN-0158 in DSC-0097, R1–R9.
Captured 2026-10-27 over Studio baseline `01a19686`. The provider remained clean at
`dcf6561ea73446e0a3e1cf1c73eda20923b38df0`; no runtime write or commit occurred.
## Reproduction and outcome
From the Studio root:
```sh
./gradlew test :prometeu-app:installedKnowledgeTest --console=plain
CARGO_TARGET_DIR=/tmp/studio-pbx-map-target python3 tools/pbx-conformance/run.py --runtime ../runtime
CARGO_TARGET_DIR=/tmp/studio-pbx-map-target python3 tools/pbx-conformance/run.py --runtime ../runtime --release
git diff --check
discussion validate
```
All returned zero. Temporary Cargo projects/targets stay outside the read-only
runtime checkout. Focused development runs used `--stack-queue-only`; retained
final VM evidence is from the two complete harness runs, including all existing
Registry, storage/copy, language and collection corpora.
Aggregated standard JUnit reports have 1,091 cases, zero failures/errors and 13
existing skips; 1,078 executed. The separate installed-knowledge task adds two
passing cases, compiling actual JAR resources in an isolated outside-checkout JVM.
The final Gradle run completed in 32 seconds with 15 executed and 79 up-to-date
tasks; unchanged suites retained valid passing results. See exact suites/skips in
[gradle-results.json](gradle-results.json). Existing skips remain BackendGateIIntegrationTest
(8), MainProjectPipelineIntegrationTest (4), ExternalSourceDevelopmentHostTest (1).
There are 106 mandatory new PBX files: 58 paired behavior/expected-fault cases,
34 paired operation-resource fixtures, four separate test-only injection files,
eight paired GC files and two import/installed examples. Each runtime profile
requires them all. The complete fixture directory contains 1,495 fingerprinted
PBX files; directory size is not itself a count of executed cases.
Each final profile observes 184 Stack + 180 Queue natural quota refusals, including
18 + 12 after visible writes (all during clear), four separate growth probes,
36 real GC observations and both distribution examples. Both ordinary and optimized
producer paths are mandatory in each profile. Missing fixtures fail qualification.
## Resources, phases and GC
[stack-queue-results.json](stack-queue-results.json) records all 34 operation/producer
peak vectors and refusal summaries per profile, natural counts, separate probes,
GC rounds and distribution results. Peak vector order is GuestBytes, HandleSlots,
AuxiliaryBytes, TemporaryBytes, StringBytes, StringAllocations, IndividualStringBytes,
CallDepth. These are whole-session/fixture peaks including setup and calls, not
standalone collection object sizes. Limits are lowered only where setup-to-operation
peaks increase, retaining the measured no-increase domains in the raw vectors.
Non-owning observations compare complete original collection/backing objects at
each instruction to the successful prefix. Before mutation, prior state survives;
afterward, earlier successful stores remain and no rollback is asserted. Clear
naturally demonstrates partial updates. Result preparation, typed empty returns,
copy/backing construction and snapshot-node refusals remain charged. Growing paths
observe at least two coexisting arrays; ordinary updates/capture retain one backing
and never reconstruct the whole collection.
The separate test-only growth probes fail after installing capacity three with
the new slot=42 and old size=2. The refused probe instruction preserves its own
entry storage/operands, retaining the earlier publication. These probes are only
in fixture-local SDK copies, never in production source, and are not counted as
natural refusal frequency.
Snapshot GC observes 1,200 → 1 → 1 → 0 nodes and Items, with no retained source
array. Collection GC observes 64 → 61 → 0 → 1 → 0 Items, one retained current/empty
backing through the first four rounds and zero afterward. Old growth backings are
not retained. Every observation asserts that the actual collection counter advanced.
Both producers and both runtime profiles pass. Final VM owner drop also releases
GuestBytes/HandleSlots/AuxiliaryBytes/TemporaryBytes/StringBytes/StringAllocations.
## Requirement coverage
| Requirement | Final evidence |
| --- | --- |
| R1 Types, identity, origin, construction | Frontend context/invariance/optional/privacy/homonym gates, SDK workspace gate, basic/capacity/references/snapshot/evaluation and alias imports |
| R2 Complete API and absence | basic/capacity, empty/single/multiple Cursor states, zero/false, evaluation, negative indexer/unsupported API cases |
| R3 Growth and bounds | exact 0→1→2→3→5→8, default/explicit capacities, arithmetic helper checks and negative/above-u32/required-size faults |
| R4 Dense/circular groups | wrap and wrapped-growth source cases, resource validation of every active/inactive slot and start/count/backing, tuple/native/reference execution |
| R5 Failure phases | 34 marked paired fixtures, successful-prefix comparisons, 364 natural refusals including 30 after writes, four separate post-write probes |
| R6 Lifetime and coexistence | array peak counts, no reconstruction on ordinary updates, actual removal/clear/reuse/old-backing GC, complete owner release |
| R7 Shared Cursor | both capture orders, sticky final/empty states, duplicates/shared mutation, mutation independence, both snapshot GC paths |
| R8 Frontend/editor/distribution | concrete public eight-method APIs/constructors/definitions, hidden fields, trusted aliases/reexports, isolated JAR compile and actual PBX execution |
| R9 Complete qualification | full regression, complete production debug/release corpora with both producers, reproducible fingerprints/raw logs and limits |
## Integrity and limits
- `source.sha256`: every changed/new code/spec/test surface, excluding discussion prose/evidence.
- `fixtures.sha256.gz`: all actual generated PBX fingerprints, including installed examples.
- `environment.json`: baseline/provider, host/tool versions, commands, mandatory fixture names,
uncompressed log digests and counts.
- `conformance-debug.log.gz`, `conformance-release.log.gz`, `regression.log.gz`:
lossless raw final outputs, compressed deterministically.
- `workflow.txt`: completion, CLI validation and housekeeping results.
- `SHA256SUMS`: integrity hashes of this evidence directory.
The standard existing skips and upstream headless-schema LifecycleRole/NonFiniteValue
gaps remain explicit. Original provider payloads remain in complete logs; those
cases are not called conformance to the unchanged schema. Qualification is local
macOS/arm64 without benchmark, cross-host or installed-game-readiness claims.
The CLI has no standalone lesson-ID query/creation. LSN-0095 was obtained through
the framework's read-only `DiscussionIndex.next_id` accessor; CLI housekeeping owns
lesson registration, counter advancement, index changes and workflow deletions.
@@ -0,0 +1,10 @@
1db55d241bb0f3088afefccf7596bf7a9014bc0dae54b80d54e15a3a47a91135 README.md
4e16e23cfc9d75228649d632f590183523fb6a854ac0f2d940eaffe021b6a70d conformance-debug.log.gz
c74d26c969512b48895178a7bdbc542c15c736b5f2a41b7b864bafb58dadc837 conformance-release.log.gz
c6d5b81a62d8e9a274615f2ca0aaf0b0f4a7159e57be8911f8f9926a507a5811 environment.json
31a231667d6dab2d50eac1814d12b9fe24deea737fd0933146a78ae3458138df fixtures.sha256.gz
0bc694f54f81807ed1d856d10e370eb652ca833ba9fc1f8a229feb8bdaee4f8c gradle-results.json
23844d7c633f5d92e3b0a0998582272383eeb1a293571553809b274303806d01 regression.log.gz
7f405c7a5cd9d47c6b46fe903e019fe4dfe8e189f9596b8133e9510ceb14a784 source.sha256
64272efe4bf46ab787455c5a82a20e5857f8ca72e39a2bdcfcde191221b0e63f stack-queue-results.json
2a42448fbc6324cc52b1840e6f337d92843a6d9209854307096916dbf8d3d6bb workflow.txt
@@ -0,0 +1,129 @@
{
"captured": "2026-10-27T08:57:39.430825+00:00",
"owner": "compiler/pbs",
"decision": "DEC-0080",
"plan": "PLN-0158",
"studio_baseline_head": "01a196868929fb87a4e3b326481e8818f77c597e",
"runtime_head": "dcf6561ea73446e0a3e1cf1c73eda20923b38df0",
"runtime_working_tree": "",
"host": "macOS-27.0.1-arm64-arm-64bit-Mach-O",
"rust": "rustc 1.98.1 (48a229cea 2026-09-01)\nbinary: rustc\ncommit-hash: 48a229ceaefd4985c50990b14116b6d856af0985\ncommit-date: 2026-09-01\nhost: aarch64-apple-darwin\nrelease: 1.98.1\nLLVM version: 22.1.8",
"stack_queue_fixture_count": 106,
"all_fixture_count": 1495,
"fixture_names": [
"pbs-queue-arithmetic-optimized.pbx",
"pbs-queue-arithmetic.pbx",
"pbs-queue-basic-optimized.pbx",
"pbs-queue-basic.pbx",
"pbs-queue-capacity-optimized.pbx",
"pbs-queue-capacity.pbx",
"pbs-queue-cursor-empty-optimized.pbx",
"pbs-queue-cursor-empty.pbx",
"pbs-queue-cursor-order-optimized.pbx",
"pbs-queue-cursor-order.pbx",
"pbs-queue-cursor-single-optimized.pbx",
"pbs-queue-cursor-single.pbx",
"pbs-queue-evaluation-optimized.pbx",
"pbs-queue-evaluation.pbx",
"pbs-queue-fault-negative-optimized.pbx",
"pbs-queue-fault-negative.pbx",
"pbs-queue-fault-required-optimized.pbx",
"pbs-queue-fault-required.pbx",
"pbs-queue-fault-too-large-optimized.pbx",
"pbs-queue-fault-too-large.pbx",
"pbs-queue-gc-collection-optimized.pbx",
"pbs-queue-gc-collection.pbx",
"pbs-queue-gc-snapshot-optimized.pbx",
"pbs-queue-gc-snapshot.pbx",
"pbs-queue-groups-optimized.pbx",
"pbs-queue-groups.pbx",
"pbs-queue-injected-growth-optimized.pbx",
"pbs-queue-injected-growth.pbx",
"pbs-queue-native-optimized.pbx",
"pbs-queue-native.pbx",
"pbs-queue-references-optimized.pbx",
"pbs-queue-references.pbx",
"pbs-queue-refusal-clear-optimized.pbx",
"pbs-queue-refusal-clear.pbx",
"pbs-queue-refusal-cursor-optimized.pbx",
"pbs-queue-refusal-cursor.pbx",
"pbs-queue-refusal-empty-optimized.pbx",
"pbs-queue-refusal-empty.pbx",
"pbs-queue-refusal-growth-optimized.pbx",
"pbs-queue-refusal-growth.pbx",
"pbs-queue-refusal-insert-optimized.pbx",
"pbs-queue-refusal-insert.pbx",
"pbs-queue-refusal-peek-optimized.pbx",
"pbs-queue-refusal-peek.pbx",
"pbs-queue-refusal-remove-optimized.pbx",
"pbs-queue-refusal-remove.pbx",
"pbs-queue-refusal-wrapped-optimized.pbx",
"pbs-queue-refusal-wrapped.pbx",
"pbs-queue-refusal-zero-optimized.pbx",
"pbs-queue-refusal-zero.pbx",
"pbs-queue-snapshot-optimized.pbx",
"pbs-queue-snapshot.pbx",
"pbs-queue-wrap-optimized.pbx",
"pbs-queue-wrap.pbx",
"pbs-stack-arithmetic-optimized.pbx",
"pbs-stack-arithmetic.pbx",
"pbs-stack-basic-optimized.pbx",
"pbs-stack-basic.pbx",
"pbs-stack-capacity-optimized.pbx",
"pbs-stack-capacity.pbx",
"pbs-stack-cursor-empty-optimized.pbx",
"pbs-stack-cursor-empty.pbx",
"pbs-stack-cursor-order-optimized.pbx",
"pbs-stack-cursor-order.pbx",
"pbs-stack-cursor-single-optimized.pbx",
"pbs-stack-cursor-single.pbx",
"pbs-stack-evaluation-optimized.pbx",
"pbs-stack-evaluation.pbx",
"pbs-stack-fault-negative-optimized.pbx",
"pbs-stack-fault-negative.pbx",
"pbs-stack-fault-required-optimized.pbx",
"pbs-stack-fault-required.pbx",
"pbs-stack-fault-too-large-optimized.pbx",
"pbs-stack-fault-too-large.pbx",
"pbs-stack-gc-collection-optimized.pbx",
"pbs-stack-gc-collection.pbx",
"pbs-stack-gc-snapshot-optimized.pbx",
"pbs-stack-gc-snapshot.pbx",
"pbs-stack-groups-optimized.pbx",
"pbs-stack-groups.pbx",
"pbs-stack-injected-growth-optimized.pbx",
"pbs-stack-injected-growth.pbx",
"pbs-stack-native-optimized.pbx",
"pbs-stack-native.pbx",
"pbs-stack-queue-imports.pbx",
"pbs-stack-queue-installed.pbx",
"pbs-stack-references-optimized.pbx",
"pbs-stack-references.pbx",
"pbs-stack-refusal-clear-optimized.pbx",
"pbs-stack-refusal-clear.pbx",
"pbs-stack-refusal-cursor-optimized.pbx",
"pbs-stack-refusal-cursor.pbx",
"pbs-stack-refusal-empty-optimized.pbx",
"pbs-stack-refusal-empty.pbx",
"pbs-stack-refusal-growth-optimized.pbx",
"pbs-stack-refusal-growth.pbx",
"pbs-stack-refusal-insert-optimized.pbx",
"pbs-stack-refusal-insert.pbx",
"pbs-stack-refusal-peek-optimized.pbx",
"pbs-stack-refusal-peek.pbx",
"pbs-stack-refusal-remove-optimized.pbx",
"pbs-stack-refusal-remove.pbx",
"pbs-stack-refusal-zero-optimized.pbx",
"pbs-stack-refusal-zero.pbx",
"pbs-stack-snapshot-optimized.pbx",
"pbs-stack-snapshot.pbx"
],
"commands": [
"./gradlew test :prometeu-app:installedKnowledgeTest --console=plain",
"CARGO_TARGET_DIR=/tmp/studio-pbx-map-target python3 tools/pbx-conformance/run.py --runtime ../runtime",
"CARGO_TARGET_DIR=/tmp/studio-pbx-map-target python3 tools/pbx-conformance/run.py --runtime ../runtime --release",
"git diff --check",
"discussion validate"
],
"regression_log_sha256": "8d7faf3e6164d929353fb6cfbba25d5abdbe5f12cc1e759cb41522b80ec9d1a1"
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,22 @@
7f46e87702529c8ea94660a644580c0c884bb27a965a2612d32a92bc31ff9b52 docs/compiler/pbs/specs/sdk-list-and-cursor.md
a47f6fc58068a333119e73201a1a04b5ba96c916ccf6c22a4a13161ee92e7629 docs/compiler/pbs/specs/sdk-stack-and-queue.md
d9e307588aa286a90a7b8906d50569d432ffa675c99d308e4f281833a8758524 prometeu-app/src/test/java/p/studio/app/compiler/CompilerProjectKnowledgeTest.java
cf4615c65aed22ccbfbb860c070b03dad1910c8dc48adc4fc03dca4d50ba91e7 prometeu-app/src/test/java/p/studio/app/compiler/InstalledKnowledgeProbe.java
e206ff3b35b3a0f1fd18946b0522ff7d36c94156121a31a9e3e45a897e4e2c39 prometeu-app/src/test/java/p/studio/app/compiler/InstalledKnowledgeTest.java
85d8f687a903862b4e7d5a5b8711cc9af720ec7f4d282bba77ddfaee93dff0a8 prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsListCursorTest.java
680402a55fe6b1d3cd41a44caa5ecdda58dbefc0854d3f3df0c25b522c435373 prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsStackQueueTest.java
d4bdf6179293b12af929369fd332a5e42143d042db64b2a248621a59a5d93a46 prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/PbsGenericInstantiation.java
e4480f091cbd9d8ea92750f31cacc667d0b288ce82b810e0ba0d952abfe8d4f4 prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/PbsSdkCollections.java
3cb79ef5f9a97dbfc48ec717de4b9f9f5624e50ce52833595851714908f78ae6 prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/lowering/PbsExecutableBodyLowerer.java
6d181bf1a77ef50d6e2f89962f04e1a04d56e56d44493a5af97c897a323bb33f prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/parser/PbsDeclarationParser.java
ac41b92f699aba21fc885b00e6ae59d313f24e084d5436655b493257430364db prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/sdk/collections/main.pbs
6567377cbb58c2e2332556fa759667e63923b7e1cfb44fe65e440c6db309d15c prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/sdk/collections/mod.barrel
a00ed6bfa995119b339443a5fc36f420c6793d1ed2f06b1fa5fca9b3b536362b prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/pbs-knowledge/examples/game/1/src/mod.barrel
053b62206cb45a5c5736ef43b58c869031bd0524a06b29be1353bba25826abe2 prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/pbs-knowledge/examples/game/1/src/stack-queue.pbs
a9fdd1f53a9be0db51fdf141513c845aef39ee603c58717a177b098dcec9d986 prometeu-compiler/frontends/prometeu-frontend-pbs/src/test/java/p/studio/compiler/pbs/PbsGateUSdkInterfaceConformanceTest.java
4007df0d9e100df34d26fe4bee3e758fe7b5d75130d46d4428d9d0f5ae81cb30 prometeu-compiler/frontends/prometeu-frontend-pbs/src/test/java/p/studio/compiler/pbs/PbsStackQueueTest.java
f25b614021eb6918e845d3e4b5076fc0a4dccc9b89a2c281cbb59cd0b4bb0385 prometeu-compiler/frontends/prometeu-frontend-pbs/src/test/java/p/studio/compiler/pbs/semantics/PbsStackQueueEditorialTest.java
d7de3d9d235678b39cdfc8d626558e026d35352aa78f98e78bda8b13507fa8e3 tools/pbx-conformance/README.md
eef34cb97cd82e162e4be6f1c0caccd0058fc44721cd9dca6cf1b9fb6c2afd09 tools/pbx-conformance/main.rs
b9a8b4d1b31d327a1e42ec1d58bb38795a68b77a298f4d77ab34cb75f8658be1 tools/pbx-conformance/run.py
b36c3c8117722328dc136676542fbee675de5a4428aa74af6fc383df48f32326 tools/pbx-conformance/stack_queue.rs
@@ -0,0 +1,32 @@
LSN-0095 allocated via read-only DiscussionIndex.next_id; all state mutations use CLI.
discussion validate
validation passed
exit=0
discussion mark-plan PLN-0158 done --json
{
"discussion_id": "DSC-0097",
"plan_id": "PLN-0158",
"status": "done"
}
exit=0
discussion housekeep DSC-0097 --lesson discussion/lessons/DSC-0097-pbs-sdk-stack-queue/LSN-0095-private-array-stacks-and-circular-queues.md
housekept DSC-0097
removed workflow artifacts: 3
registered lesson: LSN-0095
exit=0
discussion validate
validation passed
exit=0
discussion inspect DSC-0097
DSC-0097 done pbs-sdk-stack-queue
PBS SDK Stack and Queue
tags: compiler-pbs, collections, umbrella-agd-0089
lessons:
- LSN-0095 done exists /Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/studio/discussion/lessons/DSC-0097-pbs-sdk-stack-queue/LSN-0095-private-array-stacks-and-circular-queues.md
exit=0
@@ -176,6 +176,7 @@ faults. List itself rejects directly optional elements.
## Reuse, costs and conformance
The shared implementation is independent of List representation.
[Stack/Queue](sdk-stack-and-queue.md) capture in their LIFO/FIFO removal orders.
[Linked](sdk-linked-and-cursor.md) uses Cursor<T> for forward and reverse captures.
[Set](sdk-set-and-identity.md) produces Cursor<T>; Map<K,V> uses
Cursor<keyval<K,V>> as specified by [Map/Keyval](sdk-map-and-keyval.md).
@@ -0,0 +1,135 @@
# SDK Stack and Queue
Owner: `compiler/pbs`. Algorithms execute as PBS SDK source over existing typed
storage, complete-group copies, terminal checks and shared snapshot Cursor.
This contract builds on [Array/optional](typed-arrays-and-optional-execution.md),
[generic structs](generic-structs-and-free-functions.md) and
[List/shared Cursor](sdk-list-and-cursor.md#cursor-protocol).
## Types, identity and construction
`@sdk:collections` exports ordinary invariant nominal structs `stack<T>` and
`queue<T>`. Directly optional T, including grouping, is invalid; optional of the
collection and valid payloads containing optional fields remain valid. Tuple,
native, contract, function and reference groups retain their complete types and
owners. No extra cell per element circumvents Array's optional restriction.
Project homonyms/copied metadata acquire no SDK authority. Imports, aliases,
reexports and specializations preserve original SDK identity and privacy.
`new stack<T>()` / `new queue<T>()` create size zero and capacity 16. Their
one-argument constructors create size zero and exactly that capacity, including
zero. Diamond/omitted type arguments require an expected concrete application;
values do not infer T. Capacity accepts int/long with localized lossless promotion,
without general conversion/truncation. Negative/above-u32 capacity is rejected.
Collection references have stable identity through backing replacement. Assignment
and parameter passing share mutations. Payload objects remain shared instances;
duplicates and repeated aliases are separate occurrences, without deep copies or
structural equality. Storage, start, length and private helpers are inaccessible.
## Public API
| Collection | Operation | Result and behavior |
| --- | --- | --- |
| Both | size() | long count of present occurrences |
| Both | capacity() | long physical backing length |
| Both | isEmpty() | bool, size equals zero |
| Both | peek() | optional T, next removal value; none when empty |
| Both | clear() | unit, discard contents and preserve capacity |
| Both | cursor() | Cursor<T>, complete removal-order snapshot |
| Stack | push(value: T) | unit, append at top |
| Stack | pop() | optional T, remove top; none when empty |
| Queue | enqueue(value: T) | unit, append at back |
| Queue | dequeue() | optional T, remove front; none when empty |
Stack consumes LIFO, Queue FIFO. Receiver/arguments evaluate once in source order,
including named calls. Zero/false are present. Faults remain faults, never absence.
No indexer, holes, reserve/trim/resize, bounded/bulk variant, public nodes or
mutation/reset through Cursor exists.
## Capacity and private storage
`0 <= size <= capacity <= 4294967295`. Initial capacity does not cap collection size.
When required r exceeds c, automatic growth chooses
`min(4294967295, max(r, c + max(1, ceil(c/2))))`, after checking r itself fits.
Arithmetic uses checked long values without narrowing; zero grows to one.
Invalid logical requests terminate through the private SDK TRAP_EXPLICIT binding
with source attribution. Actual Array instructions retain their physical faults.
Ordinary quotas can refuse earlier. Removal/clear never shrink capacity.
Stack owns a dense array occupying exactly `[0,size)`, with top at size-1.
Queue owns a circular array occupying size logical positions from start. Empty
Queue has start zero; otherwise capacity is positive and start is below capacity.
Circular addressing avoids zero-capacity access/remainder. Every inactive slot is
empty after successful operations. Neither collection is a List/Linked adapter;
inclusion creates no collection node and dequeue never shifts remaining values.
Stack growth privately copies its dense prefix and inserts the value. Queue
growth privately copies occupied suffix and wrapped prefix directly into `[0,size)`,
then inserts at size; it installs backing, start=0 and size in that sequence.
Old storage is not edited during candidate preparation. Complete groups and payload
identities survive copies, including native owners. In-capacity insertion does not
rebuild the whole backing. End operations without growth cost O(1) apart from normal
value/carrier work; growth and clear cost O(n), plus physical capacity allocation.
## Mutation phases and lifetime
Prepare checks, next count, payloads, optional returns (including typed absence)
and candidates before visible mutation. Source-selected write sequences are:
| Operation | Writes after preparation |
| --- | --- |
| In-capacity push/enqueue | Inactive destination slot, then size |
| Growing push | Prepared backing, then size |
| Growing enqueue | Prepared backing, start=0, then size |
| Nonempty pop | Clear old top, then size |
| Nonempty dequeue | Clear front, next start (zero when empty), then size |
| Stack clear | Clear occupied slots in index order, then size=0 |
| Queue clear | Clear occupied slots in FIFO order, then start=0, then size=0 |
Reads, capture and empty removals do not write the collection. Before the first
visible write, rejection/preparation refusal preserves old backing, slots, start
and size; argument effects/provisional allocations are not undone. Success restores
all invariants. Later internal/resource faults may retain writes and incomplete
invariants, without rollback, safe reuse, retry or recovery. Per-instruction refusal
preserves its own entry state, not earlier instructions. No callback/explicit
suspension occurs between update stores. Budget/debugger pauses remain resumable
instruction boundaries; a method is not an atomic host observation region.
Removal clears the discarded slot; clear removes all occupied references while
retaining empty backing. Later reuse cannot resurrect old payloads. Old/candidate
arrays, multi-slot packing, optional carriers, copy scratch and snapshots coexist
under unchanged quotas/GC. No allocation-free insertion/result, immediate collection
or immediate quota return is promised.
## Removal-order snapshot Cursor
Stack captures top → base, Queue front → back. Inserting 20,22 yields Stack
snapshot 22,20 and Queue snapshot 20,22. Capture completes before returning and
owns one immutable private singly linked non-circular node per occurrence, with
no snapshot array/source-slot association. It costs O(n) work/additional nodes;
refusal returns no partial Cursor and leaves the source unchanged.
Reuse the entire shared table: a nonempty Cursor starts on first; hasNext tests
successor; next without successor does nothing; only empty-born current is none.
Consume current before deciding whether to advance. Captured sequence/order is
independent of later insertion/removal/growth/clear; referenced objects still share
later field changes. Consumed prefixes can become collectible, while final current
node/value remain retained until the Cursor releases them.
## Conformance and distribution
Qualify real PBS through common IR/PBX and production loader/VM, using ordinary
and optimized producers and runtime debug/release profiles. Cover complete APIs,
context/types/origin/privacy, exact capacities/growth/maximum checks, zero/false,
complete groups and ownership, order/duplicates/aliases, source/named evaluation,
wrap-around/wrapped growth, fill/drain/reuse, snapshots and sharing.
Measure coexisting arrays/carriers, quota preparation/write boundaries with
independent original-object observations and successful-prefix comparisons. Keep
explicit test-only post-write probes separate from natural refusal frequencies.
Observe actual GC collections for discarded values/replaced backings and snapshot
prefix/final release. Ship this spec and executable example in installed knowledge,
compile real installed-JAR examples outside the checkout and execute emitted PBX.
Regress shared storage/generic/Cursor behavior; retain provenance and limitations.
Runtime storage, ISA, quotas, faults and GC remain unchanged provider contracts.
@@ -53,6 +53,8 @@ class CompilerProjectKnowledgeTest {
assertTrue(result.references().stream().anyMatch(value -> value.id().equals("pbs:example:game:1:src/linked.pbs")));
assertTrue(result.references().stream().anyMatch(value -> value.id().equals("pbs:spec:sdk-map-and-keyval.md")));
assertTrue(result.references().stream().anyMatch(value -> value.id().equals("pbs:example:game:1:src/maps.pbs")));
assertTrue(result.references().stream().anyMatch(value -> value.id().equals("pbs:spec:sdk-stack-and-queue.md")));
assertTrue(result.references().stream().anyMatch(value -> value.id().equals("pbs:example:game:1:src/stack-queue.pbs")));
assertTrue(language.referenceIds().contains("pbs:quickstart"));
assertFalse(result.limitations().stream().anyMatch(value -> value.contains("DOCUMENTATION_UNAVAILABLE")));
assertFalse(Files.exists(root.resolve(".workspace")));
@@ -35,6 +35,8 @@ public final class InstalledKnowledgeProbe {
check(docs.stream().anyMatch(r -> r.id().equals("pbs:example:game:1:src/sets.pbs")), "Missing installed Set example");
check(docs.stream().anyMatch(r -> r.id().equals("pbs:spec:sdk-map-and-keyval.md")), "Missing installed Map/Keyval specification");
check(docs.stream().anyMatch(r -> r.id().equals("pbs:example:game:1:src/maps.pbs")), "Missing installed Map/Keyval example");
check(docs.stream().anyMatch(r -> r.id().equals("pbs:spec:sdk-stack-and-queue.md")), "Missing installed Stack/Queue specification");
check(docs.stream().anyMatch(r -> r.id().equals("pbs:example:game:1:src/stack-queue.pbs")), "Missing installed Stack/Queue example");
check(docs.stream().anyMatch(r -> r.id().equals("pbs:example:game:1:src/hashing.pbs")), "Missing installed hashing example");
check(docs.stream().anyMatch(r -> r.id().equals("pbs:sdk:game:1:sdk/hash/main.pbs")), "Missing installed hash SDK");
for (var reference : docs) {
@@ -97,12 +99,12 @@ public final class InstalledKnowledgeProbe {
check(linkedResult.diagnostics().stream().noneMatch(issue->issue.isError()),"Installed Linked example must compile");
Files.write(fixtures.resolve("pbs-linked-installed.pbx"),linkedResult.bytecodeBytes());
System.out.println("Installed Linked execution fixture generated");
for(var example:java.util.Map.of("set","sets.pbs","hash","hashing.pbs","map","maps.pbs").entrySet()) {
for(var example:java.util.Map.of("set","sets.pbs","hash","hashing.pbs","map","maps.pbs","stack-queue","stack-queue.pbs").entrySet()) {
Path exampleRoot=Files.createDirectory(Path.of(example.getKey()+"-example")).toRealPath();
Files.createDirectories(exampleRoot.resolve("src"));
Files.copy(root.resolve("prometeu.json"),exampleRoot.resolve("prometeu.json"));
Files.writeString(exampleRoot.resolve("src/mod.barrel"),"pub fn frame() -> void;");
String function=switch(example.getKey()){case "set"->"setExample";case "map"->"mapsExample";default->"hashingExample";};
String function=switch(example.getKey()){case "set"->"setExample";case "map"->"mapsExample";case "stack-queue"->"stackQueueExample";default->"hashingExample";};
Files.writeString(exampleRoot.resolve("src/main.pbs"),Files.readString(root.resolve("src/"+example.getValue()))
+"\n[Frame] fn frame()->void {if "+function+"()!=42 {let failure=1/0;}}");
var exampleResult=BuilderPipelineService.INSTANCE.compile(
@@ -18,6 +18,7 @@ class InstalledKnowledgeTest {
assertTrue(log.contains("Installed List/Cursor execution fixture generated"), log);
assertTrue(log.contains("Installed Linked execution fixture generated"), log);
assertTrue(log.contains("Installed map execution fixture generated"), log);
assertTrue(log.contains("Installed stack-queue execution fixture generated"), log);
}
@Test void installedCompilerAndSdkCarryTheSameVerifiedCatalog() throws Exception {
@@ -44,7 +44,7 @@ class PbsListCursorTest {
if(name.startsWith("gc"))module=PbsStructuredValuesTest.withTestSafepoint(module);
new BytecodePreloadVerifierService().verify(module);
Files.createDirectories(directory());Files.write(directory().resolve("pbs-"+collection+"-"+name+".pbx"),module.serialize());
if(!name.startsWith("gc") || collection.equals("map")) {
if(!name.startsWith("gc") || java.util.Set.of("map","stack","queue").contains(collection)) {
var optimized=new OptimizeIRVMService().optimize(new LowerToIRVMService().lower(backend));
var optimizedModule=new BytecodeEmitter().emit(optimized.coherentEmissionPlan());
if(name.startsWith("gc"))optimizedModule=PbsStructuredValuesTest.withTestSafepoint(optimizedModule);
@@ -0,0 +1,222 @@
package p.studio.compiler.backend.irvm;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Files;
import java.nio.file.Path;
import static org.junit.jupiter.api.Assertions.*;
class PbsStackQueueTest {
private static void compile(String type,String name,String source) throws Exception {
PbsListCursorTest.compileCollection(type,name,source);
}
private static void probe(String type,String name,String body) throws Exception {
compile(type,name,"declare service Probe{fn main()->int{"+body+"}}");
}
private static String insert(String type) {return type.equals("stack")?"push":"enqueue";}
private static String remove(String type) {return type.equals("stack")?"pop":"dequeue";}
@Test void fullApiZeroDefaultAndPreciseGrowth() throws Exception {
for (String type:java.util.List.of("stack","queue")) {
probe(type,"basic","""
let normal:TYPE<int>=new TYPE();if normal.capacity()!=(16 as long){return 0;}
let n:int=0;let values:TYPE<int>=new TYPE<>(n);let alias=values;
if values.isEmpty()==false or values.size()!=(0 as long) or values.capacity()!=(0 as long){return 0;}
if values.peek().hasSome() or values.REMOVE().hasSome(){return 0;}
values.clear();values.INSERT(0);if values.peek().hasNone(){return 0;}
if values.capacity()!=(1 as long){return 0;}values.INSERT(1);
if values.capacity()!=(2 as long){return 0;}values.INSERT(2);
if values.capacity()!=(3 as long){return 0;}values.INSERT(3);
if values.capacity()!=(5 as long){return 0;}values.INSERT(4);values.INSERT(5);
if values.capacity()!=(8 as long) or alias.size()!=(6 as long){return 0;}
let sum:int=0;for i:int from 0 until 6{let expected:int=ORDER;if (alias.peek() else -1)!=expected{return 0;}if (values.REMOVE() else -1)!=expected{return 0;}sum=sum+expected;}
if sum!=15 or values.REMOVE().hasSome() or values.peek().hasSome(){return 0;}
if values.capacity()!=(8 as long) or values.isEmpty()==false{return 0;}
values.INSERT(20);values.INSERT(22);values.clear();values.clear();
if values.size()!=(0 as long) or values.capacity()!=(8 as long){return 0;}
values.INSERT(42);return values.REMOVE() else 0;
""".replace("ORDER",type.equals("stack")?"5-i":"i").replace("TYPE",type).replace("INSERT",insert(type)).replace("REMOVE",remove(type)));
probe(type,"capacity","""
let cap:long=3;let values=new TYPE<int>(cap);
for i:int from 0 until 3{values.INSERT(i);}if values.capacity()!=cap{return 0;}
values.INSERT(3);if values.capacity()!=(5 as long){return 0;}
let maybe:optional (TYPE<int>)=some(new TYPE());if let owner=maybe{owner.INSERT(42);return owner.REMOVE() else 0;}return 0;
""".replace("TYPE",type).replace("INSERT",insert(type)).replace("REMOVE",remove(type)));
probe(type,"arithmetic","""
let maximum:long=4294967295;
if _grownCapacity(maximum-(1 as long),maximum)!=maximum{return 0;}
if _grownCapacity(0,42)!=(42 as long){return 0;}
if _ringIndex(maximum-(1 as long),maximum-(1 as long),maximum)!=maximum-(2 as long){return 0;}
return 42;
""");
probe(type,"fault-negative","let x=new "+type+"<int>(-1);return 0;");
probe(type,"fault-too-large","let n:long=4294967296;let x=new "+type+"<int>(n);return 0;");
probe(type,"fault-required","let maximum:long=4294967295;let x:long=_grownCapacity(maximum,maximum+1);return 0;");
}
}
@Test void circularQueueWrapsGrowsAndNormalizesAcrossRepeatedCycles() throws Exception {
probe("queue","wrap","""
let q=new queue<int>(4);for i:int from 0 until 4{q.enqueue(i);}
if (q.dequeue() else -1)!=0 or (q.dequeue() else -1)!=1{return 0;}
q.enqueue(4);q.enqueue(5);if q.capacity()!=(4 as long){return 0;}
let snapshot=q.cursor();q.enqueue(6);if q.capacity()!=(6 as long){return 0;}
for i:int from 2 until 7{if (q.dequeue() else -1)!=i{return 0;}}
for i:int from 2 until 6{if (snapshot.current() else -1)!=i{return 0;}snapshot.next();}
if (snapshot.current() else -1)!=5 or snapshot.hasNext(){return 0;}
for cycle:int from 0 until 20{
for i:int from 0 until 6{q.enqueue(cycle*10+i);}
for i:int from 0 until 6{if (q.dequeue() else -1)!=cycle*10+i{return 0;}}
if q.isEmpty()==false{return 0;}
}
for i:int from 0 until 6{q.enqueue(i);}q.dequeue();q.dequeue();q.enqueue(20);q.enqueue(22);
q.clear();q.enqueue(42);if q.capacity()!=(6 as long){return 0;}return q.dequeue() else 0;
""");
}
@Test void snapshotsKeepAllStatesOrderDuplicatesAndSharedPayloadMutation() throws Exception {
for (String type:java.util.List.of("stack","queue")) {
probe(type,"cursor-empty","""
let values=new TYPE<int>(0);let c=values.cursor();values.INSERT(42);
for i:int from 0 until 3{if c.current().hasSome() or c.hasNext(){return 0;}c.next();}return 42;
""".replace("TYPE",type).replace("INSERT",insert(type)));
probe(type,"cursor-single","""
let values=new TYPE<int>();values.INSERT(42);let c=values.cursor();values.REMOVE();values.clear();
for i:int from 0 until 3{if c.hasNext() or (c.current() else 0)!=42{return 0;}c.next();}return 42;
""".replace("TYPE",type).replace("INSERT",insert(type)).replace("REMOVE",remove(type)));
compile(type,"snapshot","""
declare struct Item(pub mut value:int);
declare service Probe{fn main()->int{
let values=new TYPE<Item>(2);let first=new Item(20);let last=new Item(22);
values.INSERT(first);values.INSERT(last);values.INSERT(first);let c=values.cursor();
values.REMOVE();values.INSERT(new Item(0));values.clear();first.value=21;
if c.hasNext()==false{return 0;}if let a=c.current(){if a.value!=21{return 0;}}else{return 0;}
c.next();if let b=c.current(){if b.value!=22{return 0;}}else{return 0;}
if c.hasNext()==false{return 0;}c.next();c.next();if c.hasNext(){return 0;}
if let a=c.current(){return a.value*2;}return 0;
}}
""".replace("TYPE",type).replace("INSERT",insert(type)).replace("REMOVE",remove(type)));
probe(type,"cursor-order","""
let values=new TYPE<int>(0);values.INSERT(20);values.INSERT(22);let c=values.cursor();
if (c.current() else 0)!=FIRST{return 0;}if c.hasNext()==false{return 0;}
c.next();if (c.current() else 0)!=LAST or c.hasNext(){return 0;}return 42;
""".replace("TYPE",type).replace("INSERT",insert(type)).replace("FIRST",type.equals("stack")?"22":"20").replace("LAST",type.equals("stack")?"20":"22"));
}
}
@Test void completeGroupsOptionalFieldsFunctionsAndContractsSurviveGrowthAndRemoval() throws Exception {
for (String type:java.util.List.of("stack","queue")) {
probe(type,"groups","""
let groups=new TYPE<(a:int,b:int)>(0);groups.INSERT((a:20,b:22));let c=groups.cursor();
groups.INSERT((a:1,b:2));
if let removed=groups.REMOVE(){if removed.a!=EXPECTED_A or removed.b!=EXPECTED_B{return 0;}}else{return 0;}
groups.clear();
if let group=c.current(){return group.a+group.b;}return 0;
""".replace("TYPE",type).replace("INSERT",insert(type)).replace("REMOVE",remove(type))
.replace("EXPECTED_A",type.equals("stack")?"1":"20").replace("EXPECTED_B",type.equals("stack")?"2":"22"));
compile(type,"references","""
declare struct Item(pub value:optional int);
declare contract Read{fn read()->int;}
implements Read for Item using item{fn read()->int{return item.value else 0;}}
fn answer()->int{return 42;}
declare service Probe{fn main()->int{
let flags=new TYPE<bool>(0);flags.INSERT(false);if flags.peek().hasNone() or (flags.REMOVE() else true){return 0;}
let items=new TYPE<Item>(0);items.INSERT(new Item(none));if let item=items.REMOVE(){if item.value.hasSome(){return 0;}}else{return 0;}
let reads=new TYPE<Read>(0);reads.INSERT(new Item(some(42)) as Read);let c=reads.cursor();reads.clear();
let functions=new TYPE<Fn()->int>(0);functions.INSERT(answer);if let f=functions.REMOVE(){if f()!=42{return 0;}}else{return 0;}
let arrays=new TYPE<array<int>>(0);let a:array<int>=[42];arrays.INSERT(a);a[0]=20;
if let shared=arrays.REMOVE(){if (shared[0] else 0)!=20{return 0;}}else{return 0;}
if let r=c.current(){return r.read();}return 0;
}}
""".replace("TYPE",type).replace("INSERT",insert(type)).replace("REMOVE",remove(type)));
compile(type,"native","""
[BuiltinType(name="vec2",version=1)]declare builtin type Vec2(pub x:float,pub y:float){}
fn nativeProbe()->int{
let values=new TYPE<Vec2>(0);values.INSERT(new Vec2(20.0,22.0));let c=values.cursor();
values.INSERT(new Vec2(1.0,2.0));
if let removed=values.REMOVE(){if removed.x!=EXPECTED_X or removed.y!=EXPECTED_Y{return 0;}}else{return 0;}
values.clear();
if let v=c.current(){return (v.x+v.y) as int;}return 0;
}
declare service Probe{fn main()->int{return nativeProbe();}}
""".replace("TYPE",type).replace("INSERT",insert(type)).replace("REMOVE",remove(type))
.replace("EXPECTED_X",type.equals("stack")?"1.0":"20.0").replace("EXPECTED_Y",type.equals("stack")?"2.0":"22.0"));
compile(type,"evaluation","""
declare struct Effects(pub mut trace:int,pub values:TYPE<int>){
fn receiver()->TYPE<int>{this.trace=this.trace*10+1;return this.values;}
fn value()->int{this.trace=this.trace*10+2;return 42;}
fn capacity()->int{this.trace=this.trace*10+3;return 0;}
}
fn insertNamed(values:TYPE<int>,value:int){values.INSERT(value);}
declare service Probe{fn main()->int{
let e=new Effects(0,new TYPE<int>());e.receiver().INSERT(e.value());if e.trace!=12{return 0;}
e.trace=0;insertNamed apply (value:e.value(),values:e.receiver());if e.trace!=21{return 0;}
e.trace=0;let created=new TYPE<int>(e.capacity());if e.trace!=3 or created.capacity()!=(0 as long){return 0;}
e.trace=0;let found=e.receiver().peek();if e.trace!=1{return 0;}return found else 0;
}}
""".replace("TYPE",type).replace("INSERT",insert(type)));
}
}
@Test void operationFixturesMarkPreparationAndAllVisibleWrites() throws Exception {
for (String type:java.util.List.of("stack","queue")) {
for (String operation:java.util.List.of("insert","growth","zero","remove","clear","peek","cursor","empty")) {
String statement=switch(operation){case "insert","growth","zero"->"values."+insert(type)+"(42);";case "remove","empty"->"let old=values."+remove(type)+"();";case "clear"->"values.clear();";case "peek"->"let old=values.peek();";default->"let c=values.cursor();";};
String setup=switch(operation){case "zero","empty"->"let values=new "+type+"<int>(0);";case "growth"->"let values=new "+type+"<int>(4);for i:int from 0 until 4{values."+insert(type)+"(i);}";default->"let values=new "+type+"<int>(8);for i:int from 0 until 4{values."+insert(type)+"(i);}";};
compile(type,"refusal-"+operation,"""
fn mutationMarker(){let marker:int=314160;}
fn completedMarker(){let marker:int=314161;}
fn perform(values:TYPE<int>){OPERATION}
declare service Probe{fn main()->int{SETUP mutationMarker();perform(values);completedMarker();return 42;}}
""".replace("TYPE",type).replace("OPERATION",statement).replace("SETUP",setup));
}
}
compile("queue","refusal-wrapped","""
fn mutationMarker(){let marker:int=314160;}fn completedMarker(){let marker:int=314161;}
fn perform(values:queue<int>){values.enqueue(42);}
declare service Probe{fn main()->int{let values=new queue<int>(4);for i:int from 0 until 4{values.enqueue(i);}values.dequeue();values.dequeue();values.enqueue(4);values.enqueue(5);mutationMarker();perform(values);completedMarker();return 42;}}
""");
String sdk=PbsSetTest.sdk();
for(String type:java.util.List.of("stack","queue")) {
int offset=sdk.indexOf(type.equals("stack")?"[SdkStack]":"[SdkQueue]");
int end=sdk.indexOf(type.equals("stack")?"// Valid only for nonempty backing":"declare contract Cursor<T>",offset);
String injected=sdk.substring(0,offset)+sdk.substring(offset,end).replace("this.storage = target;","this.storage = target;let testOnlyQuotaProbe=new array<int>(1000000);")+sdk.substring(end);
PbsListCursorTest.compileCollection(type,"injected-growth","declare service Probe{fn main()->int{let values=new "+type+"<int>(2);values."+insert(type)+"(20);values."+insert(type)+"(22);values."+insert(type)+"(42);return 42;}}",injected);
}
}
@Test void realGcFixturesObserveRemovalClearReplacedBackingAndSnapshotRelease() throws Exception {
for (String type:java.util.List.of("stack","queue")) {
compile(type,"gc-snapshot","""
declare struct Item(pub value:int);declare struct Garbage();fn collect(){let marker:int=314159;}
fn make()->Cursor<Item>{let values=new TYPE<Item>(0);for i:int from 0 until 1200{values.INSERT(new Item(i));}return values.cursor();}
fn use(){let c=make();collect();for i:int from 0 until 1199{c.next();}collect();for i:int from 0 until 1200{c.next();}collect();}
declare service Probe{fn main()->int{use();for i:int from 0 until 1200{let x=new Garbage();}collect();return 42;}}
""".replace("TYPE",type).replace("INSERT",insert(type)));
compile(type,"gc-collection","""
declare struct Item(pub value:int);declare struct Garbage();fn collect(){let marker:int=314159;}
fn pressure(){for i:int from 0 until 1200{let x=new Garbage();}}
fn make()->TYPE<Item>{let values=new TYPE<Item>(0);for i:int from 0 until 64{values.INSERT(new Item(i));}return values;}
fn discard(values:TYPE<Item>){for i:int from 0 until 3{values.REMOVE();}}
fn use(){let values=make();pressure();collect();discard(values);pressure();collect();values.clear();pressure();collect();values.INSERT(new Item(42));pressure();collect();}
declare service Probe{fn main()->int{use();pressure();collect();return 42;}}
""".replace("TYPE",type).replace("INSERT",insert(type)).replace("REMOVE",remove(type)));
}
}
@Test void aliasesAndReexportsUseInstalledSdkAuthority(@TempDir Path root) throws Exception {
Files.createDirectories(root.resolve("src/facade"));
Files.writeString(root.resolve("prometeu.json"),"{\"name\":\"app\",\"version\":\"1.0.0\",\"language\":\"pbs\",\"stdlib\":\"1\",\"target\":\"Game\",\"dependencies\":[]}");
Files.writeString(root.resolve("src/mod.barrel"),"pub fn frame()->void;");
Files.writeString(root.resolve("src/facade/mod.barrel"),"pub struct Lifo<T>;pub struct Fifo<T>;pub contract Walk<T>;");
Files.writeString(root.resolve("src/facade/main.pbs"),"import {stack as Lifo,queue as Fifo,Cursor as Walk} from @sdk:collections;");
Files.writeString(root.resolve("src/main.pbs"),"""
import {Lifo,Fifo,Walk} from @app:facade;
[Frame]fn frame()->void{
let s:Lifo<int>=new Lifo(0);let q:Fifo<int>=new Fifo<>(0);
s.push(20);s.push(22);q.enqueue(20);q.enqueue(22);
let a:Walk<int>=s.cursor();let b:Walk<int>=q.cursor();s.clear();q.clear();
if (a.current() else 0)!=22 or (b.current() else 0)!=20{let failure=1/0;}
a.next();b.next();if (a.current() else 0)!=20 or (b.current() else 0)!=22{let failure=1/0;}
}
""");
var compiled=p.studio.compiler.workspaces.BuilderPipelineService.INSTANCE.compile(
p.studio.compiler.models.BuilderPipelineContext.fromConfig(new p.studio.compiler.messages.BuilderPipelineConfig(false,root.toString())),
p.studio.utilities.logs.LogAggregator.stdout());
assertFalse(compiled.diagnostics().stream().anyMatch(d->d.isError()),compiled.diagnostics().toString());
Files.write(Path.of(System.getProperty("pbs.registryConformanceDirectory")).resolve("pbs-stack-queue-imports.pbx"),compiled.bytecodeBytes());
}
}
@@ -245,7 +245,7 @@ public final class PbsGenericInstantiation {
return null;
}
if (PbsSdkCollections.isCollection(template) && PbsSdkCollections.directOptional(arguments.getFirst())) {
error(PbsSdkCollections.isMap(template)?"MAP_OPTIONAL_KEY":PbsSdkCollections.isSet(template)?"SET_OPTIONAL_ELEMENT":PbsSdkCollections.isLinked(template) ? "LINKED_OPTIONAL_ELEMENT" : "LIST_OPTIONAL_ELEMENT",
error(PbsSdkCollections.isMap(template)?"MAP_OPTIONAL_KEY":PbsSdkCollections.isSet(template)?"SET_OPTIONAL_ELEMENT":PbsSdkCollections.isStack(template)?"STACK_OPTIONAL_ELEMENT":PbsSdkCollections.isQueue(template)?"QUEUE_OPTIONAL_ELEMENT":PbsSdkCollections.isLinked(template) ? "LINKED_OPTIONAL_ELEMENT" : "LIST_OPTIONAL_ELEMENT",
"SDK " + name(template) + " does not permit a directly optional " + (PbsSdkCollections.isMap(template)?"key":"element"), site);
return null;
}
@@ -15,6 +15,15 @@ public final class PbsSdkCollections {
public static boolean isIndexedCollection(PbsAst.TopDecl declaration) {
return isList(declaration) || isLinked(declaration);
}
public static boolean isStack(PbsAst.TopDecl declaration) {
return declaration instanceof PbsAst.StructDecl s && attribute(s.attributes(), "SdkStack") != null;
}
public static boolean isQueue(PbsAst.TopDecl declaration) {
return declaration instanceof PbsAst.StructDecl s && attribute(s.attributes(), "SdkQueue") != null;
}
public static boolean hasCapacityConstructor(PbsAst.TopDecl declaration) {
return isIndexedCollection(declaration) || isStack(declaration) || isQueue(declaration);
}
public static boolean isSet(PbsAst.TopDecl declaration) {
return declaration instanceof PbsAst.StructDecl s && attribute(s.attributes(), "SdkSet") != null;
}
@@ -25,7 +34,7 @@ public final class PbsSdkCollections {
return isIndexedCollection(declaration) || isMap(declaration);
}
public static boolean isCollection(PbsAst.TopDecl declaration) {
return hasIndexer(declaration)||isSet(declaration);
return hasIndexer(declaration)||isSet(declaration)||isStack(declaration)||isQueue(declaration);
}
public static boolean hasDefaultIdentity(PbsAst.TypeRef type,PbsContractTypes types) {
while(type!=null&&type.kind()==PbsAst.TypeRefKind.GROUP)type=type.inner();
@@ -1868,7 +1868,7 @@ final class PbsExecutableBodyLowerer {
}
private void lowerStructNew(PbsAst.NewExpr expr,PbsExecutableLoweringContext c) {
var declaration=c.types().structs.get(expr.typeName());var ref=c.types().registryType(PbsRuntimeTypes.type(expr.typeName()));
boolean list=p.studio.compiler.pbs.PbsSdkCollections.isIndexedCollection(declaration);
boolean list=p.studio.compiler.pbs.PbsSdkCollections.hasCapacityConstructor(declaration);
if(expr.ctorName()!=null) {
var ctor=declaration.ctors().stream().filter(f->f.name().equals(expr.ctorName()) && parametersMatch(f.parameters(),expr.arguments(),c,list)).findFirst().orElse(null);
if (ctor == null) {
@@ -685,7 +685,7 @@ final class PbsDeclarationParser {
final String targetSurface) {
for (final var attribute : attributes) {
if ("Doc".equals(attribute.name()) || attribute.trustedSdkOrigin() &&
java.util.Set.of("SdkList", "SdkLinked", "SdkSet", "SdkMap").contains(attribute.name()) && "struct declarations".equals(targetSurface)) {
java.util.Set.of("SdkList", "SdkLinked", "SdkSet", "SdkMap", "SdkStack", "SdkQueue").contains(attribute.name()) && "struct declarations".equals(targetSurface)) {
continue;
}
p.studio.compiler.source.diagnostics.Diagnostics.error(context.diagnostics(),
@@ -141,6 +141,145 @@ declare struct list<T>(storage: array<T>, length: long) {
}
}
[SdkStack]
declare struct stack<T>(storage: array<T>, length: long) {
ctor make() {
this.storage = new array<T>(16);
this.length = 0;
}
ctor make(capacity: long) {
_checkLength(capacity);
this.storage = new array<T>(capacity);
this.length = 0;
}
fn size() -> long { return this.length; }
fn capacity() -> long { return this.storage.length; }
fn isEmpty() -> bool { return this.length == (0 as long); }
fn peek() -> optional T {
if this.length == (0 as long) { return none; }
return this.storage[this.length - (1 as long)];
}
fn push(value: T) {
let required: long = this.length + 1;
_checkLength(required);
if required > this.storage.length {
let target: array<T> = new array<T>(_grownCapacity(this.storage.length, required));
_copy<T>(this.storage, 0, target, 0, this.length);
target[this.length] = value;
this.storage = target;
} else {
this.storage[this.length] = value;
}
this.length = required;
}
fn pop() -> optional T {
if this.length == (0 as long) { return none; }
let length: long = this.length - 1;
let previous: optional T = this.storage[length];
this.storage.clear(length);
this.length = length;
return previous;
}
fn clear() {
let index: long = 0;
while index < this.length {
this.storage.clear(index);
index = index + 1;
}
this.length = 0;
}
fn cursor() -> Cursor<T> {
let head: optional _SnapshotNode<T> = none;
let index: long = 0;
while index < this.length {
if let value = this.storage[index] {
head = some(new _SnapshotNode<T>(value, head));
}
index = index + 1;
}
return new _SnapshotCursor<T>(head) as Cursor<T>;
}
}
// Valid only for nonempty backing, start < capacity and offset <= capacity.
// The checked u32 capacity bounds make start + offset fit long without narrowing.
fn _ringIndex(start: long, offset: long, capacity: long) -> long {
let index: long = start + offset;
if index >= capacity { index = index - capacity; }
return index;
}
[SdkQueue]
declare struct queue<T>(storage: array<T>, start: long, length: long) {
ctor make() {
this.storage = new array<T>(16);
this.start = 0;
this.length = 0;
}
ctor make(capacity: long) {
_checkLength(capacity);
this.storage = new array<T>(capacity);
this.start = 0;
this.length = 0;
}
fn size() -> long { return this.length; }
fn capacity() -> long { return this.storage.length; }
fn isEmpty() -> bool { return this.length == (0 as long); }
fn peek() -> optional T {
if this.length == (0 as long) { return none; }
return this.storage[this.start];
}
fn enqueue(value: T) {
let required: long = this.length + 1;
_checkLength(required);
if required > this.storage.length {
let target: array<T> = new array<T>(_grownCapacity(this.storage.length, required));
let first: long = this.storage.length - this.start;
if first > this.length { first = this.length; }
_copy<T>(this.storage, this.start, target, 0, first);
_copy<T>(this.storage, 0, target, first, this.length - first);
target[this.length] = value;
this.storage = target;
this.start = 0;
} else {
let index: long = _ringIndex(this.start, this.length, this.storage.length);
this.storage[index] = value;
}
this.length = required;
}
fn dequeue() -> optional T {
if this.length == (0 as long) { return none; }
let length: long = this.length - 1;
let start: long = 0;
if length > (0 as long) { start = _ringIndex(this.start, 1, this.storage.length); }
let previous: optional T = this.storage[this.start];
this.storage.clear(this.start);
this.start = start;
this.length = length;
return previous;
}
fn clear() {
let offset: long = 0;
while offset < this.length {
this.storage.clear(_ringIndex(this.start, offset, this.storage.length));
offset = offset + 1;
}
this.start = 0;
this.length = 0;
}
fn cursor() -> Cursor<T> {
let head: optional _SnapshotNode<T> = none;
let offset: long = this.length;
while offset > (0 as long) {
offset = offset - 1;
if let value = this.storage[_ringIndex(this.start, offset, this.storage.length)] {
head = some(new _SnapshotNode<T>(value, head));
}
}
return new _SnapshotCursor<T>(head) as Cursor<T>;
}
}
declare contract Cursor<T> {
fn hasNext() -> bool;
fn next();
@@ -5,3 +5,5 @@ pub struct set<T>;
pub contract Identity<T>;
pub struct map<K, V>;
pub struct keyval<K, V>;
pub struct stack<T>;
pub struct queue<T>;
@@ -7,3 +7,4 @@ pub fn linkedExample() -> int;
pub fn setExample() -> int;
pub fn hashingExample() -> int;
pub fn mapsExample() -> int;
pub fn stackQueueExample() -> int;
@@ -0,0 +1,25 @@
import {stack, queue, Cursor} from @sdk:collections;
fn stackQueueExample() -> int {
let history = new stack<int>(0);
let pending = new queue<int>(2);
history.push(20);
history.push(22);
pending.enqueue(20);
pending.enqueue(22);
let lastFirst: Cursor<int> = history.cursor();
let firstFirst: Cursor<int> = pending.cursor();
history.clear();
pending.dequeue();
pending.enqueue(0);
pending.enqueue(1);
pending.clear();
if (lastFirst.current() else 0) != 22 { return 0; }
if (firstFirst.current() else 0) != 20 { return 0; }
lastFirst.next();
firstFirst.next();
if lastFirst.hasNext() or firstFirst.hasNext() { return 0; }
if (lastFirst.current() else 0) != 20 { return 0; }
if (firstFirst.current() else 0) != 22 { return 0; }
return (lastFirst.current() else 0) + (firstFirst.current() else 0);
}
@@ -124,6 +124,27 @@ class PbsGateUSdkInterfaceConformanceTest {
assertTrue(copied.hasErrors());
}
@Test
void stackQueueExportsPreserveCapacityRulesAndRejectIndexing() throws IOException {
var positive=compileWorkspaceModule(tempDir.resolve("stack-queue-positive"),"""
import {stack as Lifo,queue as Fifo} from @sdk:collections;
[Frame]fn frame()->void{let n:int=0;let s:Lifo<int>=new Lifo(n);let q:Fifo<int>=new Fifo<>();s.push(20);q.enqueue(22);}
""","pub fn frame()->void;",1,null);
assertFalse(positive.diagnostics().hasErrors(),positive.diagnostics().toString());
for(String type:java.util.List.of("stack","queue")) {
for(var entry:java.util.Map.of(
"optional","let xs=new "+type+"<optional int>();",
"index","let xs=new "+type+"<int>();let invalid=xs[0];",
"private","let xs=new "+type+"<int>();let exposed=xs.storage;",
"capacity","let xs=new "+type+"<int>(true);",
"bounded","let xs=new "+type+"<int>();xs.reserve(4);").entrySet()) {
var negative=compileWorkspaceModule(tempDir.resolve(type+"-negative-"+entry.getKey()),
"import {"+type+"} from @sdk:collections;[Frame]fn frame()->void{"+entry.getValue()+"}","pub fn frame()->void;",1,null);
assertTrue(negative.diagnostics().hasErrors(),type+"/"+entry.getKey());
}
}
}
@Test
void mapExportsUseOriginCheckedKeyTypingAndPrivateAssociations() throws IOException {
var positive=compileWorkspaceModule(tempDir.resolve("map-positive"),"""
@@ -0,0 +1,66 @@
package p.studio.compiler.pbs;
import org.junit.jupiter.api.Test;
import p.studio.compiler.models.SourceKind;
import p.studio.compiler.source.diagnostics.DiagnosticSink;
import p.studio.compiler.source.identifiers.FileId;
import java.nio.charset.StandardCharsets;
import static org.junit.jupiter.api.Assertions.*;
class PbsStackQueueTest {
private DiagnosticSink compile(String source) throws Exception {
String sdk;
try (var stream=getClass().getResourceAsStream("/game/stdlib/1/sdk/collections/main.pbs")) {
assertNotNull(stream);sdk=new String(stream.readAllBytes(),StandardCharsets.UTF_8);
}
var diagnostics=DiagnosticSink.empty();
new PbsFrontendCompiler().compileFile(new FileId(0),sdk+"\n"+source,diagnostics,SourceKind.SDK_INTERFACE);
return diagnostics;
}
@Test void capacitiesContextAndOptionalFieldsUseOrdinaryGenericRules() throws Exception {
var diagnostics=compile("""
declare struct Item(pub value:optional int);
fn sample(){
let n:int=0;let wide:long=4;
let s:stack<int>=new stack(n);let q:queue<int>=new queue<>(wide);
let defaultStack:stack<int>=new stack();let defaultQueue:queue<int>=new queue<>();
let maybe:optional (stack<Item>)=some(new stack());
let nested=new queue<array<int>>();nested.enqueue(new array<int>(0));
let items=new stack<Item>();items.push(new Item(none));
s.push(42);q.enqueue(42);s.pop();q.dequeue();s.peek();q.peek();s.clear();q.clear();
}
""");
assertFalse(diagnostics.hasErrors(),()->diagnostics.stream().map(d->d.getCode()+":"+d.getMessage()).toList().toString());
}
@Test void optionalInvariancePrivacyAndUnsupportedSurfacesAreRejected() throws Exception {
for (String type:java.util.List.of("stack","queue")) {
for (String optional:java.util.List.of("optional int","(optional int)")) {
var d=compile("fn f(){let x=new "+type+"<"+optional+">();}");
assertTrue(d.stream().anyMatch(i->i.getCode().contains(type.toUpperCase()+"_OPTIONAL_ELEMENT")),d.toString());
}
for (String statement:java.util.List.of(
"let x=new "+type+"();",
"let x:"+type+"<long>=new "+type+"<int>();",
"let x=new "+type+"<int>(true);",
"let x=new "+type+"<int>();let y=x[0];",
"let x=new "+type+"<int>();x.reserve(10);",
"let x=new "+type+"<int>();x.trim();",
"let x=new "+type+"<int>();let y=x.storage;")) {
assertTrue(compile("fn f(){"+statement+"}").hasErrors(),statement);
}
String insert=type.equals("stack")?"push":"enqueue";
assertTrue(compile("fn f(){let x=new "+type+"<long>();let n:int=1;x."+insert+"(n);}").hasErrors());
}
assertTrue(compile("fn f(){let q=new queue<int>();let hidden=q.start;}").hasErrors());
}
@Test void projectHomonymsDoNotAcquireTrustedSdkBehavior() {
for (String type:java.util.List.of("stack","queue")) {
var d=DiagnosticSink.empty();
new PbsFrontendCompiler().compileFile(new FileId(0),"declare struct "+type+"<T>(pub value:T);fn f(){let x=new "+type+"<optional int>(none);}",d);
assertFalse(d.hasErrors(),d.toString());
var forged=DiagnosticSink.empty();
new PbsFrontendCompiler().compileFile(new FileId(0),"[Sdk"+(type.equals("stack")?"Stack":"Queue")+"]declare struct "+type+"<T>(value:T);",forged);
assertTrue(forged.hasErrors());
}
}
}
@@ -0,0 +1,45 @@
package p.studio.compiler.pbs.semantics;
import org.junit.jupiter.api.Test;
import p.studio.compiler.pbs.ast.PbsAst;
import p.studio.compiler.pbs.lexer.PbsLexer;
import p.studio.compiler.pbs.parser.PbsParser;
import p.studio.compiler.source.diagnostics.DiagnosticSink;
import p.studio.compiler.source.identifiers.FileId;
import p.studio.utilities.structures.ReadOnlyList;
import java.nio.charset.StandardCharsets;
import java.util.Set;
import java.util.stream.Collectors;
import static org.junit.jupiter.api.Assertions.*;
class PbsStackQueueEditorialTest {
@Test void aliasesShowConcretePublicApiConstructorsAndOriginalSdkDefinitions() throws Exception {
var diagnostics=DiagnosticSink.empty();var sdkId=new FileId(1);String sdk;
try(var stream=getClass().getResourceAsStream("/game/stdlib/1/sdk/collections/main.pbs")) {
assertNotNull(stream);sdk=new String(stream.readAllBytes(),StandardCharsets.UTF_8);
}
var library=PbsParser.parse(PbsLexer.lex(sdk,sdkId,diagnostics),sdkId,diagnostics,PbsParser.ParseMode.INTERFACE_MODULE);
for (String type:java.util.List.of("stack","queue")) {
String insert=type.equals("stack")?"push":"enqueue",remove=type.equals("stack")?"pop":"dequeue";
String source="import {"+type+" as Values} from @sdk:collections;fn f(values:Values<int>){let x:Values<int>=new Values();values."+insert+"(42);values.storage;}";
var id=new FileId(2);var ast=PbsParser.parse(PbsLexer.lex(source,id,diagnostics),id,diagnostics);
var declarations=new java.util.ArrayList<PbsAst.TopDecl>(library.topDecls().stream().toList());
var origin=library.topDecls().stream().filter(d->d instanceof PbsAst.StructDecl s&&s.name().equals(type)).findFirst().orElseThrow();
declarations.add(new PbsAst.TypeBindingDecl("Values",origin,ast.span()));
var supplemental=ReadOnlyList.wrap(declarations);var service=new PbsEditorialSupportService();
int offset=source.indexOf("values."+insert)+7;
assertEquals(Set.of(insert,remove,"peek","size","capacity","isEmpty","clear","cursor"),
service.completion(source,ast,supplemental,offset).stream().map(c->c.label()).collect(Collectors.toSet()));
assertTrue(service.hover(source,ast,supplemental,offset).orElseThrow().signatures().getFirst().label().contains("int"));
assertEquals(sdkId,service.definition(source,ast,supplemental,offset).getFirst().span().getFileId());
var constructors=service.signatureHelp(source,ast,supplemental,source.indexOf("new Values(")+11).orElseThrow().signatures();
assertEquals(2,constructors.size());
assertTrue(constructors.stream().anyMatch(c->c.label().contains("capacity: long")),constructors.toString());
assertTrue(constructors.stream().noneMatch(c->c.label().contains("storage")||c.label().contains("$generic$")));
int hidden=source.indexOf("values.storage")+7;
assertTrue(service.hover(source,ast,supplemental,hidden).isEmpty());
assertTrue(service.definition(source,ast,supplemental,hidden).isEmpty());
}
assertFalse(diagnostics.hasErrors(),diagnostics.toString());
}
}
+21
View File
@@ -397,3 +397,24 @@ prefix reclamation and sticky final retention. Set GC tests do not assume an
iteration order. Add `--release` to qualify the Rust release profile independently
of the two producer variants; omit focused flags for the complete mandatory corpus.
All harness builds remain outside the runtime checkout, which is consumed unchanged.
## PBS Stack and Queue qualification
The mandatory Stack/Queue corpus is included in every complete run. A focused
run uses `python3 tools/pbx-conformance/run.py --runtime ../runtime --stack-queue-only`;
add `--release` for the optimized runtime profile. Both source producer paths are
mandatory in each profile. Generate fixtures with the architecture tests and
`:prometeu-app:installedKnowledgeTest` before executing the runner.
`stack_queue.rs` validates dense/circular storage, inactive-slot cleanup, exact
capacity/growth, wrapped growth, complete payloads, once/named evaluation, snapshot
orders/states, imports and actual installed-JAR examples. Lowered quota runs compare
complete original-object instruction prefixes to a successful run and distinguish
preservation before mutation from retained writes afterward. Separate test-only
growth probes demonstrate an installed candidate with old size after a later fault;
these probes are not shipped or counted as natural refusal frequencies.
GC fixtures require actual advancing collection counters. Snapshots release source
backings and observe 1,200 → 1 → 1 → 0 nodes/payloads. Collection fixtures observe
64 → 61 → 0 → 1 → 0 payloads and only one retained backing until its final owner
is dropped. Temporary Cargo projects/targets stay outside the runtime checkout.
+4 -1
View File
@@ -1,4 +1,5 @@
use prometeu_bytecode::Value;
mod stack_queue;
use prometeu_bytecode::load_limits::{LoadBudget, LoadLimits};
use prometeu_hal::syscalls::caps;
use prometeu_vm::{
@@ -41,6 +42,7 @@ fn main() {
for resource in [Q::GuestBytes,Q::HandleSlots,Q::AuxiliaryBytes,Q::TemporaryBytes,Q::StringBytes,Q::StringAllocations,Q::IndividualStringBytes,Q::CallDepth] {
println!("DEFAULT VM LIMIT {resource:?}={}",limits.get(resource));
}
if std::env::args().any(|arg| arg == "--stack-queue-only") { stack_queue::verify(&root); return; }
if std::env::args().any(|arg| arg == "--map-only") { verify_pbs_map_fixtures(&root); return; }
if std::env::args().any(|arg| arg == "--set-only") { verify_pbs_set_fixtures(&root); return; }
if std::env::args().any(|arg| arg == "--identity-hashing-only") { verify_identity_hashing_fixtures(&root); return; }
@@ -63,6 +65,7 @@ fn main() {
verify_pbs_linked_fixtures(&root);
verify_pbs_set_fixtures(&root);
verify_pbs_map_fixtures(&root);
stack_queue::verify(&root);
verify_pbs_resource_refusals(&root);
verify_pbs_closure_frames(&root);
for name in [
@@ -503,7 +506,7 @@ fn verify_pbs_fixtures(root: &std::path::Path) {
for entry in std::fs::read_dir(root).unwrap() {
let path = entry.unwrap().path();
let name = path.file_stem().unwrap().to_str().unwrap();
if name.starts_with("pbs-random-") || name.starts_with("pbs-math-") || name.starts_with("pbs-structured-") || name.starts_with("pbs-generic-contract-") || name.starts_with("pbs-generic-struct-") || name.starts_with("pbs-list-") || name.starts_with("pbs-linked-") || name.starts_with("pbs-hash-") || name.starts_with("pbs-set-") || name.starts_with("pbs-map-") || !name.starts_with("pbs-") || path.extension().and_then(|v| v.to_str()) != Some("pbx") { continue; }
if name.starts_with("pbs-random-") || name.starts_with("pbs-math-") || name.starts_with("pbs-structured-") || name.starts_with("pbs-generic-contract-") || name.starts_with("pbs-generic-struct-") || name.starts_with("pbs-list-") || name.starts_with("pbs-linked-") || name.starts_with("pbs-hash-") || name.starts_with("pbs-set-") || name.starts_with("pbs-map-") || name.starts_with("pbs-stack-") || name.starts_with("pbs-queue-") || !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)
+5 -1
View File
@@ -14,6 +14,7 @@ parser.add_argument("--online", action="store_true", help="Allow Cargo to fetch
parser.add_argument("--release", action="store_true", help="Execute an optimized runtime harness")
parser.add_argument("--set-only", action="store_true", help="Run mandatory PBS Set corpus")
parser.add_argument("--map-only", action="store_true", help="Run mandatory PBS Map/Keyval corpus")
parser.add_argument("--stack-queue-only", action="store_true", help="Run mandatory PBS Stack/Queue corpus")
parser.add_argument("--identity-hashing-only", action="store_true", help="Run mandatory neutral and PBS identity/hash corpus")
parser.add_argument("--math-only", action="store_true", help="Run the complete PBS math corpus only")
parser.add_argument("--random-only", action="store_true", help="Run the complete PBS Random corpus only")
@@ -34,6 +35,8 @@ if provider_hash_vectors.read_bytes() != consumer_hash_vectors.read_bytes():
raise SystemExit("Hash oracle differs from selected provider")
print(subprocess.check_output(["rustc", "-Vv"], text=True).strip(), flush=True)
for source in [pathlib.Path(__file__), pathlib.Path(__file__).with_name("main.rs"),
pathlib.Path(__file__).with_name("stack_queue.rs"),
pathlib.Path("prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsStackQueueTest.java"),
pathlib.Path("prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsRuntimeRandomTest.java"),
pathlib.Path("prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/sdk/random/main.pbs")]:
print("sha256", source, hashlib.sha256(source.read_bytes()).hexdigest(), flush=True)
@@ -59,4 +62,5 @@ with tempfile.TemporaryDirectory(prefix="pbx-conformance-") as directory:
(root / "Cargo.lock").write_text((runtime / "Cargo.lock").read_text())
(root / "src").mkdir()
(root / "src/main.rs").write_text(pathlib.Path(__file__).with_name("main.rs").read_text())
subprocess.run(["cargo", "run", *(["--release"] if args.release else []), *([] if args.online else ["--offline"]), "--manifest-path", str(root / "Cargo.toml"), "--", str(args.fixtures.resolve()), str(runtime / "devtools/headless-protocol/response.schema.json"), *(["--map-only"] if args.map_only else []), *(["--set-only"] if args.set_only else []), *(["--identity-hashing-only"] if args.identity_hashing_only else []), *(["--math-only"] if args.math_only else []), *(["--random-only"] if args.random_only else []), *(["--generic-contracts-only"] if args.generic_contracts_only else []), *(["--generic-structs-only"] if args.generic_structs_only else []), *(["--list-cursor-only"] if args.list_cursor_only else []), *(["--linked-only"] if args.linked_only else [])], check=True)
(root / "src/stack_queue.rs").write_text(pathlib.Path(__file__).with_name("stack_queue.rs").read_text())
subprocess.run(["cargo", "run", *(["--release"] if args.release else []), *([] if args.online else ["--offline"]), "--manifest-path", str(root / "Cargo.toml"), "--", str(args.fixtures.resolve()), str(runtime / "devtools/headless-protocol/response.schema.json"), *(["--stack-queue-only"] if args.stack_queue_only else []), *(["--map-only"] if args.map_only else []), *(["--set-only"] if args.set_only else []), *(["--identity-hashing-only"] if args.identity_hashing_only else []), *(["--math-only"] if args.math_only else []), *(["--random-only"] if args.random_only else []), *(["--generic-contracts-only"] if args.generic_contracts_only else []), *(["--generic-structs-only"] if args.generic_structs_only else []), *(["--list-cursor-only"] if args.list_cursor_only else []), *(["--linked-only"] if args.linked_only else [])], check=True)
+570
View File
@@ -0,0 +1,570 @@
//! Real PBS Stack/Queue qualification against the unchanged production provider.
use super::*;
use prometeu_bytecode::{TRAP_RESOURCE_LIMIT, decode_next, isa::core::CoreOpCode as Op};
use prometeu_vm::{
LogicalFrameEndingReason as End,
resource_budget::{RuntimeLimits, RuntimeResource as Q},
resource_diagnostics::{StorageObject, StorageValue as V},
};
fn load(
root: &std::path::Path,
collection: &str,
name: &str,
suffix: &str,
) -> std::sync::Arc<ValidatedProgramImage> {
let path = root.join(format!("pbs-{collection}-{name}{suffix}.pbx"));
let bytes =
std::fs::read(&path).unwrap_or_else(|e| panic!("mandatory {}: {e}", path.display()));
ValidatedProgramImage::load(
&bytes,
&mut LoadBudget::new(LoadLimits::default()),
caps::NONE,
)
.unwrap_or_else(|e| panic!("{}: {e:?}", path.display()))
}
fn state(
vm: &VirtualMachine,
image: &ValidatedProgramImage,
collection: &str,
) -> Vec<StorageObject> {
let objects = vm.heap().diagnostic_typed_storage();
let name = format!("{collection}<int>");
let owner = objects
.iter()
.find(|o| {
image.registry().declarations().types[o.type_id.0 as usize]
.name
.as_deref()
== Some(&name)
})
.expect("owner")
.clone();
let V::Reference(storage) = owner.groups[0][0] else {
panic!("backing reference")
};
let backing = objects
.iter()
.find(|o| o.reference == storage)
.expect("backing")
.clone();
vec![owner, backing]
}
fn integer(group: &[V]) -> i64 {
let [V::Int64(value)] = group else {
panic!("long field {group:?}")
};
*value
}
fn validate(
vm: &VirtualMachine,
image: &ValidatedProgramImage,
collection: &str,
expected: &[i32],
capacity: usize,
start: usize,
) {
let objects = state(vm, image, collection);
let owner = &objects[0];
let backing = &objects[1];
assert_eq!(backing.groups.len(), capacity);
assert_eq!(
integer(&owner.groups[if collection == "stack" { 1 } else { 2 }]),
expected.len() as i64
);
if collection == "queue" {
assert_eq!(integer(&owner.groups[1]), start as i64);
}
let mut occupied = std::collections::BTreeSet::new();
for (offset, expected) in expected.iter().enumerate() {
let index = (start + offset) % capacity;
occupied.insert(index);
let [V::Int64(_), V::Int32(value)] = backing.groups[index].as_slice() else {
panic!("present complete int group")
};
assert_eq!(value, expected);
}
for (index, group) in backing.groups.iter().enumerate() {
if !occupied.contains(&index) {
assert_eq!(*group, vec![V::Null, V::Null], "inactive slot {index}");
}
}
}
fn release(vm: VirtualMachine) {
let observer = vm.resource_observer();
drop(vm);
for q in [
Q::GuestBytes,
Q::HandleSlots,
Q::AuxiliaryBytes,
Q::TemporaryBytes,
Q::StringBytes,
Q::StringAllocations,
] {
assert_eq!(observer.used(q), 0, "last owner release {q:?}");
}
}
pub(super) fn verify(root: &std::path::Path) {
let successes = [
"basic",
"capacity",
"arithmetic",
"cursor-empty",
"cursor-single",
"snapshot",
"cursor-order",
"groups",
"references",
"native",
"evaluation",
];
let mut cases = 0;
for collection in ["stack", "queue"] {
for (name, fault) in successes
.into_iter()
.map(|n| (n, None))
.chain(
["fault-negative", "fault-too-large", "fault-required"]
.into_iter()
.map(|n| (n, Some(prometeu_bytecode::TRAP_EXPLICIT))),
)
.chain((collection == "queue").then_some(("wrap", None)))
{
for suffix in ["", "-optimized"] {
let image = load(root, collection, name, suffix);
let mut vm = VirtualMachine::from_image(image, Default::default());
vm.prepare_boot_call().unwrap();
let report = vm
.run_budget(20_000_000, &mut NoNative, &mut HostContext::new(None))
.unwrap();
if let Some(expected) = fault {
let End::Trap(info) = report.reason else {
panic!("{collection}/{name}{suffix}: {report:?}")
};
assert_eq!(info.code, expected);
} else {
assert!(
matches!(report.reason, End::Halted | End::EndOfRom),
"{collection}/{name}{suffix}: {report:?}"
);
assert_eq!(
vm.operand_stack_top(1),
vec![Value::Int32(42)],
"{collection}/{name}{suffix}"
);
}
release(vm);
cases += 1;
println!("STACK QUEUE SOURCE PASS {collection}/{name}{suffix}");
}
}
refusals(root, collection);
postwrite_probe(root, collection);
gc(root, collection);
}
distribution(root);
println!("STACK QUEUE MANDATORY BEHAVIOR CASES {cases}");
}
fn marker(image: &ValidatedProgramImage, value: i32) -> usize {
let mut pc = 0;
let mut found = Vec::new();
while pc < image.code().len() {
let i = decode_next(pc, image.code()).unwrap();
if i.opcode == Op::PushI32 && i.imm_i32().unwrap() == value {
found.push(pc);
}
pc = i.next_pc;
}
assert_eq!(found.len(), 1);
found[0]
}
fn refusals(root: &std::path::Path, collection: &str) {
let mut total = 0;
let mut after_writes = 0;
let mut backing_refusal = false;
let mut snapshot_refusal = false;
for name in [
"insert", "growth", "zero", "remove", "clear", "peek", "cursor", "empty",
]
.into_iter()
.chain((collection == "queue").then_some("wrapped"))
{
for suffix in ["", "-optimized"] {
let image = load(root, collection, &format!("refusal-{name}"), suffix);
let before_pc = marker(&image, 314160);
let after_pc = marker(&image, 314161);
let prepare = |limits| {
let mut vm = VirtualMachine::from_image(image.clone(), limits);
vm.prepare_boot_call().unwrap();
vm.insert_breakpoint(before_pc);
vm.insert_breakpoint(after_pc);
vm
};
let mut baseline = prepare(RuntimeLimits::default());
assert!(matches!(
baseline
.run_budget(20_000_000, &mut NoNative, &mut HostContext::new(None))
.unwrap()
.reason,
End::Breakpoint
));
let initial: Vec<i32> = if name == "zero" || name == "empty" {
vec![]
} else if name == "wrapped" {
vec![2, 3, 4, 5]
} else {
vec![0, 1, 2, 3]
};
let old_capacity = if name == "zero" || name == "empty" {
0
} else if name == "growth" || name == "wrapped" {
4
} else {
8
};
validate(
&baseline,
&image,
collection,
&initial,
old_capacity,
if name == "wrapped" { 2 } else { 0 },
);
let old = state(&baseline, &image, collection);
let before = baseline.resource_snapshot();
baseline.remove_breakpoint(before_pc);
let mut successful = Vec::new();
let mut max_arrays = 0;
loop {
max_arrays = max_arrays.max(
baseline
.heap()
.diagnostic_typed_storage()
.iter()
.filter(|o| {
matches!(
image.registry().declarations().types[o.type_id.0 as usize].kind,
prometeu_bytecode::registry::TypeKind::Array(_)
)
})
.count(),
);
successful.push((baseline.pc(), observe_originals(&baseline, &old)));
let report = baseline
.run_budget(1, &mut NoNative, &mut HostContext::new(None))
.unwrap();
if baseline.pc() == after_pc {
break;
}
assert!(
matches!(report.reason, End::BudgetExhausted),
"{collection}/{name}: {report:?}"
);
assert!(successful.len() < 200_000);
}
let after = baseline.resource_snapshot();
let mut expected = initial.clone();
match name {
"insert" | "growth" | "zero" | "wrapped" => expected.push(42),
"remove" => {
if collection == "stack" {
expected.pop();
} else {
expected.remove(0);
}
}
"clear" => expected.clear(),
_ => (),
}
let capacity = match name {
"zero" => 1,
"growth" | "wrapped" => 6,
_ => old_capacity,
};
validate(
&baseline,
&image,
collection,
&expected,
capacity,
if collection == "queue" && name == "remove" {
1
} else {
0
},
);
if ["growth", "zero", "wrapped"].contains(&name) {
assert!(max_arrays >= 2, "old/candidate coexistence");
} else {
assert_eq!(
max_arrays, 1,
"ordinary update/capture never reconstructs backing"
);
}
if ["peek", "cursor", "empty"].contains(&name) {
assert_eq!(state(&baseline, &image, collection), old);
}
println!(
"STACK QUEUE PEAK {collection}/{name}{suffix} arrays={max_arrays} before={:?} after={:?}",
before.budget.peaks, after.budget.peaks
);
let mut count = 0;
let mut partial = 0;
for q in [
Q::GuestBytes,
Q::HandleSlots,
Q::AuxiliaryBytes,
Q::TemporaryBytes,
Q::CallDepth,
] {
let lower = before.budget.peaks[q as usize];
let upper = after.budget.peaks[q as usize];
if lower >= upper {
continue;
}
let mut limits = vec![lower, lower + (upper - lower) / 2, upper - 1];
if q == Q::HandleSlots {
limits.extend(lower..upper.min(lower + 24));
}
limits.sort_unstable();
limits.dedup();
for limit in limits {
let mut vm = prepare(RuntimeLimits::default().lowered(q, limit).unwrap());
assert!(
matches!(
vm.run_budget(20_000_000, &mut NoNative, &mut HostContext::new(None))
.unwrap()
.reason,
End::Breakpoint
),
"{collection}/{name}/{q:?}={limit} setup"
);
let original = state(&vm, &image, collection);
vm.remove_breakpoint(before_pc);
let (report, prefix, mutated) =
trace_collection_attempt(&mut vm, &original, after_pc);
assert_mutation_prefix(&prefix, &successful);
if let End::Trap(info) = report.reason {
assert_eq!(info.code, TRAP_RESOURCE_LIMIT);
let current = observe_originals(&vm, &original);
if !mutated {
assert_eq!(
current, original,
"before first write preserves full original state"
);
}
if ["peek", "cursor", "empty"].contains(&name) {
assert_eq!(current, original);
}
let instruction = decode_next(info.pc as usize, image.code()).unwrap();
backing_refusal |= instruction.opcode == Op::ArrayNew;
if instruction.opcode == Op::StructNew {
snapshot_refusal |= image.registry().declarations().types
[instruction.imm_u32().unwrap() as usize]
.name
.as_deref()
== Some("_SnapshotNode<int>");
}
count += 1;
partial += usize::from(mutated);
println!(
"STACK QUEUE REFUSAL {collection}/{name}{suffix} mutated={mutated} resource={q:?} limit={limit} opcode={:?}",
instruction.opcode
);
} else {
assert!(
matches!(report.reason, End::BudgetExhausted | End::Breakpoint)
&& vm.pc() == after_pc
);
}
release(vm);
}
}
assert!(
count > 0,
"{collection}/{name}: operation-specific natural refusal required"
);
total += count;
after_writes += partial;
println!(
"STACK QUEUE PHASE SUMMARY {collection}/{name}{suffix} refusals={count} after_write={partial}"
);
}
}
assert!(
backing_refusal && snapshot_refusal,
"backing and snapshot preparation refusals required"
);
println!("STACK QUEUE NATURAL REFUSALS {collection} total={total} after_write={after_writes}");
}
fn postwrite_probe(root: &std::path::Path, collection: &str) {
// Separate test-only instrumentation: not natural failure frequency evidence.
for suffix in ["", "-optimized"] {
let image = load(root, collection, "injected-growth", suffix);
let mut vm = VirtualMachine::from_image(
image.clone(),
RuntimeLimits::default()
.lowered(Q::GuestBytes, 500_000)
.unwrap(),
);
vm.prepare_boot_call().unwrap();
let mut found = false;
for _ in 0..100_000 {
let instruction = decode_next(vm.pc(), image.code()).unwrap();
if instruction.opcode == Op::ArrayNew
&& vm.operand_stack_top(1) == vec![Value::Int64(1_000_000)]
{
let original = vm.heap().diagnostic_typed_storage();
let objects = state(&vm, &image, collection);
assert_eq!(
integer(&objects[0].groups[if collection == "stack" { 1 } else { 2 }]),
2
);
assert_eq!(objects[1].groups.len(), 3);
assert!(matches!(
objects[1].groups[2].as_slice(),
[V::Int64(_), V::Int32(42)]
));
let operands = vm.operand_stack_top(1).to_vec();
let report = vm
.run_budget(1, &mut NoNative, &mut HostContext::new(None))
.unwrap();
let End::Trap(info) = report.reason else {
panic!("post-write probe: {report:?}")
};
assert_eq!(info.code, TRAP_RESOURCE_LIMIT);
assert_eq!(vm.heap().diagnostic_typed_storage(), original);
assert_eq!(vm.operand_stack_top(1), operands);
println!(
"STACK QUEUE TEST-ONLY POST-WRITE PASS {collection}{suffix}: backing=3 old size=2 appended=42 retained"
);
found = true;
break;
}
let report = vm
.run_budget(1, &mut NoNative, &mut HostContext::new(None))
.unwrap();
assert!(matches!(report.reason, End::BudgetExhausted));
}
assert!(found);
release(vm);
}
}
fn gc(root: &std::path::Path, collection: &str) {
for suffix in ["", "-optimized"] {
for (name, counts) in [
("gc-snapshot", vec![1200, 1, 1, 0]),
("gc-collection", vec![64, 61, 0, 1, 0]),
] {
let image = load(root, collection, name, suffix);
let mut vm = VirtualMachine::from_image(image.clone(), Default::default());
vm.prepare_boot_call().unwrap();
let mut previous = 0;
for (round, count) in counts.into_iter().enumerate() {
let report = vm
.run_budget(100_000_000, &mut NoNative, &mut HostContext::new(None))
.unwrap();
assert!(
matches!(report.reason, End::FrameSync),
"{collection}/{name}/{round}: {report:?}"
);
let collections = vm.resource_snapshot().gc.collections;
assert!(
collections > previous,
"actual collection, not only safepoint"
);
previous = collections;
let objects = vm.heap().diagnostic_typed_storage();
let named = |n: &str| {
objects
.iter()
.filter(|o| {
image.registry().declarations().types[o.type_id.0 as usize]
.name
.as_deref()
== Some(n)
})
.count()
};
assert_eq!(
named("Item"),
count,
"{collection}/{name}/{round}: payload roots"
);
let arrays = objects
.iter()
.filter(|o| {
matches!(
image.registry().declarations().types[o.type_id.0 as usize].kind,
prometeu_bytecode::registry::TypeKind::Array(_)
)
})
.count();
if name == "gc-snapshot" {
assert_eq!(named("_SnapshotNode<Item>"), count);
assert_eq!(arrays, 0, "snapshot retains no source backing");
} else {
assert_eq!(
arrays,
usize::from(round < 4),
"only retained backing, no replaced arrays"
);
assert_eq!(named("_SnapshotNode<Item>"), 0);
}
println!(
"STACK QUEUE GC PASS {collection}/{name}{suffix} round={round} items={count} arrays={arrays}"
);
}
let report = vm
.run_budget(100_000, &mut NoNative, &mut HostContext::new(None))
.unwrap();
assert!(matches!(report.reason, End::Halted | End::EndOfRom));
assert_eq!(vm.operand_stack_top(1), vec![Value::Int32(42)]);
release(vm);
}
}
}
fn distribution(root: &std::path::Path) {
for name in ["imports", "installed"] {
let image = load(root, "stack-queue", name, "");
let mut vm = VirtualMachine::from_image(image.clone(), Default::default());
vm.prepare_boot_call().unwrap();
let report = vm
.run_budget(2_000_000, &mut NoNative, &mut HostContext::new(None))
.unwrap();
assert!(
matches!(report.reason, End::FrameSync | End::Halted | End::EndOfRom),
"{name}: {report:?}"
);
let objects = vm.heap().diagnostic_typed_storage();
let get = |reference| objects.iter().find(|o| o.reference == reference).unwrap();
let mut lasts = Vec::new();
for cursor in objects.iter().filter(|o| {
image.registry().declarations().types[o.type_id.0 as usize]
.name
.as_deref()
== Some("_SnapshotCursor<int>")
}) {
let V::Reference(carrier) = cursor.groups[0][0] else {
panic!("current carrier")
};
let V::Reference(node) = get(carrier).groups[0][0] else {
panic!("node")
};
let node = get(node);
assert_eq!(node.groups[1], vec![V::Null], "completed traversal");
let V::Int32(value) = node.groups[0][0] else {
panic!("value")
};
lasts.push(value);
}
lasts.sort_unstable();
assert_eq!(
lasts,
vec![20, 22],
"both order-sensitive snapshots traversed"
);
release(vm);
println!("STACK QUEUE DISTRIBUTION PASS {name}");
}
}