Files
prometeu-studio/docs/specs/compiler-languages/pbs/24. SDK Map and Keyval Specification.md
T

193 lines
11 KiB
Markdown

# SDK Map and read-only Keyval associations
Status: Normative. Owner: `compiler/pbs`.
Scope: SDK Map and Keyval.
Map algorithms execute as PBS SDK source. This contract
builds on [generic structs](17.%20Generic%20Structs%20and%20Free%20Functions%20Specification.md),
[Array/optional](14.%20Typed%20Arrays%20and%20Optional%20Execution%20Specification.md),
[Set/Identity/hash](23.%20SDK%20Set%20and%20Identity%20Specification.md) and the
[shared snapshot Cursor](21.%20SDK%20List%20and%20Cursor%20Specification.md#cursor-protocol).
Registry/PBX, storage, ownership, faults and resource limits remain provider contracts.
## Authority and scope
This chapter is the canonical owner of the detailed contract described below.
The [domain reading guide](README.md) identifies related chapters and their
separate responsibilities. Cross-cutting chapters refer here for these rules.
Runtime-owned ABI, instruction, resource and execution contracts retain their
authority; this chapter specifies their compiler or PBS consumer requirements.
## Types, construction and public API
`@sdk:collections` exports invariant ordinary generic structs `map<K,V>` and
`keyval<K,V>`, alongside the nominal `Identity<T>` and shared `Cursor<T>` contracts.
Applications retain nominal origin through imports, aliases and reexports. User
homonyms and untrusted SDK attributes acquire no reserved behavior.
```pbs
import {map, keyval, Identity, Cursor} from @sdk:collections;
let scores = new map<str, int>();
let contextual: map<str, int> = new map();
let entry = new keyval<str, int>("player", 42);
let previous: optional int = scores.put(entry);
```
Map offers `new map<K,V>()` and `new map<K,V>(identity: Identity<K>)`. Keyval offers
`new keyval<K,V>(key: K, value: V)`. Diamond/omitted type arguments require a
sufficient expected application; constructor values do not infer type arguments.
Every constructor initializes its fields before returning.
Directly optional K, including grouping, is invalid for Map with either constructor.
V may be optional. Independent keyval admits all valid generic field compositions,
including optional K/V. Optional of the Map itself remains valid. Array's direct
optional-element restriction does not apply to V fields in private Map nodes.
| Operation | Result | Behavior |
| --- | --- | --- |
| m[key] | optional V | none for absent key, some(stored value) for a present key |
| m[key] = value | No previous value | Insert or replace V |
| containsKey(key: K) | bool | Membership under selected key identity |
| put(entry: keyval<K,V>) | optional V | Insert/replace; return previous V if present |
| remove(key: K) | optional V | Remove; return previous V if present |
| clear() | unit | Remove associations, release table, restore lazy empty state |
| size() | long | Number of associations |
| isEmpty() | bool | size equals zero |
| cursor() | Cursor<keyval<K,V>> | Complete independent entry snapshot |
| entry.key() | K | Captured key reference/value |
| entry.value() | V | Captured value reference/value |
Receivers and arguments evaluate once in source order, including named application.
Map indexing expects K and does not apply the additional int-to-long index promotion
of Array/List/Linked. Complete key/value groups cross source calls unchanged.
Map has stable reference identity: aliases observe the same mutations.
Only one association exists for each key equivalence class; values may repeat.
Replacement changes only V and preserves the original stored K, cached hash and
size. It never triggers growth. Replacing the representative key requires removing
the entry and reinserting the new key. put reads association components without
retaining its keyval instance as an editable internal node. remove of an absent
key returns none without changing associations/topology. Prepare previous-value
carriers before replacement or unlinking.
Insertion/iteration order is unspecified. There are no keys/values projections,
capacity constructors, capacity/reserve/trim, bulk APIs, redundant tryGet, public
nodes, universal Element or positional indexing contract.
## Presence and optional payloads
The outer optional of read/put/remove describes association existence, independently
of V. For `map<str, optional int>`, absence is none, present V=none is some(none),
and present V=some(7) is some(some(7)). containsKey is true for a stored none;
assigning none as V does not remove an association. Zero/false and complete
multi-slot groups remain present. Preserve deeper valid optional nesting.
Type/callback/resource faults never become none/false.
## Key Identity and read-only Keyval
Use the exact defaults and eligibility rules of Set: int/long/bool by static-domain
value; str by exact UTF-8 content; finite float equality with equal signed zeros;
source structs, arrays, Fn, Random and eligible services by instance; contracts by
fully validated receiver identity. Tuples and other types without a default require
an explicit Identity<K>. An unavailable default constructor must not invalidate an
otherwise valid explicit-strategy application. V requires no equality/hash capability.
Hash filters candidates and equals resolves collisions. Keep all signed-long hash
bits. Identity must define a stable equivalence relation while stored and satisfy
`equals(a,b) => hash(a) == hash(b)`. Relevant key content and strategy configuration
must remain coherent. Remove from affected collections before changing content
used by hashing/equality, then reinsert. Cached hashes do not stabilize mutable
equality. No structural fallback, freezing, purity proof or effect system is added.
Keyval has private fields and only key()/value() accessors, with no mutators.
It retains ordinary struct instance identity: separately constructed keyvals are
distinct under default Identity even when components match. Component comparison
requires explicit policy; unconstrained K/V gain no equality operator. Assignment
shares the keyval instance and payload aliases. Its association cannot be edited
through Map or follow later replacements; referenced objects remain mutable/shared.
## Private storage, rehash and costs
Map owns a private bucket array with private chained nodes containing full cached
long hash, K, V and next link. It is not implemented over Set/Linked and requires
no public keyval wrapper per internally stored association. Reuse Identity/hash,
common private arithmetic helpers and shared Cursor implementation.
Empty construction has no nonempty bucket table. First inclusion uses 8 buckets.
For capacity c and next size r, grow if r exceeds floor(3*c/4), to
min(2*c, 4294967295). Use checked long arithmetic. At maximum bucket capacity,
chaining can continue within checked signed-long size and ordinary quotas;
Array's u32 bound limits buckets rather than entry count. For positive capacity,
use signed hash remainder and add capacity when negative, without abs, narrowing
or assuming powers of two. Removal does not shrink. Clear returns to lazy state.
Rehash prepares independent nodes/topology from cached hashes, with no callbacks
or edits to published links before installation. Complete payload groups and
reference identities survive. Ordinary mutation does not reconstruct the whole
table. Old/candidate structures coexist under normal quotas and GC; preparation
does not make subsequent stores atomic. Search has worst case O(N), growing rehash
costs O(new buckets + N), and String hashing costs content-dependent work. No fixed
instruction cost, adversarial resistance or allocation-free optional is promised.
## Guard, preparation and failure boundaries
Read/write indexing, containsKey, put and remove install a private guard before
Identity callbacks. Reject callback reentry into these operations or clear on the
same Map, including aliases, through the private terminal TRAP_EXPLICIT path
before changing associations. During callback preparation, size/isEmpty/cursor
may inspect the consistent prior structure without invoking strategies.
Prepare checks, callbacks/search, next sizes, values, return carriers and candidate
structures before the first structural write. Structural stores are sequential,
without user callbacks or explicit suspension. Normal returns release the guard,
including absent reads/removals and insertion/replacement.
| Outcome | Guarantee |
| --- | --- |
| Refusal before structural writes | Prior associations/topology survive; guard, external effects and provisional allocations are not undone |
| Successful return | Size, table, groups, representative identity, cleanup, snapshot and guard invariants hold |
| Internal/resource fault after structural writes start | Earlier writes and incomplete invariants may remain; no rollback, retry, recovery or safe reuse guarantee |
Installing the guard is already a write. Callback faults can leave it active.
No catch/finally, poison flag or recovery API is introduced. Allowed callback reads
do not establish post-fault reuse. Per-instruction refusal preserves that
instruction's applicable entry state, not prior instructions. Budget/debugger
pauses are resumable instruction boundaries; a source method is not an atomic
observation region for host/debugger inspection.
## Entry snapshot and lifetime
cursor creates one new independent keyval and one immutable private snapshot node
per association, without editable Map-node/position links or hash/equals calls.
Capture completes before returning; failure returns no partial Cursor and leaves
source structure unchanged. Preserve the shared Cursor state table: nonempty-born
starts on first, hasNext tests successor, next without successor keeps last, and
only empty-born has absent current. No reset, mutation or new for-in is added.
Later insertions/replacements/removals/clear/rehash cannot rewrite captured
associations. Mutations of referenced objects remain visible; order between captures
is unspecified. Capture costs O(B+N) work and O(N) additional storage, including
N keyvals, N nodes and applicable carriers. next is O(1). Consumed prefixes may
become unreachable, while final current stays retained until its Cursor releases it.
Preserve complete groups and roots/owners across calls, allocation, hashing,
rehash, returns and snapshots. Replacement/removal/clear release obsolete Map
references; snapshots/other owners remain independent. Tracing and native owners
retain normal costs; immediate GC/quota recovery is not guaranteed.
## Qualification and distribution
Compile real source through typed IR/PBX into the production loader/verifier/VM,
using ordinary/optimized producers and independent debug/release harness profiles.
Cover the full API, optional presence, evaluation order, representative retention,
identity/collisions/negative hashes, all Cursor states, groups/aliases, resource
prefix refusals, memory coexistence and real GC. Counters establish callback-free
rehash/capture. Distinguish natural production quotas from named test-only
post-write injection, never shipped in production SDK. Missing mandatory fixtures
fail qualification. Regress existing collections, hashing and language boundaries.
Package this English specification, SDK source and executable examples in installed
knowledge. Compile actual installed examples outside the checkout using installed
JARs and execute their PBX. No collection syscall/opcode, changed ABI/catalog policy,
quota relaxation or provider source mutation is required.