Datasets:
Download experiments/t2/scripts/package_examples.py from PV-SJTU/PV-Bench: direct link, hf CLI and curl.
- Browser
- Download file 12.9 kB
-
https://huggingface.co/datasets/PV-SJTU/PV-Bench/resolve/main/experiments/t2/scripts/package_examples.py
- Command line
-
hf download hf://datasets/PV-SJTU/PV-Bench/experiments/t2/scripts/package_examples.py
-
curl -L -o package_examples.py https://huggingface.co/datasets/PV-SJTU/PV-Bench/resolve/main/experiments/t2/scripts/package_examples.py
12.9 kB
| #!/usr/bin/env python3 | |
| """Maintainer-only extraction, no model or verification processes. | |
| Source root is an argument; ranges and hashes belong to the versioned selection. | |
| The public package contains reading excerpts, not independently compiled demos. | |
| """ | |
| import argparse | |
| import hashlib | |
| import json | |
| import re | |
| from pathlib import Path | |
| ROOT = Path(__file__).resolve().parents[1] / "examples" | |
| BUNDLE_VERSION = "t2-demo-examples-v3" | |
| # Units written for the bundle (not excerpts of a source-root demo); their files live in examples/<id>/ | |
| # and are hashed as they are. Provenance: scripts/demo_<name>/README.md. | |
| AUTHORED = { | |
| "D08": {"route": "direct", "after": "D07", "files": ["annotated.c", "GOAL.md", "README.md", "SUPPORT.md"], | |
| "provenance": {"source": "examples/D08 (authored for the bundle; scripts/demo_arr_sum_for/README.md)", | |
| "checked": "symexec + coqc in image pvbench-env:spike " | |
| "sha256:78a6d640cf60d001041c2d84d6f7a855125ad39558fd8869ee0e4d6f78726d52, 2026-11-15"}}, | |
| } | |
| EXPLANATIONS = { | |
| "D01": "Open field ownership and preserve entry values when swapping a pair.", | |
| "D02": "Relate the accumulator to a processed prefix; retain bounds and array ownership.", | |
| "D03": "Grow an initialized output prefix, with pointwise correspondence and an uninitialized suffix.", | |
| "D04": "Relate exchanged prefixes and unchanged suffixes of two disjoint arrays.", | |
| "D05": "Keep an upper bound and an attained witness; a bound alone is insufficient.", | |
| "D06": "Name an existential returned by a helper with Given and use that witness later.", | |
| "D07": "Represent a FIFO queue by two lists and reconcile resource states after a branch.", | |
| "D08": "Annotate a `for` that declares its counter and has an unbraced body; the code itself stays untouched.", | |
| "R01": "Carry safeExec for the remaining split and connect each abstract step to concrete list resources.", | |
| "R02": "Carry the same continuation through three merge loops and shrinking array segments.", | |
| "R03": "Connect the public prefix-table property to a low-level refinement spec and instantiate a bind helper call.", | |
| } | |
| def sha(data: bytes) -> str: | |
| return hashlib.sha256(data).hexdigest() | |
| def build(source_root: Path, destination: Path = ROOT) -> None: | |
| selection = json.loads((ROOT / "selection.json").read_text()) | |
| provenance = [] | |
| files = {} | |
| def put(rel: str, text: str): | |
| p = destination / rel | |
| p.parent.mkdir(parents=True, exist_ok=True) | |
| p.write_text(text) | |
| files[rel] = sha(p.read_bytes()) | |
| def excerpt(path: str, spans: list[tuple[int, int]]) -> str: | |
| data = (source_root / path).read_bytes() | |
| lines = data.decode().splitlines(keepends=True) | |
| provenance.append({"source": path, "sha256": sha(data), "line_ranges": spans}) | |
| return "\n".join("".join(lines[a-1:b]) for a, b in spans) | |
| index = ["T2 teaching examples — v3\n\n", | |
| "Start with D02 for a direct loop (D08 for the same loop with its counter declared in the `for` header), " | |
| "R01 for a refinement loop, or R03 for named-specification connections.\n\n", | |
| "These are annotated source and definition excerpts for reading. Ten are extracted from existing QCP demos " | |
| "and have not been rebuilt as standalone programs; D08 was written for this bundle and checked in the task " | |
| "image. Dependencies are limited to the selected operations; " | |
| "support excerpts explain their vocabulary. Use your workspace IMPORTS.md for the answer. " | |
| "Generated goal excerpts come from upstream artifacts (for D08, from the task image), not this run.\n\n", | |
| "The examples illustrate useful annotations, not certified minimal solutions. " | |
| "Read only the units relevant to your program.\n\n", | |
| "The extracted demo loops declare their counters before the loop (`int i; ... for (i = 0; ...)`) because " | |
| "their source programs do. Your program may write `for (int i = 0; ...)` instead: keep that form and put " | |
| "the `Inv` immediately before the `for`; the counter is in scope for it (D08). Never change executable " | |
| "code to match a demo.\n\n"] | |
| for unit in selection["examples"]: | |
| uid = unit["id"] | |
| source = source_root / unit["source"] | |
| if sha(source.read_bytes()) != unit["source_sha256"]: | |
| raise ValueError(f"source changed since overlap screening: {source}") | |
| if uid in {"D01", "D06", "D07", "R01", "R02", "R03"}: | |
| spans = [(1, unit["functions"][-1]["end_line"])] | |
| else: | |
| function = unit["functions"][0] | |
| # array_cases.c has a shared list header and sum declaration. Extract | |
| # only the selected function; supply its actual dependencies below. | |
| spans = [(function["definition_line"], function["end_line"])] | |
| code = excerpt(unit["source"], spans) | |
| if uid == "D02": | |
| code = ("/*@ Import Coq Require Import AUXLib.ListLib */\n" | |
| "/*@ Extern Coq (sum : list Z -> Z) */\n\n" + code) | |
| code = re.sub(r"/\*@ Import Lean.*?\*/", "", code, flags=re.S) | |
| # Remove only declarations for excluded operations. Preserve all selected | |
| # bodies, contracts and auxiliary named specifications byte-for-byte. | |
| excluded = {"R02": ["gmergesortrec", "gmergesortrec_loc0", "gmergesortrec_loc1", "mergesortrec_loc2"], | |
| "R03": ["match_loop", "no_occurance", "first_occur", "option_int_repr", "match_loop_from", "match_loop_from_after"]} | |
| for name in excluded.get(uid, []): | |
| code = re.sub(r"^\s*\(" + name + r":.*\)\s*$", "", code, flags=re.M) | |
| put(f"{uid}/annotated.c", code.strip() + "\n") | |
| fn = unit["functions"][-1]["name"] | |
| goal_path = unit["existing_manual_proof_source"].replace("_proof_manual.v", "_goal.v") | |
| goal_source = (source_root / goal_path).read_text() | |
| pattern = (r"^Definition constr_derive_high_level_spec_by_low_level_spec" if uid == "R03" | |
| else r"^Definition " + re.escape(fn) + r"_[^\n]*entail[^\n]*") | |
| start = re.search(pattern, goal_source, re.M) | |
| if not start: | |
| start = re.search(r"^Definition " + re.escape(fn) + "_", goal_source, re.M) | |
| if not start: | |
| raise ValueError(f"no selected goal in {goal_path}") | |
| end = re.search(r"\n(?:Definition |\(\*-----|Module )", goal_source[start.end():]) | |
| end_index = start.end() + end.start() if end else len(goal_source) | |
| goal = goal_source[start.start():end_index].strip() | |
| provenance.append({"source": goal_path, "sha256": sha((source_root / goal_path).read_bytes()), | |
| "extracted_definition": goal.splitlines()[0]}) | |
| put(f"{uid}/GOAL.md", "Representative upstream obligation (excerpt, imports omitted)\n\n```coq\n" + goal + "\n```\n\n" | |
| "Read its premises and conclusion alongside the nearby annotation. This is a proposition to prove, not a proof.\n") | |
| extra = "" | |
| if uid == "D07": | |
| extra = ("\nAllocation, free, and reversal are fixed external library contracts here. " | |
| "Their implementations are intentionally omitted. A helper body in your task must satisfy its contract.\n") | |
| if uid in {"R01", "R02"}: | |
| extra = ("\nThis unit illustrates implementation refinement under its supplied safeExec contract. " | |
| "For a different pure public contract, also establish the model-to-public-specification connection. See R03.\n") | |
| if uid == "R03": | |
| extra = ("\nThis is prefix-table construction only: the substring matching stage is excluded. " | |
| "Follow high_level_spec <= low_level_spec and bind_spec <= low_level_spec. " | |
| "Their derivation goals are proof obligations, not assumed facts. This uses the error-monad safeexecE_def.h interface.\n") | |
| put(f"{uid}/README.md", f"{uid}: {EXPLANATIONS[uid]}\n\nRoute: {unit['route']}.\n\n" | |
| "Read annotated.c, SUPPORT.md, then GOAL.md. The public contract is included above the selected C body.\n" + extra) | |
| support = [] | |
| def add(path, spans): | |
| support.append(f"From `{path}` (selected lines):\n\n```coq\n" + excerpt(path, spans).strip() + "\n```\n") | |
| if uid == "D01": | |
| add("Rocq/examples/QCP_demos_tutorial/swap_simple1_lib.v", [(1, 100)]) | |
| elif uid in {"D02", "D03", "D04", "D05"}: | |
| support.append("Array predicates, Znth, sublist, app and Zlength come from the fixed backend. " | |
| "full owns the whole initialized array; seg owns an indexed segment; undef owns uninitialized storage. " | |
| "A logical `list Z` models array contents; it does not require a C linked-list structure or `sll_def.h`.\n") | |
| if uid == "D02": | |
| support.append("The inline `Import Coq` loads `AUXLib.ListLib`, where `sum` is defined. " | |
| "`Extern Coq` makes its type available to the annotation parser. " | |
| "This is the only additional mathematical declaration needed by this excerpt.\n") | |
| add("Rocq/auxlibs/ListLib.v", [(821, 822)]) | |
| elif uid == "D06": | |
| support.append("The scalar helper's public contract binds an existential; Given attaches a logical name to the witness. No new predicate library is needed.\n") | |
| elif uid == "D07": | |
| add("Rocq/examples/QCP_demos_LLM/functional_queue_lib.v", [(1, 28)]) | |
| support.append("The fixed struct queue has fields `struct list *l1` and `struct list *l2`. " | |
| "The fixed list has fields `int data` and `struct list *next`. `sll(p,l)` owns that list and its contents.\n") | |
| elif uid in {"R01", "R02"}: | |
| add("Rocq/MonadLib/Examples/mergesort.v", [(1, 24), (50, 74)] if uid == "R01" else [(1, 47)]) | |
| support.append("Ordinary StateRelMonad / safeexec_def.h. `maketuple x y := (x,y)`; " | |
| "`applyf f x := f x`. In R01, reversepair swaps a pair of abstract lists; it does not implement list reversal. " | |
| "Only split or merge definitions are shown; sorting is omitted.\n") | |
| else: | |
| add("Rocq/MonadLib/Examples/kmp.v", [(1, 70), (100, 114), (124, 139)]) | |
| add("Rocq/examples/QCP_demos_LLM/kmp_rel_lib.v", [(29, 29), (37, 42)]) | |
| support.append("StateRelMonadErr / safeexecE_def.h. The prefix-table property describes each maximal proper prefix/suffix. " | |
| "The continuation supplied to inner describes the remaining construction loop. No matching algorithm is included.\n") | |
| put(f"{uid}/SUPPORT.md", "Selected vocabulary and abstract definitions\n\nThese excerpts are for reading; they are not new standalone library modules.\n\n" + "\n".join(support)) | |
| index.append(f"- [{uid}]({uid}/README.md) ({unit['route']}): {EXPLANATIONS[uid]}\n") | |
| for aid, authored in AUTHORED.items(): | |
| if authored["after"] == uid: | |
| for name in authored["files"]: | |
| files[f"{aid}/{name}"] = sha((destination / aid / name).read_bytes()) | |
| provenance.append({"unit": aid, **authored["provenance"]}) | |
| index.append(f"- [{aid}]({aid}/README.md) ({authored['route']}): {EXPLANATIONS[aid]}\n") | |
| put("INDEX.md", "".join(index)) | |
| (destination / "bundle.json").write_text(json.dumps({ | |
| "version": BUNDLE_VERSION, "selection": selection["selection"], | |
| "units": [uid for u in selection["examples"] for uid in | |
| (u["id"], *[aid for aid, a in AUTHORED.items() if a["after"] == u["id"]])], | |
| "files": files, "provenance": provenance, | |
| "transformations": ["Selected function ranges and necessary leading declarations only", | |
| "Lean imports removed", "Unused sorting/matching Extern declarations removed", | |
| "Array excerpts omit the shared sll_def.h preamble; only D02 and D08 declare sum and import AUXLib.ListLib directly", | |
| "D08 is authored for the bundle and checked in the task image, not extracted from a demo (scripts/demo_arr_sum_for/README.md)", | |
| "Definitions and one generated obligation per unit excerpted; no proof bodies exposed"], | |
| "validation": "Reading excerpts only; no standalone symbolic execution or compilation performed" | |
| }, indent=2) + "\n") | |
| if __name__ == "__main__": | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("source_root", type=Path) | |
| parser.add_argument("--output", type=Path, default=ROOT) | |
| args = parser.parse_args() | |
| build(args.source_root, args.output) | |