Skip to content

bjwanneng/veriflow-cc / src/claude_skills/vf-rtl

vf-rtl

Verified

FileKindSize
SELF_IMPROVE.mdmarkdown3.8 KB
SKILL.mdskill md11.2 KB
SKILL_INDEX.mdmarkdown5.5 KB
analysis/bug_pattern_match.pyscript26.9 KB
analysis/corner_case_generator.pyscript4.9 KB
analysis/coverage_analyzer.pyscript5.3 KB
analysis/design_graph.pyscript8.9 KB
analysis/expected_trace_gen.pyscript12.5 KB
analysis/timing_contract_checker.pyscript25.4 KB
analysis/timing_diagnostic.pyscript21.1 KB
analysis/vcd2table.pyscript31.3 KB
bug_patterns.mdmarkdown23.2 KB
coding_style.mdmarkdown9.4 KB
core/init.pyscript13.8 KB
core/rtl_utils.pyscript7.5 KB
core/state.pyscript38.9 KB
design_rules.mdmarkdown2.9 KB
error_recovery.mdmarkdown7.0 KB
kb/knowledge_base.pyscript11.7 KB
kb/reference_kb.pyscript5.6 KB
kb/self_improve.pyscript24.4 KB
references/arbiter_round_robin.vother1.4 KB
references/counter.vother545 B
references/fifo.vother1.3 KB
references/fsm_moore.vother847 B
references/handshake_valid_ready.vother1.1 KB
references/pipeline_aligner.vother760 B
runners/benchmark_runner.pyscript23.6 KB
runners/cocotb_runner.pyscript26.3 KB
runners/iverilog_runner.pyscript26.3 KB
runners/yosys_equiv.pyscript14.2 KB
stage1_spec_golden.mdmarkdown6.1 KB
stage2_codegen.mdmarkdown5.9 KB
stage3_verify_fix.mdmarkdown17.0 KB
stage4_lint_synth.mdmarkdown6.3 KB
templates/cocotb_template.pyscript42.4 KB
templates/golden_model_template.pyscript8.7 KB
templates/spec_template.jsonconfig8.5 KB
templates/tb_integration_template.vother12.4 KB
verify/candidate_selector.pyscript7.0 KB
verify/formal_prove.pyscript12.1 KB
verify/synth_score.pyscript4.4 KB

core/rtl_utils.py

View on GitHub
"""Shared utilities for VeriFlow-CC RTL pipeline tools.

Provides common functionality used by iverilog_runner.py, cocotb_runner.py,
vcd2table.py, timing_diagnostic.py, timing_contract_checker.py, and state.py.
"""

import importlib.util
import json
import os
import shutil
import signal
import sys
from pathlib import Path
from typing import Any
import contextlib


@contextlib.contextmanager
def _golden_timeout(seconds: int, what: str):
    """POSIX alarm guard around untrusted golden-model execution.

    The golden model is LLM-generated code executed in-process; a hang here
    would hang every importer (timing_diagnostic, vcd2table, expected_trace_gen).
    No-op where SIGALRM is unavailable (Windows) or seconds <= 0.
    """
    if seconds <= 0 or not hasattr(signal, "SIGALRM"):
        yield
        return

    def _handler(signum, frame):
        raise TimeoutError(f"golden model {what} exceeded {seconds}s")

    prev = signal.signal(signal.SIGALRM, _handler)
    signal.alarm(seconds)
    try:
        yield
    finally:
        signal.alarm(0)
        signal.signal(signal.SIGALRM, prev)


# Single source of truth for the ±N-cycle search window used by the failure
# classifier and timing diagnostics. Living here (not in timing_diagnostic.py)
# lets iverilog_runner import it without a try/except fallback that could
# silently drift if timing_diagnostic ever gets renamed or moved.
DIVERGENCE_SEARCH_WINDOW: int = 8


def find_executable(names: list[str]) -> str:
    """Find an executable by name, checking EDA_BIN then PATH.

    Args:
        names: Candidate executable names (e.g., ["iverilog", "iverilog.exe"]).
    Returns:
        Absolute path to the executable, or empty string if not found.
    """
    eda_bin = os.environ.get("EDA_BIN", "")
    if eda_bin:
        for name in names:
            p = Path(eda_bin) / name
            if p.exists():
                return str(p)
    for name in names:
        found = shutil.which(name)
        if found:
            return found
    return ""


def collect_rtl_sources(rtl_dir: Path) -> list[str]:
    """Find all Verilog source files in rtl_dir.

    Args:
        rtl_dir: Directory to search for *.v files.
    Returns:
        Sorted list of absolute paths as strings.
    Raises:
        SystemExit(2): If no .v files are found.
    """
    sources = sorted(rtl_dir.glob("*.v"))
    if not sources:
        print(json.dumps({
            "tests": 0, "passed": 0, "failed": 0,
            "error": f"No .v files found in {rtl_dir}"
        }))
        sys.exit(2)
    return [str(s) for s in sources]


