cli: add safe owning general-key hash maps
Use explicit static hash/equality functions, dense complete key/value entries and Copy probe indices. Preserve returned ownership and allocation failure state without unsafe code or new runtime instructions. Add normative contracts, API/reference budgets, 33 conformance cases, independent Copy/owner dict traces and 55 CLI/package/profile checks. Full corpus: 947 passing. Collection-every-step scheduler stress remains in progress, recorded in RFC/plan.
This commit is contained in:
1 parent
f02f4bd55b
commit
7bb5bd7931
52 files changed
+7736
-11
No files matched your search
@@ -557,7 +557,7 @@ The frontend MUST declare linear_aggregates plus its dependencies whenever any e
|
||||
|
||||
Outcomes: new has ok(buffer)/err(alloc_error); reserve has ok()/err(alloc_error); push has ok()/err(original_value); pop has ok(value)/err(); free has ok()/err(original_buffer). Ordinary exhaustive outcome matching/or trap applies. A returned linear value MUST be explicitly consumed. `ref values = buffer.view(b);` binds a shared slice from ref or mut b; `mut values = buffer.view(b);` requires mut b and binds an exclusive slice. The child borrow lasts for its explicit lexical scope and never escapes through an aggregate. This is a primitive borrow binding like graph access, not a general function returning a borrow (Q-034 remains open). Existing indexing/value.swap provides Copy reading and complete linear element exchange. Views expose only the initialized prefix; mutation/growth/free while a view or task loan is live MUST reject even on a dynamically full/empty/no-op branch.
|
||||
|
||||
A specialized generic body MAY use `move name` to express complete value transfer for a type parameter. If its concrete binding is Copy, lowering passes the existing Copy value and it remains available; if linear, ordinary transfer/availability applies. This rule applies to complete Copy bindings inside a specialized generic body, not borrows/storage/function-bound values. Outside a specialized generic body, move of a Copy value remains E7006. No AIR ownership rule changes and no implicit destructor/allocation is added. This makes one generic container body correct for both Copy and linear contents; ordinary borrow/effect/type constraints still apply to every specialization.
|
||||
A specialized generic body MAY use `move name` to express complete value transfer for a type parameter. If its concrete binding is Copy, lowering passes the existing Copy value and it remains available; if linear, ordinary transfer/availability applies. This rule applies to complete Copy bindings inside a specialized generic body, not borrows or internal storage/scope/guard/shield handles. A Copy value bound in frame storage remains a Copy value and is loaded normally when transferred. Outside a specialized generic body, move of a Copy value remains E7006. No AIR ownership rule changes and no implicit destructor/allocation is added. This makes one generic container body correct for both Copy and linear contents; ordinary borrow/effect/type constraints still apply to every specialization.
|
||||
|
||||
The frontend MUST emit linear_buffers and its full dependencies for buffer types/operations. Existing syntax suffices apart from admitting the buffer wrapper and the typed built-in allocator with the existing channel.make<T> type-argument form. General methods, borrowed aggregate storage, recursive ownership and from-return calls are not added.
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ APIs SHOULD offer one canonical operation for a common need, small documentation
|
||||
|
||||
## 2. Bootstrap module registry
|
||||
|
||||
The built-in registry contains `std.bytes`, `std.encoding.base64`, `std.encoding.hex`, `std.fmt`, `std.hash`, `std.map`, `std.math`, `std.option`, `std.result`, `std.utf8`, `std.vec` and `std.deque`. They are implemented in safe `.aji`; their stable source paths are `std/bytes.aji`, `std/encoding/base64.aji`, `std/encoding/hex.aji`, `std/fmt.aji`, `std/hash.aji`, `std/map.aji`, `std/math.aji`, `std/option.aji`, `std/result.aji`, `std/utf8.aji`, `std/vec.aji` and `std/deque.aji`, respectively. Spec 15 §13 defines imports; the reference API tables are in `reference/std.md`. All operations are deterministic in every profile and have no concurrency effects. Modules other than std.vec/std.deque/std.map declare effects [] and allocate no heap memory. std.vec/std.deque/std.map new/reserve declare mem.alloc and require explicit allocation authority (§2.10–§2.11, §2.13); their other functions allocate no heap. Ordinary interpreter fuel limits apply.
|
||||
The built-in registry contains `std.bytes`, `std.encoding.base64`, `std.encoding.hex`, `std.fmt`, `std.hash`, `std.hashmap`, `std.map`, `std.math`, `std.option`, `std.result`, `std.utf8`, `std.vec` and `std.deque`. They are implemented in safe `.aji`; their stable source paths are `std/bytes.aji`, `std/encoding/base64.aji`, `std/encoding/hex.aji`, `std/fmt.aji`, `std/hash.aji`, `std/hashmap.aji`, `std/map.aji`, `std/math.aji`, `std/option.aji`, `std/result.aji`, `std/utf8.aji`, `std/vec.aji` and `std/deque.aji`, respectively. Spec 15 §13 defines imports; the reference API tables are in `reference/std.md`. All operations are deterministic in every profile and have no concurrency effects. Modules other than std.vec/std.deque/std.map/std.hashmap declare effects [] and allocate no heap memory. std.vec/std.deque/std.map/std.hashmap new/reserve declare mem.alloc and require explicit allocation authority (§2.10–§2.11, §2.13–§2.14); their other functions allocate no heap. Ordinary interpreter fuel limits apply.
|
||||
|
||||
### 2.1 `std.math`
|
||||
|
||||
@@ -228,3 +228,36 @@ Insert searches for an existing key before choosing its first deleted/empty slot
|
||||
Reserve≤N is an unchanged no-op, retaining its explicit effect/capability/mut contract. Growth MUST allocate/initialize the entire new table before changing the original. Returned failure MUST preserve every old slot, metadata, key/value association and pop order. Peak quota includes both whole tables and existing user-owned allocations; old storage is refunded to its recorded authority even if a different capability funds growth. After successful allocation, transfer complete entries in old physical-index order, clear tombstones and explicitly free old internal vacant storage. No subsequent recoverable error is permitted; fuel/traps are abnormal outcomes outside returned-error preservation. Nonempty free MUST return the entire map; empty free MUST consume all internal none values and free the storage, never normally discarding an occupied/owning payload, including with corrupted caller metadata. Callers MUST consume returned linear replacements/full/remove/pop/not_empty results; no hidden destructor closes user resources.
|
||||
|
||||
Existing aggregate/enum moves, value.swap, slice bounds, borrow/task-loan exclusion, Copy/Send/Share, effects and allocation accounting verify this library without map-specific rules, diagnostics, AIR instructions/features or runtime behavior. Preflight size failures construct alloc_error values through error_values (spec 05 §14); map adds no further semantic feature. Bad moves/leaks/aliases/tasks/Copy uses retain E7003/E2002/E3002/E2101/E4101/E7005 and Share restrictions E4002. Valid operations do not trap except execution limits. Deterministic/hosted profiles agree; existing source/AIR/API meanings remain unchanged. Lookup/insert/remove are O(N) worst-case slot work, pop/free O(N), growth O(N²) worst-case collision work. Initialized-prefix copying may increase interpreter host cost; no native throughput guarantee or adversarial collision bound is added.
|
||||
|
||||
### 2.14 `std.hashmap`: bounded owning general-key map
|
||||
|
||||
The registry MUST include std.hashmap at std/hashmap.aji, ordinary safe source. `HashMap<K,V,H,E>` binds explicit static `H: fn(ref<K>) -> u64 effects []` and `E: fn(ref<K>,ref<K>) -> bool effects []` (spec 15 §18). K/V MAY be Copy, owners, files or endpoints under ordinary member/Send/Share rules. An applied type uses `HashMap<K,V,fn hash,fn equal>`; functions use `::<K,V,fn hash,fn equal>`. Distinct operation identities are distinct nominal map types. Entry<K,V> has key: K and value: V; both are returned/transferred completely, never implicitly destroyed.
|
||||
|
||||
The caller MUST supply deterministic, stable hashing and equality for live keys: E is an equivalence relation, and E(a,b) implies H(a)=H(b). Equality decides identity even when hashes collide. A stored key MUST NOT be modified in a way that changes its hash/equality; normal exclusive access rules still apply. These algebraic laws are explicit library preconditions, not compiler-proved properties. Hash/equality receive only shared key borrows, no capability or hidden state. User callback traps and fuel exhaustion are abnormal outcomes, outside returned-error preservation.
|
||||
|
||||
Ten operations are specialized by the four ordered arguments above (get additionally requires V: Copy):
|
||||
|
||||
| Operation | Result / transfer |
|
||||
|---|---|
|
||||
| new(capacity: usize, heap: cap<mem.alloc>) | NewResult<K,V,H,E>: ok(HashMap<K,V,H,E>), err(alloc_error) |
|
||||
| len(map: ref<HashMap<K,V,H,E>>) -> usize | live entry count |
|
||||
| capacity(map: ref<HashMap<K,V,H,E>>) -> usize | maximum live entries |
|
||||
| reserve(map: mut<HashMap<K,V,H,E>>, capacity: usize, heap: cap<mem.alloc>) | ReserveResult: ok, err(alloc_error) |
|
||||
| insert(map: mut<HashMap<K,V,H,E>>, key: K, value: V) | InsertResult<K,V>: inserted, replaced(Entry<K,V>), full(Entry<K,V>) |
|
||||
| contains(map: ref<HashMap<K,V,H,E>>, key: ref<K>) -> bool | presence by actual key equality |
|
||||
| get(map: ref<HashMap<K,V,H,E>>, key: ref<K>) -> std.option.Option<V> | copied value; no K: Copy requirement |
|
||||
| remove(map: mut<HashMap<K,V,H,E>>, key: ref<K>) -> std.option.Option<Entry<K,V>> | moves complete stored key/value out |
|
||||
| pop(map: mut<HashMap<K,V,H,E>>) -> std.option.Option<Entry<K,V>> | moves the last dense entry out |
|
||||
| free(map: HashMap<K,V,H,E>) | FreeResult<K,V,H,E>: ok, not_empty(HashMap<K,V,H,E>) |
|
||||
|
||||
Only new/reserve declare effects [mem.alloc] and require explicit heap authority; all other functions declare effects [] and perform no heap allocation. Insert is bounded, never grows. Replacement succeeds at full capacity and returns the previous complete key/value; the supplied equivalent key becomes the stored key. A new key when full returns the exact supplied key/value with all storage unchanged. Missing removal leaves storage unchanged. Callers MUST consume owning replaced/full/remove/pop/not_empty payloads explicitly. No borrowed value/cursor escapes.
|
||||
|
||||
Representation: HashMap has entries: buffer<StoredEntry<K,V>>, buckets: buffer<Bucket>. StoredEntry has hash: u64, key: K, value: V. Bucket has hash: u64, index: usize, state: BucketState (empty/deleted/occupied). For capacity N, entries.capacity=N, entries.len=L≤N; buckets.capacity=buckets.len=2N. Every dense entry [0,L) has one occupied bucket whose hash/index agree; no other bucket owns or refers to a live entry. Cached hash equals H(key); live keys are pairwise unequal by E. Each occupied bucket is reachable by the probing rule. Keys/values have no vacancy sentinel or default value. Manual representation construction/mutation MUST preserve this invariant; invalid representations retain ordinary memory/ownership safety but may trap or violate map behavior.
|
||||
|
||||
Probe start is the unsigned u64 hash modulo the bucket count. Advance wraps without overflow, and at most bucket count probes occur. Lookup skips deleted and stops at empty/end; occupied hash equality is only a filter before E. Insert remembers the first deleted/empty slot but searches for an existing equal key before choosing it, including when full. Zero capacity never performs modulo and returns full on insert. Deleted-only tables remain bounded and reusable.
|
||||
|
||||
Removal exchanges the last dense entry into the removed entry's position when needed and repairs that moved entry's occupied bucket by its cached hash/index. Thus the initialized prefix always contains complete values; no uninitialized hole or partial move is introduced. pop consumes the last dense entry and marks its bucket deleted without invoking H/E. Pop order is reverse current dense order (insertion appends; replacement retains position; removal may exchange the last entry into a hole). This is deterministic for the history, not sorted order. Successful reserve preserves dense/pop order and clears tombstones. Nonempty free returns the entire map unchanged, based on actual entries.len, not forgeable length metadata. Empty free explicitly drains only Copy bucket metadata and frees both buffers; it cannot normally discard a key/value, even with invalid bucket metadata.
|
||||
|
||||
New checks 2N overflow, allocates the empty entry buffer, then the fully initialized bucket buffer. A returned second-allocation failure MUST free the temporary empty entry buffer and refund its recorded authority. Reserve≤N is an unchanged no-op with its declared mut/effect/capability requirements. Growth MUST allocate/initialize a new bucket buffer before calling ownership-preserving buffer.reserve on the dense entries. Any returned failure MUST free temporary metadata, preserve both original buffers, every key/value/hash/index/state and pop order, and refund all temporary charges. After entries reserve succeeds, only cached hashes are used to rebuild the new buckets; no further recoverable allocation or callback occurs. Swap in the new buckets and explicitly free the old Copy metadata buffer. Peak quota includes old/new entry buffers, old/new bucket buffers and separately charged user owners. All old storage refunds go to their recorded authorities, even when growth uses another capability. Arithmetic/allocation-size overflow returns alloc_error.budget_exceeded; no shrink occurs.
|
||||
|
||||
Each StoredEntry slot charges hash plus full K/V slot sizes, including uninitialized capacity; each Bucket charges hash, usize and state tag. Unused capacity reserves bytes but contains no live K/V. There is no tag/default key allocation and no implicit destruction. Existing initialized buffers, aggregate transfer/exchange, borrows/task loans, bounds, effects, Copy/Send/Share and quota verification suffice; no new AIR instruction/feature, source form, verifier/runtime state or diagnostic is added. Generic callback contracts are RFC 0029. Valid bookkeeping does not trap with a valid representation and successful callbacks. Existing API/AIR meanings remain unchanged, including std.map.U64Map. Deterministic/hosted behavior agrees. Probe operations are O(N) worst-case plus callback work, pop/removal repair O(N), reserve O(N²) worst-case collision work; buffer-prefix interpreter copying may add host cost. No adversarial collision or native throughput promise is made.
|
||||
Reference in new issue
Block a user