From feb0dca3ecb45656bc7cfe3eb160308483c922a7 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Sat, 24 Oct 2026 17:43:24 +0300 Subject: [PATCH] Hold a crossing's field axis to the field its module's own data states The steps this packet landed as, in order: - Declare the crossings two pass families already hold Content: the tree of `development` at a4805b6ba1, unchanged. --- docs/CONFORMANCE-COVERAGE.md | 20 ++- scripts/conformance-coverage/coverage.py | 147 +++++++++++++++--- scripts/conformance-coverage/metal_leg.py | 114 ++++++++++++-- scripts/conformance-coverage/option_space.py | 41 ++++- .../conformance-coverage/other_crossings.tsv | 25 ++- .../conformance-coverage/test_option_space.py | 35 ++++- 6 files changed, 321 insertions(+), 61 deletions(-) diff --git a/docs/CONFORMANCE-COVERAGE.md b/docs/CONFORMANCE-COVERAGE.md index 3c7e7a4dd..83c7479ce 100644 --- a/docs/CONFORMANCE-COVERAGE.md +++ b/docs/CONFORMANCE-COVERAGE.md @@ -45,7 +45,7 @@ Its limits, measured rather than asserted: | of those, reached only where this cannot name the family | 7 | | ledger rows (a case whose gap is recorded) | 87 | | declared crossings of the option space (pairs put to Metal at once) | 24 | -| declared crossings that are no pair of it (a boolean or numeric field, or one type in two slots) | 26 | +| declared crossings that are no pair of it (a boolean or numeric field, or one type in two slots) | 30 | A tolerance names a **site of a transcript**, not an item, so the last two rows are read as written: a case that loosens one site of its own transcript may compare every other field of it exactly, and this derivation cannot tell which of a case's fields came from which Metal call. Where the distinction matters, read the case. @@ -223,18 +223,18 @@ An axis there is a Metal enum with a generated value list, which **may** be name **This document is not written** if such a row names a module no case of which ran Metal, a cell that is not one of that module's recorded cases, fewer than two axes, nothing that the cross decides, or an **enum** axis of which the module's own text states fewer than two values by name. Three refusals are this table's own: - **a row every axis of which is a Metal enum named once.** That is a pair of the option space: it belongs in the table above, under the check that the module states two values of each axis, and a row parked here would be the same claim under a weaker rule; -- **a field axis `objc2-metal` binds no such item for, or one this module's Metal leg reaches no call of.** The second is the items axis's own join, so a field axis names a call this document already reports as exercised rather than a word a row's author chose; +- **a field axis `objc2-metal` binds no such item for, or one this module's own data never reaches.** The leg must hold a call of that field at a site whose guards this module's text satisfies. Reachability is the items axis's own join, so a field axis names a call this document already reports as exercised rather than a word a row's author chose; the guards are what make the row a claim about that **field** and not about any field of its Metal type. One shared encoder sets a pass descriptor's fields in one function, each under `if let Some(x) = pass.field`, so by reachability alone every case that opens a pass reaches them all — which would let a case attaching no visibility buffer declare a crossing on `visibilityResultBuffer`; - **a field axis whose call answers a Metal type with a generated value list.** Such a field is an enum under another name — `MTLTextureDescriptor.storageMode` is one — and naming it as a field would dodge the two-values check the enum spelling carries. -What **cannot** be checked for a field axis, and is therefore what only a reader can check: that the module put **two values** of the field to Metal. A boolean's two values and a number's range are nowhere in the text this reads and in no recording's transcript, so a field axis carries the field being Metal's and this module's leg setting it, and nothing about variation. An enum axis carries the two-values check here exactly as it does above, which is why a row's enum axes are the stronger half of it. The last column, as above, is for a reader against the case. +What **cannot** be checked for a field axis, and is therefore what only a reader can check: that the module put **two values** of the field to Metal. A boolean's two values and a number's range are nowhere in the text this reads and in no recording's transcript, so a field axis carries the field being Metal's and this module stating it, and nothing about variation — and a field a module states as `None` or `false` reads here exactly like one it states a value for. For the same reason a **bare boolean** guard in the leg (`if descriptor.read_only {`) is no guard here: its body is reached on one of the field's two values, and which one a case states is what this cannot see. An enum axis carries the two-values check here exactly as it does above, which is why a row's enum axes are the stronger half of it. The last column, as above, is for a reader against the case. | | | |---|---| -| crossings declared that are not pairs of the option space | 26 | -| of those, naming a type in two or more slots | 5 | -| of those, naming a Metal field that is a boolean or a number | 22 | -| distinct Metal fields crossed | 25 | -| distinct Metal types crossed with themselves | 5 | +| crossings declared that are not pairs of the option space | 30 | +| of those, naming a type in two or more slots | 8 | +| of those, naming a Metal field that is a boolean or a number | 23 | +| distinct Metal fields crossed | 27 | +| distinct Metal types crossed with themselves | 6 | The two *of those* rows are not a partition and do not sum to the first: a row may name both, as the sampler row crossing its two filter slots with a LOD clamp does. @@ -253,6 +253,10 @@ The two *of those* rows are not a partition and do not sum to the first: a row m | `layered_targets` | `layered-attachment-places` | `MTLRenderPassAttachmentDescriptor.slice` x `MTLRenderPassAttachmentDescriptor.depthPlane` | which of the two fields selects the plane rendered, which is the target's own shape's to decide: an array texture's plane is `slice`'s and a 3D texture's is `depthPlane`'s, so the same number in the other field reaches **nothing** and the plane renders at 0. Each field alone reads as the one that selects a plane, because the cell where it is 0 is the cell the other field was selecting with; only the pair says which field the shape listens to | | `layered_targets` | `layered-depth-other-slice` | `MTLRenderPassAttachmentDescriptor.slice` x `MTLRenderPassAttachmentDescriptor.slice` | whether the slice a pass renders is the **attachment's** or the pass's. Each attachment takes its own: a pass whose colour is at slice 2 and whose depth is at slice 0 writes both, each at its own slice. The cell where the two agree is right under either rule, and only the two unequal cells part a side that took one attachment's slice for the whole pass -- which then leaves the other attachment's plane untouched and writes a plane nothing asked for | | `layered_targets` | `layered-render-target-array-length` | `MTLRenderPassDescriptor.renderTargetArrayLength` x `MTLRenderPassAttachmentDescriptor.slice` | which slices a pass reaches: the layer count says how many and the attachment's slice says where they start, so the shader's layer `i` lands in slice `slice + i` and the load and store actions cover exactly those. At a count of 2 from slice 1 the pass writes slices 1 and 2 and leaves slice 0 and slice 3 as an earlier pass left them -- the cell a count at slice 0, or a slice at the default count, reads identically to a side that took the layer absolutely | +| `pass_attachment_pairs` | `pass-two-attachments-loads` | `MTLLoadAction` x `MTLLoadAction` | which attachment each load action is read from, in one pass whose two colour attachments state different ones. An earlier pass of the same command buffer stores a different value into each, so a `Load` shows a value no clear of this pass states and the two attachments' prior values differ: the two off-diagonal pairs are the cells only the pair reaches, and a side that applied colour 0's load action to colour 1 answers both diagonal cells exactly and both off-diagonal ones wrongly. The 36 (load, store, options) triples of `pass_descriptors` read the fields back off one attachment and never render two that disagree | +| `pass_attachment_pairs` | `pass-two-attachments-loads` | `MTLPixelFormat` x `MTLPixelFormat` | which attachment each format is read from. `RGBA32Float` beside `R32Float` and the swap make the two planes different sizes **and** leave attachment 1 holding red alone, so a side that took one attachment's format for the other cannot answer the cell at all -- where the equal pair answers the same under every rule, and a sweep of one format at a time is a one-attachment question that no pairing can falsify | +| `pass_attachment_pairs` | `pass-two-attachments-resolves` | `MTLStoreAction` x `MTLStoreAction` | which attachment's resolve texture a resolving store writes into: `MultisampleResolve` at one attachment beside `DontCare` at the other, which a depth-only pass has one attachment to state. Colour 0 resolving alone, colour 1 alone and both are the three cells, and a side that took attachment 0's resolve texture for attachment 1 writes colour 0's value into colour 1's texture in the two cells where attachment 1 resolves while answering the colour-0-alone cell exactly. An attachment stored `DontCare` carries no resolve texture, so neither slot's own sweep ever has a second attachment to confuse it with | +| `pass_bound_pairs` | `pass-bound-clear-reach` | `MTLRenderPassDescriptor.renderTargetWidth` x `MTLRenderPassDescriptor.renderTargetHeight` x `MTLLoadAction` x `MTLRenderCommandEncoder.drawPrimitives:vertexStart:vertexCount:instanceCount:baseInstance:` | which texels of an attachment **larger than its pass's render area** the pass changes, and to what. A `Clear` load clears from the origin over the render area rounded up to whole 32-pixel tiles and clipped to the attachment where the pass encodes a draw, the whole level and slice where it encodes none, and a `Load` load keeps every texel whatever the area: so each axis moves a plane only at the others' settings and a case that fixes two of the three says nothing about the other cells. The two numbers are separate axes because the rounding is **per axis** -- the 8 by 40 and 40 by 8 cells are where a side that rounded the larger side, or took one axis's reach for both, answers the square cells exactly and those two wrongly -- and `draw-covers-nothing` beside `no-draw-call` is where a side that read the draw axis as whether a draw *wrote* anything answers two cells alike and both wrongly. The number sweep of `pass_descriptors` reads the two numbers back off a descriptor and renders through neither | | `pass_sequence_actions` | `pass-sequence-aspect-actions` | `MTLStoreAction` x `MTLStoreAction` x `MTLLoadAction` x `MTLLoadAction` | which attachment each aspect's action is read from, across a pass boundary where the two aspects disagree in both passes. Pass A stores the depth and discards the stencil, or the reverse, and pass B loads one aspect and clears the other: the depth plane is then a function of the depth's two slots and the stencil plane of the stencil's, and a side that took one aspect's slot for both answers the three symmetric cells exactly and the six asymmetric ones wrongly. Measured: taking the depth attachment's action for the stencil's scratch copy moves four of the nine cells, every one of them in the stencil plane and none in the depth plane | | `pass_sequence_actions` | `pass-sequence-color-actions` | `MTLRenderPassDescriptor.renderTargetWidth` x `MTLStoreAction` x `MTLLoadAction` | whether the next pass's render area bounds what its load action does to what the last pass stored. A `MTLLoadActionLoad` under a 32 by 32 area of a 40 by 40 attachment keeps every texel, so the bound moves **not one** against the whole-area cell -- the independence `pass_bound_pairs` measured inside one pass, holding across the boundary. A `MTLLoadActionClear` under the same bound clears its own tiles and leaves the 8 texels past them holding **what pass A's store action left there**, so the store action is visible through a `Clear` after all, which it is not over the whole attachment. Neither the area alone nor either action alone reaches either cell | | `sampler_crossings` | its cases | `MTLSamplerMinMagFilter` x `MTLSamplerMinMagFilter` x `MTLSamplerDescriptor.lodMinClamp` | which of the two filters reads the level `lodMinClamp` raised the requested one to. The two `(min, mag)` pairs whose filters agree answer the same under every rule, so only an unequal pair at a clamp above the sampled level parts Metal's rule from Vulkan's -- the magnifying filter at a level of zero or less, the minifying one above it -- and from a `NotMipmapped` sampler's, which ignores the clamp outright | diff --git a/scripts/conformance-coverage/coverage.py b/scripts/conformance-coverage/coverage.py index 1b5b04a56..82ae0bbb0 100644 --- a/scripts/conformance-coverage/coverage.py +++ b/scripts/conformance-coverage/coverage.py @@ -279,11 +279,13 @@ def messaged_rows(leg: metal_leg.Leg, api: metal_leg.Api, selves) -> dict[int, s def gated_items(leg: metal_leg.Leg, entry_points: set[str], keyed, messaged, frees): - """For each entry point, the items it reaches and the variants each reaching needs. + """For each entry point, the items it reaches and the gates each reaching needs. One walk of the leg's own call graph. A call inside `Step::GetBytes =>` is reached only by a - case that encodes that step, so the variants of the `match` arms around a call travel with it; - a call under no arm is reached by every case that calls the entry point at all. + case that encodes that step, and one inside `if let Some(b) = pass.visibility` only by a case + that states that field, so the gates around a call travel with it; a call under no gate is + reached by every case that calls the entry point at all. A gate set holds both kinds + (`metal_leg.GATE_FIELD` tells them apart) and a reaching needs every gate in it. Three things a call reaches, and the same gate over all three: the SDK item its selector resolves to (`keyed`), the containers' own rows its receiver messages (`messaged`), and, on an @@ -300,19 +302,19 @@ def gated_items(leg: metal_leg.Leg, entry_points: set[str], keyed, messaged, fre for call in leg.calls: if call.function != fn: continue - arms = frozenset(call.arms) + arms = frozenset(call.gates) if id(call) in keyed: here[keyed[id(call)]].add(arms) for item in messaged.get(id(call), ()): here[item].add(arms) for callee in leg.calls_function.get(fn, ()): if callee in frees: - for arms in leg.function_arms.get((fn, callee), {()}): + for arms in leg.function_gates.get((fn, callee), {()}): here[frees[callee]].add(frozenset(arms)) below = walk(callee, stack + (fn,)) if not below: continue - for arms in leg.function_arms.get((fn, callee), {()}): + for arms in leg.function_gates.get((fn, callee), {()}): for item, gates in below.items(): for gate in gates: here[item].add(frozenset(gate | set(arms))) @@ -327,12 +329,64 @@ def gated_items(leg: metal_leg.Leg, entry_points: set[str], keyed, messaged, fre # The case set -def case_families(side: list[str], enums: set[str], constructors) -> dict[str, dict]: +def field_setters() -> dict[str, set[str]]: + """Each method of the suite's own vocabulary that assigns a field, to the fields it assigns. + + A case states a field either in the struct literal or through the builder the vocabulary + offers for it — `RenderPass::counting_into(buffer)` is how a case attaches a visibility-result + buffer — so without this map a case that used the builder would read as stating nothing. The + same shape `variant_constructors` reads for an enum's helpers, over `self.field = ..` instead. + + Keyed by the method's name alone, like the guards it answers: two structs with a setter of one + name credit each other's field, which is generous in the direction that cannot refuse a true + declaration. + """ + out: dict[str, set[str]] = {} + for path in sorted(SRC.rglob("*.rs")): + text = metal_leg.blanked(path.read_text()) + for fn in metal_leg.functions(text, str(path)): + assigned = { + match.group(1) + for match in re.finditer( + r"\bself\s*\.\s*([a-z_][a-z0-9_]*)\s*=[^=]", text[fn.start : fn.end] + ) + } + if assigned: + out.setdefault(fn.name, set()).update(assigned) + return out + + +def stated_fields(text: str, setters: dict[str, set[str]]) -> set[str]: + """The vocabulary fields a case module's text states, as a guard in the leg reads them. + + Three spellings, all of them the module's own text: a struct literal's `field: value`, an + assignment onto a value (`pass.size = cell.b_area`), and a call of a builder that assigns the + field (`setters`). + + Read generously, and deliberately so. A `let size: u32` reads as stating `size`, and a field a + module states as `None` or `false` reads the same as one it states a value for — the two + values of a boolean are nowhere in this text, which is the limit a field axis already carries. + What the reading is exact about is the only thing the check turns on: a module that never + mentions the field at all states none of it. + """ + out = {match.group(1) for match in re.finditer(r"\b([a-z_][a-z0-9_]*)\s*:", text)} + out |= { + match.group(1) + for match in re.finditer(r"\.\s*([a-z_][a-z0-9_]*)\s*=[^=]", text) + } + for match in re.finditer(r"\.\s*([a-z_][a-z0-9_]*)\s*\(", text): + out |= setters.get(match.group(1), set()) + return out + + +def case_families( + side: list[str], enums: set[str], constructors, setters: dict[str, set[str]] +) -> dict[str, dict]: """Each case module, with the vocabulary its cases use and what it loosens. A module's cases share one `run`, so the module is the unit a call site can be attributed to - without running anything: which `Side` methods its text calls, and which variants of the - vocabulary its text builds. + without running anything: which `Side` methods its text calls, which variants of the + vocabulary its text builds, and which of its fields its text states. """ out: dict[str, dict] = {} for path in sorted((SRC / "cases").glob("*.rs")): @@ -353,6 +407,10 @@ def case_families(side: list[str], enums: set[str], constructors) -> dict[str, d out[path.stem] = { "calls": calls, "variants": variants, + # The vocabulary fields the module's text states, which is what a guard in the leg + # (`metal_leg.guards_of`) is satisfied by: a field written in a struct literal, one + # assigned onto a value, and one a builder of the vocabulary assigns for it. + "states": stated_fields(text, setters), # What the module loosens, and what it names as the justification. Comparison is # exact by default, so a module with no tolerance compares every measured field. # @@ -483,14 +541,23 @@ def known_gaps() -> list[tuple[str, str]]: def metal_items( index: dict[tuple[str, str], dict[str, str]], by_item: dict[tuple[str, str], dict[str, set[str]]], + stated: dict[tuple[str, str], dict[str, set[str]]], api: metal_leg.Api, ) -> dict[tuple[str, str], option_space.Item]: """Every Metal item a crossing may name as a field axis, from the sources already read. The key is the items axis's own -- `(container, item name)` of `scripts/metal-coverage`'s map -- so a field axis names an item this document already has a row for rather than a word a - row's author chose. Each carries the case modules whose Metal leg reaches it, and the Metal - type its call answers, which is what tells a boolean or numeric field from an enum-valued one. + row's author chose. Each carries the Metal type its call answers, which is what tells a boolean + or numeric field from an enum-valued one, and the case modules that reach it, in the two + strengths the sources can say apart: + + * `by_item` -- reached at all, which is the items axis's own join and what that axis counts; + * `stated` -- reached through a call site whose guards the module's own data can take. The leg + sets fifty fields of a pass descriptor in one function, each under `if let Some(x) = + pass.field`, so every case that opens a pass reaches all fifty by the first reading and only + the ones it states by the second. A crossing's field axis is checked against the second, so + a row says the module put a value to **that field** and not merely to that Metal type. The answered type is `objc2-metal`'s, keyed by the selector it binds for the item: a property is bound under its own name, and an Objective-C `BOOL` property under `isName` as well, so @@ -513,7 +580,11 @@ def metal_items( # A free function's empty container, and a container's own row, which names the type # and not a field of it. continue - out[key] = option_space.Item(set(by_item.get(key, {})), answered.get(key, "")) + out[key] = option_space.Item( + set(stated.get(key, {})), + answered.get(key, ""), + set(by_item.get(key, {})), + ) return out @@ -538,15 +609,20 @@ def inventory(): messaged = messaged_rows(leg, api, selves) side = side_methods() constructors = variant_constructors(enums) - families = case_families(side, enums, constructors) + setters = field_setters() + families = case_families(side, enums, constructors, setters) records = recordings(families) # The call graph, from each `Side` method the Metal leg implements. entries = {fn for fn in leg.calls_function} | {call.function for call in leg.calls} gated = gated_items(leg, entries & set(side), keyed, messaged, frees) - # An item to the families that reach it, and how. + # An item to the families that reach it, and how. And, apart from it, the stronger reading: the + # families whose own data can take the guards around the call site they reach it through. + # Only a crossing's field axis is checked against that second reading; the items axis counts + # reachability, which is what it has always claimed and what its own prose says. by_item: dict[tuple[str, str], dict[str, set[str]]] = defaultdict(lambda: defaultdict(set)) + stated: dict[tuple[str, str], dict[str, set[str]]] = defaultdict(lambda: defaultdict(set)) for module, family in families.items(): if not family["ran"]: # Nothing of this module's Metal is ever executed. @@ -554,9 +630,19 @@ def inventory(): for method in family["calls"]: for item, gates in gated.get(method, {}).items(): for gate in gates: - if gate <= family["variants"]: - by_item[item][module].add(method) - break + named = { + one for one in gate if not one.startswith(metal_leg.GATE_FIELD) + } + if not named <= family["variants"]: + continue + by_item[item][module].add(method) + fields = { + one.removeprefix(metal_leg.GATE_FIELD) + for one in gate + if one.startswith(metal_leg.GATE_FIELD) + } + if fields <= family["states"]: + stated[item][module].add(method) # Calls the leg makes that no family was found to reach: a call site this cannot attribute. reached = {item for method in gated.values() for item in method} @@ -575,6 +661,7 @@ def inventory(): "records": records, "gated": gated, "by_item": by_item, + "stated": stated, "called": sorted(called), "unattributed": sorted(called - set(by_item)), "unreachable": sorted(called - reached), @@ -599,7 +686,7 @@ def inventory(): for module, family in families.items() for case in family["ran"] }, - metal_items(index, by_item, api), + metal_items(index, by_item, stated, api), ), } @@ -798,9 +885,15 @@ def write_other_crossings(w, other, slots, fields, with_slots, with_fields) -> N "of each axis, and a row parked here would be the same claim under a weaker rule;" ) w( - "- **a field axis `objc2-metal` binds no such item for, or one this module's Metal leg " - "reaches no call of.** The second is the items axis's own join, so a field axis names a " - "call this document already reports as exercised rather than a word a row's author chose;" + "- **a field axis `objc2-metal` binds no such item for, or one this module's own data " + "never reaches.** The leg must hold a call of that field at a site whose guards this " + "module's text satisfies. Reachability is the items axis's own join, so a field axis names " + "a call this document already reports as exercised rather than a word a row's author " + "chose; the guards are what make the row a claim about that **field** and not about any " + "field of its Metal type. One shared encoder sets a pass descriptor's fields in one " + "function, each under `if let Some(x) = pass.field`, so by reachability alone every case " + "that opens a pass reaches them all — which would let a case attaching no visibility " + "buffer declare a crossing on `visibilityResultBuffer`;" ) w( "- **a field axis whose call answers a Metal type with a generated value list.** Such a " @@ -812,10 +905,14 @@ def write_other_crossings(w, other, slots, fields, with_slots, with_fields) -> N "What **cannot** be checked for a field axis, and is therefore what only a reader can " "check: that the module put **two values** of the field to Metal. A boolean's two values " "and a number's range are nowhere in the text this reads and in no recording's " - "transcript, so a field axis carries the field being Metal's and this module's leg setting " - "it, and nothing about variation. An enum axis carries the two-values check here exactly as " - "it does above, which is why a row's enum axes are the stronger half of it. The last " - "column, as above, is for a reader against the case." + "transcript, so a field axis carries the field being Metal's and this module stating it, " + "and nothing about variation — and a field a module states as `None` or `false` reads " + "here exactly like one it states a value for. For the same reason a **bare boolean** " + "guard in the leg (`if descriptor.read_only {`) is no guard here: its body is reached on " + "one of the field's two values, and which one a case states is what this cannot see. An " + "enum axis carries the two-values check here exactly as it does above, which is why a " + "row's enum axes are the stronger half of it. The last column, as above, is for a reader " + "against the case." ) w("") w("| | |") diff --git a/scripts/conformance-coverage/metal_leg.py b/scripts/conformance-coverage/metal_leg.py index 133d2e3a6..9d197d222 100644 --- a/scripts/conformance-coverage/metal_leg.py +++ b/scripts/conformance-coverage/metal_leg.py @@ -28,9 +28,17 @@ A message to a class — `MTLRenderPassDescriptor::renderPassDescriptor()` — n the path names its receiver. It is resolved against that class the same way an instance send is resolved against the type its receiver typed to. -A call site also carries where it sits: the function that holds it, and the enclosing `match` arms, -so a call made only for one step of the case vocabulary is attributed to that step and not to every -case that encodes any step at all. +A call site also carries where it sits: the function that holds it, and the **gates** around it, so +a call made only for one step of the case vocabulary is attributed to that step and not to every +case that encodes any step at all. Two kinds of gate are read, and a call carries every one that +encloses it: + +* a `match` arm's variant, as `Enum::Variant` ([`arms_of`]), which a case satisfies by naming that + variant; +* a guard on one field of the suite's **own** vocabulary, as `field:name` ([`guards_of`]), which a + case satisfies by stating that field. One shared encoder sets fifty fields of a descriptor, each + behind `if let Some(x) = pass.field`, so without this a case that states one of them reads as + reaching all fifty. """ import re @@ -223,8 +231,9 @@ class Call: file: str #: The function that holds it. function: str - #: The enclosing `match` arm variants, outermost first, as `Enum::Variant`. - arms: tuple[str, ...] + #: The gates around it, outermost first: a `match` arm's variant as `Enum::Variant`, and a + #: guard on one field of the suite's own vocabulary as `field:name`. + gates: tuple[str, ...] #: The Rust name, which is the selector with `:` as `_`. rust: str #: The receiver's type, or `""` where it could not be typed. @@ -255,8 +264,9 @@ class Leg: by_uniqueness: list[tuple[str, str, str]] = field(default_factory=list) #: Which functions call which, by name, for the reachability closure. calls_function: dict[str, set[str]] = field(default_factory=dict) - #: The `match` arms each function's calls to other functions sit under. - function_arms: dict[tuple[str, str], set[tuple[str, ...]]] = field(default_factory=dict) + #: The gates each function's calls to other functions sit under, the same two kinds as + #: [`Call.gates`][Call]: what a case must name, and what it must state, to reach through here. + function_gates: dict[tuple[str, str], set[tuple[str, ...]]] = field(default_factory=dict) @dataclass @@ -362,6 +372,84 @@ def arms_of(text: str, start: int, end: int, enums: set[str]) -> list[tuple[int, return out +#: How a gate on a field of the suite's own vocabulary is spelled, so a reader of a gate set can +#: tell it from a `match` arm's `Enum::Variant` and strip it where only the variants are wanted. +GATE_FIELD = "field:" + +#: The `if` conditions whose body is reached only where the field is **stated**, read from the +#: condition text between `if` and the block it opens. An `Option` unwrapped, one asked whether it +#: is there, and a collection asked whether it is not empty: in each the field names what the +#: case had to state for the call inside to happen at all. +#: +#: A bare boolean field (`if descriptor.read_only {`) is **not** one of these. Its body is reached +#: on one of the two values the field can hold, and which value a case states is nowhere in the +#: text this reads -- the same limit that keeps a field axis from carrying a two-values check -- +#: so reading it as a gate would refuse a case that states the field and sets it false. +STATED = ( + # `if let Some(x) = pass.visibility`, `if let Some(depth) = &pass.depth`, and the same with an + # adapter on the end: `if let Some(label) = self.pass.label.as_ref()`. + re.compile( + r"^let\s+(?:Some|Ok)\s*\(.*\)\s*=\s*&?\s*(?:mut\s+)?[A-Za-z_][\w.]*?\.(\w+)\s*" + r"(?:\.\s*(?:as_ref|as_deref|as_mut|clone|to_owned)\s*\(\s*\))?$" + ), + re.compile(r"^&?\s*[A-Za-z_][\w.]*?\.(\w+)\s*\.\s*is_some\s*\(\s*\)$"), + re.compile(r"^!\s*&?\s*[A-Za-z_][\w.]*?\.(\w+)\s*\.\s*is_empty\s*\(\s*\)$"), +) + + +def _condition_end(text: str, start: int, end: int) -> int: + """Where the `if` condition that starts at `start` ends: the `{` it opens, or `-1`. + + Only round and square brackets nest here: a `{` at bracket depth zero is the body's, and one + inside a call (`if let Some(x) = make(Thing { a: 1 })`) is not. + """ + depth = 0 + for i in range(start, end): + c = text[i] + if c in "([": + depth += 1 + elif c in ")]": + depth -= 1 + elif c == "{" and depth == 0: + return i + elif c == ";" and depth == 0: + # A `let .. else` or a statement boundary: this `if` opens no block here. + return -1 + return -1 + + +def guards_of(text: str, start: int, end: int) -> list[tuple[int, int, str]]: + """Every guard in `text[start:end]` on a field of the suite's own vocabulary, with its span. + + The gate is the **field's name**, as `field:name`, and the span is the guarded block alone: an + `else` branch opens its own block, which this one does not cover, so a call Metal makes only + where the field is absent carries no gate for it. + + This is what makes an item's attribution per **field** rather than per shared encoder. The + Metal leg builds one descriptor in one function, setting each field under its own guard, so + every case that calls that encoder reaches every call site in it; the guard says which of them + the case's own data could ever have taken. + + The field is read by name and not by the struct it belongs to, because the typing here follows + Metal's types and not the suite's. Two vocabulary structs with a field of one name are read as + one gate, which is generous in the safe direction: it can let a declaration through, never + refuse a true one. + """ + out: list[tuple[int, int, str]] = [] + for match in re.finditer(r"\bif\s", text[start:end]): + at = start + match.end() + brace = _condition_end(text, at, end) + if brace < 0: + continue + condition = " ".join(text[at:brace].split()) + for shape in STATED: + found = shape.match(condition) + if found: + out.append((brace, block(text, brace)[1], GATE_FIELD + found.group(1))) + break + return out + + def _at_depth(text: str, start: int, end: int, want: str) -> int: """Where `want` next appears in `text[start:end]` at bracket depth zero.""" depth = 0 @@ -674,7 +762,7 @@ def read_leg(api: Api, src: Path, files: list[str], enums: set[str]) -> Leg: answers[fn.name] = ty for name, text in blank.items(): for fn in functions(text, name): - arms = arms_of(text, fn.start, fn.end, enums) + gates = arms_of(text, fn.start, fn.end, enums) + guards_of(text, fn.start, fn.end) typing = Typing(api, fields, answers) typing.param_types(fn.signature) typing.closure_params(text[fn.start : fn.end], fn.start) @@ -698,7 +786,7 @@ def read_leg(api: Api, src: Path, files: list[str], enums: set[str]) -> Leg: ): rust = match.group(1) at = fn.start + match.start() - here = tuple(v for lo, hi, v in arms if lo <= at < hi) + here = tuple(v for lo, hi, v in gates if lo <= at < hi) owners = api.receivers(rust) recv = receiver_of(text, at) if recv == "self" or not owners: @@ -707,7 +795,7 @@ def read_leg(api: Api, src: Path, files: list[str], enums: set[str]) -> Leg: # Not a Metal call at all. A call to another function of the leg is an edge of # the reachability graph instead. leg.calls_function.setdefault(fn.name, set()).add(rust) - leg.function_arms.setdefault((fn.name, rust), set()).add(here) + leg.function_gates.setdefault((fn.name, rust), set()).add(here) continue ty = typing.typed(recv, at) if not ty and len(owners) == 1: @@ -748,7 +836,7 @@ def read_leg(api: Api, src: Path, files: list[str], enums: set[str]) -> Leg: # bitflags constructor whose name only looks like Metal's # (`MTLBlitOption::empty`). The loop below reads it as the leg's own call. continue - here = tuple(v for lo, hi, v in arms if lo <= at < hi) + here = tuple(v for lo, hi, v in gates if lo <= at < hi) item = api.binds(ty, rust) if item is None: # The class named here does not bind this selector. Not `mistyped`: nothing was @@ -781,9 +869,9 @@ def read_leg(api: Api, src: Path, files: list[str], enums: set[str]) -> Leg: qualifier = [part for part in match.group(1).split("::") if part] if qualifier and qualifier[-1][:1].isupper() and qualifier[-1] != "Self": continue - here = tuple(v for lo, hi, v in arms if lo <= at < hi) + here = tuple(v for lo, hi, v in gates if lo <= at < hi) leg.calls_function.setdefault(fn.name, set()).add(rust) - leg.function_arms.setdefault((fn.name, rust), set()).add(here) + leg.function_gates.setdefault((fn.name, rust), set()).add(here) return leg diff --git a/scripts/conformance-coverage/option_space.py b/scripts/conformance-coverage/option_space.py index 3e959959f..65edbe0e2 100644 --- a/scripts/conformance-coverage/option_space.py +++ b/scripts/conformance-coverage/option_space.py @@ -277,14 +277,27 @@ class Item: `objc2-metal` binds and what each call answers, and the items axis's own join for which case modules' Metal legs reach the item. A field axis is checked against this and nothing else, so it names a call the suite is already measured to make rather than a word a row's author chose. + + Reaching is held in two strengths, because the weaker one is not per **field**. The suite's + Metal leg builds a descriptor in one function, setting each of its fields under a guard on the + suite's own vocabulary (`if let Some(buffer) = pass.visibility`), so every case that opens a + pass reaches every one of those call sites by reachability alone -- which would let a case that + attaches no visibility buffer declare a crossing on `visibilityResultBuffer`. `modules` is the + stronger reading, and the one a field axis is checked against: the module's own data states + the field the guard tests. """ - def __init__(self, modules: set[str], answers: str): - #: The case modules whose Metal leg reaches this item, as the items axis joins them. + def __init__(self, modules: set[str], answers: str, reached: set[str] | None = None): + #: The case modules whose Metal leg reaches this item through a call site **their own data + #: can take**: every guard around it is on a field the module's text states. self.modules = frozenset(modules) #: The Metal type the call answers, or `""`. A type with a generated value list here means #: the field is an enum under another name and belongs in `crossings.tsv`. self.answers = answers + #: The case modules whose Metal leg reaches this item at all, guards aside, which is what + #: the items axis counts. A module here and not in `modules` reaches the call only where + #: another case's data would have taken it, which is what the refusal says. + self.reached = frozenset(modules if reached is None else reached) def _read_rows( @@ -506,9 +519,12 @@ def other_crossings( - a row every axis of which is a Metal enum named **once**. That is a pair of the option space: it belongs in `crossings.tsv`, under the check that the module states two values of each axis, and a row parked here would be the same claim under a weaker rule; - - a field axis naming an item `objc2-metal` binds nothing for, and one **this module's Metal - leg does not reach**. The second is the items axis's own join, so a field axis names a call - the suite is measured to make rather than a word chosen here; + - a field axis naming an item `objc2-metal` binds nothing for, and one **this module's own + data never reaches**: the leg must hold a call of that field at a site whose guards this + module's text satisfies. The reachability half is the items axis's own join, so a field axis + names a call the suite is measured to make rather than a word chosen here; the guard half is + what makes it a claim about that **field** and not about any field of its Metal type, since + one shared encoder sets fifty fields of a descriptor and every case reaches all fifty; - a field axis whose call answers a Metal type with a generated value list. Such a field is an enum under another name, and naming it as a field would dodge the two-values check that the enum spelling carries. @@ -518,9 +534,10 @@ def other_crossings( own text states two values of. What **cannot** be checked, for a field axis, is that the module put two values of the field to - Metal. A boolean's two values and a number's range are nowhere in the text this reads, and - nothing in a recording names them, so that part of a field row is what only a reader can check. - The document says so where it prints the count. + Metal. The guard check reads that the module states the field, not which values it states: a + boolean's two values and a number's range are nowhere in the text this reads, and nothing in a + recording names them, so that part of a field row is what only a reader can check. The document + says so where it prints the count. """ where = Path(OTHER).name modules_ran: dict[str, set[str]] = {} @@ -559,6 +576,14 @@ def other_crossings( "held to stating two of its values" ) if module not in held.modules: + if module in held.reached: + raise SystemExit( + f"{where} says {module} crosses {axis}, and every call of it {module}'s " + f"Metal leg reaches sits behind a guard on a field of the suite's own " + f"vocabulary that {module}'s text never states -- the leg sets {name} only " + f"where a case asks for it, and this one does not, so no case of " + f"{module} ever put a value to it" + ) raise SystemExit( f"{where} says {module} crosses {axis}, and {module}'s Metal leg reaches no " f"call of it -- the items axis attributes {name} to " diff --git a/scripts/conformance-coverage/other_crossings.tsv b/scripts/conformance-coverage/other_crossings.tsv index 04c424335..c3d0a7502 100644 --- a/scripts/conformance-coverage/other_crossings.tsv +++ b/scripts/conformance-coverage/other_crossings.tsv @@ -22,15 +22,24 @@ # decides, or whose module states fewer than TWO values of an ENUM axis by name. And on three of # its own: a row every axis of which is a Metal enum named once (that is a pair, and belongs in # crossings.tsv under its own checks); a field axis naming an item objc2-metal binds nothing for, -# or one this module's Metal leg reaches no call of; and a field axis whose call answers a Metal -# type with a generated value list, which is an enum under another name and must be crossed as -# that enum. +# or one this module's own data never reaches; and a field axis whose call answers a Metal type +# with a generated value list, which is an enum under another name and must be crossed as that +# enum. +# +# "Own data never reaches" is per FIELD and not per Metal type. The leg sets a pass descriptor's +# fields in one function, each under a guard on the suite's own vocabulary +# (`if let Some(b) = pass.visibility`), so by reachability alone every case that opens a pass +# reaches them all; the check also requires this module's text to state the field the guard tests, +# so a module that attaches no visibility buffer cannot declare a crossing on +# visibilityResultBuffer. # # What the generator CANNOT check for a field axis is that the module put TWO values of the field # to Metal. A boolean's two values and a number's range are nowhere in the text this reads and in -# no recording, so a field axis carries only that the field is Metal's and that this module's -# Metal leg sets it. That, and whether the expected answer needs both axes, is what the last field -# is for and what a reader checks against the case. +# no recording, so a field axis carries only that the field is Metal's and that this module states +# it -- a field stated as None or false reads like one stated with a value, which is also why a +# bare boolean guard in the leg (`if descriptor.read_only {`) is no guard here. That, and whether +# the expected answer needs both axes, is what the last field is for and what a reader checks +# against the case. # # A crossing with an axis that is no Metal item at all -- a pixel format's class, the shape of a # shader's output, whether a fragment writes a sample mask -- can be declared in neither file, and @@ -45,6 +54,10 @@ argument_encoder_crossings argument-encoder-cross-type-sizes MTLDataType+MTLData indirect_command_depth indirect-compute-commands-reset-and-ranges MTLIndirectCommandBuffer.resetWithRange:+MTLComputeCommandEncoder.executeCommandsInBuffer:withRange: which commands of a buffer wrote anything, which the two ranges decide together: a command is blank where the reset covers it and runs where the execution does. A side that reset the executed range, or executed the reset one, is right about each range's own bounds and writes another command's segment indirect_command_depth indirect-render-commands-inherited-state MTLIndirectCommandBufferDescriptor.inheritBuffers+MTLIndirectRenderCommand.setVertexBuffer:offset:atIndex: which binding an executed command draws from when the parent encoder and the command have each bound one. With the field off the command's own binding is the only one there is, and with the command setting none the parent's is: each alone names a segment of the output, and only the pair says which of the two wins where both exist indirect_command_depth indirect-render-commands-under-the-pass-state MTLRenderCommandEncoder.setScissorRect:+MTLIndirectRenderCommand.drawPrimitives:vertexStart:vertexCount:instanceCount:baseInstance: which pixels an indirect draw covers, which the parent encoder's scissor and the command's own vertex range decide together -- a render command may not set a scissor of its own, so a side that dropped the pass's state at the execution rasterizes each half of the draw in full while being right about the scissor alone and about the draw alone +pass_attachment_pairs pass-two-attachments-loads MTLLoadAction+MTLLoadAction which attachment each load action is read from, in one pass whose two colour attachments state different ones. An earlier pass of the same command buffer stores a different value into each, so a `Load` shows a value no clear of this pass states and the two attachments' prior values differ: the two off-diagonal pairs are the cells only the pair reaches, and a side that applied colour 0's load action to colour 1 answers both diagonal cells exactly and both off-diagonal ones wrongly. The 36 (load, store, options) triples of `pass_descriptors` read the fields back off one attachment and never render two that disagree +pass_attachment_pairs pass-two-attachments-loads MTLPixelFormat+MTLPixelFormat which attachment each format is read from. `RGBA32Float` beside `R32Float` and the swap make the two planes different sizes **and** leave attachment 1 holding red alone, so a side that took one attachment's format for the other cannot answer the cell at all -- where the equal pair answers the same under every rule, and a sweep of one format at a time is a one-attachment question that no pairing can falsify +pass_attachment_pairs pass-two-attachments-resolves MTLStoreAction+MTLStoreAction which attachment's resolve texture a resolving store writes into: `MultisampleResolve` at one attachment beside `DontCare` at the other, which a depth-only pass has one attachment to state. Colour 0 resolving alone, colour 1 alone and both are the three cells, and a side that took attachment 0's resolve texture for attachment 1 writes colour 0's value into colour 1's texture in the two cells where attachment 1 resolves while answering the colour-0-alone cell exactly. An attachment stored `DontCare` carries no resolve texture, so neither slot's own sweep ever has a second attachment to confuse it with +pass_bound_pairs pass-bound-clear-reach MTLRenderPassDescriptor.renderTargetWidth+MTLRenderPassDescriptor.renderTargetHeight+MTLLoadAction+MTLRenderCommandEncoder.drawPrimitives:vertexStart:vertexCount:instanceCount:baseInstance: which texels of an attachment **larger than its pass's render area** the pass changes, and to what. A `Clear` load clears from the origin over the render area rounded up to whole 32-pixel tiles and clipped to the attachment where the pass encodes a draw, the whole level and slice where it encodes none, and a `Load` load keeps every texel whatever the area: so each axis moves a plane only at the others' settings and a case that fixes two of the three says nothing about the other cells. The two numbers are separate axes because the rounding is **per axis** -- the 8 by 40 and 40 by 8 cells are where a side that rounded the larger side, or took one axis's reach for both, answers the square cells exactly and those two wrongly -- and `draw-covers-nothing` beside `no-draw-call` is where a side that read the draw axis as whether a draw *wrote* anything answers two cells alike and both wrongly. The number sweep of `pass_descriptors` reads the two numbers back off a descriptor and renders through neither pass_sequence_actions pass-sequence-aspect-actions MTLStoreAction+MTLStoreAction+MTLLoadAction+MTLLoadAction which attachment each aspect's action is read from, across a pass boundary where the two aspects disagree in both passes. Pass A stores the depth and discards the stencil, or the reverse, and pass B loads one aspect and clears the other: the depth plane is then a function of the depth's two slots and the stencil plane of the stencil's, and a side that took one aspect's slot for both answers the three symmetric cells exactly and the six asymmetric ones wrongly. Measured: taking the depth attachment's action for the stencil's scratch copy moves four of the nine cells, every one of them in the stencil plane and none in the depth plane pass_sequence_actions pass-sequence-color-actions MTLRenderPassDescriptor.renderTargetWidth+MTLStoreAction+MTLLoadAction whether the next pass's render area bounds what its load action does to what the last pass stored. A `MTLLoadActionLoad` under a 32 by 32 area of a 40 by 40 attachment keeps every texel, so the bound moves **not one** against the whole-area cell -- the independence `pass_bound_pairs` measured inside one pass, holding across the boundary. A `MTLLoadActionClear` under the same bound clears its own tiles and leaves the 8 texels past them holding **what pass A's store action left there**, so the store action is visible through a `Clear` after all, which it is not over the whole attachment. Neither the area alone nor either action alone reaches either cell sampler_crossings family MTLSamplerMinMagFilter+MTLSamplerMinMagFilter+MTLSamplerDescriptor.lodMinClamp which of the two filters reads the level `lodMinClamp` raised the requested one to. The two `(min, mag)` pairs whose filters agree answer the same under every rule, so only an unequal pair at a clamp above the sampled level parts Metal's rule from Vulkan's -- the magnifying filter at a level of zero or less, the minifying one above it -- and from a `NotMipmapped` sampler's, which ignores the clamp outright diff --git a/scripts/conformance-coverage/test_option_space.py b/scripts/conformance-coverage/test_option_space.py index 3abe0516e..9c9137c14 100644 --- a/scripts/conformance-coverage/test_option_space.py +++ b/scripts/conformance-coverage/test_option_space.py @@ -832,13 +832,19 @@ class Crossings(unittest.TestCase): #: The Metal items a field axis of the synthetic trees may name, as `coverage.py` hands them over: #: two fields of one type that answer no Metal type, one field whose call answers `MTLThing` -- -#: which is an enum under another name -- and a field of a type the `blends` module never touches. +#: which is an enum under another name -- a field of a type the `blends` module never touches, and +#: one the `blends` module's leg reaches only behind a guard its own data never takes, which is the +#: two-strength reading `coverage.py` derives from the guards in the leg. def items(reached: str = "blends") -> dict[tuple[str, str], option_space.Item]: return { ("MTLWidget", "spun"): option_space.Item({reached}, ""), ("MTLWidget", "setSpread:atIndex:"): option_space.Item({reached}, ""), ("MTLWidget", "thing"): option_space.Item({reached}, "MTLThing"), ("MTLGadget", "whirred"): option_space.Item({"others"}, ""), + # Reached by `blends`, stated by nobody: the shape of a field one shared encoder sets + # under a guard, which every case that calls the encoder reaches and only the cases whose + # own data asks for it ever put a value to. + ("MTLWidget", "counted"): option_space.Item(set(), "", {reached}), } @@ -956,6 +962,33 @@ class OtherCrossings(unittest.TestCase): self.declared(reached="others") self.assertIn("attributes spun to others", str(refused.exception)) + def test_a_field_reached_only_behind_a_guard_the_module_never_states_is_refused(self): + # The hole this closes: reachability alone is per shared encoder, so a field the leg sets + # under `if let Some(x) = pass.field` is reached by every case that opens a pass. A row + # whose module never states the field is a claim about the Metal **type** wearing a + # field's spelling, and is refused. + with self.assertRaises(SystemExit) as refused: + self.declared(axes="MTLThing+MTLWidget.counted") + held = str(refused.exception) + self.assertIn("sits behind a guard", held) + self.assertIn("ever put a value to it", held) + + def test_a_field_reached_under_no_guard_at_all_is_taken(self): + # The other direction: a field the leg sets unconditionally has no guard to satisfy, so + # the stronger reading is the same as reachability and the row stands. + held = self.declared(axes="MTLThing+MTLWidget.spun") + self.assertEqual(held[0]["fields"], [("MTLWidget", "spun")]) + + def test_a_field_neither_reached_nor_stated_is_refused_as_unreached(self): + # A field of a type this module never touches is refused by the other message, which names + # who does reach it: the two refusals say different things and neither is the other's + # wording. + with self.assertRaises(SystemExit) as refused: + self.declared(axes="MTLThing+MTLGadget.whirred") + held = str(refused.exception) + self.assertIn("reaches no call of it", held) + self.assertNotIn("sits behind a guard", held) + def test_an_axis_that_is_no_metal_item_is_refused(self): # The one kind of axis neither file can hold: a grouping that is no Metal item, so there is # nothing to check it against.