Add std.heap with an exact explicit pure ordering operation, bounded push, Copy-only peek, moving pop and empty-only free. Sift Copy indices while complete owners remain in dense initialized storage; repair holes through complete exchange. Reserve preserves layout on returned failure and accounts for both old/new buffers and separately owned payloads. Integrate normative contracts, RFC, references, bundle measurements, independent heapq/permutation oracles and CLI/package/profile checks. Validation: 1007 conformance cases; 34 heap GC fixtures and scheduled stress; unit/Quick Reference, formatting, hosted smoke, 70 CLI checks, 109 source coverage constructs and unchanged AIR reference bundle.
97 lines
5.4 KiB
Python
97 lines
5.4 KiB
Python
#!/usr/bin/env python3
|
|
"""Public heapq/sorted oracles; no dense entries/index/sift model.
|
|
|
|
Use --write to regenerate deterministic fixtures, executed with fuel.
|
|
"""
|
|
import heapq
|
|
from itertools import permutations
|
|
from pathlib import Path
|
|
import random
|
|
import sys
|
|
|
|
ROOT = Path(__file__).resolve().parents[1] / "tests/conformance/source/heap"
|
|
COMMON = (ROOT / "copy.aji").read_text().split("fn before(")[0]
|
|
COMMON = COMMON[COMMON.index("module test.heap"):]
|
|
|
|
|
|
def trace(owning):
|
|
rng = random.Random(32001 + int(owning))
|
|
queue, capacity, lines = [], 2, []
|
|
policy = "a.priority > b.priority" if owning else "a.priority < b.priority"
|
|
field = "owner: own<u64>" if owning else "marker: u64"
|
|
keys = f"struct Item {{ priority: u64, id: u64, {field} }}\n"
|
|
keys += f"fn before(a: ref<Item>,b: ref<Item>) -> bool effects [] {{ return {policy} or (a.priority == b.priority and a.id < b.id); }}\n"
|
|
keys += "fn checked(item: Item,priority: u64,id: u64) -> void effects [] {\n"
|
|
keys += ("let (actual_priority,actual_id,owner) = struct.unpack(move item); assert(actual_priority == priority); assert(actual_id == id); assert(own.take(move owner) == id);\n" if owning else
|
|
"assert(item.priority == priority); assert(item.id == id); assert(item.marker == id);\n")
|
|
keys += "}\n"
|
|
|
|
def pop():
|
|
if queue:
|
|
priority, identifier = heapq.heappop(queue)
|
|
if owning:
|
|
priority = -priority
|
|
return f"checked(extracted::<Item>(std.heap.pop::<Item,fn before>(q)),{priority}u64,{identifier}u64);"
|
|
return "match std.heap.pop::<Item,fn before>(q) { std.option.Option::<Item>::none => {}, std.option.Option::<Item>::some(item) => { trap; } }"
|
|
|
|
for step in range(80):
|
|
lines.append("{")
|
|
operation = rng.choice(["push"] * 4 + ["pop"] * 2 + ["reserve"])
|
|
if operation == "push":
|
|
priority, identifier = rng.choice([0, 1, 2, 3, 7, 2**64 - 1]), step + 1
|
|
value = f"Item {{ priority: {priority},id: {identifier},marker: {identifier} }}"
|
|
if owning:
|
|
lines.append(f"let incoming = Item {{ priority: {priority},id: {identifier},owner: own.new({identifier}u64,heap) or trap }};")
|
|
value = "move incoming"
|
|
full = len(queue) == capacity
|
|
if not full:
|
|
heapq.heappush(queue, (-priority if owning else priority, identifier))
|
|
success = "trap;" if full else ""
|
|
failure = f"checked({'move item' if owning else 'item'},{priority}u64,{identifier}u64);" if full else "trap;"
|
|
lines.append(f"match std.heap.push::<Item,fn before>(q,{value}) {{ std.heap.PushResult::<Item>::ok => {{ {success} }}, std.heap.PushResult::<Item>::full(item) => {{ {failure} }} }}")
|
|
elif operation == "pop":
|
|
lines.append(pop())
|
|
else:
|
|
request = rng.choice([0, 2, 4, 8])
|
|
capacity = max(capacity, request)
|
|
lines.append(f"match std.heap.reserve::<Item,fn before>(q,{request}usize,heap) {{ std.heap.ReserveResult::ok => {{}}, std.heap.ReserveResult::err(error) => {{ trap; }} }}")
|
|
lines.append(f"assert(std.heap.len::<Item,fn before>(ref q) == {len(queue)}usize); assert(std.heap.capacity::<Item,fn before>(ref q) == {capacity}usize);")
|
|
if not owning:
|
|
if queue:
|
|
priority, identifier = queue[0]
|
|
lines.append(f"checked(extracted::<Item>(std.heap.peek::<Item,fn before>(ref q)),{priority}u64,{identifier}u64);")
|
|
else:
|
|
lines.append("match std.heap.peek::<Item,fn before>(ref q) { std.option.Option::<Item>::none => {}, std.option.Option::<Item>::some(item) => { trap; } }")
|
|
lines.append("}")
|
|
while queue:
|
|
lines.append(pop())
|
|
return keys + "fn main(heap: cap<mem.alloc>) -> u64 effects [mem.alloc] {\n let value = opened::<Item,fn before>(2,heap);\n { mut q = value;\n" + "\n".join(lines) + "\n } released::<Item,fn before>(move value); return 42;\n}\n"
|
|
|
|
|
|
def exhaustive():
|
|
text = """fn before(a: ref<u64>,b: ref<u64>) -> bool effects [] { return *a < *b; }
|
|
fn check(values: slice<u64>,heap: cap<mem.alloc>) -> void effects [mem.alloc] {
|
|
let value = opened::<u64,fn before>(5,heap);
|
|
{ mut q = value;
|
|
for i in 0usize..5usize { pushed::<u64>(std.heap.push::<u64,fn before>(q,values[i])); }
|
|
for i in 0usize..5usize { assert(extracted::<u64>(std.heap.peek::<u64,fn before>(ref q)) == i as! u64); assert(extracted::<u64>(std.heap.pop::<u64,fn before>(q)) == i as! u64); }
|
|
} released::<u64,fn before>(move value);
|
|
}
|
|
fn main(heap: cap<mem.alloc>) -> u64 effects [mem.alloc] {
|
|
"""
|
|
for values in permutations(range(5)):
|
|
assert sorted(values) == list(range(5))
|
|
text += "{ let values: [u64;5] = [" + ",".join(str(value) + "u64" for value in values) + "]; check(ref values,heap); }\n"
|
|
return text + "return 42;\n}\n"
|
|
|
|
|
|
for name, body, budget in (("model", trace(False), 2048), ("model_owner", trace(True), 2048),
|
|
("permutations", exhaustive(), 120)):
|
|
path = ROOT / (name + ".aji")
|
|
expected = "// expect: run\n// result: 42\n// phase: 6\n// spec: docs/spec/16-standard-library.md §2.16\n" + f"// grant: heap=mem.alloc:{budget}\n// fuel: 2000000\n" + COMMON + body
|
|
if "--write" in sys.argv:
|
|
path.write_text(expected)
|
|
assert path.read_text() == expected, name + " differs from the independent heap oracle"
|
|
|
|
print("heap oracle passed (2 seeds, 160 operations, min/max Copy/owners, all 120 permutations of five elements)")
|