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:
dev committed 2026-10-07 10:55:09 +03:00
1 parent f02f4bd55b
commit 7bb5bd7931
52 files changed
+7736 -11

No files matched your search

+2
View File
@@ -32,6 +32,8 @@ jobs:
- run: python3 tests/hosted/source_errors.py
- run: python3 tests/hosted/source_map.py
- run: python3 tools/map_vectors.py
- run: python3 tests/hosted/source_hashmap.py
- run: python3 tools/hashmap_vectors.py
- run: zig-out/bin/aji run --grant out=io.write --grant heap=mem.alloc:64 docs/agent/syntax-example.air
- run: zig build agent-reference
- name: Source construct coverage (Phase 6A)
+2
View File
@@ -26,6 +26,8 @@ python3 tests/hosted/source_hash.py # pure hashes, chunks and source/package/hos
python3 tests/hosted/source_errors.py # pure built-in error construction and authority separation
python3 tests/hosted/source_map.py # exact numeric keys, owning values and profile/package parity
python3 tools/map_vectors.py # independent dictionary oracle for public map traces
python3 tests/hosted/source_hashmap.py # explicit general key policies, profiles and returned ownership
python3 tools/hashmap_vectors.py # independent dict and dense-order oracle, Copy/owning values
(cd tools/eval && python3 -m unittest discover tests) # evaluation harness self-tests
zig fmt --check build.zig src tools
```
+1
View File
@@ -33,6 +33,7 @@ pub fn build(b: *std.Build) void {
mod.addAnonymousImport("std_encoding_hex_aji", .{ .root_source_file = b.path("std/encoding/hex.aji") });
mod.addAnonymousImport("std_fmt_aji", .{ .root_source_file = b.path("std/fmt.aji") });
mod.addAnonymousImport("std_hash_aji", .{ .root_source_file = b.path("std/hash.aji") });
mod.addAnonymousImport("std_hashmap_aji", .{ .root_source_file = b.path("std/hashmap.aji") });
mod.addAnonymousImport("std_map_aji", .{ .root_source_file = b.path("std/map.aji") });
mod.addAnonymousImport("std_math_aji", .{ .root_source_file = b.path("std/math.aji") });
mod.addAnonymousImport("std_option_aji", .{ .root_source_file = b.path("std/option.aji") });
+2
View File
@@ -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.
+2
View File
@@ -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
+1 -1
View File
@@ -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` |
+7 -2
View File
@@ -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.
+1 -1
View File
@@ -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
+1 -1
View File
@@ -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.
+2 -1
View File
@@ -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
View File
@@ -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.
+56
View File
@@ -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.
+1 -1
View File
@@ -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.
+34 -1
View File
@@ -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.
+35
View File
@@ -0,0 +1,35 @@
module demo.hashmap
import std.hashmap;
import std.option;
struct Key { id: u64 }
fn hash(key: ref<Key>) -> u64 effects [] { return key.id; }
fn equal(a: ref<Key>, b: ref<Key>) -> bool effects [] { return a.id == b.id; }
fn main(heap: cap<mem.alloc>) -> u64 effects [mem.alloc] {
let map = match std.hashmap.new::<Key,own<u64>,fn hash,fn equal>(1,heap) {
std.hashmap.NewResult::<Key,own<u64>,fn hash,fn equal>::ok(value) => { move value },
std.hashmap.NewResult::<Key,own<u64>,fn hash,fn equal>::err(error) => { trap; }
};
let value = own.new(42u64,heap) or trap;
{ mut q = map;
match std.hashmap.insert::<Key,own<u64>,fn hash,fn equal>(q,Key { id: 7 },move value) {
std.hashmap.InsertResult::<Key,own<u64>>::inserted => {}
std.hashmap.InsertResult::<Key,own<u64>>::replaced(old) => { trap; }
std.hashmap.InsertResult::<Key,own<u64>>::full(returned) => { trap; }
}
let key = Key { id: 7 };
match std.hashmap.remove::<Key,own<u64>,fn hash,fn equal>(q,ref key) {
std.option.Option::<std.hashmap.Entry<Key,own<u64>>>::some(entry) => {
let (stored_key,owner) = struct.unpack(move entry);
assert(stored_key.id == 7u64); assert(own.take(move owner) == 42u64);
}
std.option.Option::<std.hashmap.Entry<Key,own<u64>>>::none => { trap; }
}
}
match std.hashmap.free::<Key,own<u64>,fn hash,fn equal>(move map) {
std.hashmap.FreeResult::<Key,own<u64>,fn hash,fn equal>::ok => {}
std.hashmap.FreeResult::<Key,own<u64>,fn hash,fn equal>::not_empty(returned) => { trap; }
}
return 42;
}
+1
View File
@@ -9,6 +9,7 @@ pub const registry = [_]Source{
.{ .name = "std.encoding.hex", .file = "std/encoding/hex.aji", .source = @embedFile("std_encoding_hex_aji") },
.{ .name = "std.fmt", .file = "std/fmt.aji", .source = @embedFile("std_fmt_aji") },
.{ .name = "std.hash", .file = "std/hash.aji", .source = @embedFile("std_hash_aji") },
.{ .name = "std.hashmap", .file = "std/hashmap.aji", .source = @embedFile("std_hashmap_aji") },
.{ .name = "std.map", .file = "std/map.aji", .source = @embedFile("std_map_aji") },
.{ .name = "std.math", .file = "std/math.aji", .source = @embedFile("std_math_aji") },
.{ .name = "std.option", .file = "std/option.aji", .source = @embedFile("std_option_aji") },
+268
View File
@@ -0,0 +1,268 @@
module std.hashmap
import std.option;
struct StoredEntry<K,V> { hash: u64, key: K, value: V }
struct Entry<K,V> { key: K, value: V }
enum BucketState { empty, deleted, occupied }
struct Bucket { hash: u64, index: usize, state: BucketState }
struct HashMap<K, V, H: fn(ref<K>) -> u64 effects [], E: fn(ref<K>, ref<K>) -> bool effects []> { entries: buffer<StoredEntry<K,V>>, buckets: buffer<Bucket> }
enum NewResult<K, V, H: fn(ref<K>) -> u64 effects [], E: fn(ref<K>, ref<K>) -> bool effects []> { ok(HashMap<K, V, fn H, fn E>), err(alloc_error) }
enum ReserveResult { ok, err(alloc_error) }
enum InsertResult<K,V> { inserted, replaced(Entry<K,V>), full(Entry<K,V>) }
enum FreeResult<K, V, H: fn(ref<K>) -> u64 effects [], E: fn(ref<K>, ref<K>) -> bool effects []> { ok, not_empty(HashMap<K, V, fn H, fn E>) }
fn new<K, V, H: fn(ref<K>) -> u64 effects [], E: fn(ref<K>, ref<K>) -> bool effects []>(capacity: usize, heap: cap<mem.alloc>) -> NewResult<K, V, fn H, fn E> effects [mem.alloc] {
let maximum = 0usize -% 1usize;
if capacity > maximum / 2usize { return NewResult::<K, V, fn H, fn E>::err(alloc_error::budget_exceeded); }
match buffer.new<StoredEntry<K,V>>(capacity, heap) {
err(error) => { return NewResult::<K, V, fn H, fn E>::err(error); }
ok(entries) => {
match buffer.new<Bucket>(capacity * 2usize, heap) {
err(error) => { buffer.free(move entries) or trap; return NewResult::<K, V, fn H, fn E>::err(error); }
ok(buckets) => {
{ mut output = buckets;
for index in 0usize..capacity * 2usize {
buffer.push(output, Bucket { hash: 0, index: 0, state: BucketState::empty }) or trap;
}
}
return NewResult::<K, V, fn H, fn E>::ok(HashMap::<K, V, fn H, fn E> { entries: move entries, buckets: move buckets });
}
}
}
}
}
fn len<K, V, H: fn(ref<K>) -> u64 effects [], E: fn(ref<K>, ref<K>) -> bool effects []>(map: ref<HashMap<K, V, fn H, fn E>>) -> usize effects [] {
ref entries = map.entries; return buffer.len(entries);
}
fn capacity<K, V, H: fn(ref<K>) -> u64 effects [], E: fn(ref<K>, ref<K>) -> bool effects []>(map: ref<HashMap<K, V, fn H, fn E>>) -> usize effects [] {
ref entries = map.entries; return buffer.capacity(entries);
}
fn insert<K, V, H: fn(ref<K>) -> u64 effects [], E: fn(ref<K>, ref<K>) -> bool effects []>(map: mut<HashMap<K, V, fn H, fn E>>, key: K, value: V) -> InsertResult<K,V> effects [] {
var count: usize = 0;
{ ref index = map.buckets; count = buffer.len(index); }
if count == 0usize { return InsertResult::<K,V>::full(Entry::<K,V> { key: move key, value: move value }); }
let incoming = Entry::<K,V> { key: move key, value: move value };
let hash = H(ref incoming.key);
var position: usize = (hash % (count as! u64)) as! usize;
var chosen: usize = count;
var found: bool = false;
var entry_index: usize = 0;
{ ref index = map.buckets; ref buckets = buffer.view(index);
ref storage = map.entries; ref entries = buffer.view(storage);
for probe in 0usize..count {
ref bucket = buckets[position];
var stop: bool = false;
match bucket.state {
BucketState::occupied => {
if bucket.hash == hash {
if E(ref entries[bucket.index].key, ref incoming.key) { found = true; entry_index = bucket.index; }
}
}
BucketState::deleted => { if chosen == count { chosen = position; } }
BucketState::empty => { if chosen == count { chosen = position; } stop = true; }
}
if found or stop { break; }
position = if position == count - 1usize { 0usize } else { position + 1usize };
}
}
if found {
let (key, value) = struct.unpack(move incoming);
mut storage = map.entries; mut entries = buffer.view(storage);
let previous = value.swap(mut entries[entry_index], StoredEntry::<K,V> { hash: hash, key: move key, value: move value });
let (old_hash, old_key, old_value) = struct.unpack(move previous);
return InsertResult::<K,V>::replaced(Entry::<K,V> { key: move old_key, value: move old_value });
}
var length: usize = 0;
{ ref storage = map.entries;
length = buffer.len(storage);
if length == buffer.capacity(storage) { return InsertResult::<K,V>::full(move incoming); }
}
if chosen == count { trap; }
let (key, value) = struct.unpack(move incoming);
{ mut storage = map.entries;
buffer.push(storage, StoredEntry::<K,V> { hash: hash, key: move key, value: move value }) or trap;
}
{ mut index = map.buckets; mut buckets = buffer.view(index);
buckets[chosen] = Bucket { hash: hash, index: length, state: BucketState::occupied };
}
return InsertResult::<K,V>::inserted;
}
fn contains<K, V, H: fn(ref<K>) -> u64 effects [], E: fn(ref<K>, ref<K>) -> bool effects []>(map: ref<HashMap<K, V, fn H, fn E>>, key: ref<K>) -> bool effects [] {
ref index = map.buckets; let count = buffer.len(index);
if count == 0usize { return false; }
let hash = H(key);
var position: usize = (hash % (count as! u64)) as! usize;
ref buckets = buffer.view(index); ref storage = map.entries; ref entries = buffer.view(storage);
for probe in 0usize..count {
ref bucket = buckets[position];
match bucket.state {
BucketState::occupied => { if bucket.hash == hash { if E(ref entries[bucket.index].key, key) { return true; } } }
BucketState::deleted => {}
BucketState::empty => { return false; }
}
position = if position == count - 1usize { 0usize } else { position + 1usize };
}
return false;
}
fn get<K, V: Copy, H: fn(ref<K>) -> u64 effects [], E: fn(ref<K>, ref<K>) -> bool effects []>(map: ref<HashMap<K, V, fn H, fn E>>, key: ref<K>) -> std.option.Option<V> effects [] {
ref index = map.buckets; let count = buffer.len(index);
if count == 0usize { return std.option.Option::<V>::none; }
let hash = H(key);
var position: usize = (hash % (count as! u64)) as! usize;
ref buckets = buffer.view(index); ref storage = map.entries; ref entries = buffer.view(storage);
for probe in 0usize..count {
ref bucket = buckets[position];
match bucket.state {
BucketState::occupied => { if bucket.hash == hash { if E(ref entries[bucket.index].key, key) { return std.option.Option::<V>::some(entries[bucket.index].value); } } }
BucketState::deleted => {}
BucketState::empty => { return std.option.Option::<V>::none; }
}
position = if position == count - 1usize { 0usize } else { position + 1usize };
}
return std.option.Option::<V>::none;
}
fn remove<K, V, H: fn(ref<K>) -> u64 effects [], E: fn(ref<K>, ref<K>) -> bool effects []>(map: mut<HashMap<K, V, fn H, fn E>>, key: ref<K>) -> std.option.Option<Entry<K,V>> effects [] {
var count: usize = 0;
{ ref index = map.buckets; count = buffer.len(index); }
if count == 0usize { return std.option.Option::<Entry<K,V>>::none; }
let hash = H(key);
var position: usize = (hash % (count as! u64)) as! usize;
var found: bool = false;
var entry_index: usize = 0;
{ ref index = map.buckets; ref buckets = buffer.view(index);
ref storage = map.entries; ref entries = buffer.view(storage);
for probe in 0usize..count {
ref bucket = buckets[position];
var stop: bool = false;
match bucket.state {
BucketState::occupied => { if bucket.hash == hash { if E(ref entries[bucket.index].key, key) { found = true; entry_index = bucket.index; } } }
BucketState::deleted => {}
BucketState::empty => { stop = true; }
}
if found or stop { break; }
position = if position == count - 1usize { 0usize } else { position + 1usize };
}
}
if not found { return std.option.Option::<Entry<K,V>>::none; }
{ mut index = map.buckets; mut buckets = buffer.view(index); buckets[position].state = BucketState::deleted; }
mut storage = map.entries;
let last = buffer.pop(storage) or trap;
let last_index = buffer.len(storage);
if entry_index == last_index {
let (old_hash, old_key, old_value) = struct.unpack(move last);
return std.option.Option::<Entry<K,V>>::some(Entry::<K,V> { key: move old_key, value: move old_value });
}
let last_hash = last.hash;
let removed = { mut entries = buffer.view(storage); value.swap(mut entries[entry_index], move last) };
{ mut index = map.buckets; mut buckets = buffer.view(index);
var next: usize = (last_hash % (count as! u64)) as! usize;
var repaired: bool = false;
for probe in 0usize..count {
mut bucket = buckets[next];
match bucket.state {
BucketState::occupied => {
if bucket.hash == last_hash and bucket.index == last_index { bucket.index = entry_index; repaired = true; }
}
BucketState::deleted => {}
BucketState::empty => { trap; }
}
if repaired { break; }
next = if next == count - 1usize { 0usize } else { next + 1usize };
}
if not repaired { trap; }
}
let (old_hash, old_key, old_value) = struct.unpack(move removed);
return std.option.Option::<Entry<K,V>>::some(Entry::<K,V> { key: move old_key, value: move old_value });
}
fn pop<K, V, H: fn(ref<K>) -> u64 effects [], E: fn(ref<K>, ref<K>) -> bool effects []>(map: mut<HashMap<K, V, fn H, fn E>>) -> std.option.Option<Entry<K,V>> effects [] {
var last_index: usize = 0;
var hash: u64 = 0;
{ ref storage = map.entries;
let length = buffer.len(storage);
if length == 0usize { return std.option.Option::<Entry<K,V>>::none; }
last_index = length - 1usize;
ref entries = buffer.view(storage); hash = entries[last_index].hash;
}
{ mut index = map.buckets;
let count = buffer.len(index);
if count == 0usize { trap; }
mut buckets = buffer.view(index);
var position: usize = (hash % (count as! u64)) as! usize;
var found: bool = false;
for probe in 0usize..count {
mut bucket = buckets[position];
match bucket.state {
BucketState::occupied => { if bucket.hash == hash and bucket.index == last_index { bucket.state = BucketState::deleted; found = true; } }
BucketState::empty => { trap; }
BucketState::deleted => {}
}
if found { break; }
position = if position == count - 1usize { 0usize } else { position + 1usize };
}
if not found { trap; }
}
mut storage = map.entries; let entry = buffer.pop(storage) or trap;
let (old_hash, key, value) = struct.unpack(move entry);
return std.option.Option::<Entry<K,V>>::some(Entry::<K,V> { key: move key, value: move value });
}
fn free<K, V, H: fn(ref<K>) -> u64 effects [], E: fn(ref<K>, ref<K>) -> bool effects []>(map: HashMap<K, V, fn H, fn E>) -> FreeResult<K, V, fn H, fn E> effects [] {
var length: usize = 0;
{ ref storage = map.entries; length = buffer.len(storage); }
if length != 0usize { return FreeResult::<K, V, fn H, fn E>::not_empty(move map); }
let (entries, buckets) = struct.unpack(move map);
buffer.free(move entries) or trap;
{ mut index = buckets; while buffer.len(index) != 0usize { let unused = buffer.pop(index) or trap; } }
buffer.free(move buckets) or trap;
return FreeResult::<K, V, fn H, fn E>::ok;
}
fn reserve<K, V, H: fn(ref<K>) -> u64 effects [], E: fn(ref<K>, ref<K>) -> bool effects []>(map: mut<HashMap<K, V, fn H, fn E>>, capacity: usize, heap: cap<mem.alloc>) -> ReserveResult effects [mem.alloc] {
{ ref entries = map.entries; if capacity <= buffer.capacity(entries) { return ReserveResult::ok; } }
let maximum = 0usize -% 1usize;
if capacity > maximum / 2usize { return ReserveResult::err(alloc_error::budget_exceeded); }
match buffer.new<Bucket>(capacity * 2usize, heap) {
err(error) => { return ReserveResult::err(error); }
ok(next) => {
{ mut index = next;
for i in 0usize..capacity * 2usize { buffer.push(index, Bucket { hash: 0, index: 0, state: BucketState::empty }) or trap; }
}
{ mut entries = map.entries;
match buffer.reserve(entries, capacity, heap) {
ok() => {}
err(error) => {
{ mut index = next; while buffer.len(index) != 0usize { let unused = buffer.pop(index) or trap; } }
buffer.free(move next) or trap;
return ReserveResult::err(error);
}
}
}
{ ref storage = map.entries; ref entries = buffer.view(storage);
mut index = next; let count = buffer.len(index); mut buckets = buffer.view(index);
for i in 0usize..entries.len {
let hash = entries[i].hash;
var position: usize = (hash % (count as! u64)) as! usize;
var found: bool = false;
for probe in 0usize..count {
{ ref bucket = buckets[position]; match bucket.state { BucketState::empty => { found = true; }, BucketState::deleted => { trap; }, BucketState::occupied => {} } }
if found { break; }
position = if position == count - 1usize { 0usize } else { position + 1usize };
}
if not found { trap; }
buckets[position] = Bucket { hash: hash, index: i, state: BucketState::occupied };
}
}
let previous = value.swap(mut map.buckets, move next);
{ mut index = previous; while buffer.len(index) != 0usize { let unused = buffer.pop(index) or trap; } }
buffer.free(move previous) or trap;
return ReserveResult::ok;
}
}
}
@@ -0,0 +1,30 @@
// expect: reject E2101
// phase: 6
// spec: docs/spec/16-standard-library.md §2.14
module test.hashmap
import std.hashmap;
import std.option;
fn opened<K, V, H: fn(ref<K>) -> u64 effects [], E: fn(ref<K>, ref<K>) -> bool effects []>(capacity: usize, heap: cap<mem.alloc>) -> std.hashmap.HashMap<K, V, fn H, fn E> effects [mem.alloc] {
match std.hashmap.new::<K, V, fn H, fn E>(capacity, heap) {
std.hashmap.NewResult::<K, V, fn H, fn E>::ok(map) => { return move map; }
std.hashmap.NewResult::<K, V, fn H, fn E>::err(error) => { trap; }
}
}
fn inserted<K, V>(result: std.hashmap.InsertResult<K,V>) -> void effects [] {
match move result { std.hashmap.InsertResult::<K,V>::inserted => {}, std.hashmap.InsertResult::<K,V>::full(value) => { trap; }, std.hashmap.InsertResult::<K,V>::replaced(value) => { trap; } }
}
fn extracted<T>(value: std.option.Option<T>) -> T effects [] {
match move value { std.option.Option::<T>::some(item) => { return move item; }, std.option.Option::<T>::none => { trap; } }
}
fn released<K, V, H: fn(ref<K>) -> u64 effects [], E: fn(ref<K>, ref<K>) -> bool effects []>(map: std.hashmap.HashMap<K, V, fn H, fn E>) -> void effects [] {
match std.hashmap.free::<K, V, fn H, fn E>(move map) { std.hashmap.FreeResult::<K, V, fn H, fn E>::ok => {}, std.hashmap.FreeResult::<K, V, fn H, fn E>::not_empty(value) => { trap; } }
}
struct Key { id: u64 }
fn hash(key: ref<Key>) -> u64 effects [] { return 3; }
fn equal(a: ref<Key>, b: ref<Key>) -> bool effects [] { return a.id == b.id; }
fn bad(map: mut<std.hashmap.HashMap<Key, u64, fn hash, fn equal>>) -> void effects [] {
ref entries = map.entries; ref view = buffer.view(entries);
inserted::<Key,u64>(std.hashmap.insert::<Key, u64, fn hash, fn equal>(map, Key { id: 1 }, 42));
assert(view.len == 0usize);
}
fn main() -> u64 effects [] { return 42; }
@@ -0,0 +1,50 @@
// expect: run
// result: 42
// phase: 6
// spec: docs/spec/16-standard-library.md §2.14
// grant: heap=mem.alloc:256
module test.hashmap
import std.hashmap;
import std.option;
fn opened<K, V, H: fn(ref<K>) -> u64 effects [], E: fn(ref<K>, ref<K>) -> bool effects []>(capacity: usize, heap: cap<mem.alloc>) -> std.hashmap.HashMap<K, V, fn H, fn E> effects [mem.alloc] {
match std.hashmap.new::<K, V, fn H, fn E>(capacity, heap) {
std.hashmap.NewResult::<K, V, fn H, fn E>::ok(map) => { return move map; }
std.hashmap.NewResult::<K, V, fn H, fn E>::err(error) => { trap; }
}
}
fn inserted<K, V>(result: std.hashmap.InsertResult<K,V>) -> void effects [] {
match move result { std.hashmap.InsertResult::<K,V>::inserted => {}, std.hashmap.InsertResult::<K,V>::full(value) => { trap; }, std.hashmap.InsertResult::<K,V>::replaced(value) => { trap; } }
}
fn extracted<T>(value: std.option.Option<T>) -> T effects [] {
match move value { std.option.Option::<T>::some(item) => { return move item; }, std.option.Option::<T>::none => { trap; } }
}
fn released<K, V, H: fn(ref<K>) -> u64 effects [], E: fn(ref<K>, ref<K>) -> bool effects []>(map: std.hashmap.HashMap<K, V, fn H, fn E>) -> void effects [] {
match std.hashmap.free::<K, V, fn H, fn E>(move map) { std.hashmap.FreeResult::<K, V, fn H, fn E>::ok => {}, std.hashmap.FreeResult::<K, V, fn H, fn E>::not_empty(value) => { trap; } }
}
fn hash(key: ref<buffer<u8>>) -> u64 effects [] { return 3; }
fn equal(a: ref<buffer<u8>>, b: ref<buffer<u8>>) -> bool effects [] {
ref left = buffer.view(a); ref right = buffer.view(b);
if left.len != right.len { return false; }
for i in 0usize..left.len { if left[i] != right[i] { return false; } }
return true;
}
fn bytes(value: u8, heap: cap<mem.alloc>) -> buffer<u8> effects [mem.alloc] {
let result = buffer.new<u8>(2usize, heap) or trap;
{ mut q = result; buffer.push(q, value) or trap; buffer.push(q, 0u8) or trap; }
return move result;
}
fn key_freed(key: buffer<u8>) -> void effects [] {
{ mut q = key; while buffer.len(q) != 0usize { let unused = buffer.pop(q) or trap; } } buffer.free(move key) or trap;
}
fn main(heap: cap<mem.alloc>) -> u64 effects [mem.alloc] {
let map = opened::<buffer<u8>, u64, fn hash, fn equal>(2, heap);
{ mut q = map;
let first = bytes(7u8, heap); inserted::<buffer<u8>,u64>(std.hashmap.insert::<buffer<u8>, u64, fn hash, fn equal>(q, move first, 42));
let second = bytes(8u8, heap); inserted::<buffer<u8>,u64>(std.hashmap.insert::<buffer<u8>, u64, fn hash, fn equal>(q, move second, 8));
let query = bytes(7u8, heap);
assert(extracted::<u64>(std.hashmap.get::<buffer<u8>, u64, fn hash, fn equal>(ref q, ref query)) == 42u64);
let entry = extracted::<std.hashmap.Entry<buffer<u8>,u64>>(std.hashmap.remove::<buffer<u8>, u64, fn hash, fn equal>(q, ref query));
let (key,value) = struct.unpack(move entry); assert(value == 42u64); key_freed(move key); key_freed(move query);
let last = extracted::<std.hashmap.Entry<buffer<u8>,u64>>(std.hashmap.pop::<buffer<u8>, u64, fn hash, fn equal>(q)); let (last_key,last_value) = struct.unpack(move last); assert(last_value == 8u64); key_freed(move last_key);
} released::<buffer<u8>, u64, fn hash, fn equal>(move map); return 42;
}
+53
View File
@@ -0,0 +1,53 @@
// expect: run
// result: 42
// phase: 6
// spec: docs/spec/16-standard-library.md §2.14
// grant: heap=mem.alloc:1024
module test.hashmap
import std.hashmap;
import std.option;
fn opened<K, V, H: fn(ref<K>) -> u64 effects [], E: fn(ref<K>, ref<K>) -> bool effects []>(capacity: usize, heap: cap<mem.alloc>) -> std.hashmap.HashMap<K, V, fn H, fn E> effects [mem.alloc] {
match std.hashmap.new::<K, V, fn H, fn E>(capacity, heap) {
std.hashmap.NewResult::<K, V, fn H, fn E>::ok(map) => { return move map; }
std.hashmap.NewResult::<K, V, fn H, fn E>::err(error) => { trap; }
}
}
fn inserted<K, V>(result: std.hashmap.InsertResult<K,V>) -> void effects [] {
match move result { std.hashmap.InsertResult::<K,V>::inserted => {}, std.hashmap.InsertResult::<K,V>::full(value) => { trap; }, std.hashmap.InsertResult::<K,V>::replaced(value) => { trap; } }
}
fn extracted<T>(value: std.option.Option<T>) -> T effects [] {
match move value { std.option.Option::<T>::some(item) => { return move item; }, std.option.Option::<T>::none => { trap; } }
}
fn released<K, V, H: fn(ref<K>) -> u64 effects [], E: fn(ref<K>, ref<K>) -> bool effects []>(map: std.hashmap.HashMap<K, V, fn H, fn E>) -> void effects [] {
match std.hashmap.free::<K, V, fn H, fn E>(move map) { std.hashmap.FreeResult::<K, V, fn H, fn E>::ok => {}, std.hashmap.FreeResult::<K, V, fn H, fn E>::not_empty(value) => { trap; } }
}
struct Key { id: u64 }
fn hash(key: ref<Key>) -> u64 effects [] { return 3; }
fn equal(a: ref<Key>, b: ref<Key>) -> bool effects [] { return a.id == b.id; }
fn main(heap: cap<mem.alloc>) -> u64 effects [mem.alloc] {
let map = opened::<Key, u64, fn hash, fn equal>(2, heap);
{ mut q = map;
inserted::<Key,u64>(std.hashmap.insert::<Key, u64, fn hash, fn equal>(q, Key { id: 1 }, 11));
inserted::<Key,u64>(std.hashmap.insert::<Key, u64, fn hash, fn equal>(q, Key { id: 2 }, 22));
match std.hashmap.insert::<Key, u64, fn hash, fn equal>(q, Key { id: 3 }, 33) {
std.hashmap.InsertResult::<Key,u64>::full(entry) => { assert(entry.key.id == 3u64); assert(entry.value == 33u64); },
std.hashmap.InsertResult::<Key,u64>::inserted => { trap; }, std.hashmap.InsertResult::<Key,u64>::replaced(old) => { trap; }
}
match std.hashmap.insert::<Key, u64, fn hash, fn equal>(q, Key { id: 2 }, 42) {
std.hashmap.InsertResult::<Key,u64>::replaced(old) => { assert(old.key.id == 2u64); assert(old.value == 22u64); },
std.hashmap.InsertResult::<Key,u64>::inserted => { trap; }, std.hashmap.InsertResult::<Key,u64>::full(entry) => { trap; }
}
let key = Key { id: 1 };
let removed = extracted::<std.hashmap.Entry<Key,u64>>(std.hashmap.remove::<Key, u64, fn hash, fn equal>(q, ref key));
assert(removed.key.id == 1u64); assert(removed.value == 11u64);
inserted::<Key,u64>(std.hashmap.insert::<Key, u64, fn hash, fn equal>(q, Key { id: 3 }, 33));
match std.hashmap.reserve::<Key, u64, fn hash, fn equal>(q, 4, heap) { std.hashmap.ReserveResult::ok => {}, std.hashmap.ReserveResult::err(error) => { trap; } }
}
{ ref q = map; let key = Key { id: 2 }; assert(std.hashmap.contains::<Key, u64, fn hash, fn equal>(q, ref key));
assert(extracted::<u64>(std.hashmap.get::<Key, u64, fn hash, fn equal>(q, ref key)) == 42u64);
assert(std.hashmap.len::<Key, u64, fn hash, fn equal>(q) == 2usize); assert(std.hashmap.capacity::<Key, u64, fn hash, fn equal>(q) == 4usize);
}
{ mut q = map; let last = extracted::<std.hashmap.Entry<Key,u64>>(std.hashmap.pop::<Key, u64, fn hash, fn equal>(q)); assert(last.key.id == 3u64);
let first = extracted::<std.hashmap.Entry<Key,u64>>(std.hashmap.pop::<Key, u64, fn hash, fn equal>(q)); assert(first.value == 42u64); }
released::<Key, u64, fn hash, fn equal>(move map); return 42;
}
+35
View File
@@ -0,0 +1,35 @@
// expect: run
// result: 42
// phase: 6
// spec: docs/spec/16-standard-library.md §2.14
// grant: heap=mem.alloc:58
// grant: dst=fs.write:/out
// file: /out/hashmap.txt=42
module test.hashmap
import std.hashmap;
import std.option;
fn opened<K, V, H: fn(ref<K>) -> u64 effects [], E: fn(ref<K>, ref<K>) -> bool effects []>(capacity: usize, heap: cap<mem.alloc>) -> std.hashmap.HashMap<K, V, fn H, fn E> effects [mem.alloc] {
match std.hashmap.new::<K, V, fn H, fn E>(capacity, heap) {
std.hashmap.NewResult::<K, V, fn H, fn E>::ok(map) => { return move map; }
std.hashmap.NewResult::<K, V, fn H, fn E>::err(error) => { trap; }
}
}
fn inserted<K, V>(result: std.hashmap.InsertResult<K,V>) -> void effects [] {
match move result { std.hashmap.InsertResult::<K,V>::inserted => {}, std.hashmap.InsertResult::<K,V>::full(value) => { trap; }, std.hashmap.InsertResult::<K,V>::replaced(value) => { trap; } }
}
fn extracted<T>(value: std.option.Option<T>) -> T effects [] {
match move value { std.option.Option::<T>::some(item) => { return move item; }, std.option.Option::<T>::none => { trap; } }
}
fn released<K, V, H: fn(ref<K>) -> u64 effects [], E: fn(ref<K>, ref<K>) -> bool effects []>(map: std.hashmap.HashMap<K, V, fn H, fn E>) -> void effects [] {
match std.hashmap.free::<K, V, fn H, fn E>(move map) { std.hashmap.FreeResult::<K, V, fn H, fn E>::ok => {}, std.hashmap.FreeResult::<K, V, fn H, fn E>::not_empty(value) => { trap; } }
}
struct Key { id: u64 }
fn hash(key: ref<Key>) -> u64 effects [] { return 3; }
fn equal(a: ref<Key>, b: ref<Key>) -> bool effects [] { return a.id == b.id; }
fn main(heap: cap<mem.alloc>, dst: cap<fs.write>) -> u64 effects [mem.alloc, fs.write] {
let map = opened::<Key, file<write>, fn hash, fn equal>(1, heap); let file = fs.create(dst, b"/out/hashmap.txt") or trap;
{ mut q = map; inserted::<Key,file<write>>(std.hashmap.insert::<Key, file<write>, fn hash, fn equal>(q, Key { id: 7 }, move file));
let key = Key { id: 7 }; let entry = extracted::<std.hashmap.Entry<Key,file<write>>>(std.hashmap.remove::<Key, file<write>, fn hash, fn equal>(q, ref key));
let (stored_key,item) = struct.unpack(move entry); fs.write_all(item, b"42") or trap; fs.close(move item) or trap; }
released::<Key, file<write>, fn hash, fn equal>(move map); return 42;
}
@@ -0,0 +1,28 @@
// expect: reject E3002
// phase: 6
// spec: docs/spec/16-standard-library.md §2.14
module test.hashmap
import std.hashmap;
import std.option;
fn opened<K, V, H: fn(ref<K>) -> u64 effects [], E: fn(ref<K>, ref<K>) -> bool effects []>(capacity: usize, heap: cap<mem.alloc>) -> std.hashmap.HashMap<K, V, fn H, fn E> effects [mem.alloc] {
match std.hashmap.new::<K, V, fn H, fn E>(capacity, heap) {
std.hashmap.NewResult::<K, V, fn H, fn E>::ok(map) => { return move map; }
std.hashmap.NewResult::<K, V, fn H, fn E>::err(error) => { trap; }
}
}
fn inserted<K, V>(result: std.hashmap.InsertResult<K,V>) -> void effects [] {
match move result { std.hashmap.InsertResult::<K,V>::inserted => {}, std.hashmap.InsertResult::<K,V>::full(value) => { trap; }, std.hashmap.InsertResult::<K,V>::replaced(value) => { trap; } }
}
fn extracted<T>(value: std.option.Option<T>) -> T effects [] {
match move value { std.option.Option::<T>::some(item) => { return move item; }, std.option.Option::<T>::none => { trap; } }
}
fn released<K, V, H: fn(ref<K>) -> u64 effects [], E: fn(ref<K>, ref<K>) -> bool effects []>(map: std.hashmap.HashMap<K, V, fn H, fn E>) -> void effects [] {
match std.hashmap.free::<K, V, fn H, fn E>(move map) { std.hashmap.FreeResult::<K, V, fn H, fn E>::ok => {}, std.hashmap.FreeResult::<K, V, fn H, fn E>::not_empty(value) => { trap; } }
}
struct Key { id: u64 }
fn hash(key: ref<Key>) -> u64 effects [] { return 3; }
fn equal(a: ref<Key>, b: ref<Key>) -> bool effects [] { return a.id == b.id; }
fn bad(map: std.hashmap.HashMap<Key, own<u64>, fn hash, fn equal>) -> void effects [] {
match std.hashmap.free::<Key, own<u64>, fn hash, fn equal>(move map) { std.hashmap.FreeResult::<Key, own<u64>, fn hash, fn equal>::not_empty(returned) => { return; }, std.hashmap.FreeResult::<Key, own<u64>, fn hash, fn equal>::ok => {} }
}
fn main() -> u64 effects [] { return 42; }
@@ -0,0 +1,32 @@
// expect: reject E3002
// phase: 6
// spec: docs/spec/16-standard-library.md §2.14
module test.hashmap
import std.hashmap;
import std.option;
fn opened<K, V, H: fn(ref<K>) -> u64 effects [], E: fn(ref<K>, ref<K>) -> bool effects []>(capacity: usize, heap: cap<mem.alloc>) -> std.hashmap.HashMap<K, V, fn H, fn E> effects [mem.alloc] {
match std.hashmap.new::<K, V, fn H, fn E>(capacity, heap) {
std.hashmap.NewResult::<K, V, fn H, fn E>::ok(map) => { return move map; }
std.hashmap.NewResult::<K, V, fn H, fn E>::err(error) => { trap; }
}
}
fn inserted<K, V>(result: std.hashmap.InsertResult<K,V>) -> void effects [] {
match move result { std.hashmap.InsertResult::<K,V>::inserted => {}, std.hashmap.InsertResult::<K,V>::full(value) => { trap; }, std.hashmap.InsertResult::<K,V>::replaced(value) => { trap; } }
}
fn extracted<T>(value: std.option.Option<T>) -> T effects [] {
match move value { std.option.Option::<T>::some(item) => { return move item; }, std.option.Option::<T>::none => { trap; } }
}
fn released<K, V, H: fn(ref<K>) -> u64 effects [], E: fn(ref<K>, ref<K>) -> bool effects []>(map: std.hashmap.HashMap<K, V, fn H, fn E>) -> void effects [] {
match std.hashmap.free::<K, V, fn H, fn E>(move map) { std.hashmap.FreeResult::<K, V, fn H, fn E>::ok => {}, std.hashmap.FreeResult::<K, V, fn H, fn E>::not_empty(value) => { trap; } }
}
struct Key { id: u64 }
fn hash(key: ref<Key>) -> u64 effects [] { return 3; }
fn equal(a: ref<Key>, b: ref<Key>) -> bool effects [] { return a.id == b.id; }
fn bad(map: mut<std.hashmap.HashMap<Key,own<u64>,fn hash,fn equal>>, value: own<u64>) -> void effects [] {
match std.hashmap.insert::<Key,own<u64>,fn hash,fn equal>(map, Key { id: 1 }, move value) {
std.hashmap.InsertResult::<Key,own<u64>>::inserted => {},
std.hashmap.InsertResult::<Key,own<u64>>::replaced(entry) => { trap; },
std.hashmap.InsertResult::<Key,own<u64>>::full(entry) => { return; }
}
}
fn main() -> u64 effects [] { return 42; }
@@ -0,0 +1,28 @@
// expect: reject E7005
// phase: 6
// spec: docs/spec/16-standard-library.md §2.14
module test.hashmap
import std.hashmap;
import std.option;
fn opened<K, V, H: fn(ref<K>) -> u64 effects [], E: fn(ref<K>, ref<K>) -> bool effects []>(capacity: usize, heap: cap<mem.alloc>) -> std.hashmap.HashMap<K, V, fn H, fn E> effects [mem.alloc] {
match std.hashmap.new::<K, V, fn H, fn E>(capacity, heap) {
std.hashmap.NewResult::<K, V, fn H, fn E>::ok(map) => { return move map; }
std.hashmap.NewResult::<K, V, fn H, fn E>::err(error) => { trap; }
}
}
fn inserted<K, V>(result: std.hashmap.InsertResult<K,V>) -> void effects [] {
match move result { std.hashmap.InsertResult::<K,V>::inserted => {}, std.hashmap.InsertResult::<K,V>::full(value) => { trap; }, std.hashmap.InsertResult::<K,V>::replaced(value) => { trap; } }
}
fn extracted<T>(value: std.option.Option<T>) -> T effects [] {
match move value { std.option.Option::<T>::some(item) => { return move item; }, std.option.Option::<T>::none => { trap; } }
}
fn released<K, V, H: fn(ref<K>) -> u64 effects [], E: fn(ref<K>, ref<K>) -> bool effects []>(map: std.hashmap.HashMap<K, V, fn H, fn E>) -> void effects [] {
match std.hashmap.free::<K, V, fn H, fn E>(move map) { std.hashmap.FreeResult::<K, V, fn H, fn E>::ok => {}, std.hashmap.FreeResult::<K, V, fn H, fn E>::not_empty(value) => { trap; } }
}
struct Key { id: u64 }
fn hash(key: ref<Key>) -> u64 effects [] { return 3; }
fn equal(a: ref<Key>, b: ref<Key>) -> bool effects [] { return a.id == b.id; }
fn bad(map: ref<std.hashmap.HashMap<Key,own<u64>,fn hash,fn equal>>, key: ref<Key>) -> void effects [] {
std.hashmap.get::<Key,own<u64>,fn hash,fn equal>(map, key);
}
fn main() -> u64 effects [] { return 42; }
@@ -0,0 +1,35 @@
// expect: run
// result: 42
// phase: 6
// spec: docs/spec/16-standard-library.md §2.14
// grant: heap=mem.alloc:58
module test.hashmap
import std.hashmap;
import std.option;
fn opened<K, V, H: fn(ref<K>) -> u64 effects [], E: fn(ref<K>, ref<K>) -> bool effects []>(capacity: usize, heap: cap<mem.alloc>) -> std.hashmap.HashMap<K, V, fn H, fn E> effects [mem.alloc] {
match std.hashmap.new::<K, V, fn H, fn E>(capacity, heap) {
std.hashmap.NewResult::<K, V, fn H, fn E>::ok(map) => { return move map; }
std.hashmap.NewResult::<K, V, fn H, fn E>::err(error) => { trap; }
}
}
fn inserted<K, V>(result: std.hashmap.InsertResult<K,V>) -> void effects [] {
match move result { std.hashmap.InsertResult::<K,V>::inserted => {}, std.hashmap.InsertResult::<K,V>::full(value) => { trap; }, std.hashmap.InsertResult::<K,V>::replaced(value) => { trap; } }
}
fn extracted<T>(value: std.option.Option<T>) -> T effects [] {
match move value { std.option.Option::<T>::some(item) => { return move item; }, std.option.Option::<T>::none => { trap; } }
}
fn released<K, V, H: fn(ref<K>) -> u64 effects [], E: fn(ref<K>, ref<K>) -> bool effects []>(map: std.hashmap.HashMap<K, V, fn H, fn E>) -> void effects [] {
match std.hashmap.free::<K, V, fn H, fn E>(move map) { std.hashmap.FreeResult::<K, V, fn H, fn E>::ok => {}, std.hashmap.FreeResult::<K, V, fn H, fn E>::not_empty(value) => { trap; } }
}
struct Key { id: u64 }
fn hash(key: ref<Key>) -> u64 effects [] { return 3; }
fn equal(a: ref<Key>, b: ref<Key>) -> bool effects [] { return a.id == b.id; }
fn main(heap: cap<mem.alloc>) -> u64 effects [mem.alloc] {
let map = opened::<Key, u64, fn hash, fn equal>(1, heap);
{ mut q = map; inserted::<Key,u64>(std.hashmap.insert::<Key, u64, fn hash, fn equal>(q, Key { id: 1 }, 42));
mut index = q.buckets; mut buckets = buffer.view(index); buckets[1].state = std.hashmap.BucketState::empty; }
match std.hashmap.free::<Key, u64, fn hash, fn equal>(move map) { std.hashmap.FreeResult::<Key, u64, fn hash, fn equal>::not_empty(returned) => {
let (entries,buckets) = struct.unpack(move returned); { mut q = entries; let entry = buffer.pop(q) or trap; assert(entry.value == 42u64); } buffer.free(move entries) or trap;
{ mut q = buckets; while buffer.len(q) != 0usize { let unused = buffer.pop(q) or trap; } } buffer.free(move buckets) or trap;
}, std.hashmap.FreeResult::<Key, u64, fn hash, fn equal>::ok => { trap; } } return 42;
}
@@ -0,0 +1,40 @@
// expect: run
// result: 42
// phase: 6
// spec: docs/spec/16-standard-library.md §2.14
// grant: heap=mem.alloc:82
module test.hashmap
import std.hashmap;
import std.option;
fn opened<K, V, H: fn(ref<K>) -> u64 effects [], E: fn(ref<K>, ref<K>) -> bool effects []>(capacity: usize, heap: cap<mem.alloc>) -> std.hashmap.HashMap<K, V, fn H, fn E> effects [mem.alloc] {
match std.hashmap.new::<K, V, fn H, fn E>(capacity, heap) {
std.hashmap.NewResult::<K, V, fn H, fn E>::ok(map) => { return move map; }
std.hashmap.NewResult::<K, V, fn H, fn E>::err(error) => { trap; }
}
}
fn inserted<K, V>(result: std.hashmap.InsertResult<K,V>) -> void effects [] {
match move result { std.hashmap.InsertResult::<K,V>::inserted => {}, std.hashmap.InsertResult::<K,V>::full(value) => { trap; }, std.hashmap.InsertResult::<K,V>::replaced(value) => { trap; } }
}
fn extracted<T>(value: std.option.Option<T>) -> T effects [] {
match move value { std.option.Option::<T>::some(item) => { return move item; }, std.option.Option::<T>::none => { trap; } }
}
fn released<K, V, H: fn(ref<K>) -> u64 effects [], E: fn(ref<K>, ref<K>) -> bool effects []>(map: std.hashmap.HashMap<K, V, fn H, fn E>) -> void effects [] {
match std.hashmap.free::<K, V, fn H, fn E>(move map) { std.hashmap.FreeResult::<K, V, fn H, fn E>::ok => {}, std.hashmap.FreeResult::<K, V, fn H, fn E>::not_empty(value) => { trap; } }
}
struct Key { id: u64, owner: own<u64> }
fn hash(key: ref<Key>) -> u64 effects [] { return 3; }
fn equal(a: ref<Key>, b: ref<Key>) -> bool effects [] { return a.id == b.id; }
fn consumed(entry: std.hashmap.Entry<Key,own<u64>>, expected_key: u64, expected_value: u64) -> void effects [] {
let (key,value) = struct.unpack(move entry); let (id,owner) = struct.unpack(move key);
assert(own.take(move owner) == expected_key); assert(own.take(move value) == expected_value);
}
fn main(heap: cap<mem.alloc>) -> u64 effects [mem.alloc] {
let map = opened::<Key,u64,fn hash,fn equal>(1, heap);
let key = Key { id: 7, owner: own.new(7u64,heap) or trap };
{ mut q = map; inserted::<Key,u64>(std.hashmap.insert::<Key,u64,fn hash,fn equal>(q, move key, 42)); }
let query = Key { id: 7, owner: own.new(7u64,heap) or trap };
{ ref q = map; assert(extracted::<u64>(std.hashmap.get::<Key,u64,fn hash,fn equal>(q,ref query)) == 42u64); }
let (query_id,query_owner) = struct.unpack(move query); own.take(move query_owner);
{ mut q = map; let entry = extracted::<std.hashmap.Entry<Key,u64>>(std.hashmap.pop::<Key,u64,fn hash,fn equal>(q)); let (stored_key,value) = struct.unpack(move entry); let (id,owner) = struct.unpack(move stored_key); assert(own.take(move owner) == 7u64); assert(value == 42u64); }
released::<Key,u64,fn hash,fn equal>(move map); return 42;
}
@@ -0,0 +1,30 @@
// expect: reject E7003
// phase: 6
// spec: docs/spec/16-standard-library.md §2.14
module test.hashmap
import std.hashmap;
import std.option;
fn opened<K, V, H: fn(ref<K>) -> u64 effects [], E: fn(ref<K>, ref<K>) -> bool effects []>(capacity: usize, heap: cap<mem.alloc>) -> std.hashmap.HashMap<K, V, fn H, fn E> effects [mem.alloc] {
match std.hashmap.new::<K, V, fn H, fn E>(capacity, heap) {
std.hashmap.NewResult::<K, V, fn H, fn E>::ok(map) => { return move map; }
std.hashmap.NewResult::<K, V, fn H, fn E>::err(error) => { trap; }
}
}
fn inserted<K, V>(result: std.hashmap.InsertResult<K,V>) -> void effects [] {
match move result { std.hashmap.InsertResult::<K,V>::inserted => {}, std.hashmap.InsertResult::<K,V>::full(value) => { trap; }, std.hashmap.InsertResult::<K,V>::replaced(value) => { trap; } }
}
fn extracted<T>(value: std.option.Option<T>) -> T effects [] {
match move value { std.option.Option::<T>::some(item) => { return move item; }, std.option.Option::<T>::none => { trap; } }
}
fn released<K, V, H: fn(ref<K>) -> u64 effects [], E: fn(ref<K>, ref<K>) -> bool effects []>(map: std.hashmap.HashMap<K, V, fn H, fn E>) -> void effects [] {
match std.hashmap.free::<K, V, fn H, fn E>(move map) { std.hashmap.FreeResult::<K, V, fn H, fn E>::ok => {}, std.hashmap.FreeResult::<K, V, fn H, fn E>::not_empty(value) => { trap; } }
}
struct Key { id: u64, owner: own<u64> }
fn hash(key: ref<Key>) -> u64 effects [] { return 3; }
fn equal(a: ref<Key>, b: ref<Key>) -> bool effects [] { return a.id == b.id; }
fn consumed(entry: std.hashmap.Entry<Key,own<u64>>, expected_key: u64, expected_value: u64) -> void effects [] {
let (key,value) = struct.unpack(move entry); let (id,owner) = struct.unpack(move key);
assert(own.take(move owner) == expected_key); assert(own.take(move value) == expected_value);
}
fn bad(q: mut<std.hashmap.HashMap<Key, own<u64>, fn hash, fn equal>>, key: Key, value: own<u64>) -> void effects [] { std.hashmap.insert::<Key, own<u64>, fn hash, fn equal>(q, key, move value); }
fn main() -> u64 effects [] { return 42; }
+27
View File
@@ -0,0 +1,27 @@
// expect: reject E4101
// phase: 6
// spec: docs/spec/16-standard-library.md §2.14
module test.hashmap
import std.hashmap;
import std.option;
fn opened<K, V, H: fn(ref<K>) -> u64 effects [], E: fn(ref<K>, ref<K>) -> bool effects []>(capacity: usize, heap: cap<mem.alloc>) -> std.hashmap.HashMap<K, V, fn H, fn E> effects [mem.alloc] {
match std.hashmap.new::<K, V, fn H, fn E>(capacity, heap) {
std.hashmap.NewResult::<K, V, fn H, fn E>::ok(map) => { return move map; }
std.hashmap.NewResult::<K, V, fn H, fn E>::err(error) => { trap; }
}
}
fn inserted<K, V>(result: std.hashmap.InsertResult<K,V>) -> void effects [] {
match move result { std.hashmap.InsertResult::<K,V>::inserted => {}, std.hashmap.InsertResult::<K,V>::full(value) => { trap; }, std.hashmap.InsertResult::<K,V>::replaced(value) => { trap; } }
}
fn extracted<T>(value: std.option.Option<T>) -> T effects [] {
match move value { std.option.Option::<T>::some(item) => { return move item; }, std.option.Option::<T>::none => { trap; } }
}
fn released<K, V, H: fn(ref<K>) -> u64 effects [], E: fn(ref<K>, ref<K>) -> bool effects []>(map: std.hashmap.HashMap<K, V, fn H, fn E>) -> void effects [] {
match std.hashmap.free::<K, V, fn H, fn E>(move map) { std.hashmap.FreeResult::<K, V, fn H, fn E>::ok => {}, std.hashmap.FreeResult::<K, V, fn H, fn E>::not_empty(value) => { trap; } }
}
struct Key { id: u64 }
fn hash(key: ref<Key>) -> u64 effects [] { return 3; }
fn equal(a: ref<Key>, b: ref<Key>) -> bool effects [] { return a.id == b.id; }
fn worker(q: mut<std.hashmap.HashMap<Key, u64, fn hash, fn equal>>) -> void effects [] {}
fn bad(q: mut<std.hashmap.HashMap<Key, u64, fn hash, fn equal>>) -> void effects [task.spawn, task.wait] { scope s { let t = task.spawn(s, worker, q); inserted::<Key,u64>(std.hashmap.insert::<Key, u64, fn hash, fn equal>(q, Key { id: 1 }, 42)); task.join(move t); } }
fn main() -> u64 effects [] { return 42; }
@@ -0,0 +1,34 @@
// expect: run
// result: 42
// phase: 6
// spec: docs/spec/16-standard-library.md §2.14
// grant: heap=mem.alloc:58
// schedules: 12
module test.hashmap
import std.hashmap;
import std.option;
fn opened<K, V, H: fn(ref<K>) -> u64 effects [], E: fn(ref<K>, ref<K>) -> bool effects []>(capacity: usize, heap: cap<mem.alloc>) -> std.hashmap.HashMap<K, V, fn H, fn E> effects [mem.alloc] {
match std.hashmap.new::<K, V, fn H, fn E>(capacity, heap) {
std.hashmap.NewResult::<K, V, fn H, fn E>::ok(map) => { return move map; }
std.hashmap.NewResult::<K, V, fn H, fn E>::err(error) => { trap; }
}
}
fn inserted<K, V>(result: std.hashmap.InsertResult<K,V>) -> void effects [] {
match move result { std.hashmap.InsertResult::<K,V>::inserted => {}, std.hashmap.InsertResult::<K,V>::full(value) => { trap; }, std.hashmap.InsertResult::<K,V>::replaced(value) => { trap; } }
}
fn extracted<T>(value: std.option.Option<T>) -> T effects [] {
match move value { std.option.Option::<T>::some(item) => { return move item; }, std.option.Option::<T>::none => { trap; } }
}
fn released<K, V, H: fn(ref<K>) -> u64 effects [], E: fn(ref<K>, ref<K>) -> bool effects []>(map: std.hashmap.HashMap<K, V, fn H, fn E>) -> void effects [] {
match std.hashmap.free::<K, V, fn H, fn E>(move map) { std.hashmap.FreeResult::<K, V, fn H, fn E>::ok => {}, std.hashmap.FreeResult::<K, V, fn H, fn E>::not_empty(value) => { trap; } }
}
struct Key { id: u64 }
fn hash(key: ref<Key>) -> u64 effects [] { return 3; }
fn equal(a: ref<Key>, b: ref<Key>) -> bool effects [] { return a.id == b.id; }
fn worker(q: mut<std.hashmap.HashMap<Key, u64, fn hash, fn equal>>) -> void effects [] { inserted::<Key,u64>(std.hashmap.insert::<Key, u64, fn hash, fn equal>(q, Key { id: 1 }, 42)); }
fn main(heap: cap<mem.alloc>) -> u64 effects [mem.alloc, task.spawn, task.wait] {
let map = opened::<Key, u64, fn hash, fn equal>(1, heap);
{ mut q = map; scope s { let t = task.spawn(s, worker, q); task.join(move t);
let entry = extracted::<std.hashmap.Entry<Key,u64>>(std.hashmap.pop::<Key, u64, fn hash, fn equal>(q)); assert(entry.value == 42u64); } }
released::<Key, u64, fn hash, fn equal>(move map); return 42;
}
@@ -0,0 +1,28 @@
// expect: reject E3101
// phase: 6
// spec: docs/spec/16-standard-library.md §2.14
module test.hashmap
import std.hashmap;
import std.option;
fn opened<K, V, H: fn(ref<K>) -> u64 effects [], E: fn(ref<K>, ref<K>) -> bool effects []>(capacity: usize, heap: cap<mem.alloc>) -> std.hashmap.HashMap<K, V, fn H, fn E> effects [mem.alloc] {
match std.hashmap.new::<K, V, fn H, fn E>(capacity, heap) {
std.hashmap.NewResult::<K, V, fn H, fn E>::ok(map) => { return move map; }
std.hashmap.NewResult::<K, V, fn H, fn E>::err(error) => { trap; }
}
}
fn inserted<K, V>(result: std.hashmap.InsertResult<K,V>) -> void effects [] {
match move result { std.hashmap.InsertResult::<K,V>::inserted => {}, std.hashmap.InsertResult::<K,V>::full(value) => { trap; }, std.hashmap.InsertResult::<K,V>::replaced(value) => { trap; } }
}
fn extracted<T>(value: std.option.Option<T>) -> T effects [] {
match move value { std.option.Option::<T>::some(item) => { return move item; }, std.option.Option::<T>::none => { trap; } }
}
fn released<K, V, H: fn(ref<K>) -> u64 effects [], E: fn(ref<K>, ref<K>) -> bool effects []>(map: std.hashmap.HashMap<K, V, fn H, fn E>) -> void effects [] {
match std.hashmap.free::<K, V, fn H, fn E>(move map) { std.hashmap.FreeResult::<K, V, fn H, fn E>::ok => {}, std.hashmap.FreeResult::<K, V, fn H, fn E>::not_empty(value) => { trap; } }
}
struct Key { id: u64 }
fn hash(key: ref<Key>) -> u64 effects [] { return 3; }
fn equal(a: ref<Key>, b: ref<Key>) -> bool effects [] { return a.id == b.id; }
fn bad(map: mut<std.hashmap.HashMap<Key, u64, fn hash, fn equal>>, heap: cap<mem.alloc>) -> void effects [] {
match std.hashmap.reserve::<Key, u64, fn hash, fn equal>(map, 0, heap) { std.hashmap.ReserveResult::ok => {}, std.hashmap.ReserveResult::err(error) => { trap; } }
}
fn main() -> u64 effects [] { return 42; }
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,38 @@
// expect: run
// result: 42
// phase: 6
// spec: docs/spec/16-standard-library.md §2.14
// grant: heap=mem.alloc:116
module test.hashmap
import std.hashmap;
import std.option;
fn opened<K, V, H: fn(ref<K>) -> u64 effects [], E: fn(ref<K>, ref<K>) -> bool effects []>(capacity: usize, heap: cap<mem.alloc>) -> std.hashmap.HashMap<K, V, fn H, fn E> effects [mem.alloc] {
match std.hashmap.new::<K, V, fn H, fn E>(capacity, heap) {
std.hashmap.NewResult::<K, V, fn H, fn E>::ok(map) => { return move map; }
std.hashmap.NewResult::<K, V, fn H, fn E>::err(error) => { trap; }
}
}
fn inserted<K, V>(result: std.hashmap.InsertResult<K,V>) -> void effects [] {
match move result { std.hashmap.InsertResult::<K,V>::inserted => {}, std.hashmap.InsertResult::<K,V>::full(value) => { trap; }, std.hashmap.InsertResult::<K,V>::replaced(value) => { trap; } }
}
fn extracted<T>(value: std.option.Option<T>) -> T effects [] {
match move value { std.option.Option::<T>::some(item) => { return move item; }, std.option.Option::<T>::none => { trap; } }
}
fn released<K, V, H: fn(ref<K>) -> u64 effects [], E: fn(ref<K>, ref<K>) -> bool effects []>(map: std.hashmap.HashMap<K, V, fn H, fn E>) -> void effects [] {
match std.hashmap.free::<K, V, fn H, fn E>(move map) { std.hashmap.FreeResult::<K, V, fn H, fn E>::ok => {}, std.hashmap.FreeResult::<K, V, fn H, fn E>::not_empty(value) => { trap; } }
}
struct Key { id: u64 }
fn hash(key: ref<Key>) -> u64 effects [] { return key.id; }
fn equal(a: ref<Key>, b: ref<Key>) -> bool effects [] { return a.id == b.id; }
fn main(heap: cap<mem.alloc>) -> u64 effects [mem.alloc] {
let map = opened::<Key, u64, fn hash, fn equal>(2, heap);
{ mut q = map;
for number in 0usize..4usize {
inserted::<Key,u64>(std.hashmap.insert::<Key, u64, fn hash, fn equal>(q, Key { id: number as! u64 }, 42));
let entry = extracted::<std.hashmap.Entry<Key,u64>>(std.hashmap.pop::<Key, u64, fn hash, fn equal>(q)); assert(entry.value == 42u64);
}
let absent = Key { id: 100 }; assert(not std.hashmap.contains::<Key, u64, fn hash, fn equal>(ref q, ref absent));
inserted::<Key,u64>(std.hashmap.insert::<Key, u64, fn hash, fn equal>(q, absent, 42));
let entry = extracted::<std.hashmap.Entry<Key,u64>>(std.hashmap.pop::<Key, u64, fn hash, fn equal>(q)); assert(entry.value == 42u64);
} released::<Key, u64, fn hash, fn equal>(move map); return 42;
}
@@ -0,0 +1,27 @@
// expect: reject E4002
// phase: 6
// spec: docs/spec/16-standard-library.md §2.14
module test.hashmap
import std.hashmap;
import std.option;
fn opened<K, V, H: fn(ref<K>) -> u64 effects [], E: fn(ref<K>, ref<K>) -> bool effects []>(capacity: usize, heap: cap<mem.alloc>) -> std.hashmap.HashMap<K, V, fn H, fn E> effects [mem.alloc] {
match std.hashmap.new::<K, V, fn H, fn E>(capacity, heap) {
std.hashmap.NewResult::<K, V, fn H, fn E>::ok(map) => { return move map; }
std.hashmap.NewResult::<K, V, fn H, fn E>::err(error) => { trap; }
}
}
fn inserted<K, V>(result: std.hashmap.InsertResult<K,V>) -> void effects [] {
match move result { std.hashmap.InsertResult::<K,V>::inserted => {}, std.hashmap.InsertResult::<K,V>::full(value) => { trap; }, std.hashmap.InsertResult::<K,V>::replaced(value) => { trap; } }
}
fn extracted<T>(value: std.option.Option<T>) -> T effects [] {
match move value { std.option.Option::<T>::some(item) => { return move item; }, std.option.Option::<T>::none => { trap; } }
}
fn released<K, V, H: fn(ref<K>) -> u64 effects [], E: fn(ref<K>, ref<K>) -> bool effects []>(map: std.hashmap.HashMap<K, V, fn H, fn E>) -> void effects [] {
match std.hashmap.free::<K, V, fn H, fn E>(move map) { std.hashmap.FreeResult::<K, V, fn H, fn E>::ok => {}, std.hashmap.FreeResult::<K, V, fn H, fn E>::not_empty(value) => { trap; } }
}
struct Key { id: u64 }
fn hash(key: ref<Key>) -> u64 effects [] { return 3; }
fn equal(a: ref<Key>, b: ref<Key>) -> bool effects [] { return a.id == b.id; }
fn worker(q: ref<std.hashmap.HashMap<Key, file<write>, fn hash, fn equal>>) -> void effects [] {}
fn bad(q: ref<std.hashmap.HashMap<Key, file<write>, fn hash, fn equal>>) -> void effects [task.spawn, task.wait] { scope s { let t = task.spawn(s, worker, q); task.join(move t); } }
fn main() -> u64 effects [] { return 42; }
@@ -0,0 +1,33 @@
// expect: run
// result: 42
// phase: 6
// spec: docs/spec/16-standard-library.md §2.14
// grant: heap=mem.alloc:8
module test.hashmap
import std.hashmap;
import std.option;
fn opened<K, V, H: fn(ref<K>) -> u64 effects [], E: fn(ref<K>, ref<K>) -> bool effects []>(capacity: usize, heap: cap<mem.alloc>) -> std.hashmap.HashMap<K, V, fn H, fn E> effects [mem.alloc] {
match std.hashmap.new::<K, V, fn H, fn E>(capacity, heap) {
std.hashmap.NewResult::<K, V, fn H, fn E>::ok(map) => { return move map; }
std.hashmap.NewResult::<K, V, fn H, fn E>::err(error) => { trap; }
}
}
fn inserted<K, V>(result: std.hashmap.InsertResult<K,V>) -> void effects [] {
match move result { std.hashmap.InsertResult::<K,V>::inserted => {}, std.hashmap.InsertResult::<K,V>::full(value) => { trap; }, std.hashmap.InsertResult::<K,V>::replaced(value) => { trap; } }
}
fn extracted<T>(value: std.option.Option<T>) -> T effects [] {
match move value { std.option.Option::<T>::some(item) => { return move item; }, std.option.Option::<T>::none => { trap; } }
}
fn released<K, V, H: fn(ref<K>) -> u64 effects [], E: fn(ref<K>, ref<K>) -> bool effects []>(map: std.hashmap.HashMap<K, V, fn H, fn E>) -> void effects [] {
match std.hashmap.free::<K, V, fn H, fn E>(move map) { std.hashmap.FreeResult::<K, V, fn H, fn E>::ok => {}, std.hashmap.FreeResult::<K, V, fn H, fn E>::not_empty(value) => { trap; } }
}
struct Key { id: u64 }
fn hash(key: ref<Key>) -> u64 effects [] { return 3; }
fn equal(a: ref<Key>, b: ref<Key>) -> bool effects [] { return a.id == b.id; }
fn main(heap: cap<mem.alloc>) -> u64 effects [mem.alloc] {
match std.hashmap.new::<Key, u64, fn hash, fn equal>((0usize -% 1usize) / 2usize + 1usize, heap) { std.hashmap.NewResult::<Key, u64, fn hash, fn equal>::err(error) => {}, std.hashmap.NewResult::<Key, u64, fn hash, fn equal>::ok(map) => { trap; } }
match std.hashmap.new::<Key, u64, fn hash, fn equal>((0usize -% 1usize) / 24usize + 1usize, heap) { std.hashmap.NewResult::<Key, u64, fn hash, fn equal>::err(error) => {}, std.hashmap.NewResult::<Key, u64, fn hash, fn equal>::ok(map) => { trap; } }
let map = opened::<Key, u64, fn hash, fn equal>(0, heap);
{ mut q = map; match std.hashmap.reserve::<Key, u64, fn hash, fn equal>(q, (0usize -% 1usize) / 2usize + 1usize, heap) { std.hashmap.ReserveResult::err(error) => {}, std.hashmap.ReserveResult::ok => { trap; } } }
released::<Key, u64, fn hash, fn equal>(move map); let owner = own.new(42u64, heap) or trap; return own.take(move owner);
}
@@ -0,0 +1,45 @@
// expect: run
// result: 42
// phase: 6
// spec: docs/spec/16-standard-library.md §2.14
// grant: heap=mem.alloc:1024
module test.hashmap
import std.hashmap;
import std.option;
fn opened<K, V, H: fn(ref<K>) -> u64 effects [], E: fn(ref<K>, ref<K>) -> bool effects []>(capacity: usize, heap: cap<mem.alloc>) -> std.hashmap.HashMap<K, V, fn H, fn E> effects [mem.alloc] {
match std.hashmap.new::<K, V, fn H, fn E>(capacity, heap) {
std.hashmap.NewResult::<K, V, fn H, fn E>::ok(map) => { return move map; }
std.hashmap.NewResult::<K, V, fn H, fn E>::err(error) => { trap; }
}
}
fn inserted<K, V>(result: std.hashmap.InsertResult<K,V>) -> void effects [] {
match move result { std.hashmap.InsertResult::<K,V>::inserted => {}, std.hashmap.InsertResult::<K,V>::full(value) => { trap; }, std.hashmap.InsertResult::<K,V>::replaced(value) => { trap; } }
}
fn extracted<T>(value: std.option.Option<T>) -> T effects [] {
match move value { std.option.Option::<T>::some(item) => { return move item; }, std.option.Option::<T>::none => { trap; } }
}
fn released<K, V, H: fn(ref<K>) -> u64 effects [], E: fn(ref<K>, ref<K>) -> bool effects []>(map: std.hashmap.HashMap<K, V, fn H, fn E>) -> void effects [] {
match std.hashmap.free::<K, V, fn H, fn E>(move map) { std.hashmap.FreeResult::<K, V, fn H, fn E>::ok => {}, std.hashmap.FreeResult::<K, V, fn H, fn E>::not_empty(value) => { trap; } }
}
struct Key { id: u64, owner: own<u64> }
fn hash(key: ref<Key>) -> u64 effects [] { return 3; }
fn equal(a: ref<Key>, b: ref<Key>) -> bool effects [] { return a.id == b.id; }
fn consumed(entry: std.hashmap.Entry<Key,own<u64>>) -> u64 effects [] {
let (key, value) = struct.unpack(move entry); let (id, owner) = struct.unpack(move key);
assert(own.take(move owner) == id); return own.take(move value);
}
fn main(heap: cap<mem.alloc>) -> u64 effects [mem.alloc] {
let map = opened::<Key, own<u64>, fn hash, fn equal>(2, heap);
{ mut q = map;
let k1 = Key { id: 1, owner: own.new(1u64, heap) or trap }; let v1 = own.new(11u64, heap) or trap;
inserted::<Key,own<u64>>(std.hashmap.insert::<Key, own<u64>, fn hash, fn equal>(q, move k1, move v1));
let k2 = Key { id: 2, owner: own.new(2u64, heap) or trap }; let v2 = own.new(22u64, heap) or trap;
inserted::<Key,own<u64>>(std.hashmap.insert::<Key, own<u64>, fn hash, fn equal>(q, move k2, move v2));
let query = Key { id: 1, owner: own.new(1u64, heap) or trap };
assert(consumed(extracted::<std.hashmap.Entry<Key,own<u64>>>(std.hashmap.remove::<Key, own<u64>, fn hash, fn equal>(q, ref query))) == 11u64);
let (id, owner) = struct.unpack(move query); own.take(move owner);
match std.hashmap.reserve::<Key, own<u64>, fn hash, fn equal>(q, 3, heap) { std.hashmap.ReserveResult::ok => {}, std.hashmap.ReserveResult::err(error) => { trap; } }
assert(consumed(extracted::<std.hashmap.Entry<Key,own<u64>>>(std.hashmap.pop::<Key, own<u64>, fn hash, fn equal>(q))) == 22u64);
}
released::<Key, own<u64>, fn hash, fn equal>(move map); return 42;
}
@@ -0,0 +1,47 @@
// expect: run
// result: 42
// phase: 6
// spec: docs/spec/16-standard-library.md §2.14
// grant: heap=mem.alloc:98
module test.hashmap
import std.hashmap;
import std.option;
fn opened<K, V, H: fn(ref<K>) -> u64 effects [], E: fn(ref<K>, ref<K>) -> bool effects []>(capacity: usize, heap: cap<mem.alloc>) -> std.hashmap.HashMap<K, V, fn H, fn E> effects [mem.alloc] {
match std.hashmap.new::<K, V, fn H, fn E>(capacity, heap) {
std.hashmap.NewResult::<K, V, fn H, fn E>::ok(map) => { return move map; }
std.hashmap.NewResult::<K, V, fn H, fn E>::err(error) => { trap; }
}
}
fn inserted<K, V>(result: std.hashmap.InsertResult<K,V>) -> void effects [] {
match move result { std.hashmap.InsertResult::<K,V>::inserted => {}, std.hashmap.InsertResult::<K,V>::full(value) => { trap; }, std.hashmap.InsertResult::<K,V>::replaced(value) => { trap; } }
}
fn extracted<T>(value: std.option.Option<T>) -> T effects [] {
match move value { std.option.Option::<T>::some(item) => { return move item; }, std.option.Option::<T>::none => { trap; } }
}
fn released<K, V, H: fn(ref<K>) -> u64 effects [], E: fn(ref<K>, ref<K>) -> bool effects []>(map: std.hashmap.HashMap<K, V, fn H, fn E>) -> void effects [] {
match std.hashmap.free::<K, V, fn H, fn E>(move map) { std.hashmap.FreeResult::<K, V, fn H, fn E>::ok => {}, std.hashmap.FreeResult::<K, V, fn H, fn E>::not_empty(value) => { trap; } }
}
struct Key { id: u64, owner: own<u64> }
fn hash(key: ref<Key>) -> u64 effects [] { return 3; }
fn equal(a: ref<Key>, b: ref<Key>) -> bool effects [] { return a.id == b.id; }
fn consumed(entry: std.hashmap.Entry<Key,own<u64>>, expected_key: u64, expected_value: u64) -> void effects [] {
let (key,value) = struct.unpack(move entry); let (id,owner) = struct.unpack(move key);
assert(own.take(move owner) == expected_key); assert(own.take(move value) == expected_value);
}
fn main(heap: cap<mem.alloc>) -> u64 effects [mem.alloc] {
let map = opened::<Key, own<u64>, fn hash, fn equal>(1, heap);
{ mut q = map;
let key = Key { id: 7, owner: own.new(101u64, heap) or trap }; let value = own.new(11u64, heap) or trap;
inserted::<Key,own<u64>>(std.hashmap.insert::<Key, own<u64>, fn hash, fn equal>(q, move key, move value));
let replacement = Key { id: 7, owner: own.new(202u64, heap) or trap }; let replacement_value = own.new(42u64, heap) or trap;
match std.hashmap.insert::<Key, own<u64>, fn hash, fn equal>(q, move replacement, move replacement_value) {
std.hashmap.InsertResult::<Key,own<u64>>::replaced(entry) => { consumed(move entry, 101, 11); }, std.hashmap.InsertResult::<Key,own<u64>>::inserted => { trap; }, std.hashmap.InsertResult::<Key,own<u64>>::full(entry) => { trap; } }
let full_key = Key { id: 8, owner: own.new(303u64, heap) or trap }; let full_value = own.new(99u64, heap) or trap;
match std.hashmap.insert::<Key, own<u64>, fn hash, fn equal>(q, move full_key, move full_value) {
std.hashmap.InsertResult::<Key,own<u64>>::full(entry) => { consumed(move entry, 303, 99); }, std.hashmap.InsertResult::<Key,own<u64>>::inserted => { trap; }, std.hashmap.InsertResult::<Key,own<u64>>::replaced(entry) => { trap; } }
}
match std.hashmap.free::<Key, own<u64>, fn hash, fn equal>(move map) {
std.hashmap.FreeResult::<Key, own<u64>, fn hash, fn equal>::not_empty(returned) => { { mut q = returned; consumed(extracted::<std.hashmap.Entry<Key,own<u64>>>(std.hashmap.pop::<Key, own<u64>, fn hash, fn equal>(q)), 202, 42); } released::<Key, own<u64>, fn hash, fn equal>(move returned); },
std.hashmap.FreeResult::<Key, own<u64>, fn hash, fn equal>::ok => { trap; } }
return 42;
}
@@ -0,0 +1,27 @@
// expect: reject E7005
// phase: 6
// spec: docs/spec/16-standard-library.md §2.14
module test.hashmap
import std.hashmap;
import std.option;
fn opened<K, V, H: fn(ref<K>) -> u64 effects [], E: fn(ref<K>, ref<K>) -> bool effects []>(capacity: usize, heap: cap<mem.alloc>) -> std.hashmap.HashMap<K, V, fn H, fn E> effects [mem.alloc] {
match std.hashmap.new::<K, V, fn H, fn E>(capacity, heap) {
std.hashmap.NewResult::<K, V, fn H, fn E>::ok(map) => { return move map; }
std.hashmap.NewResult::<K, V, fn H, fn E>::err(error) => { trap; }
}
}
fn inserted<K, V>(result: std.hashmap.InsertResult<K,V>) -> void effects [] {
match move result { std.hashmap.InsertResult::<K,V>::inserted => {}, std.hashmap.InsertResult::<K,V>::full(value) => { trap; }, std.hashmap.InsertResult::<K,V>::replaced(value) => { trap; } }
}
fn extracted<T>(value: std.option.Option<T>) -> T effects [] {
match move value { std.option.Option::<T>::some(item) => { return move item; }, std.option.Option::<T>::none => { trap; } }
}
fn released<K, V, H: fn(ref<K>) -> u64 effects [], E: fn(ref<K>, ref<K>) -> bool effects []>(map: std.hashmap.HashMap<K, V, fn H, fn E>) -> void effects [] {
match std.hashmap.free::<K, V, fn H, fn E>(move map) { std.hashmap.FreeResult::<K, V, fn H, fn E>::ok => {}, std.hashmap.FreeResult::<K, V, fn H, fn E>::not_empty(value) => { trap; } }
}
struct Key { id: u64 }
fn hash(key: ref<Key>) -> u64 effects [] { return 3; }
fn equal(a: ref<Key>, b: ref<Key>) -> bool effects [] { return a.id == b.id; }
fn effectful(key: ref<Key>) -> u64 effects [mem.alloc] { return 3; }
fn bad(q: ref<std.hashmap.HashMap<Key,own<u64>,fn effectful,fn equal>>) -> void effects [] {}
fn main() -> u64 effects [] { return 42; }
@@ -0,0 +1,27 @@
// expect: reject E7005
// phase: 6
// spec: docs/spec/16-standard-library.md §2.14
module test.hashmap
import std.hashmap;
import std.option;
fn opened<K, V, H: fn(ref<K>) -> u64 effects [], E: fn(ref<K>, ref<K>) -> bool effects []>(capacity: usize, heap: cap<mem.alloc>) -> std.hashmap.HashMap<K, V, fn H, fn E> effects [mem.alloc] {
match std.hashmap.new::<K, V, fn H, fn E>(capacity, heap) {
std.hashmap.NewResult::<K, V, fn H, fn E>::ok(map) => { return move map; }
std.hashmap.NewResult::<K, V, fn H, fn E>::err(error) => { trap; }
}
}
fn inserted<K, V>(result: std.hashmap.InsertResult<K,V>) -> void effects [] {
match move result { std.hashmap.InsertResult::<K,V>::inserted => {}, std.hashmap.InsertResult::<K,V>::full(value) => { trap; }, std.hashmap.InsertResult::<K,V>::replaced(value) => { trap; } }
}
fn extracted<T>(value: std.option.Option<T>) -> T effects [] {
match move value { std.option.Option::<T>::some(item) => { return move item; }, std.option.Option::<T>::none => { trap; } }
}
fn released<K, V, H: fn(ref<K>) -> u64 effects [], E: fn(ref<K>, ref<K>) -> bool effects []>(map: std.hashmap.HashMap<K, V, fn H, fn E>) -> void effects [] {
match std.hashmap.free::<K, V, fn H, fn E>(move map) { std.hashmap.FreeResult::<K, V, fn H, fn E>::ok => {}, std.hashmap.FreeResult::<K, V, fn H, fn E>::not_empty(value) => { trap; } }
}
struct Key { id: u64 }
fn hash(key: ref<Key>) -> u64 effects [] { return 3; }
fn equal(a: ref<Key>, b: ref<Key>) -> bool effects [] { return a.id == b.id; }
fn other(key: ref<Key>) -> u64 effects [] { return 3; }
fn bad(map: ref<std.hashmap.HashMap<Key, u64, fn hash, fn equal>>) -> void effects [] { std.hashmap.len::<Key,u64,fn other,fn equal>(map); }
fn main() -> u64 effects [] { return 42; }
@@ -0,0 +1,28 @@
// expect: reject E3002
// phase: 6
// spec: docs/spec/16-standard-library.md §2.14
module test.hashmap
import std.hashmap;
import std.option;
fn opened<K, V, H: fn(ref<K>) -> u64 effects [], E: fn(ref<K>, ref<K>) -> bool effects []>(capacity: usize, heap: cap<mem.alloc>) -> std.hashmap.HashMap<K, V, fn H, fn E> effects [mem.alloc] {
match std.hashmap.new::<K, V, fn H, fn E>(capacity, heap) {
std.hashmap.NewResult::<K, V, fn H, fn E>::ok(map) => { return move map; }
std.hashmap.NewResult::<K, V, fn H, fn E>::err(error) => { trap; }
}
}
fn inserted<K, V>(result: std.hashmap.InsertResult<K,V>) -> void effects [] {
match move result { std.hashmap.InsertResult::<K,V>::inserted => {}, std.hashmap.InsertResult::<K,V>::full(value) => { trap; }, std.hashmap.InsertResult::<K,V>::replaced(value) => { trap; } }
}
fn extracted<T>(value: std.option.Option<T>) -> T effects [] {
match move value { std.option.Option::<T>::some(item) => { return move item; }, std.option.Option::<T>::none => { trap; } }
}
fn released<K, V, H: fn(ref<K>) -> u64 effects [], E: fn(ref<K>, ref<K>) -> bool effects []>(map: std.hashmap.HashMap<K, V, fn H, fn E>) -> void effects [] {
match std.hashmap.free::<K, V, fn H, fn E>(move map) { std.hashmap.FreeResult::<K, V, fn H, fn E>::ok => {}, std.hashmap.FreeResult::<K, V, fn H, fn E>::not_empty(value) => { trap; } }
}
struct Key { id: u64 }
fn hash(key: ref<Key>) -> u64 effects [] { return 3; }
fn equal(a: ref<Key>, b: ref<Key>) -> bool effects [] { return a.id == b.id; }
fn bad(q: mut<std.hashmap.HashMap<Key, own<u64>, fn hash, fn equal>>) -> void effects [] {
match std.hashmap.pop::<Key, own<u64>, fn hash, fn equal>(q) { std.option.Option::<std.hashmap.Entry<Key,own<u64>>>::some(item) => { return; }, std.option.Option::<std.hashmap.Entry<Key,own<u64>>>::none => {} }
}
fn main() -> u64 effects [] { return 42; }
@@ -0,0 +1,28 @@
// expect: reject E3002
// phase: 6
// spec: docs/spec/16-standard-library.md §2.14
module test.hashmap
import std.hashmap;
import std.option;
fn opened<K, V, H: fn(ref<K>) -> u64 effects [], E: fn(ref<K>, ref<K>) -> bool effects []>(capacity: usize, heap: cap<mem.alloc>) -> std.hashmap.HashMap<K, V, fn H, fn E> effects [mem.alloc] {
match std.hashmap.new::<K, V, fn H, fn E>(capacity, heap) {
std.hashmap.NewResult::<K, V, fn H, fn E>::ok(map) => { return move map; }
std.hashmap.NewResult::<K, V, fn H, fn E>::err(error) => { trap; }
}
}
fn inserted<K, V>(result: std.hashmap.InsertResult<K,V>) -> void effects [] {
match move result { std.hashmap.InsertResult::<K,V>::inserted => {}, std.hashmap.InsertResult::<K,V>::full(value) => { trap; }, std.hashmap.InsertResult::<K,V>::replaced(value) => { trap; } }
}
fn extracted<T>(value: std.option.Option<T>) -> T effects [] {
match move value { std.option.Option::<T>::some(item) => { return move item; }, std.option.Option::<T>::none => { trap; } }
}
fn released<K, V, H: fn(ref<K>) -> u64 effects [], E: fn(ref<K>, ref<K>) -> bool effects []>(map: std.hashmap.HashMap<K, V, fn H, fn E>) -> void effects [] {
match std.hashmap.free::<K, V, fn H, fn E>(move map) { std.hashmap.FreeResult::<K, V, fn H, fn E>::ok => {}, std.hashmap.FreeResult::<K, V, fn H, fn E>::not_empty(value) => { trap; } }
}
struct Key { id: u64 }
fn hash(key: ref<Key>) -> u64 effects [] { return 3; }
fn equal(a: ref<Key>, b: ref<Key>) -> bool effects [] { return a.id == b.id; }
fn bad(q: mut<std.hashmap.HashMap<Key, own<u64>, fn hash, fn equal>>, key: ref<Key>) -> void effects [] {
match std.hashmap.remove::<Key, own<u64>, fn hash, fn equal>(q,key) { std.option.Option::<std.hashmap.Entry<Key,own<u64>>>::some(item) => { return; }, std.option.Option::<std.hashmap.Entry<Key,own<u64>>>::none => {} }
}
fn main() -> u64 effects [] { return 42; }
@@ -0,0 +1,28 @@
// expect: reject E3002
// phase: 6
// spec: docs/spec/16-standard-library.md §2.14
module test.hashmap
import std.hashmap;
import std.option;
fn opened<K, V, H: fn(ref<K>) -> u64 effects [], E: fn(ref<K>, ref<K>) -> bool effects []>(capacity: usize, heap: cap<mem.alloc>) -> std.hashmap.HashMap<K, V, fn H, fn E> effects [mem.alloc] {
match std.hashmap.new::<K, V, fn H, fn E>(capacity, heap) {
std.hashmap.NewResult::<K, V, fn H, fn E>::ok(map) => { return move map; }
std.hashmap.NewResult::<K, V, fn H, fn E>::err(error) => { trap; }
}
}
fn inserted<K, V>(result: std.hashmap.InsertResult<K,V>) -> void effects [] {
match move result { std.hashmap.InsertResult::<K,V>::inserted => {}, std.hashmap.InsertResult::<K,V>::full(value) => { trap; }, std.hashmap.InsertResult::<K,V>::replaced(value) => { trap; } }
}
fn extracted<T>(value: std.option.Option<T>) -> T effects [] {
match move value { std.option.Option::<T>::some(item) => { return move item; }, std.option.Option::<T>::none => { trap; } }
}
fn released<K, V, H: fn(ref<K>) -> u64 effects [], E: fn(ref<K>, ref<K>) -> bool effects []>(map: std.hashmap.HashMap<K, V, fn H, fn E>) -> void effects [] {
match std.hashmap.free::<K, V, fn H, fn E>(move map) { std.hashmap.FreeResult::<K, V, fn H, fn E>::ok => {}, std.hashmap.FreeResult::<K, V, fn H, fn E>::not_empty(value) => { trap; } }
}
struct Key { id: u64 }
fn hash(key: ref<Key>) -> u64 effects [] { return 3; }
fn equal(a: ref<Key>, b: ref<Key>) -> bool effects [] { return a.id == b.id; }
fn bad(q: mut<std.hashmap.HashMap<Key, own<u64>, fn hash, fn equal>>, value: own<u64>) -> void effects [] {
match std.hashmap.insert::<Key, own<u64>, fn hash, fn equal>(q,Key { id: 1 },move value) { std.hashmap.InsertResult::<Key,own<u64>>::replaced(item) => { return; }, std.hashmap.InsertResult::<Key,own<u64>>::inserted => {}, std.hashmap.InsertResult::<Key,own<u64>>::full(item) => { trap; } }
}
fn main() -> u64 effects [] { return 42; }
@@ -0,0 +1,35 @@
// expect: run
// result: 42
// phase: 6
// spec: docs/spec/16-standard-library.md §2.14
// grant: first=mem.alloc:58
// grant: second=mem.alloc:116
module test.hashmap
import std.hashmap;
import std.option;
fn opened<K, V, H: fn(ref<K>) -> u64 effects [], E: fn(ref<K>, ref<K>) -> bool effects []>(capacity: usize, heap: cap<mem.alloc>) -> std.hashmap.HashMap<K, V, fn H, fn E> effects [mem.alloc] {
match std.hashmap.new::<K, V, fn H, fn E>(capacity, heap) {
std.hashmap.NewResult::<K, V, fn H, fn E>::ok(map) => { return move map; }
std.hashmap.NewResult::<K, V, fn H, fn E>::err(error) => { trap; }
}
}
fn inserted<K, V>(result: std.hashmap.InsertResult<K,V>) -> void effects [] {
match move result { std.hashmap.InsertResult::<K,V>::inserted => {}, std.hashmap.InsertResult::<K,V>::full(value) => { trap; }, std.hashmap.InsertResult::<K,V>::replaced(value) => { trap; } }
}
fn extracted<T>(value: std.option.Option<T>) -> T effects [] {
match move value { std.option.Option::<T>::some(item) => { return move item; }, std.option.Option::<T>::none => { trap; } }
}
fn released<K, V, H: fn(ref<K>) -> u64 effects [], E: fn(ref<K>, ref<K>) -> bool effects []>(map: std.hashmap.HashMap<K, V, fn H, fn E>) -> void effects [] {
match std.hashmap.free::<K, V, fn H, fn E>(move map) { std.hashmap.FreeResult::<K, V, fn H, fn E>::ok => {}, std.hashmap.FreeResult::<K, V, fn H, fn E>::not_empty(value) => { trap; } }
}
struct Key { id: u64 }
fn hash(key: ref<Key>) -> u64 effects [] { return 3; }
fn equal(a: ref<Key>, b: ref<Key>) -> bool effects [] { return a.id == b.id; }
fn main(first: cap<mem.alloc>, second: cap<mem.alloc>) -> u64 effects [mem.alloc] {
let map = opened::<Key, u64, fn hash, fn equal>(1, first);
{ mut q = map; inserted::<Key,u64>(std.hashmap.insert::<Key, u64, fn hash, fn equal>(q, Key { id: 1 }, 42));
match std.hashmap.reserve::<Key, u64, fn hash, fn equal>(q, 2, second) { std.hashmap.ReserveResult::ok => {}, std.hashmap.ReserveResult::err(error) => { trap; } } }
let old = opened::<Key, u64, fn hash, fn equal>(1, first); released::<Key, u64, fn hash, fn equal>(move old);
{ mut q = map; let entry = extracted::<std.hashmap.Entry<Key,u64>>(std.hashmap.pop::<Key, u64, fn hash, fn equal>(q)); assert(entry.value == 42u64); }
released::<Key, u64, fn hash, fn equal>(move map); let next = opened::<Key, u64, fn hash, fn equal>(2, second); released::<Key, u64, fn hash, fn equal>(move next); return 42;
}
@@ -0,0 +1,48 @@
// expect: run
// result: 42
// phase: 6
// spec: docs/spec/16-standard-library.md §2.14
// grant: heap=mem.alloc:251
module test.hashmap
import std.hashmap;
import std.option;
fn opened<K, V, H: fn(ref<K>) -> u64 effects [], E: fn(ref<K>, ref<K>) -> bool effects []>(capacity: usize, heap: cap<mem.alloc>) -> std.hashmap.HashMap<K, V, fn H, fn E> effects [mem.alloc] {
match std.hashmap.new::<K, V, fn H, fn E>(capacity, heap) {
std.hashmap.NewResult::<K, V, fn H, fn E>::ok(map) => { return move map; }
std.hashmap.NewResult::<K, V, fn H, fn E>::err(error) => { trap; }
}
}
fn inserted<K, V>(result: std.hashmap.InsertResult<K,V>) -> void effects [] {
match move result { std.hashmap.InsertResult::<K,V>::inserted => {}, std.hashmap.InsertResult::<K,V>::full(value) => { trap; }, std.hashmap.InsertResult::<K,V>::replaced(value) => { trap; } }
}
fn extracted<T>(value: std.option.Option<T>) -> T effects [] {
match move value { std.option.Option::<T>::some(item) => { return move item; }, std.option.Option::<T>::none => { trap; } }
}
fn released<K, V, H: fn(ref<K>) -> u64 effects [], E: fn(ref<K>, ref<K>) -> bool effects []>(map: std.hashmap.HashMap<K, V, fn H, fn E>) -> void effects [] {
match std.hashmap.free::<K, V, fn H, fn E>(move map) { std.hashmap.FreeResult::<K, V, fn H, fn E>::ok => {}, std.hashmap.FreeResult::<K, V, fn H, fn E>::not_empty(value) => { trap; } }
}
struct Key { id: u64 }
fn hash(key: ref<Key>) -> u64 effects [] { return 3; }
fn equal(a: ref<Key>, b: ref<Key>) -> bool effects [] { return a.id == b.id; }
fn check(heap: cap<mem.alloc>) -> void effects [mem.alloc] {
let map = opened::<Key, u64, fn hash, fn equal>(1, heap);
{ mut q = map; inserted::<Key,u64>(std.hashmap.insert::<Key, u64, fn hash, fn equal>(q, Key { id: 1 }, 42)); }
let empty = std.hashmap.Bucket { hash: 0, index: 0, state: std.hashmap.BucketState::empty };
var before: [std.hashmap.Bucket; 2] = [empty; 2];
{ ref q = map; ref index = q.buckets; ref buckets = buffer.view(index); before[0] = buckets[0]; before[1] = buckets[1]; }
{ mut q = map;
match std.hashmap.reserve::<Key, u64, fn hash, fn equal>(q, 2, heap) { std.hashmap.ReserveResult::err(error) => { match error { alloc_error::budget_exceeded => {}, alloc_error::out_of_memory => { trap; } } }, std.hashmap.ReserveResult::ok => { trap; } }
assert(std.hashmap.capacity::<Key, u64, fn hash, fn equal>(ref q) == 1usize);
}
{ ref q = map; ref index = q.buckets; ref buckets = buffer.view(index);
for i in 0usize..2usize { assert(buckets[i].hash == before[i].hash); assert(buckets[i].index == before[i].index);
match before[i].state { std.hashmap.BucketState::empty => { match buckets[i].state { std.hashmap.BucketState::empty => {}, std.hashmap.BucketState::deleted => { trap; }, std.hashmap.BucketState::occupied => { trap; } } }, std.hashmap.BucketState::deleted => { trap; }, std.hashmap.BucketState::occupied => { match buckets[i].state { std.hashmap.BucketState::occupied => {}, std.hashmap.BucketState::empty => { trap; }, std.hashmap.BucketState::deleted => { trap; } } } }
} }
{ mut q = map; let entry = extracted::<std.hashmap.Entry<Key,u64>>(std.hashmap.pop::<Key, u64, fn hash, fn equal>(q)); assert(entry.value == 42u64); }
released::<Key, u64, fn hash, fn equal>(move map);
let reused = own.new([0u8; 125], heap) or trap; own.free(move reused);
}
fn main(heap: cap<mem.alloc>) -> u64 effects [mem.alloc] {
let early = cap.narrow.budget(heap, 125usize) or trap; check(early);
let late = cap.narrow.budget(heap, 126usize) or trap; check(late); return 42;
}
@@ -0,0 +1,34 @@
// expect: run
// result: 42
// phase: 6
// spec: docs/spec/16-standard-library.md §2.14
// grant: heap=mem.alloc:174
module test.hashmap
import std.hashmap;
import std.option;
fn opened<K, V, H: fn(ref<K>) -> u64 effects [], E: fn(ref<K>, ref<K>) -> bool effects []>(capacity: usize, heap: cap<mem.alloc>) -> std.hashmap.HashMap<K, V, fn H, fn E> effects [mem.alloc] {
match std.hashmap.new::<K, V, fn H, fn E>(capacity, heap) {
std.hashmap.NewResult::<K, V, fn H, fn E>::ok(map) => { return move map; }
std.hashmap.NewResult::<K, V, fn H, fn E>::err(error) => { trap; }
}
}
fn inserted<K, V>(result: std.hashmap.InsertResult<K,V>) -> void effects [] {
match move result { std.hashmap.InsertResult::<K,V>::inserted => {}, std.hashmap.InsertResult::<K,V>::full(value) => { trap; }, std.hashmap.InsertResult::<K,V>::replaced(value) => { trap; } }
}
fn extracted<T>(value: std.option.Option<T>) -> T effects [] {
match move value { std.option.Option::<T>::some(item) => { return move item; }, std.option.Option::<T>::none => { trap; } }
}
fn released<K, V, H: fn(ref<K>) -> u64 effects [], E: fn(ref<K>, ref<K>) -> bool effects []>(map: std.hashmap.HashMap<K, V, fn H, fn E>) -> void effects [] {
match std.hashmap.free::<K, V, fn H, fn E>(move map) { std.hashmap.FreeResult::<K, V, fn H, fn E>::ok => {}, std.hashmap.FreeResult::<K, V, fn H, fn E>::not_empty(value) => { trap; } }
}
struct Key { id: u64 }
fn hash(key: ref<Key>) -> u64 effects [] { return 3; }
fn equal(a: ref<Key>, b: ref<Key>) -> bool effects [] { return a.id == b.id; }
fn main(heap: cap<mem.alloc>) -> u64 effects [mem.alloc] {
let map = opened::<Key, u64, fn hash, fn equal>(1, heap);
{ mut q = map; inserted::<Key,u64>(std.hashmap.insert::<Key, u64, fn hash, fn equal>(q, Key { id: 1 }, 42));
match std.hashmap.reserve::<Key, u64, fn hash, fn equal>(q, 2, heap) { std.hashmap.ReserveResult::ok => {}, std.hashmap.ReserveResult::err(error) => { trap; } }
let owner = own.new([0u8; 58], heap) or trap; own.free(move owner);
let entry = extracted::<std.hashmap.Entry<Key,u64>>(std.hashmap.pop::<Key, u64, fn hash, fn equal>(q)); assert(entry.value == 42u64);
} released::<Key, u64, fn hash, fn equal>(move map); return 42;
}
@@ -0,0 +1,33 @@
// expect: run
// result: 42
// phase: 6
// spec: docs/spec/16-standard-library.md §2.14
// grant: heap=mem.alloc:40
module test.hashmap
import std.hashmap;
import std.option;
fn opened<K, V, H: fn(ref<K>) -> u64 effects [], E: fn(ref<K>, ref<K>) -> bool effects []>(capacity: usize, heap: cap<mem.alloc>) -> std.hashmap.HashMap<K, V, fn H, fn E> effects [mem.alloc] {
match std.hashmap.new::<K, V, fn H, fn E>(capacity, heap) {
std.hashmap.NewResult::<K, V, fn H, fn E>::ok(map) => { return move map; }
std.hashmap.NewResult::<K, V, fn H, fn E>::err(error) => { trap; }
}
}
fn inserted<K, V>(result: std.hashmap.InsertResult<K,V>) -> void effects [] {
match move result { std.hashmap.InsertResult::<K,V>::inserted => {}, std.hashmap.InsertResult::<K,V>::full(value) => { trap; }, std.hashmap.InsertResult::<K,V>::replaced(value) => { trap; } }
}
fn extracted<T>(value: std.option.Option<T>) -> T effects [] {
match move value { std.option.Option::<T>::some(item) => { return move item; }, std.option.Option::<T>::none => { trap; } }
}
fn released<K, V, H: fn(ref<K>) -> u64 effects [], E: fn(ref<K>, ref<K>) -> bool effects []>(map: std.hashmap.HashMap<K, V, fn H, fn E>) -> void effects [] {
match std.hashmap.free::<K, V, fn H, fn E>(move map) { std.hashmap.FreeResult::<K, V, fn H, fn E>::ok => {}, std.hashmap.FreeResult::<K, V, fn H, fn E>::not_empty(value) => { trap; } }
}
struct Key { id: u64 }
fn hash(key: ref<Key>) -> u64 effects [] { return 3; }
fn equal(a: ref<Key>, b: ref<Key>) -> bool effects [] { return a.id == b.id; }
fn main(heap: cap<mem.alloc>) -> u64 effects [mem.alloc] {
match std.hashmap.new::<Key, u64, fn hash, fn equal>(1, heap) {
std.hashmap.NewResult::<Key, u64, fn hash, fn equal>::err(error) => { match error { alloc_error::budget_exceeded => {}, alloc_error::out_of_memory => { trap; } } },
std.hashmap.NewResult::<Key, u64, fn hash, fn equal>::ok(map) => { trap; }
}
let owner = own.new([0u8; 40], heap) or trap; own.free(move owner); return 42;
}
@@ -0,0 +1,39 @@
// expect: run
// result: 42
// phase: 6
// spec: docs/spec/16-standard-library.md §2.14
// grant: heap=mem.alloc:256
// schedules: 12
module test.hashmap
import std.hashmap;
import std.option;
fn opened<K, V, H: fn(ref<K>) -> u64 effects [], E: fn(ref<K>, ref<K>) -> bool effects []>(capacity: usize, heap: cap<mem.alloc>) -> std.hashmap.HashMap<K, V, fn H, fn E> effects [mem.alloc] {
match std.hashmap.new::<K, V, fn H, fn E>(capacity, heap) {
std.hashmap.NewResult::<K, V, fn H, fn E>::ok(map) => { return move map; }
std.hashmap.NewResult::<K, V, fn H, fn E>::err(error) => { trap; }
}
}
fn inserted<K, V>(result: std.hashmap.InsertResult<K,V>) -> void effects [] {
match move result { std.hashmap.InsertResult::<K,V>::inserted => {}, std.hashmap.InsertResult::<K,V>::full(value) => { trap; }, std.hashmap.InsertResult::<K,V>::replaced(value) => { trap; } }
}
fn extracted<T>(value: std.option.Option<T>) -> T effects [] {
match move value { std.option.Option::<T>::some(item) => { return move item; }, std.option.Option::<T>::none => { trap; } }
}
fn released<K, V, H: fn(ref<K>) -> u64 effects [], E: fn(ref<K>, ref<K>) -> bool effects []>(map: std.hashmap.HashMap<K, V, fn H, fn E>) -> void effects [] {
match std.hashmap.free::<K, V, fn H, fn E>(move map) { std.hashmap.FreeResult::<K, V, fn H, fn E>::ok => {}, std.hashmap.FreeResult::<K, V, fn H, fn E>::not_empty(value) => { trap; } }
}
struct Key { id: u64 }
fn hash(key: ref<Key>) -> u64 effects [] { return 3; }
fn equal(a: ref<Key>, b: ref<Key>) -> bool effects [] { return a.id == b.id; }
struct Job { number: u64 }
fn worker(map: std.hashmap.HashMap<Key, sender<Job>, fn hash, fn equal>) -> void effects [task.wait] {
{ mut q = map; let entry = extracted::<std.hashmap.Entry<Key,sender<Job>>>(std.hashmap.pop::<Key, sender<Job>, fn hash, fn equal>(q));
let (key,tx) = struct.unpack(move entry); channel.send(tx, Job { number: 42 }) or trap; channel.close_sender(move tx); }
released::<Key, sender<Job>, fn hash, fn equal>(move map);
}
fn main(heap: cap<mem.alloc>) -> u64 effects [mem.alloc, task.spawn, task.wait] {
match channel.make<Job>(1, heap) { ok(tx,rx) => {
let map = opened::<Key, sender<Job>, fn hash, fn equal>(1, heap); { mut q = map; inserted::<Key,sender<Job>>(std.hashmap.insert::<Key, sender<Job>, fn hash, fn equal>(q, Key { id: 7 }, move tx)); }
scope s { let t = task.spawn(s, worker, move map); let job = channel.recv(rx) or trap; task.join(move t); channel.close_receiver(move rx) or trap; assert(job.number == 42u64); }
}, err(error) => { trap; } } return 42;
}
@@ -0,0 +1,33 @@
// expect: run
// result: 42
// phase: 6
// spec: docs/spec/16-standard-library.md §2.14
// grant: heap=mem.alloc:58
// schedules: 12
module test.hashmap
import std.hashmap;
import std.option;
fn opened<K, V, H: fn(ref<K>) -> u64 effects [], E: fn(ref<K>, ref<K>) -> bool effects []>(capacity: usize, heap: cap<mem.alloc>) -> std.hashmap.HashMap<K, V, fn H, fn E> effects [mem.alloc] {
match std.hashmap.new::<K, V, fn H, fn E>(capacity, heap) {
std.hashmap.NewResult::<K, V, fn H, fn E>::ok(map) => { return move map; }
std.hashmap.NewResult::<K, V, fn H, fn E>::err(error) => { trap; }
}
}
fn inserted<K, V>(result: std.hashmap.InsertResult<K,V>) -> void effects [] {
match move result { std.hashmap.InsertResult::<K,V>::inserted => {}, std.hashmap.InsertResult::<K,V>::full(value) => { trap; }, std.hashmap.InsertResult::<K,V>::replaced(value) => { trap; } }
}
fn extracted<T>(value: std.option.Option<T>) -> T effects [] {
match move value { std.option.Option::<T>::some(item) => { return move item; }, std.option.Option::<T>::none => { trap; } }
}
fn released<K, V, H: fn(ref<K>) -> u64 effects [], E: fn(ref<K>, ref<K>) -> bool effects []>(map: std.hashmap.HashMap<K, V, fn H, fn E>) -> void effects [] {
match std.hashmap.free::<K, V, fn H, fn E>(move map) { std.hashmap.FreeResult::<K, V, fn H, fn E>::ok => {}, std.hashmap.FreeResult::<K, V, fn H, fn E>::not_empty(value) => { trap; } }
}
struct Key { id: u64 }
fn hash(key: ref<Key>) -> u64 effects [] { return 3; }
fn equal(a: ref<Key>, b: ref<Key>) -> bool effects [] { return a.id == b.id; }
fn worker(q: ref<std.hashmap.HashMap<Key, u64, fn hash, fn equal>>) -> u64 effects [] { let key = Key { id: 7 }; return extracted::<u64>(std.hashmap.get::<Key, u64, fn hash, fn equal>(q, ref key)); }
fn main(heap: cap<mem.alloc>) -> u64 effects [mem.alloc, task.spawn, task.wait] {
let map = opened::<Key, u64, fn hash, fn equal>(1, heap); { mut q = map; inserted::<Key,u64>(std.hashmap.insert::<Key, u64, fn hash, fn equal>(q, Key { id: 7 }, 42)); }
{ ref q = map; scope s { let a = task.spawn(s, worker, q); let b = task.spawn(s, worker, q); assert(task.join(move a) == 42u64); assert(task.join(move b) == 42u64); } }
{ mut q = map; let entry = extracted::<std.hashmap.Entry<Key,u64>>(std.hashmap.pop::<Key, u64, fn hash, fn equal>(q)); } released::<Key, u64, fn hash, fn equal>(move map); return 42;
}
@@ -0,0 +1,38 @@
// expect: run
// result: 42
// phase: 6
// spec: docs/spec/16-standard-library.md §2.14
// grant: heap=mem.alloc:116
module test.hashmap
import std.hashmap;
import std.option;
fn opened<K, V, H: fn(ref<K>) -> u64 effects [], E: fn(ref<K>, ref<K>) -> bool effects []>(capacity: usize, heap: cap<mem.alloc>) -> std.hashmap.HashMap<K, V, fn H, fn E> effects [mem.alloc] {
match std.hashmap.new::<K, V, fn H, fn E>(capacity, heap) {
std.hashmap.NewResult::<K, V, fn H, fn E>::ok(map) => { return move map; }
std.hashmap.NewResult::<K, V, fn H, fn E>::err(error) => { trap; }
}
}
fn inserted<K, V>(result: std.hashmap.InsertResult<K,V>) -> void effects [] {
match move result { std.hashmap.InsertResult::<K,V>::inserted => {}, std.hashmap.InsertResult::<K,V>::full(value) => { trap; }, std.hashmap.InsertResult::<K,V>::replaced(value) => { trap; } }
}
fn extracted<T>(value: std.option.Option<T>) -> T effects [] {
match move value { std.option.Option::<T>::some(item) => { return move item; }, std.option.Option::<T>::none => { trap; } }
}
fn released<K, V, H: fn(ref<K>) -> u64 effects [], E: fn(ref<K>, ref<K>) -> bool effects []>(map: std.hashmap.HashMap<K, V, fn H, fn E>) -> void effects [] {
match std.hashmap.free::<K, V, fn H, fn E>(move map) { std.hashmap.FreeResult::<K, V, fn H, fn E>::ok => {}, std.hashmap.FreeResult::<K, V, fn H, fn E>::not_empty(value) => { trap; } }
}
struct Key { id: u64 }
fn hash(key: ref<Key>) -> u64 effects [] { return 3; }
fn equal(a: ref<Key>, b: ref<Key>) -> bool effects [] { return a.id == b.id; }
fn main(heap: cap<mem.alloc>) -> u64 effects [mem.alloc] {
let map = opened::<Key, u64, fn hash, fn equal>(2, heap);
{ mut q = map;
for cycle in 0usize..12usize {
inserted::<Key,u64>(std.hashmap.insert::<Key, u64, fn hash, fn equal>(q, Key { id: 1 }, 1));
inserted::<Key,u64>(std.hashmap.insert::<Key, u64, fn hash, fn equal>(q, Key { id: 2 }, 2));
let key = Key { id: 1 }; let removed = extracted::<std.hashmap.Entry<Key,u64>>(std.hashmap.remove::<Key, u64, fn hash, fn equal>(q, ref key));
assert(removed.value == 1u64);
match std.hashmap.insert::<Key, u64, fn hash, fn equal>(q, Key { id: 2 }, 42) { std.hashmap.InsertResult::<Key,u64>::replaced(old) => { assert(old.value == 2u64); }, std.hashmap.InsertResult::<Key,u64>::inserted => { trap; }, std.hashmap.InsertResult::<Key,u64>::full(old) => { trap; } }
let item = extracted::<std.hashmap.Entry<Key,u64>>(std.hashmap.pop::<Key, u64, fn hash, fn equal>(q)); assert(item.key.id == 2u64); assert(item.value == 42u64);
} } released::<Key, u64, fn hash, fn equal>(move map); return 42;
}
+36
View File
@@ -0,0 +1,36 @@
// expect: run
// result: 42
// phase: 6
// spec: docs/spec/16-standard-library.md §2.14
// grant: heap=mem.alloc:0
module test.hashmap
import std.hashmap;
import std.option;
fn opened<K, V, H: fn(ref<K>) -> u64 effects [], E: fn(ref<K>, ref<K>) -> bool effects []>(capacity: usize, heap: cap<mem.alloc>) -> std.hashmap.HashMap<K, V, fn H, fn E> effects [mem.alloc] {
match std.hashmap.new::<K, V, fn H, fn E>(capacity, heap) {
std.hashmap.NewResult::<K, V, fn H, fn E>::ok(map) => { return move map; }
std.hashmap.NewResult::<K, V, fn H, fn E>::err(error) => { trap; }
}
}
fn inserted<K, V>(result: std.hashmap.InsertResult<K,V>) -> void effects [] {
match move result { std.hashmap.InsertResult::<K,V>::inserted => {}, std.hashmap.InsertResult::<K,V>::full(value) => { trap; }, std.hashmap.InsertResult::<K,V>::replaced(value) => { trap; } }
}
fn extracted<T>(value: std.option.Option<T>) -> T effects [] {
match move value { std.option.Option::<T>::some(item) => { return move item; }, std.option.Option::<T>::none => { trap; } }
}
fn released<K, V, H: fn(ref<K>) -> u64 effects [], E: fn(ref<K>, ref<K>) -> bool effects []>(map: std.hashmap.HashMap<K, V, fn H, fn E>) -> void effects [] {
match std.hashmap.free::<K, V, fn H, fn E>(move map) { std.hashmap.FreeResult::<K, V, fn H, fn E>::ok => {}, std.hashmap.FreeResult::<K, V, fn H, fn E>::not_empty(value) => { trap; } }
}
struct Key { id: u64 }
fn hash(key: ref<Key>) -> u64 effects [] { return 3; }
fn equal(a: ref<Key>, b: ref<Key>) -> bool effects [] { return a.id == b.id; }
fn main(heap: cap<mem.alloc>) -> u64 effects [mem.alloc] {
let map = opened::<Key, u64, fn hash, fn equal>(0, heap);
{ mut q = map; let key = Key { id: 1 };
match std.hashmap.insert::<Key, u64, fn hash, fn equal>(q, key, 42) { std.hashmap.InsertResult::<Key,u64>::full(entry) => { assert(entry.value == 42u64); }, std.hashmap.InsertResult::<Key,u64>::inserted => { trap; }, std.hashmap.InsertResult::<Key,u64>::replaced(old) => { trap; } }
assert(not std.hashmap.contains::<Key, u64, fn hash, fn equal>(ref q, ref key));
match std.hashmap.remove::<Key, u64, fn hash, fn equal>(q, ref key) { std.option.Option::<std.hashmap.Entry<Key,u64>>::none => {}, std.option.Option::<std.hashmap.Entry<Key,u64>>::some(entry) => { trap; } }
match std.hashmap.pop::<Key, u64, fn hash, fn equal>(q) { std.option.Option::<std.hashmap.Entry<Key,u64>>::none => {}, std.option.Option::<std.hashmap.Entry<Key,u64>>::some(entry) => { trap; } }
match std.hashmap.reserve::<Key, u64, fn hash, fn equal>(q, 0, heap) { std.hashmap.ReserveResult::ok => {}, std.hashmap.ReserveResult::err(error) => { trap; } }
} released::<Key, u64, fn hash, fn equal>(move map); return 42;
}
+101
View File
@@ -0,0 +1,101 @@
#!/usr/bin/env python3
"""General owning maps through explicit policies, source/AIR, packages and profiles."""
import json
from pathlib import Path
import subprocess
import tempfile
REPO = Path(__file__).resolve().parents[2]
AJI = REPO / "zig-out/bin/aji"
CASES = REPO / "tests/conformance/source/hashmap"
checks = 0
def cli(*args, code=0):
global checks
run = subprocess.run([str(AJI), *map(str, args)], capture_output=True, text=True)
assert run.returncode == code, (args, run.returncode, run.stdout, run.stderr)
checks += 1
return run.stdout
def returned(path, *grants):
args = [item for grant in grants for item in ("--grant", grant)]
record = json.loads(cli("run", "--fuel", "4000000", *args, path))
assert record["status"] == "returned" and record["value"] == 42, record
return record
example = REPO / "examples/std/hashmap.aji"
returned(example, "heap=mem.alloc:66")
cli("check", example)
report = json.loads(cli("report", example))
assert report["unsafe"]["operations"] == 0 and report["unsafe"]["trusted_functions"] == [], report
canonical = cli("lower", example)
assert canonical == cli("lower", example)
assert "trusted" not in canonical and "unsafe" not in canonical
for name, budget in [("copy", 1024), ("owner", 1024), ("owner_returned", 98), ("byte_keys", 256),
("key_copy_lookup", 82), ("reserve_failure", 251), ("reserve_peak", 174),
("no_empty", 116), ("zero", 0), ("rollback", 40), ("model", 1120), ("model_owner", 1120)]:
returned(CASES / (name + ".aji"), f"heap=mem.alloc:{budget}")
for name, expected in [("full_leak", "E3002"), ("key_missing_move", "E7003"),
("get_owner", "E7005"), ("policy_mismatch", "E7005"),
("policy_effect", "E7005"), ("free_leak", "E3002")]:
commands = ("check", "report", "run", "explore") if expected == "E3002" else ("check", "lower", "report", "run", "explore")
for command in commands:
records = [json.loads(line) for line in cli(command, CASES / (name + ".aji"), code=1).splitlines()]
assert records and {error["code"] for error in records} == {expected}, records
with tempfile.TemporaryDirectory(prefix="aji-hashmap-") as directory:
root = Path(directory)
air = root / "lowered.air"
air.write_text(canonical)
cli("check", air)
assert returned(air, "heap=mem.alloc:66") == returned(example, "heap=mem.alloc:66")
# Hosted results use the same pinned library and explicit heap accounting.
result = root / "hosted.json"
stdout = cli("run", "--profile", "hosted", "--fuel", "4000000", "--grant", "heap=mem.alloc:66", "--result-file", result, example)
assert stdout == "" and json.loads(result.read_text())["value"] == 42
# Package policy selection is explicit and preserves nominal identities.
policy = root / "policy.aji"
policy.write_text('''module app.policy
struct Key { id: u64 }
fn hash(key: ref<Key>) -> u64 effects [] { return 3; }
fn equal(a: ref<Key>, b: ref<Key>) -> bool effects [] { return a.id == b.id; }
''')
entry, manifest = root / "main.aji", root / "aji.toml"
manifest.write_text('[package]\nname = "hashmap"\nversion = "1"\nentry = "main.aji"\n[modules]\napp.policy = "policy.aji"\n[capabilities]\nheap = "mem.alloc:66"\n')
program = example.read_text().replace("module demo.hashmap", "module app.entry")
start, end = program.index("struct Key"), program.index("fn main(")
program = program[:start].replace("import std.option;", "import std.option;\nimport app.policy;") + program[end:]
program = program.replace("<Key,", "<app.policy.Key,").replace("fn hash", "fn app.policy.hash").replace("fn equal", "fn app.policy.equal").replace("Key {", "app.policy.Key {")
entry.write_text(program)
record = json.loads(cli("run", "--fuel", "4000000", "--manifest", manifest))
assert record["value"] == 42, record
package_air = cli("lower", "--manifest", manifest)
cli("report", "--manifest", manifest)
imports = "import std.hashmap;\nimport std.option;\nimport app.policy;"
entry.write_text(program.replace(imports, "import app.policy;\nimport std.option;\nimport std.hashmap;"))
assert cli("lower", "--manifest", manifest) == package_air
entry.write_text(program)
policy.write_text(policy.read_text().replace("return 3;", "assert(false); return 3;"))
record = json.loads(cli("run", "--fuel", "4000000", "--manifest", manifest, code=4))
assert Path(record["source_location"]["file"]).name == "policy.aji", record
# Imported standard code diagnostics/traps retain repository paths.
invalid = (CASES / "copy.aji").read_text()
invalid = invalid.replace("fn main(", "fn entry_original(")
invalid += '''
fn main(heap: cap<mem.alloc>) -> u64 effects [mem.alloc] {
let map = opened::<Key,u64,fn hash,fn equal>(1,heap);
{ mut q = map; inserted::<Key,u64>(std.hashmap.insert::<Key,u64,fn hash,fn equal>(q, Key { id: 1 },42));
mut storage = q.buckets; mut buckets = buffer.view(storage); buckets[1].index = 7usize; }
{ ref q = map; let key = Key { id: 1 }; std.hashmap.contains::<Key,u64,fn hash,fn equal>(q,ref key); }
{ mut q = map; let entry = extracted::<std.hashmap.Entry<Key,u64>>(std.hashmap.pop::<Key,u64,fn hash,fn equal>(q)); }
released::<Key,u64,fn hash,fn equal>(move map); return 42;
}
'''
entry.write_text(invalid)
record = json.loads(cli("run", "--fuel", "4000000", "--grant", "heap=mem.alloc:1024", entry, code=4))
assert record["code"] == "T0008" and record["source_location"]["file"] == "std/hashmap.aji", record
print(f"general hash-map CLI integration passed ({checks} checks)")
+106
View File
@@ -0,0 +1,106 @@
#!/usr/bin/env python3
"""Check public general-map traces against Python dicts and the specified pop order.
The oracle models associations, bounded insertion, returned owners and dense
order; it does not model hashing, bucket placement, tombstones or rehashing.
--write regenerates the public .aji fixtures, which conformance executes.
"""
from pathlib import Path
import random
import sys
ROOT = Path(__file__).resolve().parents[1] / "tests/conformance/source/hashmap"
KEYS = """struct Key { id: u64, salt: u64 }
fn hash(key: ref<Key>) -> u64 effects [] { return key.id % 4u64; }
fn equal(a: ref<Key>, b: ref<Key>) -> bool effects [] { return a.id == b.id; }
"""
def trace(owning):
value_type = "own<u64>" if owning else "u64"
args = f"Key, {value_type}, fn hash, fn equal"
entry_type = f"std.hashmap.Entry<Key,{value_type}>"
state, dense, capacity, lines = {}, [], 2, []
rng = random.Random(301029 + int(owning))
domain = [0, 1, 2, 3, 4, 5, 6, 7, 2**64 - 1]
def check_entry(key, salt, value):
if owning:
return ("let (key,value) = struct.unpack(move entry); let number = own.take(move value); "
f"assert(key.id == {key}u64); assert(key.salt == {salt}u64); assert(number == {value}u64);")
return f"assert(entry.key.id == {key}u64); assert(entry.key.salt == {salt}u64); assert(entry.value == {value}u64);"
for step in range(96):
lines.append("{")
action = rng.choice(["insert"] * 4 + ["remove"] * 2 + ["pop", "reserve", "get"])
key = rng.choice(domain)
if action == "insert":
value, salt = rng.randrange(1, 500), step + 1
if key in state:
tag, previous = "replaced", state[key]
expected = check_entry(key, *previous)
state[key] = salt, value
elif len(state) == capacity:
tag, expected = "full", check_entry(key, salt, value)
else:
tag, expected = "inserted", ""
state[key] = salt, value
dense.append(key)
operand = f"{value}u64"
if owning:
lines.append(f"let item = own.new({value}u64, heap) or trap;")
operand = "move item"
arms = []
for variant in ("inserted", "replaced", "full"):
payload = "" if variant == "inserted" else "(entry)"
arms.append(f"std.hashmap.InsertResult::<Key,{value_type}>::{variant}{payload} => {{ {expected if variant == tag else 'trap;'} }}")
lines.append(f"match std.hashmap.insert::<{args}>(q, Key {{ id: {key}, salt: {salt} }}, {operand}) {{ " + ", ".join(arms) + " }")
elif action in ("remove", "pop"):
if action == "remove":
lines.append(f"let query = Key {{ id: {key}, salt: 0 }};")
call, present = f"std.hashmap.remove::<{args}>(q, ref query)", key in state
if present:
index, last = dense.index(key), dense.pop()
if index < len(dense):
dense[index] = last
else:
call, present = f"std.hashmap.pop::<{args}>(q)", bool(dense)
if present:
key = dense.pop()
expected = check_entry(key, *state.pop(key)) if present else "trap;"
lines.append(f"match {call} {{ std.option.Option::<{entry_type}>::some(entry) => {{ {expected} }}, std.option.Option::<{entry_type}>::none => {{ {'trap;' if present else ''} }} }}")
elif action == "reserve":
new = rng.choice([0, 2, 3, 4, 6, 8])
capacity = max(capacity, new)
lines.append(f"match std.hashmap.reserve::<{args}>(q, {new}usize, heap) {{ std.hashmap.ReserveResult::ok => {{}}, std.hashmap.ReserveResult::err(error) => {{ trap; }} }}")
lines.append(f"assert(std.hashmap.len::<{args}>(ref q) == {len(state)}usize); assert(std.hashmap.capacity::<{args}>(ref q) == {capacity}usize);")
for candidate in domain:
lines.append(f"{{ let query = Key {{ id: {candidate}, salt: 0 }}; assert(std.hashmap.contains::<{args}>(ref q, ref query) == {str(candidate in state).lower()});")
if not owning:
some = f"assert(value == {state[candidate][1]}u64);" if candidate in state else "trap;"
none = "trap;" if candidate in state else ""
lines.append(f"match std.hashmap.get::<{args}>(ref q, ref query) {{ std.option.Option::<u64>::some(value) => {{ {some} }}, std.option.Option::<u64>::none => {{ {none} }} }}")
lines.append("}")
for index, candidate in enumerate(dense):
salt, value = state[candidate]
suffix = "" if owning else f" assert(view[{index}usize].value == {value}u64);"
lines.append(f"{{ ref storage = q.entries; ref view = buffer.view(storage); assert(view[{index}usize].key.id == {candidate}u64); assert(view[{index}usize].key.salt == {salt}u64);{suffix} }}")
lines.append("}")
for key in reversed(dense):
lines.append(f"{{ let entry = extracted::<{entry_type}>(std.hashmap.pop::<{args}>(q)); " + check_entry(key, *state[key]) + " }")
return (f"fn main(heap: cap<mem.alloc>) -> u64 effects [mem.alloc] {{\n let map = opened::<{args}>(2, heap);\n {{ mut q = map;\n" +
"\n".join(lines) + f"\n }} released::<{args}>(move map); return 42;\n}}\n")
for owning in (False, True):
name = "model_owner" if owning else "model"
path = ROOT / (name + ".aji")
if "--write" in sys.argv:
base = (ROOT / "copy.aji").read_text()
preamble = base[base.index("module test.hashmap"):base.index("struct Key")]
path.write_text("// expect: run\n// result: 42\n// phase: 6\n// spec: docs/spec/16-standard-library.md §2.14\n// grant: heap=mem.alloc:1120\n// fuel: 4000000\n" + preamble + KEYS + trace(owning))
text = path.read_text()
assert KEYS in text, name + " has the wrong public key policy"
assert text[text.index("fn main("):] == trace(owning), name + " differs from the independent oracle"
print("general hash-map oracle passed (2 seeds, 192 operations; Copy/owning values, all keys and dense order)")