#!/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) -> u64 effects [] { return key.id % 4u64; } fn equal(a: ref, b: ref) -> bool effects [] { return a.id == b.id; } """ def trace(owning): value_type = "own" if owning else "u64" args = f"Key, {value_type}, fn hash, fn equal" entry_type = f"std.hashmap.Entry" 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::::{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::::some(value) => {{ {some} }}, std.option.Option::::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) -> 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)")