def load_golden_trace(golden_path: str, test_vector_index: int = 0,
                      timeout: int = 60) -> dict[int, dict[str, Any]]:
    """Load and run a golden model, returning per-cycle trace data.

    Supports three golden model interfaces:
      1. run(test_vector_index=N) -> list[dict]
      2. run() -> list[dict]
      3. compute(inputs, trace=True) returning a trace (uses TEST_VECTORS)

    Args:
        golden_path: Path to golden_model.py.
        test_vector_index: Which test vector to use (default 0).
        timeout: Wall-clock cap (POSIX) on model import + execution; the
            model is LLM-generated and may contain an infinite loop.
    Returns:
        Dict mapping cycle_number -> {signal_name: value}.
    Raises:
        RuntimeError: If the golden model cannot be loaded or produces no data.
    """
    golden_path = str(Path(golden_path).resolve())
    if not Path(golden_path).exists():
        raise RuntimeError(f"Golden model not found: {golden_path}")

    spec = importlib.util.spec_from_file_location("golden_model", golden_path)
    if not spec or not spec.loader:
        raise RuntimeError(f"Cannot create module spec for {golden_path}")

    mod = importlib.util.module_from_spec(spec)
    with _golden_timeout(timeout, "import"):
        spec.loader.exec_module(mod)

    # Interface 1: run(test_vector_index=N) or run(N) or run()
    if hasattr(mod, "run"):
        try:
            with _golden_timeout(timeout, "run()"):
                data = mod.run(test_vector_index=test_vector_index)
        except TypeError:
            try:
                with _golden_timeout(timeout, "run()"):
                    data = mod.run(test_vector_index)
            except TypeError:
                with _golden_timeout(timeout, "run()"):
                    data = mod.run()

        if isinstance(data, list):
            cycles = {}
            for i, entry in enumerate(data):
                if isinstance(entry, dict):
                    cycles[i] = entry
            if cycles:
                return cycles

    # Interface 2: compute(inputs, trace=True) with TEST_VECTORS
    if hasattr(mod, "compute") and hasattr(mod, "TEST_VECTORS"):
        tv = mod.TEST_VECTORS[test_vector_index] if test_vector_index < len(mod.TEST_VECTORS) else mod.TEST_VECTORS[0]
        inputs = tv.get("inputs", tv)
        try:
            with _golden_timeout(timeout, "compute()"):
                trace = mod.compute(inputs, trace=True)
            if isinstance(trace, list):
                cycles = {}
                for i, entry in enumerate(trace):
                    if isinstance(entry, dict):
                        cycles[i] = entry
                if cycles:
                    return cycles
            elif isinstance(trace, dict):
                return {0: trace}
        except TimeoutError:
            raise RuntimeError(f"golden model compute() hung > {timeout}s")
        except Exception as e:
            print(f"[rtl_utils] golden compute() raised, trying next interface: {e}",
                  file=sys.stderr)

    # Interface 3: simulate(inputs, trace=True) with TEST_VECTORS
    if hasattr(mod, "simulate") and hasattr(mod, "TEST_VECTORS"):
        tv = mod.TEST_VECTORS[test_vector_index] if test_vector_index < len(mod.TEST_VECTORS) else mod.TEST_VECTORS[0]
        inputs = tv.get("inputs", tv)
        try:
            with _golden_timeout(timeout, "simulate()"):
                trace = mod.simulate(inputs, trace=True)
            if isinstance(trace, list):
                cycles = {}
                for i, entry in enumerate(trace):
                    if isinstance(entry, dict):
                        cycles[i] = entry
                if cycles:
                    return cycles
        except TimeoutError:
            raise RuntimeError(f"golden model simulate() hung > {timeout}s")
        except Exception as e:
            print(f"[rtl_utils] golden simulate() raised, trying next interface: {e}",
                  file=sys.stderr)

    raise RuntimeError(
        "Golden model produced no parseable cycle data. "
        "Expected run() -> list[dict] or compute(inputs, trace=True)."
    )


def load_golden_trace_as_list(golden_path: str, test_vector_index: int = 0) -> list[dict[str, int]]:
    """Load golden model trace as a list[dict[str, int]].

    Convenience wrapper around load_golden_trace() that returns a contiguous
    list indexed by cycle number, with values coerced to int.
    """
    cycles_dict = load_golden_trace(golden_path, test_vector_index)
    if not cycles_dict:
        return []
    max_cycle = max(cycles_dict.keys())
    result = []
    for i in range(max_cycle + 1):
        entry = cycles_dict.get(i, {})
        clean = {}
        for k, v in entry.items():
            if isinstance(v, int):
                clean[k] = v
            elif isinstance(v, str):
                with contextlib.suppress(TypeError, ValueError):
                    clean[k] = int(v, 0)
        result.append(clean)
    return result
slack-gif-creatoranthropics/skillsKnowledge and utilities for creating animated GIFs optimized for Slack. Provides constraints, validation tools, and animation concepts. Use when users request animated GIFs for Slack like "make me a GIF of X doing Y for Slack."Stars: 198kUpdated Claude CodeCodexVerifiedInstall
ponytailDietrichGebert/ponytailLazy senior dev mode for any coding task: the smallest change that fully solves it, and a reply a busy human understands in one read.Stars: 194kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailHarvest every shortcut: comment into one debt ledger, so deferrals get tracked instead of forgotten. One-shot report.Stars: 194kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailList every `shortcut:` comment (and older `ponytail:` ones) as a debt ledger. One-shot report, changes nothing. Use for "ponytail debt", "what did ponytail defer", "list the shortcuts", /ponytail-debt.Stars: 194kUpdated Claude CodeCodexVerifiedInstall