test_top_step_gate_matches_formal.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. #!/usr/bin/env python3
  2. """Structure-equivalence: formal STEP gate must match real top pin gate."""
  3. from __future__ import annotations
  4. import re
  5. import unittest
  6. from pathlib import Path
  7. ROOT = Path(__file__).resolve().parents[2]
  8. TOP = ROOT / "src/top/prod2u_p4_normal_v3_top.v"
  9. FORMAL = ROOT / "tests/formal/runtime_limit_hard_stop_formal.v"
  10. def _normalize_gate_expr(expr: str) -> str:
  11. text = re.sub(r"\s+", "", expr)
  12. text = text.replace("engine_step[0]", "engine_step")
  13. text = text.replace("engine_step[1]", "engine_step")
  14. text = text.replace("engine_step[2]", "engine_step")
  15. text = text.replace("selected_limit[0]", "selected_limit")
  16. text = text.replace("selected_limit[1]", "selected_limit")
  17. text = text.replace("selected_limit[2]", "selected_limit")
  18. return text
  19. def _extract_top_gates(text: str) -> dict[str, str]:
  20. pattern = re.compile(
  21. r"assign\s+([xyz])_step\s*=\s*([^;]+);",
  22. re.MULTILINE,
  23. )
  24. return {m.group(1): _normalize_gate_expr(m.group(2)) for m in pattern.finditer(text)}
  25. def _extract_formal_gates(text: str) -> dict[str, str]:
  26. pattern = re.compile(
  27. r"assign\s+gated_step\[(\d)\]\s*=\s*([^;]+);",
  28. re.MULTILINE,
  29. )
  30. axis = {"0": "x", "1": "y", "2": "z"}
  31. return {
  32. axis[m.group(1)]: _normalize_gate_expr(m.group(2))
  33. for m in pattern.finditer(text)
  34. }
  35. class TopStepGateMatchesFormalTests(unittest.TestCase):
  36. def test_formal_gate_matches_top_structure(self) -> None:
  37. top = TOP.read_text(encoding="utf-8")
  38. formal = FORMAL.read_text(encoding="utf-8")
  39. top_gates = _extract_top_gates(top)
  40. formal_gates = _extract_formal_gates(formal)
  41. self.assertEqual(set(top_gates), {"x", "y", "z"})
  42. self.assertEqual(set(formal_gates), {"x", "y", "z"})
  43. for axis in ("x", "y", "z"):
  44. self.assertEqual(
  45. top_gates[axis],
  46. formal_gates[axis],
  47. f"axis {axis}: top={top_gates[axis]!r} formal={formal_gates[axis]!r}",
  48. )
  49. # Canonical shape: engine_step & ~selected_limit
  50. for axis, expr in top_gates.items():
  51. self.assertIn("engine_step&~selected_limit", expr, axis)
  52. if __name__ == "__main__":
  53. unittest.main()