diff --git a/discussion/lessons/DSC-0091-pbs-sdk-linked/LSN-0091-private-linked-nodes-and-atomic-publication.md b/discussion/lessons/DSC-0091-pbs-sdk-linked/LSN-0091-private-linked-nodes-and-atomic-publication.md new file mode 100644 index 00000000..a0ace1e1 --- /dev/null +++ b/discussion/lessons/DSC-0091-pbs-sdk-linked/LSN-0091-private-linked-nodes-and-atomic-publication.md @@ -0,0 +1,223 @@ +--- +id: LSN-0091 +ticket: pbs-sdk-linked +title: Private Linked Nodes and Atomic Publication +created: 2026-10-23 +tags: [compiler-pbs, collections, snapshot-cursor, atomic-publication, runtime-conformance] +--- + +## Original problem and final result + +Owner: `compiler/pbs`. Transversal owners: `compiler/general` for neutral IR/PBX +and the provider for typed storage, faults, ownership, GC and resource accounting. +DSC-0091 executed accepted DEC-0076 through PLN-0154, covering R1–R12. Their +workflow control artifacts are disposable; the [Linked specification](../../../docs/compiler/pbs/specs/sdk-linked-and-cursor.md) +is the durable normative reference. + +PBS needed a dense sequence with private doubly linked nodes and useful end +operations, while preserving the shared snapshot traversal already delivered for +List. `linked` now supplies that sequence through executable SDK source. +Forward and reverse captures both return the existing Cursor contract. A +neutral FIELDS_PUBLISH operation provides complete publication across the collection +and its neighbors, without moving node algorithms into the VM. + +The selected provider is clean commit `57992cf214e8a5f9de53a40dba9aaa7fab038c91`. +Studio changes were qualified over base `c410e3500150de5e6d55c1da8f9b22076ca84251`. +[Machine-readable evidence](runtime-conformance-evidence.json) records source/PBX +hashes, commands, configuration, lowered refusal limits and observed GC states. + +## Dense positions do not change the optional API + +A Linked contains one present value per private node. Its size counts nodes; +capacity, holes, reserve, trim, resize and clearAt do not exist. Valid indexed +reads/removals return a present optional, and invalid indices fault even when +empty. First/last and their removal operations return none for an empty collection. +This preserves the accepted API rather than changing return types because a +particular representation cannot contain holes. + +Construction is empty and takes no capacity. Explicit and contextual applications +follow the existing generic struct rules. Directly optional elements are rejected, +including through grouping, just as in Array/List. An optional collection and an +otherwise valid element containing optional fields remain valid. + +The executable API includes size, first/last, bracket read/write, add/addFirst, +insert, removeAt/removeFirst/removeLast, clear and both capture methods. Adding +appends, while addFirst prepends. Replacement preserves size; insertion/removal +changes following logical indices. Read/replace/remove require an index below +size; insert also accepts size. Long indices are not truncated, int arguments have +the same localized lossless promotion as List, and growth is checked before signed +long overflow without inheriting Array's structural size maximum. + +Preserving inserted object identity is separate from choosing a comparison policy. +There is no remove(value), generic equality or uniqueness rule in this delivery. +Repeated occurrences, including repeated references to one instance, remain +independent sequence positions. List similarly leaves value search/removal outside +its current contract. + +## Keep collection topology separate from traversal topology + +Linked nodes have reciprocal previous/next links. The SDK locates indexed values +from the nearer end, so search remains O(n) in the worst case; end operations do +not search. A constant number of link updates does not make indexed access O(1). + +Snapshot nodes are different objects: private immutable singly linked nodes with +no circular links or editable source association. Forward capture walks Linked +backwards and prepends; reverse capture walks it forwards and prepends. Both cost +O(n) work and additional nodes, and both finish before returning a Cursor. + +For a source `[20, 22]`, forward starts at 20 and reverse starts at 22. Replacing +source values, removing elements or clearing the collection cannot change either +captured sequence. Referenced objects remain shared, so later field mutations +remain visible. Snapshots preserve occurrences and object identity, not deep copies. + +The existing state table remains the only traversal protocol: + +| State | hasNext() | current() | next() | +| --- | --- | --- | --- | +| Empty | false | none | No change | +| Current node has a successor | true | Present current value | Follow successor | +| Last node, including a singleton | false | Present final value | No change | + +Process current before testing whether to advance. A hasNext-only loop omits the +last element; waiting for current to become absent never finishes a nonempty +snapshot. There is no removal/reset through Cursor. + +The [distributed example](../../../prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/pbs-knowledge/examples/game/1/src/linked.pbs) +captures both orders, then replaces a source element and clears Linked. Both +traversals still sum to 42, retaining final values 22 and 20 respectively. + +## Prepare every object before changing any object + +Insertion can update the collection's head/tail/size and two existing neighbors. +Removal also prepares the returned optional value. Separate successful field +stores are insufficient: a later allocation or frame/operand refusal could leave +half of a neighbor pair updated. + +The existing range-based STORAGE_PUBLISH operation covered an Array and two +fields of one owner. Its guarantee did not automatically extend to Linked. +The new generic FIELDS_PUBLISH uses a normal Struct TypeId as a schema: each +schema field names one destination Struct type. The stack supplies each nullable +destination followed by all its complete field groups. No request object, new +Registry category or public preparation token is needed. + +All non-null destinations must have the exact concrete type and live provenance. +All supplied value groups are validated, including those paired with a null +(skipped) destination. The original operands stay rooted and unconsumed until the +whole attempt is admitted. The VM then commits in schema order without allocation, +validation, callbacks or GC/scheduler interleaving, and consumes the operands. +Repeated destinations have ordered last-write semantics using pre-captured inputs. + +The SDK selects topology and values. It allocates and initializes a private +candidate node before publishing an insertion. Removal prepares its optional +result first. Private helper bindings lower those source-selected values to the +neutral operation. A refusal preserves the old roots, size, values and reciprocal +links; already evaluated caller argument effects remain ordinary source effects. + +Publication itself needs no heap object or scratch. This does not make a source +mutation allocation-free: optional carriers, candidate nodes, packing and call +preparation still have their normal costs. Provider tests execute publication at +already exhausted allocation ceilings, preserve native String/reference identity +and multi-slot groups, and reject a late invalid group before every shared write. + +## GC proofs require an actual collection, not only a safepoint + +Removal disconnects a node from the collection. Clear removes the collection's +roots to the whole chain. Unreachable double-link cycles are handled by the normal +tracing collector; neither operation promises immediate collection or quota return. +A retained snapshot owns captured values through its own nodes and does not need +the editable Linked nodes. + +A controlled fixture uses normal GC safepoints and independent non-owning storage +observations. With no snapshot, nodes and payloads fall from 1,200 to 1,197 after +three removals, then to zero after clear. A second fixture clears the source while +retaining its snapshot: original Linked nodes disappear, captured nodes/items go +from 1,200/1,200 to 1/1 after traversal, stay at 1/1 after repeated next, and reach +0/0 after the final Cursor owner is dropped. + +A safepoint alone does not force this collector to run. The removal/clear fixture +therefore creates ordinary garbage pressure and asserts that the collection +counter advances at each observed round. Without that check, a test can mistake +an uncollected unreachable node for a retention bug. The observer introduces no +guest root or mutation. + +## Compiler, tooling and distribution + +Linked reuses ordinary generic specialization, methods, field groups and imports. +Origin-checked SDK metadata adds constructor/index integration and the same +localized int-to-long argument promotion as List. User homonyms or copied +attributes do not acquire those privileges. + +Public projections show concrete Linked methods, optional results and source SDK +locations. They hide head/tail/length, private nodes and storage adapters, including +the internal nearest-end lookup method. Negative workspace cases reject optional +elements, capacity construction, unsupported APIs and private access. Invalid +constructor selection now reports diagnostics instead of throwing from lowering. + +The normative English spec and example ship with installed knowledge. An isolated +installDist JVM, outside the checkout, loads the actual JAR resources and compiles +the Linked example. The production harness executes its emitted PBX and observes +both completed traversals. Imports/reexports are qualified separately. + +The full harness also needed its original scalar/input corpus selector to exclude +the new Linked fixture prefix. Linked cases remain mandatory in their dedicated +validator; they are not silently treated as older scalar fixtures or skipped. + +## Qualification and limits + +| Gate | Observed result | +| --- | --- | +| Full Studio regression | 1,030 tests; no failures/errors; 13 existing skips | +| Installed knowledge | Both tests passed, including standalone Linked PBX generation | +| Provider bytecode/VM libraries | 6 + 305 passed; 2 existing measurement tests ignored | +| Linked source to production VM | 26 cases in each producer mode: 52 passed | +| Neutral storage/publication | Four common-IR fixtures executed, including ordinary/optimized FIELDS_PUBLISH | +| Whole-operation refusals | 231; all ten mutation/capture boundaries preserved previous source state | +| Linked removal/clear GC | 1,200 → 1,197 → 0 → 0 nodes and payloads | +| Snapshot GC | 1,200 → 1 → 1 → 0 captured nodes/payloads, with no retained Linked topology | +| Imports/installed traversal | Passed; installed forward/reverse final values 22/20 | +| Catalogs and canonical mirrors | Clean selected provider; catalog/exporter parity and all four mirrors match | + +The refusal matrix observed GuestBytes, HandleSlots and AuxiliaryBytes refusals. +TemporaryBytes was checked against the measured setup/success peaks; no additional +peak required a lowered refusal case in this Linked corpus. FIELDS_PUBLISH has no +scratch allocation, and the direct provider test proves publication succeeds with +TemporaryBytes already capped at current usage. This is not a claim that general +source preparation never needs temporary resources. + +Qualification used macOS 27.0.1 arm64, Rust 1.98.1/LLVM 22.1.8, the dev runtime +profile with resource-diagnostics, capabilities NONE, Gradle 9.3.1 and the Java 21 +toolchain; the installed JVM was Corretto 21.0.4. No release or cross-platform claim +is made. Two pre-existing full-harness response-schema gaps, LifecycleRole and +NonFiniteValue, remain explicitly reported with original payloads. + +## Pitfalls to preserve + +- Do not implement a multi-object mutation as a sequence of fallible stores. +- Prepare the optional removed-value carrier before publishing the removal. +- Preserve every field group and native/reference identity, including unchanged + payloads when updating neighbor links. +- Never expose source nodes to support traversal. Snapshot and collection links + have different mutability and lifetime responsibilities. +- Keep optional results despite dense positions, and faults distinct from absence. +- Keep private SDK authority tied to origin through aliases and specialization. +- Check GC collection counters when asserting reclamation at a safepoint. +- Record clean provider provenance, explicit lowered limits and mandatory fixture + counts; metadata defaults or small unit tests alone do not qualify execution. + +## References and reproduction + +- [Linked specification](../../../docs/compiler/pbs/specs/sdk-linked-and-cursor.md), + [List/shared Cursor](../../../docs/compiler/pbs/specs/sdk-list-and-cursor.md), + [generic structs](../../../docs/compiler/pbs/specs/generic-structs-and-free-functions.md) + and [generic Registry/PBX publication](../../../docs/compiler/general/specs/typed-registry-and-pbx-v0.md). +- [SDK source](../../../prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/sdk/collections/main.pbs), + [source corpus](../../../prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsLinkedTest.java), + [neutral producer](../../../prometeu-compiler/prometeu-build-pipeline/src/test/java/p/studio/compiler/backend/registry/StoragePublicationPipelineTest.java) + and [production harness instructions](../../../tools/pbx-conformance/README.md). +- [Provider publication implementation](../../../../runtime/crates/console/prometeu-vm/src/virtual_machine/storage_publication.rs) + and [previous List/Cursor lesson](../DSC-0090-pbs-sdk-list/LSN-0090-mutable-lists-and-stable-snapshot-cursors.md). + +Run `./gradlew test :prometeu-app:installedKnowledgeTest --console=plain`, followed +by `python3 tools/pbx-conformance/run.py --runtime ../runtime`, after selecting the +recorded provider. The evidence file retains command/configuration details and +R1–R12 traceability after removal of the completed workflow controls. diff --git a/discussion/lessons/DSC-0091-pbs-sdk-linked/runtime-conformance-evidence.json b/discussion/lessons/DSC-0091-pbs-sdk-linked/runtime-conformance-evidence.json new file mode 100644 index 00000000..b60dd62a --- /dev/null +++ b/discussion/lessons/DSC-0091-pbs-sdk-linked/runtime-conformance-evidence.json @@ -0,0 +1,1752 @@ +{ + "schema_version": 1, + "discussion": "DSC-0091", + "historical_decision": "DEC-0076", + "historical_plan": "PLN-0154", + "owner": "compiler/pbs", + "date": "2026-10-23", + "provenance": { + "studio_base": "c410e3500150de5e6d55c1da8f9b22076ca84251", + "studio_changes": "uncommitted implementation", + "runtime": "57992cf214e8a5f9de53a40dba9aaa7fab038c91", + "runtime_working_tree": "clean", + "runtime_base": "d9b9eeb171d2861ec660d4cf5703b0795eac49a9", + "platform": "macOS-27.0.1-arm64-arm-64bit-Mach-O", + "rustc": "1.98.1 (48a229cea 2026-09-01)", + "rust_host": "aarch64-apple-darwin", + "llvm": "22.1.8", + "gradle": "9.3.1", + "java_toolchain": 21, + "installed_java": "Corretto 21.0.4+7-LTS", + "runtime_profile": "dev", + "features": [ + "resource-diagnostics" + ], + "capabilities": "NONE", + "producer_modes": [ + "ordinary", + "optimized" + ] + }, + "default_vm_limits": { + "GuestBytes": 268435456, + "HandleSlots": 1048576, + "AuxiliaryBytes": 67108864, + "TemporaryBytes": 67108864, + "StringBytes": 67108864, + "StringAllocations": 262144, + "IndividualStringBytes": 4194304, + "CallDepth": 1024 + }, + "source_sha256": { + "tools/pbx-conformance/run.py": "485d4981854b51f450b2e99ef69fb730a036266b1f2e07bc994a6279c31acd44", + "tools/pbx-conformance/main.rs": "1718ac79085f7ae6ba3704a5ceb1363ca75df69c36b0932978b1a3b58ccd2029", + "prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsLinkedTest.java": "0e3378ea1e09a1182c0d8e15ed6ac555e3bf2e4fdf4049b80bd5ddaecc4b4537", + "prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsListCursorTest.java": "491b990797d1d0c16322cf2410b57cb1af9942f0a4cc7b5e6c6f6029b8deaf96", + "prometeu-compiler/prometeu-build-pipeline/src/test/java/p/studio/compiler/backend/registry/StoragePublicationPipelineTest.java": "fb9642b1a8c5c42ec76dbea39934aeed152aecd3e9dcb7c28c3799a1959fdc1f", + "prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/sdk/collections/main.pbs": "255a7beb2db212edf7c26f1c88f261faccc1f8b4f348f937f8ff5726f58fae8f", + "prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/sdk/collections/mod.barrel": "3045e177baffdce62287a29cbe1d5097cd18d83d3c4cdbd666209e1967399ddc", + "prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/pbs-knowledge/examples/game/1/src/linked.pbs": "061d9f67c7b01bec16d6b60eee68ec023bdd6478cc1bbbeda0c83c914f040550", + "docs/compiler/pbs/specs/sdk-linked-and-cursor.md": "0109ff880019e1811a35cc6047b25f071573e507e8194320b051ab33c859ac4a", + "docs/compiler/pbs/specs/sdk-list-and-cursor.md": "4a9539de4c56df7560f83583c4dd83be4e76d6496d16e2099cbe087f316ed86b", + "docs/compiler/general/specs/typed-registry-and-pbx-v0.md": "344054053e5f5e3a758b18f5437bb6391c853bef375a64471cc57cf77c9c22b4", + "docs/vm-arch/runtime-catalog.properties": "f3d643e84290de8c560e31ccbf80a66c36e0567d26f95d54d087b2a8091ec019", + "../runtime/crates/console/prometeu-bytecode/src/assembler.rs": "e25a9a9208539dd47920f37812481cf9c1567d7c8b1abf8233d911c3e0bd8726", + "../runtime/crates/console/prometeu-bytecode/src/disassembler.rs": "4400b2855a0042ac563c268367e66405953718d30f34e9052a922f63637a32cf", + "../runtime/crates/console/prometeu-bytecode/src/opcode.rs": "d0e8ad35fa62fae7adca80c5bdc20678cbe10899bebc76e97af2c53e75055500", + "../runtime/crates/console/prometeu-bytecode/src/opcode_spec.rs": "109b25a97cf5ad3b106352f72840834d2893dc479ed8e264731a401dbd5eb48f", + "../runtime/crates/console/prometeu-bytecode/src/registry_instruction.rs": "91bf928d74ba00cf09f055bcb718e7139f826d8e3188fa667c1379cdd51c9a90", + "../runtime/crates/console/prometeu-vm/src/registry_verifier.rs": "73f983bd114d1e0e0a1b64f58ea43d95168eb674ca26440f8091bded54ad01a8", + "../runtime/crates/console/prometeu-vm/src/registry_verifier/types.rs": "6bf1f9dd405032efd0cb0275bbef80c314b79625ec420590a54006499912e866", + "../runtime/crates/console/prometeu-vm/src/virtual_machine.rs": "9ff8cf6ab05e3f707f6f0dad1cdfe4588b767a7c7b6358ba5e2b01f4098ccc9e", + "../runtime/crates/console/prometeu-vm/src/virtual_machine/storage_publication.rs": "99cdb1953ee3b05300a28cdf89392f9402fd9452ed529bd0c87ff29d3726462f", + "../runtime/crates/console/prometeu-vm/src/virtual_machine/storage_publication_tests.rs": "3dde298415133b1959555d53f68555043c0916a33f1b724d70a61982198e03a1", + "../runtime/docs/specs/runtime/02-vm-instruction-set.md": "725671286cc2eddb72a0302e87dbb96f8510acc8b1738fb97a0505eba8f62828", + "../runtime/docs/vm-arch/ARCHITECTURE.md": "774992e8b7d42e8750bb87ece50183719dd90b28f78120190a4b7ace65c938c9", + "../runtime/docs/vm-arch/ISA_CORE.md": "26292e6ab63b8ece09e57b82ca21ad7e1a2d2f7c8af169dd1ea328b667a91512" + }, + "canonical_mirror_sha256": { + "ARCHITECTURE.md": "774992e8b7d42e8750bb87ece50183719dd90b28f78120190a4b7ace65c938c9", + "ISA_CORE.md": "26292e6ab63b8ece09e57b82ca21ad7e1a2d2f7c8af169dd1ea328b667a91512", + "INTRINSICS.csv": "0c1bb78a9b81d1e3480ef5713f3d70f0b06772a7dfab2fd00c1f0a6364f98daa", + "BUILTIN_CONSTANTS.csv": "e407e4718127aa7ef7b1097b5b4b67d86dd979235e73a551a7c36b628cddc039" + }, + "pbx_sha256": { + "common-fields-optimized.pbx": "a7f71d70478875c52cd7eefa890d54568cbf5df44d00c5ed688a007ca1a8c53b", + "common-fields.pbx": "a7f71d70478875c52cd7eefa890d54568cbf5df44d00c5ed688a007ca1a8c53b", + "common-storage-optimized.pbx": "2820aa4ab46544e719e73dfce7e2c03b36377399e5f12e44f32d1f3020bbd087", + "common-storage.pbx": "2820aa4ab46544e719e73dfce7e2c03b36377399e5f12e44f32d1f3020bbd087", + "pbs-linked-basic-optimized.pbx": "2be13b88996d5e610fd71f6912a0977ad7be53890875e0e82796537f6cd1ce92", + "pbs-linked-basic.pbx": "8e1d3abe73b961e0a5c34b11bba9883b47afe8225b6c4268f3b0bea0d8c26e59", + "pbs-linked-construction-optimized.pbx": "b43e79cfbbf6da7321e9cc9d751081824cb0a61c854349dd029ae3869e11c034", + "pbs-linked-construction.pbx": "dc5677b1e09e59173c990816300e7f716820900ec93c9a4d0bbaadfe666d2013", + "pbs-linked-contract-optimized.pbx": "0ef40d166b1a7efbf6a20b31b1d4bfcc2a8694ed917dfbbbd2bca16735bef1d4", + "pbs-linked-contract.pbx": "a793e3abe16e200ea8d2bf4ff7212226bf6020ffcc5cab936ffaede294358bc0", + "pbs-linked-empty-cursor-optimized.pbx": "bcf25b8322cd6388b2f9d26c7f856e53842bc791ba1a5fc94d6e064186074f68", + "pbs-linked-empty-cursor.pbx": "fe2b06440d7286231efb1580020bd8d85a06726c38103b8e61070c5158ae5d63", + "pbs-linked-empty-reverseCursor-optimized.pbx": "2de99facd606c034e78c8b9d623889d591e9dd8fe07c7f0f6fe6d9ebda2e1603", + "pbs-linked-empty-reverseCursor.pbx": "1d674d0cfcf9ef7ddf3f32b83ccde03a4bd6dbbf2f3ddf00a433f223883df1f6", + "pbs-linked-evaluation-optimized.pbx": "ff81478be599442b05b4a916a3f2ef2230e2f9adb16529225aa0292de72e4764", + "pbs-linked-evaluation.pbx": "c0397c829ba271c2e40da8a3e84501e1b64f83f80fc682c2a3cfc33f5699a4c7", + "pbs-linked-false-present-optimized.pbx": "bedde7f2fc134c707aeda288c0ad23d688fffd1496c2b79cf7d076f40ec388d2", + "pbs-linked-false-present.pbx": "ebd5ae21fd687e93949f6abd8aae84a77ce98f44f9cc535c048f0913b8b7f27a", + "pbs-linked-fault-insert-optimized.pbx": "a5fa4f468ccd0e3d52237e01c980a61039b7abad01dd0b3214ee66ce8cd7b47a", + "pbs-linked-fault-insert.pbx": "ebaecdd62c7cc504a9942f8d5a1a52d7bc19c22b2254cfa80635b2a52bb8bc17", + "pbs-linked-fault-long-index-optimized.pbx": "c7b341191b33f333c12d2825363054852479fb0dd1bd4a2bf33170068693b321", + "pbs-linked-fault-long-index.pbx": "a614653a2c6379ba663c52dfc3395ae5debc0212a8cf491b3b7c8b232d386925", + "pbs-linked-fault-negative-optimized.pbx": "70bf6e2fce43cfaa7b085a359c417fa6e1ac5f198452a010dfb816f48a18bd2c", + "pbs-linked-fault-negative.pbx": "f8d11951105aec97d8e581491fbd359dd563245c2c1d6b950007a7138c1b096f", + "pbs-linked-fault-overflow-optimized.pbx": "676b70ac9c692737869ca051a0dadf262d559a3c69686f9720ea702164258360", + "pbs-linked-fault-overflow.pbx": "b9a1623b5be02d642312b783bc2c82dcc678964a2816c0d55b69b609abcdbf9e", + "pbs-linked-fault-read-optimized.pbx": "109afbec81ec824945420779c5933d5c56a53ab90f5c4daffe4807dac613c773", + "pbs-linked-fault-read.pbx": "eddfa0874dccdebd67ac57f0a36e0f12b479335be9bf431f1cc632a1279f96ea", + "pbs-linked-fault-remove-optimized.pbx": "7c5e8c1dfd72f532279f080c0e9fe0217525c3212713e9e35fd2cd0cc295b279", + "pbs-linked-fault-remove.pbx": "47950af507a93a96fe4b499292b4afa28ac3e8ce2cb63fdf71b028f6f2486904", + "pbs-linked-fault-write-optimized.pbx": "beae150b43275ffc380944812afa296c4a796214f7d43c3f36b6692d1f628b89", + "pbs-linked-fault-write.pbx": "831973b3ed035a7454712db94d020df4c21b10844c3264010f9c1ec7c8fa1630", + "pbs-linked-function-optimized.pbx": "b21b0e03cc816ee78dd7f5cda7ea3bb074e20fc040523263d3905ae3286358b4", + "pbs-linked-function.pbx": "6be395698c731ae7511cad681320118c94b7ef1140a09e599e669967a8b329d9", + "pbs-linked-gc-collection.pbx": "ceb0b3b07a4ddc9a7c849cd18e16a65fbd94a82c0879eb055791a52fd10a440b", + "pbs-linked-gc.pbx": "0c988bb23f988befc97f03f5ccad4b72254e3115d0a91bfea48f60fa282f271c", + "pbs-linked-identity-optimized.pbx": "e80818d1a5a15ab0c77655f886a94a2be4e5a37a28c07e43bc47b45f575dfeb4", + "pbs-linked-identity.pbx": "89982b2934e64535916620b4b148b7468d29c39a0f77267239a1850542212839", + "pbs-linked-imports.pbx": "71e50e920f3e776dfac6140fa3b31db629e23501f5870465d6c7ad84bf198f7f", + "pbs-linked-installed.pbx": "fba1bf80dfbc218287f2aecff41d21092c3b7737d449da119854e79dc207cf1a", + "pbs-linked-links-optimized.pbx": "a5d8ff6d8ffb6a7768d3bcb985a6fc5f5bd1af706382ecbf7ddfd0e6f962266f", + "pbs-linked-links.pbx": "d2c2f9af267c997c1b0497f9e2a034868b204337af4157bd17150aae2b2524d0", + "pbs-linked-long-size-optimized.pbx": "42360e169c21e4a8d947f093ece8117e24c063bcb50f0d33b0d072e16bc41503", + "pbs-linked-long-size.pbx": "55f451233fd85021fe75d38f729cea9ebcc6c50078200def8ee7b77a3ebb2d4d", + "pbs-linked-nested-array-optimized.pbx": "0420d6144905b4856af80bc4beaaae87ea39ba78c2b1c74187fb95aeb3b49a86", + "pbs-linked-nested-array.pbx": "6a35ae62b22d2b9f974521cfdda0a5de8108fb447750ed0e196b65cd3eb38061", + "pbs-linked-optional-field-optimized.pbx": "b6da326a5830fa811d96b15e589f36b0d189299a98ba2b1cc7aded6af7085fa1", + "pbs-linked-optional-field.pbx": "b5e849c6213c1da745f55af1be70e8315ed68b19782b98663e0a1999c1b77e4a", + "pbs-linked-pixel-optimized.pbx": "3fabbcb8ec3a5eb2492df6fc310e4f741c62b619335b665516b6822bc062e47a", + "pbs-linked-pixel.pbx": "228bf78fc440bc653b0bd7c83b25ffd4354319dc1f0f07b0ef857455b50778f5", + "pbs-linked-refusal-add.pbx": "b94613042de7758b208554856ca5ec1ba8b2bfce157f5aafad4c150c6e36ef2a", + "pbs-linked-refusal-addFirst.pbx": "c54c617139e37403b68cfe938d6fbc1b349cad83c1e5dc6484920af11d1e6c8b", + "pbs-linked-refusal-clear.pbx": "d1cf7b699d1ca03876a836a571195d6cf75c2ffdc14f96e99c165a3a02d9d0b4", + "pbs-linked-refusal-cursor.pbx": "d3c40728b658e29bad8ee06f3da88241572723dd943f6867f19b886e7f12f091", + "pbs-linked-refusal-insert.pbx": "64f8a1d16be362422f8ea8fbf2a3e7710ae782a5d9c5458869b42e90082cf2ce", + "pbs-linked-refusal-remove.pbx": "a915e88d034db27f11f930f4175e48caa9921df8fc3d1f89312c63f13c3f6027", + "pbs-linked-refusal-removeFirst.pbx": "fd9034b4765257c3727ff67ae7bf0229fc048e878a0a07424efcb2eb5c4d1ac1", + "pbs-linked-refusal-removeLast.pbx": "b6bf6715fe6384bc142ba1f69923cfcf8ad183c26b140892058f72a8a77f00c6", + "pbs-linked-refusal-replace.pbx": "c9a8f40ed5b57b08f53e6b83c43bb40cb0fb1e2e49f7be41bfe2a4f2b342e554", + "pbs-linked-refusal-reverseCursor.pbx": "b4db990f22c4fa8d8da5304249200515fe02bbebcc9cd9443373de66b5c2fadb", + "pbs-linked-single-cursor-optimized.pbx": "2f98a00f84f5106293bdc3cbe572c05cff1f5197449db328d131b341c419ab11", + "pbs-linked-single-cursor.pbx": "c1ab79b30bd8642a0f041f1f8986155ca8ae2050b81c90dc4639153311dcb0fa", + "pbs-linked-single-reverseCursor-optimized.pbx": "a096a4a1fa73080d21c950cda8ededb60f65e2835a70af7ba73496e7b253b111", + "pbs-linked-single-reverseCursor.pbx": "9b1e322623c4e9713e1b39cf1e7ec160e67808dbf1898a7ebb418ec44fd86a4b", + "pbs-linked-snapshot-optimized.pbx": "6634680c1b7e2aae117ec894968bd8facdf56ebfe64f68ba266342614e525126", + "pbs-linked-snapshot.pbx": "b986d069dbd8a2c91b49f4ebca6030f3b0744f130a23636958477469566dbfd5", + "pbs-linked-tuple-optimized.pbx": "ea8e90a80ae07d66f40357877b47b6c86eef4412c2198e79b2d4ce441508db39", + "pbs-linked-tuple.pbx": "9e9f6ae6b28975e0cad5f3fdbc51236e1dbb14efa95d6f04e3728544497e74f9", + "pbs-linked-vec2-optimized.pbx": "bef1b46432b776033353eb4270c6e352c7562cfa6dc02b175eb58a2ecca03c5b", + "pbs-linked-vec2.pbx": "8b3405d7712a79932f28361038b28abdd2740583a5cdaed002b6535e1615c4d8" + }, + "pbs_execution_passes": [ + "basic", + "basic-optimized", + "links", + "links-optimized", + "construction", + "construction-optimized", + "long-size", + "long-size-optimized", + "empty-cursor", + "empty-cursor-optimized", + "empty-reverseCursor", + "empty-reverseCursor-optimized", + "single-cursor", + "single-cursor-optimized", + "single-reverseCursor", + "single-reverseCursor-optimized", + "snapshot", + "snapshot-optimized", + "false-present", + "false-present-optimized", + "optional-field", + "optional-field-optimized", + "identity", + "identity-optimized", + "tuple", + "tuple-optimized", + "nested-array", + "nested-array-optimized", + "function", + "function-optimized", + "evaluation", + "evaluation-optimized", + "vec2", + "vec2-optimized", + "pixel", + "pixel-optimized", + "contract", + "contract-optimized", + "fault-read", + "fault-read-optimized", + "fault-write", + "fault-write-optimized", + "fault-negative", + "fault-negative-optimized", + "fault-insert", + "fault-insert-optimized", + "fault-remove", + "fault-remove-optimized", + "fault-overflow", + "fault-overflow-optimized", + "fault-long-index", + "fault-long-index-optimized" + ], + "common_ir_execution_passes": [ + "common-storage", + "common-storage-optimized", + "common-fields", + "common-fields-optimized" + ], + "distribution_execution_passes": [ + "imports", + "installed" + ], + "distribution_assertions": { + "imports_reverse_final_value": 20, + "installed_forward_reverse_final_values": [ + 22, + 20 + ] + }, + "atomic_refusals": [ + { + "operation": "insert", + "resource": "GuestBytes", + "limit": 99024, + "opcode": "StructNew" + }, + { + "operation": "insert", + "resource": "GuestBytes", + "limit": 100776, + "opcode": "StructNew" + }, + { + "operation": "insert", + "resource": "GuestBytes", + "limit": 102528, + "opcode": "StructNew" + }, + { + "operation": "insert", + "resource": "GuestBytes", + "limit": 106031, + "opcode": "StructNew" + }, + { + "operation": "insert", + "resource": "HandleSlots", + "limit": 324, + "opcode": "StructNew" + }, + { + "operation": "insert", + "resource": "HandleSlots", + "limit": 325, + "opcode": "StructNew" + }, + { + "operation": "insert", + "resource": "HandleSlots", + "limit": 326, + "opcode": "StructNew" + }, + { + "operation": "insert", + "resource": "HandleSlots", + "limit": 327, + "opcode": "StructNew" + }, + { + "operation": "insert", + "resource": "HandleSlots", + "limit": 328, + "opcode": "StructNew" + }, + { + "operation": "insert", + "resource": "HandleSlots", + "limit": 329, + "opcode": "StructNew" + }, + { + "operation": "insert", + "resource": "HandleSlots", + "limit": 330, + "opcode": "StructNew" + }, + { + "operation": "insert", + "resource": "HandleSlots", + "limit": 331, + "opcode": "StructNew" + }, + { + "operation": "insert", + "resource": "HandleSlots", + "limit": 332, + "opcode": "StructNew" + }, + { + "operation": "insert", + "resource": "HandleSlots", + "limit": 333, + "opcode": "StructNew" + }, + { + "operation": "insert", + "resource": "HandleSlots", + "limit": 334, + "opcode": "StructNew" + }, + { + "operation": "insert", + "resource": "HandleSlots", + "limit": 335, + "opcode": "StructNew" + }, + { + "operation": "insert", + "resource": "HandleSlots", + "limit": 336, + "opcode": "StructNew" + }, + { + "operation": "insert", + "resource": "HandleSlots", + "limit": 337, + "opcode": "StructNew" + }, + { + "operation": "insert", + "resource": "HandleSlots", + "limit": 338, + "opcode": "StructNew" + }, + { + "operation": "insert", + "resource": "HandleSlots", + "limit": 339, + "opcode": "StructNew" + }, + { + "operation": "insert", + "resource": "HandleSlots", + "limit": 340, + "opcode": "StructNew" + }, + { + "operation": "insert", + "resource": "HandleSlots", + "limit": 341, + "opcode": "StructNew" + }, + { + "operation": "insert", + "resource": "HandleSlots", + "limit": 342, + "opcode": "StructNew" + }, + { + "operation": "insert", + "resource": "HandleSlots", + "limit": 343, + "opcode": "StructNew" + }, + { + "operation": "insert", + "resource": "HandleSlots", + "limit": 344, + "opcode": "StructNew" + }, + { + "operation": "insert", + "resource": "HandleSlots", + "limit": 345, + "opcode": "StructNew" + }, + { + "operation": "insert", + "resource": "HandleSlots", + "limit": 346, + "opcode": "StructNew" + }, + { + "operation": "insert", + "resource": "AuxiliaryBytes", + "limit": 32480, + "opcode": "Call" + }, + { + "operation": "insert", + "resource": "AuxiliaryBytes", + "limit": 33080, + "opcode": "Call" + }, + { + "operation": "insert", + "resource": "AuxiliaryBytes", + "limit": 33680, + "opcode": "Call" + }, + { + "operation": "add", + "resource": "GuestBytes", + "limit": 99024, + "opcode": "StructNew" + }, + { + "operation": "add", + "resource": "GuestBytes", + "limit": 99788, + "opcode": "StructNew" + }, + { + "operation": "add", + "resource": "GuestBytes", + "limit": 100552, + "opcode": "StructNew" + }, + { + "operation": "add", + "resource": "GuestBytes", + "limit": 102079, + "opcode": "StructNew" + }, + { + "operation": "add", + "resource": "HandleSlots", + "limit": 324, + "opcode": "StructNew" + }, + { + "operation": "add", + "resource": "HandleSlots", + "limit": 325, + "opcode": "StructNew" + }, + { + "operation": "add", + "resource": "HandleSlots", + "limit": 326, + "opcode": "StructNew" + }, + { + "operation": "add", + "resource": "HandleSlots", + "limit": 327, + "opcode": "StructNew" + }, + { + "operation": "add", + "resource": "HandleSlots", + "limit": 328, + "opcode": "StructNew" + }, + { + "operation": "add", + "resource": "HandleSlots", + "limit": 329, + "opcode": "StructNew" + }, + { + "operation": "add", + "resource": "HandleSlots", + "limit": 330, + "opcode": "StructNew" + }, + { + "operation": "add", + "resource": "HandleSlots", + "limit": 331, + "opcode": "StructNew" + }, + { + "operation": "add", + "resource": "HandleSlots", + "limit": 332, + "opcode": "StructNew" + }, + { + "operation": "add", + "resource": "HandleSlots", + "limit": 333, + "opcode": "StructNew" + }, + { + "operation": "add", + "resource": "AuxiliaryBytes", + "limit": 32480, + "opcode": "Call" + }, + { + "operation": "add", + "resource": "AuxiliaryBytes", + "limit": 33080, + "opcode": "Call" + }, + { + "operation": "add", + "resource": "AuxiliaryBytes", + "limit": 33680, + "opcode": "Call" + }, + { + "operation": "addFirst", + "resource": "GuestBytes", + "limit": 99024, + "opcode": "StructNew" + }, + { + "operation": "addFirst", + "resource": "GuestBytes", + "limit": 99940, + "opcode": "StructNew" + }, + { + "operation": "addFirst", + "resource": "GuestBytes", + "limit": 100856, + "opcode": "StructNew" + }, + { + "operation": "addFirst", + "resource": "GuestBytes", + "limit": 102687, + "opcode": "StructNew" + }, + { + "operation": "addFirst", + "resource": "HandleSlots", + "limit": 324, + "opcode": "StructNew" + }, + { + "operation": "addFirst", + "resource": "HandleSlots", + "limit": 325, + "opcode": "StructNew" + }, + { + "operation": "addFirst", + "resource": "HandleSlots", + "limit": 326, + "opcode": "StructNew" + }, + { + "operation": "addFirst", + "resource": "HandleSlots", + "limit": 327, + "opcode": "StructNew" + }, + { + "operation": "addFirst", + "resource": "HandleSlots", + "limit": 328, + "opcode": "StructNew" + }, + { + "operation": "addFirst", + "resource": "HandleSlots", + "limit": 329, + "opcode": "StructNew" + }, + { + "operation": "addFirst", + "resource": "HandleSlots", + "limit": 330, + "opcode": "StructNew" + }, + { + "operation": "addFirst", + "resource": "HandleSlots", + "limit": 331, + "opcode": "StructNew" + }, + { + "operation": "addFirst", + "resource": "HandleSlots", + "limit": 332, + "opcode": "StructNew" + }, + { + "operation": "addFirst", + "resource": "HandleSlots", + "limit": 333, + "opcode": "StructNew" + }, + { + "operation": "addFirst", + "resource": "HandleSlots", + "limit": 334, + "opcode": "StructNew" + }, + { + "operation": "addFirst", + "resource": "HandleSlots", + "limit": 335, + "opcode": "StructNew" + }, + { + "operation": "addFirst", + "resource": "AuxiliaryBytes", + "limit": 32480, + "opcode": "Call" + }, + { + "operation": "addFirst", + "resource": "AuxiliaryBytes", + "limit": 33080, + "opcode": "Call" + }, + { + "operation": "addFirst", + "resource": "AuxiliaryBytes", + "limit": 33680, + "opcode": "Call" + }, + { + "operation": "remove", + "resource": "GuestBytes", + "limit": 99024, + "opcode": "StructNew" + }, + { + "operation": "remove", + "resource": "GuestBytes", + "limit": 100771, + "opcode": "StructNew" + }, + { + "operation": "remove", + "resource": "GuestBytes", + "limit": 102518, + "opcode": "StructNew" + }, + { + "operation": "remove", + "resource": "GuestBytes", + "limit": 106011, + "opcode": "StructNew" + }, + { + "operation": "remove", + "resource": "HandleSlots", + "limit": 324, + "opcode": "StructNew" + }, + { + "operation": "remove", + "resource": "HandleSlots", + "limit": 325, + "opcode": "StructNew" + }, + { + "operation": "remove", + "resource": "HandleSlots", + "limit": 326, + "opcode": "StructNew" + }, + { + "operation": "remove", + "resource": "HandleSlots", + "limit": 327, + "opcode": "StructNew" + }, + { + "operation": "remove", + "resource": "HandleSlots", + "limit": 328, + "opcode": "StructNew" + }, + { + "operation": "remove", + "resource": "HandleSlots", + "limit": 329, + "opcode": "StructNew" + }, + { + "operation": "remove", + "resource": "HandleSlots", + "limit": 330, + "opcode": "StructNew" + }, + { + "operation": "remove", + "resource": "HandleSlots", + "limit": 331, + "opcode": "StructNew" + }, + { + "operation": "remove", + "resource": "HandleSlots", + "limit": 332, + "opcode": "StructNew" + }, + { + "operation": "remove", + "resource": "HandleSlots", + "limit": 333, + "opcode": "StructNew" + }, + { + "operation": "remove", + "resource": "HandleSlots", + "limit": 334, + "opcode": "StructNew" + }, + { + "operation": "remove", + "resource": "HandleSlots", + "limit": 335, + "opcode": "StructNew" + }, + { + "operation": "remove", + "resource": "HandleSlots", + "limit": 336, + "opcode": "StructNew" + }, + { + "operation": "remove", + "resource": "HandleSlots", + "limit": 337, + "opcode": "StructNew" + }, + { + "operation": "remove", + "resource": "HandleSlots", + "limit": 338, + "opcode": "StructNew" + }, + { + "operation": "remove", + "resource": "HandleSlots", + "limit": 339, + "opcode": "StructNew" + }, + { + "operation": "remove", + "resource": "HandleSlots", + "limit": 340, + "opcode": "StructNew" + }, + { + "operation": "remove", + "resource": "HandleSlots", + "limit": 341, + "opcode": "StructNew" + }, + { + "operation": "remove", + "resource": "HandleSlots", + "limit": 342, + "opcode": "StructNew" + }, + { + "operation": "remove", + "resource": "HandleSlots", + "limit": 343, + "opcode": "StructNew" + }, + { + "operation": "remove", + "resource": "HandleSlots", + "limit": 344, + "opcode": "StructNew" + }, + { + "operation": "remove", + "resource": "HandleSlots", + "limit": 345, + "opcode": "StructNew" + }, + { + "operation": "remove", + "resource": "HandleSlots", + "limit": 346, + "opcode": "StructNew" + }, + { + "operation": "remove", + "resource": "AuxiliaryBytes", + "limit": 32480, + "opcode": "Call" + }, + { + "operation": "remove", + "resource": "AuxiliaryBytes", + "limit": 33080, + "opcode": "Call" + }, + { + "operation": "remove", + "resource": "AuxiliaryBytes", + "limit": 33680, + "opcode": "Call" + }, + { + "operation": "removeFirst", + "resource": "GuestBytes", + "limit": 99024, + "opcode": "StructNew" + }, + { + "operation": "removeFirst", + "resource": "GuestBytes", + "limit": 99935, + "opcode": "StructNew" + }, + { + "operation": "removeFirst", + "resource": "GuestBytes", + "limit": 100846, + "opcode": "StructNew" + }, + { + "operation": "removeFirst", + "resource": "GuestBytes", + "limit": 102667, + "opcode": "StructNew" + }, + { + "operation": "removeFirst", + "resource": "HandleSlots", + "limit": 324, + "opcode": "StructNew" + }, + { + "operation": "removeFirst", + "resource": "HandleSlots", + "limit": 325, + "opcode": "StructNew" + }, + { + "operation": "removeFirst", + "resource": "HandleSlots", + "limit": 326, + "opcode": "StructNew" + }, + { + "operation": "removeFirst", + "resource": "HandleSlots", + "limit": 327, + "opcode": "StructNew" + }, + { + "operation": "removeFirst", + "resource": "HandleSlots", + "limit": 328, + "opcode": "StructNew" + }, + { + "operation": "removeFirst", + "resource": "HandleSlots", + "limit": 329, + "opcode": "StructNew" + }, + { + "operation": "removeFirst", + "resource": "HandleSlots", + "limit": 330, + "opcode": "StructNew" + }, + { + "operation": "removeFirst", + "resource": "HandleSlots", + "limit": 331, + "opcode": "StructNew" + }, + { + "operation": "removeFirst", + "resource": "HandleSlots", + "limit": 332, + "opcode": "StructNew" + }, + { + "operation": "removeFirst", + "resource": "HandleSlots", + "limit": 333, + "opcode": "StructNew" + }, + { + "operation": "removeFirst", + "resource": "HandleSlots", + "limit": 334, + "opcode": "StructNew" + }, + { + "operation": "removeFirst", + "resource": "HandleSlots", + "limit": 335, + "opcode": "StructNew" + }, + { + "operation": "removeFirst", + "resource": "AuxiliaryBytes", + "limit": 32480, + "opcode": "Call" + }, + { + "operation": "removeFirst", + "resource": "AuxiliaryBytes", + "limit": 33080, + "opcode": "Call" + }, + { + "operation": "removeFirst", + "resource": "AuxiliaryBytes", + "limit": 33680, + "opcode": "Call" + }, + { + "operation": "removeLast", + "resource": "GuestBytes", + "limit": 99024, + "opcode": "StructNew" + }, + { + "operation": "removeLast", + "resource": "GuestBytes", + "limit": 99935, + "opcode": "StructNew" + }, + { + "operation": "removeLast", + "resource": "GuestBytes", + "limit": 100846, + "opcode": "StructNew" + }, + { + "operation": "removeLast", + "resource": "GuestBytes", + "limit": 102667, + "opcode": "StructNew" + }, + { + "operation": "removeLast", + "resource": "HandleSlots", + "limit": 324, + "opcode": "StructNew" + }, + { + "operation": "removeLast", + "resource": "HandleSlots", + "limit": 325, + "opcode": "StructNew" + }, + { + "operation": "removeLast", + "resource": "HandleSlots", + "limit": 326, + "opcode": "StructNew" + }, + { + "operation": "removeLast", + "resource": "HandleSlots", + "limit": 327, + "opcode": "StructNew" + }, + { + "operation": "removeLast", + "resource": "HandleSlots", + "limit": 328, + "opcode": "StructNew" + }, + { + "operation": "removeLast", + "resource": "HandleSlots", + "limit": 329, + "opcode": "StructNew" + }, + { + "operation": "removeLast", + "resource": "HandleSlots", + "limit": 330, + "opcode": "StructNew" + }, + { + "operation": "removeLast", + "resource": "HandleSlots", + "limit": 331, + "opcode": "StructNew" + }, + { + "operation": "removeLast", + "resource": "HandleSlots", + "limit": 332, + "opcode": "StructNew" + }, + { + "operation": "removeLast", + "resource": "HandleSlots", + "limit": 333, + "opcode": "StructNew" + }, + { + "operation": "removeLast", + "resource": "HandleSlots", + "limit": 334, + "opcode": "StructNew" + }, + { + "operation": "removeLast", + "resource": "HandleSlots", + "limit": 335, + "opcode": "StructNew" + }, + { + "operation": "removeLast", + "resource": "AuxiliaryBytes", + "limit": 32480, + "opcode": "Call" + }, + { + "operation": "removeLast", + "resource": "AuxiliaryBytes", + "limit": 33080, + "opcode": "Call" + }, + { + "operation": "removeLast", + "resource": "AuxiliaryBytes", + "limit": 33680, + "opcode": "Call" + }, + { + "operation": "replace", + "resource": "GuestBytes", + "limit": 99024, + "opcode": "StructNew" + }, + { + "operation": "replace", + "resource": "GuestBytes", + "limit": 100088, + "opcode": "StructNew" + }, + { + "operation": "replace", + "resource": "GuestBytes", + "limit": 101152, + "opcode": "StructNew" + }, + { + "operation": "replace", + "resource": "GuestBytes", + "limit": 103279, + "opcode": "StructNew" + }, + { + "operation": "replace", + "resource": "HandleSlots", + "limit": 324, + "opcode": "StructNew" + }, + { + "operation": "replace", + "resource": "HandleSlots", + "limit": 325, + "opcode": "StructNew" + }, + { + "operation": "replace", + "resource": "HandleSlots", + "limit": 326, + "opcode": "StructNew" + }, + { + "operation": "replace", + "resource": "HandleSlots", + "limit": 327, + "opcode": "StructNew" + }, + { + "operation": "replace", + "resource": "HandleSlots", + "limit": 328, + "opcode": "StructNew" + }, + { + "operation": "replace", + "resource": "HandleSlots", + "limit": 329, + "opcode": "StructNew" + }, + { + "operation": "replace", + "resource": "HandleSlots", + "limit": 330, + "opcode": "StructNew" + }, + { + "operation": "replace", + "resource": "HandleSlots", + "limit": 331, + "opcode": "StructNew" + }, + { + "operation": "replace", + "resource": "HandleSlots", + "limit": 332, + "opcode": "StructNew" + }, + { + "operation": "replace", + "resource": "HandleSlots", + "limit": 333, + "opcode": "StructNew" + }, + { + "operation": "replace", + "resource": "HandleSlots", + "limit": 334, + "opcode": "StructNew" + }, + { + "operation": "replace", + "resource": "HandleSlots", + "limit": 335, + "opcode": "StructNew" + }, + { + "operation": "replace", + "resource": "HandleSlots", + "limit": 336, + "opcode": "StructNew" + }, + { + "operation": "replace", + "resource": "HandleSlots", + "limit": 337, + "opcode": "StructNew" + }, + { + "operation": "replace", + "resource": "AuxiliaryBytes", + "limit": 32480, + "opcode": "Call" + }, + { + "operation": "replace", + "resource": "AuxiliaryBytes", + "limit": 33080, + "opcode": "Call" + }, + { + "operation": "replace", + "resource": "AuxiliaryBytes", + "limit": 33680, + "opcode": "GetLocal" + }, + { + "operation": "clear", + "resource": "GuestBytes", + "limit": 99024, + "opcode": "StructNew" + }, + { + "operation": "clear", + "resource": "GuestBytes", + "limit": 99176, + "opcode": "StructNew" + }, + { + "operation": "clear", + "resource": "GuestBytes", + "limit": 99328, + "opcode": "StructNew" + }, + { + "operation": "clear", + "resource": "GuestBytes", + "limit": 99631, + "opcode": "StructNew" + }, + { + "operation": "clear", + "resource": "HandleSlots", + "limit": 324, + "opcode": "StructNew" + }, + { + "operation": "clear", + "resource": "HandleSlots", + "limit": 325, + "opcode": "StructNew" + }, + { + "operation": "clear", + "resource": "AuxiliaryBytes", + "limit": 32480, + "opcode": "Call" + }, + { + "operation": "clear", + "resource": "AuxiliaryBytes", + "limit": 33080, + "opcode": "Call" + }, + { + "operation": "cursor", + "resource": "GuestBytes", + "limit": 99024, + "opcode": "StructNew" + }, + { + "operation": "cursor", + "resource": "GuestBytes", + "limit": 109044, + "opcode": "StructNew" + }, + { + "operation": "cursor", + "resource": "GuestBytes", + "limit": 119064, + "opcode": "StructNew" + }, + { + "operation": "cursor", + "resource": "GuestBytes", + "limit": 139103, + "opcode": "StructNew" + }, + { + "operation": "cursor", + "resource": "HandleSlots", + "limit": 324, + "opcode": "StructNew" + }, + { + "operation": "cursor", + "resource": "HandleSlots", + "limit": 325, + "opcode": "StructNew" + }, + { + "operation": "cursor", + "resource": "HandleSlots", + "limit": 326, + "opcode": "StructNew" + }, + { + "operation": "cursor", + "resource": "HandleSlots", + "limit": 327, + "opcode": "StructNew" + }, + { + "operation": "cursor", + "resource": "HandleSlots", + "limit": 328, + "opcode": "StructNew" + }, + { + "operation": "cursor", + "resource": "HandleSlots", + "limit": 329, + "opcode": "StructNew" + }, + { + "operation": "cursor", + "resource": "HandleSlots", + "limit": 330, + "opcode": "StructNew" + }, + { + "operation": "cursor", + "resource": "HandleSlots", + "limit": 331, + "opcode": "StructNew" + }, + { + "operation": "cursor", + "resource": "HandleSlots", + "limit": 332, + "opcode": "StructNew" + }, + { + "operation": "cursor", + "resource": "HandleSlots", + "limit": 333, + "opcode": "StructNew" + }, + { + "operation": "cursor", + "resource": "HandleSlots", + "limit": 334, + "opcode": "StructNew" + }, + { + "operation": "cursor", + "resource": "HandleSlots", + "limit": 335, + "opcode": "StructNew" + }, + { + "operation": "cursor", + "resource": "HandleSlots", + "limit": 336, + "opcode": "StructNew" + }, + { + "operation": "cursor", + "resource": "HandleSlots", + "limit": 337, + "opcode": "StructNew" + }, + { + "operation": "cursor", + "resource": "HandleSlots", + "limit": 338, + "opcode": "StructNew" + }, + { + "operation": "cursor", + "resource": "HandleSlots", + "limit": 339, + "opcode": "StructNew" + }, + { + "operation": "cursor", + "resource": "HandleSlots", + "limit": 340, + "opcode": "StructNew" + }, + { + "operation": "cursor", + "resource": "HandleSlots", + "limit": 341, + "opcode": "StructNew" + }, + { + "operation": "cursor", + "resource": "HandleSlots", + "limit": 342, + "opcode": "StructNew" + }, + { + "operation": "cursor", + "resource": "HandleSlots", + "limit": 343, + "opcode": "StructNew" + }, + { + "operation": "cursor", + "resource": "HandleSlots", + "limit": 344, + "opcode": "StructNew" + }, + { + "operation": "cursor", + "resource": "HandleSlots", + "limit": 345, + "opcode": "StructNew" + }, + { + "operation": "cursor", + "resource": "HandleSlots", + "limit": 346, + "opcode": "StructNew" + }, + { + "operation": "cursor", + "resource": "HandleSlots", + "limit": 347, + "opcode": "StructNew" + }, + { + "operation": "cursor", + "resource": "HandleSlots", + "limit": 356, + "opcode": "StructNew" + }, + { + "operation": "cursor", + "resource": "HandleSlots", + "limit": 389, + "opcode": "StructNew" + }, + { + "operation": "cursor", + "resource": "HandleSlots", + "limit": 454, + "opcode": "StructNew" + }, + { + "operation": "cursor", + "resource": "AuxiliaryBytes", + "limit": 32480, + "opcode": "Call" + }, + { + "operation": "cursor", + "resource": "AuxiliaryBytes", + "limit": 33080, + "opcode": "Call" + }, + { + "operation": "cursor", + "resource": "AuxiliaryBytes", + "limit": 33680, + "opcode": "StructNew" + }, + { + "operation": "reverseCursor", + "resource": "GuestBytes", + "limit": 99024, + "opcode": "StructNew" + }, + { + "operation": "reverseCursor", + "resource": "GuestBytes", + "limit": 109044, + "opcode": "StructNew" + }, + { + "operation": "reverseCursor", + "resource": "GuestBytes", + "limit": 119064, + "opcode": "StructNew" + }, + { + "operation": "reverseCursor", + "resource": "GuestBytes", + "limit": 139103, + "opcode": "StructNew" + }, + { + "operation": "reverseCursor", + "resource": "HandleSlots", + "limit": 324, + "opcode": "StructNew" + }, + { + "operation": "reverseCursor", + "resource": "HandleSlots", + "limit": 325, + "opcode": "StructNew" + }, + { + "operation": "reverseCursor", + "resource": "HandleSlots", + "limit": 326, + "opcode": "StructNew" + }, + { + "operation": "reverseCursor", + "resource": "HandleSlots", + "limit": 327, + "opcode": "StructNew" + }, + { + "operation": "reverseCursor", + "resource": "HandleSlots", + "limit": 328, + "opcode": "StructNew" + }, + { + "operation": "reverseCursor", + "resource": "HandleSlots", + "limit": 329, + "opcode": "StructNew" + }, + { + "operation": "reverseCursor", + "resource": "HandleSlots", + "limit": 330, + "opcode": "StructNew" + }, + { + "operation": "reverseCursor", + "resource": "HandleSlots", + "limit": 331, + "opcode": "StructNew" + }, + { + "operation": "reverseCursor", + "resource": "HandleSlots", + "limit": 332, + "opcode": "StructNew" + }, + { + "operation": "reverseCursor", + "resource": "HandleSlots", + "limit": 333, + "opcode": "StructNew" + }, + { + "operation": "reverseCursor", + "resource": "HandleSlots", + "limit": 334, + "opcode": "StructNew" + }, + { + "operation": "reverseCursor", + "resource": "HandleSlots", + "limit": 335, + "opcode": "StructNew" + }, + { + "operation": "reverseCursor", + "resource": "HandleSlots", + "limit": 336, + "opcode": "StructNew" + }, + { + "operation": "reverseCursor", + "resource": "HandleSlots", + "limit": 337, + "opcode": "StructNew" + }, + { + "operation": "reverseCursor", + "resource": "HandleSlots", + "limit": 338, + "opcode": "StructNew" + }, + { + "operation": "reverseCursor", + "resource": "HandleSlots", + "limit": 339, + "opcode": "StructNew" + }, + { + "operation": "reverseCursor", + "resource": "HandleSlots", + "limit": 340, + "opcode": "StructNew" + }, + { + "operation": "reverseCursor", + "resource": "HandleSlots", + "limit": 341, + "opcode": "StructNew" + }, + { + "operation": "reverseCursor", + "resource": "HandleSlots", + "limit": 342, + "opcode": "StructNew" + }, + { + "operation": "reverseCursor", + "resource": "HandleSlots", + "limit": 343, + "opcode": "StructNew" + }, + { + "operation": "reverseCursor", + "resource": "HandleSlots", + "limit": 344, + "opcode": "StructNew" + }, + { + "operation": "reverseCursor", + "resource": "HandleSlots", + "limit": 345, + "opcode": "StructNew" + }, + { + "operation": "reverseCursor", + "resource": "HandleSlots", + "limit": 346, + "opcode": "StructNew" + }, + { + "operation": "reverseCursor", + "resource": "HandleSlots", + "limit": 347, + "opcode": "StructNew" + }, + { + "operation": "reverseCursor", + "resource": "HandleSlots", + "limit": 356, + "opcode": "StructNew" + }, + { + "operation": "reverseCursor", + "resource": "HandleSlots", + "limit": 389, + "opcode": "StructNew" + }, + { + "operation": "reverseCursor", + "resource": "HandleSlots", + "limit": 454, + "opcode": "StructNew" + }, + { + "operation": "reverseCursor", + "resource": "AuxiliaryBytes", + "limit": 32480, + "opcode": "Call" + }, + { + "operation": "reverseCursor", + "resource": "AuxiliaryBytes", + "limit": 33080, + "opcode": "Call" + }, + { + "operation": "reverseCursor", + "resource": "AuxiliaryBytes", + "limit": 33680, + "opcode": "StructNew" + } + ], + "atomic_refusal_counts": { + "GuestBytes": 40, + "HandleSlots": 162, + "AuxiliaryBytes": 29 + }, + "refusal_observation": "Non-owning BFS of original Linked roots, all optional-link carriers, nodes and complete stored groups; prior roots/length and every reciprocal link unchanged after refusal; resource usage zero after VM drop.", + "temporary_bytes_qualification": "Measured setup/success peaks produced no extra TemporaryBytes refusal case in the Linked source matrix. FIELDS_PUBLISH allocates no scratch; direct provider tests publish at exhausted GuestBytes, HandleSlots, AuxiliaryBytes and TemporaryBytes ceilings.", + "collection_gc_safepoints": [ + { + "round": 0, + "nodes": 1200, + "items": 1200 + }, + { + "round": 1, + "nodes": 1197, + "items": 1197 + }, + { + "round": 2, + "nodes": 0, + "items": 0 + }, + { + "round": 3, + "nodes": 0, + "items": 0 + } + ], + "snapshot_gc_safepoints": [ + { + "round": 0, + "nodes": 1200, + "items": 1200, + "collected": 15042 + }, + { + "round": 1, + "nodes": 1, + "items": 1, + "collected": 22236 + }, + { + "round": 2, + "nodes": 1, + "items": 1, + "collected": 24636 + }, + { + "round": 3, + "nodes": 0, + "items": 0, + "collected": 25842 + } + ], + "gc_assertions": [ + "Actual GC collection counter increases at each observed safepoint", + "Removed payloads and nodes collectible without snapshots", + "Clear releases unreachable double-link cycles", + "Snapshots retain no editable Linked nodes", + "Consumed snapshot prefixes collectible", + "Last payload 1199 retained after repeated next", + "Final Cursor release permits all payloads/nodes to be collected" + ], + "gates": [ + { + "command": "./gradlew :prometeu-architecture-tests:test --tests '*PbsLinkedTest' :prometeu-compiler:frontends:prometeu-frontend-pbs:test :prometeu-lsp:prometeu-lsp-v1:test --console=plain", + "result": "passed" + }, + { + "command": "./gradlew -q test :prometeu-app:installedKnowledgeTest --console=plain", + "result": "passed", + "junit_reports": { + "tests": 1030, + "failures": 0, + "errors": 0, + "skipped": 13 + }, + "notes": "Final Java implementation regression; subsequent durable-doc/example changes passed the installed gate below." + }, + { + "command": "./gradlew -q :prometeu-app:installedKnowledgeTest --console=plain", + "result": "passed", + "passed": 2, + "notes": "Final example demonstrates both forward/reverse captures after source replacement and clear; actual installed JAR resources in isolated JVM." + }, + { + "command": "cargo test -q -p prometeu-bytecode -p prometeu-vm --lib --features prometeu-vm/resource-diagnostics --locked --offline", + "working_directory": "../runtime", + "environment": { + "CARGO_TARGET_DIR": "/tmp/prometeu-linked-provider-final-target" + }, + "result": "passed", + "passed": 311, + "ignored": 2 + }, + { + "command": "python3 tools/pbx-conformance/run.py --runtime ../runtime", + "environment": { + "CARGO_TARGET_DIR": "/tmp/prometeu-linked-harness-target" + }, + "result": "passed", + "exit_code": 0, + "notes": "Full mandatory existing and new production corpus; all 52 Linked cases, ten mutation/capture refusal boundaries, both GC fixtures and imports/installed examples." + }, + { + "command": "python3 tools/runtime-catalog/verify.py --runtime ../runtime", + "result": "passed", + "notes": "Clean selected provider, two catalog hashes and actual exporter parity; all four canonical mirrors also compared byte-for-byte." + }, + { + "command": "git diff --check", + "result": "passed" + }, + { + "command": "discussion validate", + "result": "passed" + } + ], + "traceability": { + "R1": "Construction/context/optional diagnostics and optional-field/compound positive source cases", + "R2": "Full API/link/order/identity cases and independent all-node state observations", + "R3": "Every public operation in empty/singleton/multiple-node cases", + "R4": "Bounds, long maximum guard, int/long/named/single evaluation and forbidden numeric payload promotion", + "R5": "Both capture orders, full shared state table, duplicates, mutation independence and installed dual traversal", + "R6": "SDK nearest-end lookup algorithm and explicit indexed/snapshot complexity documentation", + "R7": "231 refused whole source operations, pre-prepared optional result and allocation-free generic commit", + "R8": "Neutral schema-driven FIELDS_PUBLISH through ordinary/optimized producer and production provider with exact pin/mirrors", + "R9": "Independent normal-GC counts for removal/clear, source topology release, consumed prefixes and final owners", + "R10": "Origin/privacy/constructor diagnostics, concrete editor projections, LSP, imports/reexports and isolated installed JAR examples/spec", + "R11": "Full Studio/provider/production conformance and recorded provenance/quotas/hashes", + "R12": "No value removal/equality/public-node/mutable-Cursor/capacity/Set/Map extension; English specs/lesson and complete workflow closure" + }, + "limitations": [ + "Recorded macOS arm64 dev profile only; no release or cross-platform qualification", + "Thirteen existing Studio skips and two existing provider measurement tests ignored", + "Two pre-existing full-harness response-schema gaps, LifecycleRole and NonFiniteValue, are reported with original payloads; no Linked case skipped" + ], + "workflow_cli_gap": "No create-lesson/next-id CLI. LSN-0091 was read from the framework model without mutation; discussion housekeep registers the artifact and updates the counter/index.", + "workflow_completion": { + "discussion_status": "done", + "plan_status_before_housekeeping": "done", + "lesson": "LSN-0091", + "housekeeping": "discussion housekeep DSC-0091 --lesson discussion/lessons/DSC-0091-pbs-sdk-linked/LSN-0091-private-linked-nodes-and-atomic-publication.md", + "removed_control_artifacts": 3, + "validation_after_housekeeping": "passed" + } +} diff --git a/docs/compiler/general/specs/typed-registry-and-pbx-v0.md b/docs/compiler/general/specs/typed-registry-and-pbx-v0.md index dddb68c6..96db50c1 100644 --- a/docs/compiler/general/specs/typed-registry-and-pbx-v0.md +++ b/docs/compiler/general/specs/typed-registry-and-pbx-v0.md @@ -244,3 +244,37 @@ before mutation. A refused preparation still charges the attempted work. Neither operation is a safepoint. Consumers must prepare any potentially failing return carrier and all call operands before publication; a series of ordinary stores is not a substitute for whole-operation safety. + + +## Atomic publication of multiple Struct instances + +FIELDS_PUBLISH (`0xAB`) has one little-endian u32 schema TypeId immediate. The +schema MUST be a Registry Struct whose ordered field types are all Struct types. +Names are descriptive only. The schema is declarative metadata; no request object, +new Registry category or preparation token is allocated or exposed. + +For each schema entry, the operand stack supplies one nullable destination +reference followed by every destination field's complete typed value group, in +field declaration order. The stack effect is the sum, over entries, of one plus +the destination instance's initialization-slot count; no results are produced. +Null skips that destination, but every supplied field group is still validated. +Non-null destinations require exact concrete Struct identity and a live reference +of the current session/generation. Array, Trait, Fn and builtin schema entries are +invalid, including in unreachable instructions. The full schema and exact stack +height/groups are checked under normal Registry admission/work limits. + +Validate all destinations and value groups before any shared write or operand +consumption. The original operands remain roots throughout preparation. Then write +all fields in schema order, without allocation, fallible validation, callbacks, +GC or scheduler interleaving, and consume the entire input. Input values are +captured before publication; repeated destinations use ordered last-write +semantics. Complete multi-slot/native/reference groups retain identity and normal +ownership. A failed attempt preserves every destination and the operand stack. + +The operation allocates no publication scratch or guest object. Operand/frame and +source value preparation remain normally charged and may fail before publication. +Base cost is 6 cycles. After the stack-height check, precharge one cycle per schema +entry and one per destination field execution slot for the complete declared +attempt, including skipped destinations. Quotas are unchanged. +This is a generic typed storage mechanism; collection algorithms and node topology +remain source-owned, with no collection-specific VM instruction or syscall. diff --git a/docs/compiler/pbs/specs/sdk-linked-and-cursor.md b/docs/compiler/pbs/specs/sdk-linked-and-cursor.md new file mode 100644 index 00000000..68878d76 --- /dev/null +++ b/docs/compiler/pbs/specs/sdk-linked-and-cursor.md @@ -0,0 +1,127 @@ +# SDK Linked and bidirectional snapshot capture + +Owner: `compiler/pbs`. Linked algorithms belong to executable PBS SDK source. +Multi-object publication, storage, faults, ownership, GC and quotas remain generic +compiler/provider mechanisms. This contract builds on [generic structs](generic-structs-and-free-functions.md), +[arrays and optional](typed-arrays-and-optional-execution.md) and the +[shared Cursor protocol](sdk-list-and-cursor.md#cursor-protocol). + +## Type, identity and construction + +The collections SDK exports `linked`. It is an ordinary invariant generic +struct with stable reference identity: aliases observe mutations of the same +collection. `new linked()` creates an empty collection. Contextual construction +follows generic struct rules, requiring a concrete expected application; constructor +values do not infer T. There is no capacity argument. + +A directly optional element, including through grouping, is invalid. +`optional (linked)` remains valid, as do otherwise valid element types containing +optional fields. Values retain their complete groups and normal identities, +including tuples, native values, arrays, functions and contract views. No public +Dynamic, universal Element or wrapper node is introduced. + +Storage consists of private doubly linked nodes, each containing one present +value. Logical size equals node count. Empty collections have no head or tail; +one-node collections have the same head and tail. Neighbor links are reciprocal, +forward and backward traversals agree, and there are no extra predecessor or +successor nodes beyond the ends. Nodes and private helpers are not a public API. + +## Operations and bounds + +| Operation | Result | Behavior | +| --- | --- | --- | +| `size()` | long | Number of elements | +| `first()` / `last()` | optional T | End value, or none when empty | +| `xs[i]` | optional T | Present value at a valid index | +| `xs[i] = value` | unit | Replace a valid position without changing size | +| `add(value)` | unit | Append | +| `addFirst(value)` | unit | Prepend | +| `insert(i, value)` | unit | Insert at `0 <= i <= size` | +| `removeAt(i)` | optional T | Remove and return a valid position | +| `removeFirst()` / `removeLast()` | optional T | Remove and return end value, or none when empty | +| `clear()` | unit | Remove all elements and set size to zero | +| `cursor()` | Cursor | Capture first to last | +| `reverseCursor()` | Cursor | Capture last to first | + +Reading, replacing and removing by index require `0 <= i < size`; invalid indices +raise TRAP_OOB even when empty. Insertion accepts size, including zero in an empty +collection. Other insertion indices raise TRAP_OOB. Every valid position contains +an element, so indexed read/removal returns a present optional. Zero and false are +present values. Empty-end results do not suppress type or resource faults. + +Insertion/removal changes the logical indices of following elements. Replacement +preserves size. There are no holes, clearAt, capacity, reserve, trim or resize. +Duplicate occurrences are preserved; no equality or uniqueness rule is imposed. +Value search/removal is outside this API, consistently with List. + +Size is nonnegative long. Indices accept int and long with localized lossless +promotion, without general numeric conversion or truncation. The SDK checks the +current size against the maximum signed long before incrementing, using the generic +logical guard; an unrepresentable next size is rejected before arithmetic or +mutation. Array's u32 structural maximum is not a Linked size limit. Provider +quotas and applicable structural limits can refuse allocation much earlier. +Receiver/arguments evaluate once in source order, including named application. + +## Snapshots and costs + +Both capture methods return the existing Cursor contract and preserve its +complete state table. A nonempty cursor starts on its first captured value; +hasNext asks whether a successor exists; next without a successor does nothing. +Only a snapshot born empty has an absent current. Repeated next retains the final +value. Capturing `[A, B, C]` produces `[A, B, C]` or `[C, B, A]` respectively. + +Each capture completes before return and owns private immutable singly linked, +non-circular snapshot nodes, independent of the collection's doubly linked nodes. +It uses no snapshot array or live association with editable source nodes. +Subsequent insertion, replacement, removal and clear cannot change the captured +sequence. Shared objects retain identity and later field changes remain visible. +There is no removal/reset through Cursor or public node access. + +End operations locate their nodes without traversal. Indexed operations search +from the nearer end and remain O(n) in the worst case. Both captures cost O(n) +work and O(n) additional nodes; next follows one link in O(1). Allocation, +optional-carrier preparation, ownership and eventual GC retain their normal +costs. Repeated indexed reads are not an efficient traversal strategy. + +## Complete mutation attempts and lifetime + +Before publication, prepare bounds, next size, candidate nodes, optional results, +all field values and call/operand resources. Private generic FIELDS_PUBLISH +publishes complete field groups of source-selected objects after validating all +receivers and groups. Null destinations represent missing neighbors. Algorithms +select the new head/tail/size and neighbor fields in SDK source; the VM has no +Linked opcode or syscall. + +No fallible allocation, callback, scheduler or GC boundary may expose partial +publication. A refused mutation preserves all previous head/tail/size values, +elements and neighbor links. This includes optional return preparation for +removals and mutations without new nodes. Individually atomic stores do not prove +whole-operation atomicity. Previously evaluated argument effects are ordinary +source effects and are not rolled back. + +Unpublished candidates follow normal ownership and quotas. Capture failure returns +no partial Cursor and does not change the source. Removal and clear release +collection references to discarded nodes and payloads. Doubly linked cycles are +collected by normal tracing when unreachable; no immediate reclamation is promised. +Snapshots retain payloads, not the editable source topology; consumed prefixes +become collectible while the last current value stays retained until released. + +## Conformance and distribution + +Qualification executes real PBS through common IR/PBX and the production verifier +and VM, with ordinary and optimized producer paths. Cover the full API in empty, +single and multi-node states, reciprocal links and size, nearest-end lookup, all +bounds, int/long and single/named evaluation, complete groups and identity, +optional-element diagnostics, both Cursor orders/states and mutation independence. + +Independently observe all original fields, link carriers, nodes and groups around +quota refusals, including node/result/operand preparation. Exercise ordinary GC +safepoints for removed nodes/values, clear, snapshots and prefix/final release. +Generic publication also requires non-PBS producers and malformed/dead operand +coverage. Regress shared Array/List/generic/contract/Cursor behavior and editor/LSP +projections. Ship the specification and executable example with installed SDK +knowledge, compile the actual packaged example outside the checkout and execute +its emitted PBX with the production provider. + +See [generic Registry/PBX publication](../../general/specs/typed-registry-and-pbx-v0.md) +for the language-neutral instruction contract. diff --git a/docs/compiler/pbs/specs/sdk-list-and-cursor.md b/docs/compiler/pbs/specs/sdk-list-and-cursor.md index aba1689b..8f6d5135 100644 --- a/docs/compiler/pbs/specs/sdk-list-and-cursor.md +++ b/docs/compiler/pbs/specs/sdk-list-and-cursor.md @@ -152,11 +152,12 @@ faults. List itself rejects directly optional elements. ## Reuse, costs and conformance -The shared implementation is independent of List representation. Future Linked -and Set producers use Cursor; Map uses Cursor>. Set/Map gain +The shared implementation is independent of List representation. +[Linked](sdk-linked-and-cursor.md) uses Cursor for forward and reverse captures. +Future Set producers use Cursor; Map uses Cursor>. Set/Map gain no ordering guarantee between captures. A captured keyval association is read-only and does not follow later association replacement; referenced objects stay shared. -Those collections and keyval are separate deliveries. +Set/Map and keyval are separate deliveries. For n logical List positions and k present occurrences, capture takes O(n) work and O(k) additional nodes; next follows one link in O(1). Each node costs allocation, diff --git a/docs/vm-arch/ARCHITECTURE.md b/docs/vm-arch/ARCHITECTURE.md index 6e95828c..e14fa72f 100644 --- a/docs/vm-arch/ARCHITECTURE.md +++ b/docs/vm-arch/ARCHITECTURE.md @@ -202,3 +202,12 @@ The [Program Registry contract](../specs/runtime/02c-program-registry-and-pbx-v0 ## VM-owned random core See the [random contract](../specs/runtime/02e-vm-owned-random-core.md) for Random BuiltinId 0x0016, ObjectKind tag 9, intrinsics 0x4000–0x4003, atomic state mutation, bounded 4+8*N costs and rejection-limit trap 0x00000015. Random is managed by the VM heap and existing GC, without host entropy or PBX changes. + + +## Atomic publication of multiple Struct instances + +FIELDS_PUBLISH (0xAB) atomically publishes complete typed fields to multiple +source-selected Struct destinations. Its schema is an ordinary Registry Struct; +no new category, request object, syscall or safepoint is introduced. Exact nullable +destination rules, stack effects, validation, costs and commit semantics are in the +[canonical instruction contract](../specs/runtime/02-vm-instruction-set.md#atomic-publication-of-multiple-struct-instances). diff --git a/docs/vm-arch/ISA_CORE.md b/docs/vm-arch/ISA_CORE.md index d50b3e41..a2263afd 100644 --- a/docs/vm-arch/ISA_CORE.md +++ b/docs/vm-arch/ISA_CORE.md @@ -198,3 +198,12 @@ STORAGE_PUBLISH (0xAA) provide generic logical validation, complete stored-group transfer and prepared atomic publication. Their encoding, typed operands, exact faults, overlap semantics, costs and preflight/commit guarantees are defined by the [canonical instruction contract](../specs/runtime/02-vm-instruction-set.md#logical-guards-and-atomic-storage-publication). No new Registry category, syscall, collection algorithm or safepoint is introduced. + + +## Atomic publication of multiple Struct instances + +FIELDS_PUBLISH (0xAB) atomically publishes complete typed fields to multiple +source-selected Struct destinations. Its schema is an ordinary Registry Struct; +no new category, request object, syscall or safepoint is introduced. Exact nullable +destination rules, stack effects, validation, costs and commit semantics are in the +[canonical instruction contract](../specs/runtime/02-vm-instruction-set.md#atomic-publication-of-multiple-struct-instances). diff --git a/docs/vm-arch/runtime-catalog.properties b/docs/vm-arch/runtime-catalog.properties index 021ac2d3..42ad730c 100644 --- a/docs/vm-arch/runtime-catalog.properties +++ b/docs/vm-arch/runtime-catalog.properties @@ -1,3 +1,3 @@ -runtime.revision=d9b9eeb171d2861ec660d4cf5703b0795eac49a9 +runtime.revision=57992cf214e8a5f9de53a40dba9aaa7fab038c91 INTRINSICS.csv.sha256=0c1bb78a9b81d1e3480ef5713f3d70f0b06772a7dfab2fd00c1f0a6364f98daa BUILTIN_CONSTANTS.csv.sha256=e407e4718127aa7ef7b1097b5b4b67d86dd979235e73a551a7c36b628cddc039 diff --git a/prometeu-app/src/test/java/p/studio/app/compiler/CompilerProjectKnowledgeTest.java b/prometeu-app/src/test/java/p/studio/app/compiler/CompilerProjectKnowledgeTest.java index 71f9e2dc..1ba9f90a 100644 --- a/prometeu-app/src/test/java/p/studio/app/compiler/CompilerProjectKnowledgeTest.java +++ b/prometeu-app/src/test/java/p/studio/app/compiler/CompilerProjectKnowledgeTest.java @@ -49,6 +49,8 @@ class CompilerProjectKnowledgeTest { assertTrue(result.references().stream().anyMatch(value -> value.id().equals("pbs:quickstart"))); assertTrue(result.references().stream().anyMatch(value -> value.id().equals("pbs:spec:sdk-list-and-cursor.md"))); assertTrue(result.references().stream().anyMatch(value -> value.id().equals("pbs:example:game:1:src/collections.pbs"))); + assertTrue(result.references().stream().anyMatch(value -> value.id().equals("pbs:spec:sdk-linked-and-cursor.md"))); + assertTrue(result.references().stream().anyMatch(value -> value.id().equals("pbs:example:game:1:src/linked.pbs"))); assertTrue(language.referenceIds().contains("pbs:quickstart")); assertFalse(result.limitations().stream().anyMatch(value -> value.contains("DOCUMENTATION_UNAVAILABLE"))); assertFalse(Files.exists(root.resolve(".workspace"))); diff --git a/prometeu-app/src/test/java/p/studio/app/compiler/InstalledKnowledgeProbe.java b/prometeu-app/src/test/java/p/studio/app/compiler/InstalledKnowledgeProbe.java index 3d6e3aec..99fcbd03 100644 --- a/prometeu-app/src/test/java/p/studio/app/compiler/InstalledKnowledgeProbe.java +++ b/prometeu-app/src/test/java/p/studio/app/compiler/InstalledKnowledgeProbe.java @@ -29,6 +29,8 @@ public final class InstalledKnowledgeProbe { check(docs.stream().anyMatch(r -> r.id().equals("pbs:example:game:1:src/generics.pbs")), "Missing installed generic struct/function example"); check(docs.stream().anyMatch(r -> r.id().equals("pbs:spec:sdk-list-and-cursor.md")), "Missing installed List/Cursor specification"); check(docs.stream().anyMatch(r -> r.id().equals("pbs:example:game:1:src/collections.pbs")), "Missing installed List/Cursor example"); + check(docs.stream().anyMatch(r -> r.id().equals("pbs:spec:sdk-linked-and-cursor.md")), "Missing installed Linked specification"); + check(docs.stream().anyMatch(r -> r.id().equals("pbs:example:game:1:src/linked.pbs")), "Missing installed Linked example"); for (var reference : docs) { if (reference.id().startsWith("pbs:example:game:1:")) { Path file = root.resolve(reference.id().substring("pbs:example:game:1:".length())); @@ -75,6 +77,20 @@ public final class InstalledKnowledgeProbe { Path fixtures=Path.of(System.getProperty("pbs.registryConformanceDirectory")); Files.createDirectories(fixtures);Files.write(fixtures.resolve("pbs-list-installed.pbx"),listResult.bytecodeBytes()); System.out.println("Installed List/Cursor execution fixture generated"); + Path linkedRoot=Files.createDirectory(Path.of("linked-example")).toRealPath(); + Files.createDirectories(linkedRoot.resolve("src")); + Files.copy(root.resolve("prometeu.json"),linkedRoot.resolve("prometeu.json")); + Files.writeString(linkedRoot.resolve("src/mod.barrel"),"pub fn frame() -> void;"); + Files.writeString(linkedRoot.resolve("src/main.pbs"),Files.readString(root.resolve("src/linked.pbs"))+"\n"+""" + [Frame] fn frame() -> void { + if linkedExample()!=42 {let failure=1/0;} + } + """); + var linkedResult=BuilderPipelineService.INSTANCE.compile( + BuilderPipelineContext.fromConfig(new BuilderPipelineConfig(false,linkedRoot.toString())),LogAggregator.stdout()); + 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"); verifyExternalSources(provider.getClass().getClassLoader()); registration.unsubscribe(); System.out.println("Installed knowledge verified: " + docs.size() + " references; example compiled"); diff --git a/prometeu-app/src/test/java/p/studio/app/compiler/InstalledKnowledgeTest.java b/prometeu-app/src/test/java/p/studio/app/compiler/InstalledKnowledgeTest.java index 103e3dc8..6911cf04 100644 --- a/prometeu-app/src/test/java/p/studio/app/compiler/InstalledKnowledgeTest.java +++ b/prometeu-app/src/test/java/p/studio/app/compiler/InstalledKnowledgeTest.java @@ -16,6 +16,7 @@ class InstalledKnowledgeTest { assertTrue(log.contains("references; example compiled"), log); assertTrue(log.contains("Packaged external sources verified"), log); assertTrue(log.contains("Installed List/Cursor execution fixture generated"), log); + assertTrue(log.contains("Installed Linked execution fixture generated"), log); } @Test void installedCompilerAndSdkCarryTheSameVerifiedCatalog() throws Exception { diff --git a/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsLinkedTest.java b/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsLinkedTest.java new file mode 100644 index 00000000..113de20a --- /dev/null +++ b/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsLinkedTest.java @@ -0,0 +1,274 @@ +package p.studio.compiler.backend.irvm; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import java.nio.file.*; +import java.nio.charset.StandardCharsets; +import static org.junit.jupiter.api.Assertions.*; + +class PbsLinkedTest { + static void compile(String name, String source) throws Exception { + PbsListCursorTest.compileCollection("linked", name, source); + } + static void probe(String name, String body) throws Exception { + compile(name,"declare service Probe {fn main()->int {"+body+"}}"); + } + @Test void allOperationsPreserveBothDirectionsAndLogicalSize() throws Exception { + probe("basic",""" + let values:linked=new linked();let alias=values; + if values.first().hasSome() or values.last().hasSome() {return 0;} + if values.removeFirst().hasSome() or values.removeLast().hasSome() {return 0;} + values.clear();values.add(20);values.addFirst(1);values.insert(1,2); + values.insert(3,22);values[1]=42; + if (alias.size() as int)!=4 {return 0;} + if (values.first() else 0)!=1 or (values.last() else 0)!=22 {return 0;} + if (values.removeAt(1) else 0)!=42 {return 0;} + if (values.removeFirst() else 0)!=1 {return 0;} + if (values.removeLast() else 0)!=22 {return 0;} + if (values.first() else 0)!=20 or (values.last() else 0)!=20 {return 0;} + if (values.removeLast() else 0)!=20 {return 0;} + if (values.size() as int)!=0 or values.first().hasSome() {return 0;} + values.addFirst(42);if (values.removeFirst() else 0)!=42 {return 0;} + values.add(7);values.clear();values.add(42);return alias[0] else 0; + """); + probe("links",""" + let values=new linked(); + for i:int from 0 until 16 {values.add(i);} + values.insert(8,90);values.insert(0,91);values.insert(18,92); + values.removeAt(9);values.removeFirst();values.removeLast(); + let forward=values.cursor();let backward=values.reverseCursor(); + for i:int from 0 until 16 { + if (values[i] else -1)!=i {return 0;} + if (forward.current() else -1)!=i {return 0;} + if (backward.current() else -1)!=(15-i) {return 0;} + forward.next();backward.next(); + } + if forward.hasNext() or backward.hasNext() {return 0;} + if (values.size() as int)!=16 {return 0;}return 42; + """); + probe("construction",""" + let values:linked=new linked(); + let diamond:linked=new linked<>(); + let maybe:optional (linked)=some(new linked()); + if let owner=maybe {if (owner.size() as int)!=0 {return 0;}} else {return 0;} + let index:int=0;values.insert(index,42);let at:long=0;return values[at] else 0; + """); + probe("long-size",""" + let maximum:long=9223372036854775807; + if _linkedNextSize(maximum-1)!=maximum {return 0;} + let beyondArray:long=4294967296; + if _linkedNextSize(beyondArray-1)!=beyondArray {return 0;} + return 42; + """); + } + @Test void snapshotsHaveTheSharedStatesAndStayIndependentInBothOrders() throws Exception { + for (var method:new String[]{"cursor","reverseCursor"}) { + probe("empty-"+method,"let values=new linked();let cursor=values."+method+"();values.add(42);cursor.next();cursor.next();if cursor.hasNext() or cursor.current().hasSome() {return 0;}return 42;"); + probe("single-"+method,"let values=new linked();values.add(42);let cursor=values."+method+"();values.clear();cursor.next();cursor.next();if cursor.hasNext() {return 0;}return cursor.current() else 0;"); + } + probe("snapshot",""" + let values=new linked();values.add(20);values.add(22);values.add(20); + let forward=values.cursor();let reverse=values.reverseCursor(); + values[0]=99;values.insert(1,7);values.removeAt(2);values.addFirst(3); + values.removeFirst();values.removeLast();values.clear();values.add(100); + if (forward.current() else 0)!=20 or (reverse.current() else 0)!=20 {return 0;} + if forward.hasNext()==false or reverse.hasNext()==false {return 0;} + forward.next();reverse.next(); + if (forward.current() else 0)!=22 or (reverse.current() else 0)!=22 {return 0;} + forward.next();reverse.next();forward.next();reverse.next(); + if forward.hasNext() or reverse.hasNext() {return 0;} + return (forward.current() else 0)+(reverse.current() else 0)+2; + """); + probe("false-present",""" + let values=new linked();values.add(false); + let cursor=values.reverseCursor();values.clear(); + if let value=cursor.current() {if value==false {return 42;}}return 0; + """); + } + @Test void identityAndFullGroupsSurviveAllMutations() throws Exception { + compile("optional-field",""" + declare struct Payload(pub value:optional int); + declare service Probe {fn main()->int { + let values=new linked();values.add(new Payload(some(42))); + let cursor=values.cursor();values.clear(); + if let item=cursor.current() {return item.value else 0;}return 0; + }} + """); + compile("identity",""" + declare struct Item(pub mut value:int); + declare service Probe {fn main()->int { + let item=new Item(20);let other=new Item(20);let values=new linked(); + values.add(item);values.add(other);values.add(item); + let cursor=values.reverseCursor();values.removeAt(1);values.clear();item.value=22; + if let first=cursor.current() {if first!=item {return 0;}} else {return 0;} + cursor.next();if let middle=cursor.current() {if middle==item {return 0;}} else {return 0;} + cursor.next();if let last=cursor.current() {return last.value+other.value;}return 0; + }} + """); + probe("tuple",""" + let values=new linked<(left:int,right:int)>(); + values.add((left:1,right:2));values.addFirst((left:3,right:4)); + values[1]=(left:20,right:22);values.removeFirst(); + let cursor=values.reverseCursor();values.clear(); + if let value=cursor.current() {return value.left+value.right;}return 0; + """); + probe("nested-array",""" + let payload:array=[20];let values=new linked>(); + values.add(payload);values.insert(0,payload);values.removeAt(1); + let cursor=values.cursor();values.clear();payload[0]=42; + if let value=cursor.current() {return value[0] else 0;}return 0; + """); + compile("function",""" + fn answer()->int {return 42;} + declare service Probe {fn main()->int { + let values=new linkedint>();values.add(answer);values.addFirst(answer); + values.removeLast();let cursor=values.reverseCursor();values.clear(); + if let call=cursor.current() {return call();}return 0; + }} + """); + compile("contract",""" + declare contract Reader {fn read()->int;} + declare struct Item(pub value:int); + implements Reader for Item using item {fn read()->int {return item.value;}} + declare service Probe {fn main()->int { + let item=new Item(42);let values=new linked();values.add(item as Reader); + values.addFirst(item as Reader);values.removeAt(1); + let cursor=values.reverseCursor();values.clear(); + if let value=cursor.current() {return value.read();}return 0; + }} + """); + compile("vec2",""" + [BuiltinType(name="vec2",version=1)] declare builtin type Vector(pub x:float,pub y:float) {} + fn nativeProbe()->int { + let values=new linked();values.add(new Vector(1.0,2.0)); + values.addFirst(new Vector(20.0,22.0));values.removeLast(); + let cursor=values.cursor();values.clear(); + if let value=cursor.current() {return (value.x+value.y) as int;}return 0; + } + declare service Probe {fn main()->int {return nativeProbe();}} + """); + String color; + try(var stream=getClass().getResourceAsStream("/game/stdlib/1/core/color/main.pbs")) { + assertNotNull(stream);color=new String(stream.readAllBytes(),StandardCharsets.UTF_8); + } + compile("pixel",color+""" + [BuiltinType(name="pixel",version=1)] declare builtin type Pixel(pub x:long,pub y:long,pub color:Color) {} + fn nativeProbe()->int { + let values=new linked();values.add(new Pixel(1,2,BLUE)); + values.insert(0,new Pixel(20,22,RED));values.removeAt(1); + let cursor=values.reverseCursor();values.clear(); + if let value=cursor.current() {if value.color!=RED {return 0;}return (value.x+value.y) as int;}return 0; + } + declare service Probe {fn main()->int {return nativeProbe();}} + """); + } + @Test void evaluationAndNamedApplicationPreserveSourceOrder() throws Exception { + compile("evaluation",""" + declare struct Effects(pub mut count:int,pub values:linked) { + fn receiver()->linked {this.count=this.count*10+1;return this.values;} + fn index()->int {this.count=this.count*10+2;return 0;} + fn value()->int {this.count=this.count*10+3;return 42;} + } + declare service Probe {fn main()->int { + let values=new linked();values.add(0);let effects=new Effects(0,values); + effects.receiver()[effects.index()]=effects.value();if effects.count!=123 {return 0;} + effects.count=0;effects.receiver().insert apply (value:effects.value(),index:effects.index()); + if effects.count!=132 {return 0;} + let index:int=1;values.removeAt apply index;return values[0] else 0; + }} + """); + } + @Test void invalidIndicesAndGrowthCannotTruncateOrWrap() throws Exception { + var cases=java.util.Map.of( + "fault-read","let values=new linked();return values[0] else 0;", + "fault-write","let values=new linked();values[0]=42;return 0;", + "fault-remove","let values=new linked();values.removeAt(0);return 0;", + "fault-negative","let values=new linked();values.add(1);return values[-1] else 0;", + "fault-insert","let values=new linked();values.insert(1,42);return 0;", + "fault-long-index","let values=new linked();values.add(42);let index:long=4294967296;return values[index] else 0;", + "fault-overflow","_linkedNextSize(9223372036854775807);return 0;"); + for(var item:cases.entrySet())probe(item.getKey(),item.getValue()); + } + @Test void resourceFixturesExposeEveryMutationBoundary() throws Exception { + var operations=java.util.Map.of("insert","values.insert(12,42);","add","values.add(42);", + "addFirst","values.addFirst(42);","remove","let previous=values.removeAt(12);", + "removeFirst","let previous=values.removeFirst();","removeLast","let previous=values.removeLast();", + "replace","values[12]=42;","clear","values.clear();", + "cursor","let snapshot=values.cursor();","reverseCursor","let snapshot=values.reverseCursor();"); + for(var operation:operations.entrySet())compile("refusal-"+operation.getKey(),""" + fn mutationMarker() {let marker:int=314160;} + fn completedMarker() {let marker:int=314161;} + fn performSecond(values:linked) {OPERATION} + fn descend(values:linked,depth:int) {if depth>0 {descend(values,depth-1);} else {performSecond(values);}} + fn perform(values:linked) {descend(values,24);} + declare service Probe {fn main()->int { + let values=new linked();for i:int from 0 until 32 {values.add(i);} + mutationMarker();perform(values);completedMarker();return 42; + }} + """.replace("OPERATION",operation.getValue())); + } + @Test void snapshotsReleaseOriginalNodesAndConsumedPrefixesAtNormalSafepoints() throws Exception { + compile("gc",""" + declare struct Item(pub value:int);declare struct Garbage(); + fn collect() {let marker:int=314159;} + fn makeCursor()->Cursor { + let values=new linked();for i:int from 0 until 1200 {values.add(new Item(i));} + let cursor=values.cursor();values.removeAt(600);values.removeFirst();values.removeLast();values.clear(); + return cursor; + } + fn useCursor() { + let cursor=makeCursor();collect(); + for i:int from 0 until 1199 {cursor.next();}collect(); + for i:int from 0 until 1200 {cursor.next();}collect(); + if let item=cursor.current() {if item.value!=1199 {let failure=1/0;}} else {let failure=1/0;} + } + declare service Probe {fn main()->int { + useCursor();for i:int from 0 until 1200 {let discarded=new Garbage();}collect();return 42; + }} + """); + } + @Test void removedPayloadsAndDoubleLinkedCyclesBecomeCollectible() throws Exception { + compile("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 garbage=new Garbage();}} + fn create()->linked { + let values=new linked();for i:int from 0 until 1200 {values.add(new Item(i));}return values; + } + fn discard(values:linked) {values.removeAt(600);values.removeFirst();values.removeLast();} + fn useCollection() { + let values=create();collect();discard(values);pressure();collect();values.clear();pressure();collect(); + if (values.size() as int)!=0 {let failure=1/0;} + } + declare service Probe {fn main()->int {useCollection();pressure();collect();return 42;}} + """); + } + @Test void realSdkImportsAndReexportsCompile(@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 Items;pub contract Walk;"); + Files.writeString(root.resolve("src/facade/main.pbs"),"import {linked as Items,Cursor as Walk} from @sdk:collections;"); + Files.writeString(root.resolve("src/main.pbs"),""" + import {Items,Walk} from @app:facade; + [Frame] fn frame() -> void { + let values:Items=new Items();values.add(20);values.add(22); + let cursor:Walk=values.reverseCursor();values.clear(); + let total:int=0; + while true { + if let value=cursor.current() {total=total+value;} else {break;} + if cursor.hasNext() {cursor.next();} else {break;} + } + if total!=42 {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()); + assertTrue(compiled.bytecodeBytes().length>0); + Files.write(Path.of(System.getProperty("pbs.registryConformanceDirectory")).resolve("pbs-linked-imports.pbx"),compiled.bytecodeBytes()); + } +} diff --git a/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsListCursorTest.java b/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsListCursorTest.java index a3d1932d..ad18e4e7 100644 --- a/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsListCursorTest.java +++ b/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsListCursorTest.java @@ -18,6 +18,9 @@ import static org.junit.jupiter.api.Assertions.*; class PbsListCursorTest { private static Path directory() { return Path.of(System.getProperty("pbs.registryConformanceDirectory")); } static BytecodeModule compile(String name,String source) throws Exception { + return compileCollection("list", name, source); + } + static BytecodeModule compileCollection(String collection,String name,String source) throws Exception { var diagnostics=DiagnosticSink.empty();var id=new FileId(0);var sdkId=new FileId(1); String sdk; try(var stream=PbsListCursorTest.class.getResourceAsStream("/game/stdlib/1/sdk/collections/main.pbs")) { @@ -33,14 +36,14 @@ class PbsListCursorTest { .intrinsicPool(file.intrinsicPool()).callableSignatures(file.callableSignatures()).build(); var program=new LowerToIRVMService().lower(backend); var module=new BytecodeEmitter().emit(program.coherentEmissionPlan()); - if(name.equals("gc"))module=PbsStructuredValuesTest.withTestSafepoint(module); + if(name.startsWith("gc"))module=PbsStructuredValuesTest.withTestSafepoint(module); new BytecodePreloadVerifierService().verify(module); - Files.createDirectories(directory());Files.write(directory().resolve("pbs-list-"+name+".pbx"),module.serialize()); - if(!name.equals("gc")&&!name.startsWith("refusal-")) { + Files.createDirectories(directory());Files.write(directory().resolve("pbs-"+collection+"-"+name+".pbx"),module.serialize()); + if(!name.startsWith("gc")&&!name.startsWith("refusal-")) { var optimized=new OptimizeIRVMService().optimize(new LowerToIRVMService().lower(backend)); var optimizedModule=new BytecodeEmitter().emit(optimized.coherentEmissionPlan()); new BytecodePreloadVerifierService().verify(optimizedModule); - Files.write(directory().resolve("pbs-list-"+name+"-optimized.pbx"),optimizedModule.serialize()); + Files.write(directory().resolve("pbs-"+collection+"-"+name+"-optimized.pbx"),optimizedModule.serialize()); } return module; } diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/PbsGenericInstantiation.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/PbsGenericInstantiation.java index 395157b0..9e9c6fa3 100644 --- a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/PbsGenericInstantiation.java +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/PbsGenericInstantiation.java @@ -237,8 +237,9 @@ public final class PbsGenericInstantiation { error("ARITY", name(template)+" requires "+parameters(template).size()+" explicit type argument(s)", site); return null; } - if (PbsSdkCollections.isList(template) && PbsSdkCollections.directOptional(arguments.getFirst())) { - error("LIST_OPTIONAL_ELEMENT", "SDK list does not permit a directly optional element", site); + if (PbsSdkCollections.isIndexedCollection(template) && PbsSdkCollections.directOptional(arguments.getFirst())) { + error(PbsSdkCollections.isLinked(template) ? "LINKED_OPTIONAL_ELEMENT" : "LIST_OPTIONAL_ELEMENT", + "SDK " + name(template) + " does not permit a directly optional element", site); return null; } var application = PbsAst.TypeRef.applied(name(template), arguments, template.span()); @@ -631,7 +632,12 @@ public final class PbsGenericInstantiation { } var concreteType = type(applied); if (symbolicProbe) requiredShapes.add(concreteType.name()); - var constructor = PbsSdkCollections.isList(s) && n.ctorName() == null ? "make" : n.ctorName(); + var constructor = PbsSdkCollections.isIndexedCollection(s) && n.ctorName() == null ? "make" : n.ctorName(); + if (constructor != null && s.ctors().stream().noneMatch(c -> c.name().equals(constructor) + && c.parameters().size() == n.arguments().size())) { + error("CONSTRUCTOR_ARITY", "No constructor '" + constructor + "' with " + + n.arguments().size() + " argument(s) for " + name(s), n.span()); + } var fields = constructorParameters(concreteType, constructor, n.arguments().size()); var arguments = new ArrayList(); for (int i = 0; i < n.arguments().size(); i++) arguments.add(expression(n.arguments().get(i), diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/PbsGenericTemplateValidator.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/PbsGenericTemplateValidator.java index a3174614..5effd65c 100644 --- a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/PbsGenericTemplateValidator.java +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/PbsGenericTemplateValidator.java @@ -153,7 +153,7 @@ final class PbsGenericTemplateValidator { context.error("CONTEXT", "Generic construction requires an expected application or explicit type arguments", n.span()); if (d instanceof PbsAst.StructDecl s) { var env = bindings(s, result); - var constructor = PbsSdkCollections.isList(s) && n.ctorName()==null ? "make" : n.ctorName(); + var constructor = PbsSdkCollections.isIndexedCollection(s) && n.ctorName()==null ? "make" : n.ctorName(); var expectedParameters = constructor == null ? map(s.fields(), f -> new PbsAst.Parameter(f.name(), PbsTypeSubstitution.substitute(f.typeRef(), env), f.span())) : s.ctors().stream().filter(c -> c.name().equals(constructor) && c.parameters().size()==n.arguments().size()).findFirst().map(c -> map(c.parameters(), p -> new PbsAst.Parameter(p.name(), PbsTypeSubstitution.substitute(p.typeRef(), env), p.span()))).orElse(ReadOnlyList.empty()); diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/PbsSdkCollections.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/PbsSdkCollections.java index 550962c9..91c73bb8 100644 --- a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/PbsSdkCollections.java +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/PbsSdkCollections.java @@ -9,6 +9,12 @@ public final class PbsSdkCollections { public static boolean isList(PbsAst.TopDecl declaration) { return declaration instanceof PbsAst.StructDecl s && attribute(s.attributes(), "SdkList") != null; } + public static boolean isLinked(PbsAst.TopDecl declaration) { + return declaration instanceof PbsAst.StructDecl s && attribute(s.attributes(), "SdkLinked") != null; + } + public static boolean isIndexedCollection(PbsAst.TopDecl declaration) { + return isList(declaration) || isLinked(declaration); + } public static PbsAst.Attribute attribute(ReadOnlyList attributes, String name) { return attributes.stream().filter(a -> a.trustedSdkOrigin() && a.name().equals(name)).findFirst().orElse(null); } diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/lowering/PbsExecutableBodyLowerer.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/lowering/PbsExecutableBodyLowerer.java index 5c1eccd2..2d76271c 100644 --- a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/lowering/PbsExecutableBodyLowerer.java +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/lowering/PbsExecutableBodyLowerer.java @@ -1113,7 +1113,7 @@ final class PbsExecutableBodyLowerer { var methods=declaration.methods().stream().filter(m->m.name().equals(member.memberName())&&m.parameters().size()==tuple.items().size()).toList(); if(methods.size()!=1)return false; var method=methods.getFirst(); - boolean listIndex=p.studio.compiler.pbs.PbsSdkCollections.isList(declaration)&&java.util.Set.of("insert","clearAt","removeAt","resize","reserve").contains(member.memberName()); + boolean listIndex=p.studio.compiler.pbs.PbsSdkCollections.isIndexedCollection(declaration)&&java.util.Set.of("insert","clearAt","removeAt","resize","reserve").contains(member.memberName()); var receiverName=c.nextLabel("named_receiver"); lowerExpected(member.receiver(),owner,c); int receiver=c.declareLocalSlots(receiverName,1);c.localTypes.put(receiverName,owner); @@ -1166,7 +1166,7 @@ final class PbsExecutableBodyLowerer { var array = PbsRuntimeTypes.unwrap(expressionType(index.receiver(), c)); if(array==null)return null; var declaration=c.types().structs.get(array.name()); - return p.studio.compiler.pbs.PbsSdkCollections.isList(declaration) + return p.studio.compiler.pbs.PbsSdkCollections.isIndexedCollection(declaration) ? declaration.methods().stream().filter(m->m.name().equals("_at")).findFirst().orElseThrow().returnType() : PbsAst.TypeRef.optional(array.inner(),index.span()); } @@ -1617,6 +1617,43 @@ final class PbsExecutableBodyLowerer { var operation=p.studio.compiler.pbs.PbsSdkCollections.argument(binding,"name"); var span=function.span(); switch(operation) { + case "publishFields" -> { + var owners = new java.util.ArrayList(); + int parameter = 0, offset = 0, pops = 0; + while (parameter < function.parameters().size()) { + var receiver = PbsRuntimeTypes.unwrap(function.parameters().get(parameter++).typeRef()); + var owner = receiver.kind() == PbsAst.TypeRefKind.OPTIONAL + ? PbsRuntimeTypes.unwrap(receiver.inner()) : receiver; + var declaration = c.types().structs.get(owner.name()); + if (declaration == null) throw new IllegalArgumentException("Publication destination must be Struct"); + owners.add(c.types().registryType(owner)); + if (receiver.kind() == PbsAst.TypeRefKind.OPTIONAL) { + var absent = c.nextLabel("absent_publication_destination"); + var ready = c.nextLabel("publication_destination_ready"); + optionalPresence(offset, receiver, span, c); + emitJump(IRBackendExecutableFunction.InstructionKind.JMP_IF_FALSE, absent, span, c); + unwrapOptional(offset, receiver, span, c); + emitJump(IRBackendExecutableFunction.InstructionKind.JMP, ready, span, c); + emitLabel(absent, span, c); + emitDefault(c.types().registryType(owner), 1, span, c); + emitLabel(ready, span, c); + } else emitGetLocal(offset, span, c); + offset += c.types().slots(receiver); + pops++; + for (var field : declaration.fields()) { + if (parameter >= function.parameters().size()) throw new IllegalArgumentException("Missing publication field"); + var value = function.parameters().get(parameter++).typeRef(); + if (!c.types().key(value).equals(c.types().key(field.typeRef()))) + throw new IllegalArgumentException("Publication field type mismatch"); + int width = c.types().slots(value); + emitLoadLocalSlots(offset, width, span, c); + packStorage(value, span, c); + offset += width; + pops += storageWidth(value, c); + } + } + registry(FIELDS_PUBLISH, c.types().publicationSchema(owners), 0, pops, 0, span, c); + } case "indexGuard" -> { emitLoadLocalSlots(0,2,span,c); registry(INDEX_GUARD,null,0,2,0,span,c); @@ -1668,9 +1705,9 @@ final class PbsExecutableBodyLowerer { c.instructions().add(new IRBackendExecutableFunction.Instruction(IRBackendExecutableFunction.InstructionKind.RET,"",null,null,span)); } - private boolean lowerListIndex(PbsAst.IndexExpr index, PbsAst.Expression value, PbsAst.TypeRef type, PbsExecutableLoweringContext c) { + private boolean lowerCollectionIndex(PbsAst.IndexExpr index, PbsAst.Expression value, PbsAst.TypeRef type, PbsExecutableLoweringContext c) { var declaration=type==null?null:c.types().structs.get(type.name()); - if(!p.studio.compiler.pbs.PbsSdkCollections.isList(declaration))return false; + if(!p.studio.compiler.pbs.PbsSdkCollections.isIndexedCollection(declaration))return false; var name=value==null?"_at":"_put"; var method=declaration.methods().stream().filter(m->m.name().equals(name)).findFirst().orElseThrow(); lowerExpected(index.receiver(),type,c); @@ -1723,7 +1760,7 @@ final class PbsExecutableBodyLowerer { } private void lowerArrayWrite(PbsAst.IndexExpr index,PbsAst.Expression value,PbsExecutableLoweringContext c) { var type=PbsRuntimeTypes.unwrap(expressionType(index.receiver(),c)); - if(lowerListIndex(index,value,type,c))return; + if(lowerCollectionIndex(index,value,type,c))return; lowerExpected(index.receiver(),type,c); lowerArrayIndex(index.index(),c); lowerExpected(value,type.inner(),c); @@ -1733,7 +1770,7 @@ final class PbsExecutableBodyLowerer { } private void lowerArrayRead(PbsAst.IndexExpr index,PbsExecutableLoweringContext c) { var type=PbsRuntimeTypes.unwrap(expressionType(index.receiver(),c)); - if(lowerListIndex(index,null,type,c))return; + if(lowerCollectionIndex(index,null,type,c))return; var optional=PbsAst.TypeRef.optional(type.inner(),index.span()); lowerExpected(index.receiver(),type,c); lowerArrayIndex(index.index(),c); @@ -1839,9 +1876,14 @@ 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.isList(declaration); + boolean list=p.studio.compiler.pbs.PbsSdkCollections.isIndexedCollection(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().orElseThrow(); + 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) { + reportUnsupportedLowering("No matching constructor '" + expr.ctorName() + "' for " + + expr.typeName() + " with " + expr.arguments().size() + " argument(s)", expr.span(), c); + return; + } var arguments=new java.util.ArrayList(); for(int i=0;im.name().equals(member.memberName())&¶metersMatch(m.parameters(),call.arguments(),c,listIndex) && returnMatches(m.returnType(),owner.name(),c)).findFirst().orElse(null); if(method==null)return false; lowerExpected(member.receiver(),owner,c);int pops=1; diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/lowering/PbsRuntimeTypes.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/lowering/PbsRuntimeTypes.java index 70d2af95..1e6a474b 100644 --- a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/lowering/PbsRuntimeTypes.java +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/lowering/PbsRuntimeTypes.java @@ -138,6 +138,15 @@ final class PbsRuntimeTypes { used.putIfAbsent(ref.declarationKey(), new IRRegistry.TypeDeclaration(ref, null, new IRRegistry.Array(element))); return ref; } + IRRegistry.TypeRef publicationSchema(List owners) { + var ref = new IRRegistry.TypeRef("pbs:field-publication:" + owners.stream() + .map(IRRegistry.TypeRef::declarationKey).map(k -> k.length() + ":" + k) + .collect(java.util.stream.Collectors.joining())); + used.putIfAbsent(ref.declarationKey(), new IRRegistry.TypeDeclaration(ref, null, + new IRRegistry.Struct(ReadOnlyList.wrap(owners.stream() + .map(owner -> new IRRegistry.NamedType(owner, null)).toList())))); + return ref; + } IRRegistry.TypeRef builtin(int id) { var ref = IRRegistry.TypeRef.builtin(id); used.putIfAbsent(ref.declarationKey(),new IRRegistry.TypeDeclaration(ref,null,new IRRegistry.Builtin(id))); diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/parser/PbsDeclarationParser.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/parser/PbsDeclarationParser.java index b27ab7d8..d5ffe671 100644 --- a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/parser/PbsDeclarationParser.java +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/parser/PbsDeclarationParser.java @@ -685,7 +685,7 @@ final class PbsDeclarationParser { final String targetSurface) { for (final var attribute : attributes) { if ("Doc".equals(attribute.name()) || attribute.trustedSdkOrigin() && - "SdkList".equals(attribute.name()) && "struct declarations".equals(targetSurface)) { + java.util.Set.of("SdkList", "SdkLinked").contains(attribute.name()) && "struct declarations".equals(targetSurface)) { continue; } p.studio.compiler.source.diagnostics.Diagnostics.error(context.diagnostics(), diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsEditorialSupportService.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsEditorialSupportService.java index b31b954b..5986bb30 100644 --- a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsEditorialSupportService.java +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsEditorialSupportService.java @@ -759,7 +759,7 @@ public final class PbsEditorialSupportService { final Map completions = new LinkedHashMap<>(); var symbolic = symbolicStruct(receiverType); if (symbolic != null) { - for (var field : symbolic.fields()) if(!p.studio.compiler.pbs.PbsSdkCollections.isList(symbolic)||field.isPublic()) completions.put(field.name(), new PbsEditorialCompletionCandidate( + for (var field : symbolic.fields()) if(!p.studio.compiler.pbs.PbsSdkCollections.isIndexedCollection(symbolic)||field.isPublic()) completions.put(field.name(), new PbsEditorialCompletionCandidate( field.name(), PbsEditorialSymbolKind.FIELD, field.typeRef().surface(), symbolic.name())); for (var method : symbolic.methods()) if(p.studio.compiler.pbs.PbsSdkCollections.attribute(method.attributes(),"SdkPrivate")==null) completions.put(method.name(), new PbsEditorialCompletionCandidate( method.name(), PbsEditorialSymbolKind.METHOD, signatureFromFunction(method.name(), method.parameters(), @@ -778,7 +778,7 @@ public final class PbsEditorialSupportService { final StructInfo structInfo = model.structs.get(receiverType.name()); if (structInfo != null) { for (final var field : structInfo.fields().entrySet()) { - if(model.isSdkList(receiverType)&&!field.getValue().isPublic())continue; + if(model.isSdkIndexedCollection(receiverType)&&!field.getValue().isPublic())continue; completions.put(field.getKey(), new PbsEditorialCompletionCandidate( field.getKey(), PbsEditorialSymbolKind.FIELD, @@ -786,7 +786,7 @@ public final class PbsEditorialSupportService { receiverType.name())); } for (final var method : structInfo.methods().entrySet()) { - if(model.isSdkList(receiverType)&&java.util.Set.of("_at","_put").contains(method.getKey()))continue; + if(model.isSdkPrivateMember(receiverType, method.getKey()))continue; completions.put(method.getKey(), new PbsEditorialCompletionCandidate( method.getKey(), PbsEditorialSymbolKind.METHOD, diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsFlowCallableResolutionAnalyzer.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsFlowCallableResolutionAnalyzer.java index 699cd6ef..5299d79b 100644 --- a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsFlowCallableResolutionAnalyzer.java +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsFlowCallableResolutionAnalyzer.java @@ -51,7 +51,7 @@ final class PbsFlowCallableResolutionAnalyzer { } final boolean listIndexArgument = callExpr.callee() instanceof PbsAst.MemberExpr member && java.util.Set.of("insert","clearAt","removeAt","resize","reserve").contains(member.memberName()) - && context.model().isSdkList(analyzeValueExpression(member.receiver(),context,null).type()); + && context.model().isSdkIndexedCollection(analyzeValueExpression(member.receiver(),context,null).type()); final var callee = analyzeTargetExpression(callExpr.callee(), context, ExprUse.CALL_TARGET); final var expectedInputs = callee.callables().size() == 1 ? callee.callables().getFirst().inputTypes() : java.util.List.of(); @@ -88,7 +88,7 @@ final class PbsFlowCallableResolutionAnalyzer { final var callee = analyzeTargetExpression(applyExpr.callee(), context, ExprUse.APPLY_TARGET); boolean listIndex=applyExpr.callee() instanceof PbsAst.MemberExpr member && java.util.Set.of("insert","clearAt","removeAt","resize","reserve").contains(member.memberName()) - && context.model().isSdkList(analyzeValueExpression(member.receiver(),context,null).type()); + && context.model().isSdkIndexedCollection(analyzeValueExpression(member.receiver(),context,null).type()); TypeView argument; if (applyExpr.argument() instanceof PbsAst.TupleExpr tuple && !tuple.items().isEmpty() && tuple.items().getFirst().label() != null && callee.callables().size() == 1) { @@ -209,7 +209,8 @@ final class PbsFlowCallableResolutionAnalyzer { } return ExprResult.type(field.type()); } - if(model.isSdkList(receiver) && java.util.Set.of("_at","_put").contains(memberExpr.memberName())) { + if(model.isSdkPrivateMember(receiver, memberExpr.memberName()) + && (receiverType == null || !receiver.name().equals(receiverType.name()))) { Diagnostics.error(diagnostics,"E_SEM_SDK_PRIVATE_MEMBER","SDK storage adapters are private",memberExpr.span()); return ExprResult.type(TypeView.unknown()); } diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsFlowSemanticSupport.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsFlowSemanticSupport.java index d0a0263a..49bdf8c3 100644 --- a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsFlowSemanticSupport.java +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsFlowSemanticSupport.java @@ -198,10 +198,17 @@ final class PbsFlowSemanticSupport { static final class Model { p.studio.compiler.pbs.PbsContractTypes contractTypes; - boolean isSdkList(TypeView type) { - return type != null && p.studio.compiler.pbs.PbsSdkCollections.isList(contractTypes.declaration( + boolean isSdkIndexedCollection(TypeView type) { + return type != null && p.studio.compiler.pbs.PbsSdkCollections.isIndexedCollection(contractTypes.declaration( type.sourceType() == null ? PbsAst.TypeRef.simple(type.name(), Span.none()) : type.sourceType())); } + boolean isSdkPrivateMember(TypeView type, String member) { + if (type == null) return false; + var declaration = contractTypes.declaration(type.sourceType() == null + ? PbsAst.TypeRef.simple(type.name(), Span.none()) : type.sourceType()); + return declaration instanceof PbsAst.StructDecl owner && owner.methods().stream() + .anyMatch(m -> m.name().equals(member) && p.studio.compiler.pbs.PbsSdkCollections.attribute(m.attributes(), "SdkPrivate") != null); + } final Map> topLevelCallables = new HashMap<>(); final Map structs = new HashMap<>(); final Map services = new HashMap<>(); diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsFlowStructuralExpressionAnalyzer.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsFlowStructuralExpressionAnalyzer.java index bf7b8a5e..cfade1a1 100644 --- a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsFlowStructuralExpressionAnalyzer.java +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsFlowStructuralExpressionAnalyzer.java @@ -53,7 +53,7 @@ final class PbsFlowStructuralExpressionAnalyzer { if (expression instanceof PbsAst.IndexExpr index) { final var receiver = analyzeValueExpression(index.receiver(), context, null).type(); checkArrayIndex(index.index(), context); - if (model.isSdkList(receiver)) { + if (model.isSdkIndexedCollection(receiver)) { return ExprResult.type(model.structs.get(receiver.name()).methods().get("_at").getFirst().outputType()); } if (receiver.kind() != Kind.ARRAY) { diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/sdk/collections/main.pbs b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/sdk/collections/main.pbs index 7e81e828..fc95befa 100644 --- a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/sdk/collections/main.pbs +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/sdk/collections/main.pbs @@ -154,3 +154,160 @@ implements Cursor for _SnapshotCursor using snapshot { fn next() { snapshot.next(); } fn current() -> optional T { return snapshot.current(); } } + +// Complete-object publication is neutral; this source chooses the node topology. +[StoragePrimitive(name = "publishFields")] +fn _linkedPublish(owner: linked, head: optional _LinkedNode, tail: optional _LinkedNode, length: long, + previous: optional _LinkedNode, previousValue: T, previousPrevious: optional _LinkedNode, previousNext: optional _LinkedNode, + next: optional _LinkedNode, nextValue: T, nextPrevious: optional _LinkedNode, nextNext: optional _LinkedNode) {} + +[StoragePrimitive(name = "publishFields")] +fn _linkedEmpty(owner: linked, head: optional _LinkedNode, tail: optional _LinkedNode, length: long) {} + +[StoragePrimitive(name = "publishFields")] +fn _linkedReplace(owner: _LinkedNode, value: T, previous: optional _LinkedNode, next: optional _LinkedNode) {} + +fn _linkedNextSize(length: long) -> long { + // Check before adding; Linked does not inherit Array's u32 structural bound. + let maximum: long = 9223372036854775807; + _bounds(length, maximum); + return length + 1; +} + +declare struct _LinkedNode(pub mut value: T, pub mut previous: optional _LinkedNode, pub mut next: optional _LinkedNode) { + ctor make(value: T, previous: optional _LinkedNode, next: optional _LinkedNode) { + this.value = value; + this.previous = previous; + this.next = next; + } +} + +[SdkLinked] +declare struct linked(head: optional _LinkedNode, tail: optional _LinkedNode, length: long) { + ctor make() { + this.head = none; + this.tail = none; + this.length = 0; + } + fn size() -> long { return this.length; } + fn first() -> optional T { + if let node = this.head { return some(node.value); } + return none; + } + fn last() -> optional T { + if let node = this.tail { return some(node.value); } + return none; + } + [SdkPrivate] + fn _node(index: long) -> optional _LinkedNode { + _bounds(index, this.length); + let node: optional _LinkedNode = none; + let remaining: long = 0; + if index < this.length / (2 as long) { + node = this.head; + remaining = index; + while remaining > (0 as long) { + if let current = node { node = current.next; } + remaining = remaining - 1; + } + } else { + node = this.tail; + remaining = this.length - index - 1; + while remaining > (0 as long) { + if let current = node { node = current.previous; } + remaining = remaining - 1; + } + } + return node; + } + [SdkPrivate] + fn _at(index: long) -> optional T { + if let node = this._node(index) { return some(node.value); } + return none; + } + [SdkPrivate] + fn _put(index: long, value: T) { + if let node = this._node(index) { + _linkedReplace(node, value, node.previous, node.next); + } + } + fn add(value: T) { this.insert(this.length, value); } + fn addFirst(value: T) { this.insert(0, value); } + fn insert(index: long, value: T) { + if index != this.length { _bounds(index, this.length); } + let required: long = _linkedNextSize(this.length); + let next: optional _LinkedNode = none; + let previous: optional _LinkedNode = this.tail; + if index < this.length { + next = this._node(index); + if let node = next { previous = node.previous; } + } + let inserted: optional _LinkedNode = some(new _LinkedNode(value, previous, next)); + let head: optional _LinkedNode = this.head; + let tail: optional _LinkedNode = this.tail; + if index == (0 as long) { head = inserted; } + if index == this.length { tail = inserted; } + let previousValue: T = value; + let previousPrevious: optional _LinkedNode = none; + let nextValue: T = value; + let nextNext: optional _LinkedNode = none; + if let node = previous { previousValue = node.value; previousPrevious = node.previous; } + if let node = next { nextValue = node.value; nextNext = node.next; } + _linkedPublish(this, head, tail, required, + previous, previousValue, previousPrevious, inserted, + next, nextValue, inserted, nextNext); + } + fn removeAt(index: long) -> optional T { + if let removed = this._node(index) { + let removedValue: optional T = some(removed.value); + let previous: optional _LinkedNode = removed.previous; + let next: optional _LinkedNode = removed.next; + let head: optional _LinkedNode = this.head; + let tail: optional _LinkedNode = this.tail; + if previous.hasNone() { head = next; } + if next.hasNone() { tail = previous; } + let previousValue: T = removed.value; + let previousPrevious: optional _LinkedNode = none; + let nextValue: T = removed.value; + let nextNext: optional _LinkedNode = none; + if let node = previous { previousValue = node.value; previousPrevious = node.previous; } + if let node = next { nextValue = node.value; nextNext = node.next; } + _linkedPublish(this, head, tail, this.length - 1, + previous, previousValue, previousPrevious, next, + next, nextValue, previous, nextNext); + return removedValue; + } + return none; + } + fn removeFirst() -> optional T { + if this.length == (0 as long) { return none; } + return this.removeAt(0); + } + fn removeLast() -> optional T { + if this.length == (0 as long) { return none; } + return this.removeAt(this.length - 1); + } + fn clear() { _linkedEmpty(this, none, none, 0); } + fn cursor() -> Cursor { + let captured: optional _SnapshotNode = none; + let source: optional _LinkedNode = this.tail; + while source.hasSome() { + if let node = source { + captured = some(new _SnapshotNode(node.value, captured)); + source = node.previous; + } + } + return new _SnapshotCursor(captured) as Cursor; + } + fn reverseCursor() -> Cursor { + let captured: optional _SnapshotNode = none; + let source: optional _LinkedNode = this.head; + while source.hasSome() { + if let node = source { + captured = some(new _SnapshotNode(node.value, captured)); + source = node.next; + } + } + return new _SnapshotCursor(captured) as Cursor; + } +} diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/sdk/collections/mod.barrel b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/sdk/collections/mod.barrel index 3aa05292..a983ef18 100644 --- a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/sdk/collections/mod.barrel +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/sdk/collections/mod.barrel @@ -1,2 +1,3 @@ pub struct list; pub contract Cursor; +pub struct linked; diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/pbs-knowledge/examples/game/1/src/linked.pbs b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/pbs-knowledge/examples/game/1/src/linked.pbs new file mode 100644 index 00000000..e4eaf620 --- /dev/null +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/pbs-knowledge/examples/game/1/src/linked.pbs @@ -0,0 +1,27 @@ +import { linked, Cursor } from @sdk:collections; + +fn sumLinkedSnapshot(snapshot: Cursor) -> int { + let total: int = 0; + while true { + if let value = snapshot.current() { total = total + value; } + else { break; } + if snapshot.hasNext() { snapshot.next(); } + else { break; } + } + return total; +} + +fn linkedExample() -> int { + let values: linked = new linked(); + values.add(20); + values.add(22); + let forward: Cursor = values.cursor(); + let reverse: Cursor = values.reverseCursor(); + values[0] = 99; + values.clear(); // Completed snapshots still visit 20/22 and 22/20. + let forwardTotal: int = sumLinkedSnapshot(forward); + let reverseTotal: int = sumLinkedSnapshot(reverse); + if forwardTotal != 42 or reverseTotal != 42 { return 0; } + // next() retains 22 in forward.current(), and 20 in reverse.current(). + return reverseTotal; +} diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/pbs-knowledge/examples/game/1/src/mod.barrel b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/pbs-knowledge/examples/game/1/src/mod.barrel index c15a13d8..69d88a0f 100644 --- a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/pbs-knowledge/examples/game/1/src/mod.barrel +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/pbs-knowledge/examples/game/1/src/mod.barrel @@ -3,3 +3,4 @@ pub fn frame() -> void; pub fn contractExample() -> int; pub fn genericsExample() -> int; pub fn collectionsExample() -> int; +pub fn linkedExample() -> int; diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/test/java/p/studio/compiler/pbs/PbsGateUSdkInterfaceConformanceTest.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/test/java/p/studio/compiler/pbs/PbsGateUSdkInterfaceConformanceTest.java index e645613f..3fa38e86 100644 --- a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/test/java/p/studio/compiler/pbs/PbsGateUSdkInterfaceConformanceTest.java +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/test/java/p/studio/compiler/pbs/PbsGateUSdkInterfaceConformanceTest.java @@ -89,6 +89,41 @@ class PbsGateUSdkInterfaceConformanceTest { assertTrue(copied.hasErrors(),"Project attributes cannot acquire SDK bindings"); } + @Test + void linkedRejectsOptionalElementsCapacityAndPrivateProjectAccess() throws IOException { + var cases=java.util.Map.ofEntries( + java.util.Map.entry("optional","let xs:linked=new linked();"), + java.util.Map.entry("grouped","let xs:linked<(optional int)>=new linked<(optional int)>();"), + java.util.Map.entry("capacity","let xs=new linked(4);"), + java.util.Map.entry("context","let xs=new linked();"), + java.util.Map.entry("invariance","let xs:linked=new linked();"), + java.util.Map.entry("index","let xs=new linked();let invalid=xs[1.5];"), + java.util.Map.entry("head","let xs=new linked();let exposed=xs.head;"), + java.util.Map.entry("node","let xs=new linked();let exposed=xs._node(0);"), + java.util.Map.entry("adapter","let xs=new linked();let exposed=xs._at(0);"), + java.util.Map.entry("payload","let xs=new linked();let value:int=1;xs.add(value);"), + java.util.Map.entry("holes","let xs=new linked();xs.clearAt(0);"), + java.util.Map.entry("value-remove","let xs=new linked();xs.remove(42);")); + for(var entry:cases.entrySet()) { + var result=compileWorkspaceModule(tempDir.resolve("linked-negative-"+entry.getKey()), + "import {linked} from @sdk:collections;[Frame] fn frame()->void {"+entry.getValue()+"}", + "pub fn frame()->void;",1,null); + assertTrue(result.diagnostics().hasErrors(),entry.getKey()); + } + var diagnostics=DiagnosticSink.empty(); + new PbsFrontendCompiler().compileFile(new FileId(202),""" + declare struct linked(value:T) {} + fn main() {let xs=new linked(1);let invalid=xs[0];} + """,diagnostics,SourceKind.PROJECT); + assertTrue(diagnostics.stream().anyMatch(d->d.getCode().equals("E_SEM_ARRAY_RECEIVER"))); + var copied=DiagnosticSink.empty(); + new PbsFrontendCompiler().compileFile(new FileId(203),""" + [SdkLinked] declare struct linked(value:T) {} + [StoragePrimitive(name="publishFields")] fn fake() {} + """,copied,SourceKind.PROJECT); + assertTrue(copied.hasErrors()); + } + @Test void removedInputObjectsExplainTheirMigration() throws IOException { final var result = compileWorkspaceModule(tempDir.resolve("removed-input"), """ diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/test/java/p/studio/compiler/pbs/semantics/PbsListCursorEditorialTest.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/test/java/p/studio/compiler/pbs/semantics/PbsListCursorEditorialTest.java index adeb59c0..57c09099 100644 --- a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/test/java/p/studio/compiler/pbs/semantics/PbsListCursorEditorialTest.java +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/test/java/p/studio/compiler/pbs/semantics/PbsListCursorEditorialTest.java @@ -11,14 +11,16 @@ import java.nio.charset.StandardCharsets; import static org.junit.jupiter.api.Assertions.*; class PbsListCursorEditorialTest { - @Test void concreteApiHidesStorageAndKeepsSdkDefinitionOrigins() throws Exception { + @org.junit.jupiter.params.ParameterizedTest + @org.junit.jupiter.params.provider.ValueSource(strings={"list","linked"}) + void concreteApiHidesStorageAndKeepsSdkDefinitionOrigins(String collection) 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); - var list=library.topDecls().stream().filter(d->d instanceof PbsAst.StructDecl s&&s.name().equals("list")).findFirst().orElseThrow(); + var list=library.topDecls().stream().filter(d->d instanceof PbsAst.StructDecl s&&s.name().equals(collection)).findFirst().orElseThrow(); var cursor=library.topDecls().stream().filter(d->d instanceof PbsAst.ContractDecl c&&c.name().equals("Cursor")).findFirst().orElseThrow(); var source=""" import {list as Values,Cursor} from @sdk:collections; @@ -26,19 +28,19 @@ class PbsListCursorEditorialTest { let created:Values=new Values(0); values.add(42); cursor.hasNext(); return cursor.current(); } - """; + """.replace("{list as", "{"+collection+" as").replace("new Values(0)", collection.equals("list")?"new Values(0)":"new Values()"); var id=new FileId(2);var ast=PbsParser.parse(PbsLexer.lex(source,id,diagnostics),id,diagnostics); assertFalse(diagnostics.hasErrors()); var supplemental=ReadOnlyList.from(new PbsAst.TypeBindingDecl("Values",list,ast.span()),cursor); var service=new PbsEditorialSupportService();int member=source.indexOf("values.add")+7; var typeHover=service.hover(source,ast,supplemental,source.indexOf("Values")).orElseThrow(); assertFalse(typeHover.signatures().stream().anyMatch(s->s.label().startsWith("_"))); - var constructors=service.signatureHelp(source,ast,supplemental,source.indexOf("new Values(0")+11).orElseThrow().signatures(); - assertEquals(2,constructors.size()); + var constructors=service.signatureHelp(source,ast,supplemental,source.indexOf("new Values(")+11).orElseThrow().signatures(); + assertEquals(collection.equals("list")?2:1,constructors.size()); assertTrue(constructors.stream().allMatch(s->!s.label().contains("storage")&&!s.label().contains("$generic$"))); var completions=service.completion(source,ast,supplemental,member); assertTrue(completions.stream().anyMatch(c->c.label().equals("add")&&c.detail().contains("int"))); - assertFalse(completions.stream().anyMatch(c->java.util.Set.of("storage","length","_at","_put").contains(c.label()))); + assertFalse(completions.stream().anyMatch(c->java.util.Set.of("storage","length","head","tail","_at","_put","_node").contains(c.label()))); var definition=service.definition(source,ast,supplemental,member); assertEquals(sdkId,definition.getFirst().span().getFileId()); int current=source.indexOf("cursor.current")+7; diff --git a/prometeu-compiler/prometeu-build-pipeline/src/main/java/p/studio/compiler/backend/bytecode/BytecodeOpcodeLayout.java b/prometeu-compiler/prometeu-build-pipeline/src/main/java/p/studio/compiler/backend/bytecode/BytecodeOpcodeLayout.java index 67234e66..c89d247e 100644 --- a/prometeu-compiler/prometeu-build-pipeline/src/main/java/p/studio/compiler/backend/bytecode/BytecodeOpcodeLayout.java +++ b/prometeu-compiler/prometeu-build-pipeline/src/main/java/p/studio/compiler/backend/bytecode/BytecodeOpcodeLayout.java @@ -8,7 +8,7 @@ final class BytecodeOpcodeLayout { 0x30,0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39,0x3a,0x3b,0x3c,0x3d,0x3e,0x51,0x80,0xa7 -> 2; case 0x16 -> 3; case 0x02,0x03,0x04,0x10,0x17,0x18,0x40,0x41,0x42,0x43,0x50,0x53,0x57,0x70,0x71,0x72, - 0x90,0x91,0x92,0xa0,0xa3,0xa4,0xa5,0xa6,0xa8,0xa9 -> 6; + 0x90,0x91,0x92,0xa0,0xa3,0xa4,0xa5,0xa6,0xa8,0xa9,0xab -> 6; case 0x14,0x15,0x52,0x58,0x93,0x94,0x95,0x96,0xa1,0xa2 -> 10; case 0xaa -> 18; default -> throw new BytecodeMarshalingException(BytecodeMarshalingErrorCode.MARSHAL_VERIFY_PRECHECK_UNKNOWN_OPCODE, diff --git a/prometeu-compiler/prometeu-build-pipeline/src/main/java/p/studio/compiler/backend/bytecode/BytecodePreloadVerifierService.java b/prometeu-compiler/prometeu-build-pipeline/src/main/java/p/studio/compiler/backend/bytecode/BytecodePreloadVerifierService.java index 6b87c1ee..76fcf7b8 100644 --- a/prometeu-compiler/prometeu-build-pipeline/src/main/java/p/studio/compiler/backend/bytecode/BytecodePreloadVerifierService.java +++ b/prometeu-compiler/prometeu-build-pipeline/src/main/java/p/studio/compiler/backend/bytecode/BytecodePreloadVerifierService.java @@ -59,6 +59,10 @@ public class BytecodePreloadVerifierService { case 0xa0 -> check(type(r,a).body() instanceof Struct,"Struct category"); case 0xa1,0xa2 -> field(r,a,b); case 0xa3,0xa4,0xa5,0xa6,0xa8,0xa9 -> array(r,a); + case 0xab -> { + check(type(r,a).body() instanceof Struct,"Struct publication schema"); + for (var entry : ((Struct)type(r,a).body()).fields()) check(r.type(entry.type()).body() instanceof Struct,"Struct publication destination"); + } case 0xaa -> {array(r,a);field(r,b,instruction.third());field(r,b,instruction.fourth());check(instruction.third()!=instruction.fourth(),"publication fields must differ");} default -> { } } @@ -167,6 +171,14 @@ public class BytecodePreloadVerifierService { case 0xa4 -> {consume(s,facts(r,type(r,a).identity()),typed);s.stack.add(carrier("i64"));} case 0xa5 -> {consume(s,List.of(carrier("i64")),typed);consume(s,facts(r,type(r,a).identity()),typed);produce(s,facts(r,array(r,a).element()),i.pc());} case 0xa6 -> {consume(s,facts(r,array(r,a).element()),typed);consume(s,List.of(carrier("i64")),typed);consume(s,facts(r,type(r,a).identity()),typed);} + case 0xab -> { + var expected=new ArrayList(); + for(var entry:((Struct)type(r,a).body()).fields()) { + expected.addAll(facts(r,entry.type())); + for(var field:((Struct)r.type(entry.type()).body()).fields()) expected.addAll(facts(r,field.type())); + } + consume(s,expected,typed); + } case 0xa7 -> consume(s,List.of(carrier("i64"),carrier("i64")),typed); case 0xa8 -> consume(s,List.of(carrier("i64")),typed); case 0xa9,0xaa -> { diff --git a/prometeu-compiler/prometeu-build-pipeline/src/main/java/p/studio/compiler/backend/registry/RegistryInstructionLowerer.java b/prometeu-compiler/prometeu-build-pipeline/src/main/java/p/studio/compiler/backend/registry/RegistryInstructionLowerer.java index a1c56ead..36fbc0d4 100644 --- a/prometeu-compiler/prometeu-build-pipeline/src/main/java/p/studio/compiler/backend/registry/RegistryInstructionLowerer.java +++ b/prometeu-compiler/prometeu-build-pipeline/src/main/java/p/studio/compiler/backend/registry/RegistryInstructionLowerer.java @@ -51,6 +51,14 @@ public final class RegistryInstructionLowerer { pops=instruction.kind()==IRRegistryInstruction.Kind.STRUCT_SET?1+width:1;pushes=instruction.kind()==IRRegistryInstruction.Kind.STRUCT_GET?width:0; } } + case FIELDS_PUBLISH -> { + if (!(body instanceof Struct schema)) throw new IllegalArgumentException("Struct publication schema required"); + for (var entry : schema.fields()) { + if (!(registry.type(entry.type()).body() instanceof Struct owner)) throw new IllegalArgumentException("Struct publication destination required"); + pops = Math.addExact(pops, 1); + for (var field : owner.fields()) pops = Math.addExact(pops, registry.width(field.type())); + } + } case INDEX_GUARD -> pops=2; case ARRAY_CHECK_LENGTH,ARRAY_COPY,STORAGE_PUBLISH -> { if(!(body instanceof Array array))throw new IllegalArgumentException("Array category required"); diff --git a/prometeu-compiler/prometeu-build-pipeline/src/test/java/p/studio/compiler/backend/irvm/IRVMIntrinsicRegistryParityTest.java b/prometeu-compiler/prometeu-build-pipeline/src/test/java/p/studio/compiler/backend/irvm/IRVMIntrinsicRegistryParityTest.java index efeddc3c..a34793ea 100644 --- a/prometeu-compiler/prometeu-build-pipeline/src/test/java/p/studio/compiler/backend/irvm/IRVMIntrinsicRegistryParityTest.java +++ b/prometeu-compiler/prometeu-build-pipeline/src/test/java/p/studio/compiler/backend/irvm/IRVMIntrinsicRegistryParityTest.java @@ -77,7 +77,7 @@ class IRVMIntrinsicRegistryParityTest { assertNotNull(input); properties.load(input); } - assertEquals("f7d7c167531bb662a1af9d73fc326bb476bf8aa7", properties.getProperty("runtime.revision")); + assertEquals("57992cf214e8a5f9de53a40dba9aaa7fab038c91", properties.getProperty("runtime.revision")); for (var name : List.of("INTRINSICS.csv", "BUILTIN_CONSTANTS.csv")) { assertEquals(properties.getProperty(name + ".sha256"), HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes(name)))); diff --git a/prometeu-compiler/prometeu-build-pipeline/src/test/java/p/studio/compiler/backend/registry/StoragePublicationPipelineTest.java b/prometeu-compiler/prometeu-build-pipeline/src/test/java/p/studio/compiler/backend/registry/StoragePublicationPipelineTest.java index 582aa1be..72a240b6 100644 --- a/prometeu-compiler/prometeu-build-pipeline/src/test/java/p/studio/compiler/backend/registry/StoragePublicationPipelineTest.java +++ b/prometeu-compiler/prometeu-build-pipeline/src/test/java/p/studio/compiler/backend/registry/StoragePublicationPipelineTest.java @@ -31,6 +31,35 @@ class StoragePublicationPipelineTest { } private void number(long value){literal(PUSH_I64,Long.toString(value));} + @Test void multiObjectFieldsPublishThroughNeutralOrdinaryAndOptimizedProducers() throws Exception { + var schema = new TypeRef("synthetic:publication-schema"); + var registry = new IRRegistry(ReadOnlyList.from( + new TypeDeclaration(INTEGER,null,new Builtin(0x10)), + new TypeDeclaration(LONG,null,new Builtin(0x11)), + new TypeDeclaration(OWNER,"State",new Struct(ReadOnlyList.from( + new NamedType(LONG,"generation"),new NamedType(INTEGER,"answer")))), + new TypeDeclaration(schema,null,new Struct(ReadOnlyList.from( + new NamedType(OWNER,null),new NamedType(OWNER,null))))),null); + typed(STRUCT_NEW,OWNER,0);local(SET_LOCAL,0); + typed(STRUCT_NEW,OWNER,0);local(SET_LOCAL,1); + local(GET_LOCAL,0);number(7);literal(PUSH_I32,"20"); + local(GET_LOCAL,1);number(9);literal(PUSH_I32,"42"); + typed(FIELDS_PUBLISH,schema,0); + local(GET_LOCAL,1);typed(STRUCT_GET,OWNER,1);literal(RET,null); + var function=new IRBackendExecutableFunction(new FileId(0),new ModuleId(0),"main",new CallableId(0),0,0,0,2,1,6, + ReadOnlyList.wrap(instructions),null,new FunctionMetadata(new Signature(null,ReadOnlyList.from(INTEGER)),null,Role.NONE)); + var backend=IRBackend.builder().entryPointModuleId(new ModuleId(0)).entryPointCallableName("main") + .registry(registry).executableFunctions(ReadOnlyList.from(function)).build(); + for(boolean optimize:new boolean[]{false,true}) { + var program=new LowerToIRVMService().lower(backend); + if(optimize)program=new OptimizeIRVMService().optimize(program); + var module=new BytecodeEmitter().emit(program.coherentEmissionPlan()); + new BytecodePreloadVerifierService().verify(module); + var directory=Path.of("build/registry-conformance");Files.createDirectories(directory); + Files.write(directory.resolve("common-fields"+(optimize?"-optimized":"")+".pbx"),module.serialize()); + } + } + @Test void guardsTransfersAndPublicationSurviveBothProducerPaths() throws Exception { var registry=new IRRegistry(ReadOnlyList.from( new TypeDeclaration(INTEGER,null,new Builtin(0x10)),new TypeDeclaration(LONG,null,new Builtin(0x11)), diff --git a/prometeu-compiler/prometeu-frontend-api/src/main/java/p/studio/compiler/models/registry/IRRegistryInstruction.java b/prometeu-compiler/prometeu-frontend-api/src/main/java/p/studio/compiler/models/registry/IRRegistryInstruction.java index 60a3a335..aef81401 100644 --- a/prometeu-compiler/prometeu-frontend-api/src/main/java/p/studio/compiler/models/registry/IRRegistryInstruction.java +++ b/prometeu-compiler/prometeu-frontend-api/src/main/java/p/studio/compiler/models/registry/IRRegistryInstruction.java @@ -15,7 +15,7 @@ public record IRRegistryInstruction(Kind kind, IRRegistry.TypeRef type, IRRegist REF_IS_EXACT(0x93), REF_IMPLEMENTS(0x94), REF_TO_TRAIT(0x95), REF_CAST(0x96), STRUCT_NEW(0xa0), STRUCT_GET(0xa1), STRUCT_SET(0xa2), ARRAY_NEW(0xa3), ARRAY_LEN(0xa4), ARRAY_GET(0xa5), ARRAY_SET(0xa6), - INDEX_GUARD(0xa7), ARRAY_CHECK_LENGTH(0xa8), ARRAY_COPY(0xa9), STORAGE_PUBLISH(0xaa); + INDEX_GUARD(0xa7), ARRAY_CHECK_LENGTH(0xa8), ARRAY_COPY(0xa9), STORAGE_PUBLISH(0xaa), FIELDS_PUBLISH(0xab); private final int opcode; Kind(int opcode) { this.opcode=opcode; } public int opcode(){return opcode;} diff --git a/tools/pbx-conformance/README.md b/tools/pbx-conformance/README.md index 4d862509..20a6f48b 100644 --- a/tools/pbx-conformance/README.md +++ b/tools/pbx-conformance/README.md @@ -264,3 +264,33 @@ Evidence prints compiler/provider source hashes, exact provider revision and dir state, toolchain, platform/profile, capabilities, every default VM ceiling and each explicitly lowered refusal limit. Development runs against a dirty provider are identified as such; final catalog verification requires its clean selected commit. + + +## SDK Linked and multi-object publication + +```sh +./gradlew :prometeu-compiler:prometeu-build-pipeline:test :prometeu-architecture-tests:test :prometeu-app:installedKnowledgeTest +python3 tools/pbx-conformance/run.py --runtime ../runtime --linked-only +``` + +The full harness requires this corpus too. Ordinary and optimized source programs +exercise the complete Linked API, both snapshot orders, empty/single/multiple +states, reciprocal links, identities and full native/tuple/contract/Fn groups, +logical and long bounds, contextual construction and source/named evaluation. +Neutral common-IR fixtures execute FIELDS_PUBLISH without PBS or collection types. + +Ten explicit mutation boundaries qualify every mutation and both captures. The +harness lowers resource ceilings around measured setup/success peaks and compares +all prior Linked roots, optional-link carriers, nodes and complete groups after +each refusal. Node allocation, optional removed-value preparation, snapshot-node +allocation and frame/operand preparation must all produce observed refusals. +Publication itself uses no allocation or scratch; provider tests prove it succeeds +at already exhausted allocation ceilings and rejects late invalid groups before +any write, including for null destinations and aliased targets. + +Normal GC safepoints qualify removal/clear without snapshots (1,200 → 1,197 → 0 +nodes and payloads), and snapshot traversal (1,200 → 1 → 1 → 0). Fixtures introduce +ordinary garbage pressure so every asserted round performs an actual collection. +Snapshots retain no editable Linked nodes. Source imports/reexports and a separately +compiled installed-JAR example must execute; its forward/reverse traversals retain +final values 22/20 after later replacement and clear. Missing fixtures are failures. diff --git a/tools/pbx-conformance/main.rs b/tools/pbx-conformance/main.rs index 7db24459..6704c6de 100644 --- a/tools/pbx-conformance/main.rs +++ b/tools/pbx-conformance/main.rs @@ -41,6 +41,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 == "--linked-only") { verify_common_storage_fixtures(&root); verify_pbs_linked_fixtures(&root); return; } if std::env::args().any(|arg| arg == "--list-cursor-only") { verify_common_storage_fixtures(&root); verify_pbs_list_cursor_fixtures(&root); return; } if std::env::args().any(|arg| arg == "--generic-contracts-only") { verify_pbs_generic_contract_fixtures(&root); return; } if std::env::args().any(|arg| arg == "--generic-structs-only") { verify_pbs_generic_struct_fixtures(&root); return; } @@ -55,6 +56,7 @@ fn main() { verify_pbs_generic_struct_fixtures(&root); verify_common_storage_fixtures(&root); verify_pbs_list_cursor_fixtures(&root); + verify_pbs_linked_fixtures(&root); verify_pbs_resource_refusals(&root); verify_pbs_closure_frames(&root); for name in [ @@ -491,7 +493,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-") || 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-") || 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) @@ -1168,10 +1170,12 @@ fn verify_list_cursor_refusals(root:&std::path::Path) { assert!(operand_preparation,"source operation operand/frame preparation refusal"); } -fn verify_list_cursor_gc(root:&std::path::Path) { +fn verify_list_cursor_gc(root:&std::path::Path) { verify_collection_cursor_gc(root,"list"); } + +fn verify_collection_cursor_gc(root:&std::path::Path,collection:&str) { use prometeu_vm::{LogicalFrameEndingReason as End,resource_budget::RuntimeLimits}; use prometeu_vm::resource_diagnostics::StorageValue as V; - let bytes=std::fs::read(root.join("pbs-list-gc.pbx")).expect("mandatory snapshot GC fixture"); + let bytes=std::fs::read(root.join(format!("pbs-{collection}-gc.pbx"))).expect("mandatory snapshot GC fixture"); let image=ValidatedProgramImage::load(&bytes,&mut LoadBudget::new(LoadLimits::default()),caps::NONE).unwrap(); let mut vm=VirtualMachine::from_image(image.clone(),RuntimeLimits::default());vm.prepare_boot_call().unwrap(); let mut previous=0; @@ -1184,9 +1188,10 @@ fn verify_list_cursor_gc(root:&std::path::Path) { prometeu_bytecode::registry::TypeKind::Array(_))),"Cursor retains no source or snapshot array"); let named=|name:&str|objects.iter().filter(|o|image.registry().declarations().types[o.type_id.0 as usize].name.as_deref()==Some(name)).collect::>(); assert_eq!(named("_SnapshotNode").len(),nodes,"prefix nodes round {round}"); + if collection=="linked" {assert!(named("_LinkedNode").is_empty(),"snapshot does not retain original Linked nodes");} let values=named("Item");assert_eq!(values.len(),items,"captured object roots round {round}"); if items==1 {assert_eq!(values[0].groups[0],[V::Int32(1199)],"sticky last payload remains live");} - println!("PBS CURSOR GC PASS round={round} nodes={nodes} items={items} collected={}",snapshot.gc.reclaimed); + println!("PBS {} CURSOR GC PASS round={round} nodes={nodes} items={items} collected={}",collection.to_uppercase(),snapshot.gc.reclaimed); } 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)]); @@ -1194,7 +1199,7 @@ fn verify_list_cursor_gc(root:&std::path::Path) { fn verify_common_storage_fixtures(root:&std::path::Path) { use prometeu_vm::{LogicalFrameEndingReason as End,resource_budget::RuntimeLimits}; - for name in ["common-storage","common-storage-optimized"] { + for name in ["common-storage","common-storage-optimized","common-fields","common-fields-optimized"] { let bytes=std::fs::read(root.join(format!("{name}.pbx"))).expect("mandatory non-PBS storage fixture"); let image=ValidatedProgramImage::load(&bytes,&mut LoadBudget::new(LoadLimits::default()),caps::NONE).unwrap(); let mut vm=VirtualMachine::from_image(image,RuntimeLimits::default());vm.prepare_boot_call().unwrap(); @@ -1205,24 +1210,176 @@ fn verify_common_storage_fixtures(root:&std::path::Path) { } } -fn verify_list_cursor_distribution(root:&std::path::Path) { +fn verify_list_cursor_distribution(root:&std::path::Path) { verify_collection_distribution(root,"list",22); } + +fn verify_collection_distribution(root:&std::path::Path,collection:&str,last:i32) { use prometeu_vm::{LogicalFrameEndingReason as End,resource_budget::RuntimeLimits}; for name in ["imports","installed"] { - let bytes=std::fs::read(root.join(format!("pbs-list-{name}.pbx"))).expect("mandatory workspace/installed List fixture"); + let bytes=std::fs::read(root.join(format!("pbs-{collection}-{name}.pbx"))).expect("mandatory workspace/installed List fixture"); let image=ValidatedProgramImage::load(&bytes,&mut LoadBudget::new(LoadLimits::default()),caps::NONE).unwrap(); let mut vm=VirtualMachine::from_image(image.clone(),RuntimeLimits::default());vm.prepare_boot_call().unwrap(); let report=vm.run_budget(1_000_000,&mut NoNative,&mut HostContext::new(None)).unwrap(); assert!(matches!(report.reason,End::FrameSync|End::Halted|End::EndOfRom),"{name}: {report:?}"); use prometeu_vm::resource_diagnostics::StorageValue as V; let objects=vm.heap().diagnostic_typed_storage(); - let cursor=objects.iter().find(|o|image.registry().declarations().types[o.type_id.0 as usize].name.as_deref()==Some("_SnapshotCursor")) - .expect("distributed frame actually created its shared snapshot Cursor"); - let V::Reference(current)=cursor.groups[0][0] else {panic!("nonempty Cursor retains its current node carrier")}; - let carrier=objects.iter().find(|o|o.reference==current).unwrap(); - let V::Reference(node)=carrier.groups[0][0] else {panic!("current points at a snapshot node")}; - let node=objects.iter().find(|o|o.reference==node).unwrap(); - assert_eq!(node.groups[0],[V::Int32(22)],"{name}: complete traversal retains the final value"); - assert_eq!(node.groups[1],[V::Null],"{name}: final node has no successor"); - println!("PBS LIST/CURSOR DISTRIBUTION LOAD/EXEC PASS {name}"); + let cursors=objects.iter().filter(|o|image.registry().declarations().types[o.type_id.0 as usize].name.as_deref()==Some("_SnapshotCursor")).collect::>(); + assert!(!cursors.is_empty(),"distributed frame actually created its shared snapshot Cursor"); + let mut retained=Vec::new(); + for cursor in cursors { + let V::Reference(current)=cursor.groups[0][0] else {panic!("nonempty Cursor retains its current node carrier")}; + let carrier=objects.iter().find(|o|o.reference==current).unwrap(); + let V::Reference(node)=carrier.groups[0][0] else {panic!("current points at a snapshot node")}; + let node=objects.iter().find(|o|o.reference==node).unwrap(); + let V::Int32(value)=node.groups[0][0] else {panic!("typed captured value")}; + retained.push(value); + assert_eq!(node.groups[1],[V::Null],"{name}: final node has no successor"); + } + retained.sort_unstable(); + let expected=if collection=="linked"&&name=="installed" {vec![20,22]} else {vec![last]}; + assert_eq!(retained,expected,"{collection} {name}: complete traversal retains each final value"); + println!("PBS {} DISTRIBUTION LOAD/EXEC PASS {name}",collection.to_uppercase()); } } + +fn verify_pbs_linked_fixtures(root: &std::path::Path) { + use prometeu_vm::{LogicalFrameEndingReason as End, resource_budget::{RuntimeLimits,RuntimeResource}}; + use prometeu_bytecode::TRAP_OOB; + let successful=["basic","links","construction","long-size","empty-cursor","empty-reverseCursor", + "single-cursor","single-reverseCursor","snapshot","false-present","optional-field","identity","tuple","nested-array","function","evaluation","vec2","pixel","contract"]; + let faults=[("fault-read",TRAP_OOB),("fault-write",TRAP_OOB),("fault-negative",TRAP_OOB), + ("fault-insert",TRAP_OOB),("fault-remove",TRAP_OOB),("fault-overflow",TRAP_OOB),("fault-long-index",TRAP_OOB)]; + let cases=successful.into_iter().map(|n|(n,None)).chain(faults.into_iter().map(|(n,c)|(n,Some(c)))) + .flat_map(|(name,fault)|[(name.to_string(),fault),(format!("{name}-optimized"),fault)]); + for (name,fault) in cases { + let bytes=std::fs::read(root.join(format!("pbs-linked-{name}.pbx"))) + .unwrap_or_else(|e|panic!("missing mandatory SDK Linked fixture {name}: {e}")); + let image=ValidatedProgramImage::load(&bytes,&mut LoadBudget::new(LoadLimits::default()),caps::NONE) + .unwrap_or_else(|e|panic!("Linked {name}: {e:?}")); + let mut vm=VirtualMachine::from_image(image,RuntimeLimits::default()); + let observer=vm.resource_observer(); + vm.prepare_boot_call().unwrap(); + let report=vm.run_budget(1_000_000,&mut NoNative,&mut HostContext::new(None)).unwrap(); + if let Some(code)=fault { + let End::Trap(info)=report.reason else {panic!("{name}: {report:?}")}; + assert_eq!(info.code,code,"{name}: {info:?}"); + } else { + assert!(matches!(report.reason,End::Halted|End::EndOfRom),"{name}: {report:?}"); + assert_eq!(vm.operand_stack_top(1),vec![Value::Int32(42)],"{name}"); + } + drop(vm); + for resource in [RuntimeResource::GuestBytes,RuntimeResource::HandleSlots,RuntimeResource::AuxiliaryBytes, + RuntimeResource::TemporaryBytes,RuntimeResource::StringBytes,RuntimeResource::StringAllocations] { + assert_eq!(observer.used(resource),0,"{name}: final owner release {resource:?}"); + } + println!("PBS LINKED SOURCE/LOAD/EXEC PASS {name}"); + } + verify_linked_collection_gc(root); + verify_linked_refusals(root); + verify_collection_cursor_gc(root,"linked"); + verify_collection_distribution(root,"linked",20); +} + +fn linked_state(vm:&VirtualMachine,image:&ValidatedProgramImage)->Vec { + use prometeu_vm::resource_diagnostics::StorageValue as V; + let objects=vm.heap().diagnostic_typed_storage(); + let root=objects.iter().find(|o|image.registry().declarations().types[o.type_id.0 as usize].name.as_deref()==Some("linked")) + .expect("source Linked remains observable"); + let mut pending=vec![root.reference];let mut state=Vec::new(); + while let Some(reference)=pending.pop() { + if state.iter().any(|o:&prometeu_vm::resource_diagnostics::StorageObject|o.reference==reference) {continue;} + let object=objects.iter().find(|o|o.reference==reference).expect("live complete Linked group"); + for group in &object.groups {for value in group {if let V::Reference(r)=value {pending.push(*r);}}} + state.push(object.clone()); + } + state.sort_by_key(|o|(o.reference.index,o.reference.generation));state +} + +fn verify_linked_refusals(root:&std::path::Path) { + use prometeu_vm::{LogicalFrameEndingReason as End,resource_budget::{RuntimeLimits,RuntimeResource as Q}}; + use prometeu_vm::resource_diagnostics::StorageValue as V; + use prometeu_bytecode::{decode_next,TRAP_RESOURCE_LIMIT}; + use prometeu_bytecode::isa::core::CoreOpCode as Op; + let mut node_allocation=false;let mut optional_return=false;let mut snapshot_allocation=false;let mut preparation=false; + for name in ["insert","add","addFirst","remove","removeFirst","removeLast","replace","clear","cursor","reverseCursor"] { + let bytes=std::fs::read(root.join(format!("pbs-linked-refusal-{name}.pbx"))).expect("mandatory Linked refusal fixture"); + let image=ValidatedProgramImage::load(&bytes,&mut LoadBudget::new(LoadLimits::default()),caps::NONE).unwrap(); + let marker=|value:i32| { + let mut pc=0;let mut found=Vec::new(); + while pc")).unwrap(); + let expected=match name {"insert"|"add"|"addFirst"=>33,"remove"|"removeFirst"|"removeLast"=>31,"clear"=>0,_=>32}; + assert_eq!(owner.groups[2],[V::Int64(expected)]); + if name=="cursor"||name=="reverseCursor" {assert_eq!(changed,original);} + let mut refused=0; + for q in [Q::GuestBytes,Q::HandleSlots,Q::AuxiliaryBytes,Q::TemporaryBytes] { + 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)/4,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());let observer=vm.resource_observer(); + let setup=vm.run_budget(20_000_000,&mut NoNative,&mut HostContext::new(None)).unwrap(); + assert!(matches!(setup.reason,End::Breakpoint),"{name} setup {q:?}={limit}: {setup:?}"); + let old=linked_state(&vm,&image);vm.remove_breakpoint(before_pc); + let report=vm.run_budget(20_000_000,&mut NoNative,&mut HostContext::new(None)).unwrap(); + if let End::Trap(info)=report.reason { + assert_eq!(info.code,TRAP_RESOURCE_LIMIT,"{name} {q:?}={limit}: {info:?}"); + assert_eq!(linked_state(&vm,&image),old,"{name}: all original fields, groups and reciprocal links at {q:?}={limit}"); + let instruction=decode_next(info.pc as usize,image.code()).unwrap(); + preparation|=q==Q::AuxiliaryBytes; + if instruction.opcode==Op::StructNew { + let declaration=&image.registry().declarations().types[instruction.imm_u32().unwrap() as usize]; + node_allocation|=declaration.name.as_deref()==Some("_LinkedNode"); + snapshot_allocation|=declaration.name.as_deref()==Some("_SnapshotNode"); + if name.starts_with("remove") { + if let prometeu_bytecode::registry::TypeKind::Struct(fields)=&declaration.kind { + optional_return|=fields.len()==1&&matches!(image.registry().declarations().types[fields[0].type_id.0 as usize].kind, + prometeu_bytecode::registry::TypeKind::Builtin(prometeu_bytecode::registry::BuiltinId::INT32)); + } + } + } + refused+=1;println!("PBS LINKED ATOMIC REFUSAL {name} resource={q:?} limit={limit} opcode={:?}",instruction.opcode); + } else {assert!(matches!(report.reason,End::Breakpoint),"{name}: {report:?}");} + drop(vm);for resource in [Q::GuestBytes,Q::HandleSlots,Q::AuxiliaryBytes,Q::TemporaryBytes] {assert_eq!(observer.used(resource),0);} + } + } + assert!(refused>0,"{name}: whole-source-operation refusals required"); + } + assert!(node_allocation,"new Linked node refusal");assert!(optional_return,"optional removed-value refusal"); + assert!(snapshot_allocation,"snapshot node refusal");assert!(preparation,"frame/operand preparation refusal"); +} + + +fn verify_linked_collection_gc(root:&std::path::Path) { + use prometeu_vm::{LogicalFrameEndingReason as End,resource_budget::RuntimeLimits}; + let bytes=std::fs::read(root.join("pbs-linked-gc-collection.pbx")).expect("mandatory Linked removal/clear GC fixture"); + let image=ValidatedProgramImage::load(&bytes,&mut LoadBudget::new(LoadLimits::default()),caps::NONE).unwrap(); + let mut vm=VirtualMachine::from_image(image.clone(),RuntimeLimits::default());vm.prepare_boot_call().unwrap(); + let mut previous=0; + for (round,count) in [1200,1197,0,0].into_iter().enumerate() { + let report=vm.run_budget(30_000_000,&mut NoNative,&mut HostContext::new(None)).unwrap(); + assert!(matches!(report.reason,End::FrameSync),"collection GC {round}: {report:?}"); + let collections=vm.resource_snapshot().gc.collections;assert!(collections>previous,"real collection at round {round}");previous=collections; + let objects=vm.heap().diagnostic_typed_storage(); + for name in ["_LinkedNode","Item"] { + let actual=objects.iter().filter(|o|image.registry().declarations().types[o.type_id.0 as usize].name.as_deref()==Some(name)).count(); + assert_eq!(actual,count,"{name} after removal/clear at round {round}"); + } + println!("PBS LINKED COLLECTION GC PASS round={round} nodes={count} items={count}"); + } + 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)]); +} diff --git a/tools/pbx-conformance/run.py b/tools/pbx-conformance/run.py index 4e2e5d68..71f16a8b 100644 --- a/tools/pbx-conformance/run.py +++ b/tools/pbx-conformance/run.py @@ -15,6 +15,7 @@ parser.add_argument("--release", action="store_true", help="Execute an optimized 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") parser.add_argument("--generic-contracts-only", action="store_true", help="Run the mandatory generic-contract source corpus only") +parser.add_argument("--linked-only", action="store_true", help="Run mandatory SDK Linked corpus only") parser.add_argument("--list-cursor-only", action="store_true", help="Run the mandatory SDK List/Cursor corpus only") parser.add_argument("--generic-structs-only", action="store_true", help="Run the mandatory generic-struct/function source corpus only") args = parser.parse_args() @@ -32,6 +33,7 @@ for source in [pathlib.Path(__file__), pathlib.Path(__file__).with_name("main.rs print("runtime", subprocess.check_output(["git", "-C", str(runtime), "rev-parse", "HEAD"], text=True).strip(), flush=True) print("runtime working tree", subprocess.check_output(["git","-C",str(runtime),"status","--short"],text=True).strip() or "clean",flush=True) for source in [pathlib.Path("prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsListCursorTest.java"), + pathlib.Path("prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsLinkedTest.java"), pathlib.Path("prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/sdk/collections/main.pbs"), runtime / "crates/console/prometeu-vm/src/virtual_machine/storage_publication.rs"]: print("sha256",source,hashlib.sha256(source.read_bytes()).hexdigest(),flush=True) @@ -50,4 +52,4 @@ with tempfile.TemporaryDirectory(prefix="pbx-conformance-") as directory: (root / "Cargo.lock").write_text((runtime / "Cargo.lock").read_text()) (root / "src").mkdir() (root / "src/main.rs").write_text(pathlib.Path(__file__).with_name("main.rs").read_text()) - subprocess.run(["cargo", "run", *(["--release"] if args.release else []), *([] if args.online else ["--offline"]), "--manifest-path", str(root / "Cargo.toml"), "--", str(args.fixtures.resolve()), str(runtime / "devtools/headless-protocol/response.schema.json"), *(["--math-only"] if args.math_only else []), *(["--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 [])], check=True) + subprocess.run(["cargo", "run", *(["--release"] if args.release else []), *([] if args.online else ["--offline"]), "--manifest-path", str(root / "Cargo.toml"), "--", str(args.fixtures.resolve()), str(runtime / "devtools/headless-protocol/response.schema.json"), *(["--math-only"] if args.math_only else []), *(["--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)