diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d403ce24246..8fce6137741 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -538,6 +538,15 @@ jobs: --expected conformance/sv-tests/expected.tsv --report "$RUNNER_TEMP/sv-tests-report.tsv" + - name: Summarize sv-tests failures + if: always() + shell: bash + run: | + report="$RUNNER_TEMP/sv-tests-report.summary.md" + if [ -f "$report" ]; then + cat "$report" >> "$GITHUB_STEP_SUMMARY" + fi + - name: Retain the report and official per-case logs if: always() uses: actions/upload-artifact@v7 @@ -546,6 +555,8 @@ jobs: path: | ${{ runner.temp }}/sv-tests-report.tsv ${{ runner.temp }}/sv-tests-report.summary.json + ${{ runner.temp }}/sv-tests-report.summary.md + ${{ runner.temp }}/sv-tests-report.failures.json ${{ runner.temp }}/sv-tests-results if-no-files-found: ignore retention-days: 14 diff --git a/Cargo.lock b/Cargo.lock index a33a7e74520..2ff45141965 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5664,9 +5664,9 @@ dependencies = [ [[package]] name = "zstd-sys" -version = "2.0.16+zstd.1.5.7" +version = "2.1.2+zstd.1.5.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91e19ebc2adc8f83e43039e79776e3fda8ca919132d68a1fed6a5faca2683748" +checksum = "481ada9c543b2323cbb7bbdbb5249177fbf0188ed959ed2c15e4b22421c84ed3" dependencies = [ "cc", "pkg-config", diff --git a/conformance/sv-tests/README.md b/conformance/sv-tests/README.md index fec41b659ee..aea0736743f 100644 --- a/conformance/sv-tests/README.md +++ b/conformance/sv-tests/README.md @@ -45,7 +45,7 @@ modes, sources without a module still undergo preprocessing and parsing; root detection then reports the actual no-root diagnostic. The current compiler and simulator require a module root, so the driver reports a failure for rootless unit, package and interface inputs. The official runner still decides -the case verdict, including expected failures. There is no `no_top` classification +the case verdict, including expected failures. There is no `no_top` verdict or preemptive skip. Without an explicit top, the driver infers a single root from parsed declarations and instantiations; multiple roots receive a diagnostic because Celox’s simulator requires one root. Each input file is a separate @@ -361,3 +361,68 @@ These fixtures exercise the actual upstream runner with a controlled driver, including mode priority, skips, negative tests, assertions, timeouts, library injection and missing-environment failures. The Rust example is a single-case compiler/simulator driver; it does not parse sv-tests metadata or judge verdicts. + +## Failure triage + +`run.py` now writes four companion artifacts: + +- `report.tsv`: official verdicts plus `failure_category`, `diagnostic`, a bounded + diagnostic excerpt (`evidence`), and `negative_test` (`1`, `0`, or empty when unknown). +- `report.summary.json`: schema version 2, collection completeness, requested and + collected row counts, per-group/per-state totals, failure counts and frequent + diagnostics. `classification_version` identifies the diagnostic rules. +- `report.summary.md`: a readable overview, also attached to the CI job summary. +- `report.failures.json`: every failing case with its classification and log path, + plus collection errors. No case is removed from the TSV or denominator. + +Categories describe **observed diagnostics**, not proven compiler root causes: + +| Category | Evidence | +| --- | --- | +| `unsupported` | explicit unsupported-construct or single-module-root diagnostic | +| `compile_error` | parse-error or illegal-context diagnostic, even if the selected mode was simulation | +| `runtime_error` | `$fatal` or lost-runtime-event diagnostic | +| `assertion_failure` | official simulation output validation failed after a successful positive invocation | +| `unexpected_success` | a negative test's driver succeeded | +| `timeout` | upstream timeout return code **and** timeout diagnostic | +| `crash` | Rust panic diagnostic or abnormal/signal return code | +| `input_issue` | the reviewed upstream input defect described above | +| `environment` | missing include directory without the reviewed input exception | +| `unclassified` | unknown diagnostic, missing log, or TSV/log metadata disagreement | + +For example, a parser error on a valid but unimplemented grammar construct is +still `compile_error`; the classifier does not guess whether the source or the +parser is wrong. A nonzero return code in simulation mode alone does not establish +a runtime bug because compilation may have failed first. Frequent diagnostic +counts normalize source paths and line numbers; `.failures.json` retains the +individual evidence and log locations. Tag counts still overlap as described above. + +Negative-test passes accompanied by unsupported, root-requirement, timeout or +crash diagnostics appear in `negative_pass_diagnostics` for review. They remain +**official passes**, not new failures. No assertion expression is evaluated by +this classification code. + +Missing drivers, missing libraries, runner exceptions and other collection +errors still return exit code 2 and prohibit `--update`. A failed collection now +retains already completed rows and separate `collection_errors`, with +`complete: false`; cancelled/unrun cases do not become invented failure rows. +An incomplete report must not be used as a full conformance score. Successful +collection has `complete: true` even when comparison with expectations returns 1. + +Reclassify a downloaded or older **run report**, without rerunning simulations or +changing `expected.tsv`: + +```bash +python conformance/sv-tests/reporting.py work/sv-tests-report.tsv \ + --log-root work/sv-tests-results \ + --meta-tags ../sv-tests/conf/meta-tags.conf \ + --output work/triage/report.tsv +``` + +`--log-root` relocates logs using `STATE/TEST/official.log`. Otherwise the paths +in the TSV are used (relative paths resolve against the TSV directory). +`--meta-tags` should reference the matching pinned checkout; omit it to count +only literal tags, reported as `meta_tags_expanded: false`. The existing summary +supplies the corpus revision and incomplete-collection provenance. Without a +completeness marker in that summary, offline reports use `complete: null` +(unknown), not a claim that every case ran. Missing logs stay unclassified. diff --git a/conformance/sv-tests/reporting.py b/conformance/sv-tests/reporting.py new file mode 100644 index 00000000000..21d3c427679 --- /dev/null +++ b/conformance/sv-tests/reporting.py @@ -0,0 +1,211 @@ +#!/usr/bin/env python3 +"""Classify sv-tests diagnostics without changing the official runner verdicts.""" + +import argparse +from collections import Counter +import csv +import json +from pathlib import Path +import re +import sys + +CLASSIFICATION_VERSION = 1 +FIELDS = ("failure_category", "diagnostic", "evidence", "negative_test") +BASE_FIELDS = ("test", "state_mode", "result", "mode", "tags", "group", + "input_issue", "rc", "tool_success", "log") + + +def classify(row, log): + """Evidence labels, not a second verdict evaluator or a proof of root cause.""" + meta, separator, body = log.partition("\n\n") + metadata = dict(line.split(": ", 1) for line in meta.splitlines() if ": " in line) if separator else {} + # BaseRunner puts the invocation on the first line, except on timeout. + lines = body.splitlines() if separator else [] + if lines and not lines[0].startswith("Timeout: > "): + lines = lines[1:] + text = re.sub(r"\x1b\[[0-9;]*m", "", "\n".join(lines)) + rc = metadata.get("rc", row.get("rc", "")) + success = metadata.get("tool_success", row.get("tool_success", "")) + negative = metadata.get("should_fail", "") == "1" + category, diagnostic = "unclassified", "unrecognized_diagnostic" + evidence = next((line.strip() for line in text.splitlines() if line.strip()), "no driver diagnostic") + if not log: + diagnostic, evidence = "missing_log", "official log is unavailable" + elif row.get("input_issue"): + category, diagnostic, evidence = "input_issue", "reviewed_upstream_input", row["input_issue"] + elif rc == "71" and re.search(r"^Timeout: > \d+s$", text, re.MULTILINE): + category, diagnostic = "timeout", "runner_timeout" + elif re.search(r"^thread .* panicked at", text, re.MULTILINE): + category, diagnostic = "crash", "rust_panic" + evidence = re.search(r"^thread .* panicked at.*$", text, re.MULTILINE)[0] + elif re.fullmatch(r"-?\d+", rc) and (int(rc) < 0 or int(rc) >= 126): + category, diagnostic, evidence = "crash", "abnormal_exit", f"driver return code {rc}" + elif row["result"] == "fail" and success == "1" and negative: + category, diagnostic, evidence = "unexpected_success", "negative_test_succeeded", "negative test: driver succeeded" + elif row["result"] == "fail" and success == "1" and metadata.get("should_fail") == "0" and row.get("mode") == "simulation": + category, diagnostic, evidence = "assertion_failure", "official_output_validation", "official simulation output validation failed" + elif re.search(r"^unsupported_simulator_parser$|^Unsupported SystemVerilog construct:", text, re.MULTILINE): + category, diagnostic = "unsupported", "unsupported_construct" + # Join miette's wrapped diagnostic, keeping the specific missing feature. + clean = " ".join(line.strip(" │×╰─") for line in text.splitlines() if line.strip()) + match = re.search(r"Unsupported SystemVerilog construct: (.*)", clean) + evidence = match[1].rstrip(") ") if match else evidence + elif text.startswith("elaboration requires a module root;") or text.startswith("multiple module roots ("): + category, diagnostic = "unsupported", "module_root_requirement" + elif text.startswith("SystemVerilog parse error:"): + category, diagnostic = "compile_error", "parse_error" + elif re.search(r"^illegal_context$", text, re.MULTILINE): + category, diagnostic = "compile_error", "illegal_context" + elif re.search(r"^.*include directory is unavailable:", text, re.MULTILINE): + category, diagnostic = "environment", "missing_include_directory" + elif re.search(r"^\$fatal: |^\d+ runtime events were lost$", text, re.MULTILINE): + category, diagnostic = "runtime_error", "runtime_diagnostic" + evidence = re.search(r"^\$fatal: .*|^\d+ runtime events were lost$", text, re.MULTILINE)[0] + if row["result"] == "pass" and success == "1": + diagnostic, evidence = "", "" + if log and any(row.get(key) and metadata.get(key) != row[key] for key in ("rc", "mode", "tool_success")): + category, diagnostic, evidence = "unclassified", "metadata_mismatch", "TSV and official log metadata disagree" + # Driver failure in simulation mode can still be a compiler failure. Leave + # unknown diagnostics unclassified instead of labelling them runtime bugs. + return { + "failure_category": category if row["result"] == "fail" else "", + "diagnostic": diagnostic if row["result"] != "skip" else "", + "evidence": evidence[:1000] if row["result"] != "skip" else "", + "negative_test": "1" if negative else "0" if metadata.get("should_fail") == "0" else "", + } + + +def annotate(row, log): + return {**row, **classify(row, log)} + + +def breakdown(rows): + failures = [row for row in rows if row["result"] == "fail"] + counts = Counter(row.get("failure_category") or "unclassified" for row in failures) + diagnostics = Counter((row.get("failure_category") or "unclassified", row.get("diagnostic") or "unknown") + for row in failures) + reasons = Counter() + examples = {} + for row in failures: + evidence = re.sub(r"\S+\.svh?:\d+(?::\d+)?:?", "", row.get("evidence", "")) + key = (row.get("failure_category") or "unclassified", row.get("diagnostic") or "unknown", evidence) + reasons[key] += 1 + examples.setdefault(key, {"test": row.get("test", ""), "log": row.get("log", "")}) + return { + "by_failure_reason": [{"category": key[0], "diagnostic": key[1], "evidence": key[2], + "count": count, "example": examples[key]} + for key, count in sorted(reasons.items(), key=lambda item: (-item[1], item[0]))], + "by_failure_category": dict(sorted(counts.items())), + "by_failure_diagnostic": [{"category": category, "diagnostic": diagnostic, "count": count} + for (category, diagnostic), count in sorted(diagnostics.items())], + "negative_pass_diagnostics": dict(sorted(Counter( + row["diagnostic"] for row in rows + if row["result"] == "pass" and row.get("negative_test") == "1" + and row.get("diagnostic") in {"unsupported_construct", "module_root_requirement", "runner_timeout", "rust_panic", "abnormal_exit"} + ).items())), + } + + +def markdown(summary): + def cell(value): + return str(value).replace("|", "\\|").replace("\n", " ") + lines = ["# sv-tests results", "", f"Corpus revision: `{summary.get('revision') or 'unknown'}`", ""] + if summary["complete"] is None: + lines += ["**Collection completeness is unknown: the source report has no completeness marker.**", ""] + elif not summary["complete"]: + lines += ["**INCOMPLETE: collection failed. These totals are not a full conformance result.**", ""] + lines += ["| Group | State | Pass / executed | Pass % | Skipped |", "| --- | --- | ---: | ---: | ---: |"] + for group, states in summary["groups"].items(): + for state, counts in states.items(): + lines.append(f"| {cell(group)} | {state} | {counts['passed']} / {counts['executed']} | {counts['pass_percent']} | {counts['skipped']} |") + lines += ["", "## Failure categories", "", "| Group | State | Category | Count |", "| --- | --- | --- | ---: |"] + for group, states in summary["groups"].items(): + for state, counts in states.items(): + for category, count in counts["by_failure_category"].items(): + lines.append(f"| {cell(group)} | {state} | {category} | {count} |") + for group, states in summary["groups"].items(): + for state, counts in states.items(): + if counts["by_failure_reason"]: + lines += ["", f"### Frequent diagnostics: {cell(group)} / {state}", "", + "| Count | Category | Diagnostic | Evidence |", "| ---: | --- | --- | --- |"] + for reason in counts["by_failure_reason"][:10]: + lines.append(f"| {reason['count']} | {reason['category']} | {reason['diagnostic']} | {cell(reason['evidence'][:200])} |") + if counts["negative_pass_diagnostics"]: + lines += ["", f"Negative-test passes requiring diagnostic review ({cell(group)}, {state}): " + + cell(counts["negative_pass_diagnostics"]), ""] + if summary["collection_errors"]: + lines += ["", "## Collection errors", ""] + lines += [f"- {cell(error.get('test', error['stage']))} {cell(error.get('state_mode', ''))}: {cell(error['message'])}" + for error in summary["collection_errors"]] + lines += ["", "Official verdicts and denominators are unchanged. Categories describe observed evidence, not proven root causes.", + "Unrecognized diagnostics remain unclassified. Case names, diagnostics and log paths are in the companion .failures.json.", ""] + return "\n".join(lines) + + +def write_reports(path, rows, groups, revision, errors=(), requested=None, complete=True, meta_tags_expanded=True): + path.parent.mkdir(parents=True, exist_ok=True) + fieldnames = list(BASE_FIELDS) + list(FIELDS) + with path.open("w", newline="") as stream: + writer = csv.DictWriter(stream, fieldnames=fieldnames, delimiter="\t", lineterminator="\n", extrasaction="ignore") + writer.writeheader() + writer.writerows(rows) + summary = {"schema_version": 2, "classification_version": CLASSIFICATION_VERSION, + "revision": revision, "complete": False if errors else complete, "collected": len(rows), + "meta_tags_expanded": meta_tags_expanded, + "requested": requested, "collection_errors": list(errors), "groups": groups} + path.with_suffix(".summary.json").write_text(json.dumps(summary, indent=2) + "\n") + path.with_suffix(".summary.md").write_text(markdown(summary)) + failures = [{key: row.get(key, "") for key in (*BASE_FIELDS, *FIELDS)} + for row in rows if row["result"] == "fail"] + path.with_suffix(".failures.json").write_text(json.dumps({ + "classification_version": CLASSIFICATION_VERSION, "complete": summary["complete"], + "failures": failures, "collection_errors": list(errors), + }, indent=2) + "\n") + return summary + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("report", type=Path, help="existing run.py TSV (never expected.tsv)") + parser.add_argument("--output", type=Path, required=True, help="new annotated TSV and companion reports") + parser.add_argument("--log-root", type=Path, help="relocated logs: ROOT/STATE/TEST/official.log") + parser.add_argument("--meta-tags", type=Path, help="pinned upstream conf/meta-tags.conf") + args = parser.parse_args(argv) + try: + # Import here to keep the classifier reusable by run.py. + from run import read_meta_tags, summarize + if args.output.resolve() == args.report.resolve(): + raise ValueError("output must differ from the source report") + with args.report.open(newline="") as stream: + reader = csv.DictReader(stream, delimiter="\t") + if not set(BASE_FIELDS).issubset(reader.fieldnames or []): + raise ValueError("expected a run.py report with case metadata and log paths") + rows, seen = [], set() + for row in reader: + key = (row["test"], row["state_mode"]) + test = Path(row["test"]) + if (None in row or any(value is None for value in row.values()) or key in seen + or not row["test"] or test.is_absolute() or ".." in test.parts + or row["state_mode"] not in ("2state", "4state") or row["result"] not in ("pass", "fail", "skip")): + raise ValueError(f"invalid or duplicate report row: {key}") + seen.add(key) + log = args.log_root / row["state_mode"] / test / "official.log" if args.log_root else Path(row["log"]) + if not args.log_root and not log.is_absolute(): + log = args.report.parent / log + row["log"] = str(log) + rows.append(annotate(row, log.read_text() if log.is_file() else "")) + companion = args.report.with_suffix(".summary.json") + source = json.loads(companion.read_text()) if companion.is_file() else {} + rows.sort(key=lambda row: (row["test"], row["state_mode"])) + groups = summarize(rows, read_meta_tags(args.meta_tags) if args.meta_tags else {}) + write_reports(args.output, rows, groups, source.get("revision"), + source.get("collection_errors", []), source.get("requested"), + complete=source.get("complete"), meta_tags_expanded=args.meta_tags is not None) + return 0 + except (OSError, ValueError) as error: + print(f"sv-tests reporting: {error}", file=sys.stderr) + return 2 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/conformance/sv-tests/run.py b/conformance/sv-tests/run.py index 7c977a6db6b..304da24d526 100644 --- a/conformance/sv-tests/run.py +++ b/conformance/sv-tests/run.py @@ -3,7 +3,7 @@ import argparse from collections import Counter -from concurrent.futures import ThreadPoolExecutor, as_completed +from concurrent.futures import CancelledError, ThreadPoolExecutor, as_completed import csv import importlib.util import json @@ -13,6 +13,8 @@ import subprocess import sys +import reporting + MODES = ("2state", "4state") HEADER = ("test", "state_mode", "result") REPO = Path(__file__).resolve().parents[2] @@ -116,7 +118,7 @@ def run_case(root, driver, out_dir, test, state_mode): verdict = official_verdict(result.stderr, log, test) meta = log_metadata(log) if log else {} input_issues = json.loads((REPO / "conformance/sv-tests/input-issues.json").read_text())["cases"] - return { + return reporting.annotate({ "test": test, "state_mode": state_mode, "result": verdict, "mode": meta.get("mode", ""), "tags": meta.get("tags", ""), "group": (meta.get("results_group") or "main") if meta else "unclassified", @@ -124,7 +126,7 @@ def run_case(root, driver, out_dir, test, state_mode): if meta.get("rc") == "1" and "include directory is unavailable:" in log else ""), "rc": meta.get("rc", ""), "tool_success": meta.get("tool_success", ""), "log": str(log_path), - } + }, log) def read_meta_tags(path): @@ -171,6 +173,7 @@ def summarize(rows, meta_tags=None): "by_tag": {tag: {"passed": count["pass"], "executed": sum(count.values())} for tag, count in sorted(tags.items())}, "by_execution_mode": {mode: dict(count) for mode, count in sorted(modes.items())}, + **reporting.breakdown(selected), } return groups @@ -182,23 +185,38 @@ def positive_int(value): return number +class CollectionError(ValueError): + def __init__(self, rows, errors): + super().__init__("official runner infrastructure failure; collection is incomplete") + self.rows = sorted(rows, key=lambda row: (row["test"], row["state_mode"])) + self.errors = sorted(errors, key=lambda error: (error["test"], error["state_mode"])) + + def collect_cases(root, driver, out_dir, tests, modes, jobs): - # Each official runner owns a unique case/state directory. BaseRunner also - # uses mkdtemp for its work directory below OUT_DIR/tmp. + # Preserve completed evidence, but never update a baseline after an error. + rows, errors = [], [] executor = ThreadPoolExecutor(max_workers=jobs) - futures = [] - rows = [] try: - futures = [executor.submit(run_case, root, driver, out_dir, test, mode) - for test in tests for mode in modes] + futures = {executor.submit(run_case, root, driver, out_dir, test, mode): (test, mode) + for test in tests for mode in modes} for future in as_completed(futures): - rows.append(future.result()) - if len(rows) % (100 * len(modes)) == 0: + test, mode = futures[future] + try: + rows.append(future.result()) + except CancelledError: + continue + except (OSError, ValueError) as error: + errors.append({"category": "infrastructure", "stage": "collection", "test": test, + "state_mode": mode, "message": str(error), + "log": str(out_dir / mode / test / "runner.log")}) + for pending in futures: + pending.cancel() + if len(rows) and len(rows) % (100 * len(modes)) == 0: print(f"sv-tests: {len(rows)}/{len(tests) * len(modes)} mode runs", file=sys.stderr) finally: - # A preparation/infrastructure error cannot accept a partial baseline. - # Cancel queued work and let already running official processes clean up. executor.shutdown(wait=True, cancel_futures=True) + if errors: + raise CollectionError(rows, errors) return sorted(rows, key=lambda row: (row["test"], row["state_mode"])) @@ -216,31 +234,31 @@ def main(argv=None): if options.update and not options.expected: parser.error("--update requires --expected") root, driver, out_dir = options.sv_tests.resolve(), options.driver.resolve(), options.out_dir.resolve() + report = options.report or out_dir / "report.tsv" + rows, meta_tags, requested = [], {}, None + stage = "preflight" + revision = None try: + result = subprocess.run(["git", "-C", str(root), "rev-parse", "HEAD"], capture_output=True, text=True) + revision = result.stdout.strip() if result.returncode == 0 else None preflight(root, driver) meta_tags = read_meta_tags(root / "conf/meta-tags.conf") modes = MODES if options.state_mode == "both" else (options.state_mode,) expected = read_expected(options.expected) if options.expected and options.expected.exists() else {} if options.expected and not options.expected.exists() and not options.update: raise ValueError(f"expectations do not exist: {options.expected}") + stage = "corpus" tests = sorted(p.relative_to(root / "tests").as_posix() for p in (root / "tests").rglob("*") if p.is_file() and p.suffix.lower() == ".sv") if not tests: raise ValueError("sv-tests checkout contains no .sv tests") + requested = len(tests) * len(modes) + stage = "collection" rows = collect_cases(root, driver, out_dir, tests, modes, options.jobs) results = {(row["test"], row["state_mode"]): row["result"] for row in rows} - report = options.report or out_dir / "report.tsv" - report.parent.mkdir(parents=True, exist_ok=True) - with report.open("w", newline="") as stream: - writer = csv.DictWriter(stream, fieldnames=list(rows[0]), delimiter="\t", lineterminator="\n") - writer.writeheader() - writer.writerows(rows) + stage = "report" groups = summarize(rows, meta_tags) - revision = subprocess.run(["git", "-C", str(root), "rev-parse", "HEAD"], - capture_output=True, text=True) - summary = {"revision": revision.stdout.strip() if revision.returncode == 0 else None, - "groups": groups} - report.with_suffix(".summary.json").write_text(json.dumps(summary, indent=2) + "\n") + reporting.write_reports(report, rows, groups, revision, requested=requested) for group, states in groups.items(): for mode, counts in states.items(): print(f"{group} [{mode}]: {counts['passed']}/{counts['executed']} passed " @@ -263,6 +281,13 @@ def main(argv=None): return 0 except (OSError, ValueError) as error: print(f"sv-tests: {error}", file=sys.stderr) + errors = [{"category": "infrastructure", "stage": stage, "message": str(error)}] + if isinstance(error, CollectionError): + rows, errors = error.rows, error.errors + try: + reporting.write_reports(report, rows, summarize(rows, meta_tags), revision, errors, requested) + except OSError as report_error: + print(f"sv-tests: cannot write incomplete report: {report_error}", file=sys.stderr) return 2 diff --git a/conformance/sv-tests/test_reporting.py b/conformance/sv-tests/test_reporting.py new file mode 100644 index 00000000000..91ea351f2ea --- /dev/null +++ b/conformance/sv-tests/test_reporting.py @@ -0,0 +1,131 @@ +"""Diagnostic classification and offline report contracts (no verdict recomputation).""" + +import csv +import json +from pathlib import Path +import tempfile +import unittest + +import reporting +import run as runner + + +def fixture(body, result="fail", rc="1", mode="elaboration", negative="0"): + row = {"test": "chapter-18/test.sv", "state_mode": "2state", "group": "main", "tags": "18 a", + "result": result, "rc": rc, "mode": mode, "tool_success": "1" if rc == "0" else "0", + "log": "official.log", "input_issue": ""} + log = f"mode: {mode}\nrc: {rc}\ntool_success: {row['tool_success']}\nshould_fail: {negative}\n\n/driver -- source.sv\n{body}\n" + return row, log + + +class ClassificationTests(unittest.TestCase): + def test_observed_failures_are_distinct(self): + examples = [ + ("unsupported_simulator_parser\n\n × Unsupported SystemVerilog\n │ construct: constrained randomize)", "1", "elaboration", "0", "unsupported"), + ("SystemVerilog parse error: /root/a.sv:2:3: expected `;`", "1", "simulation", "0", "compile_error"), + ("illegal_context\n × invalid argument", "1", "elaboration", "0", "compile_error"), + ("elaboration requires a module root; none found", "1", "elaboration", "0", "unsupported"), + ("$fatal: bad data", "1", "simulation", "0", "runtime_error"), + ("Timeout: > 30s", "71", "simulation", "0", "timeout"), + ("thread 'main' panicked at x.rs:1", "101", "elaboration", "0", "crash"), + ("", "-11", "simulation", "1", "crash"), + ("", "139", "simulation", "0", "crash"), + (":assert: (1 == 2)", "0", "simulation", "0", "assertion_failure"), + ("", "0", "elaboration", "1", "unexpected_success"), + ("include directory is unavailable: /missing", "1", "elaboration", "0", "environment"), + ("some new diagnostic", "1", "simulation", "0", "unclassified"), + ("unsupported file name only", "1", "simulation", "0", "unclassified"), + ] + for body, rc, mode, negative, category in examples: + with self.subTest(body=body, rc=rc): + row, log = fixture(body, rc=rc, mode=mode, negative=negative) + actual = reporting.annotate(row, log) + self.assertEqual(actual["failure_category"], category) + self.assertEqual(actual["result"], "fail") + row, log = fixture(examples[0][0]) + self.assertEqual(reporting.annotate(row, log)["evidence"], "constrained randomize") + + def test_passes_and_negative_diagnostic_warnings_do_not_become_failures(self): + row, log = fixture("unsupported_simulator_parser", result="pass", negative="1") + annotated = reporting.annotate(row, log) + self.assertEqual(annotated["failure_category"], "") + summary = runner.summarize([annotated])["main"]["2state"] + self.assertEqual((summary["passed"], summary["failed"], summary["executed"]), (1, 0, 1)) + self.assertEqual(summary["negative_pass_diagnostics"], {"unsupported_construct": 1}) + row, log = fixture(":assert: (1 == 1)", result="pass", rc="0", mode="simulation") + self.assertEqual(reporting.annotate(row, log)["diagnostic"], "") + row["result"] = "skip" + self.assertEqual(reporting.annotate(row, "")["failure_category"], "") + + def test_missing_stale_and_ambiguous_evidence_is_not_guessed(self): + row, log = fixture("unsupported_simulator_parser") + self.assertEqual(reporting.annotate(row, "")["diagnostic"], "missing_log") + self.assertEqual(reporting.annotate(row, log.replace("rc: 1", "rc: 0"))["diagnostic"], "metadata_mismatch") + row, log = fixture("driver returned an ordinary error", rc="71") + self.assertEqual(reporting.annotate(row, log)["failure_category"], "unclassified") + row["input_issue"] = "reviewed bad include" + self.assertEqual(reporting.annotate(row, log)["failure_category"], "input_issue") + + def test_summaries_partition_failures_without_changing_dashboard_totals(self): + rows = [] + for state in ("2state", "4state"): + for source in ("/checkout/a.sv:2:3:", "/other/b.sv:90:12:"): + row, log = fixture(f"SystemVerilog parse error: {source} expected `;`") + row["state_mode"] = state + rows.append(reporting.annotate(row, log)) + row, log = fixture("", result="pass", rc="0") + rows.append(reporting.annotate(row, log)) + groups = runner.summarize(rows) + for counts in groups["main"].values(): + self.assertEqual(sum(counts["by_failure_category"].values()), counts["failed"]) + self.assertEqual(len(counts["by_failure_reason"]), 1) + self.assertEqual(counts["by_failure_reason"][0]["count"], 2) + self.assertEqual(groups["main"]["2state"]["pass_percent"], 33.33) + self.assertEqual(groups["main"]["4state"]["pass_percent"], 0) + + def test_offline_report_relocates_logs_and_preserves_incomplete_provenance(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + row, log = fixture("unsupported_simulator_parser") + source = root / "old.tsv" + with source.open("w", newline="") as stream: + writer = csv.DictWriter(stream, fieldnames=list(row), delimiter="\t") + writer.writeheader() + writer.writerow(row) + source.with_suffix(".summary.json").write_text(json.dumps({ + "revision": "pinned", "complete": False, "requested": 2, + "collection_errors": [{"stage": "collection", "message": "broken runner"}], + })) + logs = root / "logs" + path = logs / row["state_mode"] / row["test"] / "official.log" + path.parent.mkdir(parents=True) + path.write_text(log) + output = root / "classified.tsv" + before = source.read_bytes() + self.assertEqual(reporting.main([str(source), "--output", str(output), "--log-root", str(logs)]), 0) + summary = json.loads(output.with_suffix(".summary.json").read_text()) + failures = json.loads(output.with_suffix(".failures.json").read_text()) + self.assertFalse(summary["complete"]) + self.assertFalse(failures["complete"]) + self.assertEqual(summary["revision"], "pinned") + self.assertEqual(failures["failures"][0]["failure_category"], "unsupported") + self.assertIn("INCOMPLETE", output.with_suffix(".summary.md").read_text()) + self.assertEqual(source.read_bytes(), before) + self.assertEqual(reporting.main([str(source), "--output", str(source)]), 2) + source.with_suffix(".summary.json").unlink() + self.assertEqual(reporting.main([str(source), "--output", str(output), "--log-root", str(logs)]), 0) + self.assertIsNone(json.loads(output.with_suffix(".summary.json").read_text())["complete"]) + self.assertIsNone(json.loads(output.with_suffix(".failures.json").read_text())["complete"]) + + def test_offline_rejects_baselines_and_duplicate_rows(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + source, output = root / "input.tsv", root / "output.tsv" + source.write_text("test\tstate_mode\tresult\na.sv\t2state\tfail\n") + self.assertEqual(reporting.main([str(source), "--output", str(output)]), 2) + row, _ = fixture("") + with source.open("w", newline="") as stream: + writer = csv.DictWriter(stream, fieldnames=list(row), delimiter="\t") + writer.writeheader() + writer.writerows([row, row]) + self.assertEqual(reporting.main([str(source), "--output", str(output)]), 2) diff --git a/conformance/sv-tests/test_runner.py b/conformance/sv-tests/test_runner.py index 024343e13ce..c9592135f0a 100644 --- a/conformance/sv-tests/test_runner.py +++ b/conformance/sv-tests/test_runner.py @@ -112,7 +112,12 @@ def test_official_metadata_defaults_priority_negative_and_assertions(self): self.assertEqual(self.case()["mode"], "elaboration") self.assertEqual(self.case(":type: parsing elaboration\n")["mode"], "elaboration") self.assertEqual(self.case(":type: elaboration simulation\n", "// OUTPUT: :assert: 1 == 1")["result"], "pass") - self.assertEqual(self.case(":type: simulation\n", "// OUTPUT: :assert: 1 == 2")["result"], "fail") + row = self.case(":type: simulation\n", "// OUTPUT: :assert: 1 == 2") + self.assertEqual((row["result"], row["failure_category"]), ("fail", "assertion_failure")) + row = self.case(":should_fail_because: invalid\n") + self.assertEqual((row["result"], row["failure_category"]), ("fail", "unexpected_success")) + row = self.case(":should_fail_because: invalid\n", "// OUTPUT: unsupported_simulator_parser\n// EXIT: 1") + self.assertEqual((row["result"], row["diagnostic"]), ("pass", "unsupported_construct")) row = self.case(":type: simulation\n:should_fail_because: invalid\n", "// EXIT: 1") self.assertEqual((row["result"], row["rc"]), ("pass", "1")) self.assertEqual(self.case(":type: simulation\n:should_fail_because: invalid\n", "// EXIT: 1\n// OUTPUT: :assert: False")["result"], "fail") @@ -172,6 +177,7 @@ def test_variants_are_forwarded_separately_only_for_simulation(self): def test_official_timeout(self): row = self.case(":type: simulation\n:timeout: 1\n", "// SLEEP") self.assertEqual((row["result"], row["rc"]), ("fail", "71")) + self.assertEqual(row["failure_category"], "timeout") def test_partial_update_and_comparison(self): self.case() @@ -230,3 +236,23 @@ def test_parallel_infrastructure_error_preserves_expectations(self): "--jobs", "4", "--expected", str(expected), "--update"]) self.assertEqual(code, 2) self.assertEqual(expected.read_bytes(), original) + summary = json.loads((self.out / "report.summary.json").read_text()) + self.assertFalse(summary["complete"]) + self.assertEqual(summary["requested"], 4) + self.assertTrue(summary["collection_errors"]) + self.assertTrue(all(error["test"] == "broken.sv" for error in summary["collection_errors"])) + with (self.out / "report.tsv").open() as stream: + rows = list(csv.DictReader(stream, delimiter="\t")) + self.assertTrue(all(row["result"] == "pass" for row in rows)) + self.assertIn("INCOMPLETE", (self.out / "report.summary.md").read_text()) + + def test_preflight_failure_replaces_stale_reports(self): + self.case() + args = [str(self.root), "--driver", str(self.driver), "--out-dir", str(self.out)] + self.assertEqual(runner.main(args), 0) + self.driver.unlink() + self.assertEqual(runner.main(args), 2) + summary = json.loads((self.out / "report.summary.json").read_text()) + self.assertFalse(summary["complete"]) + self.assertEqual(summary["collected"], 0) + self.assertEqual(summary["collection_errors"][0]["stage"], "preflight") diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index 22f1c650f7c..77e3c065724 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -46,7 +46,7 @@ mod procedural; type RegionedVarAddr = RegionedVarAddrBase; type GlueBlock = GlueBlockBase; -const MAX_SV_SPECIALIZATIONS_PER_MODULE: usize = 64; +const MAX_SV_RECURSIVE_SPECIALIZATIONS: usize = 64; /// The name of a module's [`SimModule::time_slot`]. const TIME_SLOT: &str = "$time"; @@ -2268,7 +2268,7 @@ fn prepare_external_hierarchy_collecting( names.sort(); let mut module_ids = HashMap::default(); - let mut module_specialization_counts = HashMap::default(); + let mut specialization_parents = HashMap::default(); let mut queue = Vec::new(); let mut requested_roots = HashMap::default(); for name in names { @@ -2309,7 +2309,6 @@ fn prepare_external_hierarchy_collecting( } let module_id = ModuleId(module_ids.len()); module_ids.insert(key.clone(), module_id); - module_specialization_counts.insert(name.clone(), 1usize); queue.push(key); } @@ -2374,7 +2373,6 @@ fn prepare_external_hierarchy_collecting( if !module_ids.contains_key(&dependency) { let id = ModuleId(module_ids.len()); module_ids.insert(dependency.clone(), id); - module_specialization_counts.insert(name.clone(), 1); queue.push(dependency); } } @@ -2400,13 +2398,7 @@ fn prepare_external_hierarchy_collecting( continue; } if !module_ids.contains_key(&child_key) { - let specialization_count = module_specialization_counts - .entry(child_key.name.clone()) - .or_insert(0); - if *specialization_count >= MAX_SV_SPECIALIZATIONS_PER_MODULE { - return Err(sv_specialization_limit_error(child_key.name.clone()).into()); - } - *specialization_count += 1; + register_specialization_parent(&child_key, &key, &mut specialization_parents)?; let child_id = ModuleId(module_ids.len()); module_ids.insert(child_key.clone(), child_id); queue.push(child_key); @@ -2885,8 +2877,7 @@ fn schedule_sources_collecting( let root_id = ModuleId(0); let mut module_ids = HashMap::default(); module_ids.insert(root_key.clone(), root_id); - let mut module_specialization_counts = HashMap::default(); - module_specialization_counts.insert(root_key.name.clone(), 1usize); + let mut specialization_parents = HashMap::default(); let mut queue = vec![root_key.clone()]; let mut index = 0; let mut elaborated = HashMap::default(); @@ -2923,13 +2914,7 @@ fn schedule_sources_collecting( return Err(unsupported_sv_instance(child_key.name.clone()).into()); } if !module_ids.contains_key(&child_key) { - let specialization_count = module_specialization_counts - .entry(child_key.name.clone()) - .or_insert(0); - if *specialization_count >= MAX_SV_SPECIALIZATIONS_PER_MODULE { - return Err(sv_specialization_limit_error(child_key.name.clone()).into()); - } - *specialization_count += 1; + register_specialization_parent(&child_key, &key, &mut specialization_parents)?; let child_id = ModuleId(module_ids.len()); module_ids.insert(child_key.clone(), child_id); queue.push(child_key); @@ -3210,6 +3195,29 @@ fn restore_interface_member_paths(module: &mut SimModule, source: &AnalyzedSvMod } } +/// Bound parameter-changing recursion along one instantiation path. Independent +/// siblings may have any number of distinct parameter specializations. Repeated +/// identical keys are handled by the hierarchy cycle checks. +fn register_specialization_parent( + child: &LoweredSvModuleKey, + parent: &LoweredSvModuleKey, + parents: &mut HashMap, +) -> Result<(), ParserError> { + let mut ancestor = Some(parent); + let mut occurrences = 1usize; + while let Some(key) = ancestor { + if key.name == child.name { + occurrences += 1; + if occurrences > MAX_SV_RECURSIVE_SPECIALIZATIONS { + return Err(sv_specialization_limit_error(child.name.clone())); + } + } + ancestor = parents.get(key); + } + parents.insert(child.clone(), parent.clone()); + Ok(()) +} + fn sv_specialization_limit_error(name: String) -> ParserError { ParserError::unsupported( sv::SV_FRONTEND_TRACKING_ISSUE, @@ -7463,6 +7471,90 @@ struct DynamicPackedWrite { window: Option, } +/// Recover a constant outer element for a checked dynamic bit select of a +/// one-bit packed element. Its only valid inner index is its declared bound. +/// An arbitrary dynamic unpacked element permits more than one index and must +/// retain its dynamic element addressing. +fn single_bit_select_window( + lsb: &sv::ir::ConstExpr, + width: usize, + constants: &HashMap, + types: &HashMap, +) -> Option { + use sv::ir::{BinaryOp, ConstExpr}; + fn selected<'a>( + mut expr: &'a ConstExpr, + constants: &HashMap, + types: &HashMap, + ) -> &'a ConstExpr { + while let ConstExpr::Mux { + condition, + then_expr, + else_expr, + } = expr + { + match sv::typecheck::eval_const_expr_with_types(condition, constants, types) { + Some(0) => expr = else_expr, + Some(_) => expr = then_expr, + None => break, + } + } + expr + } + let (base, offset) = split_dynamic_array_offset(lsb, constants, types)?; + let ConstExpr::Mux { + condition, + then_expr, + else_expr, + } = selected(base, constants, types) + else { + return None; + }; + let ConstExpr::Binary { + left, + op: BinaryOp::LogicAnd, + right, + } = selected(condition, constants, types) + else { + return None; + }; + let bound = |expr, expected| { + let ConstExpr::Binary { left, op, right } = selected(expr, constants, types) else { + return None; + }; + let ConstExpr::Ident(name) = left.as_ref() else { + return None; + }; + if *op != expected { + return None; + } + Some(( + name, + sv::typecheck::eval_const_expr_with_types(right, constants, types)?, + )) + }; + let lower = bound(left, BinaryOp::Ge)?; + let upper = bound(right, BinaryOp::Le)?; + if lower != upper { + return None; + } + let invalid = sv::typecheck::eval_const_expr_with_types(else_expr, constants, types)? + .checked_add(offset)?; + let width = i128::try_from(width).ok()?; + if (0..width).contains(&invalid) { + return None; + } + let mut checked_index = constants.clone(); + checked_index.insert(lower.0.clone(), lower.1); + let position = sv::typecheck::eval_const_expr_with_types(then_expr, &checked_index, types)? + .checked_add(offset)?; + if !(0..width).contains(&position) { + return None; + } + let position = usize::try_from(position).ok()?; + Some(BitAccess::new(position, position)) +} + /// For a run-time select inside one element of an unpacked array, such as /// `mem[1][i]`, the bits of that element: the constant part of the flattened /// position names the element, and the run-time part moves within it. @@ -7473,9 +7565,13 @@ fn runtime_select_window( constants: &HashMap, parameter_types: &HashMap, ) -> Option { - // One-bit elements have no bits within an element, and their run-time - // index has no stride to recognize. - if element_width <= 1 || element_width == width { + // A checked bit select inside a one-bit element can only write its zero + // bit. Preserve the constant outer element in both driver analysis and + // lowering; an arbitrary run-time array index remains unconstrained. + if element_width == 1 { + return single_bit_select_window(lsb, width, constants, parameter_types); + } + if element_width == 0 || element_width == width { return None; } let (base, offset) = split_dynamic_array_offset(lsb, constants, parameter_types)?; @@ -9238,6 +9334,14 @@ fn dynamic_array_element_subselection( if !is_dynamic { return None; } + // This is a dynamic bit inside one constant one-bit element, rather + // than a dynamic element of the whole array. Let the packed lowering + // retain the checked element window. + if packed_element_width == 1 + && single_bit_select_window(lsb, variable.width, constants, parameter_types).is_some() + { + return None; + } let (msb_base, msb_offset) = split_dynamic_array_offset(msb, constants, parameter_types)?; let (lsb_base, lsb_offset) = split_dynamic_array_offset(lsb, constants, parameter_types)?; if msb_base != lsb_base { @@ -9372,6 +9476,14 @@ fn dynamic_array_element_lvalue( if !is_dynamic { return None; } + // This is a dynamic bit inside one constant one-bit element, rather + // than a dynamic element of the whole array. Let the packed lowering + // retain the checked element window. + if packed_element_width == 1 + && single_bit_select_window(lsb, variable.width, constants, parameter_types).is_some() + { + return None; + } let (msb_base, msb_offset) = split_dynamic_array_offset(msb, constants, parameter_types)?; let (lsb_base, lsb_offset) = split_dynamic_array_offset(lsb, constants, parameter_types)?; if msb_base != lsb_base { diff --git a/crates/celox-sv-syntax/src/nodes.rs b/crates/celox-sv-syntax/src/nodes.rs index 7d4a6be5969..219e8a8fea3 100644 --- a/crates/celox-sv-syntax/src/nodes.rs +++ b/crates/celox-sv-syntax/src/nodes.rs @@ -960,6 +960,14 @@ pub struct VariableDeclaration { pub tokens: TokenRange, } +/// A named constraint block. Unsupported constraint forms retain their name +/// but no executable expressions, so randomization cannot silently ignore them. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct ClassConstraint { + pub name: Name, + pub expressions: Option>, +} + /// A class declaration (IEEE 1800-2023 8.3). Its body also remains an /// unconverted body item covering the same tokens. #[derive(Clone, Debug, Eq, PartialEq)] @@ -976,6 +984,7 @@ pub struct ClassDeclaration { pub interfaces: Vec, /// Whether the class declares constraints, including prototypes. pub has_constraints: bool, + pub constraints: Vec, /// The parameter port list `#(...)`, after which the parameters the /// body declares are local (8.25). pub parameter_ports: Option, diff --git a/crates/celox-sv-syntax/src/parser/classes.rs b/crates/celox-sv-syntax/src/parser/classes.rs index bed49079811..637f457812e 100644 --- a/crates/celox-sv-syntax/src/parser/classes.rs +++ b/crates/celox-sv-syntax/src/parser/classes.rs @@ -223,6 +223,7 @@ impl Parser<'_> { base, interfaces, has_constraints: false, + constraints: Vec::new(), parameter_ports, parameters: Vec::new(), type_aliases: Vec::new(), diff --git a/crates/celox-sv-syntax/src/parser/constraints.rs b/crates/celox-sv-syntax/src/parser/constraints.rs index 3dcdfc0bbc4..2469d9465da 100644 --- a/crates/celox-sv-syntax/src/parser/constraints.rs +++ b/crates/celox-sv-syntax/src/parser/constraints.rs @@ -1,5 +1,5 @@ //! Class constraint syntax validation. Constraints retain their opaque class -//! owner; no randomization or solver semantics are introduced here. +//! owner. Simple expression blocks also retain their expression nodes. use super::*; enum Job { @@ -32,10 +32,26 @@ impl Parser<'_> { class.has_constraints = true; } let prototype = self.eat("extern") || self.eat("pure"); - self.eat("static"); + let is_static = self.eat("static"); self.expect("constraint")?; - self.name()?; + let name = self.name()?; + if self.class_stack.last().is_some_and(|class| { + class + .constraints + .iter() + .any(|block| block.name.spelling == name.spelling) + }) { + return Err(self.error("duplicate constraint block")); + } + let mut expressions = Vec::new(); + let mut supported = !is_static; if self.eat(";") { + if let Some(class) = self.class_stack.last_mut() { + class.constraints.push(ClassConstraint { + name, + expressions: None, + }); + } return Ok(()); } if prototype { @@ -52,6 +68,7 @@ impl Parser<'_> { } jobs.push(Job::Block(solve)); if solve && self.eat("solve") { + supported = false; self.constraint_primary_list()?; self.expect("before")?; self.constraint_primary_list()?; @@ -74,32 +91,41 @@ impl Parser<'_> { } Job::Expression => { if self.eat("if") { + supported = false; self.expect("(")?; self.expression(0)?; self.expect(")")?; jobs.push(Job::Else); jobs.push(Job::Set); } else if self.eat("foreach") { + supported = false; self.foreach_header()?; jobs.push(Job::Set); } else if self.eat("disable") { + supported = false; self.expect("soft")?; self.constraint_primary()?; self.expect(";")?; } else if self.eat("unique") { + supported = false; self.constraint_ranges(false)?; self.expect(";")?; } else { let soft = self.eat("soft"); if soft { + supported = false; self.expression(0)?; } else { - self.constraint_condition()?; + let (expression, simple) = self.constraint_condition()?; + expressions.push(expression); + supported &= simple; } if !soft && self.eat("->") { + supported = false; jobs.push(Job::Set); } else { if self.eat("dist") { + supported = false; self.constraint_ranges(true)?; } self.expect(";")?; @@ -108,17 +134,25 @@ impl Parser<'_> { } } } + if let Some(class) = self.class_stack.last_mut() { + class.constraints.push(ClassConstraint { + name, + expressions: supported.then_some(expressions), + }); + } Ok(()) } - fn constraint_condition(&mut self) -> Result<()> { + fn constraint_condition(&mut self) -> Result<(ExprId, bool)> { // Keep the constraint-set arrow for the outer continuation. Equivalence // shares its expression precedence, so consume it explicitly here. - self.expression(2)?; + let expression = self.expression(2)?; + let mut simple = true; while self.eat("<->") { + simple = false; self.expression(2)?; } - Ok(()) + Ok((expression, simple)) } fn constraint_ranges(&mut self, distribution: bool) -> Result<()> { diff --git a/crates/celox-sv-syntax/src/parser/tests.rs b/crates/celox-sv-syntax/src/parser/tests.rs index c6b29330e73..53d0d1c822a 100644 --- a/crates/celox-sv-syntax/src/parser/tests.rs +++ b/crates/celox-sv-syntax/src/parser/tests.rs @@ -3043,3 +3043,14 @@ fn malformed_array_method_with_is_rejected() { ); } } + +#[test] +fn constraints_retain_simple_expressions_and_mark_other_forms() { + let tree = parse( + "class C; rand int x; constraint a { x > 0; x < 3; } constraint b { if (x) x == 1; } endclass", + ); + let blocks = &tree.classes[0].constraints; + assert_eq!(blocks[0].name.spelling, "a"); + assert_eq!(blocks[0].expressions.as_ref().unwrap().len(), 2); + assert!(blocks[1].expressions.is_none()); +} diff --git a/crates/celox-test-suite/src/sv/cases/hierarchy.vtest b/crates/celox-test-suite/src/sv/cases/hierarchy.vtest index d9a8121de40..891856da116 100644 --- a/crates/celox-test-suite/src/sv/cases/hierarchy.vtest +++ b/crates/celox-test-suite/src/sv/cases/hierarchy.vtest @@ -1738,3 +1738,25 @@ (assert_eq y (fourstate 0x55 0xa0)) (modify (set d 0x96)) (assert_eq y 0x96)) + +(case many_sibling_parameter_specializations + (source "sibling_specializations.sv" #" + module Leaf #(parameter ID=0)(input wire [7:0] x, output wire [7:0] q); + assign q=x ^ 8'(ID); + endmodule + module Top(input wire [7:0] x, output wire [7:0] first, last); + wire [7:0] lanes[65]; + for (genvar n=0; n<65; n=n+1) begin : siblings + Leaf #(.ID(n)) u(.x(x), .q(lanes[n])); + end + assign first=lanes[0]; + assign last=lanes[64]; + endmodule + "#) + (top Top) + (modify (set x 60)) + (assert_eq first 60) + (assert_eq last 124) + (modify (set x 255)) + (assert_eq first 255) + (assert_eq last 191)) diff --git a/crates/celox-test-suite/src/sv/cases/indexed_select.vtest b/crates/celox-test-suite/src/sv/cases/indexed_select.vtest index 65c69699a08..0af60134328 100644 --- a/crates/celox-test-suite/src/sv/cases/indexed_select.vtest +++ b/crates/celox-test-suite/src/sv/cases/indexed_select.vtest @@ -2185,3 +2185,75 @@ (assert_eq b2 (? (> cycle 1) (* (- cycle 1) 17) 0)) (assert_eq a4 (? (> cycle 3) (* (- cycle 3) 17) 0)) (assert_eq b4 (? (> cycle 3) (* (- cycle 3) 17) 0)))) + +(case disjoint_single_bit_array_drivers + (source "single_bit_drivers.sv" #" + module Top #(parameter BASE=0)(input logic signed [31:0] index, input logic [2:0] value, + output wire [2:0] q); + logic [BASE:BASE] ready[3]; + for (genvar n=0; n<3; n=n+1) begin : lanes + always_comb begin + ready[n] = '0; + ready[n][index] = value[n]; + end + assign q[n] = ready[n][BASE]; + end + endmodule + "#) + (top Top) + (modify (set index 0) (set value 5)) + (assert_eq q 5) + (modify (set value 2)) + (assert_eq q 2) + (modify (set value 0)) + (assert_eq q 0) + (modify (set value 7)) + (assert_eq q 7)) + +(case disjoint_shifted_single_bit_array_drivers + (source "single_bit_drivers.sv" #" + module Top #(parameter BASE=7)(input logic signed [31:0] index, input logic [2:0] value, + output wire [2:0] q); + logic [BASE:BASE] ready[3]; + for (genvar n=0; n<3; n=n+1) begin : lanes + always_comb begin + ready[n] = '0; + ready[n][index] = value[n]; + end + assign q[n] = ready[n][BASE]; + end + endmodule + "#) + (top Top) + (modify (set index 7) (set value 5)) + (assert_eq q 5) + (modify (set value 2)) + (assert_eq q 2) + (modify (set value 0)) + (assert_eq q 0) + (modify (set value 7)) + (assert_eq q 7)) + +(case disjoint_negative_single_bit_array_drivers + (source "single_bit_drivers.sv" #" + module Top #(parameter BASE=-2)(input logic signed [31:0] index, input logic [2:0] value, + output wire [2:0] q); + logic [BASE:BASE] ready[3]; + for (genvar n=0; n<3; n=n+1) begin : lanes + always_comb begin + ready[n] = '0; + ready[n][index] = value[n]; + end + assign q[n] = ready[n][BASE]; + end + endmodule + "#) + (top Top) + (modify (set index (trunc 32 -2)) (set value 5)) + (assert_eq q 5) + (modify (set value 2)) + (assert_eq q 2) + (modify (set value 0)) + (assert_eq q 0) + (modify (set value 7)) + (assert_eq q 7)) diff --git a/crates/celox-vpi/src/bin/celox.rs b/crates/celox-vpi/src/bin/celox.rs index 225e09851ca..e5829c56bd8 100644 --- a/crates/celox-vpi/src/bin/celox.rs +++ b/crates/celox-vpi/src/bin/celox.rs @@ -839,35 +839,18 @@ fn compile_native_design(design: &Design) -> Result .iter() .map(|(text, path)| (text.as_str(), path.as_path())) .collect(); - let untimed = configure_sv( + // VPI advances time and dispatches callbacks even for a process-free + // DUT. Compile its process-capable image directly, rather than first + // compiling an untimed image and repeating analysis and optimization + // when that builder discovers a process. + let simulation = configure_sv( design, - celox::Simulator::from_sv_sources(refs.clone(), &design.top), + celox::Simulation::from_sv_sources(refs, &design.top), ) - .compile_native(); - let image = match untimed { - Ok(simulator) => { - report_warnings(simulator.warnings())?; - simulator.into_program_image() - } - // A design with processes runs as a timed simulation, in step - // with the VPI time callbacks. - Err(error) - if matches!( - error.kind(), - celox::SimulatorErrorKind::ProcessRequiresSimulation(_) - ) => - { - let simulation = configure_sv( - design, - celox::Simulation::from_sv_sources(refs, &design.top), - ) - .compile_native() - .map_err(|error| format!("compilation failed:\n{error}"))?; - report_warnings(simulation.warnings())?; - simulation.into_program_image() - } - Err(error) => return Err(format!("compilation failed:\n{error}")), - }; + .compile_native() + .map_err(|error| format!("compilation failed:\n{error}"))?; + report_warnings(simulation.warnings())?; + let image = simulation.into_program_image(); return Ok(image); } #[cfg(not(feature = "systemverilog"))] diff --git a/crates/celox/tests/frontends/systemverilog/hierarchy.rs b/crates/celox/tests/frontends/systemverilog/hierarchy.rs index 1e0a3cd893c..8c893ac3d94 100644 --- a/crates/celox/tests/frontends/systemverilog/hierarchy.rs +++ b/crates/celox/tests/frontends/systemverilog/hierarchy.rs @@ -776,3 +776,9 @@ fn rejects_malformed_non_ansi_port_declarations() { assert!(error.contains(message), "{source}: {error}"); } } + +sv_backends! { + fn many_sibling_parameter_specializations(sim) { + @case "hierarchy::many_sibling_parameter_specializations"; + } +} diff --git a/crates/celox/tests/frontends/systemverilog/indexed_select.rs b/crates/celox/tests/frontends/systemverilog/indexed_select.rs index 6350b87d6f7..80f2ce3f756 100644 --- a/crates/celox/tests/frontends/systemverilog/indexed_select.rs +++ b/crates/celox/tests/frontends/systemverilog/indexed_select.rs @@ -403,3 +403,44 @@ sv_backends! { @case "indexed_select::generated_pipeline_with_explicit_generate_branches"; } } + +sv_backends! { + fn disjoint_single_bit_array_drivers(sim) { + @case "indexed_select::disjoint_single_bit_array_drivers"; + } +} + +// Verilator 5.052 truncates the bit index of a one-bit packed element and +// writes its zero bit for index 2. Keep the out-of-range check local; the +// disjoint-driver behavior at valid indices is shared with both adapters. +sv_backends! { + fn single_bit_array_drivers_ignore_invalid_inner_indices(sim) { + @setup { + let source = "module Top(input logic [1:0] index, input logic [2:0] value, + output wire [2:0] q); + logic [0:0] ready[3]; + for (genvar n=0; n<3; n=n+1) begin : lanes + always_comb begin ready[n]='0; ready[n][index]=value[n]; end + assign q[n]=ready[n][0]; + end + endmodule"; + } + @build Simulator::from_sv_sources(vec![(source, Path::new("single_bit_bounds.sv"))], "Top"); + let index=sim.signal("index"); + let value=sim.signal("value"); + let q=sim.signal("q"); + for (position, bits, expected) in [(0u8,5u8,5u8),(1,5,0),(2,5,0),(0,2,2)] { + sim.modify(|io| {io.set(index,position);io.set(value,bits);}).unwrap(); + assert_eq!(sim.get(q),BigUint::from(expected)); + } + } +} + +sv_backends! { + fn disjoint_shifted_single_bit_array_drivers(sim) { + @case "indexed_select::disjoint_shifted_single_bit_array_drivers"; + } + fn disjoint_negative_single_bit_array_drivers(sim) { + @case "indexed_select::disjoint_negative_single_bit_array_drivers"; + } +} diff --git a/crates/celox/tests/frontends/systemverilog/review_regressions.rs b/crates/celox/tests/frontends/systemverilog/review_regressions.rs index 9d03cf15da5..5c9d4afab27 100644 --- a/crates/celox/tests/frontends/systemverilog/review_regressions.rs +++ b/crates/celox/tests/frontends/systemverilog/review_regressions.rs @@ -8974,3 +8974,42 @@ fn net_alias_coalescing_retains_distinct_and_variable_drivers() { assert!(error.contains(diagnostic), "{error}"); } } + +#[test] +fn single_bit_array_driver_windows_still_reject_overlaps() { + for source in [ + "module Top(input logic index, input logic a, b, output logic [0:0] q[2]); + always_comb begin q[0]='0; q[0][index]=a; end + always_comb begin q[0]='0; q[0][index]=b; end endmodule", + "module Top(input logic index, input logic a, b, output logic [0:0] q[2]); + always_comb q[index]=a; + always_comb q[0]=b; endmodule", + ] { + let error = cranelift_build_error(source); + assert!(error.contains("multiple variable drivers"), "{error}"); + } +} + +#[test] +fn mixed_hierarchies_accept_many_sibling_specializations() { + let veryl = "module Top(x: input logic<8>, y: output logic<8>) { inst tree: $sv::Root(x, y); }"; + let sv = "module Leaf #(parameter ID=0)(input wire [7:0] x, output wire [7:0] y); + assign y=x ^ 8'(ID); endmodule + module Root(input wire [7:0] x, output wire [7:0] y); + wire [7:0] lanes[65]; + for(genvar n=0;n<65;n=n+1) begin: g + Leaf #(.ID(n)) u(.x(x),.y(lanes[n])); + end + assign y=lanes[64]; endmodule"; + let mut sim = Simulator::from_mixed_sources( + vec![(veryl, Path::new("top.veryl"))], + vec![(sv, Path::new("siblings.sv"))], + "Top", + ) + .build_cranelift() + .unwrap(); + let x = sim.signal("x"); + let y = sim.signal("y"); + sim.modify(|io| io.set(x, 60u8)).unwrap(); + assert_eq!(sim.get(y), BigUint::from(124u8)); +}