diff --git a/AGENTS.md b/AGENTS.md index 11b41a361..10011c234 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -36,7 +36,7 @@ The translator's core lives in `crates/metal2vulkan-air/src/` and, in | `docs/ARCHITECTURE.md` | The translator's stages and module map | | `docs/FAST-PATHS.md` | The ledger of speed-for-accuracy defaults and their exact switches | | `docs/VALIDATION.md` | The validation ladder | -| `docs/CONFORMANCE-COVERAGE.md` | Generated: which Metal items the conformance suite compares against Metal, and which it does not | +| `docs/CONFORMANCE-COVERAGE.md` | Generated, along two axes: which Metal items the conformance suite compares against Metal, and which of each Metal enum's and option set's values it compared | | `CONTRIBUTING.md` | Build, test, golden tables | | `crates/metal2vulkan/src/env_vars.rs` | The `METAL2VULKAN_*` variables | diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 4ac94aeff..518e5a04a 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -135,6 +135,7 @@ Edit the source, then regenerate: |---|---|---| | `docs/REFUSALS.md` | `python3 scripts/refusal-surface/refusal_surface.py` (`--check` to verify) | the code's refusal types; `reach.tsv` beside the script | | `docs/METAL-COVERAGE.md` | `python3 scripts/metal-coverage/coverage.py` (`--check` to verify) | `scripts/metal-coverage/coverage.tsv` | +| `docs/CONFORMANCE-COVERAGE.md` | `python3 scripts/conformance-coverage/coverage.py` (`--check` to verify, `--selftest` for the option-space axis's own tests) | the suite's sources, its committed recordings, `scripts/metal-coverage/coverage.tsv`, `objc2_metal.tsv`, and the generated Metal enum tables | | `crates/metal2vulkan/src/spv.rs`, `crates/metal2vulkan/src/spirv_binary/table.rs` | `scripts/regen-spirv-grammar/regen-spirv-grammar.sh` | Khronos SPIRV-Headers' grammar JSON, and `items.txt` beside the script | | `crates/metal2vulkan-validation/profiles/*.json` | `scripts/regen-device-profiles/` | gpuinfo reports and local captures | diff --git a/crates/metal2vulkan-conformance/tests/conformance_coverage.rs b/crates/metal2vulkan-conformance/tests/conformance_coverage.rs index e238e7604..2d5e3572e 100644 --- a/crates/metal2vulkan-conformance/tests/conformance_coverage.rs +++ b/crates/metal2vulkan-conformance/tests/conformance_coverage.rs @@ -12,6 +12,13 @@ //! cannot see. It derives per-case facts from the committed recordings, which is only the case //! set if the case set and the recordings are the same names. A case with no recording, or a //! recording no case claims, would leave the document counting something that is not the suite. +//! - [`the_option_space_axis_still_measures_what_it_claims`] holds the second axis against the one +//! way a derivation over text fails silently. `--check` catches a number that went **stale**; it +//! cannot catch one that went **vacuous**, because a spelling the sources use that the regexes +//! no longer match, or a renamed recording key, lowers every count at once and the document +//! still reads like a measurement. So the axis is run over little trees whose answers are known +//! by construction, each asserting both that a value it should find is found and that a value it +//! must not count is not. use std::collections::BTreeSet; use std::fs; @@ -23,9 +30,8 @@ fn root() -> PathBuf { Path::new(env!("CARGO_MANIFEST_DIR")).join("../..") } -/// The document is what the sources and the recordings derive, as the generator writes it. -#[test] -fn the_conformance_coverage_document_is_what_the_sources_derive() { +/// The generator run with `verb`, as its own words and its exit status. +fn generator(verb: &str) -> (bool, String) { let script = root().join("scripts/conformance-coverage/coverage.py"); // `-B` so the run leaves no `__pycache__` beside the script: a test writes nothing into the // tree it is checking. @@ -33,16 +39,36 @@ fn the_conformance_coverage_document_is_what_the_sources_derive() { .arg("-I") .arg("-B") .arg(&script) - .arg("--check") + .arg(verb) .current_dir(root()) .output() - .unwrap_or_else(|error| panic!("python3 {}: {error}", script.display())); + .unwrap_or_else(|error| panic!("python3 {} {verb}: {error}", script.display())); let out = format!( "{}{}", String::from_utf8_lossy(&run.stdout), String::from_utf8_lossy(&run.stderr) ); - assert!(run.status.success(), "{out}"); + (run.status.success(), out) +} + +/// The document is what the sources and the recordings derive, as the generator writes it. +#[test] +fn the_conformance_coverage_document_is_what_the_sources_derive() { + let (ok, out) = generator("--check"); + assert!(ok, "{out}"); +} + +/// The option-space axis finds the values it should and refuses the ones it should not. +/// +/// `--check` holds the document to the sources, which catches a count that went stale. It cannot +/// catch one that went vacuous: the axis reads the suite's text and its recordings, and a spelling +/// it stops matching takes values out of every column at once, leaving a document that still reads +/// like a measurement. `--selftest` runs the axis over trees it builds itself, where the answer is +/// known, and each of its cases asserts both directions. +#[test] +fn the_option_space_axis_still_measures_what_it_claims() { + let (ok, out) = generator("--selftest"); + assert!(ok, "{out}"); } /// Every case of the suite has a committed recording, and every recording is a case's. diff --git a/docs/CONFORMANCE-COVERAGE.md b/docs/CONFORMANCE-COVERAGE.md index c67e54193..9ea08128b 100644 --- a/docs/CONFORMANCE-COVERAGE.md +++ b/docs/CONFORMANCE-COVERAGE.md @@ -4,6 +4,8 @@ Generated by `scripts/conformance-coverage/coverage.py` from the suite's own sou This is not [METAL-COVERAGE.md](METAL-COVERAGE.md), which says what we **implement**. This says what the conformance suite **compares against Metal**. An item counts as *exercised* here only where a case's native Metal leg calls it; a case's Metal answer is a recorded fact only where the recording is committed. The two claims are different sizes, and only the second is conformance. +It says it along **two axes**, because either one alone reads as more than it is. The **items** axis is reach: one call of a selector is enough, so a selector that takes an enum counts as exercised whatever value reached it. The **option space** axis is depth: of each Metal enum's and option set's values, which ones the suite compared. A high number on the first and a low one on the second is what a suite that touches everything shallowly looks like. + ## What this measures, and what it cannot The suite reaches Metal through `objc2-metal`, whose Rust name for a binding is the selector with each `:` written `_`. So a call site names its selector outright, and the derivation resolves the **receiver's type** by following what made it — a class's constructor, a getter whose answer `objc2_metal.tsv` records, a field of the side's own struct, a parameter's declared type — and then walks that type's supertypes to the container the SDK declares the item on. A message to a class, written `MTLType::selector(..)`, names its own receiver and needs no typing. @@ -38,6 +40,156 @@ A tolerance names a **site of a transcript**, not an item, so the last two rows *Exercised* and *recorded* are one number here, not two, and deliberately: a case is credited with exercising an item only through its cases whose answer record mode took by **running** Metal, and such a case has a committed recording by construction. A case that carries an answer, or whose call Metal never returned from, runs no native leg and exercises nothing, however much Metal its code names. +## By option space, which is depth rather than reach + +The axis above counts a Metal **item** as exercised where one call of it ran. A selector that takes an enum therefore counts whatever value reached it, so that axis says nothing about how much of an enum the suite ever put to Metal. This one does, over the values themselves. + +The denominator is generated, never written here: `crates/metal2vulkan/src/metal/generated.rs` and the front end's hold every enumerator name and ordinal `scripts/regen-metal-enums/` extracts from the SDK's Metal headers. A Metal type this tree models by hand instead has **no denominator here** and is listed apart, below. + +A value is **compared** where either of two things holds, which are different claims: + +- **answered** — the enumerator's name is in a committed recording's transcript of an answer Metal **ran**. Metal named the value back at a site the comparison reads, so the value is in the compared text itself. +- **in effect** — a case module's own text names the value, and that module has at least one case whose recording is a Metal run. Metal's recorded answer was taken with the value in effect, so what is compared is Metal's behaviour **under** it, even where no site reads it back. A blend factor is this and not the first: what the recording holds is the texels Metal blended with it. + +What this axis cannot see, measured rather than asserted: + +- **A value Metal answers as a bare ordinal.** A transcript holds a `uint`, and nothing in it says which enum the number belongs to, so only a site that records the enumerator's **name** is read. The *answered* column is a floor by every site that records an ordinal instead. +- **A value a case states as a raw ordinal.** A case may hand the Metal leg an enum's ordinal as a number — a sweep over `0..n` rather than over named variants — and no reading of the text can say which value a computed number is. So *in effect*, and the *stated* column of the hand-modelled table below, are floors by every sweep written that way: a type they report short of its values may in fact be swept exhaustively, and the case is what says so. Read the case before taking a row of the work list as work. +- **Which case put a value in effect.** The unit is the case module, as it is for the items axis: a value named anywhere in a module whose cases include a Metal run counts for that module, even where one of its cases names it and the rest do not. +- **A value only the suite's shared sources name** — 4 of them. Some case puts it to Metal through the render or texture vocabulary, but which case is not a property of the text, so it is neither compared nor missing and has its own column. +- **Combinations.** Every column here is per value. A type whose values are all compared says nothing about the pairs and triples of them, which is where most of the behaviour an implementation can get wrong lives. +- **Metal's API validation is excluded.** Its complaints name enumerators, and the suite records that leg and never compares it, so reading it would count Apple's prose as a comparison. So are the cost and timing tables: a site name there is what was measured, not an answer that was compared. +- **A `#[cfg(test)]` item is excluded.** One of the suite's unit tests names four blend factors to assert that no case uses them; counting those would have this report the opposite of what the code says. + +| | | +|---|---| +| Metal enums and option sets with a generated value list | 43 | +| their values | 703 | +| values compared | 341 | +| share compared | 49% | +| values only the suite's shared sources name | 4 | +| values no source names and no recording holds | 358 | +| types every value of which is compared | 13 | +| types no value of which is compared | 5 | + +The share is weakly informative on its own: `MTLPixelFormat`, `MTLDataType`, `MTLAttributeFormat`, `MTLVertexFormat` hold 506 of the 703 values between them, so an aggregate over types this uneven is mostly theirs. The per-type table is the one to read. + +### Depth by type + +Deepest gap first, which is the order the work list reads in. *answered* and *in effect* overlap; *compared* is their union. + +| Metal type | values | compared | answered | in effect | shared only | missing | +|---|---|---|---|---|---|---| +| `MTLPixelFormat` | 301 | 179 | 112 | 110 | 0 | 122 | +| `MTLDataType` | 97 | 15 | 10 | 9 | 0 | 82 | +| `MTLAttributeFormat` | 54 | 1 | 0 | 1 | 0 | 53 | +| `MTLVertexFormat` | 54 | 18 | 2 | 16 | 0 | 36 | +| `MTLBindingType` | 12 | 4 | 4 | 0 | 0 | 8 | +| `MTLBlendFactor` | 20 | 14 | 10 | 13 | 0 | 6 | +| `MTLCompareFunction` | 8 | 4 | 0 | 4 | 0 | 4 | +| `MTLFunctionType` | 7 | 3 | 3 | 0 | 0 | 4 | +| `MTLStepFunction` | 9 | 5 | 0 | 5 | 0 | 4 | +| `MTLFunctionOptions` | 5 | 2 | 1 | 2 | 0 | 3 | +| `MTLReadWriteTextureTier` | 3 | 0 | 0 | 0 | 0 | 3 | +| `MTLSamplerMipFilter` | 3 | 0 | 0 | 0 | 0 | 3 | +| `MTLSamplerReductionMode` | 3 | 0 | 0 | 0 | 0 | 3 | +| `MTLStencilOperation` | 8 | 5 | 0 | 5 | 0 | 3 | +| `MTLTextureUsage` | 9 | 6 | 0 | 6 | 0 | 3 | +| `MTLIndirectCommandType` | 8 | 5 | 0 | 5 | 1 | 2 | +| `MTLArgumentBuffersTier` | 2 | 0 | 0 | 0 | 0 | 2 | +| `MTLBarrierScope` | 3 | 1 | 0 | 1 | 0 | 2 | +| `MTLPrimitiveTopologyClass` | 4 | 2 | 2 | 0 | 0 | 2 | +| `MTLTessellationFactorStepFunction` | 4 | 2 | 2 | 0 | 0 | 2 | +| `MTLTessellationPartitionMode` | 4 | 2 | 2 | 0 | 0 | 2 | +| `MTLVertexStepFunction` | 5 | 3 | 2 | 2 | 0 | 2 | +| `MTLSamplerBorderColor` | 3 | 1 | 0 | 1 | 1 | 1 | +| `MTLBlendOperation` | 6 | 5 | 5 | 5 | 0 | 1 | +| `MTLColorWriteMask` | 7 | 6 | 0 | 6 | 0 | 1 | +| `MTLPatchType` | 3 | 2 | 2 | 0 | 0 | 1 | +| `MTLResourceUsage` | 3 | 2 | 0 | 2 | 0 | 1 | +| `MTLSamplerMinMagFilter` | 3 | 2 | 0 | 2 | 0 | 1 | +| `MTLTessellationControlPointIndexType` | 3 | 2 | 2 | 0 | 0 | 1 | +| `MTLDispatchType` | 2 | 0 | 0 | 0 | 2 | 0 | +| `MTLBindingAccess` | 3 | 3 | 3 | 0 | 0 | 0 | +| `MTLCullMode` | 3 | 3 | 0 | 3 | 0 | 0 | +| `MTLDepthClipMode` | 2 | 2 | 0 | 2 | 0 | 0 | +| `MTLIndexType` | 2 | 2 | 0 | 2 | 0 | 0 | +| `MTLMutability` | 3 | 3 | 3 | 0 | 0 | 0 | +| `MTLPrimitiveType` | 5 | 5 | 0 | 5 | 0 | 0 | +| `MTLRenderStages` | 5 | 5 | 0 | 5 | 0 | 0 | +| `MTLSamplerAddressMode` | 6 | 6 | 0 | 6 | 0 | 0 | +| `MTLTessellationFactorFormat` | 1 | 1 | 1 | 0 | 0 | 0 | +| `MTLTextureSwizzle` | 6 | 6 | 0 | 6 | 0 | 0 | +| `MTLTextureType` | 10 | 10 | 1 | 10 | 0 | 0 | +| `MTLTriangleFillMode` | 2 | 2 | 0 | 2 | 0 | 0 | +| `MTLWinding` | 2 | 2 | 2 | 2 | 0 | 0 | + +### The values not compared + +The work list. A name here is a value of Metal's that no committed recording holds and no case module states **by name**: it is not a claim that Metal accepts the value on every device, and not a claim that no case reaches it, because a case that sweeps a type by ordinal states none of its values here. Each row is a question for the case, not a verdict on it. + +- **`MTLPixelFormat`**, 122 of 301: `MTLPixelFormatR16Sint`, `MTLPixelFormatRG8Unorm_sRGB`, `MTLPixelFormatRG8Uint`, `MTLPixelFormatRG8Sint`, `MTLPixelFormatRGB8Unorm`, `MTLPixelFormatRGB8Snorm`, `MTLPixelFormatRGB8Uint`, `MTLPixelFormatRGB8Sint`, `MTLPixelFormatRG16Uint`, `MTLPixelFormatRG16Sint`, `MTLPixelFormatRGBA8Sint`, `MTLPixelFormatRGB10A2Uint`, `MTLPixelFormatRGB16Unorm`, `MTLPixelFormatRGB16Snorm`, `MTLPixelFormatRGB16Uint`, `MTLPixelFormatRGB16Sint`, `MTLPixelFormatRGB16Float`, `MTLPixelFormatRG32Uint`, `MTLPixelFormatRG32Sint`, `MTLPixelFormatRGBA16Sint`, `MTLPixelFormatRGB32Uint`, `MTLPixelFormatRGB32Sint`, `MTLPixelFormatRGB32Float`, `MTLPixelFormatBC1_RGBA_sRGB`, `MTLPixelFormatBC2_RGBA`, `MTLPixelFormatBC2_RGBA_sRGB`, `MTLPixelFormatBC3_RGBA`, `MTLPixelFormatBC3_RGBA_sRGB`, `MTLPixelFormatBC4_RUnorm`, `MTLPixelFormatBC4_RSnorm`, `MTLPixelFormatBC5_RGUnorm`, `MTLPixelFormatBC5_RGSnorm`, `MTLPixelFormatBC6H_RGBFloat`, `MTLPixelFormatBC6H_RGBUfloat`, `MTLPixelFormatBC7_RGBAUnorm_sRGB`, `MTLPixelFormatPVRTC_RGB_2BPP`, `MTLPixelFormatPVRTC_RGB_2BPP_sRGB`, `MTLPixelFormatPVRTC_RGB_4BPP`, `MTLPixelFormatPVRTC_RGB_4BPP_sRGB`, `MTLPixelFormatPVRTC_RGBA_2BPP`, `MTLPixelFormatPVRTC_RGBA_2BPP_sRGB`, `MTLPixelFormatASTC_4x4_HDR`, `MTLPixelFormatASTC_5x4_HDR`, `MTLPixelFormatASTC_5x5_HDR`, `MTLPixelFormatASTC_6x5_HDR`, `MTLPixelFormatASTC_6x6_HDR`, `MTLPixelFormatASTC_8x5_HDR`, `MTLPixelFormatASTC_8x6_HDR`, `MTLPixelFormatASTC_8x8_HDR`, `MTLPixelFormatASTC_10x5_HDR`, `MTLPixelFormatASTC_10x6_HDR`, `MTLPixelFormatASTC_10x8_HDR`, `MTLPixelFormatASTC_10x10_HDR`, `MTLPixelFormatASTC_12x10_HDR`, `MTLPixelFormatASTC_12x12_HDR`, `MTLPixelFormatX24_Stencil8`, `MTLPixelFormatASTC_4x2_sRGB`, `MTLPixelFormatASTC_8x4_sRGB`, `MTLPixelFormatASTC_4x2_LDR`, `MTLPixelFormatASTC_8x4_LDR`, `MTLPixelFormatASTC_4x2_HDR`, `MTLPixelFormatASTC_8x4_HDR`, `MTLPixelFormatBGRA4Unorm`, `MTLPixelFormatARGB8Unorm_sRGB`, `MTLPixelFormatRGB16Bfloat`, `MTLPixelFormatRGBX8Unorm`, `MTLPixelFormatRGBX8Unorm_sRGB`, `MTLPixelFormatRGBX8Snorm`, `MTLPixelFormatRGBX8Uint`, `MTLPixelFormatRGBX8Sint`, `MTLPixelFormatRGBX16Uint`, `MTLPixelFormatRGBX16Sint`, `MTLPixelFormatRGBX16Float`, `MTLPixelFormatRGBX32Uint`, `MTLPixelFormatRGBX32Sint`, `MTLPixelFormatRGBX32Float`, `MTLPixelFormatYCBCR8_422_1P`, `MTLPixelFormatYCBCR10_444_1P`, `MTLPixelFormatYCBCR8_422_1P_sRGB`, `MTLPixelFormatYCBCR10_444_1P_sRGB`, `MTLPixelFormatYCBCRA8_444_1P`, `MTLPixelFormatYCBCR8_422_1P_REV`, `MTLPixelFormatYCBCR10_444_1P_PQ`, `MTLPixelFormatRGB10A2Unorm_PQ`, `MTLPixelFormatR10Unorm_PACKED`, `MTLPixelFormatRG10Unorm_PACKED`, `MTLPixelFormatYCBCR10_444_1P_XR`, `MTLPixelFormatR12Unorm_X4`, `MTLPixelFormatR12Unorm_X4_PQ`, `MTLPixelFormatRG12Unorm_X8`, `MTLPixelFormatR10Unorm_X6_PQ`, `MTLPixelFormatYCBCR10_444_1P_HLG`, `MTLPixelFormatR10Unorm_X6_HLG`, `MTLPixelFormatR12Unorm_X4_HLG`, `MTLPixelFormatRGB10A2Unorm_HLG`, `MTLPixelFormatRGB10A8_2P`, `MTLPixelFormatRGB10A8_2P_sRGB`, `MTLPixelFormatRGB10A8_2P_PQ`, `MTLPixelFormatRGB10A8_2P_HLG`, `MTLPixelFormatBGR10A2Unorm_sRGB`, `MTLPixelFormatBGR10A2Unorm_PQ`, `MTLPixelFormatBGRA10Uint_PACKED`, `MTLPixelFormatBGRA10_XR_PACKED`, `MTLPixelFormatBGRA10_XR_PACKED_sRGB`, `MTLPixelFormatBGRA10Unorm_PACKED`, `MTLPixelFormatBGRA10Unorm_PACKED_sRGB`, `MTLPixelFormatBGRA10Unorm_PACKED_HLG`, `MTLPixelFormatBGRA10Unorm_PACKED_PQ`, `MTLPixelFormatBGRA10Uint`, `MTLPixelFormatBGRA10Unorm`, `MTLPixelFormatBGRA10Unorm_sRGB`, `MTLPixelFormatBGRA10Unorm_HLG`, `MTLPixelFormatBGRA10Unorm_PQ`, `MTLPixelFormatR10Uint_X6`, `MTLPixelFormatR10Uint_PACKED`, `MTLPixelFormatRG10Uint_X12`, `MTLPixelFormatRG10Uint_PACKED`, `MTLPixelFormatR12Uint_X4`, `MTLPixelFormatR12Uint_PACKED`, `MTLPixelFormatRG12Uint_X8`, `MTLPixelFormatRG12Uint_PACKED`, `MTLPixelFormatRGB10A8Uint_2P` +- **`MTLDataType`**, 82 of 97: `MTLDataTypeNone`, `MTLDataTypeArray`, `MTLDataTypeFloat3`, `MTLDataTypeFloat2x2`, `MTLDataTypeFloat2x3`, `MTLDataTypeFloat2x4`, `MTLDataTypeFloat3x2`, `MTLDataTypeFloat3x3`, `MTLDataTypeFloat3x4`, `MTLDataTypeFloat4x2`, `MTLDataTypeFloat4x3`, `MTLDataTypeFloat4x4`, `MTLDataTypeHalf`, `MTLDataTypeHalf3`, `MTLDataTypeHalf4`, `MTLDataTypeHalf2x2`, `MTLDataTypeHalf2x3`, `MTLDataTypeHalf2x4`, `MTLDataTypeHalf3x2`, `MTLDataTypeHalf3x3`, `MTLDataTypeHalf3x4`, `MTLDataTypeHalf4x2`, `MTLDataTypeHalf4x3`, `MTLDataTypeHalf4x4`, `MTLDataTypeInt`, `MTLDataTypeInt2`, `MTLDataTypeInt3`, `MTLDataTypeInt4`, `MTLDataTypeUInt2`, `MTLDataTypeUInt3`, `MTLDataTypeUInt4`, `MTLDataTypeShort`, `MTLDataTypeShort2`, `MTLDataTypeShort3`, `MTLDataTypeShort4`, `MTLDataTypeUShort`, `MTLDataTypeUShort2`, `MTLDataTypeUShort3`, `MTLDataTypeUShort4`, `MTLDataTypeChar`, `MTLDataTypeChar2`, `MTLDataTypeChar3`, `MTLDataTypeChar4`, `MTLDataTypeUChar`, `MTLDataTypeUChar2`, `MTLDataTypeUChar3`, `MTLDataTypeBool2`, `MTLDataTypeBool3`, `MTLDataTypeBool4`, `MTLDataTypeR8Unorm`, `MTLDataTypeR8Snorm`, `MTLDataTypeR16Unorm`, `MTLDataTypeR16Snorm`, `MTLDataTypeRG8Unorm`, `MTLDataTypeRG8Snorm`, `MTLDataTypeRG16Unorm`, `MTLDataTypeRG16Snorm`, `MTLDataTypeRGBA8Unorm`, `MTLDataTypeRGBA8Unorm_sRGB`, `MTLDataTypeRGBA8Snorm`, `MTLDataTypeRGBA16Unorm`, `MTLDataTypeRGBA16Snorm`, `MTLDataTypeRGB10A2Unorm`, `MTLDataTypeRG11B10Float`, `MTLDataTypeRGB9E5Float`, `MTLDataTypeLong`, `MTLDataTypeLong2`, `MTLDataTypeLong3`, `MTLDataTypeLong4`, `MTLDataTypeULong`, `MTLDataTypeULong2`, `MTLDataTypeULong3`, `MTLDataTypeULong4`, `MTLDataTypeIntersectionFunctionTable`, `MTLDataTypePrimitiveAccelerationStructure`, `MTLDataTypeInstanceAccelerationStructure`, `MTLDataTypeBFloat`, `MTLDataTypeBFloat2`, `MTLDataTypeBFloat3`, `MTLDataTypeBFloat4`, `MTLDataTypeDepthStencilState`, `MTLDataTypeTensor` +- **`MTLAttributeFormat`**, 53 of 54: `MTLAttributeFormatInvalid`, `MTLAttributeFormatUChar2`, `MTLAttributeFormatUChar3`, `MTLAttributeFormatUChar4`, `MTLAttributeFormatChar2`, `MTLAttributeFormatChar3`, `MTLAttributeFormatChar4`, `MTLAttributeFormatUChar2Normalized`, `MTLAttributeFormatUChar3Normalized`, `MTLAttributeFormatUChar4Normalized`, `MTLAttributeFormatChar2Normalized`, `MTLAttributeFormatChar3Normalized`, `MTLAttributeFormatChar4Normalized`, `MTLAttributeFormatUShort2`, `MTLAttributeFormatUShort3`, `MTLAttributeFormatUShort4`, `MTLAttributeFormatShort2`, `MTLAttributeFormatShort3`, `MTLAttributeFormatShort4`, `MTLAttributeFormatUShort2Normalized`, `MTLAttributeFormatUShort3Normalized`, `MTLAttributeFormatUShort4Normalized`, `MTLAttributeFormatShort2Normalized`, `MTLAttributeFormatShort3Normalized`, `MTLAttributeFormatShort4Normalized`, `MTLAttributeFormatHalf2`, `MTLAttributeFormatHalf3`, `MTLAttributeFormatHalf4`, `MTLAttributeFormatFloat`, `MTLAttributeFormatFloat2`, `MTLAttributeFormatFloat3`, `MTLAttributeFormatFloat4`, `MTLAttributeFormatInt`, `MTLAttributeFormatInt2`, `MTLAttributeFormatInt3`, `MTLAttributeFormatInt4`, `MTLAttributeFormatUInt2`, `MTLAttributeFormatUInt3`, `MTLAttributeFormatUInt4`, `MTLAttributeFormatInt1010102Normalized`, `MTLAttributeFormatUInt1010102Normalized`, `MTLAttributeFormatUChar4Normalized_BGRA`, `MTLAttributeFormatUChar`, `MTLAttributeFormatChar`, `MTLAttributeFormatUCharNormalized`, `MTLAttributeFormatCharNormalized`, `MTLAttributeFormatUShort`, `MTLAttributeFormatShort`, `MTLAttributeFormatUShortNormalized`, `MTLAttributeFormatShortNormalized`, `MTLAttributeFormatHalf`, `MTLAttributeFormatFloatRG11B10`, `MTLAttributeFormatFloatRGB9E5` +- **`MTLVertexFormat`**, 36 of 54: `MTLVertexFormatUChar2Normalized`, `MTLVertexFormatUChar3Normalized`, `MTLVertexFormatUChar4Normalized`, `MTLVertexFormatChar2Normalized`, `MTLVertexFormatChar3Normalized`, `MTLVertexFormatChar4Normalized`, `MTLVertexFormatUShort2Normalized`, `MTLVertexFormatUShort3Normalized`, `MTLVertexFormatUShort4Normalized`, `MTLVertexFormatShort2Normalized`, `MTLVertexFormatShort3Normalized`, `MTLVertexFormatShort4Normalized`, `MTLVertexFormatHalf2`, `MTLVertexFormatHalf3`, `MTLVertexFormatHalf4`, `MTLVertexFormatFloat`, `MTLVertexFormatFloat3`, `MTLVertexFormatFloat4`, `MTLVertexFormatInt`, `MTLVertexFormatInt2`, `MTLVertexFormatInt3`, `MTLVertexFormatInt4`, `MTLVertexFormatUInt`, `MTLVertexFormatUInt2`, `MTLVertexFormatUInt3`, `MTLVertexFormatUInt4`, `MTLVertexFormatInt1010102Normalized`, `MTLVertexFormatUInt1010102Normalized`, `MTLVertexFormatUChar4Normalized_BGRA`, `MTLVertexFormatUCharNormalized`, `MTLVertexFormatCharNormalized`, `MTLVertexFormatUShortNormalized`, `MTLVertexFormatShortNormalized`, `MTLVertexFormatHalf`, `MTLVertexFormatFloatRG11B10`, `MTLVertexFormatFloatRGB9E5` +- **`MTLBindingType`**, 8 of 12: `MTLBindingTypeImageblockData`, `MTLBindingTypeImageblock`, `MTLBindingTypeVisibleFunctionTable`, `MTLBindingTypePrimitiveAccelerationStructure`, `MTLBindingTypeInstanceAccelerationStructure`, `MTLBindingTypeIntersectionFunctionTable`, `MTLBindingTypeObjectPayload`, `MTLBindingTypeTensor` +- **`MTLBlendFactor`**, 6 of 20: `MTLBlendFactorOneMinusBlendColor`, `MTLBlendFactorSource1Color`, `MTLBlendFactorOneMinusSource1Color`, `MTLBlendFactorSource1Alpha`, `MTLBlendFactorOneMinusSource1Alpha`, `MTLBlendFactorUnspecialized` +- **`MTLCompareFunction`**, 4 of 8: `MTLCompareFunctionLessEqual`, `MTLCompareFunctionGreater`, `MTLCompareFunctionNotEqual`, `MTLCompareFunctionGreaterEqual` +- **`MTLFunctionType`**, 4 of 7: `MTLFunctionTypeVisible`, `MTLFunctionTypeIntersection`, `MTLFunctionTypeMesh`, `MTLFunctionTypeObject` +- **`MTLStepFunction`**, 4 of 9: `MTLStepFunctionPerVertex`, `MTLStepFunctionPerInstance`, `MTLStepFunctionPerPatch`, `MTLStepFunctionPerPatchControlPoint` +- **`MTLFunctionOptions`**, 3 of 5: `MTLFunctionOptionCompileToBinary`, `MTLFunctionOptionFailOnBinaryArchiveMiss`, `MTLFunctionOptionPipelineIndependent` +- **`MTLReadWriteTextureTier`**, 3 of 3: `MTLReadWriteTextureTierNone`, `MTLReadWriteTextureTier1`, `MTLReadWriteTextureTier2` +- **`MTLSamplerMipFilter`**, 3 of 3: `MTLSamplerMipFilterNotMipmapped`, `MTLSamplerMipFilterNearest`, `MTLSamplerMipFilterLinear` +- **`MTLSamplerReductionMode`**, 3 of 3: `MTLSamplerReductionModeWeightedAverage`, `MTLSamplerReductionModeMinimum`, `MTLSamplerReductionModeMaximum` +- **`MTLStencilOperation`**, 3 of 8: `MTLStencilOperationDecrementClamp`, `MTLStencilOperationIncrementWrap`, `MTLStencilOperationDecrementWrap` +- **`MTLTextureUsage`**, 3 of 9: `MTLTextureUsageUnknown`, `MTLTextureUsageNoConcurrentAccess`, `MTLTextureUsageVideo` +- **`MTLArgumentBuffersTier`**, 2 of 2: `MTLArgumentBuffersTier1`, `MTLArgumentBuffersTier2` +- **`MTLBarrierScope`**, 2 of 3: `MTLBarrierScopeBuffers`, `MTLBarrierScopeRenderTargets` +- **`MTLIndirectCommandType`**, 2 of 8: `MTLIndirectCommandTypeDrawPatches`, `MTLIndirectCommandTypeDrawIndexedPatches` +- **`MTLPrimitiveTopologyClass`**, 2 of 4: `MTLPrimitiveTopologyClassPoint`, `MTLPrimitiveTopologyClassLine` +- **`MTLTessellationFactorStepFunction`**, 2 of 4: `MTLTessellationFactorStepFunctionPerPatch`, `MTLTessellationFactorStepFunctionPerInstance` +- **`MTLTessellationPartitionMode`**, 2 of 4: `MTLTessellationPartitionModeInteger`, `MTLTessellationPartitionModeFractionalEven` +- **`MTLVertexStepFunction`**, 2 of 5: `MTLVertexStepFunctionPerPatch`, `MTLVertexStepFunctionPerPatchControlPoint` +- **`MTLBlendOperation`**, 1 of 6: `MTLBlendOperationUnspecialized` +- **`MTLColorWriteMask`**, 1 of 7: `MTLColorWriteMaskUnspecialized` +- **`MTLPatchType`**, 1 of 3: `MTLPatchTypeQuad` +- **`MTLResourceUsage`**, 1 of 3: `MTLResourceUsageSample` +- **`MTLSamplerBorderColor`**, 1 of 3: `MTLSamplerBorderColorOpaqueBlack` +- **`MTLSamplerMinMagFilter`**, 1 of 3: `MTLSamplerMinMagFilterCubic` +- **`MTLTessellationControlPointIndexType`**, 1 of 3: `MTLTessellationControlPointIndexTypeUInt16` + +And the values only the suite's shared sources name, which some case reaches and this cannot attribute: + +- **`MTLDispatchType`**: `MTLDispatchTypeSerial`, `MTLDispatchTypeConcurrent` +- **`MTLIndirectCommandType`**: `MTLIndirectCommandTypeDrawMeshThreads` +- **`MTLSamplerBorderColor`**: `MTLSamplerBorderColorTransparentBlack` + +### Metal types with no generated value list + +These the tree models by hand: a Rust item whose own doc comment opens by naming a Metal type, and whose shape is a closed enum or a newtype over one integer. `regen-metal-enums` holds no value list for them, so **this axis has no denominator here**, and *declared* is our own sources' variant count rather than the SDK's — a newtype option set declares none. There is no *answered* column either: a recording names a value by its Metal enumerator, and for these types this has no list of those names to match against. Giving one a denominator means appending its Metal name to `scripts/regen-metal-enums/`'s `ENUMS` or `OPTIONS` and regenerating. + +These 17 are what that shape finds, and the list is a floor: a type the tree models without saying so on the item lands in neither table, and so is nowhere in this axis at all. + +| Metal type | the tree's type | declared | stated by a recorded case | shared only | +|---|---|---|---|---| +| `MTLBlitOption` | `BlitOption` | 4 | 0 | 4 | +| `MTLCPUCacheMode` | `CpuCacheMode` | 2 | 1 | 1 | +| `MTLCommandBufferStatus` | `CommandBufferStatus` | 6 | 0 | 6 | +| `MTLHazardTrackingMode` | `HazardTrackingMode` | 3 | 1 | 2 | +| `MTLHeapType` | `HeapType` | 3 | 2 | 1 | +| `MTLLoadAction` | `LoadAction` | 3 | 2 | 1 | +| `MTLMultisampleDepthResolveFilter` | `MultisampleDepthResolveFilter` | 3 | 0 | 1 | +| `MTLMultisampleStencilResolveFilter` | `MultisampleStencilResolveFilter` | 2 | 0 | 1 | +| `MTLPipelineOption` | `PipelineOption` | — a bit set | 0 | 0 | +| `MTLPurgeableState` | `PurgeableState` | 4 | 1 | 3 | +| `MTLResourceOptions` | `ResourceOptions` | — a bit set | 0 | 0 | +| `MTLSparsePageSize` | `SparsePageSize` | 3 | 3 | 0 | +| `MTLSparseTextureRegionAlignmentMode` | `SparseTextureRegionAlignmentMode` | 2 | 0 | 2 | +| `MTLStorageMode` | `StorageMode` | 4 | 0 | 3 | +| `MTLStoreAction` | `StoreAction` | 6 | 4 | 0 | +| `MTLStoreActionOptions` | `StoreActionOptions` | — a bit set | 0 | 0 | +| `MTLVisibilityResultMode` | `VisibilityResultMode` | 3 | 3 | 0 | + ## By container Every container with an implemented item, by how much of it the suite reaches. diff --git a/scripts/conformance-coverage/coverage.py b/scripts/conformance-coverage/coverage.py index a071fdbf1..75b1a8178 100644 --- a/scripts/conformance-coverage/coverage.py +++ b/scripts/conformance-coverage/coverage.py @@ -6,6 +6,11 @@ against Metal**, which is a different and narrower claim: an item is only verifi native Metal leg calls it, the case has a committed recording of Metal's answer, and our side's answer is compared with it. +Two axes, because one of them alone reads as more than it is. The **items** axis is reachability: +one call of a selector is enough, so a selector that takes an enum counts as exercised whatever +value reached it. The **option space** axis (`option_space.py`) is depth: of each Metal enum's and +option set's values, which ones the suite actually compared. + Nothing here is a maintained list. Every number is derived, at the moment this runs, from four things already in the tree: @@ -19,11 +24,15 @@ things already in the tree: says which of the suite's own vocabulary reaches each call. 4. `crates/metal2vulkan-conformance/recordings/` — the committed recordings, which are what makes a case's Metal answer a recorded fact rather than an intention. +5. `crates/metal2vulkan/src/metal/generated.rs` and the front end's — the SDK's enumerator names + and ordinals, which `scripts/regen-metal-enums/` extracts from the Metal headers. They are the + option-space axis's denominator; no value list is written here. Usage: coverage.py write docs/CONFORMANCE-COVERAGE.md coverage.py --check fail if docs/CONFORMANCE-COVERAGE.md is not what the sources derive coverage.py --api (Mac only) fail if objc2_metal.tsv is not what objc2-metal's sources say + coverage.py --selftest run the option-space axis over inputs whose answers are known """ import csv @@ -39,6 +48,7 @@ ROOT = HERE.parent.parent sys.path.insert(0, str(HERE)) import metal_leg # noqa: E402 (the resolver, beside this script) +import option_space # noqa: E402 (the option-space axis, beside this script) SUITE = ROOT / "crates/metal2vulkan-conformance" SRC = SUITE / "src" @@ -434,6 +444,11 @@ def inventory(): "keyed": keyed, "unlisted": unlisted, "gaps": known_gaps(), + # The second axis. A module with no case whose answer Metal ran puts no value to Metal, + # which is the same gate the items axis applies to a call. + "option_space": option_space.inventory( + ROOT, {module for module, family in families.items() if family["ran"]} + ), } @@ -451,6 +466,188 @@ def families_line(modules: dict[str, set[str]]) -> str: return ", ".join(f"`{module}`" for module in sorted(modules)) +def names_line(names: list[str]) -> str: + """Enumerator names as the document prints them.""" + return ", ".join(f"`{name}`" for name in names) + + +def write_option_space(w, space) -> None: + """The second axis: of each Metal enum's and option set's values, which the suite compared.""" + rows = space["rows"] + values = sum(len(row["values"]) for row in rows) + compared = sum(len(row["compared"]) for row in rows) + shared = sum(len(row["shared"]) for row in rows) + missing = sum(len(row["missing"]) for row in rows) + + w("## By option space, which is depth rather than reach") + w("") + w( + "The axis above counts a Metal **item** as exercised where one call of it ran. A selector " + "that takes an enum therefore counts whatever value reached it, so that axis says nothing " + "about how much of an enum the suite ever put to Metal. This one does, over the values " + "themselves." + ) + w("") + w( + "The denominator is generated, never written here: " + "`crates/metal2vulkan/src/metal/generated.rs` and the front end's hold every enumerator " + "name and ordinal `scripts/regen-metal-enums/` extracts from the SDK's Metal headers. A " + "Metal type this tree models by hand instead has **no denominator here** and is listed " + "apart, below." + ) + w("") + w("A value is **compared** where either of two things holds, which are different claims:") + w("") + w( + "- **answered** — the enumerator's name is in a committed recording's transcript of an " + "answer Metal **ran**. Metal named the value back at a site the comparison reads, so the " + "value is in the compared text itself." + ) + w( + "- **in effect** — a case module's own text names the value, and that module has at least " + "one case whose recording is a Metal run. Metal's recorded answer was taken with the " + "value in effect, so what is compared is Metal's behaviour **under** it, even where no " + "site reads it back. A blend factor is this and not the first: what the recording holds is " + "the texels Metal blended with it." + ) + w("") + w("What this axis cannot see, measured rather than asserted:") + w("") + w( + "- **A value Metal answers as a bare ordinal.** A transcript holds a `uint`, and nothing " + "in it says which enum the number belongs to, so only a site that records the enumerator's " + "**name** is read. The *answered* column is a floor by every site that records an ordinal " + "instead." + ) + w( + "- **A value a case states as a raw ordinal.** A case may hand the Metal leg an enum's " + "ordinal as a number — a sweep over `0..n` rather than over named variants — and no " + "reading of the text can say which value a computed number is. So *in effect*, and the " + "*stated* column of the hand-modelled table below, are floors by every sweep written that " + "way: a type they report short of its values may in fact be swept exhaustively, and the " + "case is what says so. Read the case before taking a row of the work list as work." + ) + w( + "- **Which case put a value in effect.** The unit is the case module, as it is for the " + "items axis: a value named anywhere in a module whose cases include a Metal run counts for " + "that module, even where one of its cases names it and the rest do not." + ) + w( + f"- **A value only the suite's shared sources name** — {shared} of them. Some case puts it " + "to Metal through the render or texture vocabulary, but which case is not a property of " + "the text, so it is neither compared nor missing and has its own column." + ) + w( + "- **Combinations.** Every column here is per value. A type whose values are all compared " + "says nothing about the pairs and triples of them, which is where most of the behaviour " + "an implementation can get wrong lives." + ) + w( + "- **Metal's API validation is excluded.** Its complaints name enumerators, and the suite " + "records that leg and never compares it, so reading it would count Apple's prose as a " + "comparison. So are the cost and timing tables: a site name there is what was measured, " + "not an answer that was compared." + ) + w( + "- **A `#[cfg(test)]` item is excluded.** One of the suite's unit tests names four blend " + "factors to assert that no case uses them; counting those would have this report the " + "opposite of what the code says." + ) + w("") + w("| | |") + w("|---|---|") + w(f"| Metal enums and option sets with a generated value list | {len(rows)} |") + w(f"| their values | {values} |") + w(f"| values compared | {compared} |") + w(f"| share compared | {100.0 * compared / values:.0f}% |") + w(f"| values only the suite's shared sources name | {shared} |") + w(f"| values no source names and no recording holds | {missing} |") + whole = sum(1 for row in rows if not row["missing"] and not row["shared"]) + w(f"| types every value of which is compared | {whole} |") + w(f"| types no value of which is compared | {sum(1 for r in rows if not r['compared'])} |") + w("") + largest = sorted(rows, key=lambda r: -len(r["values"]))[:4] + w( + "The share is weakly informative on its own: " + + ", ".join(f"`{row['metal']}`" for row in largest) + + f" hold {sum(len(row['values']) for row in largest)} of the {values} values between " + "them, so an aggregate over types this uneven is mostly theirs. The per-type table is the " + "one to read." + ) + w("") + w( + "### Depth by type" + ) + w("") + w( + "Deepest gap first, which is the order the work list reads in. *answered* and *in effect* " + "overlap; *compared* is their union." + ) + w("") + w("| Metal type | values | compared | answered | in effect | shared only | missing |") + w("|---|---|---|---|---|---|---|") + for row in sorted(rows, key=lambda r: (-len(r["missing"]), -len(r["shared"]), r["metal"])): + w( + f"| `{row['metal']}` | {len(row['values'])} | {len(row['compared'])} | " + f"{len(row['answered'])} | {len(row['in_effect'])} | {len(row['shared'])} | " + f"{len(row['missing'])} |" + ) + w("") + w("### The values not compared") + w("") + w( + "The work list. A name here is a value of Metal's that no committed recording holds and no " + "case module states **by name**: it is not a claim that Metal accepts the value on every " + "device, and not a claim that no case reaches it, because a case that sweeps a type by " + "ordinal states none of its values here. Each row is a question for the case, not a " + "verdict on it." + ) + w("") + for row in sorted(rows, key=lambda r: (-len(r["missing"]), r["metal"])): + if not row["missing"]: + continue + w(f"- **`{row['metal']}`**, {len(row['missing'])} of {len(row['values'])}: " + + names_line(row["missing"])) + w("") + only = [row for row in rows if row["shared"]] + if only: + w( + "And the values only the suite's shared sources name, which some case reaches and this " + "cannot attribute:" + ) + w("") + for row in sorted(only, key=lambda r: r["metal"]): + w(f"- **`{row['metal']}`**: " + names_line(row["shared"])) + w("") + w("### Metal types with no generated value list") + w("") + w( + "These the tree models by hand: a Rust item whose own doc comment opens by naming a Metal " + "type, and whose shape is a closed enum or a newtype over one integer. " + "`regen-metal-enums` holds no value list for them, so **this axis has no denominator " + "here**, and *declared* is our own sources' variant count rather than the SDK's — a " + "newtype option set declares none. There is no *answered* column either: a recording names " + "a value by its Metal enumerator, and for these types this has no list of those names to " + "match against. Giving one a denominator means appending its Metal name to " + "`scripts/regen-metal-enums/`'s `ENUMS` or `OPTIONS` and regenerating." + ) + w("") + w( + f"These {len(space['by_hand'])} are what that shape finds, and the list is a floor: a type " + "the tree models without saying so on the item lands in neither table, and so is nowhere " + "in this axis at all." + ) + w("") + w("| Metal type | the tree's type | declared | stated by a recorded case | shared only |") + w("|---|---|---|---|---|") + for row in space["by_hand"]: + w( + f"| `{row['metal']}` | `{row['rust']}` | {len(row['declared']) or '— a bit set'} | " + f"{len(row['stated'])} | {len(row['shared'])} |" + ) + w("") + + def write(data) -> str: """The document's text.""" rows, index, api, leg = data["rows"], data["index"], data["api"], data["leg"] @@ -480,6 +677,15 @@ def write(data) -> str: "sizes, and only the second is conformance." ) w("") + w( + "It says it along **two axes**, because either one alone reads as more than it is. The " + "**items** axis is reach: one call of a selector is enough, so a selector that takes an " + "enum counts as exercised whatever value reached it. The **option space** axis is depth: " + "of each Metal enum's and option set's values, which ones the suite compared. A high " + "number on the first and a low one on the second is what a suite that touches everything " + "shallowly looks like." + ) + w("") w("## What this measures, and what it cannot") w("") @@ -577,6 +783,8 @@ def write(data) -> str: ) w("") + write_option_space(w, data["option_space"]) + w("## By container") w("") w("Every container with an implemented item, by how much of it the suite reaches.") @@ -846,7 +1054,20 @@ def check_api() -> int: return 0 +def selftest() -> int: + """Run the option-space axis over inputs whose answers are known.""" + import unittest + + import test_option_space + + loaded = unittest.TestLoader().loadTestsFromModule(test_option_space) + found = unittest.TextTestRunner(verbosity=2).run(loaded) + return 0 if found.wasSuccessful() else 1 + + def main(argv: list[str]) -> int: + if "--selftest" in argv: + return selftest() if "--api" in argv: return check_api() text = write(inventory()) diff --git a/scripts/conformance-coverage/option_space.py b/scripts/conformance-coverage/option_space.py new file mode 100644 index 000000000..af70a9ec4 --- /dev/null +++ b/scripts/conformance-coverage/option_space.py @@ -0,0 +1,387 @@ +"""The suite's depth in each Metal enum and option set: which of a type's values it compared. + +`coverage.py`'s other axis is **reachability**: an item counts as exercised where a case's Metal +leg calls it, so one call is enough and a selector that takes an enum says nothing about how many +of that enum's values ever reached Metal. This is the second axis, over the values themselves. + +The denominator is generated, never written here: `crates/metal2vulkan/src/metal/generated.rs` and +`crates/metal2vulkan-air/src/metal/generated.rs` hold every enumerator name and ordinal of the +Metal types `scripts/regen-metal-enums/` extracts from the SDK headers. A Metal type the tree +models by hand instead has **no denominator here** and is reported as such rather than guessed at; +the fix is appending its name to that script's lists and regenerating. + +The numerator is two derived sets, which are different claims and are kept apart: + +- **answered** — the enumerator's name appears in a committed recording's transcript of an answer + Metal **ran**. Metal named the value back to us at a site the comparison reads, so the value is + in the compared text itself. +- **in effect** — a case module's own text names the value, and that module has at least one case + whose recording is a Metal run. Metal's recorded answer was taken with the value in effect, so + the comparison is of Metal's behaviour **under** that value even where no site reads it back. + +`compared` is their union. A value that only the suite's **shared** sources name (a default of the +render vocabulary, say) is counted in neither: some case puts it to Metal, but which case is not a +property of the text, so it is reported in its own column and is neither compared nor missing. + +# Why a value stated as a raw ordinal is not resolved, and must not be + +Both numerators read **names**. A case may instead hand the Metal leg an enum's ordinal as a +number — a sweep over `0..n`, or a literal field — and such a value appears nowhere by name, so +every column reads short of what the case does. That is stated as a limit in the document rather +than worked around, because the obvious way to close it is unsound: + +the leg types some of these fields itself (`MTLPixelFormat(request.format as usize)` says that +`format` holds a pixel format's ordinal), which invites reading every `format: ` in the +suite as a pixel format. It is not one. `recording.rs` declares `format: u32` for the **recording +format's version**, so `format: 1` there is version 1 and not `MTLPixelFormatA8Unorm`, and a rule +keyed on the field's name would quietly credit the suite with a value nothing ever set. One +vocabulary's word for a thing is not another's. + +So the floor stays a floor and says so. Closing it properly means a case stating its values by +name, or a transcript site recording the enumerator beside the ordinal it already stores — not a +cleverer reading of the text here. +""" + +import json +import re +from pathlib import Path + +import metal_leg + +#: The generated files holding the SDK's enumerator names and ordinals. +GENERATED = ( + "crates/metal2vulkan/src/metal/generated.rs", + "crates/metal2vulkan-air/src/metal/generated.rs", +) + +#: The published crates' sources, where a Metal type the tree models by hand is declared. +BY_HAND = ( + "crates/metal2vulkan-runtime/src", + "crates/metal2vulkan/src", + "crates/metal2vulkan-air/src", +) + +#: A recording answer whose transcript is Metal's own, rather than one the case carries. +RAN = "metal_run" + + +class Type: + """One Metal enum or option set, with the SDK's values as the generated table holds them.""" + + def __init__(self, metal: str, rust: str, kind: str, values: list[tuple[str, str]]): + #: The Metal type name, `MTLBlendFactor`. + self.metal = metal + #: The Rust name the tree gives it, `BlendFactor`. + self.rust = rust + #: `enum` for an `NS_ENUM`, `flags` for an `NS_OPTIONS`. + self.kind = kind + #: Each value as `(Rust name, Metal enumerator name)`, in declaration order. + self.values = values + + @property + def names(self) -> list[str]: + """The Metal enumerator names, in declaration order.""" + return [metal for _, metal in self.values] + + +def read_types(root: Path) -> dict[str, Type]: + """Every Metal type the generated tables hold, by Metal name. + + `MTLDataType` is in both files (the front end's, which `metal` re-exports); the first reading + wins, and the two are the same table. + """ + out: dict[str, Type] = {} + for name in GENERATED: + path = root / name + text = path.read_text() + found = 0 + for block in re.finditer(r"metal_(enum|flags)!\s*\{(.*?)\n\}\n", text, re.S): + kind, body = block.group(1), block.group(2) + head = re.match(r".*?\b(\w+)\s*=\s*\"(MTL\w+)\"\s*\{", body, re.S) + if head is None: + raise SystemExit(f"{name}: a {kind} block with no `Rust = \"MTLName\" {{` head") + declared, _, _ = body[head.end() :].partition("aliases {") + values = re.findall( + r"(\w+)\s*=\s*(?:0x[0-9a-fA-F]+|\d+),\s*\"(MTL\w+)\"\s*;", declared + ) + if not values: + raise SystemExit(f"{name}: {head.group(2)} parsed to no values") + found += 1 + out.setdefault(head.group(2), Type(head.group(2), head.group(1), kind, values)) + if not found: + # The parse silently matching nothing is the one way this axis can report a denominator + # of zero and look like a closed option space, so it is a failure, not a count. + raise SystemExit(f"{name}: no metal_enum!/metal_flags! block parsed") + return out + + +def without_tests(text: str) -> str: + """`blanked(text)` with every `#[cfg(test)]` item blanked too. + + A unit test naming a value is not the suite putting it to Metal, and one of them names four + blend factors to **assert that no case uses them**. Counting those would have the axis report + the opposite of what the code says. + """ + out = list(metal_leg.blanked(text)) + for attr in re.finditer(r"#\s*\[\s*cfg\s*\(\s*test\s*\)\s*\]", "".join(out)): + i = attr.end() + n = len(out) + # Skip the attributes between this one and the item it sits on. + while True: + while i < n and out[i].isspace(): + i += 1 + if i < n and out[i] == "#": + depth = 0 + while i < n: + if out[i] in "([{": + depth += 1 + elif out[i] in ")]}": + depth -= 1 + if depth == 0: + i += 1 + break + i += 1 + continue + break + # The item ends at its body's closing brace, or at the `;` of one with no body. A `;` or a + # brace inside brackets (`[u8; 4]`) is the type's, not the item's. + depth = 0 + end = None + while i < n: + char = out[i] + if char in "([": + depth += 1 + elif char in ")]": + depth -= 1 + elif depth == 0 and char == "{": + _, end = metal_leg.block("".join(out), i) + break + elif depth == 0 and char == ";": + end = i + 1 + break + i += 1 + if end is None: + raise SystemExit("a #[cfg(test)] item with neither a body nor a `;`") + for at in range(attr.start(), end): + if not out[at].isspace(): + out[at] = " " + return "".join(out) + + +def _stated_in(text: str, by_rust: dict[str, Type], by_metal: dict[str, Type]): + """The `(Metal type, value)` pairs `text` names, in either of the two spellings it uses. + + The suite names a Metal value two ways, and both have to be read: + + - through the tree's own type, `BlendFactor::SourceAlpha` — and `rotated_targets.rs` writes + `use BlendFactor as F;` and then every factor as `F::SourceAlpha`, so a derivation reading + only `BlendFactor::` spellings reports a third of that module's blend factors as never + exercised; + - through `objc2-metal`'s own enum, `MTLStorageMode::Private`, which the Metal leg writes + directly. `objc2` names a variant with its type's prefix dropped, so the enumerator is the + two spelled back together, and it counts only where that concatenation is a name the + generated table holds — never by assuming the rule held. + """ + alias: dict[str, str] = {} + for found in re.finditer(r"\b([A-Za-z_]\w*)\s+as\s+([A-Za-z_]\w*)\b", text): + if found.group(1) in by_rust: + alias[found.group(2)] = found.group(1) + out: set[tuple[str, str]] = set() + for found in re.finditer(r"\b([A-Za-z_]\w*)::([A-Za-z_]\w*)\b", text): + head, tail = found.group(1), found.group(2) + held = by_rust.get(alias.get(head, head)) + if held is not None: + for rust, value in held.values: + if rust == tail: + out.add((held.metal, value)) + held = by_metal.get(head) + if held is None: + continue + if head + tail in held.names: + out.add((held.metal, head + tail)) + elif held.kind == "by hand" and tail in held.names: + # A hand-modelled type has no SDK enumerator list, so our own variant name is the only + # name there is; `objc2` spells the same value the same way after the prefix. + out.add((held.metal, tail)) + return out + + +def stated(root: Path, types: dict[str, Type], ran: set[str]): + """The values each case module names, and the ones only the suite's shared sources name. + + `ran` is the case modules with at least one committed recording of an answer Metal ran; a + module not in it puts nothing to Metal however much its text names. + """ + by_rust = {held.rust: held for held in types.values()} + by_metal = {held.metal: held for held in types.values()} + src = root / "crates/metal2vulkan-conformance/src" + in_effect: dict[tuple[str, str], set[str]] = {} + for path in sorted((src / "cases").glob("*.rs")): + if path.stem not in ran: + continue + for pair in _stated_in(without_tests(path.read_text()), by_rust, by_metal): + in_effect.setdefault(pair, set()).add(path.stem) + shared: set[tuple[str, str]] = set() + for path in sorted(src.rglob("*.rs")): + held = path.relative_to(src) + if held.parts[0] in ("cases", "tests", "bin") or held.name == "tests.rs": + continue + shared |= _stated_in(without_tests(path.read_text()), by_rust, by_metal) + return in_effect, shared + + +def _tokens(value, key: str | None, out: list[str]) -> None: + """Every identifier-shaped token of a transcript value, less the base64 of its bytes.""" + if isinstance(value, str): + if key != "bytes": + out.extend(re.findall(r"[A-Za-z0-9_]+", value)) + elif isinstance(value, dict): + for name, held in value.items(): + _tokens(held, name, out) + elif isinstance(value, list): + for held in value: + _tokens(held, key, out) + + +def answered(root: Path, types: dict[str, Type]) -> dict[tuple[str, str], set[str]]: + """The values a committed recording's compared transcript holds, by the cases holding them. + + Only `answers[].outcomes[].transcript` is read. An answer's `validated` leg is Metal's API + validation, which the suite records and **never compares**, and its complaints name + enumerators; reading it would count Apple's prose as a comparison. The cost and timing tables + are not read either: a site name there is what was measured, not an answer that was compared. + """ + of_name = {metal: held.metal for held in types.values() for metal in held.names} + out: dict[tuple[str, str], set[str]] = {} + for path in sorted((root / "crates/metal2vulkan-conformance/recordings").glob("*.json")): + data = json.loads(path.read_text()) + found: list[str] = [] + for answer in data.get("answers", []): + if answer.get("provenance") != RAN: + continue + for outcome in answer.get("outcomes", []): + _tokens(outcome.get("transcript"), None, found) + for token in set(found): + if token in of_name: + out.setdefault((of_name[token], token), set()).add(data["case"]) + return out + + +#: A Rust item the tree declares to be one Metal enum or option set: a doc comment naming the +#: Metal type, then the item it documents, which is a closed enum (an `NS_ENUM`) or a newtype over +#: one integer (an `NS_OPTIONS`). A multi-field struct is a Metal *structure*, and a class or +#: descriptor is neither, so the shape of the item is what tells the three apart. +MODELS = re.compile( + r"///\s*`(MTL\w+)`[^\n]*\n(?:[ \t]*(?:///[^\n]*|#\[[^\n]*\])\n)*" + r"[ \t]*pub\s+(?:(enum)\s+([A-Za-z_]\w*)\s*\{" + r"|(struct)\s+([A-Za-z_]\w*)\s*\(\s*u(?:8|16|32|64|size)\s*\)\s*;)" +) + + +def _opens_the_doc(source: str, at: int) -> bool: + """Whether the doc line at `at` is the first of its item's doc block. + + The generated enums write the Metal name on the first line, and so do the hand-written ones. A + name mentioned part-way through a paragraph is prose about a Metal type, not a declaration of + being one: `CommandDescriptor`'s doc says it models `MTLIndirectCommandBufferDescriptor` "as + far as the record format needs it", which is a description and not that enum. + """ + before = source.rfind("\n", 0, at) + if before < 0: + return True + line = source[source.rfind("\n", 0, before) + 1 : before] + return not line.lstrip().startswith("///") + + +def by_hand(root: Path, types: dict[str, Type]) -> list[tuple[str, str, list[str]]]: + """The Metal enums and option sets the tree models by hand, with our own variant names. + + Found by shape: a doc comment naming a Metal type on an item that is a closed Rust enum or a + newtype over one integer. These have **no generated value list**, so this axis has no + denominator for them, and the names returned are our own sources', not the SDK's. An option-set + newtype declares no variants and returns an empty list. + + The list is itself a floor: a type the tree models without saying so in a doc comment on the + item is in neither table and nowhere in this axis. + """ + out: dict[str, tuple[str, list[str]]] = {} + for where in BY_HAND: + for path in sorted((root / where).rglob("*.rs")): + if "tests" in path.parts or path.name in ("generated.rs", "tests.rs"): + continue + source = path.read_text() + # `blanked` keeps every offset, so the brace walk below reads against the source. It + # is a character loop over the whole file, so it runs only where a match needs it: + # almost no file in these crates declares one of these types. + text: str | None = None + for found in MODELS.finditer(source): + metal = found.group(1) + if metal in types or not _opens_the_doc(source, found.start()): + continue + if found.group(2): + if text is None: + text = metal_leg.blanked(source) + start, end = metal_leg.block(text, found.end() - 1) + names = re.findall(r"^\s*([A-Z]\w*)\s*(?:,|\{|\(|$)", text[start:end], re.M) + out[metal] = (found.group(3), names) + else: + out[metal] = (found.group(5), []) + return [(metal, rust, names) for metal, (rust, names) in sorted(out.items())] + + +def inventory(root: Path, ran: set[str]) -> dict: + """The axis, derived: every type with its three sets of values.""" + types = read_types(root) + hand = by_hand(root, types) + # A hand-modelled type is carried through the same resolution, keyed by its own Rust variant + # names: this axis has no SDK enumerator list for it, so a variant is all there is to name. + held = dict(types) + for metal, rust, names in hand: + held[metal] = Type(metal, rust, "by hand", [(name, name) for name in names]) + effect, shared = stated(root, held, ran) + read_back = answered(root, types) + rows = [] + for metal, held in sorted(types.items()): + compared, only_shared, missing = [], [], [] + for name in held.names: + key = (metal, name) + if key in read_back or key in effect: + compared.append(name) + elif key in shared: + only_shared.append(name) + else: + missing.append(name) + rows.append( + { + "metal": metal, + "rust": held.rust, + "kind": held.kind, + "values": held.names, + "compared": compared, + "answered": [n for n in held.names if (metal, n) in read_back], + "in_effect": [n for n in held.names if (metal, n) in effect], + "shared": only_shared, + "missing": missing, + "modules": sorted({m for n in held.names for m in effect.get((metal, n), ())}), + } + ) + hand_rows = [ + { + "metal": metal, + "rust": rust, + "declared": names, + "stated": [name for name in names if (metal, name) in effect], + "shared": [ + name + for name in names + if (metal, name) not in effect and (metal, name) in shared + ], + } + for metal, rust, names in hand + ] + return { + "rows": rows, + "by_hand": hand_rows, + "answered": read_back, + "in_effect": effect, + } diff --git a/scripts/conformance-coverage/test_option_space.py b/scripts/conformance-coverage/test_option_space.py new file mode 100644 index 000000000..87436ce87 --- /dev/null +++ b/scripts/conformance-coverage/test_option_space.py @@ -0,0 +1,366 @@ +"""The option-space axis over inputs whose answers are known. + +Run by `coverage.py --selftest`, which is what the suite's +`the_option_space_axis_still_measures_what_it_claims` runs. + +The axis is a derivation over text, and the way a derivation like it fails is by quietly matching +nothing: a renamed JSON key, a spelling the sources use that the regex does not, and every count +reads zero while the document still looks like a measurement. So each test here builds its own +little tree, where the answer is known by construction, and asserts both directions — that a value +it should find is found, and that a value it must not count is not. + +Every test owns its inputs. Nothing here reads the repository. +""" + +import json +import shutil +import tempfile +import unittest +from pathlib import Path + +import option_space + +#: Every tree `tree` made, removed by `tearDownModule`. Each test wants a fresh one and none of +#: them wants it afterwards, so one list and one sweep is the whole lifetime. +MADE: list[Path] = [] + + +def tearDownModule() -> None: + """Remove the trees the tests built.""" + while MADE: + shutil.rmtree(MADE.pop(), ignore_errors=True) + +#: A generated table of one enum and one option set, as `regen-metal-enums` writes them. +GENERATED = """\ +// Generated from the macOS 27.0 SDK Metal.framework headers (names and values). + +metal_enum! { + /// `MTLThing`. + #[non_exhaustive] + Thing = "MTLThing" { + Alpha = 0, "MTLThingAlpha"; + Beta = 1, "MTLThingBeta"; + Gamma = 2, "MTLThingGamma"; + Delta = 3, "MTLThingDelta"; + Epsilon = 4, "MTLThingEpsilon"; + Zeta = 5, "MTLThingZeta"; + } + aliases { + "MTLThingOldBeta" => Beta; + } +} + +metal_flags! { + /// `MTLSpread`. + Spread = "MTLSpread" { + NONE = 0, "MTLSpreadNone"; + LEFT = 0x1, "MTLSpreadLeft"; + RIGHT = 0x2, "MTLSpreadRight"; + } + aliases { + } + dropped { + } +} +""" + + +def tree( + cases: dict[str, str], + shared: str = "", + recordings: tuple[dict, ...] = (), + generated: str = GENERATED, +) -> Path: + """A repository-shaped tree of exactly these sources and recordings.""" + root = Path(tempfile.mkdtemp(prefix="option-space-selftest-")) + MADE.append(root) + for name in option_space.GENERATED: + path = root / name + path.parent.mkdir(parents=True, exist_ok=True) + # The front end's file holds a different type in the tree; here one copy is enough, and + # `read_types` keeping the first reading is what this relies on. + path.write_text(generated) + for name in option_space.BY_HAND: + (root / name).mkdir(parents=True, exist_ok=True) + suite = root / "crates/metal2vulkan-conformance" + (suite / "src/cases").mkdir(parents=True, exist_ok=True) + (suite / "recordings").mkdir(parents=True, exist_ok=True) + for module, text in cases.items(): + (suite / "src/cases" / f"{module}.rs").write_text(text) + (suite / "src/side.rs").write_text(shared) + for data in recordings: + (suite / "recordings" / f"{data['case']}.json").write_text(json.dumps(data)) + return root + + +def recording(case: str, value: str, provenance: str = option_space.RAN, where: str = "ran") -> dict: + """A recording of `case` whose transcript, or whose validated leg, names `value`.""" + node = { + "name": "case", + "observed": {"value": {"fields": {"factor": {"fields": {"name": {"lines": [value]}}}}}}, + } + answer = {"provenance": provenance, "runs": 1, "outcomes": []} + if where == "ran": + answer["outcomes"] = [{"runs": 1, "transcript": {"root": node}}] + else: + answer["outcomes"] = [{"runs": 1, "transcript": {"root": {"name": "case"}}}] + answer["validated"] = {"stopped": {"message": f"Thing Validation\n{value} is not allowed"}} + return {"format": 1, "case": case, "suite_version": 1, "answers": [answer]} + + +def axis(root: Path, ran: set[str]): + """The axis over `root`, as the one row of `MTLThing`.""" + held = option_space.inventory(root, ran) + return next(row for row in held["rows"] if row["metal"] == "MTLThing") + + +class Denominator(unittest.TestCase): + """The value list comes from the generated tables, and a parse of nothing is a failure.""" + + def test_the_values_are_the_generated_table_s(self): + row = axis(tree({}), set()) + self.assertEqual(len(row["values"]), 6) + self.assertEqual(row["values"][0], "MTLThingAlpha") + self.assertEqual(row["compared"], []) + self.assertEqual(row["missing"], row["values"]) + + def test_an_option_set_s_named_combinations_are_values(self): + held = option_space.inventory(tree({}), set()) + row = next(r for r in held["rows"] if r["metal"] == "MTLSpread") + self.assertEqual(row["values"], ["MTLSpreadNone", "MTLSpreadLeft", "MTLSpreadRight"]) + + def test_a_generated_file_that_parses_to_nothing_fails(self): + with self.assertRaises(SystemExit): + option_space.read_types(tree({}, generated="// nothing at all\n")) + + def test_a_type_that_parses_to_no_values_fails(self): + broken = GENERATED.replace('Alpha = 0, "MTLThingAlpha";', "").replace( + 'Beta = 1, "MTLThingBeta";', "" + ) + broken = broken.replace('Gamma = 2, "MTLThingGamma";', "") + broken = broken.replace('Delta = 3, "MTLThingDelta";', "") + broken = broken.replace('Epsilon = 4, "MTLThingEpsilon";', "") + broken = broken.replace('Zeta = 5, "MTLThingZeta";', "") + with self.assertRaises(SystemExit): + option_space.read_types(tree({}, generated=broken)) + + +class InEffect(unittest.TestCase): + """A value a recorded case module states is in effect; one it does not is not.""" + + def test_a_value_a_case_module_names_is_in_effect(self): + row = axis(tree({"blends": "fn go() { let x = Thing::Beta; }"}), {"blends"}) + self.assertEqual(row["in_effect"], ["MTLThingBeta"]) + self.assertIn("MTLThingBeta", row["compared"]) + self.assertNotIn("MTLThingBeta", row["missing"]) + + def test_an_aliased_spelling_is_in_effect(self): + # `use Thing as T;` and then `T::Gamma`, which is how the blend sweeps are written. A + # derivation reading only `Thing::` spellings reports this value as never exercised. + row = axis(tree({"blends": "use Thing as T;\nfn go() { let x = T::Gamma; }"}), {"blends"}) + self.assertEqual(row["in_effect"], ["MTLThingGamma"]) + + def test_the_objc2_spelling_is_in_effect(self): + # `MTLThing::Delta`, which is how the Metal leg names a fixed value: `objc2` drops the + # type's prefix, so the enumerator is the two spelled back together. + row = axis(tree({"blends": "fn go() { d.set(MTLThing::Delta); }"}), {"blends"}) + self.assertEqual(row["in_effect"], ["MTLThingDelta"]) + + def test_an_objc2_spelling_of_no_generated_name_is_not_counted(self): + row = axis(tree({"blends": "fn go() { d.set(MTLThing::Omega); }"}), {"blends"}) + self.assertEqual(row["in_effect"], []) + + def test_a_module_with_no_metal_run_recording_puts_nothing_in_effect(self): + text = "fn go() { let x = Thing::Beta; }" + self.assertEqual(axis(tree({"blends": text}), set())["in_effect"], []) + self.assertEqual(axis(tree({"blends": text}), {"blends"})["in_effect"], ["MTLThingBeta"]) + + def test_a_cfg_test_item_is_not_in_effect(self): + text = ( + "fn go() { let x = Thing::Beta; }\n" + "#[cfg(test)]\nmod tests {\n" + " #[test]\n fn refused() { assert!(!matches!(f, Thing::Zeta)); }\n" + "}\n" + ) + row = axis(tree({"blends": text}), {"blends"}) + self.assertEqual(row["in_effect"], ["MTLThingBeta"]) + self.assertIn("MTLThingZeta", row["missing"]) + + def test_a_cfg_test_item_with_no_body_is_blanked_to_its_semicolon(self): + text = ( + "#[cfg(test)]\nconst WIDTHS: [u8; 4] = [Thing::Zeta as u8; 4];\n" + "fn go() { let x = Thing::Beta; }\n" + ) + row = axis(tree({"blends": text}), {"blends"}) + self.assertEqual(row["in_effect"], ["MTLThingBeta"]) + + def test_a_sweep_by_ordinal_states_nothing(self): + # The boundary of this column, kept visible: a case that hands the leg `0..n` reaches every + # value and names none, so the column reads zero and the document says it is a floor by + # exactly this. There is no sound textual reading of a computed ordinal, so the test holds + # the limit rather than a fix for it. + text = "fn go() { for raw in 0..6 { side.set_thing(raw); } }" + self.assertEqual(axis(tree({"sweep": text}), {"sweep"})["in_effect"], []) + + def test_a_comment_naming_a_value_is_not_in_effect(self): + row = axis(tree({"blends": "// Thing::Beta is what Metal defaults to.\nfn go() {}"}), {"blends"}) + self.assertEqual(row["in_effect"], []) + + +class Answered(unittest.TestCase): + """A value a recording's compared transcript holds is answered; the other legs are not read.""" + + def test_a_value_in_a_run_transcript_is_answered(self): + root = tree({}, recordings=(recording("one", "MTLThingGamma"),)) + row = axis(root, set()) + self.assertEqual(row["answered"], ["MTLThingGamma"]) + self.assertIn("MTLThingGamma", row["compared"]) + + def test_a_carried_answer_is_not_answered(self): + root = tree({}, recordings=(recording("one", "MTLThingGamma", provenance="carried"),)) + row = axis(root, set()) + self.assertEqual(row["answered"], []) + self.assertIn("MTLThingGamma", row["missing"]) + + def test_the_validated_leg_is_not_answered(self): + root = tree({}, recordings=(recording("one", "MTLThingGamma", where="validated"),)) + row = axis(root, set()) + self.assertEqual(row["answered"], []) + + def test_base64_bytes_are_not_read_as_names(self): + # A recorded buffer is base64, and the alphabet is alphanumeric, so a payload **can** spell + # an enumerator name exactly: `MTLThingZeta` is twelve characters of the base64 alphabet, + # which is to say nine bytes of some texture. Reading it would credit the suite with a + # value from the contents of a buffer. + data = recording("one", "MTLThingGamma") + data["answers"][0]["outcomes"][0]["transcript"]["root"]["observed"] = { + "value": {"bytes": "MTLThingZeta"} + } + row = axis(tree({}, recordings=(data,)), set()) + self.assertEqual(row["answered"], []) + + def test_a_compound_site_name_is_split_into_its_tokens(self): + data = recording("one", "MTLThingGamma") + data["answers"][0]["outcomes"][0]["transcript"]["root"] = { + "name": "MTLThingZeta/TextureBuffer/64x1x1", + "observed": {"value": "absent"}, + } + row = axis(tree({}, recordings=(data,)), set()) + self.assertEqual(row["answered"], ["MTLThingZeta"]) + + +class SharedOnly(unittest.TestCase): + """A value only the suite's shared sources name is its own column, not a gap.""" + + def test_a_value_only_shared_sources_name_is_neither_compared_nor_missing(self): + row = axis(tree({}, shared="fn go() { d.set(Thing::Delta); }"), set()) + self.assertEqual(row["shared"], ["MTLThingDelta"]) + self.assertNotIn("MTLThingDelta", row["compared"]) + self.assertNotIn("MTLThingDelta", row["missing"]) + + def test_a_case_module_naming_it_takes_it_out_of_shared(self): + root = tree( + {"blends": "fn go() { let x = Thing::Delta; }"}, + shared="fn go() { d.set(Thing::Delta); }", + ) + row = axis(root, {"blends"}) + self.assertEqual(row["shared"], []) + self.assertEqual(row["in_effect"], ["MTLThingDelta"]) + + def test_every_value_is_in_exactly_one_column(self): + root = tree( + {"blends": "use Thing as T;\nfn go() { let x = T::Beta; }"}, + shared="fn go() { d.set(Thing::Delta); }", + recordings=(recording("one", "MTLThingGamma"),), + ) + row = axis(root, {"blends"}) + self.assertEqual( + len(row["compared"]) + len(row["shared"]) + len(row["missing"]), len(row["values"]) + ) + self.assertEqual(sorted(row["compared"]), ["MTLThingBeta", "MTLThingGamma"]) + self.assertEqual(row["shared"], ["MTLThingDelta"]) + self.assertEqual(row["missing"], ["MTLThingAlpha", "MTLThingEpsilon", "MTLThingZeta"]) + + +class ByHand(unittest.TestCase): + """A Metal type the tree models by hand is reported apart, with no denominator.""" + + SOURCE = """\ +/// `MTLThingy`. +pub enum Thingy { + /// `MTLThingyFirst`. + First, + /// `MTLThingySecond`. + Second, +} + +impl Thingy { + pub fn from_raw(raw: u64) -> Result { + Ok(match raw { + 0 => Thingy::First, + 1 => Thingy::Second, + raw => return Err(undefined("MTLThingy", raw)), + }) + } +} +""" + + def held(self, cases: dict[str, str], ran: set[str]): + root = tree(cases) + (root / option_space.BY_HAND[0] / "values.rs").write_text(self.SOURCE) + found = option_space.inventory(root, ran) + return next(row for row in found["by_hand"] if row["metal"] == "MTLThingy") + + def test_a_hand_modelled_type_is_found_with_its_own_variants(self): + row = self.held({}, set()) + self.assertEqual(row["rust"], "Thingy") + self.assertEqual(row["declared"], ["First", "Second"]) + self.assertEqual(row["stated"], []) + + def test_a_recorded_case_naming_one_states_it(self): + row = self.held({"blends": "fn go() { let x = Thingy::Second; }"}, {"blends"}) + self.assertEqual(row["stated"], ["Second"]) + + def test_the_objc2_spelling_of_a_hand_modelled_type_states_it(self): + row = self.held({"blends": "fn go() { c.setThing(MTLThingy::First); }"}, {"blends"}) + self.assertEqual(row["stated"], ["First"]) + + def test_an_option_set_newtype_is_listed_with_no_variants(self): + root = tree({}) + (root / option_space.BY_HAND[0] / "values.rs").write_text( + "/// `MTLThingOptions`.\n#[repr(transparent)]\npub struct ThingOptions(u64);\n" + ) + found = option_space.inventory(root, set()) + row = next(r for r in found["by_hand"] if r["metal"] == "MTLThingOptions") + self.assertEqual((row["rust"], row["declared"]), ("ThingOptions", [])) + + def test_a_metal_structure_is_not_an_option_space(self): + # `MTLOrigin` is a structure of three numbers, not an enum; it has no values to count. + root = tree({}) + (root / option_space.BY_HAND[0] / "values.rs").write_text( + "/// `MTLWhere`.\npub struct Where {\n pub x: u64,\n pub y: u64,\n}\n" + ) + self.assertEqual(option_space.inventory(root, set())["by_hand"], []) + + def test_a_metal_name_part_way_through_a_doc_is_prose(self): + # A type that says it models part of a Metal type is describing itself, not declaring that + # it is that type's value list. + root = tree({}) + (root / option_space.BY_HAND[0] / "values.rs").write_text( + "/// What a buffer allows (Metal's\n" + "/// `MTLThingy`, as far as the format needs it): the kinds it takes.\n" + "pub enum Shape {\n First,\n Second,\n}\n" + ) + self.assertEqual(option_space.inventory(root, set())["by_hand"], []) + + def test_a_generated_type_is_not_listed_as_hand_modelled(self): + root = tree({}) + (root / option_space.BY_HAND[0] / "values.rs").write_text( + self.SOURCE.replace("MTLThingy", "MTLThing") + ) + found = option_space.inventory(root, set()) + self.assertEqual([row["metal"] for row in found["by_hand"]], []) + + +if __name__ == "__main__": + unittest.main()