Files
prometeu-studio/docs/compiler/pbs/specs/sdk-stack-and-queue.md
T

7.7 KiB

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, generic structs and List/shared Cursor.

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, 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.