"""Real RTL Icarus matrix for compile-time motor polarity / endpoint masks. Authority path (feature acceptance): temp project.json → public generate_project / CLI → temp generated params → compile real production RTL + real top + TB ``_render_params`` is not used here. """ from __future__ import annotations import copy import itertools import json import os import subprocess import tempfile import unittest from pathlib import Path from tools.generate_project import generate_project, load_project from tools.prod2u_p4_harness import PRODUCTION_RTL_SOURCES, ROOT, resolve_tool POLARITY_TB = "prod2u_p4_alt_config_polarity_tb" STARTUP_TB = "prod2u_p4_alt_config_startup_tb" PROJECT_PATH = ROOT / "projects" / "prod2u-door-temp" / "project.json" def _write_alt_project( directory: Path, *, limit_active_high: list[bool], dir_close_level: list[int], close_limit_is_ls: list[bool], ) -> Path: """Deep-copy canonical project.json and mutate only the three public arrays.""" project = json.loads(PROJECT_PATH.read_text(encoding="utf-8")) project["limits"]["limit_active_high"] = list(limit_active_high) project["motors"]["dir_close_level"] = list(dir_close_level) project["limits"]["close_limit_is_ls"] = list(close_limit_is_ls) # Leave legacy limits.active_level untouched (non-authoritative). path = directory / "project.json" path.write_text(json.dumps(project, indent=2) + "\n", encoding="utf-8") return path class AltConfigRtlMatrixTests(unittest.TestCase): @classmethod def setUpClass(cls) -> None: cls.iverilog = resolve_tool("iverilog") cls.vvp = resolve_tool("vvp") if not cls.iverilog or not cls.vvp: raise unittest.SkipTest("iverilog/vvp unavailable") # Confirm canonical load still works (defaults). cls.base_project = load_project(PROJECT_PATH) def _run_public_case( self, name: str, *, tb_name: str, limit_active_high: list[bool], dir_close_level: list[int], close_limit_is_ls: list[bool], timeout_s: int = 180, ) -> None: with tempfile.TemporaryDirectory(prefix=f"alt-rtl-{name}-") as tmp: tmp_path = Path(tmp) pj = _write_alt_project( tmp_path, limit_active_high=limit_active_high, dir_close_level=dir_close_level, close_limit_is_ls=close_limit_is_ls, ) gen_out = tmp_path / "generated-out" # Public API path (not _render_params). generate_project(pj, gen_out) # Include layout: generated-out/generated/params.vh must win via # -I where include_root/src/generated/... exists. include_root = tmp_path / "include" gen_dir = include_root / "src" / "generated" gen_dir.mkdir(parents=True) params_src = gen_out / "generated" / "prod2u_door_temp_params.vh" self.assertTrue(params_src.is_file(), params_src) (gen_dir / "prod2u_door_temp_params.vh").write_text( params_src.read_text(encoding="ascii"), encoding="ascii", ) work = tmp_path / "work" work.mkdir() vvp_out = work / f"{tb_name}.vvp" # Omit checked-in params.vh so public-generate include_root is sole # authority (cwd=work → `include "src/generated/..."` hits -I first). sources = [ str(ROOT / rel) for rel in PRODUCTION_RTL_SOURCES if Path(rel).name != "prod2u_door_temp_params.vh" ] sources.append(str(ROOT / "tests" / "sim" / f"{tb_name}.v")) compile_cmd = [ str(self.iverilog), "-g2005-sv", "-I", str(include_root), "-I", str(ROOT), "-s", tb_name, "-o", str(vvp_out), *sources, ] compiled = subprocess.run( compile_cmd, cwd=work, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=False, timeout=120, ) self.assertEqual( compiled.returncode, 0, f"{name}/{tb_name} iverilog failed:\n{compiled.stdout}\n{compiled.stderr}", ) ran = subprocess.run( [str(self.vvp), str(vvp_out)], cwd=work, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=False, timeout=timeout_s, ) self.assertEqual( ran.returncode, 0, f"{name}/{tb_name} vvp failed:\n{ran.stdout}\n{ran.stderr}", ) self.assertIn(f"PASS {tb_name}", ran.stdout, ran.stdout) def _run_polarity(self, name: str, **kwargs) -> None: self._run_public_case(name, tb_name=POLARITY_TB, timeout_s=180, **kwargs) def _run_startup(self, name: str, **kwargs) -> None: # 5000+500 with force tick is heavier. self._run_public_case(name, tb_name=STARTUP_TB, timeout_s=600, **kwargs) def test_default_production_masks_rtl(self) -> None: self._run_polarity( "all_default", limit_active_high=[True, True, True], dir_close_level=[1, 1, 1], close_limit_is_ls=[True, True, True], ) def test_single_axis_x_2x2x2_matrix(self) -> None: """Eight X-axis configs; Y/Z stay production default.""" for ah, dcl, cls in itertools.product((False, True), (0, 1), (False, True)): name = f"x_ah{int(ah)}_dcl{dcl}_cls{int(cls)}" with self.subTest(name=name): self._run_polarity( name, limit_active_high=[ah, True, True], dir_close_level=[dcl, 1, 1], close_limit_is_ls=[cls, True, True], ) def test_all_active_low(self) -> None: self._run_polarity( "all_active_low", limit_active_high=[False, False, False], dir_close_level=[1, 1, 1], close_limit_is_ls=[True, True, True], ) def test_dir_all_invert(self) -> None: self._run_polarity( "dir_all_invert", limit_active_high=[True, True, True], dir_close_level=[0, 0, 0], close_limit_is_ls=[True, True, True], ) def test_ls_hs_all_swap(self) -> None: self._run_polarity( "ls_hs_all_swap", limit_active_high=[True, True, True], dir_close_level=[1, 1, 1], close_limit_is_ls=[False, False, False], ) def test_all_three_inverted(self) -> None: self._run_polarity( "all_three_inverted", limit_active_high=[False, False, False], dir_close_level=[0, 0, 0], close_limit_is_ls=[False, False, False], ) def test_mixed_xyz_asymmetric(self) -> None: """X default / Y active-low+DIR invert / Z LS-HS swap (bit order check).""" self._run_polarity( "mixed_xyz", limit_active_high=[True, False, True], dir_close_level=[1, 0, 1], close_limit_is_ls=[True, True, False], ) # --- Startup 5000+500 behavioral matrix (public generate path) --- def test_startup_default(self) -> None: self._run_startup( "startup_default", limit_active_high=[True, True, True], dir_close_level=[1, 1, 1], close_limit_is_ls=[True, True, True], ) def test_startup_all_active_low(self) -> None: self._run_startup( "startup_all_active_low", limit_active_high=[False, False, False], dir_close_level=[1, 1, 1], close_limit_is_ls=[True, True, True], ) def test_startup_ls_hs_swap(self) -> None: self._run_startup( "startup_ls_hs_swap", limit_active_high=[True, True, True], dir_close_level=[1, 1, 1], close_limit_is_ls=[False, False, False], ) def test_startup_dir_invert(self) -> None: self._run_startup( "startup_dir_invert", limit_active_high=[True, True, True], dir_close_level=[0, 0, 0], close_limit_is_ls=[True, True, True], ) def test_startup_mixed_xyz(self) -> None: self._run_startup( "startup_mixed_xyz", limit_active_high=[True, False, True], dir_close_level=[1, 0, 1], close_limit_is_ls=[True, True, False], ) class AltConfigPublicCliTests(unittest.TestCase): """Python/CLI-only — must run even when Icarus is unavailable.""" def test_public_cli_generates_alt_params_for_rtl(self) -> None: """CLI path (not only Python API) must feed the same include layout.""" import sys with tempfile.TemporaryDirectory(prefix="alt-cli-") as tmp: tmp_path = Path(tmp) pj = _write_alt_project( tmp_path, limit_active_high=[False, True, True], dir_close_level=[1, 1, 1], close_limit_is_ls=[True, True, True], ) out = tmp_path / "out" proc = subprocess.run( [sys.executable, str(ROOT / "tools" / "generate_project.py"), str(pj), str(out)], capture_output=True, text=True, check=False, ) self.assertEqual(proc.returncode, 0, proc.stderr or proc.stdout) params = (out / "generated" / "prod2u_door_temp_params.vh").read_text(encoding="ascii") self.assertIn("`define P4_LIMIT_ACTIVE_HIGH_MASK 3'b110", params) class AltConfigFormalNormalizeTests(unittest.TestCase): """BMC/cover only — never claim infinite prove for alt-config normalize.""" def test_alt_config_normalize_bmc_cover(self) -> None: sby = resolve_tool("sby") if not sby: candidate = Path("/data/prod2u/oss-cad-suite/latest/bin/sby") sby = str(candidate) if candidate.is_file() else None if not sby: self.skipTest("sby unavailable") formal_dir = ROOT / "tests" / "formal" sby_path = formal_dir / "alt_config_limit_normalize.sby" self.assertTrue(sby_path.is_file(), sby_path) env = os.environ.copy() oss_bin = str(Path(sby).resolve().parent) env["PATH"] = oss_bin + os.pathsep + env.get("PATH", "") env.pop("LD_LIBRARY_PATH", None) env.pop("LD_PRELOAD", None) env.pop("QT_PLUGIN_PATH", None) tmp_root = Path(os.environ.get("TMPDIR", "/tmp")) for task in ("bmc", "cover"): with self.subTest(task=task): # Isolate SBY workdirs under TMPDIR — never pollute tests/formal. work = Path( tempfile.mkdtemp( prefix=f"prod2u-sby-alt-config-{task}-", dir=str(tmp_root), ) ) completed = subprocess.run( [sby, "-f", "-d", str(work), str(sby_path), task], cwd=formal_dir, text=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, check=False, timeout=300, env=env, ) self.assertEqual( completed.returncode, 0, f"sby {task} failed:\n{completed.stdout}", ) # Honesty: this is BMC/cover depth-bounded, not unbounded proof. self.assertNotIn("UNBOUNDED PROOF", completed.stdout.upper()) self.assertNotIn("prove", task) self.assertTrue( str(work.resolve()).startswith(str(tmp_root.resolve())), f"sby workdir not under TMPDIR: {work}", ) self.assertTrue( (work / "PASS").is_file(), f"missing PASS marker in isolated workdir {work}\n{completed.stdout}", ) def test_formal_model_structurally_tracks_top(self) -> None: """Helper BMC model must keep the same normalize identifiers as real top. Formal evidence type remains BMC/cover only — not unbounded proof and not a substitute for the real-top Icarus matrix above. """ top = (ROOT / "src" / "top" / "prod2u_p4_normal_v3_top.v").read_text( encoding="utf-8" ) formal = ( ROOT / "tests" / "formal" / "alt_config_limit_normalize_formal.v" ).read_text(encoding="utf-8") # Top uses localparam names; formal shell uses lowercase ports that # mirror the same normalize / selected_limit / DIR edge equations. for needle in ( "selected_limit", "close_limit", "open_limit", "ls_reached", "hs_reached", ): self.assertIn(needle, top) self.assertIn(needle, formal) self.assertIn("LIMIT_ACTIVE_HIGH", top) self.assertIn("limit_active_high", formal) self.assertIn("DIR_CLOSE_LEVEL", top) self.assertIn("dir_close_level", formal) self.assertIn("CLOSE_LIMIT_IS_LS", top) self.assertIn("close_limit_is_ls", formal) self.assertIn("BMC/cover only", formal) if __name__ == "__main__": unittest.main()