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
@@ -119,3 +119,5 @@ RFC 0027 explicit error values (cl100k, relative to hashes): Quick Reference 7,8
|
||||
RFC 0028 numeric-key owning map (cl100k, relative to error_values; includes the separate integer-pattern clarification): Quick Reference stays 7,863, other source docs 48,061 → 50,079, full source excluding AIR 55,924 → 57,942 (+3.6%). The on-demand library page is 14,167 tokens. AIR remains 179,282 bytes / 51 sections. No map-specific instruction, source form, verifier state or diagnostic is added; general keys remain Q-037. Cumulative source growth is +70.5%, with review justification in the RFC and no claimed MCC benefit.
|
||||
|
||||
RFC 0029 static function parameters (cl100k, relative to numeric maps): Quick Reference 7,863 → 8,051 (+2.4%); other source docs 50,079 → 51,002 (+1.8%); full source excluding AIR 57,942 → 59,053 (+1.9%). language/generics.md is 2,194 tokens; AIR remains 179,282 bytes / 51 sections. One explicit operation-selection concept adds two source forms and bounded frontend state, with no runtime/verifier state or new AIR construct/diagnostic. Cumulative growth is +73.8%; the RFC justifies the general hash/equality/order prerequisite, keeps general collections open and makes no empirical MCC claim.
|
||||
|
||||
RFC 0030 general owning HashMap (cl100k, relative to static operations): Quick Reference 8,051 → 8,124 (+0.9%), other source docs 51,002 → 53,363 (+4.6%), full source excluding AIR 59,053 → 61,487 (+4.1%). library/std.md is 16,504 tokens; AIR remains 179,282 bytes / 51 sections. Ten safe source functions use explicit static policies and complete key/value transfer, with no new language form, verifier/runtime state or diagnostic. Cumulative source growth is +80.9%, justified in the RFC without an empirical MCC claim; full policies/failure/dense-index invariants stay on demand.
|
||||
@@ -363,6 +363,8 @@ The usual enum rules apply: missing arm `E7004`, wrong enum/payload `E7005`, unk
|
||||
|
||||
`std.fmt.write_u64/i64/usize/isize` write decimal integers into supplied output slices; `WriteResult::ok(count)` / `short_output` expose capacity, with unchanged output on failure. Composition and signatures are in `/docs/library/std.md`.
|
||||
|
||||
`std.hashmap.HashMap<K,V,fn hash,fn equal>` supports general owning keys/values through explicit pure ref-key operations (§12). Insert returns replaced/full key/value pairs; remove/pop move both out, get requires only V: Copy, growth is explicit and free returns nonempty maps. Full contracts are in `/docs/library/std.md`.
|
||||
|
||||
`std.hash.fnv1a64` and `crc32c` hash byte slices without allocation; their `_extend` forms continue from a previous result. Hashes do not establish key equality or authentication. Exact algorithms and chunk/byte-order conventions are in `/docs/library/std.md`.
|
||||
|
||||
## 11. Package modules
|
||||
|
||||
@@ -8,7 +8,7 @@ The other files in `/docs` hold the full rules. Open one only when this page is
|
||||
|
||||
| Need | Read |
|
||||
|---|---|
|
||||
| built-in bytes/math/text/formatting/hash, option/result, owning Vec and Deque, signatures and failure contracts | `/docs/library/std.md` |
|
||||
| built-in bytes/math/text/formatting/hash, option/result, owning Vec/Deque and numeric/general maps, signatures and failure contracts | `/docs/library/std.md` |
|
||||
| initialized buffer storage, explicit growth/drain and child views | `/docs/language/buffers.md` |
|
||||
| whole-value linear aggregates, unpack, exchange and allocation failure | `/docs/language/linear-aggregates.md` |
|
||||
| generic declarations/applications, property constraints, static function contracts and specialization limits | `/docs/language/generics.md` |
|
||||
|
||||
@@ -4,9 +4,9 @@ Status: STD-6d.2 numeric-key branch implementation (RFC 0028 Proposed); general
|
||||
|
||||
## Key policy and scope
|
||||
|
||||
The eventual collection gate still requires HashMap<Key, Own<Value>>. Current type parameters are types, not hashing/equality operations (spec 15 §15); Copy supplies neither. Source has no callbacks, methods, user traits or value generic parameters. Treating a digest as key identity is incorrect because different keys can collide. Adding a language feature solely to make this API look generic would add more agent concepts before establishing their general value.
|
||||
The eventual collection gate still requires HashMap<Key, Own<Value>>. At the numeric-map decision, type parameters supplied no hashing/equality operations (spec 15 §15); Copy supplies neither. RFC 0029/spec 15 §18 now supplies explicit static functions without runtime callbacks, methods, user traits or captured values. Treating a digest as key identity is incorrect because different keys can collide. Adding a language feature solely to make this API look generic would add more agent concepts before establishing their general value.
|
||||
|
||||
Start with `std.map.U64Map<V>`: exact u64 keys, generic Copy or linear values, initialized buffer primitives and explicit error construction (RFC 0027). Users with genuine numeric identifiers can use it directly. Bytes/struct keys cannot be converted to digests and then treated as unique numeric keys; general key hashing/equality is Q-037. Byte-key ownership needs a separate owning representation contract. Do not name this specialization HashMap<K,V> or claim that it satisfies the general-key gate.
|
||||
The initial branch increment was `std.map.U64Map<V>`: exact u64 keys, generic Copy or linear values, initialized buffer primitives and explicit error construction (RFC 0027). Users with genuine numeric identifiers can use it directly. Bytes/struct keys cannot be converted to digests and then treated as unique numeric keys; general key hashing/equality is Q-037. Byte-key ownership needs a separate owning representation contract. Do not name this specialization HashMap<K,V> or claim that it satisfies the general-key gate.
|
||||
|
||||
## Public API
|
||||
|
||||
@@ -50,3 +50,8 @@ Before marking the specialization done, test exact collisions, tombstones before
|
||||
## Agent complexity impact
|
||||
|
||||
The numeric-key library adds no map-specific language concept, verifier state, syntax, diagnostic, callback, trait or runtime feature. Its separately implemented error construction prerequisite is RFC 0027. Key equality, probing and returned replacement ownership reuse existing complete-value patterns. Ten operations avoid independent entry/cursor/borrow lifetimes. Public representation invariants increase documentation needs, so full details belong on demand. This design stays outside the source/AIR bundles; RFC 0028 measures the normative API cost. No performance or Model Capability Compression result is inferred from fixtures or benchmark tasks.
|
||||
|
||||
|
||||
## General-key implementation
|
||||
|
||||
RFC 0030/spec 16 §2.14 introduces separate std.hashmap so std.map's numeric signatures remain compatible without overloads. Explicit H/E contracts support arbitrary complete owning keys and values. Dense initialized StoredEntry<K,V> slots plus Copy bucket indices permit shared key borrows, avoiding vacancy/default keys and borrowed-enum/partial-move features. Replacement returns the entire previous key/value; full returns the entire input pair. Removal exchanges the last entry into the hole and repairs its index; pop is reverse current dense order. Growth initializes new indices first, then uses failure-preserving buffer.reserve, rehashes cached hashes and frees old indices. This keeps failure exact while charging both layouts at the peak. The full library contract, rather than this historical numeric design, is normative. HashSet and BinaryHeap are later increments.
|
||||
@@ -275,7 +275,7 @@ STD-5 intentionally enables only complete fixed-size values and individually own
|
||||
|
||||
HashMap<K,V> needs a stable hash/equality pair: equal keys must hash equally, while hash collisions must still compare actual keys. Current Copy/Send/Share/Freeze/Local constraints supply no user operations; type parameters cannot carry callbacks or values (spec 15 §15). Struct/byte-key equality, key ownership and effect-visible callable policies have no general source contract. A hash digest alone cannot represent original-key identity.
|
||||
|
||||
**Open for general keys.** The [owning map proposal](hash-map.md) starts with an honest U64Map<V> specialization, exact numeric equality and existing safe primitives. This does not complete the HashMap<Key, Own<Value>> collection gate. General key support must either use an independently specified concrete representation or justify a generally useful vertical language facility; it must not silently infer hashing/equality or introduce map-only compiler magic.
|
||||
**Static-operation prerequisite implemented (RFC 0029); general map validation in progress (RFC 0030).** The [owning map proposal](hash-map.md) starts with an honest U64Map<V> specialization, exact numeric equality and existing safe primitives. This does not complete the HashMap<Key, Own<Value>> collection gate. General key support must either use an independently specified concrete representation or justify a generally useful vertical language facility; it must not silently infer hashing/equality or introduce map-only compiler magic.
|
||||
|
||||
## Q-038 — Pure construction of built-in errors
|
||||
|
||||
|
||||
@@ -141,4 +141,4 @@ Lowering layers (P6A-3/4), each with accepted (golden AIR), rejected (`E7xxx`) a
|
||||
| P6-9 | todo | Port reference programs and examples to `.aji` | P6-5 | `tests/programs/`, `examples/` | exit criterion passes |
|
||||
| P6-10 | todo | Phase exit review | all | plan status | exit criterion passes |
|
||||
|
||||
The [standard-library track](standard-library.md) implements twelve compiler-pinned modules and qualified standard enum names. STD-3/RFC 0021 completes P6-3 on the branch with explicit manifest source mapping, acyclic linking, direct qualified names, imported struct literals and task workers. Dependency fetching/resolution is separate package work; STD-4/RFC 0022 completes explicit generics and structural constraints on the branch. STD-5/RFC 0023 adds whole-value linear structs/enums/fixed arrays, complete unpack/match, explicit exchange and ownership-preserving allocation failure through all layers (spec 15 §16). STD-6a/b/RFC 0024 resolves Q-036 with initialized buffer<T> and safe std.vec, explicit growth, returned failure ownership and draining (spec 15 §17). STD-6c/RFC 0025 adds safe owning Deque with existing source primitives. STD-6d.1/RFC 0026 adds pure std.hash; STD-6d.2/RFC 0028 adds safe owning U64Map<V> after the explicit error_values prerequisite (RFC 0027). STD-6d.3/RFC 0029 adds explicit static function parameters for general hash/equality/order operations with existing AIR calls/workers. General key policy remains Q-037. Remaining maps/sets/heaps are STD-6d. Existing `from`-returns remain unimplemented (Q-034). These increments do not complete Phase 6.
|
||||
The [standard-library track](standard-library.md) implements thirteen compiler-pinned modules and qualified standard enum names. STD-3/RFC 0021 completes P6-3 on the branch with explicit manifest source mapping, acyclic linking, direct qualified names, imported struct literals and task workers. Dependency fetching/resolution is separate package work; STD-4/RFC 0022 completes explicit generics and structural constraints on the branch. STD-5/RFC 0023 adds whole-value linear structs/enums/fixed arrays, complete unpack/match, explicit exchange and ownership-preserving allocation failure through all layers (spec 15 §16). STD-6a/b/RFC 0024 resolves Q-036 with initialized buffer<T> and safe std.vec, explicit growth, returned failure ownership and draining (spec 15 §17). STD-6c/RFC 0025 adds safe owning Deque with existing source primitives. STD-6d.1/RFC 0026 adds pure std.hash; STD-6d.2/RFC 0028 adds safe owning U64Map<V> after the explicit error_values prerequisite (RFC 0027). STD-6d.3/RFC 0029 adds explicit static function parameters for general hash/equality/order operations with existing AIR calls/workers. STD-6d.4/RFC 0030 implements the general owning-key std.hashmap contract; its final GC/stress validation remains in progress (Q-037). Remaining sets/heaps are STD-6d. Existing `from`-returns remain unimplemented (Q-034). These increments do not complete Phase 6.
|
||||
@@ -61,7 +61,8 @@ SQL/database clients, Redis/Kafka, ORMs, application authentication, gRPC/protob
|
||||
| STD-6d.1 | done (branch implementation; RFC 0026 Proposed) | pure std.hash: FNV-1a 64 / CRC32C, fresh/extend | STD-1b | four safe functions, exact byte/chunk conventions, independent public vectors and CLI/profile checks |
|
||||
| STD-6d.2a | done (branch implementation; RFC 0027 Proposed) | pure built-in error construction prerequisite | STD-6d.1 | vertical error_values feature, no authority/effect/resource changes; preflight allocation validation |
|
||||
| STD-6d.2 | done (numeric-key branch implementation; RFC 0028 Proposed) | U64Map<V> first; general HashMap<K,V> key policy Q-037 | STD-6d.1 | safe map with ownership/failure/collision tests and error_values prerequisite (RFC 0027); general-key gate remains open |
|
||||
| STD-6d.3 | done (branch implementation ; RFC 0029 Proposed) | explicit static hash/equality/order functions | STD-4 | exact callable contracts, ordinary AIR calls/workers and nominal operation identity; general collections remain required |
|
||||
| STD-6d.3 | done (branch implementation; RFC 0029 Proposed) | explicit static hash/equality/order functions | STD-4 | exact callable contracts, ordinary AIR calls/workers and nominal operation identity; general collections remain required |
|
||||
| STD-6d.4 | implementation validated; final GC/stress in progress (RFC 0030 Proposed) | general owning HashMap<K,V,H,E> | STD-6d.3 | dense complete entries, Copy probe indices, exact equality and returned key/value ownership |
|
||||
| STD-7 | todo | concrete I/O adapters, buffered I/O and lexical paths | STD-1b/2a/2b; STD-3 for public types | short reads, EOF, capacity and write failures covered; paths never grant filesystem authority |
|
||||
| STD-8 | todo | filesystem gaps, args/env capability RFC, time/random distinctions and structured log | STD-3/7; vertical runtime feature where needed | CLI/storage milestone examples work in deterministic and hosted profiles; all authority is granted at entry |
|
||||
| STD-9 | todo | independent integration application and API review | STD-6/7/8 | integration gate; public application is not private benchmark material |
|
||||
|
||||
+28
-3
@@ -1,8 +1,8 @@
|
||||
# Standard library API
|
||||
|
||||
Normative contracts: spec 16. Import rules: spec 15 §13. These modules are bundled with the compiler, with no external source dependencies. Allocation authority is explicit for std.vec/std.deque/std.map new/reserve.
|
||||
Normative contracts: spec 16. Import rules: spec 15 §13. These modules are bundled with the compiler, with no external source dependencies. Allocation authority is explicit for std.vec/std.deque/std.map/std.hashmap new/reserve.
|
||||
|
||||
Except std.vec/std.deque/std.map new/reserve, functions below declare `effects []`, allocate no heap memory and retain no borrows. Pass arrays/slices using explicit `ref` or `mut`. Names are fully qualified; no alias or short-name import exists.
|
||||
Except std.vec/std.deque/std.map/std.hashmap new/reserve, functions below declare `effects []`, allocate no heap memory and retain no borrows. Pass arrays/slices using explicit `ref` or `mut`. Names are fully qualified; no alias or short-name import exists.
|
||||
|
||||
| Module | Function signature | Result/failure |
|
||||
|---|---|---|
|
||||
@@ -281,7 +281,7 @@ End operations and indexing use constant slot work; construction/growth/free use
|
||||
|
||||
## Owning numeric-key maps
|
||||
|
||||
Import `std.map`; each generic operation supplies `::<V>`. `U64Map<V>` is always linear, uses exact u64 key equality and supports Copy values, owners, files and sender endpoints. Hashes select probe positions; they never establish key equality. General `HashMap<K,V>` remains Q-037.
|
||||
Import `std.map`; each generic operation supplies `::<V>`. `U64Map<V>` is always linear, uses exact u64 key equality and supports Copy values, owners, files and sender endpoints. Hashes select probe positions; they never establish key equality. General keys use `std.hashmap` with explicit hash/equality (§2.14).
|
||||
|
||||
| Operation | Return / ownership |
|
||||
|---|---|
|
||||
@@ -301,3 +301,28 @@ Only new/reserve declare `effects [mem.alloc]` and take allocation authority. No
|
||||
Representation: `U64Map<V> { storage: buffer<Slot<V>>, length: usize }`, `Slot<V> { key: u64, state: SlotState, value: std.option.Option<V> }`, `SlotState { empty, deleted, occupied }`. Occupied implies some(V), vacancies imply none, keys are unique and reachable, and length equals occupied count. Direct representation writes must preserve spec 16 §2.13's invariant. Capacity N allocates and initializes 2N physical slots, with both enum tags charged. N=0 allocates no bytes. Both whole tables and user allocations count toward growth's peak quota; old storage is refunded to its original authority. Overflowing size returns budget_exceeded.
|
||||
|
||||
Lookup traverses deleted slots, compares original keys and terminates after bounded probes, even with no empty slots. Pop drains physical-index order; successful rehash may change this deterministic order. Worst-case probe work is O(N); collision-heavy growth is O(N²). Existing borrow, task-loan, Copy/Send/Share and resource diagnostics apply. The [owning example](../../examples/std/map.aji) returns 42 with heap=mem.alloc:256.
|
||||
|
||||
## Owning general-key maps
|
||||
|
||||
Import `std.hashmap` and `std.option` for lookup/extraction results. `HashMap<K,V,fn hash,fn equal>` stores complete keys and values, including owning byte buffers, structs, owners, files and channel endpoints. The two declared functions have exactly `fn(ref<K>) -> u64 effects []` / `fn(ref<K>,ref<K>) -> bool effects []`. Equality is stable equivalence and equal keys must hash equally; hash equality alone never identifies a key. Do not change a live key's hash/equality. Different bound functions produce distinct nominal map types. Operations never capture state or gain authority from selection.
|
||||
|
||||
Every call supplies `::<K,V,fn hash,fn equal>` (get additionally requires V: Copy, without requiring K: Copy):
|
||||
|
||||
| Function arguments | Result |
|
||||
|---|---|
|
||||
| new(capacity: usize, heap: cap<mem.alloc>) | NewResult<K,V,fn hash,fn equal>: ok(HashMap), err(alloc_error) |
|
||||
| len(map: ref<HashMap>) | usize live count |
|
||||
| capacity(map: ref<HashMap>) | usize maximum live entries |
|
||||
| reserve(map: mut<HashMap>, capacity: usize, heap: cap<mem.alloc>) | ReserveResult: ok, err(alloc_error) |
|
||||
| insert(map: mut<HashMap>, key: K, value: V) | InsertResult<K,V>: inserted, replaced(Entry<K,V>), full(Entry<K,V>) |
|
||||
| contains(map: ref<HashMap>, key: ref<K>) | bool |
|
||||
| get(map: ref<HashMap>, key: ref<K>) | std.option.Option<V> copied value |
|
||||
| remove(map: mut<HashMap>, key: ref<K>) | std.option.Option<Entry<K,V>> moving extraction |
|
||||
| pop(map: mut<HashMap>) | std.option.Option<Entry<K,V>> moving extraction |
|
||||
| free(map: HashMap) | FreeResult<K,V,fn hash,fn equal>: ok, not_empty(HashMap) |
|
||||
|
||||
Here HashMap abbreviates the fully applied type, and Entry<K,V> has key: K/value: V. Pass `ref q` when querying through mut q; ownership transfer of named linear K/V requires move. Replacement returns both old resources and retains the new equivalent key. Full insert returns both original inputs. Explicitly consume every owning result; free returns the nonempty map. get cannot copy an owned V, while contains/remove work without Copy requirements. No borrowed value/cursor escapes.
|
||||
|
||||
Only new/reserve allocate and declare mem.alloc with explicit authority. Growth has no implicit trigger and returned failure preserves every old entry/bucket and pop order. A capacity N reserves N StoredEntry slots (hash + full K/V sizes) and 2N Copy Bucket slots (hash + usize + state tag). Live entries form an initialized dense prefix, with a separate probe-index table and cached hashes. Removing a middle entry exchanges the last into its position, repairing the index. Pop drains reverse current dense order; reserve preserves it and clears tombstones. Zero capacity is valid. Peak growth includes both entry buffers, both index buffers and external user owners; refunds follow the recorded allocation capabilities. Capacity-one Key{id:u64}/own<u64> reserves 58 bytes, plus 8 for the owned payload in the [checked example](../../examples/std/hashmap.aji), which runs with heap=mem.alloc:66.
|
||||
|
||||
Representation fields are ordinary visible source; manual construction/mutation must preserve the full invariant in spec 16 §2.14. Hash/equality traps and fuel exhaustion are abnormal outcomes. Existing moves, alias/task-loan and Copy/Send/Share rules apply without unsafe or map-specific runtime semantics. Worst-case lookup/insert/remove/pop is O(N) plus callback work, rehash O(N²); no adversarial collision/native-throughput guarantee is made. `std.map.U64Map<V>` retains its existing API for numeric keys.
|
||||
@@ -0,0 +1,56 @@
|
||||
# RFC 0030: Safe owning general-key hash map
|
||||
|
||||
Status: Proposed
|
||||
Scope: STD-6d.4, ordinary safe library source after RFC 0029
|
||||
|
||||
## Motivation
|
||||
|
||||
Arbitrary keys need exact equality and explicit hash policy. Numeric-key U64Map cannot represent bytes/structs/owners by digest alone. Static functions supply reusable typed operations without container-specific language rules.
|
||||
|
||||
## Invariant and normative changes
|
||||
|
||||
Spec 16 §2.14 defines std.hashmap.HashMap<K,V,H,E>, dense initialized complete entries and Copy probe metadata. Every live entry has one reachable occupied bucket; cached hashes and equality agree. Keys and values may both own resources, with no vacancy key/default allocation. The registry/reference/API changes land together.
|
||||
|
||||
## Verifier rule
|
||||
|
||||
No new transfer function. Complete buffer transfer/pop/exchange, borrowed fields, exact callable contracts, normal effects/capabilities, Copy/Send/Share and ownership verification apply. Representation/hash-law preconditions are explicit, as for existing containers. No manual unsafe implementation is allowed.
|
||||
|
||||
## Runtime and deterministic behavior
|
||||
|
||||
Ordinary AIR. Probes are bounded; replacement/full/removal/free return complete owners. Allocation failure rolls back temporary empty storage, preserving old buffers/metadata/pop order. Explicit peak charges include both layouts and separately owned payloads. Removal swaps the last dense entry into a hole and repairs Copy indices. Rehash uses cached hashes after allocation succeeds; no recoverable failure follows the first old-buffer mutation. Normal profiles agree; fuel/callback traps are abnormal outcomes.
|
||||
|
||||
## Valid and rejected examples
|
||||
|
||||
A struct key containing an owner and a Copy identity field supplies pure ref-key hash/equality functions; insert transfers it with an owned value, removal/pop returns both for explicit consumption. Copy-value lookup does not need Copy keys. Missing moves, leaked full/replacement/pop/nonempty-free results, illegal aliases/loans, Copy lookup of owning V and sharing non-Share contents reject through existing codes. Mismatched static policy identities reject E7005.
|
||||
|
||||
## Diagnostics / compatibility / AIR
|
||||
|
||||
No new diagnostic, opcode, AIR feature or runtime boundary. Existing E7003/E2002/E3002/E2101/E4101/E7005/E4002 and ordinary call/effect checks apply. The new module is additive; std.map.U64Map and every existing API retain meaning. No implicit growth, destructor, retained borrow or authority is introduced. Spec 15 §17 clarifies the existing distinction between a Copy value bound in frame storage and internal storage/scope/guard/shield handles; ordinary Copy loading is unchanged.
|
||||
|
||||
## Agent complexity impact
|
||||
|
||||
No new language concept, syntax or verifier/runtime state beyond already specified static operations. Ten functions match the numeric-map operation set; four explicit arguments name type/hash/equality policies, and linear replacement returns both old resources. Algebraic hash/equality and visible dense/index invariants add documentation obligations, which are kept on demand and measured below. Existing safe primitives suffice without borrowing enum payloads or partial moves. No MCC or throughput benefit is claimed from fixtures.
|
||||
|
||||
## Alternatives
|
||||
|
||||
Digest identity loses collisions. Per-key duplication loses general reuse. A vacant Option<Entry> table cannot observe owning keys through existing Copy enum switching. Two dense/probe buffers need no default key, borrowed enum feature, private representation privilege or unsafe pointer.
|
||||
|
||||
## Validation gate
|
||||
|
||||
Independent dictionary/model traces, exact collisions, tombstones/wrap, full replacement, moving-hole repair, zero capacity, complete owners/files/senders, allocation rollback/peak/refunds, immutable/exclusive/task loans, nominal policies, invalid representation safety, source/AIR/profile/package consistency and GC/schedule stress are required before completion. HashSet and BinaryHeap remain separate increments.
|
||||
|
||||
## Documentation budget
|
||||
|
||||
Relative to the static-operation prerequisite (RFC 0029), all full-source counts exclude AIR:
|
||||
|
||||
| Group | cl100k before → after | o200k before → after | Qwen2.5 before → after |
|
||||
|---|---|---|---|
|
||||
| Quick Reference | 8,051 → 8,124 | 8,082 → 8,156 | 8,300 → 8,374 |
|
||||
| Other source | 51,002 → 53,363 | 51,150 → 53,537 | 52,468 → 54,845 |
|
||||
| Full source | 59,053 → 61,487 | 59,232 → 61,693 | 60,768 → 63,219 |
|
||||
|
||||
cl100k growth is +0.9% / +4.6% / +4.1%. library/std.md is 16,504 cl100k tokens. AIR remains 179,282 bytes / 19 files / 51 sections (46,300 cl100k in the source bundle). No normative AIR material is needed. Full source growth from the pre-stdlib 33,981-token baseline is +80.9%; the justification is a general owning-key map meeting the original HashMap<Key, Own<Value>> gate, exact failure/resource contracts and a separate numeric API retained for compatibility. The Quick Reference has one compact paragraph; policies/invariants/accounting stay on demand. Selective reference reading/consolidation remains separate work; no empirical MCC benefit is claimed.
|
||||
|
||||
## Validation progress
|
||||
|
||||
The complete conformance corpus passes 947 cases, including 33 general-map cases. Unit tests, Quick Reference checking, formatting, reference-bundle generation, source coverage (104/104 constructs) and 55 CLI/source/AIR/profile/package/provenance checks pass. Independent Python dict/dense-order oracles cover 192 public operations across Copy and owning-value traces, checking every key and complete returned owners. Tests cover owning byte-buffer keys, owning key/value replacement/full returns, files, sender task transfer, shared lookups, exact allocation peaks, both reserve-failure phases, new-allocation rollback, cross-authority refunds and invalid-metadata nonempty free. The focused collection-before-every-step/scheduler-stress process is still running; its result is not yet claimed. No wall-clock execution limit is used.
|
||||
@@ -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