Merge branch 'feat/semantic-registry-s4' into feat/semantic-registry

This commit is contained in:
elforeign committed 2026-11-24 03:40:09 -06:00
commit b541dce0cc
3 files changed
+671

No files matched your search

+1
View File
@@ -24,6 +24,7 @@ either path. The [changelog](../CHANGELOG.md) records notable changes.
- [Instruction coverage](shaders/instruction-coverage.md) — Desktop gfx1030 instruction forms, operand limits, and CPU and GPU results.
- [Semantic coverage](shaders/semantic-coverage.md) — Generated per-family counts of identified, declared, decoded, lowered and verified gfx1030 forms.
- [SOP2 scalar ALU](shaders/scalar-alu.md) — Supported scalar add, subtract and bitwise forms, their SCC rules and sources.
- [Semantic registry](shaders/semantic-registry.md) — How to add an instruction form: registry fields, validation, generation and the independence rule.
- [VOPC integer compares](shaders/vector-compare.md) — Wave32 compare forms, the VCC/EXEC contract, runtime `s_cbranch_vccz` and the Metal mapping.
- [Metal Shading Language generation](shaders/msl.md) and [independent CPU reference](shaders/reference-interpreter.md) — Translation rules and separate CPU execution models.
+205
View File
@@ -0,0 +1,205 @@
# Adding an instruction through the semantic registry
The semantic registry is a data file that declares what each supported gfx1030
instruction form does. A generator checks it and turns it into Rust tables that
the decoder uses. This page explains where entries live, what each field means,
how to check and regenerate the tables, and what the generator does not do for
you.
The registry covers the nine SOP2 forms listed in [SOP2 scalar ALU](scalar-alu.md).
## Files
| File | Role |
| --- | --- |
| `crates/isa/semantics/rdna2.toml` | The registry. Data only: every value comes from a closed vocabulary. |
| `crates/isa/generate_semantics.py` | Validates the registry and writes the Rust tables. Python 3.11 or newer, standard library only. |
| `crates/isa/data/rdna2.jsonl` | Pinned snapshot of the AMD machine-readable ISA XML, used to cross-check identity and operands. |
| `crates/isa/src/semantics_gen.rs` | Generated output. Never edit it by hand. |
| `crates/isa/src/semantics.rs` | The Rust types the generated tables use (`FormSemantics`, `Operation`, `SccEffect` and so on). |
| `crates/isa/src/primitive.rs` | The shared integer primitives that the generated `evaluate` calls. |
| `tests/semantics_generator/` | Unit tests for the generator. |
## Fields
The top of the file holds:
- `schema`: must be `1`.
- `architecture`: must be `"gfx1030"`.
- `source_sha256`: must equal the `sha256` on the `source` line of
`crates/isa/data/rdna2.jsonl`, so the registry is always checked against the
snapshot it was written for.
- `[documents.<name>]`: the public documents that spec references cite. Only
`guide` (the AMD RDNA 2 ISA reference guide) and `xml` (the AMD
machine-readable ISA) are allowed.
- `[operand_rules.<name>]`: an operand rule shared by a whole family. The
decoder implements each rule once, and the generator only accepts a rule
whose declaration matches the decoder's implementation exactly. Today there
is one rule, `sop2_sgpr`: an SGPR destination `s0`-`s105`, two scalar sources
(an SGPR, an inline integer -16 to 64, or a literal word) and at most one
literal. Its `unsupported` list names the encodings the rule rejects, which
stay unsupported instead of being guessed.
Each `[[form]]` entry has exactly these fields. A missing or unknown field is an
error.
| Field | Meaning | Allowed values |
| --- | --- | --- |
| `name` | XML instruction name, the form's stable identity | upper-case, e.g. `S_ADD_U32` |
| `family` | Encoding family; must match the XML base encoding | e.g. `SOP2` |
| `opcode` | Opcode; must match the XML | non-negative integer |
| `variant` | Rust enum variant of the typed operation | CamelCase, e.g. `AddU32` |
| `operation` | The primitive the form uses | `add`, `sub`, `and`, `or`, `xor` |
| `signedness` | How operands are read | `unsigned`, `signed`, `bitwise` (`bitwise` exactly for `and`, `or`, `xor`) |
| `carry_in` | Whether the form reads SCC as carry-in or borrow-in | `none`, `scc` (`scc` only for unsigned `add` and `sub`) |
| `width` | Operand and result width in bits | `32` |
| `scc` | What the form writes to SCC | `carry_out`, `borrow`, `signed_overflow`, `nonzero`, `unchanged` |
| `vcc`, `exec` | Effect on VCC and EXEC, stated rather than implied | `unchanged` |
| `wave` | Wave sizes the form is valid in | `any`, `wave32` |
| `operands` | Name of an `[operand_rules]` entry for the same family | e.g. `sop2_sgpr` |
| `spec` | References `{ document, section, page }` | at least one `guide` reference with a page above 0 |
| `verify` | Evidence the form needs before it counts as verified | `reference`, `independent`, `metal`, `llvm_encoding` |
The `operation` and `signedness` pair picks one primitive, and that primitive
fixes the `scc` value:
| `operation` / `signedness` | Required `scc` | Primitive | Reads carry-in |
| --- | --- | --- | --- |
| `add` / `unsigned` | `carry_out` | `add_carry_u32` | allowed |
| `sub` / `unsigned` | `borrow` | `sub_borrow_u32` | allowed |
| `add` / `signed` | `signed_overflow` | `add_overflow_i32` | no |
| `sub` / `signed` | `signed_overflow` | `sub_overflow_i32` | no |
| `and`, `or`, `xor` / `bitwise` | `nonzero` | `and_nonzero_b32`, `or_nonzero_b32`, `xor_nonzero_b32` | no |
Behaviour is chosen only from these declared fields, never from the mnemonic.
## What the validator checks
`validate` reports every error it finds, not only the first (a form with a missing field is not checked further). Besides the
vocabularies above, it rejects:
- contradictions: a declared `scc` or `carry_in` that the primitive does not
have, `bitwise` on an arithmetic operation or the reverse;
- duplicates: the same `name`, the same `(family, opcode)` or the same
`variant` declared twice;
- XML disagreements: a family with no XML encoding, a form with no default XML
variant, a different opcode, an SCC input or output the XML does not show (or
that the declaration omits), an operand width other than `width`, a signed
declaration on unsigned XML formats or the reverse, an operand direction that
differs, and XML operands the operand rule does not cover;
- references: a spec citing an undeclared document, a bad section or page, or
no guide page at all;
- operand rules the decoder does not implement, or whose declaration differs
from the implemented one.
## What the generator does not do
- **The XML gives identity and encodings only.** The snapshot confirms the
name, family, opcode, operand fields, widths, number formats and whether SCC
is read or written. It says nothing about the arithmetic. Behaviour comes from
the AMD guide, cited in `spec`, through the closed primitive table.
- **It does not invent behaviour.** A form whose operation, signedness or
operand rule is not already implemented is rejected. Adding a new operation
means hand-writing a primitive in `primitive.rs`, a variant in
`semantics.rs` and a row in the generator's vocabulary tables, reviewed like
any other code.
- **Undeclared forms stay unsupported.** The generated `from_word` returns
`None` for every opcode not in the registry, and the decoder reports
`UnsupportedOpcode`. Nothing falls back to a guess or a no-op.
- **It does not write tests or reference semantics.** The reference
interpreter (`crates/ref`) and the independent interpreter
(`tests/validation/independent_ref.rs`) never read the registry or the
generated code, and their known-answer tests are written by hand from the
guide. That independence is what lets them catch a wrong registry entry; keep
it when you add a form. Agreement with these references is agreement with a
reading of the public AMD guide, not with Xbox hardware.
## Commands
Run these from the repository root. `python3` must be 3.11 or newer.
```sh
# Check the registry only.
python3 crates/isa/generate_semantics.py validate
# Validate, then rewrite crates/isa/src/semantics_gen.rs.
python3 crates/isa/generate_semantics.py generate
# Validate and regenerate in memory; exit 1 if the committed file is stale. Never writes.
python3 crates/isa/generate_semantics.py --check
# Generator unit tests.
python3 -m unittest discover -s tests/semantics_generator
# The XML metadata tables the registry is cross-checked against are still current.
python3 crates/isa/generate_rdna2_meta.py --check
# Rust tests of the generated tables and the decoder that uses them.
cargo test --locked -p xenora-isa -p xenora-decoder
# Independent CPU validation.
cargo test --locked -p xenora-semantic-review
# Native GPU correctness on Apple silicon.
scripts/test-gpu.sh
```
The LLVM encoding corpus check needs an LLVM build with the AMDGPU target:
```sh
python3 crates/isa/tests/llvm/corpus.py --llvm-bin /path/to/llvm/bin --check
```
## Worked example: `s_addc_u32`
`s_addc_u32` adds two 32-bit sources plus SCC and writes the carry-out of
bit 31 to SCC (guide section 12.1, page 102; SCC rules in section 5.3, page 33).
Its registry entry is:
```toml
[[form]]
name = "S_ADDC_U32"
family = "SOP2"
opcode = 4
variant = "AddcU32"
operation = "add"
signedness = "unsigned"
carry_in = "scc"
width = 32
scc = "carry_out"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [
{ document = "guide", section = "12.1", page = 102 },
{ document = "guide", section = "5.3", page = 33 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
```
How each field is checked:
1. The XML snapshot has a default `ENC_SOP2` variant named `S_ADDC_U32` with
opcode 4, so `name`, `family` and `opcode` agree.
2. That XML variant reads and writes SCC, which matches `carry_in = "scc"` and
an `scc` other than `unchanged`.
3. `add` / `unsigned` selects `add_carry_u32`, which requires
`scc = "carry_out"` and accepts a carry-in.
4. The XML `SDST`, `SSRC0` and `SSRC1` operands are 32-bit `FMT_NUM_U32`
fields, which matches `width = 32`, `unsigned` and the `sop2_sgpr` rule.
From this entry the generator emits, in `semantics_gen.rs`, the `AddcU32`
variant of `ScalarAluOp`, its `from_word` arm (`0x8200_0000`), the mnemonic
`s_addc_u32`, `reads_scc() == true`, an `evaluate` arm that calls
`primitive::add_carry_u32(src0, src1, carry_in)`, and a `FormSemantics` row.
To add a form the same way:
1. Confirm its behaviour in the AMD guide and note the section and page.
2. Check that an existing primitive and operand rule cover it. If not, the
form needs hand-written code first (see above).
3. Add a `[[form]]` entry and run `validate` until it reports no errors.
4. Run `generate` and commit the registry and `semantics_gen.rs` together.
5. Add known-answer tests to the reference and independent interpreters by
hand, then run every command in [Commands](#commands).
@@ -0,0 +1,465 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Unit tests for crates/isa/generate_semantics.py.
Each rejection rule is fed a small in-memory registry that breaks exactly that
rule, checked against a tiny hand-written XML snapshot. The real registry and
snapshot are only read, never edited. Run from the repository root:
python3 -m unittest discover -s tests/semantics_generator
"""
import copy
import importlib.util
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
SCRIPT = ROOT / "crates/isa/generate_semantics.py"
_spec = importlib.util.spec_from_file_location("generate_semantics", SCRIPT)
gen = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(gen)
SHA = "0" * 64
# Minimal stand-in for crates/isa/data/rdna2.jsonl: the SOP2 encoding and the
# default variants of the four forms the fixture declares (values copied from
# the AMD XML snapshot).
U32 = "FMT_NUM_U32"
I32 = "FMT_NUM_I32"
def _operands(data_format, scc_in=False):
rows = [
["SDST", data_format, "OPR_SDST", 32, False, True, False, True],
["SSRC0", data_format, "OPR_SSRC_NOLDS", 32, True, False, False, True],
["SSRC1", data_format, "OPR_SSRC_NOLDS", 32, True, False, False, True],
["", "FMT_NUM_B1", "OPR_SSRC_SPECIAL_SCC", 1, False, True, True, True],
]
if scc_in:
rows.append(["", "FMT_NUM_B1", "OPR_SSRC_SPECIAL_SCC", 1, True, False, True, True])
return rows
def snapshot():
sop2_base = 0x80000000
encoding = {
"name": "ENC_SOP2",
"bits": 32,
"fields": [
["SSRC0", [[0, 8]]], ["SSRC1", [[8, 8]]], ["SDST", [[16, 7]]],
["OP", [[23, 7]]], ["ENCODING", [[30, 2]]],
],
"identifier_mask": 0xFF800000,
"identifiers": [sop2_base | (op << 23) for op in (0, 2, 4, 14)],
}
variants = {}
for name, opcode, operands in (
("S_ADD_U32", 0, _operands(U32)),
("S_ADD_I32", 2, _operands(I32)),
("S_ADDC_U32", 4, _operands(U32, scc_in=True)),
("S_AND_B32", 14, _operands(U32)),
):
variants[(name, "ENC_SOP2")] = {
"instruction": name, "encoding": "ENC_SOP2", "opcode": opcode, "operands": operands,
}
return {"source": {"sha256": SHA}, "encodings": {"ENC_SOP2": encoding}, "variants": variants}
def _form(name, opcode, variant, operation, signedness, scc, carry_in="none"):
return {
"name": name, "family": "SOP2", "opcode": opcode, "variant": variant,
"operation": operation, "signedness": signedness, "carry_in": carry_in,
"width": 32, "scc": scc, "vcc": "unchanged", "exec": "unchanged", "wave": "any",
"operands": "sop2_sgpr",
"spec": [{"document": "guide", "section": "12.1", "page": 101}],
"verify": ["reference", "independent"],
}
def registry():
rule = copy.deepcopy(gen.OPERAND_RULES["sop2_sgpr"]["shape"])
rule["unsupported"] = ["dst_vcc", "two_literals"]
return {
"schema": 1,
"architecture": "gfx1030",
"source_sha256": SHA,
"documents": {"guide": {"title": "guide"}, "xml": {"title": "xml"}},
"operand_rules": {"sop2_sgpr": rule},
"form": [
_form("S_ADD_U32", 0, "AddU32", "add", "unsigned", "carry_out"),
_form("S_ADD_I32", 2, "AddI32", "add", "signed", "signed_overflow"),
_form("S_ADDC_U32", 4, "AddcU32", "add", "unsigned", "carry_out", carry_in="scc"),
_form("S_AND_B32", 14, "AndB32", "and", "bitwise", "nonzero"),
],
}
def form(reg, name):
return next(item for item in reg["form"] if item["name"] == name)
class Validate(unittest.TestCase):
def errors(self, reg, snap=None):
return gen.validate(reg, snap if snap is not None else snapshot())
def rejects(self, reg, fragment, snap=None):
errors = self.errors(reg, snap)
self.assertTrue(
any(fragment in error for error in errors),
f"expected an error containing {fragment!r}, got {errors}",
)
# ---- acceptance ----
def test_accepts_the_fixture(self):
self.assertEqual(self.errors(registry()), [])
def test_accepts_the_real_registry(self):
self.assertEqual(gen.validate(gen.load_registry(), gen.load_snapshot()), [])
# ---- top level ----
def test_rejects_wrong_schema(self):
reg = registry()
reg["schema"] = 2
self.rejects(reg, "schema 2 is not 1")
def test_rejects_source_sha256_mismatch(self):
reg = registry()
reg["source_sha256"] = "f" * 64
self.rejects(reg, "source_sha256 does not match")
def test_rejects_unknown_top_level_key(self):
reg = registry()
reg["notes"] = "x"
self.rejects(reg, "unknown top-level keys ['notes']")
def test_rejects_empty_registry(self):
reg = registry()
reg["form"] = []
self.rejects(reg, "declares no forms")
# ---- incomplete or unknown fields ----
def test_rejects_missing_required_field(self):
reg = registry()
del form(reg, "S_ADD_U32")["scc"]
self.rejects(reg, "S_ADD_U32: incomplete, missing ['scc']")
def test_rejects_unknown_form_key(self):
reg = registry()
form(reg, "S_ADD_U32")["expression"] = "a + b"
self.rejects(reg, "S_ADD_U32: unknown keys ['expression']")
# ---- closed vocabularies ----
def test_rejects_unknown_operation(self):
reg = registry()
form(reg, "S_ADD_U32")["operation"] = "mul"
self.rejects(reg, "S_ADD_U32: unknown operation 'mul'")
def test_rejects_unknown_scc_effect(self):
reg = registry()
form(reg, "S_ADD_U32")["scc"] = "overflow"
self.rejects(reg, "S_ADD_U32: unknown scc 'overflow'")
def test_rejects_unknown_mask_effect(self):
reg = registry()
form(reg, "S_ADD_U32")["vcc"] = "written"
self.rejects(reg, "S_ADD_U32: unknown vcc 'written'")
def test_rejects_unsupported_width(self):
reg = registry()
form(reg, "S_ADD_U32")["width"] = 64
self.rejects(reg, "S_ADD_U32: width 64 is not supported")
def test_rejects_unknown_evidence(self):
reg = registry()
form(reg, "S_ADD_U32")["verify"] = ["reference", "hardware"]
self.rejects(reg, "S_ADD_U32: unknown verification requirement")
def test_rejects_empty_evidence(self):
reg = registry()
form(reg, "S_ADD_U32")["verify"] = []
self.rejects(reg, "S_ADD_U32: no verification requirement")
# ---- contradictions ----
def test_rejects_bitwise_operation_declared_signed(self):
reg = registry()
form(reg, "S_AND_B32")["signedness"] = "signed"
self.rejects(reg, "S_AND_B32: signedness signed contradicts operation and")
def test_rejects_carry_in_on_logical_operation(self):
reg = registry()
form(reg, "S_AND_B32")["carry_in"] = "scc"
self.rejects(reg, "S_AND_B32: carry_in scc contradicts and/bitwise")
def test_rejects_carry_out_on_signed_form(self):
reg = registry()
form(reg, "S_ADD_I32")["scc"] = "carry_out"
self.rejects(reg, "S_ADD_I32: scc carry_out contradicts add/signed")
def test_rejects_scc_unchanged_on_a_form_that_writes_it(self):
# Declared as preserving SCC while the primitive and the XML both write it.
reg = registry()
form(reg, "S_ADD_U32")["scc"] = "unchanged"
self.rejects(reg, "S_ADD_U32: scc unchanged contradicts add/unsigned")
self.rejects(reg, "S_ADD_U32: scc unchanged contradicts the XML SCC output")
def test_rejects_carry_in_the_xml_does_not_read(self):
reg = registry()
form(reg, "S_ADD_U32")["carry_in"] = "scc"
self.rejects(reg, "S_ADD_U32: carry_in scc contradicts the XML SCC input")
def test_rejects_signedness_contradicting_xml_format(self):
reg = registry()
f = form(reg, "S_ADD_I32")
f["signedness"], f["scc"] = "unsigned", "carry_out"
self.rejects(reg, "S_ADD_I32: signedness unsigned contradicts XML format FMT_NUM_I32")
# ---- identity against the XML snapshot ----
def test_rejects_opcode_mismatch(self):
reg = registry()
form(reg, "S_ADD_U32")["opcode"] = 1
self.rejects(reg, "S_ADD_U32: opcode 1 disagrees with the XML opcode 0")
def test_rejects_family_mismatch(self):
reg = registry()
form(reg, "S_ADD_U32")["family"] = "SOPC"
self.rejects(reg, "S_ADD_U32: operand rule sop2_sgpr is for SOP2")
self.rejects(reg, "S_ADD_U32: family SOPC has no XML encoding ENC_SOPC")
def test_rejects_form_absent_from_the_xml(self):
reg = registry()
reg["form"].append(_form("S_MUL_I32", 38, "MulI32", "add", "signed", "signed_overflow"))
self.rejects(reg, "S_MUL_I32: no default ENC_SOP2 variant in the XML snapshot")
# ---- duplicates ----
def test_rejects_duplicate_name(self):
reg = registry()
reg["form"].append(copy.deepcopy(form(reg, "S_ADD_U32")))
self.rejects(reg, "S_ADD_U32: duplicate name S_ADD_U32")
def test_rejects_same_encoding_claimed_twice(self):
reg = registry()
twin = copy.deepcopy(form(reg, "S_ADD_U32"))
twin["name"], twin["variant"] = "S_ADD_U32_COPY", "AddU32Copy"
reg["form"].append(twin)
self.rejects(reg, "S_ADD_U32_COPY: duplicate opcode ('SOP2', 0)")
def test_rejects_duplicate_variant(self):
reg = registry()
form(reg, "S_ADD_I32")["variant"] = "AddU32"
self.rejects(reg, "S_ADD_I32: duplicate variant AddU32")
# ---- references ----
def test_rejects_missing_guide_reference(self):
reg = registry()
form(reg, "S_ADD_U32")["spec"] = [{"document": "xml", "section": "1", "page": 0}]
self.rejects(reg, "S_ADD_U32: missing a guide section and page reference")
def test_rejects_undeclared_document(self):
reg = registry()
form(reg, "S_ADD_U32")["spec"].append({"document": "blog", "section": "1", "page": 1})
self.rejects(reg, "S_ADD_U32: spec cites undeclared document 'blog'")
# ---- operand rules ----
def test_rejects_unknown_operand_rule_on_a_form(self):
reg = registry()
form(reg, "S_ADD_U32")["operands"] = "vop2_vgpr"
self.rejects(reg, "S_ADD_U32: unknown operand rule 'vop2_vgpr'")
def test_rejects_operand_rule_the_decoder_does_not_implement(self):
reg = registry()
reg["operand_rules"]["vop2_vgpr"] = {"family": "VOP2"}
self.rejects(reg, "operand rule vop2_vgpr: not implemented by the decoder")
def test_rejects_operand_rule_shape_differing_from_the_decoder(self):
reg = registry()
reg["operand_rules"]["sop2_sgpr"]["max_literals"] = 2
self.rejects(reg, "operand rule sop2_sgpr: declaration differs")
def test_rejects_unknown_unsupported_combo(self):
reg = registry()
reg["operand_rules"]["sop2_sgpr"]["unsupported"].append("dst_lds")
self.rejects(reg, "operand rule sop2_sgpr: unknown unsupported combos ['dst_lds']")
def test_rejects_duplicate_unsupported_combo(self):
reg = registry()
reg["operand_rules"]["sop2_sgpr"]["unsupported"].append("dst_vcc")
self.rejects(reg, "operand rule sop2_sgpr: duplicate unsupported combos")
# ---- remaining vocabulary, identity and reference rules ----
def test_rejects_wrong_architecture(self):
reg = registry()
reg["architecture"] = "gfx1100"
self.rejects(reg, "architecture 'gfx1100' is not gfx1030")
def test_rejects_unknown_document(self):
reg = registry()
reg["documents"]["blog"] = {"title": "blog"}
self.rejects(reg, "unknown document blog")
def test_rejects_unknown_signedness_carry_in_exec_and_wave(self):
for key, value in (
("signedness", "float"), ("carry_in", "vcc"), ("exec", "written"), ("wave", "wave64"),
):
with self.subTest(key=key):
reg = registry()
form(reg, "S_ADD_U32")[key] = value
self.rejects(reg, f"S_ADD_U32: unknown {key} {value!r}")
def test_rejects_invalid_name_variant_and_opcode(self):
for key, value, fragment in (
("name", "s_add_u32", "s_add_u32: invalid name"),
("variant", "add_u32", "S_ADD_U32: invalid variant 'add_u32'"),
("opcode", -1, "S_ADD_U32: invalid opcode"),
("opcode", True, "S_ADD_U32: invalid opcode"),
):
with self.subTest(key=key, value=value):
reg = registry()
form(reg, "S_ADD_U32")[key] = value
self.rejects(reg, fragment)
def test_rejects_declaration_no_primitive_implements(self):
reg = registry()
form(reg, "S_AND_B32")["operation"] = "sub"
self.rejects(reg, "S_AND_B32: no primitive implements sub/bitwise")
def test_rejects_duplicate_evidence(self):
reg = registry()
form(reg, "S_ADD_U32")["verify"] = ["reference", "reference"]
self.rejects(reg, "S_ADD_U32: duplicate verification requirement")
def test_rejects_malformed_spec_references(self):
for ref, fragment in (
({"document": "guide", "section": "12.1"}, "spec reference needs exactly document, section, page"),
({"document": "guide", "section": "12.x", "page": 101}, "invalid spec section '12.x'"),
({"document": "guide", "section": "12.1", "page": -1}, "invalid spec page"),
):
with self.subTest(ref=ref):
reg = registry()
form(reg, "S_ADD_U32")["spec"].append(ref)
self.rejects(reg, f"S_ADD_U32: {fragment}")
def test_rejects_guide_reference_without_a_page(self):
reg = registry()
form(reg, "S_ADD_U32")["spec"] = [{"document": "guide", "section": "12.1", "page": 0}]
self.rejects(reg, "S_ADD_U32: missing a guide section and page reference")
def test_rejects_opcode_outside_the_encoding_identifiers(self):
snap = snapshot()
snap["encodings"]["ENC_SOP2"]["identifiers"].remove(0x80000000 | (14 << 23))
self.rejects(registry(), "S_AND_B32: opcode 14 is not an identifier of ENC_SOP2", snap)
def test_rejects_xml_operand_disagreements(self):
cases = (
("missing", lambda ops: ops.pop(2), "S_ADD_U32: XML has no operand SSRC1"),
("width", lambda ops: ops[1].__setitem__(3, 64), "S_ADD_U32: SSRC0 is 64 bits in the XML"),
("direction", lambda ops: ops[0].__setitem__(4, True),
"S_ADD_U32: SDST direction disagrees with the XML"),
("extra", lambda ops: ops.append(["SIMM16", U32, "OPR_SIMM16", 16, True, False, False, True]),
"S_ADD_U32: XML operands ['SIMM16'] are not covered by rule sop2_sgpr"),
)
for label, change, fragment in cases:
with self.subTest(case=label):
snap = snapshot()
change(snap["variants"][("S_ADD_U32", "ENC_SOP2")]["operands"])
self.rejects(registry(), fragment, snap)
def _reorder(value):
"""Reverse the key order of every mapping, keeping list order."""
if isinstance(value, dict):
return {key: _reorder(value[key]) for key in reversed(list(value))}
if isinstance(value, list):
return [_reorder(item) for item in value]
return value
class Render(unittest.TestCase):
def test_two_renders_are_identical(self):
self.assertEqual(gen.render(registry(), snapshot()), gen.render(registry(), snapshot()))
def test_render_ignores_mapping_key_order(self):
reg = registry()
reordered = _reorder(reg)
self.assertNotEqual(list(reg["form"][0]), list(reordered["form"][0]))
self.assertEqual(gen.render(reg, snapshot()), gen.render(reordered, snapshot()))
def test_dispatch_is_sorted_by_opcode(self):
reg = registry()
reg["form"].reverse()
text = gen.render(reg, snapshot())
body = text.split("match word & ", 1)[1].split("_ => None", 1)[0]
words = [line.split(" => ")[0].strip() for line in body.splitlines()[1:] if "=>" in line]
self.assertEqual(words, sorted(words))
self.assertEqual(len(words), 4)
def test_real_registry_renders_the_committed_file(self):
text = gen.render(gen.load_registry(), gen.load_snapshot())
self.assertEqual(text, gen.RUST.read_text(encoding="utf-8"))
class CommandLine(unittest.TestCase):
def run_cli(self, *arguments):
return subprocess.run(
[sys.executable, str(SCRIPT), *map(str, arguments)],
capture_output=True, text=True, check=False,
)
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
self.dir = Path(self.tmp.name)
def test_check_passes_on_the_committed_file(self):
result = self.run_cli("--check")
self.assertEqual(result.returncode, 0, result.stderr)
def test_check_passes_on_a_fresh_file_and_fails_on_a_stale_one(self):
output = self.dir / "semantics_gen.rs"
result = self.run_cli("generate", "--output", output)
self.assertEqual(result.returncode, 0, result.stderr)
fresh = output.read_text(encoding="utf-8")
self.assertEqual(self.run_cli("--check", "--output", output).returncode, 0)
output.write_text(fresh.replace("pub const GENERATED_SCHEMA: u32 = 1;", "pub const GENERATED_SCHEMA: u32 = 2;"))
stale = self.run_cli("--check", "--output", output)
self.assertEqual(stale.returncode, 1)
self.assertIn("is stale", stale.stderr)
# --check never writes.
self.assertNotEqual(output.read_text(encoding="utf-8"), fresh)
def test_check_fails_when_the_generated_file_is_missing(self):
self.assertEqual(self.run_cli("--check", "--output", self.dir / "absent.rs").returncode, 1)
def test_invalid_registry_fails_every_mode_without_writing(self):
bad = self.dir / "rdna2.toml"
text = gen.REGISTRY.read_text(encoding="utf-8")
bad.write_text(text.replace("\nschema = 1\n", "\nschema = 2\n", 1), encoding="utf-8")
output = self.dir / "out.rs"
for mode in (("validate",), ("generate",), ("--check",)):
result = self.run_cli(*mode, "--registry", bad, "--output", output)
self.assertEqual(result.returncode, 1, mode)
self.assertIn("error: schema 2 is not 1", result.stderr)
self.assertFalse(output.exists())
def test_validate_reports_the_form_count(self):
result = self.run_cli("validate")
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(result.stdout.strip(), f"registry valid: {len(gen.load_registry()['form'])} forms")
if __name__ == "__main__":
unittest.main()